repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
jabref-main/src/test/java/org/jabref/logic/layout/format/OrdinalTest.java
package org.jabref.logic.layout.format; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class OrdinalTest { @Test public void testEmpty() { assertEquals("", new Ordinal().format("")); } @Test public void testNull() { assertNull(new Ordinal().format(null)); } @Test public void testSingleDigit() { assertEquals("1st", new Ordinal().format("1")); assertEquals("2nd", new Ordinal().format("2")); assertEquals("3rd", new Ordinal().format("3")); assertEquals("4th", new Ordinal().format("4")); } @Test public void testMultiDigits() { assertEquals("11th", new Ordinal().format("11")); assertEquals("111th", new Ordinal().format("111")); assertEquals("21st", new Ordinal().format("21")); } @Test public void testAlreadyOrdinals() { assertEquals("1st", new Ordinal().format("1st")); assertEquals("111th", new Ordinal().format("111th")); assertEquals("22nd", new Ordinal().format("22nd")); } @Test public void testFullSentence() { assertEquals("1st edn.", new Ordinal().format("1 edn.")); assertEquals("1st edition", new Ordinal().format("1st edition")); assertEquals("The 2nd conference on 3rd.14th", new Ordinal().format("The 2 conference on 3.14")); } @Test public void testLetters() { assertEquals("abCD eFg", new Ordinal().format("abCD eFg")); } }
1,580
28.277778
105
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RTFCharsTest.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; class RTFCharsTest { private LayoutFormatter formatter; @BeforeEach void setUp() { formatter = new RTFChars(); } @AfterEach void tearDown() { formatter = null; } @Test void testBasicFormat() { assertEquals("", formatter.format("")); assertEquals("hallo", formatter.format("hallo")); assertEquals("R\\u233eflexions sur le timing de la quantit\\u233e", formatter.format("Réflexions sur le timing de la quantité")); assertEquals("h\\'e1llo", formatter.format("h\\'allo")); assertEquals("h\\'e1llo", formatter.format("h\\'allo")); } @Test void testLaTeXHighlighting() { assertEquals("{\\i hallo}", formatter.format("\\emph{hallo}")); assertEquals("{\\i hallo}", formatter.format("{\\emph hallo}")); assertEquals("An article title with {\\i a book title} emphasized", formatter.format("An article title with \\emph{a book title} emphasized")); assertEquals("{\\i hallo}", formatter.format("\\textit{hallo}")); assertEquals("{\\i hallo}", formatter.format("{\\textit hallo}")); assertEquals("{\\b hallo}", formatter.format("\\textbf{hallo}")); assertEquals("{\\b hallo}", formatter.format("{\\textbf hallo}")); } @Test void testComplicated() { assertEquals("R\\u233eflexions sur le timing de la quantit\\u233e {\\u230ae} should be \\u230ae", formatter.format("Réflexions sur le timing de la quantité {\\ae} should be æ")); } @Test void testComplicated2() { assertEquals("h\\'e1ll{\\u339oe}", formatter.format("h\\'all{\\oe}")); } @Test void testComplicated3() { assertEquals("Le c\\u339oeur d\\u233e\\u231cu mais l'\\u226ame plut\\u244ot na\\u239ive, Lou\\u255ys r" + "\\u234eva de crapa\\u252?ter en cano\\u235e au del\\u224a des \\u238iles, pr\\u232es du m\\u228alstr" + "\\u246om o\\u249u br\\u251ulent les nov\\u230ae.", formatter.format("Le cœur déçu mais l'âme plutôt " + "naïve, Louÿs rêva de crapaüter en canoë au delà des îles, près du mälström où brûlent les novæ.")); } @Test void testComplicated4() { assertEquals("l'\\u238ile exigu\\u235e\n" + " O\\u249u l'ob\\u232ese jury m\\u251ur\n" + " F\\u234ete l'ha\\u239i volap\\u252?k,\n" + " \\u194Ane ex a\\u233equo au whist,\n" + " \\u212Otez ce v\\u339oeu d\\u233e\\u231cu.", formatter.format("l'île exiguë\n" + " Où l'obèse jury mûr\n" + " Fête l'haï volapük,\n" + " Âne ex aéquo au whist,\n" + " Ôtez ce vœu déçu.")); } @Test void testComplicated5() { assertEquals("\\u193Arv\\u237izt\\u369?r\\u337? t\\u252?k\\u246orf\\u250ur\\u243og\\u233ep", formatter.format("Árvíztűrő tükörfúrógép")); } @Test void testComplicated6() { assertEquals("Pchn\\u261a\\u263c w t\\u281e \\u322l\\u243od\\u378z je\\u380za lub o\\u347sm skrzy\\u324n fig", formatter.format("Pchnąć w tę łódź jeża lub ośm skrzyń fig")); } @Test void testSpecialCharacters() { assertEquals("\\'f3", formatter.format("\\'{o}")); // ó assertEquals("\\'f2", formatter.format("\\`{o}")); // ò assertEquals("\\'f4", formatter.format("\\^{o}")); // ô assertEquals("\\'f6", formatter.format("\\\"{o}")); // ö assertEquals("\\u245o", formatter.format("\\~{o}")); // õ assertEquals("\\u333o", formatter.format("\\={o}")); assertEquals("\\u335o", formatter.format("{\\uo}")); assertEquals("\\u231c", formatter.format("{\\cc}")); // ç assertEquals("{\\u339oe}", formatter.format("{\\oe}")); assertEquals("{\\u338OE}", formatter.format("{\\OE}")); assertEquals("{\\u230ae}", formatter.format("{\\ae}")); // æ assertEquals("{\\u198AE}", formatter.format("{\\AE}")); // Æ assertEquals("", formatter.format("\\.{o}")); // ??? assertEquals("", formatter.format("\\vo")); // ??? assertEquals("", formatter.format("\\Ha")); // ã // ??? assertEquals("", formatter.format("\\too")); assertEquals("", formatter.format("\\do")); // ??? assertEquals("", formatter.format("\\bo")); // ??? assertEquals("\\u229a", formatter.format("{\\aa}")); // å assertEquals("\\u197A", formatter.format("{\\AA}")); // Å assertEquals("\\u248o", formatter.format("{\\o}")); // ø assertEquals("\\u216O", formatter.format("{\\O}")); // Ø assertEquals("\\u322l", formatter.format("{\\l}")); assertEquals("\\u321L", formatter.format("{\\L}")); assertEquals("\\u223ss", formatter.format("{\\ss}")); // ß assertEquals("\\u191?", formatter.format("\\`?")); // ¿ assertEquals("\\u161!", formatter.format("\\`!")); // ¡ assertEquals("", formatter.format("\\dag")); assertEquals("", formatter.format("\\ddag")); assertEquals("\\u167S", formatter.format("{\\S}")); // § assertEquals("\\u182P", formatter.format("{\\P}")); // ¶ assertEquals("\\u169?", formatter.format("{\\copyright}")); // © assertEquals("\\u163?", formatter.format("{\\pounds}")); // £ } @ParameterizedTest(name = "specialChar={0}, formattedStr={1}") @CsvSource({ "ÀÁÂÃÄĀĂĄ, \\u192A\\u193A\\u194A\\u195A\\u196A\\u256A\\u258A\\u260A", // A "àáâãäåāăą, \\u224a\\u225a\\u226a\\u227a\\u228a\\u229a\\u257a\\u259a\\u261a", // a "ÇĆĈĊČ, \\u199C\\u262C\\u264C\\u266C\\u268C", // C "çćĉċč, \\u231c\\u263c\\u265c\\u267c\\u269c", // c "ÐĐ, \\u208D\\u272D", // D "ðđ, \\u240d\\u273d", // d "ÈÉÊËĒĔĖĘĚ, \\u200E\\u201E\\u202E\\u203E\\u274E\\u276E\\u278E\\u280E\\u282E", // E "èéêëēĕėęě, \\u232e\\u233e\\u234e\\u235e\\u275e\\u277e\\u279e\\u281e\\u283e", // e "ĜĞĠĢŊ, \\u284G\\u286G\\u288G\\u290G\\u330G", // G "ĝğġģŋ, \\u285g\\u287g\\u289g\\u291g\\u331g", // g "ĤĦ, \\u292H\\u294H", // H "ĥħ, \\u293h\\u295h", // h "ÌÍÎÏĨĪĬĮİ, \\u204I\\u205I\\u206I\\u207I\\u296I\\u298I\\u300I\\u302I\\u304I", // I "ìíîïĩīĭį, \\u236i\\u237i\\u238i\\u239i\\u297i\\u299i\\u301i\\u303i", // i "Ĵ, \\u308J", // J "ĵ, \\u309j", // j "Ķ, \\u310K", // K "ķ, \\u311k", // k "ĹĻĿ, \\u313L\\u315L\\u319L", // L "ĺļŀł, \\u314l\\u316l\\u320l\\u322l", // l "ÑŃŅŇ, \\u209N\\u323N\\u325N\\u327N", // N "ñńņň, \\u241n\\u324n\\u326n\\u328n", // n "ÒÓÔÕÖØŌŎ, \\u210O\\u211O\\u212O\\u213O\\u214O\\u216O\\u332O\\u334O", // O "òóôõöøōŏ, \\u242o\\u243o\\u244o\\u245o\\u246o\\u248o\\u333o\\u335o", // o "ŔŖŘ, \\u340R\\u342R\\u344R", // R "ŕŗř, \\u341r\\u343r\\u345r", // r "ŚŜŞŠ, \\u346S\\u348S\\u350S\\u352S", // S "śŝşš, \\u347s\\u349s\\u351s\\u353s", // s "ŢŤŦ, \\u354T\\u356T\\u358T", // T "ţŧ, \\u355t\\u359t", // t "ÙÚÛÜŨŪŬŮŲ, \\u217U\\u218U\\u219U\\u220U\\u360U\\u362U\\u364U\\u366U\\u370U", // U "ùúûũūŭůų, \\u249u\\u250u\\u251u\\u361u\\u363u\\u365u\\u367u\\u371u", // u "Ŵ, \\u372W", // W "ŵ, \\u373w", // w "ŶŸÝ, \\u374Y\\u376Y\\u221Y", // Y "ŷÿ, \\u375y\\u255y", // y "ŹŻŽ, \\u377Z\\u379Z\\u381Z", // Z "źżž, \\u378z\\u380z\\u382z", // z "Æ, \\u198AE", // AE "æ, \\u230ae", // ae "Œ, \\u338OE", // OE "œ, \\u339oe", // oe "Þ, \\u222TH", // TH "ß, \\u223ss", // ss "¡, \\u161!" // ! }) public void testMoreSpecialCharacters(String specialChar, String expectedResult) { String formattedStr = formatter.format(specialChar); assertEquals(expectedResult, formattedStr); } @Test void testRTFCharacters() { assertEquals("\\'e0", formatter.format("\\`{a}")); assertEquals("\\'e8", formatter.format("\\`{e}")); assertEquals("\\'ec", formatter.format("\\`{i}")); assertEquals("\\'f2", formatter.format("\\`{o}")); assertEquals("\\'f9", formatter.format("\\`{u}")); assertEquals("\\'e1", formatter.format("\\'a")); assertEquals("\\'e9", formatter.format("\\'e")); assertEquals("\\'ed", formatter.format("\\'i")); assertEquals("\\'f3", formatter.format("\\'o")); assertEquals("\\'fa", formatter.format("\\'u")); assertEquals("\\'e2", formatter.format("\\^a")); assertEquals("\\'ea", formatter.format("\\^e")); assertEquals("\\'ee", formatter.format("\\^i")); assertEquals("\\'f4", formatter.format("\\^o")); assertEquals("\\'fa", formatter.format("\\^u")); assertEquals("\\'e4", formatter.format("\\\"a")); assertEquals("\\'eb", formatter.format("\\\"e")); assertEquals("\\'ef", formatter.format("\\\"i")); assertEquals("\\'f6", formatter.format("\\\"o")); assertEquals("\\u252u", formatter.format("\\\"u")); assertEquals("\\'f1", formatter.format("\\~n")); } @Test void testRTFCharactersCapital() { assertEquals("\\'c0", formatter.format("\\`A")); assertEquals("\\'c8", formatter.format("\\`E")); assertEquals("\\'cc", formatter.format("\\`I")); assertEquals("\\'d2", formatter.format("\\`O")); assertEquals("\\'d9", formatter.format("\\`U")); assertEquals("\\'c1", formatter.format("\\'A")); assertEquals("\\'c9", formatter.format("\\'E")); assertEquals("\\'cd", formatter.format("\\'I")); assertEquals("\\'d3", formatter.format("\\'O")); assertEquals("\\'da", formatter.format("\\'U")); assertEquals("\\'c2", formatter.format("\\^A")); assertEquals("\\'ca", formatter.format("\\^E")); assertEquals("\\'ce", formatter.format("\\^I")); assertEquals("\\'d4", formatter.format("\\^O")); assertEquals("\\'db", formatter.format("\\^U")); assertEquals("\\'c4", formatter.format("\\\"A")); assertEquals("\\'cb", formatter.format("\\\"E")); assertEquals("\\'cf", formatter.format("\\\"I")); assertEquals("\\'d6", formatter.format("\\\"O")); assertEquals("\\'dc", formatter.format("\\\"U")); } }
10,901
43.680328
151
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RemoveBracketsAddCommaTest.java
package org.jabref.logic.layout.format; import java.util.stream.Stream; import org.jabref.logic.layout.LayoutFormatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoveBracketsAddCommaTest { private LayoutFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveBracketsAddComma(); } @ParameterizedTest @MethodSource("provideExamples") void formatTextWithBrackets(String formattedString, String originalString) { assertEquals(formattedString, formatter.format(originalString)); } private static Stream<Arguments> provideExamples() { return Stream.of( Arguments.of("some text,", "{some text}"), Arguments.of("some text", "{some text"), Arguments.of("some text,", "some text}") ); } }
1,062
28.527778
80
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RemoveBracketsTest.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.LayoutFormatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoveBracketsTest { private LayoutFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveBrackets(); } @Test public void bracePairCorrectlyRemoved() throws Exception { assertEquals("some text", formatter.format("{some text}")); } @Test public void singleOpeningBraceCorrectlyRemoved() throws Exception { assertEquals("some text", formatter.format("{some text")); } @Test public void singleClosingBraceCorrectlyRemoved() throws Exception { assertEquals("some text", formatter.format("some text}")); } @Test public void bracePairWithEscapedBackslashCorrectlyRemoved() throws Exception { assertEquals("\\some text\\", formatter.format("\\{some text\\}")); } @Test public void withoutBracketsUnmodified() throws Exception { assertEquals("some text", formatter.format("some text")); } }
1,177
26.395349
82
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RemoveLatexCommandsFormatterTest.java
package org.jabref.logic.layout.format; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class RemoveLatexCommandsFormatterTest { private RemoveLatexCommandsFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveLatexCommandsFormatter(); } @Test public void withoutLatexCommandsUnmodified() { assertEquals("some text", formatter.format("some text")); } @Test public void singleCommandWiped() { assertEquals("", formatter.format("\\sometext")); } @Test public void singleSpaceAfterCommandRemoved() { assertEquals("text", formatter.format("\\some text")); } @Test public void multipleSpacesAfterCommandRemoved() { assertEquals("text", formatter.format("\\some text")); } @Test public void escapedBackslashBecomesBackslash() { assertEquals("\\", formatter.format("\\\\")); } @Test public void escapedBackslashFollowedByTextBecomesBackslashFollowedByText() { assertEquals("\\some text", formatter.format("\\\\some text")); } @Test public void escapedBackslashKept() { assertEquals("\\some text\\", formatter.format("\\\\some text\\\\")); } @Test public void escapedUnderscoreReplaces() { assertEquals("some_text", formatter.format("some\\_text")); } @Test public void exampleUrlCorrectlyCleaned() { assertEquals("http://pi.informatik.uni-siegen.de/stt/36_2/./03_Technische_Beitraege/ZEUS2016/beitrag_2.pdf", formatter.format("http://pi.informatik.uni-siegen.de/stt/36\\_2/./03\\_Technische\\_Beitraege/ZEUS2016/beitrag\\_2.pdf")); } }
1,763
27.451613
239
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RemoveTildeTest.java
package org.jabref.logic.layout.format; import java.util.stream.Stream; import org.jabref.logic.layout.LayoutFormatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoveTildeTest { private LayoutFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveTilde(); } @ParameterizedTest @MethodSource("provideArguments") void formatText(String formattedString, String originalString) { assertEquals(formattedString, formatter.format(originalString)); } private static Stream<Arguments> provideArguments() { return Stream.of( Arguments.of("", ""), Arguments.of("simple", "simple"), Arguments.of(" ", "~"), Arguments.of(" ", "~~~"), Arguments.of(" \\~ ", "~\\~~"), Arguments.of("\\\\ ", "\\\\~"), Arguments.of("Doe Joe and Jane, M. and Kamp, J. A.", "Doe Joe and Jane, M. and Kamp, J.~A."), Arguments.of("T\\~olkien, J. R. R.", "T\\~olkien, J.~R.~R.") ); } }
1,312
31.02439
109
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RemoveWhitespaceTest.java
package org.jabref.logic.layout.format; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class RemoveWhitespaceTest { @Test public void testEmptyExpectEmpty() { assertEquals("", new RemoveWhitespace().format("")); } @Test public void testNullExpectNull() { assertNull(new RemoveWhitespace().format(null)); } @Test public void testNormal() { assertEquals("abcd EFG", new RemoveWhitespace().format("abcd EFG")); } @Test public void testTab() { assertEquals("abcd EFG", new RemoveWhitespace().format("abcd\t EFG")); } @Test public void testNewLineCombo() { assertEquals("abcd EFG", new RemoveWhitespace().format("abcd\r E\nFG\r\n")); } }
856
23.485714
84
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/ReplaceTest.java
package org.jabref.logic.layout.format; import org.jabref.logic.layout.ParamLayoutFormatter; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class ReplaceTest { @Test public void testSimpleText() { ParamLayoutFormatter a = new Replace(); a.setArgument("Bob,Ben"); assertEquals("Ben Bruce", a.format("Bob Bruce")); } @Test public void testSimpleTextNoHit() { ParamLayoutFormatter a = new Replace(); a.setArgument("Bob,Ben"); assertEquals("Jolly Jumper", a.format("Jolly Jumper")); } @Test public void testFormatNull() { ParamLayoutFormatter a = new Replace(); a.setArgument("Eds.,Ed."); assertEquals(null, a.format(null)); } @Test public void testFormatEmpty() { ParamLayoutFormatter a = new Replace(); a.setArgument("Eds.,Ed."); assertEquals("", a.format("")); } @Test public void testNoArgumentSet() { ParamLayoutFormatter a = new Replace(); assertEquals("Bob Bruce and Jolly Jumper", a.format("Bob Bruce and Jolly Jumper")); } @Test public void testNoProperArgument() { ParamLayoutFormatter a = new Replace(); a.setArgument("Eds."); assertEquals("Bob Bruce and Jolly Jumper", a.format("Bob Bruce and Jolly Jumper")); } }
1,396
25.865385
91
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/ReplaceUnicodeLigaturesFormatterTest.java
package org.jabref.logic.layout.format; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class ReplaceUnicodeLigaturesFormatterTest { private ReplaceUnicodeLigaturesFormatter formatter; @BeforeEach public void setUp() { formatter = new ReplaceUnicodeLigaturesFormatter(); } @Test public void testPlainFormat() { assertEquals("lorem ipsum", formatter.format("lorem ipsum")); } @Test public void testSingleLigatures() { assertEquals("AA", formatter.format("\uA732")); assertEquals("fi", formatter.format("fi")); assertEquals("et", formatter.format("\uD83D\uDE70")); } @Test public void testLigatureSequence() { assertEquals("aefffflstue", formatter.format("æfffflstᵫ")); } @Test public void testSampleInput() { assertEquals("AEneas", formatter.format("Æneas")); } }
983
24.230769
69
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RisKeywordsTest.java
package org.jabref.logic.layout.format; import org.jabref.logic.util.OS; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RisKeywordsTest { @Test public void testEmpty() { assertEquals("", new RisKeywords().format("")); } @Test public void testNull() { assertEquals("", new RisKeywords().format(null)); } @Test public void testSingleKeyword() { assertEquals("KW - abcd", new RisKeywords().format("abcd")); } @Test public void testTwoKeywords() { assertEquals("KW - abcd" + OS.NEWLINE + "KW - efg", new RisKeywords().format("abcd, efg")); } @Test public void testMultipleKeywords() { assertEquals("KW - abcd" + OS.NEWLINE + "KW - efg" + OS.NEWLINE + "KW - hij" + OS.NEWLINE + "KW - klm", new RisKeywords().format("abcd, efg, hij, klm")); } }
933
24.243243
101
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/RisMonthTest.java
package org.jabref.logic.layout.format; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class RisMonthTest { @Test public void testEmpty() { assertEquals("", new RisMonth().format("")); } @Test public void testNull() { assertEquals("", new RisMonth().format(null)); } @ParameterizedTest(name = "input={0}, formattedStr={1}") @CsvSource({ "jan, 01", // jan "feb, 02", // feb "mar, 03", // mar "apr, 04", // apr "may, 05", // may "jun, 06", // jun "jul, 07", // jul "aug, 08", // aug "sep, 09", // sep "oct, 10", // oct "nov, 11", // nov "dec, 12", // dec }) public void testValidMonth(String input, String expectedResult) { String formattedStr = new RisMonth().format(input); assertEquals(expectedResult, formattedStr); } @Test public void testInvalidMonth() { assertEquals("abcd", new RisMonth().format("abcd")); } }
1,222
25.586957
69
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/ShortMonthFormatterTest.java
package org.jabref.logic.layout.format; import java.util.stream.Stream; import org.jabref.logic.layout.LayoutFormatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class ShortMonthFormatterTest { private LayoutFormatter formatter; @BeforeEach public void setUp() { formatter = new ShortMonthFormatter(); } @Test public void formatNullInput() { assertEquals("", formatter.format(null)); } @ParameterizedTest @MethodSource("provideArguments") public void formatDifferentInputs(String formattedString, String originalString) { assertEquals(formattedString, formatter.format(originalString)); } private static Stream<Arguments> provideArguments() { return Stream.of( Arguments.of("jan", "jan"), Arguments.of("jan", "January"), Arguments.of("jan", "Januar"), Arguments.of("jan", "01"), Arguments.of("", "Invented Month"), Arguments.of("", "") ); } }
1,301
27.304348
86
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/ToLowerCaseTest.java
package org.jabref.logic.layout.format; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; public class ToLowerCaseTest { @Test public void testNull() { assertNull(new ToLowerCase().format(null)); } @ParameterizedTest @MethodSource("provideArguments") public void toLowerCaseWithDifferentInputs(String expectedString, String originalString) { assertEquals(expectedString, new ToLowerCase().format(originalString)); } private static Stream<Arguments> provideArguments() { return Stream.of( Arguments.of("", ""), Arguments.of("abcd efg", "abcd efg"), Arguments.of("abcd efg", "ABCD EFG"), Arguments.of("abcd efg", "abCD eFg"), Arguments.of("abcd123efg", "abCD123eFg"), Arguments.of("hello!*#", "Hello!*#"), Arguments.of("123*%&456", "123*%&456") ); } }
1,232
31.447368
94
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/ToUpperCaseTest.java
package org.jabref.logic.layout.format; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class ToUpperCaseTest { ToUpperCase upperCase = new ToUpperCase(); @ParameterizedTest @MethodSource("toUpperCaseTests") void toUpperCaseTests(String expectedString, String inputString) { assertEquals(expectedString, upperCase.format(inputString)); } private static Stream<Arguments> toUpperCaseTests() { return Stream.of( Arguments.of("", ""), Arguments.of(null, null), Arguments.of("ABCD EFG", "abcd efg"), Arguments.of("ABCD EFG", "ABCD EFG"), Arguments.of("ABCD EFG", "abCD eFg") ); } }
927
28.935484
70
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/WrapContentTest.java
package org.jabref.logic.layout.format; import java.util.stream.Stream; import org.jabref.logic.layout.ParamLayoutFormatter; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class WrapContentTest { private ParamLayoutFormatter wrapContentParamLayoutFormatter = new WrapContent(); @ParameterizedTest @MethodSource("provideContent") void formatContent(String formattedContent, String originalContent, String desiredFormat) { if (!desiredFormat.isEmpty()) { wrapContentParamLayoutFormatter.setArgument(desiredFormat); } assertEquals(formattedContent, wrapContentParamLayoutFormatter.format(originalContent)); } private static Stream<Arguments> provideContent() { return Stream.of( Arguments.of("<Bob>", "Bob", "<,>"), Arguments.of("Bob:", "Bob", ",:"), Arguments.of("Content: Bob", "Bob", "Content: ,"), Arguments.of("Name,Field,Bob,Author", "Bob", "Name\\,Field\\,,\\,Author"), Arguments.of(null, null, "Eds.,Ed."), Arguments.of("", "", "Eds.,Ed."), Arguments.of("Bob Bruce and Jolly Jumper", "Bob Bruce and Jolly Jumper", ""), Arguments.of("Bob Bruce and Jolly Jumper", "Bob Bruce and Jolly Jumper", "Eds.") ); } }
1,508
36.725
96
java
null
jabref-main/src/test/java/org/jabref/logic/layout/format/WrapFileLinksTest.java
package org.jabref.logic.layout.format; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class WrapFileLinksTest { private WrapFileLinks formatter; @BeforeEach void setUp() { formatter = new WrapFileLinks(Collections.emptyList(), ""); } @Test void testEmpty() { assertEquals("", formatter.format("")); } @Test void testNull() { assertEquals("", formatter.format(null)); } @Test void testNoFormatSetNonEmptyString() { assertThrows(NullPointerException.class, () -> formatter.format("test.pdf")); } @Test void testFileExtension() { formatter.setArgument("\\x"); assertEquals("pdf", formatter.format("test.pdf")); } @Test void testFileExtensionNoExtension() { formatter.setArgument("\\x"); assertEquals("", formatter.format("test")); } @Test void testPlainTextString() { formatter.setArgument("x"); assertEquals("x", formatter.format("test.pdf")); } @Test void testDescription() { formatter.setArgument("\\d"); assertEquals("Test file", formatter.format("Test file:test.pdf:PDF")); } @Test void testDescriptionNoDescription() { formatter.setArgument("\\d"); assertEquals("", formatter.format("test.pdf")); } @Test void testType() { formatter.setArgument("\\f"); assertEquals("PDF", formatter.format("Test file:test.pdf:PDF")); } @Test void testTypeNoType() { formatter.setArgument("\\f"); assertEquals("", formatter.format("test.pdf")); } @Test void testIterator() { formatter.setArgument("\\i"); assertEquals("1", formatter.format("Test file:test.pdf:PDF")); } @Test void testIteratorTwoItems() { formatter.setArgument("\\i\n"); assertEquals("1\n2\n", formatter.format("Test file:test.pdf:PDF;test2.pdf")); } @Test void testEndingBracket() { formatter.setArgument("(\\d)"); assertEquals("(Test file)", formatter.format("Test file:test.pdf:PDF")); } @Test void testPath() throws IOException { formatter = new WrapFileLinks(Collections.singletonList(Path.of("src/test/resources/pdfs/")), ""); formatter.setArgument("\\p"); assertEquals(new File("src/test/resources/pdfs/encrypted.pdf").getCanonicalPath(), formatter.format("Preferences:encrypted.pdf:PDF")); } @Test void testPathFallBackToGeneratedDir() throws IOException { formatter = new WrapFileLinks(Collections.emptyList(), "src/test/resources/pdfs/"); formatter.setArgument("\\p"); assertEquals(new File("src/test/resources/pdfs/encrypted.pdf").getCanonicalPath(), formatter.format("Preferences:encrypted.pdf:PDF")); } @Test void testPathReturnsRelativePathIfNotFound() { formatter = new WrapFileLinks(Collections.singletonList(Path.of("src/test/resources/pdfs/")), ""); formatter.setArgument("\\p"); assertEquals("test.pdf", formatter.format("Preferences:test.pdf:PDF")); } @Test void testRelativePath() { formatter.setArgument("\\r"); assertEquals("test.pdf", formatter.format("Test file:test.pdf:PDF")); } }
3,574
27.149606
106
java
null
jabref-main/src/test/java/org/jabref/logic/msbib/MSBibConverterTest.java
package org.jabref.logic.msbib; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class MSBibConverterTest { private final BibEntry BIB_ENTRY_TEST = new BibEntry(StandardEntryType.InProceedings) .withField(StandardField.AUTHOR, "Igor Steinmacher and Tayana Uchoa Conte and Christoph Treude and Marco Aurélio Gerosa") .withField(StandardField.DATE, "14-22 May 2016") .withField(StandardField.YEAR, "2016") .withField(StandardField.EVENTDATE, "14-22 May 2016") .withField(StandardField.EVENTTITLEADDON, "Austin, TX, USA") .withField(StandardField.LOCATION, "Austin, TX, USA") .withField(StandardField.DOI, "10.1145/2884781.2884806") .withField(StandardField.JOURNALTITLE, "2016 IEEE/ACM 38th International Conference on Software Engineering (ICSE)") .withField(StandardField.PAGES, "273--284") .withField(StandardField.ISBN, "978-1-5090-2071-3") .withField(StandardField.ISSN, "1558-1225") .withField(StandardField.LANGUAGE, "english") .withField(StandardField.PUBLISHER, "IEEE") .withField(StandardField.KEYWORDS, "Portals, Documentation, Computer bugs, Joining processes, Industries, Open source software, Newcomers, Newbies, Novices, Beginners, Open Source Software, Barriers, Obstacles, Onboarding, Joining Process") .withField(StandardField.TITLE, "Overcoming Open Source Project Entry Barriers with a Portal for Newcomers") .withField(StandardField.FILE, ":https\\://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7886910:PDF"); private BibEntry entry; @Test void convert() { entry = BIB_ENTRY_TEST; MSBibConverter.convert(entry); assertEquals(Optional.of("english"), entry.getField(StandardField.LANGUAGE)); } }
2,083
47.465116
252
java
null
jabref-main/src/test/java/org/jabref/logic/msbib/MsBibAuthorTest.java
package org.jabref.logic.msbib; import org.jabref.model.entry.Author; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class MsBibAuthorTest { @Test public void testGetFirstName() { Author author = new Author("Gustav Peter Johann", null, null, "Bach", null); MsBibAuthor msBibAuthor = new MsBibAuthor(author); assertEquals("Gustav", msBibAuthor.getFirstName()); } @Test public void testGetMiddleName() { Author author = new Author("Gustav Peter Johann", null, null, "Bach", null); MsBibAuthor msBibAuthor = new MsBibAuthor(author); assertEquals("Peter Johann", msBibAuthor.getMiddleName()); } @Test public void testGetNoMiddleName() { Author author = new Author("Gustav", null, null, "Bach", null); MsBibAuthor msBibAuthor = new MsBibAuthor(author); assertEquals(null, msBibAuthor.getMiddleName()); } @Test public void testGetNoFirstName() { Author author = new Author(null, null, null, "Bach", null); MsBibAuthor msBibAuthor = new MsBibAuthor(author); assertEquals(null, msBibAuthor.getMiddleName()); } @Test public void testGetLastName() { Author author = new Author("Gustav Peter Johann", null, null, "Bach", null); MsBibAuthor msBibAuthor = new MsBibAuthor(author); assertEquals("Bach", msBibAuthor.getLastName()); } @Test public void testGetVonAndLastName() { Author author = new Author("John", null, "von", "Neumann", null); MsBibAuthor msBibAuthor = new MsBibAuthor(author); assertEquals("von Neumann", msBibAuthor.getLastName()); } }
1,722
31.509434
84
java
null
jabref-main/src/test/java/org/jabref/logic/msbib/MsBibMappingTest.java
package org.jabref.logic.msbib; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class MsBibMappingTest { @Test public void testGetLanguage() { String lang = MSBibMapping.getLanguage(1609); assertEquals("basque", lang); } @Test public void testGetLCID() { int lcid = MSBibMapping.getLCID("basque"); assertEquals(1609, lcid); } @Test public void testGetInvalidLanguage() { String lang = MSBibMapping.getLanguage(1234567); assertEquals("english", lang); } @Test public void testInvalidLCID() { int lcid = MSBibMapping.getLCID("not a language"); assertEquals(1033, lcid); } }
745
22.3125
60
java
null
jabref-main/src/test/java/org/jabref/logic/net/MimeTypeDetectorTest.java
package org.jabref.logic.net; /* import com.github.tomakehurst.wiremock.WireMockServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.head; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class MimeTypeDetectorTest { private WireMockServer wireMockServer = new WireMockServer(); @BeforeEach void before() { wireMockServer.start(); } @AfterEach void after() { wireMockServer.stop(); } @Test void handlePermanentRedirections() throws IOException { String redirectedUrl = "http://localhost:8080/redirection"; stubFor(any(urlEqualTo("/redirection")) .willReturn( aResponse() .withStatus(301) .withHeader("Location", "http://docs.oasis-open.org/wsbpel/2.0/OS/wsbpel-v2.0-OS.pdf") ) ); assertTrue(new URLDownload(redirectedUrl).isMimeType("application/pdf")); } @Test void beFalseForUnreachableUrl() throws IOException { String invalidUrl = "http://idontknowthisurlforsure.de"; assertFalse(new URLDownload(invalidUrl).isMimeType("application/pdf")); } @Test void beTrueForPdfMimeType() throws IOException { String pdfUrl = "http://docs.oasis-open.org/wsbpel/2.0/OS/wsbpel-v2.0-OS.pdf"; assertTrue(new URLDownload(pdfUrl).isMimeType("application/pdf")); } @Test void beTrueForLocalPdfUri() throws URISyntaxException, IOException { String localPath = MimeTypeDetectorTest.class.getResource("empty.pdf").toURI().toASCIIString(); assertTrue(new URLDownload(localPath).isMimeType("application/pdf")); } @Test void beTrueForPDFMimeTypeVariations() throws IOException { String mimeTypeVariation = "http://localhost:8080/mimevariation"; stubFor(any(urlEqualTo("/mimevariation")) .willReturn( aResponse().withHeader("Content-Type", "application/pdf;charset=ISO-8859-1") ) ); assertTrue(new URLDownload(mimeTypeVariation).isMimeType("application/pdf")); } @Test void beAbleToUseHeadRequest() throws IOException { String mimeTypeVariation = "http://localhost:8080/mimevariation"; stubFor(head(urlEqualTo("/mimevariation")) .willReturn( aResponse().withHeader("Content-Type", "application/pdf;charset=ISO-8859-1") ) ); assertTrue(new URLDownload(mimeTypeVariation).isMimeType("application/pdf")); } @Test void beAbleToUseGetRequest() throws IOException { String mimeTypeVariation = "http://localhost:8080/mimevariation"; stubFor(head(urlEqualTo("/mimevariation")) .willReturn( aResponse().withStatus(404) ) ); stubFor(get(urlEqualTo("/mimevariation")) .willReturn( aResponse().withHeader("Content-Type", "application/pdf;charset=ISO-8859-1") ) ); assertTrue(new URLDownload(mimeTypeVariation).isMimeType("application/pdf")); } } */
3,768
33.263636
118
java
null
jabref-main/src/test/java/org/jabref/logic/net/ProxyTest.java
package org.jabref.logic.net; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class ProxyTest { /** * The test checks if ProxyPreference class is still able to store password and use it from memory, * even though it's no longer stored in register. */ @Test public void testProxyPreferencesStorePassword() { // mock data boolean useProxy = true; String hostname = "testName"; String port = "8080"; boolean useAuthentication = true; String username = "testUserName"; String password = "testPassword"; boolean persist = false; // Creates proxy preference ProxyPreferences proxyPref = new ProxyPreferences( useProxy, hostname, port, useAuthentication, username, password, persist); // Check if mock data is stored in object memory and can be extracted assertEquals(proxyPref.shouldUseProxy(), true); assertEquals(proxyPref.getHostname(), hostname); assertEquals(proxyPref.getPort(), port); assertEquals(proxyPref.shouldUseAuthentication(), true); assertEquals(proxyPref.getUsername(), username); assertEquals(proxyPref.getPassword(), password); assertEquals(proxyPref.shouldPersistPassword(), persist); } }
1,418
32
102
java
null
jabref-main/src/test/java/org/jabref/logic/net/URLDownloadTest.java
package org.jabref.logic.net; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherServerException; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import kong.unirest.UnirestException; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @FetcherTest public class URLDownloadTest { private static final Logger LOGGER = LoggerFactory.getLogger(URLDownloadTest.class); @Test public void testStringDownloadWithSetEncoding() throws IOException { URLDownload dl = new URLDownload(new URL("http://www.google.com")); assertTrue(dl.asString().contains("Google"), "google.com should contain google"); } @Test public void testStringDownload() throws IOException { URLDownload dl = new URLDownload(new URL("http://www.google.com")); assertTrue(dl.asString(StandardCharsets.UTF_8).contains("Google"), "google.com should contain google"); } @Test public void testFileDownload() throws IOException { File destination = File.createTempFile("jabref-test", ".html"); try { URLDownload dl = new URLDownload(new URL("http://www.google.com")); dl.toFile(destination.toPath()); assertTrue(destination.exists(), "file must exist"); } finally { // cleanup if (!destination.delete()) { LOGGER.error("Cannot delete downloaded file"); } } } @Test public void testDetermineMimeType() throws IOException { URLDownload dl = new URLDownload(new URL("http://www.google.com")); assertTrue(dl.getMimeType().startsWith("text/html")); } @Test public void downloadToTemporaryFilePathWithoutFileSavesAsTmpFile() throws IOException { URLDownload google = new URLDownload(new URL("http://www.google.com")); String path = google.toTemporaryFile().toString(); assertTrue(path.endsWith(".tmp"), path); } @Test public void downloadToTemporaryFileKeepsName() throws IOException { URLDownload google = new URLDownload(new URL("https://github.com/JabRef/jabref/blob/main/LICENSE.md")); String path = google.toTemporaryFile().toString(); assertTrue(path.contains("LICENSE") && path.endsWith(".md"), path); } @Test @DisabledOnCIServer("CI Server is apparently blocked") public void downloadOfFTPSucceeds() throws IOException { URLDownload ftp = new URLDownload(new URL("ftp://ftp.informatik.uni-stuttgart.de/pub/library/ncstrl.ustuttgart_fi/INPROC-2016-15/INPROC-2016-15.pdf")); Path path = ftp.toTemporaryFile(); assertNotNull(path); } @Test public void downloadOfHttpSucceeds() throws IOException { URLDownload ftp = new URLDownload(new URL("http://www.jabref.org")); Path path = ftp.toTemporaryFile(); assertNotNull(path); } @Test public void downloadOfHttpsSucceeds() throws IOException { URLDownload ftp = new URLDownload(new URL("https://www.jabref.org")); Path path = ftp.toTemporaryFile(); assertNotNull(path); } @Test public void testCheckConnectionSuccess() throws MalformedURLException { URLDownload google = new URLDownload(new URL("http://www.google.com")); assertTrue(google.canBeReached()); } @Test public void testCheckConnectionFail() throws MalformedURLException { URLDownload nonsense = new URLDownload(new URL("http://nonsenseadddress")); assertThrows(UnirestException.class, nonsense::canBeReached); } @Test public void connectTimeoutIsNeverNull() throws MalformedURLException { URLDownload urlDownload = new URLDownload(new URL("http://www.example.com")); assertNotNull(urlDownload.getConnectTimeout(), "there's a non-null default by the constructor"); urlDownload.setConnectTimeout(null); assertNotNull(urlDownload.getConnectTimeout(), "no null value can be set"); } @Test public void test503ErrorThrowsNestedIOExceptionWithFetcherServerException() throws Exception { URLDownload urlDownload = new URLDownload(new URL("http://httpstat.us/503")); Exception exception = assertThrows(IOException.class, urlDownload::asString); assertTrue(exception.getCause() instanceof FetcherServerException); } @Test public void test429ErrorThrowsNestedIOExceptionWithFetcherServerException() throws Exception { URLDownload urlDownload = new URLDownload(new URL("http://httpstat.us/429")); Exception exception = assertThrows(IOException.class, urlDownload::asString); assertTrue(exception.getCause() instanceof FetcherClientException); } }
5,199
34.862069
159
java
null
jabref-main/src/test/java/org/jabref/logic/net/URLUtilTest.java
package org.jabref.logic.net; import org.jabref.gui.fieldeditors.URLUtil; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class URLUtilTest { @Test void cleanGoogleSearchURL() throws Exception { // empty text assertEquals("", URLUtil.cleanGoogleSearchURL("")); assertEquals(" ", URLUtil.cleanGoogleSearchURL(" ")); // no URL assertEquals("this is no url!", URLUtil.cleanGoogleSearchURL("this is no url!")); // no Google search URL assertEquals("http://dl.acm.org/citation.cfm?id=321811", URLUtil.cleanGoogleSearchURL("http://dl.acm.org/citation.cfm?id=321811")); // malformed Google URL assertEquals("https://www.google.de/url♥", URLUtil.cleanGoogleSearchURL("https://www.google.de/url♥")); // no queries assertEquals("https://www.google.de/url", URLUtil.cleanGoogleSearchURL("https://www.google.de/url")); assertEquals("https://www.google.de/url?", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?")); // no multiple queries assertEquals("https://www.google.de/url?key=value", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?key=value")); // no key values assertEquals("https://www.google.de/url?key", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?key")); assertEquals("https://www.google.de/url?url", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?url")); assertEquals("https://www.google.de/url?key=", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?key=")); // no url param assertEquals("https://www.google.de/url?key=value&key2=value2", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?key=value&key2=value2")); // no url param value assertEquals("https://www.google.de/url?url=", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?url=")); // url param value no URL assertEquals("https://www.google.de/url?url=this+is+no+url", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?url=this+is+no+url")); // Http assertEquals( "http://moz.com/ugc/the-ultimate-guide-to-the-google-search-parameters", URLUtil.cleanGoogleSearchURL("http://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCEQFjAAahUKEwjJurHd2sfHAhWBsxQKHSrEAaM&url=http%3A%2F%2Fmoz.com%2Fugc%2Fthe-ultimate-guide-to-the-google-search-parameters&ei=0THeVYmOJIHnUqqIh5gK&usg=AFQjCNHnid_r_d2LP8_MqvI7lQnTC3lB_g&sig2=ICzxDroG2ENTJSUGmdhI2w")); // Https assertEquals( "https://moz.com/ugc/the-ultimate-guide-to-the-google-search-parameters", URLUtil.cleanGoogleSearchURL("https://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCEQFjAAahUKEwjJurHd2sfHAhWBsxQKHSrEAaM&url=https%3A%2F%2Fmoz.com%2Fugc%2Fthe-ultimate-guide-to-the-google-search-parameters&ei=0THeVYmOJIHnUqqIh5gK&usg=AFQjCNHnid_r_d2LP8_MqvI7lQnTC3lB_g&sig2=ICzxDroG2ENTJSUGmdhI2w")); // root domain assertEquals( "https://moz.com/ugc/the-ultimate-guide-to-the-google-search-parameters", URLUtil.cleanGoogleSearchURL("https://google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCEQFjAAahUKEwjJurHd2sfHAhWBsxQKHSrEAaM&url=https%3A%2F%2Fmoz.com%2Fugc%2Fthe-ultimate-guide-to-the-google-search-parameters&ei=0THeVYmOJIHnUqqIh5gK&usg=AFQjCNHnid_r_d2LP8_MqvI7lQnTC3lB_g&sig2=ICzxDroG2ENTJSUGmdhI2w")); // foreign domain assertEquals( "https://moz.com/ugc/the-ultimate-guide-to-the-google-search-parameters", URLUtil.cleanGoogleSearchURL("https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCEQFjAAahUKEwjJurHd2sfHAhWBsxQKHSrEAaM&url=https%3A%2F%2Fmoz.com%2Fugc%2Fthe-ultimate-guide-to-the-google-search-parameters&ei=0THeVYmOJIHnUqqIh5gK&usg=AFQjCNHnid_r_d2LP8_MqvI7lQnTC3lB_g&sig2=ICzxDroG2ENTJSUGmdhI2w")); // foreign domain co.uk assertEquals( "https://moz.com/ugc/the-ultimate-guide-to-the-google-search-parameters", URLUtil.cleanGoogleSearchURL("https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCEQFjAAahUKEwjJurHd2sfHAhWBsxQKHSrEAaM&url=https%3A%2F%2Fmoz.com%2Fugc%2Fthe-ultimate-guide-to-the-google-search-parameters&ei=0THeVYmOJIHnUqqIh5gK&usg=AFQjCNHnid_r_d2LP8_MqvI7lQnTC3lB_g&sig2=ICzxDroG2ENTJSUGmdhI2w")); // accept ftp results assertEquals( "ftp://moz.com/ugc/the-ultimate-guide-to-the-google-search-parameters", URLUtil.cleanGoogleSearchURL("https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCEQFjAAahUKEwjJurHd2sfHAhWBsxQKHSrEAaM&url=ftp%3A%2F%2Fmoz.com%2Fugc%2Fthe-ultimate-guide-to-the-google-search-parameters&ei=0THeVYmOJIHnUqqIh5gK&usg=AFQjCNHnid_r_d2LP8_MqvI7lQnTC3lB_g&sig2=ICzxDroG2ENTJSUGmdhI2w")); } @Test void isURLshouldAcceptValidURL() { assertTrue(URLUtil.isURL("http://www.google.com")); assertTrue(URLUtil.isURL("https://www.google.com")); } @Test void isURLshouldRejectInvalidURL() { assertFalse(URLUtil.isURL("www.google.com")); assertFalse(URLUtil.isURL("google.com")); } @Test void isURLshouldRejectEmbeddedURL() { assertFalse(URLUtil.isURL("dblp computer science bibliography, http://dblp.org")); } }
5,638
67.768293
351
java
null
jabref-main/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java
package org.jabref.logic.openoffice.style; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; class OOBibStyleTest { private final LayoutFormatterPreferences layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); private final JournalAbbreviationRepository abbreviationRepository = mock(JournalAbbreviationRepository.class); @Test void testAuthorYear() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); assertFalse(style.isBoldCitations()); assertFalse(style.isFormatCitations()); assertFalse(style.isItalicCitations()); assertFalse(style.isNumberEntries()); assertFalse(style.isSortByPosition()); } @Test void testAuthorYearAsFile() throws URISyntaxException, IOException { Path defFile = Path.of(OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()); OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, abbreviationRepository); assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); assertFalse(style.isBoldCitations()); assertFalse(style.isFormatCitations()); assertFalse(style.isItalicCitations()); assertFalse(style.isNumberEntries()); assertFalse(style.isSortByPosition()); } @Test void testNumerical() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertTrue(style.isValid()); assertFalse(style.isCitationKeyCiteMarkers()); assertFalse(style.isBoldCitations()); assertFalse(style.isFormatCitations()); assertFalse(style.isItalicCitations()); assertTrue(style.isNumberEntries()); assertTrue(style.isSortByPosition()); } /* * begin helpers */ static String runGetNumCitationMarker2a(OOBibStyle style, List<Integer> num, int minGroupingCount, boolean inList) { return OOBibStyleTestHelper.runGetNumCitationMarker2a(style, num, minGroupingCount, inList); } static CitationMarkerNumericEntry numEntry(String key, int num, String pageInfoOrNull) { return OOBibStyleTestHelper.numEntry(key, num, pageInfoOrNull); } static CitationMarkerNumericBibEntry numBibEntry(String key, Optional<Integer> num) { return OOBibStyleTestHelper.numBibEntry(key, num); } static String runGetNumCitationMarker2b(OOBibStyle style, int minGroupingCount, CitationMarkerNumericEntry... s) { List<CitationMarkerNumericEntry> input = Stream.of(s).collect(Collectors.toList()); OOText res = style.getNumCitationMarker2(input, minGroupingCount); return res.toString(); } static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, BibDatabase database, String uniqueLetterQ, String pageInfoQ, boolean isFirstAppearanceOfSource) { return OOBibStyleTestHelper.makeCitationMarkerEntry(entry, database, uniqueLetterQ, pageInfoQ, isFirstAppearanceOfSource); } /* * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ static String getCitationMarker2(OOBibStyle style, List<BibEntry> entries, Map<BibEntry, BibDatabase> entryDBMap, boolean inParenthesis, String[] uniquefiers, Boolean[] isFirstAppearanceOfSource, String[] pageInfo) { return OOBibStyleTestHelper.getCitationMarker2(style, entries, entryDBMap, inParenthesis, uniquefiers, isFirstAppearanceOfSource, pageInfo); } static String getCitationMarker2b(OOBibStyle style, List<BibEntry> entries, Map<BibEntry, BibDatabase> entryDBMap, boolean inParenthesis, String[] uniquefiers, Boolean[] isFirstAppearanceOfSource, String[] pageInfo) { return OOBibStyleTestHelper.getCitationMarker2b(style, entries, entryDBMap, inParenthesis, uniquefiers, isFirstAppearanceOfSource, pageInfo); } /* * end helpers */ @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertEquals("[1] ", runGetNumCitationMarker2a(style, List.of(1), -1, true)); assertEquals("[1]", runGetNumCitationMarker2a(style, List.of(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2b(style, -1, numEntry("key", 1, null))); assertEquals("[1] ", runGetNumCitationMarker2a(style, List.of(1), 0, true)); CitationMarkerNumericEntry e2 = numEntry("key", 1, "pp. 55-56"); assertTrue(e2.getPageInfo().isPresent()); assertEquals("pp. 55-56", e2.getPageInfo().get().toString()); OOBibStyleTestHelper.testGetNumCitationMarkerExtra(style); } @Test void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); // unresolved citations look like [??key] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", runGetNumCitationMarker2b(style, 1, numEntry("key", 0, null))); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; p1]", runGetNumCitationMarker2b(style, 1, numEntry("key", 0, "p1"))); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", runGetNumCitationMarker2b(style, 1, numEntry("x4", 4, ""), numEntry("x2", 2, ""), numEntry("x3", 3, ""), numEntry("key", 0, ""))); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, ""), numEntry("x2", 2, ""), numEntry("y3", 3, ""), numEntry("key", 0, ""))); // multiple unresolved citations are not collapsed assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "x1" + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "x2" + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 0, ""), numEntry("x2", 0, ""), numEntry("x3", 0, ""))); /* * BIBLIOGRAPHY */ CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", style.getNumCitationMarkerForBibliography(x).toString()); } @Test void testGetCitProperty() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertEquals(", ", style.getStringCitProperty("AuthorSeparator")); // old assertEquals(3, style.getIntCitProperty("MaxAuthors")); assertTrue(style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)); // new assertEquals(3, style.getMaxAuthors()); assertTrue(style.getMultiCiteChronological()); assertEquals("Default", style.getCitationCharacterFormat()); assertEquals("Default [number] style file.", style.getName()); Set<String> journals = style.getJournals(); assertTrue(journals.contains("Journal name 1")); } @Test void testGetCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") .withField(StandardField.YEAR, "2006") .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") .withField(StandardField.PUBLISHER, "ACM") .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") .withField(StandardField.PAGES, "11--18"); entry.setCitationKey("Bostrom2006"); // citation key is not optional now BibDatabase database = new BibDatabase(); database.insertEntry(entry); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); entryDBMap.put(entry, database); // Check what unlimAuthors values correspond to isFirstAppearanceOfSource false/true assertEquals(3, style.getMaxAuthors()); assertEquals(-1, style.getMaxAuthorsFirst()); assertEquals("[Boström et al., 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, null, null)); assertEquals("Boström et al. [2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, false, null, new Boolean[]{false}, null)); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, new Boolean[]{true}, null)); } @Test void testLayout() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") .withField(StandardField.YEAR, "2006") .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") .withField(StandardField.PUBLISHER, "ACM") .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") .withField(StandardField.PAGES, "11--18"); BibDatabase database = new BibDatabase(); database.insertEntry(entry); Layout l = style.getReferenceFormat(new UnknownEntryType("default")); l.setPostFormatter(new OOPreFormatter()); assertEquals( "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (<b>2006</b>). <i>Extending XP practices to support security requirements engineering</i>, : 11-18.", l.doLayout(entry, database)); l = style.getReferenceFormat(StandardEntryType.InCollection); l.setPostFormatter(new OOPreFormatter()); assertEquals( "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (<b>2006</b>). <i>Extending XP practices to support security requirements engineering</i>. In: (Ed.), <i>SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems</i>, ACM.", l.doLayout(entry, database)); } @Test void testInstitutionAuthor() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); BibDatabase database = new BibDatabase(); Layout l = style.getReferenceFormat(StandardEntryType.Article); l.setPostFormatter(new OOPreFormatter()); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "{JabRef Development Team}"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); assertEquals("<b>JabRef Development Team</b> (<b>2016</b>). <i>JabRef Manual</i>, .", l.doLayout(entry, database)); } @Test void testVonAuthor() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); BibDatabase database = new BibDatabase(); Layout l = style.getReferenceFormat(StandardEntryType.Article); l.setPostFormatter(new OOPreFormatter()); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); assertEquals("<b>von Beta, A.</b> (<b>2016</b>). <i>JabRef Manual</i>, .", l.doLayout(entry, database)); } @Test void testInstitutionAuthorMarker() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setCitationKey("JabRef2016"); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "{JabRef Development Team}"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("[JabRef Development Team, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test void testVonAuthorMarker() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("[von Beta, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test void testNullAuthorMarker() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.YEAR, "2016"); entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("[, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test void testNullYearMarker() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("[von Beta, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test void testEmptyEntryMarker() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("[, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry(); entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", getCitationMarker2b(style, entries, entryDBMap, true, null, null, null)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", getCitationMarker2(style, entries, entryDBMap, true, new String[]{"a", "b", ""}, new Boolean[]{false, false, false}, null)); } @Test void testGetCitationMarkerInTextUniquefiers() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry(); entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); entries.add(entry2); entry2.setCitationKey("a2"); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", getCitationMarker2b(style, entries, entryDBMap, false, null, null, null)); assertEquals("Beta [2000a,b]; Epsilon [2001]", getCitationMarker2(style, entries, entryDBMap, false, new String[]{"a", "b", ""}, new Boolean[]{false, false, false}, null)); } @Test void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry(); entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("[Beta, 2000a,b,c]", getCitationMarker2(style, entries, entryDBMap, true, new String[]{"a", "b", "c"}, new Boolean[]{false, false, false}, null)); } @Test void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry(); entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("Beta [2000a,b,c]", getCitationMarker2(style, entries, entryDBMap, false, new String[]{"a", "b", "c"}, new Boolean[]{false, false, false}, null)); } @Test // TODO: equals only work when initialized from file, not from reader void testEquals() throws IOException { OOBibStyle style1 = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); OOBibStyle style2 = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertEquals(style1, style2); } @Test // TODO: equals only work when initialized from file, not from reader void testNotEquals() throws IOException { OOBibStyle style1 = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); OOBibStyle style2 = new OOBibStyle( StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertNotEquals(style1, style2); } @Test void testCompareToEqual() throws IOException { OOBibStyle style1 = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); OOBibStyle style2 = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertEquals(0, style1.compareTo(style2)); } @Test void testCompareToNotEqual() throws IOException { OOBibStyle style1 = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); OOBibStyle style2 = new OOBibStyle( StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); assertTrue(style1.compareTo(style2) > 0); assertFalse(style2.compareTo(style1) > 0); } @Test void testEmptyStringPropertyAndOxfordComma() throws Exception { OOBibStyle style = new OOBibStyle("test.jstyle", layoutFormatterPreferences, abbreviationRepository); Map<BibEntry, BibDatabase> entryDBMap = new HashMap<>(); List<BibEntry> entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta and Gamma Epsilon and Ypsilon Tau"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("von Beta, Epsilon, & Tau, 2016", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test void testIsValidWithDefaultSectionAtTheStart() throws Exception { OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", layoutFormatterPreferences, abbreviationRepository); assertTrue(style.isValid()); } @Test void testGetCitationMarkerJoinFirst() throws IOException { OOBibStyle style = new OOBibStyle( StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences, abbreviationRepository); // Question: What should happen if some sources are // marked as isFirstAppearanceOfSource? // This test documents what is happening now. // Two entries with identical normalizedMarkers and many authors. BibEntry entry1 = new BibEntry() .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m" + " and Jaana W\\\"{a}yrynen" + " and Marine Bod\\'{e}n" + " and Konstantin Beznosov" + " and Philippe Kruchten") .withField(StandardField.YEAR, "2006") .withField(StandardField.BOOKTITLE, "A book 1") .withField(StandardField.PUBLISHER, "ACM") .withField(StandardField.TITLE, "Title 1") .withField(StandardField.PAGES, "11--18"); entry1.setCitationKey("b1"); BibEntry entry2 = new BibEntry() .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m" + " and Jaana W\\\"{a}yrynen" + " and Marine Bod\\'{e}n" + " and Konstantin Beznosov" + " and Philippe Kruchten") .withField(StandardField.YEAR, "2006") .withField(StandardField.BOOKTITLE, "A book 2") .withField(StandardField.PUBLISHER, "ACM") .withField(StandardField.TITLE, "title2") .withField(StandardField.PAGES, "11--18"); entry2.setCitationKey("b2"); // Last Author differs. BibEntry entry3 = new BibEntry() .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m" + " and Jaana W\\\"{a}yrynen" + " and Marine Bod\\'{e}n" + " and Konstantin Beznosov" + " and Philippe NotKruchten") .withField(StandardField.YEAR, "2006") .withField(StandardField.BOOKTITLE, "A book 3") .withField(StandardField.PUBLISHER, "ACM") .withField(StandardField.TITLE, "title3") .withField(StandardField.PAGES, "11--18"); entry3.setCitationKey("b3"); BibDatabase database = new BibDatabase(); database.insertEntry(entry1); database.insertEntry(entry2); database.insertEntry(entry3); // Without pageInfo, two isFirstAppearanceOfSource may be joined. // The third is NotKruchten, should not be joined. if (true) { List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = makeCitationMarkerEntry(entry1, database, "a", null, true); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = makeCitationMarkerEntry(entry2, database, "b", null, true); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = makeCitationMarkerEntry(entry3, database, "c", null, true); citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).toString()); assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", style.createCitationMarker(citationMarkerEntries, false, NonUniqueCitationMarker.THROWS).toString()); } // Without pageInfo, only the first is isFirstAppearanceOfSource. // The second may be joined, based on expanded normalizedMarkers. // The third is NotKruchten, should not be joined. if (true) { List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = makeCitationMarkerEntry(entry1, database, "a", null, true); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = makeCitationMarkerEntry(entry2, database, "b", null, false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = makeCitationMarkerEntry(entry3, database, "c", null, false); citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" + "; Boström et al., 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).toString()); } // Without pageInfo, only the second is isFirstAppearanceOfSource. // The second is not joined, because it is a first appearance, thus // requires more names to be shown. // The third is NotKruchten, should not be joined. if (true) { List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = makeCitationMarkerEntry(entry1, database, "a", null, false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = makeCitationMarkerEntry(entry2, database, "b", null, true); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = makeCitationMarkerEntry(entry3, database, "c", null, false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a" + "; Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006b" + "; Boström et al., 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).toString()); } // Without pageInfo, neither is isFirstAppearanceOfSource. // The second is joined. // The third is NotKruchten, but is joined because NotKruchten is not among the names shown. // Is this the correct behaviour? if (true) { List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = makeCitationMarkerEntry(entry1, database, "a", null, false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = makeCitationMarkerEntry(entry2, database, "b", null, false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = makeCitationMarkerEntry(entry3, database, "c", null, false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a,b,c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).toString()); } // With pageInfo: different entries with identical non-null pageInfo: not joined. // XY [2000a,b,c; p1] whould be confusing. if (true) { List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = makeCitationMarkerEntry(entry1, database, "a", "p1", false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = makeCitationMarkerEntry(entry2, database, "b", "p1", false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = makeCitationMarkerEntry(entry3, database, "c", "p1", false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a; p1" + "; Boström et al., 2006b; p1" + "; Boström et al., 2006c; p1]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).toString()); } // With pageInfo: same entries with identical non-null pageInfo: collapsed. // Note: "same" here looks at the visible parts and citation key only, // but ignores the rest. Normally the citation key should distinguish. if (true) { List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = makeCitationMarkerEntry(entry1, database, "a", "p1", false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = makeCitationMarkerEntry(entry1, database, "a", "p1", false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = makeCitationMarkerEntry(entry1, database, "a", "p1", false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a; p1]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).toString()); } // With pageInfo: same entries with different pageInfo: kept separate. // Empty ("") and missing pageInfos considered equal, thus collapsed. if (true) { List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = makeCitationMarkerEntry(entry1, database, "a", "p1", false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = makeCitationMarkerEntry(entry1, database, "a", "p2", false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = makeCitationMarkerEntry(entry1, database, "a", "", false); citationMarkerEntries.add(cm3); CitationMarkerEntry cm4 = makeCitationMarkerEntry(entry1, database, "a", null, false); citationMarkerEntries.add(cm4); assertEquals("[Boström et al., 2006a; p1" + "; Boström et al., 2006a; p2" + "; Boström et al., 2006a]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).toString()); } } }
42,727
43.741361
302
java
null
jabref-main/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java
package org.jabref.logic.openoffice.style; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationLookupResult; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.PageInfo; import static org.junit.jupiter.api.Assertions.assertEquals; class OOBibStyleTestHelper { /* * Minimal implementation for CitationMarkerNumericEntry */ static class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntry { /* * The number encoding "this entry is unresolved" for the constructor. */ public final static int UNRESOLVED_ENTRY_NUMBER = 0; private final String citationKey; private final Optional<Integer> num; private final Optional<OOText> pageInfo; public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional<OOText> pageInfo) { this.citationKey = citationKey; this.num = num == UNRESOLVED_ENTRY_NUMBER ? Optional.empty() : Optional.of(num); this.pageInfo = PageInfo.normalizePageInfo(pageInfo); } @Override public String getCitationKey() { return citationKey; } @Override public Optional<Integer> getNumber() { return num; } @Override public Optional<OOText> getPageInfo() { return pageInfo; } } static class CitationMarkerNumericBibEntryImpl implements CitationMarkerNumericBibEntry { String key; Optional<Integer> number; public CitationMarkerNumericBibEntryImpl(String key, Optional<Integer> number) { this.key = key; this.number = number; } @Override public String getCitationKey() { return key; } @Override public Optional<Integer> getNumber() { return number; } } static CitationMarkerNumericBibEntry numBibEntry(String key, Optional<Integer> number) { return new CitationMarkerNumericBibEntryImpl(key, number); } /** * Reproduce old method * * @param inList true means label for the bibliography */ static String runGetNumCitationMarker2a(OOBibStyle style, List<Integer> num, int minGroupingCount, boolean inList) { if (inList) { if (num.size() != 1) { throw new IllegalArgumentException("Numeric label for the bibliography with " + num.size() + " numbers?"); } int n = num.get(0); CitationMarkerNumericBibEntryImpl x = new CitationMarkerNumericBibEntryImpl("key", (n == 0) ? Optional.empty() : Optional.of(n)); return style.getNumCitationMarkerForBibliography(x).toString(); } else { List<CitationMarkerNumericEntry> input = num.stream() .map(n -> new CitationMarkerNumericEntryImpl("key" + n, n, Optional.empty())) .collect(Collectors.toList()); return style.getNumCitationMarker2(input, minGroupingCount).toString(); } } /* * Unlike getNumCitationMarker, getNumCitationMarker2 can handle pageInfo. */ static CitationMarkerNumericEntry numEntry(String key, int num, String pageInfoOrNull) { Optional<OOText> pageInfo = Optional.ofNullable(OOText.fromString(pageInfoOrNull)); return new CitationMarkerNumericEntryImpl(key, num, pageInfo); } static String runGetNumCitationMarker2b(OOBibStyle style, int minGroupingCount, CitationMarkerNumericEntry... s) { List<CitationMarkerNumericEntry> input = Stream.of(s).collect(Collectors.toList()); OOText res = style.getNumCitationMarker2(input, minGroupingCount); return res.toString(); } /* * end Helpers for testing style.getNumCitationMarker2 */ /* * begin helper */ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, BibDatabase database, String uniqueLetterQ, String pageInfoQ, boolean isFirstAppearanceOfSource) { if (entry.getCitationKey().isEmpty()) { throw new IllegalArgumentException("entry.getCitationKey() is empty"); } String citationKey = entry.getCitationKey().get(); Citation result = new Citation(citationKey); result.setLookupResult(Optional.of(new CitationLookupResult(entry, database))); result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); Optional<OOText> pageInfo = Optional.ofNullable(OOText.fromString(pageInfoQ)); result.setPageInfo(PageInfo.normalizePageInfo(pageInfo)); result.setIsFirstAppearanceOfSource(isFirstAppearanceOfSource); return result; } /* * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ static String getCitationMarker2ab(OOBibStyle style, List<BibEntry> entries, Map<BibEntry, BibDatabase> entryDBMap, boolean inParenthesis, String[] uniquefiers, Boolean[] isFirstAppearanceOfSource, String[] pageInfo, NonUniqueCitationMarker nonunique) { if (uniquefiers == null) { uniquefiers = new String[entries.size()]; Arrays.fill(uniquefiers, null); } if (pageInfo == null) { pageInfo = new String[entries.size()]; Arrays.fill(pageInfo, null); } if (isFirstAppearanceOfSource == null) { isFirstAppearanceOfSource = new Boolean[entries.size()]; Arrays.fill(isFirstAppearanceOfSource, false); } List<CitationMarkerEntry> citationMarkerEntries = new ArrayList<>(); for (int i = 0; i < entries.size(); i++) { BibEntry entry = entries.get(i); CitationMarkerEntry e = makeCitationMarkerEntry(entry, entryDBMap.get(entry), uniquefiers[i], pageInfo[i], isFirstAppearanceOfSource[i]); citationMarkerEntries.add(e); } return style.createCitationMarker(citationMarkerEntries, inParenthesis, nonunique).toString(); } static String getCitationMarker2(OOBibStyle style, List<BibEntry> entries, Map<BibEntry, BibDatabase> entryDBMap, boolean inParenthesis, String[] uniquefiers, Boolean[] isFirstAppearanceOfSource, String[] pageInfo) { return getCitationMarker2ab(style, entries, entryDBMap, inParenthesis, uniquefiers, isFirstAppearanceOfSource, pageInfo, NonUniqueCitationMarker.THROWS); } static String getCitationMarker2b(OOBibStyle style, List<BibEntry> entries, Map<BibEntry, BibDatabase> entryDBMap, boolean inParenthesis, String[] uniquefiers, Boolean[] isFirstAppearanceOfSource, String[] pageInfo) { return getCitationMarker2ab(style, entries, entryDBMap, inParenthesis, uniquefiers, isFirstAppearanceOfSource, pageInfo, NonUniqueCitationMarker.FORGIVEN); } /* * end helper */ static void testGetNumCitationMarkerExtra(OOBibStyle style) { // Identical numeric entries are joined. assertEquals("[1; 2]", runGetNumCitationMarker2b(style, 3, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x1", 2, null), numEntry("x2", 1, null))); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", runGetNumCitationMarker2b(style, 0, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x1", 2, null), numEntry("x2", 1, null))); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, "p1a"), numEntry("x1", 1, "p1b"), numEntry("x2", 2, "p2"), numEntry("x2", 2, "p2"), numEntry("x3", 3, null), numEntry("x3", 3, null))); // Consecutive numbers can become a range ... assertEquals("[1-3]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x3", 3, null))); // ... unless minGroupingCount is too high assertEquals("[1; 2; 3]", runGetNumCitationMarker2b(style, 4, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x3", 3, null))); // ... or if minGroupingCount <= 0 assertEquals("[1; 2; 3]", runGetNumCitationMarker2b(style, 0, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x3", 3, null))); // ... a pageInfo needs to be emitted assertEquals("[1; p1; 2-3]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, "p1"), numEntry("x2", 2, null), numEntry("x3", 3, null))); // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. assertEquals("[1]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, ""), numEntry("x1", 1, null), numEntry("x1", 1, " "))); // pageInfos are trimmed assertEquals("[1; p1]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, "p1"), numEntry("x1", 1, " p1"), numEntry("x1", 1, "p1 "))); // The citation numbers come out sorted assertEquals("[3-5; 7; 10-12]", runGetNumCitationMarker2b(style, 1, numEntry("x12", 12, null), numEntry("x7", 7, null), numEntry("x3", 3, null), numEntry("x4", 4, null), numEntry("x11", 11, null), numEntry("x10", 10, null), numEntry("x5", 5, null))); // pageInfos are sorted together with the numbers // (but they inhibit ranges where they are, even if they are identical, // but not empty-or-null) assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", runGetNumCitationMarker2b(style, 1, numEntry("x12", 12, "px"), numEntry("x7", 7, "p7"), numEntry("x3", 3, "p3"), numEntry("x4", 4, "p4"), numEntry("x11", 11, "px"), numEntry("x10", 10, "px"), numEntry("x5", 5, "p5"))); // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, ""), numEntry("x1", 1, "b"), numEntry("x1", 1, "a"))); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, "p20"), numEntry("x1", 1, "p9"), numEntry("x1", 1, "p100"))); assertEquals("[1-3]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x3", 3, null))); assertEquals("[1; 2; 3]", runGetNumCitationMarker2b(style, 5, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x3", 3, null))); assertEquals("[1; 2; 3]", runGetNumCitationMarker2b(style, -1, numEntry("x1", 1, null), numEntry("x2", 2, null), numEntry("x3", 3, null))); assertEquals("[1; 3; 12]", runGetNumCitationMarker2b(style, 1, numEntry("x1", 1, null), numEntry("x12", 12, null), numEntry("x3", 3, null))); assertEquals("[3-5; 7; 10-12]", runGetNumCitationMarker2b(style, 1, numEntry("x12", 12, ""), numEntry("x7", 7, ""), numEntry("x3", 3, ""), numEntry("x4", 4, ""), numEntry("x11", 11, ""), numEntry("x10", 10, ""), numEntry("x5", 5, ""))); } }
14,675
39.098361
122
java
null
jabref-main/src/test/java/org/jabref/logic/openoffice/style/OOPreFormatterTest.java
package org.jabref.logic.openoffice.style; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class OOPreFormatterTest { @Test public void testPlainFormat() { assertEquals("aaa", new OOPreFormatter().format("aaa")); assertEquals("$", new OOPreFormatter().format("\\$")); assertEquals("%", new OOPreFormatter().format("\\%")); assertEquals("\\", new OOPreFormatter().format("\\\\")); } @Test public void testFormatAccents() { assertEquals("ä", new OOPreFormatter().format("{\\\"{a}}")); assertEquals("Ä", new OOPreFormatter().format("{\\\"{A}}")); assertEquals("Ç", new OOPreFormatter().format("{\\c{C}}")); } @Test public void testSpecialCommands() { assertEquals("å", new OOPreFormatter().format("{\\aa}")); assertEquals("bb", new OOPreFormatter().format("{\\bb}")); assertEquals("å a", new OOPreFormatter().format("\\aa a")); assertEquals("å a", new OOPreFormatter().format("{\\aa a}")); assertEquals("åÅ", new OOPreFormatter().format("\\aa\\AA")); assertEquals("bb a", new OOPreFormatter().format("\\bb a")); } @Test public void testUnsupportedSpecialCommands() { assertEquals("ftmch", new OOPreFormatter().format("\\ftmch")); assertEquals("ftmch", new OOPreFormatter().format("{\\ftmch}")); assertEquals("ftmchaaa", new OOPreFormatter().format("{\\ftmch\\aaa}")); } @Test public void testEquations() { assertEquals("Σ", new OOPreFormatter().format("$\\Sigma$")); } @Test public void testFormatStripLatexCommands() { assertEquals("-", new OOPreFormatter().format("\\mbox{-}")); } @Test public void testFormatting() { assertEquals("<i>kkk</i>", new OOPreFormatter().format("\\textit{kkk}")); assertEquals("<i>kkk</i>", new OOPreFormatter().format("{\\it kkk}")); assertEquals("<i>kkk</i>", new OOPreFormatter().format("\\emph{kkk}")); assertEquals("<b>kkk</b>", new OOPreFormatter().format("\\textbf{kkk}")); assertEquals("<smallcaps>kkk</smallcaps>", new OOPreFormatter().format("\\textsc{kkk}")); assertEquals("<s>kkk</s>", new OOPreFormatter().format("\\sout{kkk}")); assertEquals("<u>kkk</u>", new OOPreFormatter().format("\\underline{kkk}")); assertEquals("<tt>kkk</tt>", new OOPreFormatter().format("\\texttt{kkk}")); assertEquals("<sup>kkk</sup>", new OOPreFormatter().format("\\textsuperscript{kkk}")); assertEquals("<sub>kkk</sub>", new OOPreFormatter().format("\\textsubscript{kkk}")); } }
2,672
40.123077
97
java
null
jabref-main/src/test/java/org/jabref/logic/openoffice/style/StyleLoaderTest.java
package org.jabref.logic.openoffice.style; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StyleLoaderTest { private static final int NUMBER_OF_INTERNAL_STYLES = 2; private StyleLoader loader; private OpenOfficePreferences preferences; private LayoutFormatterPreferences layoutPreferences; private JournalAbbreviationRepository abbreviationRepository; @BeforeEach public void setUp() { preferences = mock(OpenOfficePreferences.class, Answers.RETURNS_DEEP_STUBS); layoutPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); abbreviationRepository = mock(JournalAbbreviationRepository.class); } @Test public void throwNPEWithNullPreferences() { assertThrows(NullPointerException.class, () -> loader = new StyleLoader(null, layoutPreferences, abbreviationRepository)); } @Test public void throwNPEWithNullLayoutPreferences() { assertThrows(NullPointerException.class, () -> loader = new StyleLoader(mock(OpenOfficePreferences.class), null, abbreviationRepository)); } @Test public void throwNPEWithNullAbbreviationRepository() { assertThrows(NullPointerException.class, () -> loader = new StyleLoader(mock(OpenOfficePreferences.class), layoutPreferences, null)); } @Test public void testGetStylesWithEmptyExternal() { preferences.setExternalStyles(Collections.emptyList()); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); assertEquals(2, loader.getStyles().size()); } @Test public void testAddStyleLeadsToOneMoreStyle() throws URISyntaxException { preferences.setExternalStyles(Collections.emptyList()); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); String filename = Path.of(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); loader.addStyleIfValid(filename); assertEquals(NUMBER_OF_INTERNAL_STYLES + 1, loader.getStyles().size()); } @Test public void testAddInvalidStyleLeadsToNoMoreStyle() { preferences.setExternalStyles(Collections.emptyList()); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); int beforeAdding = loader.getStyles().size(); loader.addStyleIfValid("DefinitelyNotAValidFileNameOrWeAreExtremelyUnlucky"); assertEquals(beforeAdding, loader.getStyles().size()); } @Test public void testInitalizeWithOneExternalFile() throws URISyntaxException { String filename = Path.of(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); when(preferences.getExternalStyles()).thenReturn(FXCollections.singletonObservableList(filename)); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); assertEquals(NUMBER_OF_INTERNAL_STYLES + 1, loader.getStyles().size()); } @Test public void testInitalizeWithIncorrectExternalFile() { preferences.setExternalStyles(Collections.singletonList("DefinitelyNotAValidFileNameOrWeAreExtremelyUnlucky")); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); assertEquals(NUMBER_OF_INTERNAL_STYLES, loader.getStyles().size()); } @Test public void testInitalizeWithOneExternalFileRemoveStyle() throws URISyntaxException { String filename = Path.of(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); when(preferences.getExternalStyles()).thenReturn(FXCollections.singletonObservableList(filename)); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); List<OOBibStyle> toremove = new ArrayList<>(); int beforeRemoving = loader.getStyles().size(); for (OOBibStyle style : loader.getStyles()) { if (!style.isInternalStyle()) { toremove.add(style); } } for (OOBibStyle style : toremove) { assertTrue(loader.removeStyle(style)); } assertEquals(beforeRemoving - 1, loader.getStyles().size()); } @Test public void testInitalizeWithOneExternalFileRemoveStyleUpdatesPreferences() throws URISyntaxException { String filename = Path.of(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); when(preferences.getExternalStyles()).thenReturn(FXCollections.singletonObservableList(filename)); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); List<OOBibStyle> toremove = new ArrayList<>(); for (OOBibStyle style : loader.getStyles()) { if (!style.isInternalStyle()) { toremove.add(style); } } for (OOBibStyle style : toremove) { assertTrue(loader.removeStyle(style)); } // As the prefs are mocked away, the getExternalStyles still returns the initial one assertFalse(preferences.getExternalStyles().isEmpty()); } @Test public void testAddSameStyleTwiceLeadsToOneMoreStyle() throws URISyntaxException { preferences.setExternalStyles(Collections.emptyList()); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); int beforeAdding = loader.getStyles().size(); String filename = Path.of(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); loader.addStyleIfValid(filename); loader.addStyleIfValid(filename); assertEquals(beforeAdding + 1, loader.getStyles().size()); } @Test public void testAddNullStyleThrowsNPE() { loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); assertThrows(NullPointerException.class, () -> loader.addStyleIfValid(null)); } @Test public void testGetDefaultUsedStyleWhenEmpty() { when(preferences.getCurrentStyle()).thenReturn(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH); preferences.clearCurrentStyle(); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); OOBibStyle style = loader.getUsedStyle(); assertTrue(style.isValid()); assertEquals(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, style.getPath()); assertEquals(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, preferences.getCurrentStyle()); } @Test public void testGetStoredUsedStyle() { when(preferences.getCurrentStyle()).thenReturn(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); OOBibStyle style = loader.getUsedStyle(); assertTrue(style.isValid()); assertEquals(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, style.getPath()); assertEquals(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, preferences.getCurrentStyle()); } @Test public void testGetDefaultUsedStyleWhenIncorrect() { when(preferences.getCurrentStyle()).thenReturn("ljlkjlkjnljnvdlsjniuhwelfhuewfhlkuewhfuwhelu"); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); OOBibStyle style = loader.getUsedStyle(); assertTrue(style.isValid()); assertEquals(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, style.getPath()); } @Test public void testRemoveInternalStyleReturnsFalseAndDoNotRemove() { preferences.setExternalStyles(Collections.emptyList()); loader = new StyleLoader(preferences, layoutPreferences, abbreviationRepository); List<OOBibStyle> toremove = new ArrayList<>(); for (OOBibStyle style : loader.getStyles()) { if (style.isInternalStyle()) { toremove.add(style); } } assertFalse(loader.removeStyle(toremove.get(0))); assertEquals(NUMBER_OF_INTERNAL_STYLES, loader.getStyles().size()); } }
9,081
42.663462
146
java
null
jabref-main/src/test/java/org/jabref/logic/pdf/EntryAnnotationImporterTest.java
package org.jabref.logic.pdf; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Map; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.pdf.FileAnnotation; import org.jabref.preferences.FilePreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class EntryAnnotationImporterTest { private final BibDatabaseContext databaseContext = mock(BibDatabaseContext.class); private BibEntry entry; @BeforeEach public void setUp() { entry = new BibEntry(); when(databaseContext.getFileDirectories(any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs/"))); } @Test public void readEntryExampleThesis() { // given entry.setField(StandardField.FILE, ":thesis-example.pdf:PDF"); EntryAnnotationImporter entryAnnotationImporter = new EntryAnnotationImporter(entry); // when Map<Path, List<FileAnnotation>> annotations = entryAnnotationImporter.importAnnotationsFromFiles(databaseContext, mock(FilePreferences.class)); // then int fileCounter = 0; int annotationCounter = 0; for (List<FileAnnotation> annotationsOfFile : annotations.values()) { fileCounter++; annotationCounter += annotationsOfFile.size(); } assertEquals(1, fileCounter); assertEquals(2, annotationCounter); } }
1,759
32.207547
151
java
null
jabref-main/src/test/java/org/jabref/logic/pdf/PdfAnnotationImporterTest.java
package org.jabref.logic.pdf; import java.nio.file.Path; import java.time.LocalDateTime; import java.util.Collections; import java.util.Optional; import org.jabref.model.pdf.FileAnnotation; import org.jabref.model.pdf.FileAnnotationType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class PdfAnnotationImporterTest { private final AnnotationImporter importer = new PdfAnnotationImporter(); @Test public void invalidPath() { assertEquals(Collections.emptyList(), importer.importAnnotations(Path.of("/asdf/does/not/exist.pdf"))); } @Test public void invalidDirectory() { assertEquals(Collections.emptyList(), importer.importAnnotations(Path.of("src/test/resources/pdfs"))); } @Test public void invalidDocumentType() { assertEquals(Collections.emptyList(), importer.importAnnotations(Path.of("src/test/resources/pdfs/write-protected.docx"))); } @Test public void noAnnotationsWriteProtected() { assertEquals(Collections.emptyList(), importer.importAnnotations(Path.of("src/test/resources/pdfs/write-protected.pdf"))); } @Test public void noAnnotationsEncrypted() { assertEquals(Collections.emptyList(), importer.importAnnotations(Path.of("src/test/resources/pdfs/encrypted.pdf"))); } @Test public void twoAnnotationsThesisExample() { assertEquals(2, importer.importAnnotations(Path.of("src/test/resources/pdfs/thesis-example.pdf")).size()); } @Test public void noAnnotationsMinimal() { assertEquals(Collections.emptyList(), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal.pdf"))); } @Test public void inlineNoteMinimal() { final FileAnnotation expected = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 25), 1, "inline note annotation", FileAnnotationType.FREETEXT, Optional.empty()); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-inlinenote.pdf"))); } @Test public void popupNoteMinimal() { final FileAnnotation expected = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 17, 24), 1, "A simple pop-up note", FileAnnotationType.TEXT, Optional.empty()); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-popup.pdf"))); } @Test public void highlightMinimalFoxit() { final FileAnnotation expectedLinkedAnnotation = new FileAnnotation("lynyus", LocalDateTime.of(2017, 5, 31, 15, 16, 1), 1, "this is a foxit highlight", FileAnnotationType.HIGHLIGHT, Optional.empty()); final FileAnnotation expected = new FileAnnotation("lynyus", LocalDateTime.of(2017, 5, 31, 15, 16, 1), 1, "Hello", FileAnnotationType.HIGHLIGHT, Optional.of(expectedLinkedAnnotation)); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-foxithighlight.pdf"))); } @Test public void highlightNoNoteMinimal() { final FileAnnotation expectedLinkedAnnotation = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 28, 39), 1, "", FileAnnotationType.HIGHLIGHT, Optional.empty()); final FileAnnotation expected = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 28, 39), 1, "World", FileAnnotationType.HIGHLIGHT, Optional.of(expectedLinkedAnnotation)); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-highlight-no-note.pdf"))); } @Test public void squigglyWithNoteMinimal() { final FileAnnotation expectedLinkedAnnotation = new FileAnnotation("lynyus", LocalDateTime.of(2017, 6, 1, 2, 40, 25), 1, "Squiggly note", FileAnnotationType.SQUIGGLY, Optional.empty()); final FileAnnotation expected = new FileAnnotation("lynyus", LocalDateTime.of(2017, 6, 1, 2, 40, 25), 1, "ello", FileAnnotationType.SQUIGGLY, Optional.of(expectedLinkedAnnotation)); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-squiggly.pdf"))); } @Test public void strikeoutWithNoteMinimal() { final FileAnnotation expectedLinkedAnnotation = new FileAnnotation("lynyus", LocalDateTime.of(2017, 6, 1, 13, 2, 3), 1, "striked out", FileAnnotationType.STRIKEOUT, Optional.empty()); final FileAnnotation expected = new FileAnnotation("lynyus", LocalDateTime.of(2017, 6, 1, 13, 2, 3), 1, "World", FileAnnotationType.STRIKEOUT, Optional.of(expectedLinkedAnnotation)); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-strikeout.pdf"))); } @Test public void highlightWithNoteMinimal() { final FileAnnotation expectedLinkedAnnotation = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 32, 2), 1, "linked note to highlight", FileAnnotationType.HIGHLIGHT, Optional.empty()); final FileAnnotation expected = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 32, 2), 1, "World", FileAnnotationType.HIGHLIGHT, Optional.of(expectedLinkedAnnotation)); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-highlight-with-note.pdf"))); } @Test public void underlineWithNoteMinimal() { final FileAnnotation expectedLinkedAnnotation = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 36, 9), 1, "underlined", FileAnnotationType.UNDERLINE, Optional.empty()); final FileAnnotation expected = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 12, 20, 36, 9), 1, "Hello", FileAnnotationType.UNDERLINE, Optional.of(expectedLinkedAnnotation)); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-underline.pdf"))); } @Test public void polygonNoNoteMinimal() { final FileAnnotation expected = new FileAnnotation("Linus Dietz", LocalDateTime.of(2017, 3, 16, 9, 21, 1), 1, "polygon annotation", FileAnnotationType.POLYGON, Optional.empty()); assertEquals(Collections.singletonList(expected), importer.importAnnotations(Path.of("src/test/resources/pdfs/minimal-polygon.pdf"))); } }
6,892
45.891156
135
java
null
jabref-main/src/test/java/org/jabref/logic/pdf/search/indexing/DocumentReaderTest.java
package org.jabref.logic.pdf.search.indexing; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.FilePreferences; import org.apache.lucene.document.Document; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DocumentReaderTest { private BibDatabaseContext databaseContext; private FilePreferences filePreferences; @BeforeEach public void setup() { this.databaseContext = mock(BibDatabaseContext.class); when(databaseContext.getFileDirectories(Mockito.any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs"))); this.filePreferences = mock(FilePreferences.class); when(filePreferences.getUserAndHost()).thenReturn("testuser-testhost"); when(filePreferences.getMainFileDirectory()).thenReturn(Optional.empty()); when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(true); } @Test public void unknownFileTestShouldReturnEmptyList() { // given BibEntry entry = new BibEntry(); entry.setFiles(Collections.singletonList(new LinkedFile("Wrong path", "NOT_PRESENT.pdf", "Type"))); // when final List<Document> emptyDocumentList = new DocumentReader(entry, filePreferences).readLinkedPdfs(databaseContext); // then assertEquals(Collections.emptyList(), emptyDocumentList); } private static Stream<Arguments> getLinesToMerge() { return Stream.of( Arguments.of("Sentences end with periods.", "Sentences end\nwith periods."), Arguments.of("Text is usually wrapped with hyphens.", "Text is us-\nually wrapp-\ned with hyphens."), Arguments.of("Longer texts often have both.", "Longer te-\nxts often\nhave both."), Arguments.of("No lines to break here", "No lines to break here") ); } @ParameterizedTest @MethodSource("getLinesToMerge") public void mergeLinesTest(String expected, String linesToMerge) { String result = DocumentReader.mergeLines(linesToMerge); assertEquals(expected, result); } }
2,708
37.7
138
java
null
jabref-main/src/test/java/org/jabref/logic/pdf/search/indexing/PdfIndexerTest.java
package org.jabref.logic.pdf.search.indexing; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.Optional; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.preferences.FilePreferences; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.store.NIOFSDirectory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PdfIndexerTest { private PdfIndexer indexer; private BibDatabase database; private BibDatabaseContext context = mock(BibDatabaseContext.class); @BeforeEach public void setUp(@TempDir Path indexDir) throws IOException { FilePreferences filePreferences = mock(FilePreferences.class); this.database = new BibDatabase(); this.context = mock(BibDatabaseContext.class); when(context.getDatabasePath()).thenReturn(Optional.of(Path.of("src/test/resources/pdfs/"))); when(context.getFileDirectories(Mockito.any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs"))); when(context.getFulltextIndexPath()).thenReturn(indexDir); when(context.getDatabase()).thenReturn(database); when(context.getEntries()).thenReturn(database.getEntries()); this.indexer = PdfIndexer.of(context, filePreferences); } @Test public void exampleThesisIndex() throws IOException { // given BibEntry entry = new BibEntry(StandardEntryType.PhdThesis); entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName()))); database.insertEntry(entry); // when indexer.createIndex(); indexer.addToIndex(context); // then try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(33, reader.numDocs()); } } @Test public void dontIndexNonPdf() throws IOException { // given BibEntry entry = new BibEntry(StandardEntryType.PhdThesis); entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.AUX.getName()))); database.insertEntry(entry); // when indexer.createIndex(); indexer.addToIndex(context); // then try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(0, reader.numDocs()); } } @Test public void dontIndexOnlineLinks() throws IOException { // given BibEntry entry = new BibEntry(StandardEntryType.PhdThesis); entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "https://raw.githubusercontent.com/JabRef/jabref/main/src/test/resources/pdfs/thesis-example.pdf", StandardFileType.PDF.getName()))); database.insertEntry(entry); // when indexer.createIndex(); indexer.addToIndex(context); // then try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(0, reader.numDocs()); } } @Test public void exampleThesisIndexWithKey() throws IOException { // given BibEntry entry = new BibEntry(StandardEntryType.PhdThesis); entry.setCitationKey("Example2017"); entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName()))); database.insertEntry(entry); // when indexer.createIndex(); indexer.addToIndex(context); // then try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(33, reader.numDocs()); } } @Test public void metaDataIndex() throws IOException { // given BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "metaData.pdf", StandardFileType.PDF.getName()))); database.insertEntry(entry); // when indexer.createIndex(); indexer.addToIndex(context); // then try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(1, reader.numDocs()); } } @Test public void testFlushIndex() throws IOException { // given BibEntry entry = new BibEntry(StandardEntryType.PhdThesis); entry.setCitationKey("Example2017"); entry.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName()))); database.insertEntry(entry); indexer.createIndex(); indexer.addToIndex(context); // index actually exists try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(33, reader.numDocs()); } // when indexer.flushIndex(); // then try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(0, reader.numDocs()); } } @Test public void exampleThesisIndexAppendMetaData() throws IOException { // given BibEntry exampleThesis = new BibEntry(StandardEntryType.PhdThesis); exampleThesis.setCitationKey("ExampleThesis2017"); exampleThesis.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName()))); database.insertEntry(exampleThesis); indexer.createIndex(); indexer.addToIndex(context); // index with first entry try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(33, reader.numDocs()); } BibEntry metadata = new BibEntry(StandardEntryType.Article); metadata.setCitationKey("MetaData2017"); metadata.setFiles(Collections.singletonList(new LinkedFile("Metadata file", "metaData.pdf", StandardFileType.PDF.getName()))); // when indexer.addToIndex(metadata, null); // then try (IndexReader reader = DirectoryReader.open(new NIOFSDirectory(context.getFulltextIndexPath()))) { assertEquals(34, reader.numDocs()); } } }
7,068
36.601064
215
java
null
jabref-main/src/test/java/org/jabref/logic/pdf/search/retrieval/PdfSearcherTest.java
package org.jabref.logic.pdf.search.retrieval; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import org.jabref.logic.pdf.search.indexing.PdfIndexer; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.pdf.search.PdfSearchResults; import org.jabref.preferences.FilePreferences; import org.apache.lucene.queryparser.classic.ParseException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PdfSearcherTest { private PdfSearcher search; @BeforeEach public void setUp(@TempDir Path indexDir) throws IOException { FilePreferences filePreferences = mock(FilePreferences.class); // given BibDatabase database = new BibDatabase(); BibDatabaseContext context = mock(BibDatabaseContext.class); when(context.getFileDirectories(Mockito.any())).thenReturn(Collections.singletonList(Path.of("src/test/resources/pdfs"))); when(context.getFulltextIndexPath()).thenReturn(indexDir); when(context.getDatabase()).thenReturn(database); when(context.getEntries()).thenReturn(database.getEntries()); BibEntry examplePdf = new BibEntry(StandardEntryType.Article); examplePdf.setFiles(Collections.singletonList(new LinkedFile("Example Entry", "example.pdf", StandardFileType.PDF.getName()))); database.insertEntry(examplePdf); BibEntry metaDataEntry = new BibEntry(StandardEntryType.Article); metaDataEntry.setFiles(Collections.singletonList(new LinkedFile("Metadata Entry", "metaData.pdf", StandardFileType.PDF.getName()))); metaDataEntry.setCitationKey("MetaData2017"); database.insertEntry(metaDataEntry); BibEntry exampleThesis = new BibEntry(StandardEntryType.PhdThesis); exampleThesis.setFiles(Collections.singletonList(new LinkedFile("Example Thesis", "thesis-example.pdf", StandardFileType.PDF.getName()))); exampleThesis.setCitationKey("ExampleThesis"); database.insertEntry(exampleThesis); PdfIndexer indexer = PdfIndexer.of(context, filePreferences); search = PdfSearcher.of(context); indexer.createIndex(); indexer.addToIndex(context); } @Test public void searchForTest() throws IOException, ParseException { PdfSearchResults result = search.search("test", 10); assertEquals(8, result.numSearchResults()); } @Test public void searchForUniversity() throws IOException, ParseException { PdfSearchResults result = search.search("University", 10); assertEquals(1, result.numSearchResults()); } @Test public void searchForStopWord() throws IOException, ParseException { PdfSearchResults result = search.search("and", 10); assertEquals(0, result.numSearchResults()); } @Test public void searchForSecond() throws IOException, ParseException { PdfSearchResults result = search.search("second", 10); assertEquals(4, result.numSearchResults()); } @Test public void searchForAnnotation() throws IOException, ParseException { PdfSearchResults result = search.search("annotation", 10); assertEquals(2, result.numSearchResults()); } @Test public void searchForEmptyString() throws IOException { PdfSearchResults result = search.search("", 10); assertEquals(0, result.numSearchResults()); } @Test public void searchWithNullString() throws IOException { assertThrows(NullPointerException.class, () -> search.search(null, 10)); } @Test public void searchForZeroResults() throws IOException { assertThrows(IllegalArgumentException.class, () -> search.search("test", 0)); } }
4,276
38.238532
146
java
null
jabref-main/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsListTest.java
package org.jabref.logic.protectedterms; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class ProtectedTermsListTest { private ProtectedTermsList internalList; private ProtectedTermsList externalList; @BeforeEach public void setUp(@TempDir Path temporaryFolder) throws IOException { Path path = temporaryFolder.resolve("ThisIsARandomlyNamedFile"); Files.createFile(path); String tempFileName = path.toString(); internalList = new ProtectedTermsList("Name", new ArrayList<>(Arrays.asList("AAA", "BBB")), "location", true); externalList = new ProtectedTermsList("Namely", new ArrayList<>(Arrays.asList("AAA", "BBB")), tempFileName); } @Test public void testProtectedTermsListStringListOfStringStringBoolean() { assertTrue(internalList.isInternalList()); } @Test public void testProtectedTermsListStringListOfStringString() { assertFalse(externalList.isInternalList()); } @Test public void testGetDescription() { assertEquals("Name", internalList.getDescription()); } @Test public void testGetTermList() { assertEquals(Arrays.asList("AAA", "BBB"), internalList.getTermList()); } @Test public void testGetLocation() { assertEquals("location", internalList.getLocation()); } @Test public void testGetTermListing() { assertEquals("AAA\nBBB", internalList.getTermListing()); } @Test public void testCompareTo() { assertEquals(-2, internalList.compareTo(externalList)); } @Test public void testSetEnabledIsEnabled() { assertFalse(internalList.isEnabled()); internalList.setEnabled(true); assertTrue(internalList.isEnabled()); } @Test public void testNotEnabledByDefault() { assertFalse(internalList.isEnabled()); } @Test public void testCanNotAddTermToInternalList() { assertFalse(internalList.addProtectedTerm("CCC")); } @Test public void testTermNotAddedToInternalList() { internalList.addProtectedTerm("CCC"); assertFalse(internalList.getTermList().contains("CCC")); } @Test public void testCanAddTermToExternalList() { assertTrue(externalList.addProtectedTerm("CCC")); } @Test public void testTermAddedToExternalList() { externalList.addProtectedTerm("CCC"); assertTrue(externalList.getTermList().contains("CCC")); } }
2,880
27.524752
118
java
null
jabref-main/src/test/java/org/jabref/logic/protectedterms/ProtectedTermsLoaderTest.java
package org.jabref.logic.protectedterms; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jabref.logic.l10n.Localization; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class ProtectedTermsLoaderTest { private ProtectedTermsLoader loader; @BeforeEach void setUp() { loader = new ProtectedTermsLoader(new ProtectedTermsPreferences(ProtectedTermsLoader.getInternalLists(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); } @Test void testGetProtectedTerms() throws URISyntaxException { List<ProtectedTermsList> backupList = new ArrayList<>(loader.getProtectedTermsLists()); for (ProtectedTermsList list : backupList) { loader.removeProtectedTermsList(list); } assertTrue(loader.getProtectedTermsLists().isEmpty()); String filename = Path.of(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") .toURI()) .toFile().getPath(); loader.addProtectedTermsListFromFile(filename, true); assertEquals(List.of("Einstein"), loader.getProtectedTerms()); } @Test void testAddProtectedTermsListFromFile() throws URISyntaxException { String filename = Path.of(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") .toURI()) .toFile().getPath(); assertEquals(ProtectedTermsLoader.getInternalLists().size(), loader.getProtectedTermsLists().size()); loader.addProtectedTermsListFromFile(filename, false); assertEquals(ProtectedTermsLoader.getInternalLists().size() + 1, loader.getProtectedTermsLists().size()); } @Test void testReadProtectedTermsListFromFileReadsDescription() throws URISyntaxException { Path file = Path.of( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") .toURI()); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertEquals("Term list", list.getDescription()); } @Test void testReadProtectedTermsListFromFileDisabledWorks() throws URISyntaxException { Path file = Path.of(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") .toURI()); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, false); assertFalse(list.isEnabled()); } @Test void testReadProtectedTermsListFromFileEnabledWorks() throws URISyntaxException { Path file = Path.of(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") .toURI()); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertTrue(list.isEnabled()); } @Test void testReadProtectedTermsListFromFileIsNotInternalList() throws URISyntaxException { Path file = Path.of(ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/namedterms.terms") .toURI()); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertFalse(list.isInternalList()); } @Test void testReadProtectedTermsListFromFileNoDescriptionGivesDefaultDescription() throws URISyntaxException { Path file = Path.of( ProtectedTermsLoader.class.getResource("/org/jabref/logic/protectedterms/unnamedterms.terms") .toURI()); ProtectedTermsList list = ProtectedTermsLoader.readProtectedTermsListFromFile(file, true); assertEquals(Localization.lang("The text after the last line starting with # will be used"), list.getDescription()); } @Test void testNewListsAreIncluded() { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); assertEquals(ProtectedTermsLoader.getInternalLists().size(), localLoader.getProtectedTermsLists().size()); } @Test void testNewListsAreEnabled() { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); for (ProtectedTermsList list : localLoader.getProtectedTermsLists()) { assertTrue(list.isEnabled()); } } @Test void testInitalizedAllInternalDisabled() { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); for (ProtectedTermsList list : localLoader.getProtectedTermsLists()) { assertFalse(list.isEnabled()); } } @Test void testUnknownExternalFileWillNotLoad() { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( ProtectedTermsLoader.getInternalLists(), Collections.singletonList("someUnlikelyNameThatNeverWillExist"), Collections.emptyList(), Collections.emptyList())); assertEquals(ProtectedTermsLoader.getInternalLists().size(), localLoader.getProtectedTermsLists().size()); } @Test void testAllDisabledNoWords() { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); assertEquals(Collections.emptyList(), localLoader.getProtectedTerms()); } @Test void testDoNotLoadTheSameInternalListTwice() { ProtectedTermsLoader localLoader = new ProtectedTermsLoader( new ProtectedTermsPreferences( ProtectedTermsLoader.getInternalLists(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); assertEquals(ProtectedTermsLoader.getInternalLists().size(), localLoader.getProtectedTermsLists().size()); } @Test void testAddNewTermListAddsList(@TempDir Path tempDir) { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); localLoader.addNewProtectedTermsList("My new list", tempDir.resolve("MyNewList.terms").toAbsolutePath().toString()); assertEquals(ProtectedTermsLoader.getInternalLists().size() + 1, localLoader.getProtectedTermsLists().size()); } @Test void testAddNewTermListNewListInList(@TempDir Path tempDir) { ProtectedTermsLoader localLoader = new ProtectedTermsLoader( new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); ProtectedTermsList newList = localLoader.addNewProtectedTermsList("My new list", tempDir.resolve("MyNewList.terms") .toAbsolutePath() .toString()); assertTrue(localLoader.getProtectedTermsLists().contains(newList)); } @Test void testRemoveTermList(@TempDir Path tempDir) { ProtectedTermsLoader localLoader = new ProtectedTermsLoader( new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); ProtectedTermsList newList = localLoader.addNewProtectedTermsList("My new list", tempDir.resolve("MyNewList.terms").toAbsolutePath().toString()); assertTrue(localLoader.removeProtectedTermsList(newList)); } @Test void testRemoveTermListReduceTheCount(@TempDir Path tempDir) { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); ProtectedTermsList newList = localLoader.addNewProtectedTermsList("My new list", tempDir.resolve("MyNewList.terms").toAbsolutePath().toString()); localLoader.removeProtectedTermsList(newList); assertEquals(ProtectedTermsLoader.getInternalLists().size(), localLoader.getProtectedTermsLists().size()); } @Test void testAddNewTermListSetsCorrectDescription(@TempDir Path tempDir) { ProtectedTermsLoader localLoader = new ProtectedTermsLoader(new ProtectedTermsPreferences( Collections.emptyList(), Collections.emptyList(), ProtectedTermsLoader.getInternalLists(), Collections.emptyList())); ProtectedTermsList newList = localLoader.addNewProtectedTermsList("My new list", tempDir.resolve("MyNewList.terms").toAbsolutePath().toString()); assertEquals("My new list", newList.getDescription()); } }
10,673
46.022026
153
java
null
jabref-main/src/test/java/org/jabref/logic/remote/RemoteCommunicationTest.java
package org.jabref.logic.remote; import java.io.IOException; import org.jabref.logic.remote.client.RemoteClient; import org.jabref.logic.remote.server.RemoteListenerServerManager; import org.jabref.logic.remote.server.RemoteMessageHandler; import org.jabref.support.DisabledOnCIServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for the case where the client and server are set-up correctly. Testing the exceptional cases happens in {@link * RemoteSetupTest}. */ @DisabledOnCIServer("Tests fails sporadically on CI server") class RemoteCommunicationTest { private RemoteClient client; private RemoteListenerServerManager serverLifeCycle; private RemoteMessageHandler server; @BeforeEach void setUp() { final int port = 34567; server = mock(RemoteMessageHandler.class); serverLifeCycle = new RemoteListenerServerManager(); serverLifeCycle.openAndStart(server, port); client = new RemoteClient(port); } @AfterEach void tearDown() { serverLifeCycle.close(); } @Test void pingReturnsTrue() throws IOException, InterruptedException { assertTrue(client.ping()); } @Test void commandLineArgumentSinglePassedToServer() { final String[] message = new String[]{"my message"}; client.sendCommandLineArguments(message); verify(server).handleCommandLineArguments(message); } @Test void commandLineArgumentTwoPassedToServer() { final String[] message = new String[]{"my message", "second"}; client.sendCommandLineArguments(message); verify(server).handleCommandLineArguments(message); } @Test void commandLineArgumentMultiLinePassedToServer() { final String[] message = new String[]{"my message\n second line", "second \r and third"}; client.sendCommandLineArguments(message); verify(server).handleCommandLineArguments(message); } @Test void commandLineArgumentEncodingAndDecoding() { final String[] message = new String[]{"D:\\T EST\\测试te st.bib"}; // will be encoded as "D%3A%5CT+EST%5C%E6%B5%8B%E8%AF%95te+st.bib" client.sendCommandLineArguments(message); verify(server).handleCommandLineArguments(message); } }
2,509
27.850575
119
java
null
jabref-main/src/test/java/org/jabref/logic/remote/RemotePreferencesTest.java
package org.jabref.logic.remote; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class RemotePreferencesTest { private RemotePreferences preferences; @BeforeEach public void setUp() { preferences = new RemotePreferences(1000, true); } @Test public void testGetPort() { assertEquals(1000, preferences.getPort()); } @Test public void testSetPort() { preferences.setPort(2000); assertEquals(2000, preferences.getPort()); } @Test public void testUseRemoteServer() { assertTrue(preferences.useRemoteServer()); } @Test public void testSetUseRemoteServer() { preferences.setUseRemoteServer(false); assertFalse(preferences.useRemoteServer()); } @Test public void testIsDifferentPortTrue() { assertTrue(preferences.isDifferentPort(2000)); } @Test public void testIsDifferentPortFalse() { assertFalse(preferences.isDifferentPort(1000)); } }
1,217
22.882353
60
java
null
jabref-main/src/test/java/org/jabref/logic/remote/RemoteSetupTest.java
package org.jabref.logic.remote; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import org.jabref.logic.remote.client.RemoteClient; import org.jabref.logic.remote.server.RemoteListenerServerManager; import org.jabref.logic.remote.server.RemoteMessageHandler; import org.jabref.logic.util.OS; import org.jabref.support.DisabledOnCIServer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @DisabledOnCIServer("Tests fails sporadically on CI server") class RemoteSetupTest { private RemoteMessageHandler messageHandler; @BeforeEach void setUp() { messageHandler = mock(RemoteMessageHandler.class); } @Test void testGoodCase() { final int port = 34567; final String[] message = new String[]{"MYMESSAGE"}; try (RemoteListenerServerManager server = new RemoteListenerServerManager()) { assertFalse(server.isOpen()); server.openAndStart(messageHandler, port); assertTrue(server.isOpen()); assertTrue(new RemoteClient(port).sendCommandLineArguments(message)); verify(messageHandler).handleCommandLineArguments(message); server.stop(); assertFalse(server.isOpen()); } } @Test void testGoodCaseWithAllLifecycleMethods() { final int port = 34567; final String[] message = new String[]{"MYMESSAGE"}; try (RemoteListenerServerManager server = new RemoteListenerServerManager()) { assertFalse(server.isOpen()); assertTrue(server.isNotStartedBefore()); server.stop(); assertFalse(server.isOpen()); assertTrue(server.isNotStartedBefore()); server.open(messageHandler, port); assertTrue(server.isOpen()); assertTrue(server.isNotStartedBefore()); server.start(); assertTrue(server.isOpen()); assertFalse(server.isNotStartedBefore()); assertTrue(new RemoteClient(port).sendCommandLineArguments(message)); verify(messageHandler).handleCommandLineArguments(message); server.stop(); assertFalse(server.isOpen()); assertTrue(server.isNotStartedBefore()); } } @Test void testPortAlreadyInUse() throws IOException { assumeFalse(OS.OS_X); final int port = 34567; try (ServerSocket socket = new ServerSocket(port)) { assertTrue(socket.isBound()); try (RemoteListenerServerManager server = new RemoteListenerServerManager()) { assertFalse(server.isOpen()); server.openAndStart(messageHandler, port); assertFalse(server.isOpen()); verify(messageHandler, never()).handleCommandLineArguments(any()); } } } @Test void testClientTimeout() { final int port = 34567; final String message = "MYMESSAGE"; assertFalse(new RemoteClient(port).sendCommandLineArguments(new String[]{message})); } @Test void pingReturnsFalseForWrongServerListening() throws IOException, InterruptedException { final int port = 34567; try (ServerSocket socket = new ServerSocket(port)) { // Setup dummy server always answering "whatever" new Thread(() -> { try (Socket message = socket.accept(); OutputStream os = message.getOutputStream()) { os.write("whatever".getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { // Ignored } }).start(); Thread.sleep(100); assertFalse(new RemoteClient(port).ping()); } } @Test void pingReturnsFalseForNoServerListening() throws IOException, InterruptedException { final int port = 34567; assertFalse(new RemoteClient(port).ping()); } @Test void pingReturnsTrueWhenServerIsRunning() { final int port = 34567; try (RemoteListenerServerManager server = new RemoteListenerServerManager()) { server.openAndStart(messageHandler, port); assertTrue(new RemoteClient(port).ping()); } } }
4,714
32.439716
101
java
null
jabref-main/src/test/java/org/jabref/logic/remote/RemoteUtilTest.java
package org.jabref.logic.remote; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class RemoteUtilTest { @Test public void rejectPortNumberBelowZero() { assertFalse(RemoteUtil.isUserPort(-55), "Port number must be non negative."); } @Test public void rejectReservedSystemPorts() { assertFalse(RemoteUtil.isUserPort(0), "Port number must be outside reserved system range (0-1023)."); assertFalse(RemoteUtil.isUserPort(1023), "Port number must be outside reserved system range (0-1023)."); } @Test public void rejectPortsAbove16Bits() { // 2 ^ 16 - 1 => 65535 assertFalse(RemoteUtil.isUserPort(65536), "Port number should be below 65535."); } @Test public void acceptPortsAboveSystemPorts() { // ports 1024 -> 65535 assertTrue(RemoteUtil.isUserPort(1024), "Port number in between 1024 and 65535 should be valid."); assertTrue(RemoteUtil.isUserPort(65535), "Port number in between 1024 and 65535 should be valid."); } }
1,148
32.794118
112
java
null
jabref-main/src/test/java/org/jabref/logic/search/DatabaseSearcherTest.java
package org.jabref.logic.search; import java.util.Collections; import java.util.EnumSet; import java.util.List; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.search.rules.SearchRules; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class DatabaseSearcherTest { public static final SearchQuery INVALID_SEARCH_QUERY = new SearchQuery("\\asd123{}asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); private BibDatabase database; @BeforeEach public void setUp() { database = new BibDatabase(); } @Test public void testNoMatchesFromEmptyDatabase() { List<BibEntry> matches = new DatabaseSearcher(new SearchQuery("whatever", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches(); assertEquals(Collections.emptyList(), matches); } @Test public void testNoMatchesFromEmptyDatabaseWithInvalidSearchExpression() { List<BibEntry> matches = new DatabaseSearcher(INVALID_SEARCH_QUERY, database).getMatches(); assertEquals(Collections.emptyList(), matches); } @Test public void testGetDatabaseFromMatchesDatabaseWithEmptyEntries() { database.insertEntry(new BibEntry()); List<BibEntry> matches = new DatabaseSearcher(new SearchQuery("whatever", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches(); assertEquals(Collections.emptyList(), matches); } @Test public void testNoMatchesFromDatabaseWithArticleTypeEntry() { BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "harrer"); database.insertEntry(entry); List<BibEntry> matches = new DatabaseSearcher(new SearchQuery("whatever", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches(); assertEquals(Collections.emptyList(), matches); } @Test public void testCorrectMatchFromDatabaseWithArticleTypeEntry() { BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "harrer"); database.insertEntry(entry); List<BibEntry> matches = new DatabaseSearcher(new SearchQuery("harrer", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)), database).getMatches(); assertEquals(Collections.singletonList(entry), matches); } @Test public void testNoMatchesFromEmptyDatabaseWithInvalidQuery() { SearchQuery query = new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database); assertEquals(Collections.emptyList(), databaseSearcher.getMatches()); } @Test public void testCorrectMatchFromDatabaseWithIncollectionTypeEntry() { BibEntry entry = new BibEntry(StandardEntryType.InCollection); entry.setField(StandardField.AUTHOR, "tonho"); database.insertEntry(entry); SearchQuery query = new SearchQuery("tonho", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); List<BibEntry> matches = new DatabaseSearcher(query, database).getMatches(); assertEquals(Collections.singletonList(entry), matches); } @Test public void testNoMatchesFromDatabaseWithTwoEntries() { BibEntry entry = new BibEntry(); database.insertEntry(entry); entry = new BibEntry(StandardEntryType.InCollection); entry.setField(StandardField.AUTHOR, "tonho"); database.insertEntry(entry); SearchQuery query = new SearchQuery("tonho", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database); assertEquals(Collections.singletonList(entry), databaseSearcher.getMatches()); } @Test public void testNoMatchesFromDabaseWithIncollectionTypeEntry() { BibEntry entry = new BibEntry(StandardEntryType.InCollection); entry.setField(StandardField.AUTHOR, "tonho"); database.insertEntry(entry); SearchQuery query = new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database); assertEquals(Collections.emptyList(), databaseSearcher.getMatches()); } @Test public void testNoMatchFromDatabaseWithEmptyEntry() { BibEntry entry = new BibEntry(); database.insertEntry(entry); SearchQuery query = new SearchQuery("tonho", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); DatabaseSearcher databaseSearcher = new DatabaseSearcher(query, database); assertEquals(Collections.emptyList(), databaseSearcher.getMatches()); } }
5,442
42.544
202
java
null
jabref-main/src/test/java/org/jabref/logic/search/SearchQueryTest.java
package org.jabref.logic.search; import java.util.EnumSet; import java.util.Optional; import java.util.regex.Pattern; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.search.rules.SearchRules; import org.jabref.model.search.rules.SearchRules.SearchFlags; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class SearchQueryTest { @Test public void testToString() { assertEquals("\"asdf\" (case sensitive, regular expression)", new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).toString()); assertEquals("\"asdf\" (case insensitive, plain text)", new SearchQuery("asdf", EnumSet.noneOf(SearchFlags.class)).toString()); } @Test public void testIsContainsBasedSearch() { assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isContainsBasedSearch()); assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isContainsBasedSearch()); assertFalse(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isContainsBasedSearch()); } @Test public void testIsGrammarBasedSearch() { assertFalse(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isGrammarBasedSearch()); assertFalse(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isGrammarBasedSearch()); assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isGrammarBasedSearch()); } @Test public void testGrammarSearch() { BibEntry entry = new BibEntry(); entry.addKeyword("one two", ','); SearchQuery searchQuery = new SearchQuery("keywords=\"one two\"", EnumSet.noneOf(SearchFlags.class)); assertTrue(searchQuery.isMatch(entry)); } @Test public void testGrammarSearchFullEntryLastCharMissing() { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "systematic revie"); SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", EnumSet.noneOf(SearchFlags.class)); assertFalse(searchQuery.isMatch(entry)); } @Test public void testGrammarSearchFullEntry() { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "systematic review"); SearchQuery searchQuery = new SearchQuery("title=\"systematic review\"", EnumSet.noneOf(SearchFlags.class)); assertTrue(searchQuery.isMatch(entry)); } @Test public void testSearchingForOpenBraketInBooktitle() { BibEntry e = new BibEntry(StandardEntryType.InProceedings); e.setField(StandardField.BOOKTITLE, "Super Conference (SC)"); SearchQuery searchQuery = new SearchQuery("booktitle=\"(\"", EnumSet.noneOf(SearchFlags.class)); assertTrue(searchQuery.isMatch(e)); } @Test public void testSearchMatchesSingleKeywordNotPart() { BibEntry e = new BibEntry(StandardEntryType.InProceedings); e.setField(StandardField.KEYWORDS, "banana, pineapple, orange"); SearchQuery searchQuery = new SearchQuery("anykeyword==apple", EnumSet.noneOf(SearchFlags.class)); assertFalse(searchQuery.isMatch(e)); } @Test public void testSearchMatchesSingleKeyword() { BibEntry e = new BibEntry(StandardEntryType.InProceedings); e.setField(StandardField.KEYWORDS, "banana, pineapple, orange"); SearchQuery searchQuery = new SearchQuery("anykeyword==pineapple", EnumSet.noneOf(SearchFlags.class)); assertTrue(searchQuery.isMatch(e)); } @Test public void testSearchAllFields() { BibEntry e = new BibEntry(StandardEntryType.InProceedings); e.setField(StandardField.TITLE, "Fruity features"); e.setField(StandardField.KEYWORDS, "banana, pineapple, orange"); SearchQuery searchQuery = new SearchQuery("anyfield==\"fruity features\"", EnumSet.noneOf(SearchFlags.class)); assertTrue(searchQuery.isMatch(e)); } @Test public void testSearchAllFieldsNotForSpecificField() { BibEntry e = new BibEntry(StandardEntryType.InProceedings); e.setField(StandardField.TITLE, "Fruity features"); e.setField(StandardField.KEYWORDS, "banana, pineapple, orange"); SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords!=banana", EnumSet.noneOf(SearchFlags.class)); assertFalse(searchQuery.isMatch(e)); } @Test public void testSearchAllFieldsAndSpecificField() { BibEntry e = new BibEntry(StandardEntryType.InProceedings); e.setField(StandardField.TITLE, "Fruity features"); e.setField(StandardField.KEYWORDS, "banana, pineapple, orange"); SearchQuery searchQuery = new SearchQuery("anyfield=fruit and keywords=apple", EnumSet.noneOf(SearchFlags.class)); assertTrue(searchQuery.isMatch(e)); } @Test public void testIsMatch() { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "asdf"); assertFalse(new SearchQuery("BiblatexEntryType", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry)); assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry)); assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry)); } @Test public void testIsValidQueryNotAsRegEx() { assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid()); } @Test public void testIsValidQueryContainsBracketNotAsRegEx() { assertTrue(new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid()); } @Test public void testIsNotValidQueryContainsBracketNotAsRegEx() { assertTrue(new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid()); } @Test public void testIsValidQueryAsRegEx() { assertTrue(new SearchQuery("asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid()); } @Test public void testIsValidQueryWithNumbersAsRegEx() { assertTrue(new SearchQuery("123", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid()); } @Test public void testIsValidQueryContainsBracketAsRegEx() { assertTrue(new SearchQuery("asdf[", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid()); } @Test public void testIsValidQueryWithEqualSignAsRegEx() { assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid()); } @Test public void testIsValidQueryWithNumbersAndEqualSignAsRegEx() { assertTrue(new SearchQuery("author=123", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isValid()); } @Test public void testIsValidQueryWithEqualSignNotAsRegEx() { assertTrue(new SearchQuery("author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid()); } @Test public void testIsValidQueryWithNumbersAndEqualSignNotAsRegEx() { assertTrue(new SearchQuery("author=123", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)).isValid()); } @Test public void isMatchedForNormalAndFieldBasedSearchMixed() { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "asdf"); entry.setField(StandardField.ABSTRACT, "text"); assertTrue(new SearchQuery("text AND author=asdf", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)).isMatch(entry)); } @Test public void testSimpleTerm() { String query = "progress"; SearchQuery result = new SearchQuery(query, EnumSet.noneOf(SearchFlags.class)); assertFalse(result.isGrammarBasedSearch()); } @Test public void testGetPattern() { String query = "progress"; SearchQuery result = new SearchQuery(query, EnumSet.noneOf(SearchFlags.class)); Pattern pattern = Pattern.compile("(\\Qprogress\\E)"); // We can't directly compare the pattern objects assertEquals(Optional.of(pattern.toString()), result.getPatternForWords().map(Pattern::toString)); } @Test public void testGetRegexpPattern() { String queryText = "[a-c]\\d* \\d*"; SearchQuery regexQuery = new SearchQuery(queryText, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION)); Pattern pattern = Pattern.compile("([a-c]\\d* \\d*)"); assertEquals(Optional.of(pattern.toString()), regexQuery.getPatternForWords().map(Pattern::toString)); } @Test public void testGetRegexpJavascriptPattern() { String queryText = "[a-c]\\d* \\d*"; SearchQuery regexQuery = new SearchQuery(queryText, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION)); Pattern pattern = Pattern.compile("([a-c]\\d* \\d*)"); assertEquals(Optional.of(pattern.toString()), regexQuery.getJavaScriptPatternForWords().map(Pattern::toString)); } @Test public void testEscapingInPattern() { // first word contain all java special regex characters String queryText = "<([{\\\\^-=$!|]})?*+.> word1 word2."; SearchQuery textQueryWithSpecialChars = new SearchQuery(queryText, EnumSet.noneOf(SearchFlags.class)); String pattern = "(\\Q<([{\\^-=$!|]})?*+.>\\E)|(\\Qword1\\E)|(\\Qword2.\\E)"; assertEquals(Optional.of(pattern), textQueryWithSpecialChars.getPatternForWords().map(Pattern::toString)); } @Test public void testEscapingInJavascriptPattern() { // first word contain all javascript special regex characters that should be escaped individually in text based search String queryText = "([{\\\\^$|]})?*+./ word1 word2."; SearchQuery textQueryWithSpecialChars = new SearchQuery(queryText, EnumSet.noneOf(SearchFlags.class)); String pattern = "(\\(\\[\\{\\\\\\^\\$\\|\\]\\}\\)\\?\\*\\+\\.\\/)|(word1)|(word2\\.)"; assertEquals(Optional.of(pattern), textQueryWithSpecialChars.getJavaScriptPatternForWords().map(Pattern::toString)); } }
11,148
44.692623
202
java
null
jabref-main/src/test/java/org/jabref/logic/shared/ConnectorTest.java
package org.jabref.logic.shared; import java.sql.SQLException; import org.jabref.logic.shared.exception.InvalidDBMSConnectionPropertiesException; import org.jabref.testutils.category.DatabaseTest; /** * Stores the credentials for the test systems */ @DatabaseTest public class ConnectorTest { public static DBMSConnection getTestDBMSConnection(DBMSType dbmsType) throws SQLException, InvalidDBMSConnectionPropertiesException { DBMSConnectionProperties properties = getTestConnectionProperties(dbmsType); return new DBMSConnection(properties); } public static DBMSConnectionProperties getTestConnectionProperties(DBMSType dbmsType) { switch (dbmsType) { case MYSQL: return new DBMSConnectionPropertiesBuilder().setType(dbmsType).setHost("127.0.0.1").setPort(3800).setDatabase("jabref").setUser("root").setPassword("root").setUseSSL(false).setAllowPublicKeyRetrieval(true).createDBMSConnectionProperties(); case POSTGRESQL: return new DBMSConnectionPropertiesBuilder().setType(dbmsType).setHost("localhost").setPort(dbmsType.getDefaultPort()).setDatabase("postgres").setUser("postgres").setPassword("postgres").setUseSSL(false).createDBMSConnectionProperties(); case ORACLE: return new DBMSConnectionPropertiesBuilder().setType(dbmsType).setHost("localhost").setPort(32118).setDatabase("jabref").setUser("jabref").setPassword("jabref").setUseSSL(false).createDBMSConnectionProperties(); default: return new DBMSConnectionPropertiesBuilder().createDBMSConnectionProperties(); } } }
1,646
50.46875
255
java
null
jabref-main/src/test/java/org/jabref/logic/shared/DBMSConnectionPropertiesTest.java
package org.jabref.logic.shared; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class DBMSConnectionPropertiesTest { @Test void urlForMySqlDoesNotIncludeSslConfig() { DBMSConnectionProperties connectionProperties = new DBMSConnectionPropertiesBuilder().setType(DBMSType.MYSQL).setHost("localhost").setPort(3108).setDatabase("jabref").setUser("user").setPassword("password").setUseSSL(false).setAllowPublicKeyRetrieval(true).setServerTimezone("").createDBMSConnectionProperties(); assertEquals("jdbc:mariadb://localhost:3108/jabref", connectionProperties.getUrl()); } @Test void urlForOracle() { DBMSConnectionProperties connectionProperties = new DBMSConnectionPropertiesBuilder().setType(DBMSType.ORACLE).setHost("localhost").setPort(3108).setDatabase("jabref").setUser("user").setPassword("password").setUseSSL(false).setServerTimezone("").createDBMSConnectionProperties(); assertEquals("jdbc:oracle:thin:@localhost:3108/jabref", connectionProperties.getUrl()); } }
1,078
50.380952
320
java
null
jabref-main/src/test/java/org/jabref/logic/shared/DBMSConnectionTest.java
package org.jabref.logic.shared; import java.sql.SQLException; import org.jabref.testutils.category.DatabaseTest; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import static org.junit.jupiter.api.Assertions.assertThrows; @DatabaseTest public class DBMSConnectionTest { @ParameterizedTest @EnumSource(DBMSType.class) public void getConnectionFailsWhenconnectingToInvalidHost(DBMSType dbmsType) { assertThrows(SQLException.class, () -> new DBMSConnection( new DBMSConnectionPropertiesBuilder() .setType(dbmsType) .setHost("XXXX") .setPort(33778) .setDatabase("XXXX") .setUser("XXXX") .setPassword("XXXX") .setUseSSL(false) .setServerTimezone("XXXX") .createDBMSConnectionProperties()) .getConnection()); } }
1,146
33.757576
82
java
null
jabref-main/src/test/java/org/jabref/logic/shared/DBMSProcessorTest.java
package org.jabref.logic.shared; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.logic.shared.exception.OfflineLockException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.DatabaseTest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @DatabaseTest @Execution(ExecutionMode.SAME_THREAD) class DBMSProcessorTest { private DBMSConnection dbmsConnection; private DBMSProcessor dbmsProcessor; private DBMSType dbmsType; @BeforeEach public void setup() throws Exception { this.dbmsType = TestManager.getDBMSTypeTestParameter(); this.dbmsConnection = ConnectorTest.getTestDBMSConnection(dbmsType); this.dbmsProcessor = DBMSProcessor.getProcessorInstance(ConnectorTest.getTestDBMSConnection(dbmsType)); TestManager.clearTables(this.dbmsConnection); dbmsProcessor.setupSharedDatabase(); } @AfterEach public void closeDbmsConnection() throws SQLException { this.dbmsConnection.getConnection().close(); } @Test void databaseIntegrityFullFiledAfterSetup() throws SQLException { assertTrue(dbmsProcessor.checkBaseIntegrity()); } @Test void databaseIntegrityBrokenAfterClearedTables() throws SQLException { TestManager.clearTables(this.dbmsConnection); assertFalse(dbmsProcessor.checkBaseIntegrity()); } @Test void testInsertEntry() throws SQLException { BibEntry expectedEntry = getBibEntryExample(); dbmsProcessor.insertEntry(expectedEntry); BibEntry emptyEntry = getBibEntryExample(); emptyEntry.getSharedBibEntryData().setSharedID(1); dbmsProcessor.insertEntry(emptyEntry); // does not insert, due to same sharedID. Map<String, String> actualFieldMap = new HashMap<>(); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertTrue(entryResultSet.next()); assertEquals(1, entryResultSet.getInt("SHARED_ID")); assertEquals("inproceedings", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertFalse(entryResultSet.next()); try (ResultSet fieldResultSet = selectFrom("FIELD", dbmsConnection, dbmsProcessor)) { while (fieldResultSet.next()) { actualFieldMap.put(fieldResultSet.getString("NAME"), fieldResultSet.getString("VALUE")); } } } Map<String, String> expectedFieldMap = expectedEntry.getFieldMap().entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey().getName(), Map.Entry::getValue)); assertEquals(expectedFieldMap, actualFieldMap); } @Test void testInsertEntryWithEmptyFields() throws SQLException { BibEntry expectedEntry = new BibEntry(StandardEntryType.Article); dbmsProcessor.insertEntry(expectedEntry); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertTrue(entryResultSet.next()); assertEquals(1, entryResultSet.getInt("SHARED_ID")); assertEquals("article", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertFalse(entryResultSet.next()); // Adding an empty entry should not create an entry in field table, only in entry table try (ResultSet fieldResultSet = selectFrom("FIELD", dbmsConnection, dbmsProcessor)) { assertFalse(fieldResultSet.next()); } } } private static BibEntry getBibEntryExample() { return new BibEntry(StandardEntryType.InProceedings) .withField(StandardField.AUTHOR, "Wirthlin, Michael J and Hutchings, Brad L and Gilson, Kent L") .withField(StandardField.TITLE, "The nano processor: a low resource reconfigurable processor") .withField(StandardField.BOOKTITLE, "FPGAs for Custom Computing Machines, 1994. Proceedings. IEEE Workshop on") .withField(StandardField.YEAR, "1994") .withCitationKey("nanoproc1994"); } @Test void testUpdateEntry() throws Exception { BibEntry expectedEntry = getBibEntryExample(); dbmsProcessor.insertEntry(expectedEntry); expectedEntry.setType(StandardEntryType.Book); expectedEntry.setField(StandardField.AUTHOR, "Michael J and Hutchings"); expectedEntry.setField(new UnknownField("customField"), "custom value"); expectedEntry.clearField(StandardField.BOOKTITLE); dbmsProcessor.updateEntry(expectedEntry); Optional<BibEntry> actualEntry = dbmsProcessor.getSharedEntry(expectedEntry.getSharedBibEntryData().getSharedID()); assertEquals(Optional.of(expectedEntry), actualEntry); } @Test void testUpdateEmptyEntry() throws Exception { BibEntry expectedEntry = new BibEntry(StandardEntryType.Article); dbmsProcessor.insertEntry(expectedEntry); expectedEntry.setField(StandardField.AUTHOR, "Michael J and Hutchings"); expectedEntry.setField(new UnknownField("customField"), "custom value"); // Update field should now find the entry dbmsProcessor.updateEntry(expectedEntry); Optional<BibEntry> actualEntry = dbmsProcessor.getSharedEntry(expectedEntry.getSharedBibEntryData().getSharedID()); assertEquals(Optional.of(expectedEntry), actualEntry); } @Test void testGetEntriesByIdList() throws Exception { BibEntry firstEntry = getBibEntryExample(); firstEntry.setField(InternalField.INTERNAL_ID_FIELD, "00001"); BibEntry secondEntry = getBibEntryExample(); secondEntry.setField(InternalField.INTERNAL_ID_FIELD, "00002"); dbmsProcessor.insertEntry(firstEntry); dbmsProcessor.insertEntry(secondEntry); List<BibEntry> sharedEntriesByIdList = dbmsProcessor.getSharedEntries(Arrays.asList(1, 2)); assertEquals(List.of(firstEntry, secondEntry), sharedEntriesByIdList); } @Test void testUpdateNewerEntry() { BibEntry bibEntry = getBibEntryExample(); dbmsProcessor.insertEntry(bibEntry); // simulate older version bibEntry.getSharedBibEntryData().setVersion(0); bibEntry.setField(StandardField.YEAR, "1993"); assertThrows(OfflineLockException.class, () -> dbmsProcessor.updateEntry(bibEntry)); } @Test void testUpdateEqualEntry() throws OfflineLockException, SQLException { BibEntry expectedBibEntry = getBibEntryExample(); dbmsProcessor.insertEntry(expectedBibEntry); // simulate older version expectedBibEntry.getSharedBibEntryData().setVersion(0); dbmsProcessor.updateEntry(expectedBibEntry); Optional<BibEntry> actualBibEntryOptional = dbmsProcessor .getSharedEntry(expectedBibEntry.getSharedBibEntryData().getSharedID()); assertEquals(Optional.of(expectedBibEntry), actualBibEntryOptional); } @Test void testRemoveAllEntries() throws SQLException { BibEntry firstEntry = getBibEntryExample(); BibEntry secondEntry = getBibEntryExample2(); List<BibEntry> entriesToRemove = Arrays.asList(firstEntry, secondEntry); dbmsProcessor.insertEntry(firstEntry); dbmsProcessor.insertEntry(secondEntry); dbmsProcessor.removeEntries(entriesToRemove); try (ResultSet resultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertFalse(resultSet.next()); } } @Test void testRemoveSomeEntries() throws SQLException { BibEntry firstEntry = getBibEntryExample(); BibEntry secondEntry = getBibEntryExample2(); BibEntry thirdEntry = getBibEntryExample3(); // Remove the first and third entries - the second should remain (SHARED_ID will be 2) List<BibEntry> entriesToRemove = Arrays.asList(firstEntry, thirdEntry); dbmsProcessor.insertEntry(firstEntry); dbmsProcessor.insertEntry(secondEntry); dbmsProcessor.insertEntry(thirdEntry); dbmsProcessor.removeEntries(entriesToRemove); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertTrue(entryResultSet.next()); assertEquals(2, entryResultSet.getInt("SHARED_ID")); assertFalse(entryResultSet.next()); } } @Test void testRemoveSingleEntry() throws SQLException { BibEntry entryToRemove = getBibEntryExample(); dbmsProcessor.insertEntry(entryToRemove); dbmsProcessor.removeEntries(Collections.singletonList(entryToRemove)); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertFalse(entryResultSet.next()); } } @Test void testRemoveEntriesOnNullThrows() { assertThrows(NullPointerException.class, () -> dbmsProcessor.removeEntries(null)); } @Test void testRemoveEmptyEntryList() throws SQLException { dbmsProcessor.removeEntries(Collections.emptyList()); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertFalse(entryResultSet.next()); } } @Test void testGetSharedEntries() { BibEntry bibEntry = getBibEntryExampleWithEmptyFields(); dbmsProcessor.insertEntry(bibEntry); List<BibEntry> actualEntries = dbmsProcessor.getSharedEntries(); assertEquals(List.of(bibEntry), actualEntries); } @Test void testGetSharedEntry() { BibEntry expectedBibEntry = getBibEntryExampleWithEmptyFields(); dbmsProcessor.insertEntry(expectedBibEntry); Optional<BibEntry> actualBibEntryOptional = dbmsProcessor.getSharedEntry(expectedBibEntry.getSharedBibEntryData().getSharedID()); assertEquals(Optional.of(expectedBibEntry), actualBibEntryOptional); } @Test void testGetNotExistingSharedEntry() { Optional<BibEntry> actualBibEntryOptional = dbmsProcessor.getSharedEntry(1); assertFalse(actualBibEntryOptional.isPresent()); } @Test void testGetSharedIDVersionMapping() throws OfflineLockException, SQLException { BibEntry firstEntry = getBibEntryExample(); BibEntry secondEntry = getBibEntryExample(); dbmsProcessor.insertEntry(firstEntry); dbmsProcessor.insertEntry(secondEntry); dbmsProcessor.updateEntry(secondEntry); Map<Integer, Integer> expectedIDVersionMap = new HashMap<>(); expectedIDVersionMap.put(firstEntry.getSharedBibEntryData().getSharedID(), 1); expectedIDVersionMap.put(secondEntry.getSharedBibEntryData().getSharedID(), 2); Map<Integer, Integer> actualIDVersionMap = dbmsProcessor.getSharedIDVersionMapping(); assertEquals(expectedIDVersionMap, actualIDVersionMap); } @Test void testGetSharedMetaData() { insertMetaData("databaseType", "bibtex;", dbmsConnection, dbmsProcessor); insertMetaData("protectedFlag", "true;", dbmsConnection, dbmsProcessor); insertMetaData("saveActions", "enabled;\nauthor[capitalize,html_to_latex]\ntitle[title_case]\n;", dbmsConnection, dbmsProcessor); insertMetaData("saveOrderConfig", "specified;author;false;title;false;year;true;", dbmsConnection, dbmsProcessor); insertMetaData("VersionDBStructure", "1", dbmsConnection, dbmsProcessor); Map<String, String> expectedMetaData = getMetaDataExample(); Map<String, String> actualMetaData = dbmsProcessor.getSharedMetaData(); assertEquals(expectedMetaData, actualMetaData); } @Test void testSetSharedMetaData() throws SQLException { Map<String, String> expectedMetaData = getMetaDataExample(); dbmsProcessor.setSharedMetaData(expectedMetaData); Map<String, String> actualMetaData = dbmsProcessor.getSharedMetaData(); assertEquals(expectedMetaData, actualMetaData); } private static Map<String, String> getMetaDataExample() { Map<String, String> expectedMetaData = new HashMap<>(); expectedMetaData.put("databaseType", "bibtex;"); expectedMetaData.put("protectedFlag", "true;"); expectedMetaData.put("saveActions", "enabled;\nauthor[capitalize,html_to_latex]\ntitle[title_case]\n;"); expectedMetaData.put("saveOrderConfig", "specified;author;false;title;false;year;true;"); expectedMetaData.put("VersionDBStructure", "1"); return expectedMetaData; } private static BibEntry getBibEntryExampleWithEmptyFields() { BibEntry bibEntry = new BibEntry() .withField(StandardField.AUTHOR, "Author") .withField(StandardField.TITLE, "") .withField(StandardField.YEAR, ""); bibEntry.getSharedBibEntryData().setSharedID(1); return bibEntry; } private static BibEntry getBibEntryExample2() { return new BibEntry(StandardEntryType.InProceedings) .withField(StandardField.AUTHOR, "Shelah, Saharon and Ziegler, Martin") .withField(StandardField.TITLE, "Algebraically closed groups of large cardinality") .withField(StandardField.JOURNAL, "The Journal of Symbolic Logic") .withField(StandardField.YEAR, "1979") .withCitationKey("algegrou1979"); } private static BibEntry getBibEntryExample3() { return new BibEntry(StandardEntryType.InProceedings) .withField(StandardField.AUTHOR, "Hodges, Wilfrid and Shelah, Saharon") .withField(StandardField.TITLE, "Infinite games and reduced products") .withField(StandardField.JOURNAL, "Annals of Mathematical Logic") .withField(StandardField.YEAR, "1981") .withCitationKey("infigame1981"); } @Test void testInsertMultipleEntries() throws SQLException { List<BibEntry> entries = new ArrayList<>(); for (int i = 0; i < 5; i++) { entries.add(new BibEntry(StandardEntryType.Article).withField(StandardField.JOURNAL, "journal " + i) .withField(StandardField.ISSUE, Integer.toString(i))); } entries.get(3).setType(StandardEntryType.Thesis); dbmsProcessor.insertEntries(entries); Map<Integer, Map<String, String>> actualFieldMap = new HashMap<>(); try (ResultSet entryResultSet = selectFrom("ENTRY", dbmsConnection, dbmsProcessor)) { assertTrue(entryResultSet.next()); assertEquals(1, entryResultSet.getInt("SHARED_ID")); assertEquals("article", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertTrue(entryResultSet.next()); assertEquals(2, entryResultSet.getInt("SHARED_ID")); assertEquals("article", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertTrue(entryResultSet.next()); assertEquals(3, entryResultSet.getInt("SHARED_ID")); assertEquals("article", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertTrue(entryResultSet.next()); assertEquals(4, entryResultSet.getInt("SHARED_ID")); assertEquals("thesis", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertTrue(entryResultSet.next()); assertEquals(5, entryResultSet.getInt("SHARED_ID")); assertEquals("article", entryResultSet.getString("TYPE")); assertEquals(1, entryResultSet.getInt("VERSION")); assertFalse(entryResultSet.next()); try (ResultSet fieldResultSet = selectFrom("FIELD", dbmsConnection, dbmsProcessor)) { while (fieldResultSet.next()) { if (actualFieldMap.containsKey(fieldResultSet.getInt("ENTRY_SHARED_ID"))) { actualFieldMap.get(fieldResultSet.getInt("ENTRY_SHARED_ID")).put( fieldResultSet.getString("NAME"), fieldResultSet.getString("VALUE")); } else { int sharedId = fieldResultSet.getInt("ENTRY_SHARED_ID"); actualFieldMap.put(sharedId, new HashMap<>()); actualFieldMap.get(sharedId).put(fieldResultSet.getString("NAME"), fieldResultSet.getString("VALUE")); } } } } Map<Integer, Map<String, String>> expectedFieldMap = entries.stream() .collect(Collectors.toMap(bibEntry -> bibEntry.getSharedBibEntryData().getSharedID(), bibEntry -> bibEntry.getFieldMap().entrySet().stream() .collect(Collectors.toMap(entry -> entry.getKey().getName(), Map.Entry::getValue)))); assertEquals(expectedFieldMap, actualFieldMap); } private ResultSet selectFrom(String table, DBMSConnection dbmsConnection, DBMSProcessor dbmsProcessor) { try { return dbmsConnection.getConnection().createStatement().executeQuery("SELECT * FROM " + escape_Table(table, dbmsProcessor)); } catch (SQLException e) { fail(e.getMessage()); return null; } } // Oracle does not support multiple tuple insertion in one INSERT INTO command. // Therefore this function was defined to improve the readability and to keep the code short. private void insertMetaData(String key, String value, DBMSConnection dbmsConnection, DBMSProcessor dbmsProcessor) { try { dbmsConnection.getConnection().createStatement().executeUpdate("INSERT INTO " + escape_Table("METADATA", dbmsProcessor) + "(" + escape("KEY", dbmsProcessor) + ", " + escape("VALUE", dbmsProcessor) + ") VALUES(" + escapeValue(key) + ", " + escapeValue(value) + ")"); } catch (SQLException e) { fail(e.getMessage()); } } private static String escape(String expression, DBMSProcessor dbmsProcessor) { return dbmsProcessor.escape(expression); } private static String escape_Table(String expression, DBMSProcessor dbmsProcessor) { return dbmsProcessor.escape_Table(expression); } private static String escapeValue(String value) { return "'" + value + "'"; } }
19,805
42.150327
183
java
null
jabref-main/src/test/java/org/jabref/logic/shared/DBMSSynchronizerTest.java
package org.jabref.logic.shared; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.cleanup.FieldFormatterCleanup; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.logic.exporter.MetaDataSerializer; import org.jabref.logic.formatter.casechanger.LowerCaseFormatter; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.event.EntriesEventSource; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.metadata.MetaData; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.testutils.category.DatabaseTest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @DatabaseTest @Execution(ExecutionMode.SAME_THREAD) public class DBMSSynchronizerTest { private DBMSSynchronizer dbmsSynchronizer; private BibDatabase bibDatabase; private final GlobalCitationKeyPattern pattern = GlobalCitationKeyPattern.fromPattern("[auth][year]"); private DBMSConnection dbmsConnection; private DBMSProcessor dbmsProcessor; private DBMSType dbmsType; private BibEntry createExampleBibEntry(int index) { BibEntry bibEntry = new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Wirthlin, Michael J" + index) .withField(StandardField.TITLE, "The nano processor" + index); bibEntry.getSharedBibEntryData().setSharedID(index); return bibEntry; } @BeforeEach public void setup() throws Exception { this.dbmsType = TestManager.getDBMSTypeTestParameter(); this.dbmsConnection = ConnectorTest.getTestDBMSConnection(dbmsType); this.dbmsProcessor = DBMSProcessor.getProcessorInstance(this.dbmsConnection); TestManager.clearTables(this.dbmsConnection); this.dbmsProcessor.setupSharedDatabase(); bibDatabase = new BibDatabase(); BibDatabaseContext context = new BibDatabaseContext(bibDatabase); dbmsSynchronizer = new DBMSSynchronizer(context, ',', pattern, new DummyFileUpdateMonitor()); bibDatabase.registerListener(dbmsSynchronizer); dbmsSynchronizer.openSharedDatabase(dbmsConnection); } @AfterEach public void clear() { dbmsSynchronizer.closeSharedDatabase(); } @Test public void testEntryAddedEventListener() throws Exception { BibEntry expectedEntry = createExampleBibEntry(1); BibEntry furtherEntry = createExampleBibEntry(1); bibDatabase.insertEntry(expectedEntry); // should not add into shared database. bibDatabase.insertEntry(furtherEntry, EntriesEventSource.SHARED); List<BibEntry> actualEntries = dbmsProcessor.getSharedEntries(); assertEquals(List.of(expectedEntry), actualEntries); } @Test public void twoLocalFieldChangesAreSynchronizedCorrectly() throws Exception { BibEntry expectedEntry = createExampleBibEntry(1); expectedEntry.registerListener(dbmsSynchronizer); bibDatabase.insertEntry(expectedEntry); expectedEntry.setField(StandardField.AUTHOR, "Brad L and Gilson"); expectedEntry.setField(StandardField.TITLE, "The micro multiplexer"); List<BibEntry> actualEntries = dbmsProcessor.getSharedEntries(); assertEquals(Collections.singletonList(expectedEntry), actualEntries); } @Test public void oneLocalAndOneSharedFieldChangeIsSynchronizedCorrectly() throws Exception { BibEntry exampleBibEntry = createExampleBibEntry(1); exampleBibEntry.registerListener(dbmsSynchronizer); bibDatabase.insertEntry(exampleBibEntry); exampleBibEntry.setField(StandardField.AUTHOR, "Brad L and Gilson"); // shared updates are not synchronized back to the remote database exampleBibEntry.setField(StandardField.TITLE, "The micro multiplexer", EntriesEventSource.SHARED); List<BibEntry> actualEntries = dbmsProcessor.getSharedEntries(); BibEntry expectedBibEntry = createExampleBibEntry(1) .withField(StandardField.AUTHOR, "Brad L and Gilson"); assertEquals(Collections.singletonList(expectedBibEntry), actualEntries); } @Test public void testEntriesRemovedEventListener() throws Exception { BibEntry bibEntry = createExampleBibEntry(1); bibDatabase.insertEntry(bibEntry); List<BibEntry> actualEntries = dbmsProcessor.getSharedEntries(); assertEquals(1, actualEntries.size()); assertEquals(bibEntry, actualEntries.get(0)); bibDatabase.removeEntry(bibEntry); actualEntries = dbmsProcessor.getSharedEntries(); assertEquals(0, actualEntries.size()); bibDatabase.insertEntry(bibEntry); bibDatabase.removeEntry(bibEntry, EntriesEventSource.SHARED); actualEntries = dbmsProcessor.getSharedEntries(); assertEquals(1, actualEntries.size()); assertEquals(bibEntry, actualEntries.get(0)); } @Test public void testMetaDataChangedEventListener() throws Exception { MetaData testMetaData = new MetaData(); testMetaData.registerListener(dbmsSynchronizer); dbmsSynchronizer.setMetaData(testMetaData); testMetaData.setMode(BibDatabaseMode.BIBTEX); Map<String, String> expectedMap = MetaDataSerializer.getSerializedStringMap(testMetaData, pattern); Map<String, String> actualMap = dbmsProcessor.getSharedMetaData(); actualMap.remove("VersionDBStructure"); assertEquals(expectedMap, actualMap); } @Test public void testInitializeDatabases() throws Exception { dbmsSynchronizer.initializeDatabases(); assertTrue(dbmsProcessor.checkBaseIntegrity()); dbmsSynchronizer.initializeDatabases(); assertTrue(dbmsProcessor.checkBaseIntegrity()); } @Test public void testSynchronizeLocalDatabaseWithEntryRemoval() throws Exception { List<BibEntry> expectedBibEntries = Arrays.asList(createExampleBibEntry(1), createExampleBibEntry(2)); dbmsProcessor.insertEntry(expectedBibEntries.get(0)); dbmsProcessor.insertEntry(expectedBibEntries.get(1)); assertTrue(bibDatabase.getEntries().isEmpty()); dbmsSynchronizer.synchronizeLocalDatabase(); assertEquals(expectedBibEntries, bibDatabase.getEntries()); dbmsProcessor.removeEntries(Collections.singletonList(expectedBibEntries.get(0))); expectedBibEntries = Collections.singletonList(expectedBibEntries.get(1)); dbmsSynchronizer.synchronizeLocalDatabase(); assertEquals(expectedBibEntries, bibDatabase.getEntries()); } @Test public void testSynchronizeLocalDatabaseWithEntryUpdate() throws Exception { BibEntry bibEntry = createExampleBibEntry(1); bibDatabase.insertEntry(bibEntry); assertEquals(List.of(bibEntry), bibDatabase.getEntries()); BibEntry modifiedBibEntry = createExampleBibEntry(1) .withField(new UnknownField("custom"), "custom value"); modifiedBibEntry.clearField(StandardField.TITLE); modifiedBibEntry.setType(StandardEntryType.Article); dbmsProcessor.updateEntry(modifiedBibEntry); assertEquals(1, modifiedBibEntry.getSharedBibEntryData().getSharedID()); dbmsSynchronizer.synchronizeLocalDatabase(); assertEquals(List.of(modifiedBibEntry), bibDatabase.getEntries()); assertEquals(List.of(modifiedBibEntry), dbmsProcessor.getSharedEntries()); } @Test public void updateEntryDoesNotModifyLocalDatabase() throws Exception { BibEntry bibEntry = createExampleBibEntry(1); bibDatabase.insertEntry(bibEntry); assertEquals(List.of(bibEntry), bibDatabase.getEntries()); BibEntry modifiedBibEntry = createExampleBibEntry(1) .withField(new UnknownField("custom"), "custom value"); modifiedBibEntry.clearField(StandardField.TITLE); modifiedBibEntry.setType(StandardEntryType.Article); dbmsProcessor.updateEntry(modifiedBibEntry); assertEquals(List.of(bibEntry), bibDatabase.getEntries()); assertEquals(List.of(modifiedBibEntry), dbmsProcessor.getSharedEntries()); } @Test public void testApplyMetaData() throws Exception { BibEntry bibEntry = createExampleBibEntry(1); bibDatabase.insertEntry(bibEntry); MetaData testMetaData = new MetaData(); testMetaData.setSaveActions(new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.AUTHOR, new LowerCaseFormatter())))); dbmsSynchronizer.setMetaData(testMetaData); dbmsSynchronizer.applyMetaData(); assertEquals("wirthlin, michael j1", bibEntry.getField(StandardField.AUTHOR).get()); } }
9,445
39.025424
172
java
null
jabref-main/src/test/java/org/jabref/logic/shared/DBMSTypeTest.java
package org.jabref.logic.shared; import java.util.Optional; import org.jabref.testutils.category.DatabaseTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @DatabaseTest public class DBMSTypeTest { @Test public void toStringCorrectForMysql() { assertEquals("MySQL", DBMSType.MYSQL.toString()); } @Test public void toStringCorrectForOracle() { assertEquals("Oracle", DBMSType.ORACLE.toString()); } @Test public void toStringCorrectForPostgres() { assertEquals("PostgreSQL", DBMSType.POSTGRESQL.toString()); } @Test public void fromStringWorksForMySQL() { assertEquals(Optional.of(DBMSType.MYSQL), DBMSType.fromString("MySQL")); } @Test public void fromStringWorksForPostgreSQL() { assertEquals(Optional.of(DBMSType.POSTGRESQL), DBMSType.fromString("PostgreSQL")); } @Test public void fromStringWorksForNullString() { assertEquals(Optional.empty(), DBMSType.fromString(null)); } @Test public void fromStringWorksForEmptyString() { assertEquals(Optional.empty(), DBMSType.fromString("")); } @Test public void fromStringWorksForUnkownString() { assertEquals(Optional.empty(), DBMSType.fromString("unknown")); } @Test public void driverClassForMysqlIsCorrect() { assertEquals("org.mariadb.jdbc.Driver", DBMSType.MYSQL.getDriverClassPath()); } @Test public void driverClassForOracleIsCorrect() { assertEquals("oracle.jdbc.driver.OracleDriver", DBMSType.ORACLE.getDriverClassPath()); } @Test public void driverClassForPostgresIsCorrect() { assertEquals("org.postgresql.Driver", DBMSType.POSTGRESQL.getDriverClassPath()); } @Test public void fromStringForMysqlReturnsCorrectValue() { assertEquals(DBMSType.MYSQL, DBMSType.fromString("MySQL").get()); } @Test public void fromStringForOracleRturnsCorrectValue() { assertEquals(DBMSType.ORACLE, DBMSType.fromString("Oracle").get()); } @Test public void fromStringForPostgresReturnsCorrectValue() { assertEquals(DBMSType.POSTGRESQL, DBMSType.fromString("PostgreSQL").get()); } @Test public void fromStringFromInvalidStringReturnsOptionalEmpty() { assertFalse(DBMSType.fromString("XXX").isPresent()); } @Test public void getUrlForMysqlHasCorrectFormat() { assertEquals("jdbc:mariadb://localhost:3306/xe", DBMSType.MYSQL.getUrl("localhost", 3306, "xe")); } @Test public void getUrlForOracleHasCorrectFormat() { assertEquals("jdbc:oracle:thin:@localhost:1521/xe", DBMSType.ORACLE.getUrl("localhost", 1521, "xe")); } @Test public void getUrlForPostgresHasCorrectFormat() { assertEquals("jdbc:postgresql://localhost:5432/xe", DBMSType.POSTGRESQL.getUrl("localhost", 5432, "xe")); } @Test public void getDefaultPortForMysqlHasCorrectValue() { assertEquals(3306, DBMSType.MYSQL.getDefaultPort()); } @Test public void getDefaultPortForOracleHasCorrectValue() { assertEquals(1521, DBMSType.ORACLE.getDefaultPort()); } @Test public void getDefaultPortForPostgresHasCorrectValue() { assertEquals(5432, DBMSType.POSTGRESQL.getDefaultPort()); } }
3,429
27.583333
113
java
null
jabref-main/src/test/java/org/jabref/logic/shared/SynchronizationEventListenerTest.java
package org.jabref.logic.shared; import org.jabref.logic.shared.event.SharedEntriesNotPresentEvent; import org.jabref.logic.shared.event.UpdateRefusedEvent; import org.jabref.testutils.category.DatabaseTest; import com.google.common.eventbus.Subscribe; @DatabaseTest public class SynchronizationEventListenerTest { private SharedEntriesNotPresentEvent sharedEntriesNotPresentEvent; private UpdateRefusedEvent updateRefusedEvent; @Subscribe public void listen(SharedEntriesNotPresentEvent event) { this.sharedEntriesNotPresentEvent = event; } @Subscribe public void listen(UpdateRefusedEvent event) { this.updateRefusedEvent = event; } public SharedEntriesNotPresentEvent getSharedEntriesNotPresentEvent() { return sharedEntriesNotPresentEvent; } public UpdateRefusedEvent getUpdateRefusedEvent() { return updateRefusedEvent; } }
917
26.818182
75
java
null
jabref-main/src/test/java/org/jabref/logic/shared/SynchronizationSimulatorTest.java
package org.jabref.logic.shared; import java.sql.SQLException; import java.util.List; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.testutils.category.DatabaseTest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @DatabaseTest @Execution(ExecutionMode.SAME_THREAD) public class SynchronizationSimulatorTest { private BibDatabaseContext clientContextA; private BibDatabaseContext clientContextB; private SynchronizationEventListenerTest eventListenerB; // used to monitor occurring events private final GlobalCitationKeyPattern pattern = GlobalCitationKeyPattern.fromPattern("[auth][year]"); private BibEntry getBibEntryExample(int index) { return new BibEntry(StandardEntryType.InProceedings) .withField(StandardField.AUTHOR, "Wirthlin, Michael J and Hutchings, Brad L and Gilson, Kent L " + index) .withField(StandardField.TITLE, "The nano processor: a low resource reconfigurable processor " + index) .withField(StandardField.BOOKTITLE, "FPGAs for Custom Computing Machines, 1994. Proceedings. IEEE Workshop on " + index) .withField(StandardField.YEAR, "199" + index) .withCitationKey("nanoproc199" + index); } @BeforeEach public void setup() throws Exception { DBMSConnection dbmsConnection = ConnectorTest.getTestDBMSConnection(TestManager.getDBMSTypeTestParameter()); TestManager.clearTables(dbmsConnection); clientContextA = new BibDatabaseContext(); DBMSSynchronizer synchronizerA = new DBMSSynchronizer(clientContextA, ',', pattern, new DummyFileUpdateMonitor()); clientContextA.convertToSharedDatabase(synchronizerA); clientContextA.getDBMSSynchronizer().openSharedDatabase(dbmsConnection); clientContextB = new BibDatabaseContext(); DBMSSynchronizer synchronizerB = new DBMSSynchronizer(clientContextB, ',', pattern, new DummyFileUpdateMonitor()); clientContextB.convertToSharedDatabase(synchronizerB); // use a second connection, because this is another client (typically on another machine) clientContextB.getDBMSSynchronizer().openSharedDatabase(ConnectorTest.getTestDBMSConnection(TestManager.getDBMSTypeTestParameter())); eventListenerB = new SynchronizationEventListenerTest(); clientContextB.getDBMSSynchronizer().registerListener(eventListenerB); } @AfterEach public void clear() throws SQLException { clientContextA.getDBMSSynchronizer().closeSharedDatabase(); clientContextB.getDBMSSynchronizer().closeSharedDatabase(); } @Test public void simulateEntryInsertionAndManualPull() throws Exception { // client A inserts an entry clientContextA.getDatabase().insertEntry(getBibEntryExample(1)); // client A inserts another entry clientContextA.getDatabase().insertEntry(getBibEntryExample(2)); // client B pulls the changes clientContextB.getDBMSSynchronizer().pullChanges(); assertEquals(clientContextA.getDatabase().getEntries(), clientContextB.getDatabase().getEntries()); } @Test public void simulateEntryUpdateAndManualPull() throws Exception { BibEntry bibEntry = getBibEntryExample(1); // client A inserts an entry clientContextA.getDatabase().insertEntry(bibEntry); // client A changes the entry bibEntry.setField(new UnknownField("custom"), "custom value"); // client B pulls the changes bibEntry.clearField(StandardField.AUTHOR); clientContextB.getDBMSSynchronizer().pullChanges(); assertEquals(clientContextA.getDatabase().getEntries(), clientContextB.getDatabase().getEntries()); } @Test public void simulateEntryDelitionAndManualPull() throws Exception { BibEntry bibEntry = getBibEntryExample(1); // client A inserts an entry clientContextA.getDatabase().insertEntry(bibEntry); // client B pulls the entry clientContextB.getDBMSSynchronizer().pullChanges(); assertFalse(clientContextA.getDatabase().getEntries().isEmpty()); assertFalse(clientContextB.getDatabase().getEntries().isEmpty()); assertEquals(clientContextA.getDatabase().getEntries(), clientContextB.getDatabase().getEntries()); // client A removes the entry clientContextA.getDatabase().removeEntry(bibEntry); // client B pulls the change clientContextB.getDBMSSynchronizer().pullChanges(); assertTrue(clientContextA.getDatabase().getEntries().isEmpty()); assertTrue(clientContextB.getDatabase().getEntries().isEmpty()); } @Test public void simulateUpdateOnNoLongerExistingEntry() throws Exception { BibEntry bibEntryOfClientA = getBibEntryExample(1); // client A inserts an entry clientContextA.getDatabase().insertEntry(bibEntryOfClientA); // client B pulls the entry clientContextB.getDBMSSynchronizer().pullChanges(); assertFalse(clientContextA.getDatabase().getEntries().isEmpty()); assertFalse(clientContextB.getDatabase().getEntries().isEmpty()); assertEquals(clientContextA.getDatabase().getEntries(), clientContextB.getDatabase().getEntries()); // client A removes the entry clientContextA.getDatabase().removeEntry(bibEntryOfClientA); assertFalse(clientContextB.getDatabase().getEntries().isEmpty()); assertNull(eventListenerB.getSharedEntriesNotPresentEvent()); // client B tries to update the entry BibEntry bibEntryOfClientB = clientContextB.getDatabase().getEntries().get(0); bibEntryOfClientB.setField(StandardField.YEAR, "2009"); // here a new SharedEntryNotPresentEvent has been thrown. In this case the user B would get an pop-up window. assertNotNull(eventListenerB.getSharedEntriesNotPresentEvent()); assertEquals(List.of(bibEntryOfClientB), eventListenerB.getSharedEntriesNotPresentEvent().getBibEntries()); } @Test public void simulateEntryChangeConflicts() { BibEntry bibEntryOfClientA = getBibEntryExample(1); // client A inserts an entry clientContextA.getDatabase().insertEntry(bibEntryOfClientA); // client B pulls the entry clientContextB.getDBMSSynchronizer().pullChanges(); // A now increases the version number bibEntryOfClientA.setField(StandardField.YEAR, "2001"); // B does nothing here, so there is no event occurrence assertFalse(clientContextB.getDatabase().getEntries().isEmpty()); assertNull(eventListenerB.getUpdateRefusedEvent()); BibEntry bibEntryOfClientB = clientContextB.getDatabase().getEntries().get(0); // B also tries to change something bibEntryOfClientB.setField(StandardField.YEAR, "2016"); // B now cannot update the shared entry, due to optimistic offline lock. // In this case an BibEntry merge dialog pops up. assertNotNull(eventListenerB.getUpdateRefusedEvent()); } }
7,889
45.964286
141
java
null
jabref-main/src/test/java/org/jabref/logic/shared/TestManager.java
package org.jabref.logic.shared; import java.sql.SQLException; import java.util.Objects; /** * This class provides helping methods for database tests. Furthermore, it determines database systems which are ready to * be used for tests. */ public class TestManager { /** * Determine the DBMSType to test from the environment variable "DMBS". In case that variable is not set, use "PostgreSQL" as default */ public static DBMSType getDBMSTypeTestParameter() { return DBMSType.fromString(System.getenv("DBMS")).orElse(DBMSType.POSTGRESQL); } public static void clearTables(DBMSConnection dbmsConnection) throws SQLException { Objects.requireNonNull(dbmsConnection); DBMSType dbmsType = dbmsConnection.getProperties().getType(); if (dbmsType == DBMSType.MYSQL) { dbmsConnection.getConnection().createStatement().executeUpdate("DROP TABLE IF EXISTS `JABREF_FIELD`"); dbmsConnection.getConnection().createStatement().executeUpdate("DROP TABLE IF EXISTS `JABREF_ENTRY`"); dbmsConnection.getConnection().createStatement().executeUpdate("DROP TABLE IF EXISTS `JABREF_METADATA`"); } else if (dbmsType == DBMSType.POSTGRESQL) { dbmsConnection.getConnection().createStatement().executeUpdate("DROP TABLE IF EXISTS jabref.\"FIELD\""); dbmsConnection.getConnection().createStatement().executeUpdate("DROP TABLE IF EXISTS jabref.\"ENTRY\""); dbmsConnection.getConnection().createStatement().executeUpdate("DROP TABLE IF EXISTS jabref.\"METADATA\""); dbmsConnection.getConnection().createStatement().executeUpdate("DROP SCHEMA IF EXISTS jabref"); } else if (dbmsType == DBMSType.ORACLE) { dbmsConnection.getConnection().createStatement() .executeUpdate("BEGIN\n" + "EXECUTE IMMEDIATE 'DROP TABLE \"FIELD\"';\n" + "EXCEPTION\n" + "WHEN OTHERS THEN\n" + "IF SQLCODE != -942 THEN\n" + "RAISE;\n" + "END IF;\n" + "END;\n"); dbmsConnection.getConnection().createStatement() .executeUpdate("BEGIN\n" + "EXECUTE IMMEDIATE 'DROP TABLE \"ENTRY\"';\n" + "EXCEPTION\n" + "WHEN OTHERS THEN\n" + "IF SQLCODE != -942 THEN\n" + "RAISE;\n" + "END IF;\n" + "END;\n"); dbmsConnection.getConnection().createStatement() .executeUpdate("BEGIN\n" + "EXECUTE IMMEDIATE 'DROP TABLE \"METADATA\"';\n" + "EXCEPTION\n" + "WHEN OTHERS THEN\n" + "IF SQLCODE != -942 THEN\n" + "RAISE;\n" + "END IF;\n" + "END;\n"); dbmsConnection.getConnection().createStatement() // Sequence does not exist has a different error code than table does not exist .executeUpdate("BEGIN\n" + "EXECUTE IMMEDIATE 'DROP SEQUENCE \"ENTRY_SEQ\"';\n" + "EXCEPTION\n" + "WHEN OTHERS THEN\n" + "IF SQLCODE != -2289 THEN\n" + "RAISE;\n" + "END IF;\n" + "END;\n"); } } }
3,221
59.792453
137
java
null
jabref-main/src/test/java/org/jabref/logic/shared/security/PasswordTest.java
package org.jabref.logic.shared.security; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class PasswordTest { @Test void passwordAESTest() throws GeneralSecurityException, UnsupportedEncodingException { String phrase = "Password"; Password password = new Password(phrase, "someKey"); String encryptedPassword = password.encrypt(); assertNotEquals(phrase, encryptedPassword); } @Test void passwordAsCharTest() throws GeneralSecurityException, UnsupportedEncodingException { char[] charPhrase = "Password".toCharArray(); Password charPassword = new Password(charPhrase, "someKey"); String charEncryptedPassword = charPassword.encrypt(); String stringPhrase = "Password"; Password stringPassword = new Password(stringPhrase, "someKey"); String stringEncryptedPassword = stringPassword.encrypt(); assertEquals(charEncryptedPassword, stringEncryptedPassword); } }
1,184
33.852941
93
java
null
jabref-main/src/test/java/org/jabref/logic/texparser/DefaultTexParserTest.java
package org.jabref.logic.texparser; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import org.jabref.model.texparser.LatexParserResult; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class DefaultTexParserTest { private final static String DARWIN = "Darwin1888"; private final static String EINSTEIN = "Einstein1920"; private final static String NEWTON = "Newton1999"; private final static String EINSTEIN_A = "Einstein1920a"; private final static String EINSTEIN_C = "Einstein1920c"; private final static String UNRESOLVED = "UnresolvedKey"; private final static String UNKNOWN = "UnknownKey"; private void testMatchCite(String key, String citeString) { LatexParserResult latexParserResult = new DefaultLatexParser().parse(citeString); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.addKey(key, Path.of(""), 1, 0, citeString.length(), citeString); assertEquals(expectedParserResult, latexParserResult); } private void testNonMatchCite(String citeString) { LatexParserResult latexParserResult = new DefaultLatexParser().parse(citeString); LatexParserResult expectedParserResult = new LatexParserResult(); assertEquals(expectedParserResult, latexParserResult); } @Test public void testCiteCommands() { testMatchCite(UNRESOLVED, "\\cite[pre][post]{UnresolvedKey}"); testMatchCite(UNRESOLVED, "\\cite*{UnresolvedKey}"); testMatchCite(UNRESOLVED, "\\parencite[post]{UnresolvedKey}"); testMatchCite(UNRESOLVED, "\\cite[pre][post]{UnresolvedKey}"); testMatchCite(EINSTEIN_C, "\\citep{Einstein1920c}"); testMatchCite(EINSTEIN_C, "\\autocite{Einstein1920c}"); testMatchCite(EINSTEIN_C, "\\Autocite{Einstein1920c}"); testMatchCite(DARWIN, "\\blockcquote[p. 28]{Darwin1888}{some text}"); testMatchCite(DARWIN, "\\textcquote[p. 18]{Darwin1888}{blablabla}"); testNonMatchCite("\\citet21312{123U123n123resolvedKey}"); testNonMatchCite("\\1cite[pr234e][post]{UnresolvedKey}"); testNonMatchCite("\\citep55{5}UnresolvedKey}"); testNonMatchCite("\\cit2et{UnresolvedKey}"); } @Test public void testTwoCitationsSameLine() { String citeString = "\\citep{Einstein1920c} and \\citep{Einstein1920a}"; LatexParserResult latexParserResult = new DefaultLatexParser().parse(citeString); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.addKey(EINSTEIN_C, Path.of(""), 1, 0, 21, citeString); expectedParserResult.addKey(EINSTEIN_A, Path.of(""), 1, 26, 47, citeString); assertEquals(expectedParserResult, latexParserResult); } @Test public void testFileEncodingUtf8() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("utf-8.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); expectedParserResult.addKey("anykey", texFile, 1, 32, 45, "Danach wir anschließend mittels \\cite{anykey}."); assertEquals(expectedParserResult, parserResult); } @Test public void testFileEncodingIso88591() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("iso-8859-1.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); // The character � is on purpose - we cannot use Apache Tika's CharsetDetector - see ADR-0005 expectedParserResult .addKey("anykey", texFile, 1, 32, 45, "Danach wir anschlie�end mittels \\cite{anykey}."); assertEquals(expectedParserResult, parserResult); } @Test public void testFileEncodingIso885915() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("iso-8859-15.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); // The character � is on purpose - we cannot use Apache Tika's CharsetDetector - see ADR-0005 expectedParserResult .addKey("anykey", texFile, 1, 32, 45, "Danach wir anschlie�end mittels \\cite{anykey}."); assertEquals(expectedParserResult, parserResult); } @Test public void testFileEncodingForThreeFiles() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("utf-8.tex").toURI()); Path texFile2 = Path.of(DefaultTexParserTest.class.getResource("iso-8859-1.tex").toURI()); Path texFile3 = Path.of(DefaultTexParserTest.class.getResource("iso-8859-15.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser() .parse(Arrays.asList(texFile, texFile2, texFile3)); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().addAll(Arrays.asList(texFile, texFile2, texFile3)); expectedParserResult .addKey("anykey", texFile, 1, 32, 45, "Danach wir anschließend mittels \\cite{anykey}."); expectedParserResult .addKey("anykey", texFile2, 1, 32, 45, "Danach wir anschlie�end mittels \\cite{anykey}."); expectedParserResult .addKey("anykey", texFile3, 1, 32, 45, "Danach wir anschlie�end mittels \\cite{anykey}."); assertEquals(expectedParserResult, parserResult); } @Test public void testSingleFile() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("paper.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); expectedParserResult.addBibFile(texFile, texFile.getParent().resolve("origin.bib")); expectedParserResult.addKey(EINSTEIN, texFile, 4, 0, 19, "\\cite{Einstein1920}"); expectedParserResult.addKey(DARWIN, texFile, 5, 0, 17, "\\cite{Darwin1888}."); expectedParserResult.addKey(EINSTEIN, texFile, 6, 14, 33, "Einstein said \\cite{Einstein1920} that lorem impsum, consectetur adipiscing elit."); expectedParserResult.addKey(DARWIN, texFile, 7, 67, 84, "Nunc ultricies leo nec libero rhoncus, eu vehicula enim efficitur. \\cite{Darwin1888}"); assertEquals(expectedParserResult, parserResult); } @Test public void testTwoFiles() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("paper.tex").toURI()); Path texFile2 = Path.of(DefaultTexParserTest.class.getResource("paper2.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(Arrays.asList(texFile, texFile2)); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().addAll(Arrays.asList(texFile, texFile2)); expectedParserResult.addBibFile(texFile, texFile.getParent().resolve("origin.bib")); expectedParserResult.addBibFile(texFile2, texFile2.getParent().resolve("origin.bib")); expectedParserResult.addKey(EINSTEIN, texFile, 4, 0, 19, "\\cite{Einstein1920}"); expectedParserResult.addKey(DARWIN, texFile, 5, 0, 17, "\\cite{Darwin1888}."); expectedParserResult.addKey(EINSTEIN, texFile, 6, 14, 33, "Einstein said \\cite{Einstein1920} that lorem impsum, consectetur adipiscing elit."); expectedParserResult.addKey(DARWIN, texFile, 7, 67, 84, "Nunc ultricies leo nec libero rhoncus, eu vehicula enim efficitur. \\cite{Darwin1888}"); expectedParserResult.addKey(DARWIN, texFile2, 4, 48, 65, "This is some content trying to cite a bib file: \\cite{Darwin1888}"); expectedParserResult.addKey(EINSTEIN, texFile2, 5, 48, 67, "This is some content trying to cite a bib file: \\cite{Einstein1920}"); expectedParserResult.addKey(NEWTON, texFile2, 6, 48, 65, "This is some content trying to cite a bib file: \\cite{Newton1999}"); assertEquals(expectedParserResult, parserResult); } @Test public void testDuplicateFiles() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("paper.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(Arrays.asList(texFile, texFile)); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().addAll(Arrays.asList(texFile, texFile)); expectedParserResult.addBibFile(texFile, texFile.getParent().resolve("origin.bib")); expectedParserResult.addKey(EINSTEIN, texFile, 4, 0, 19, "\\cite{Einstein1920}"); expectedParserResult.addKey(DARWIN, texFile, 5, 0, 17, "\\cite{Darwin1888}."); expectedParserResult.addKey(EINSTEIN, texFile, 6, 14, 33, "Einstein said \\cite{Einstein1920} that lorem impsum, consectetur adipiscing elit."); expectedParserResult.addKey(DARWIN, texFile, 7, 67, 84, "Nunc ultricies leo nec libero rhoncus, eu vehicula enim efficitur. \\cite{Darwin1888}"); assertEquals(expectedParserResult, parserResult); } @Test public void testUnknownKey() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("unknown_key.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); expectedParserResult.addBibFile(texFile, texFile.getParent().resolve("origin.bib")); expectedParserResult.addKey(DARWIN, texFile, 4, 48, 65, "This is some content trying to cite a bib file: \\cite{Darwin1888}"); expectedParserResult.addKey(EINSTEIN, texFile, 5, 48, 67, "This is some content trying to cite a bib file: \\cite{Einstein1920}"); expectedParserResult.addKey(UNKNOWN, texFile, 6, 48, 65, "This is some content trying to cite a bib file: \\cite{UnknownKey}"); assertEquals(expectedParserResult, parserResult); } @Test public void testFileNotFound() { Path texFile = Path.of("file_not_found.tex"); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); assertEquals(expectedParserResult, parserResult); } @Test public void testNestedFiles() throws URISyntaxException { Path texFile = Path.of(DefaultTexParserTest.class.getResource("nested.tex").toURI()); Path texFile2 = Path.of(DefaultTexParserTest.class.getResource("nested2.tex").toURI()); Path texFile3 = Path.of(DefaultTexParserTest.class.getResource("paper.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); expectedParserResult.getNestedFiles().addAll(Arrays.asList(texFile2, texFile3)); expectedParserResult.addBibFile(texFile, texFile.getParent().resolve("origin.bib")); expectedParserResult.addBibFile(texFile2, texFile2.getParent().resolve("origin.bib")); expectedParserResult.addBibFile(texFile3, texFile3.getParent().resolve("origin.bib")); expectedParserResult.addKey(EINSTEIN, texFile3, 4, 0, 19, "\\cite{Einstein1920}"); expectedParserResult.addKey(DARWIN, texFile3, 5, 0, 17, "\\cite{Darwin1888}."); expectedParserResult.addKey(EINSTEIN, texFile3, 6, 14, 33, "Einstein said \\cite{Einstein1920} that lorem impsum, consectetur adipiscing elit."); expectedParserResult.addKey(DARWIN, texFile3, 7, 67, 84, "Nunc ultricies leo nec libero rhoncus, eu vehicula enim efficitur. \\cite{Darwin1888}"); assertEquals(expectedParserResult, parserResult); } }
12,596
51.4875
154
java
null
jabref-main/src/test/java/org/jabref/logic/texparser/LatexParserTest.java
package org.jabref.logic.texparser; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.texparser.LatexBibEntriesResolverResult; import org.jabref.model.texparser.LatexParserResult; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.LibraryPreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; public class LatexParserTest { private final static String DARWIN = "Darwin1888"; private final static String EINSTEIN = "Einstein1920"; private final static String NEWTON = "Newton1999"; private final static String EINSTEIN_A = "Einstein1920a"; private final static String EINSTEIN_B = "Einstein1920b"; private final static String EINSTEIN_C = "Einstein1920c"; private final FileUpdateMonitor fileMonitor = new DummyFileUpdateMonitor(); private LibraryPreferences libraryPreferences; private ImportFormatPreferences importFormatPreferences; private BibDatabase database; private BibDatabase database2; @BeforeEach void setUp() { libraryPreferences = mock(LibraryPreferences.class, Answers.RETURNS_DEEP_STUBS); importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); database = new BibDatabase(); database2 = new BibDatabase(); BibEntry darwin = new BibEntry(StandardEntryType.Book) .withCitationKey(DARWIN) .withField(StandardField.TITLE, "The descent of man, and selection in relation to sex") .withField(StandardField.PUBLISHER, "J. Murray") .withField(StandardField.YEAR, "1888") .withField(StandardField.AUTHOR, "Darwin, Charles"); database.insertEntry(darwin); BibEntry einstein = new BibEntry(StandardEntryType.Book) .withCitationKey(EINSTEIN) .withField(StandardField.TITLE, "Relativity: The special and general theory") .withField(StandardField.PUBLISHER, "Penguin") .withField(StandardField.YEAR, "1920") .withField(StandardField.AUTHOR, "Einstein, Albert"); database.insertEntry(einstein); BibEntry newton = new BibEntry(StandardEntryType.Book) .withCitationKey(NEWTON) .withField(StandardField.TITLE, "The Principia: mathematical principles of natural philosophy") .withField(StandardField.PUBLISHER, "Univ of California Press") .withField(StandardField.YEAR, "1999") .withField(StandardField.AUTHOR, "Newton, Isaac"); database.insertEntry(newton); database2.insertEntry(newton); BibEntry einsteinA = new BibEntry(StandardEntryType.InBook) .withCitationKey(EINSTEIN_A) .withField(StandardField.CROSSREF, "Einstein1920") .withField(StandardField.PAGES, "22--23"); database.insertEntry(einsteinA); BibEntry einsteinB = new BibEntry(StandardEntryType.InBook) .withCitationKey(EINSTEIN_B) .withField(StandardField.CROSSREF, "Einstein1921") .withField(StandardField.PAGES, "22--23"); database.insertEntry(einsteinB); BibEntry einsteinC = new BibEntry(StandardEntryType.InBook) .withCitationKey(EINSTEIN_C) .withField(StandardField.CROSSREF, "Einstein1920") .withField(StandardField.PAGES, "25--33"); database.insertEntry(einsteinC); } @Test public void testSameFileDifferentDatabases() throws URISyntaxException { Path texFile = Path.of(LatexParserTest.class.getResource("paper.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().add(texFile); expectedParserResult.addBibFile(texFile, texFile.getParent().resolve("origin.bib")); expectedParserResult.addKey(EINSTEIN, texFile, 4, 0, 19, "\\cite{Einstein1920}"); expectedParserResult.addKey(DARWIN, texFile, 5, 0, 17, "\\cite{Darwin1888}."); expectedParserResult.addKey(EINSTEIN, texFile, 6, 14, 33, "Einstein said \\cite{Einstein1920} that lorem impsum, consectetur adipiscing elit."); expectedParserResult.addKey(DARWIN, texFile, 7, 67, 84, "Nunc ultricies leo nec libero rhoncus, eu vehicula enim efficitur. \\cite{Darwin1888}"); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(expectedParserResult); assertEquals(expectedCrossingResult, crossingResult); LatexBibEntriesResolverResult crossingResult2 = new TexBibEntriesResolver(database2, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult2 = new LatexBibEntriesResolverResult(expectedParserResult); expectedCrossingResult2.addEntry(database.getEntryByCitationKey(EINSTEIN).get()); expectedCrossingResult2.addEntry(database.getEntryByCitationKey(DARWIN).get()); assertEquals(expectedCrossingResult2, crossingResult2); } @Test public void testTwoFilesDifferentDatabases() throws URISyntaxException { Path texFile = Path.of(LatexParserTest.class.getResource("paper.tex").toURI()); Path texFile2 = Path.of(LatexParserTest.class.getResource("paper2.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(Arrays.asList(texFile, texFile2)); LatexParserResult expectedParserResult = new LatexParserResult(); expectedParserResult.getFileList().addAll(Arrays.asList(texFile, texFile2)); expectedParserResult.addBibFile(texFile, texFile.getParent().resolve("origin.bib")); expectedParserResult.addBibFile(texFile2, texFile2.getParent().resolve("origin.bib")); expectedParserResult.addKey(EINSTEIN, texFile, 4, 0, 19, "\\cite{Einstein1920}"); expectedParserResult.addKey(DARWIN, texFile, 5, 0, 17, "\\cite{Darwin1888}."); expectedParserResult.addKey(EINSTEIN, texFile, 6, 14, 33, "Einstein said \\cite{Einstein1920} that lorem impsum, consectetur adipiscing elit."); expectedParserResult.addKey(DARWIN, texFile, 7, 67, 84, "Nunc ultricies leo nec libero rhoncus, eu vehicula enim efficitur. \\cite{Darwin1888}"); expectedParserResult.addKey(DARWIN, texFile2, 4, 48, 65, "This is some content trying to cite a bib file: \\cite{Darwin1888}"); expectedParserResult.addKey(EINSTEIN, texFile2, 5, 48, 67, "This is some content trying to cite a bib file: \\cite{Einstein1920}"); expectedParserResult.addKey(NEWTON, texFile2, 6, 48, 65, "This is some content trying to cite a bib file: \\cite{Newton1999}"); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(expectedParserResult); assertEquals(expectedCrossingResult, crossingResult); LatexBibEntriesResolverResult crossingResult2 = new TexBibEntriesResolver(database2, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult2 = new LatexBibEntriesResolverResult(expectedParserResult); expectedCrossingResult2.addEntry(database.getEntryByCitationKey(EINSTEIN).get()); expectedCrossingResult2.addEntry(database.getEntryByCitationKey(DARWIN).get()); assertEquals(expectedCrossingResult2, crossingResult2); } }
8,407
54.315789
173
java
null
jabref-main/src/test/java/org/jabref/logic/texparser/TexBibEntriesResolverTest.java
package org.jabref.logic.texparser; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.texparser.LatexBibEntriesResolverResult; import org.jabref.model.texparser.LatexParserResult; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.LibraryPreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; public class TexBibEntriesResolverTest { private final static String DARWIN = "Darwin1888"; private final static String EINSTEIN = "Einstein1920"; private final static String NEWTON = "Newton1999"; private final static String EINSTEIN_A = "Einstein1920a"; private final static String EINSTEIN_B = "Einstein1920b"; private final static String EINSTEIN_C = "Einstein1920c"; private final FileUpdateMonitor fileMonitor = new DummyFileUpdateMonitor(); private LibraryPreferences libraryPreferences; private ImportFormatPreferences importFormatPreferences; private BibDatabase database; private BibDatabase database2; private BibEntry bibEntry; @BeforeEach void setUp() { libraryPreferences = mock(LibraryPreferences.class, Answers.RETURNS_DEEP_STUBS); importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); database = new BibDatabase(); database2 = new BibDatabase(); BibEntry darwin = new BibEntry(StandardEntryType.Book) .withCitationKey(DARWIN) .withField(StandardField.TITLE, "The descent of man, and selection in relation to sex") .withField(StandardField.PUBLISHER, "J. Murray") .withField(StandardField.YEAR, "1888") .withField(StandardField.AUTHOR, "Darwin, Charles"); database.insertEntry(darwin); BibEntry einstein = new BibEntry(StandardEntryType.Book) .withCitationKey(EINSTEIN) .withField(StandardField.TITLE, "Relativity: The special and general theory") .withField(StandardField.PUBLISHER, "Penguin") .withField(StandardField.YEAR, "1920") .withField(StandardField.AUTHOR, "Einstein, Albert"); database.insertEntry(einstein); BibEntry newton = new BibEntry(StandardEntryType.Book) .withCitationKey(NEWTON) .withField(StandardField.TITLE, "The Principia: mathematical principles of natural philosophy") .withField(StandardField.PUBLISHER, "Univ of California Press") .withField(StandardField.YEAR, "1999") .withField(StandardField.AUTHOR, "Newton, Isaac"); database.insertEntry(newton); BibEntry einsteinA = new BibEntry(StandardEntryType.InBook) .withCitationKey(EINSTEIN_A) .withField(StandardField.CROSSREF, EINSTEIN) .withField(StandardField.PAGES, "22--23"); database2.insertEntry(einsteinA); BibEntry einsteinB = new BibEntry(StandardEntryType.InBook) .withCitationKey(EINSTEIN_B) .withField(StandardField.CROSSREF, "Einstein1921") .withField(StandardField.PAGES, "22--23"); database.insertEntry(einsteinB); BibEntry einsteinC = new BibEntry(StandardEntryType.InBook) .withCitationKey(EINSTEIN_C) .withField(StandardField.CROSSREF, EINSTEIN) .withField(StandardField.PAGES, "25--33"); database.insertEntry(einsteinC); bibEntry = new BibEntry(StandardEntryType.InBook) .withCitationKey(EINSTEIN_A) .withField(StandardField.TITLE, "Relativity: The special and general theory") .withField(StandardField.PUBLISHER, "Penguin") .withField(StandardField.YEAR, "1920") .withField(StandardField.AUTHOR, "Einstein, Albert") .withField(StandardField.CROSSREF, "Einstein1920") .withField(StandardField.PAGES, "22--23"); } @Test public void testSingleFile() throws URISyntaxException { Path texFile = Path.of(TexBibEntriesResolverTest.class.getResource("paper.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(parserResult); assertEquals(expectedCrossingResult, crossingResult); } @Test public void testTwoFiles() throws URISyntaxException { Path texFile = Path.of(TexBibEntriesResolverTest.class.getResource("paper.tex").toURI()); Path texFile2 = Path.of(TexBibEntriesResolverTest.class.getResource("paper2.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(Arrays.asList(texFile, texFile2)); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(parserResult); assertEquals(expectedCrossingResult, crossingResult); } @Test public void testDuplicateFiles() throws URISyntaxException { Path texFile = Path.of(TexBibEntriesResolverTest.class.getResource("paper.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(parserResult); assertEquals(expectedCrossingResult, crossingResult); } @Test public void testUnknownKey() throws URISyntaxException { Path texFile = Path.of(TexBibEntriesResolverTest.class.getResource("unknown_key.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(parserResult); assertEquals(expectedCrossingResult, crossingResult); } @Test public void testNestedFiles() throws URISyntaxException { Path texFile = Path.of(TexBibEntriesResolverTest.class.getResource("nested.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(parserResult); assertEquals(expectedCrossingResult, crossingResult); } @Test public void testCrossRef() throws URISyntaxException { Path texFile = Path.of(TexBibEntriesResolverTest.class.getResource("crossref.tex").toURI()); LatexParserResult parserResult = new DefaultLatexParser().parse(texFile); LatexBibEntriesResolverResult crossingResult = new TexBibEntriesResolver(database, libraryPreferences, importFormatPreferences, fileMonitor).resolve(parserResult); LatexBibEntriesResolverResult expectedCrossingResult = new LatexBibEntriesResolverResult(parserResult); expectedCrossingResult.addEntry(bibEntry); assertEquals(expectedCrossingResult, crossingResult); } }
8,343
48.372781
171
java
null
jabref-main/src/test/java/org/jabref/logic/util/BuildInfoTest.java
package org.jabref.logic.util; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class BuildInfoTest { @Test public void testDefaults() { BuildInfo buildInfo = new BuildInfo("asdf"); assertEquals("UNKNOWN", buildInfo.version.getFullVersion()); } @Test public void testFileImport() { BuildInfo buildInfo = new BuildInfo("/org/jabref/util/build.properties"); assertEquals("42", buildInfo.version.getFullVersion()); } @Test public void azureInstrumentationKeyIsNotEmpty() { BuildInfo buildInfo = new BuildInfo(); assertNotNull(buildInfo.azureInstrumentationKey); } }
769
26.5
81
java
null
jabref-main/src/test/java/org/jabref/logic/util/DevelopmentStageTest.java
package org.jabref.logic.util; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class DevelopmentStageTest { @Test public void checkStabilityOrder() { assertTrue(Version.DevelopmentStage.ALPHA.isMoreStableThan(Version.DevelopmentStage.UNKNOWN)); assertTrue(Version.DevelopmentStage.BETA.isMoreStableThan(Version.DevelopmentStage.ALPHA)); assertTrue(Version.DevelopmentStage.STABLE.isMoreStableThan(Version.DevelopmentStage.BETA)); assertEquals(4, Version.DevelopmentStage.values().length, "It seems that the development stages have been changed, please adjust the test"); } @Test public void parseStages() { assertEquals(Version.DevelopmentStage.ALPHA, Version.DevelopmentStage.parse("-alpha")); assertEquals(Version.DevelopmentStage.BETA, Version.DevelopmentStage.parse("-beta")); assertEquals(Version.DevelopmentStage.STABLE, Version.DevelopmentStage.parse("")); } @Test public void parseNull() { assertEquals(Version.DevelopmentStage.UNKNOWN, Version.DevelopmentStage.parse(null)); } @Test public void parseUnknownString() { assertEquals(Version.DevelopmentStage.UNKNOWN, Version.DevelopmentStage.parse("asdf")); } }
1,361
36.833333
148
java
null
jabref-main/src/test/java/org/jabref/logic/util/ExternalLinkCreatorTest.java
package org.jabref.logic.util; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.Test; import static org.jabref.logic.util.ExternalLinkCreator.getShortScienceSearchURL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class ExternalLinkCreatorTest { /** * Validates URL conformance to RFC2396. Does not perform complex checks such as opening connections. */ private boolean urlIsValid(String url) { try { // This will throw on non-compliance to RFC2396. new URL(url).toURI(); return true; } catch (MalformedURLException | URISyntaxException e) { return false; } } @Test void getShortScienceSearchURLEncodesSpecialCharacters() { BibEntry entry = new BibEntry(); String rfc3986ReservedCharacters = "!*'();:@&=+$,/?#[]"; entry.setField(StandardField.TITLE, rfc3986ReservedCharacters); Optional<String> url = getShortScienceSearchURL(entry); assertTrue(url.isPresent()); assertTrue(urlIsValid(url.get())); } @Test void getShortScienceSearchURLReturnsEmptyOnMissingTitle() { BibEntry entry = new BibEntry(); assertEquals(Optional.empty(), getShortScienceSearchURL(entry)); } @Test void getShortScienceSearchURLLinksToSearchResults() { // Take an arbitrary article name BibEntry entry = new BibEntry().withField(StandardField.TITLE, "JabRef bibliography management"); Optional<String> url = getShortScienceSearchURL(entry); // Expected behaviour is to link to the search results page, /internalsearch assertEquals(Optional.of("https://www.shortscience.org/internalsearch?q=JabRef+bibliography+management"), url); } }
2,018
34.421053
119
java
null
jabref-main/src/test/java/org/jabref/logic/util/FileNameCleanerTest.java
package org.jabref.logic.util; import org.jabref.logic.util.io.FileNameCleaner; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class FileNameCleanerTest { @Test public void testCleanFileName() { assertEquals("legalFilename.txt", FileNameCleaner.cleanFileName("legalFilename.txt")); assertEquals("illegalFilename______.txt", FileNameCleaner.cleanFileName("illegalFilename/?*<>|.txt")); } @Test public void testCleanDirectoryName() { assertEquals("legalFilename.txt", FileNameCleaner.cleanDirectoryName("legalFilename.txt")); assertEquals("subdir/legalFilename.txt", FileNameCleaner.cleanDirectoryName("subdir/legalFilename.txt")); assertEquals("illegalFilename/_____.txt", FileNameCleaner.cleanDirectoryName("illegalFilename/?*<>|.txt")); } @Test public void testCleanDirectoryNameForWindows() { assertEquals("legalFilename.txt", FileNameCleaner.cleanDirectoryName("legalFilename.txt")); assertEquals("subdir\\legalFilename.txt", FileNameCleaner.cleanDirectoryName("subdir\\legalFilename.txt")); assertEquals("illegalFilename\\_____.txt", FileNameCleaner.cleanDirectoryName("illegalFilename\\?*<>|.txt")); } @Test public void testCleanCurlyBracesAsWell() { assertEquals("The Evolution of Sentiment_ Analysis_A Review of Research Topics, Venues, and Top Cited Papers.PDF", FileNameCleaner.cleanFileName("The Evolution of Sentiment} Analysis}A Review of Research Topics, Venues, and Top Cited Papers.PDF")); } }
1,593
43.277778
256
java
null
jabref-main/src/test/java/org/jabref/logic/util/UpdateFieldTest.java
package org.jabref.logic.util; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import org.jabref.logic.preferences.OwnerPreferences; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.model.FieldChange; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class UpdateFieldTest { private BibEntry entry; @BeforeEach public void setUp() throws Exception { entry = new BibEntry(); entry.setChanged(false); } @Test public void testUpdateFieldWorksEmptyField() { assertFalse(entry.hasField(StandardField.YEAR)); UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertEquals(Optional.of("2016"), entry.getField(StandardField.YEAR)); } @Test public void testUpdateFieldWorksNonEmptyField() { entry.setField(StandardField.YEAR, "2015"); UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertEquals(Optional.of("2016"), entry.getField(StandardField.YEAR)); } @Test public void testUpdateFieldHasChanged() { assertFalse(entry.hasChanged()); UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertTrue(entry.hasChanged()); } @Test public void testUpdateFieldValidFieldChange() { Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertTrue(change.isPresent()); } @Test public void testUpdateFieldCorrectFieldChangeContentsEmptyField() { Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertNull(change.get().getOldValue()); assertEquals(StandardField.YEAR, change.get().getField()); assertEquals("2016", change.get().getNewValue()); assertEquals(entry, change.get().getEntry()); } @Test public void testUpdateFieldCorrectFieldChangeContentsNonEmptyField() { entry.setField(StandardField.YEAR, "2015"); Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertEquals("2015", change.get().getOldValue()); assertEquals(StandardField.YEAR, change.get().getField()); assertEquals("2016", change.get().getNewValue()); assertEquals(entry, change.get().getEntry()); } @Test public void testUpdateFieldSameValueNoChange() { entry.setField(StandardField.YEAR, "2016"); Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertFalse(change.isPresent()); } @Test public void testUpdateFieldSameValueNotChange() { entry.setField(StandardField.YEAR, "2016"); entry.setChanged(false); UpdateField.updateField(entry, StandardField.YEAR, "2016"); assertFalse(entry.hasChanged()); } @Test public void testUpdateFieldSetToNullClears() { entry.setField(StandardField.YEAR, "2016"); UpdateField.updateField(entry, StandardField.YEAR, null); assertFalse(entry.hasField(StandardField.YEAR)); } @Test public void testUpdateFieldSetEmptyToNullClears() { UpdateField.updateField(entry, StandardField.YEAR, null); assertFalse(entry.hasField(StandardField.YEAR)); } @Test public void testUpdateFieldSetToNullHasFieldChangeContents() { entry.setField(StandardField.YEAR, "2016"); Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, null); assertTrue(change.isPresent()); } @Test public void testUpdateFieldSetRmptyToNullHasNoFieldChangeContents() { Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, null); assertFalse(change.isPresent()); } @Test public void testUpdateFieldSetToNullCorrectFieldChangeContents() { entry.setField(StandardField.YEAR, "2016"); Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, null); assertNull(change.get().getNewValue()); assertEquals(StandardField.YEAR, change.get().getField()); assertEquals("2016", change.get().getOldValue()); assertEquals(entry, change.get().getEntry()); } @Test public void testUpdateFieldSameContentClears() { entry.setField(StandardField.YEAR, "2016"); UpdateField.updateField(entry, StandardField.YEAR, "2016", true); assertFalse(entry.hasField(StandardField.YEAR)); } @Test public void testUpdateFieldSameContentHasChanged() { entry.setField(StandardField.YEAR, "2016"); entry.setChanged(false); UpdateField.updateField(entry, StandardField.YEAR, "2016", true); assertTrue(entry.hasChanged()); } @Test public void testUpdateFieldSameContentHasFieldChange() { entry.setField(StandardField.YEAR, "2016"); Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, "2016", true); assertTrue(change.isPresent()); } @Test public void testUpdateFieldSameContentHasCorrectFieldChange() { entry.setField(StandardField.YEAR, "2016"); Optional<FieldChange> change = UpdateField.updateField(entry, StandardField.YEAR, "2016", true); assertNull(change.get().getNewValue()); assertEquals(StandardField.YEAR, change.get().getField()); assertEquals("2016", change.get().getOldValue()); assertEquals(entry, change.get().getEntry()); } @Test public void testUpdateNonDisplayableFieldUpdates() { assertFalse(entry.hasField(StandardField.YEAR)); UpdateField.updateNonDisplayableField(entry, StandardField.YEAR, "2016"); assertTrue(entry.hasField(StandardField.YEAR)); assertEquals(Optional.of("2016"), entry.getField(StandardField.YEAR)); } @Test public void testUpdateNonDisplayableFieldHasNotChanged() { assertFalse(entry.hasChanged()); UpdateField.updateNonDisplayableField(entry, StandardField.YEAR, "2016"); assertFalse(entry.hasChanged()); } @Test public void emptyOwnerFieldNowPresentAfterAutomaticSet() { assertEquals(Optional.empty(), entry.getField(StandardField.OWNER), "Owner is present"); OwnerPreferences ownerPreferences = createOwnerPreference(true, true); TimestampPreferences timestampPreferences = createTimestampPreference(); UpdateField.setAutomaticFields(List.of(entry), ownerPreferences, timestampPreferences); assertEquals(Optional.of("testDefaultOwner"), entry.getField(StandardField.OWNER), "No owner exists"); } @Test public void ownerAssignedCorrectlyAfterAutomaticSet() { OwnerPreferences ownerPreferences = createOwnerPreference(true, true); TimestampPreferences timestampPreferences = createTimestampPreference(); UpdateField.setAutomaticFields(List.of(entry), ownerPreferences, timestampPreferences); assertEquals(Optional.of("testDefaultOwner"), entry.getField(StandardField.OWNER)); } @Test public void ownerIsNotResetAfterAutomaticSetIfOverwriteOwnerFalse() { String alreadySetOwner = "alreadySetOwner"; entry.setField(StandardField.OWNER, alreadySetOwner); assertEquals(Optional.of(alreadySetOwner), entry.getField(StandardField.OWNER)); OwnerPreferences ownerPreferences = createOwnerPreference(true, false); TimestampPreferences timestampPreferences = createTimestampPreference(); UpdateField.setAutomaticFields(List.of(entry), ownerPreferences, timestampPreferences); assertNotEquals(Optional.of("testDefaultOwner"), entry.getField(StandardField.OWNER), "Owner has changed"); assertEquals(Optional.of(alreadySetOwner), entry.getField(StandardField.OWNER), "Owner has not changed"); } @Test public void emptyCreationDateFieldNowPresentAfterAutomaticSet() { assertEquals(Optional.empty(), entry.getField(StandardField.CREATIONDATE), "CreationDate is present"); OwnerPreferences ownerPreferences = createOwnerPreference(true, true); TimestampPreferences timestampPreferences = createTimestampPreference(); UpdateField.setAutomaticFields(List.of(entry), ownerPreferences, timestampPreferences); String creationDate = timestampPreferences.now(); assertEquals(Optional.of(creationDate), entry.getField(StandardField.CREATIONDATE), "No CreationDate exists"); } @Test public void creationDateAssignedCorrectlyAfterAutomaticSet() { OwnerPreferences ownerPreferences = createOwnerPreference(true, true); TimestampPreferences timestampPreferences = createTimestampPreference(); UpdateField.setAutomaticFields(List.of(entry), ownerPreferences, timestampPreferences); String creationDate = timestampPreferences.now(); assertEquals(Optional.of(creationDate), entry.getField(StandardField.CREATIONDATE), "Not the same date"); } @Test public void ownerSetToDefaultValueForCollectionOfBibEntries() { BibEntry entry2 = new BibEntry(); BibEntry entry3 = new BibEntry(); assertEquals(Optional.empty(), entry.getField(StandardField.OWNER), "Owner field for entry is present"); assertEquals(Optional.empty(), entry.getField(StandardField.OWNER), "Owner field for entry2 is present"); assertEquals(Optional.empty(), entry.getField(StandardField.OWNER), "Owner field for entry3 is present"); Collection<BibEntry> bibs = Arrays.asList(entry, entry2, entry3); OwnerPreferences ownerPreferences = createOwnerPreference(true, true); TimestampPreferences timestampPreferences = createTimestampPreference(); UpdateField.setAutomaticFields(bibs, ownerPreferences, timestampPreferences); String defaultOwner = "testDefaultOwner"; assertEquals(Optional.of(defaultOwner), entry.getField(StandardField.OWNER), "entry has no owner field"); assertEquals(Optional.of(defaultOwner), entry2.getField(StandardField.OWNER), "entry2 has no owner field"); assertEquals(Optional.of(defaultOwner), entry3.getField(StandardField.OWNER), "entry3 has no owner field"); } @Test public void ownerNotChangedForCollectionOfBibEntriesIfOptionsDisabled() { String initialOwner = "initialOwner"; entry.setField(StandardField.OWNER, initialOwner); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.OWNER, initialOwner); assertEquals(Optional.of(initialOwner), entry.getField(StandardField.OWNER), "Owner field for entry is not present"); assertEquals(Optional.of(initialOwner), entry2.getField(StandardField.OWNER), "Owner field for entry2 is not present"); Collection<BibEntry> bibs = Arrays.asList(entry, entry2); OwnerPreferences ownerPreferences = createOwnerPreference(true, false); TimestampPreferences timestampPreferences = createTimestampPreference(); UpdateField.setAutomaticFields(bibs, ownerPreferences, timestampPreferences); assertEquals(Optional.of(initialOwner), entry.getField(StandardField.OWNER), "entry has new value for owner field"); assertEquals(Optional.of(initialOwner), entry2.getField(StandardField.OWNER), "entry2 has new value for owner field"); } private OwnerPreferences createOwnerPreference(boolean useOwner, boolean overwriteOwner) { String defaultOwner = "testDefaultOwner"; return new OwnerPreferences(useOwner, defaultOwner, overwriteOwner); } private TimestampPreferences createTimestampPreference() { return new TimestampPreferences(true, true, true, StandardField.CREATIONDATE, "dd.mm.yyyy"); } }
12,264
41.586806
127
java
null
jabref-main/src/test/java/org/jabref/logic/util/VersionTest.java
package org.jabref.logic.util; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class VersionTest { @Test public void unknownVersionAsString() { Version version = Version.parse(BuildInfo.UNKNOWN_VERSION); assertEquals(BuildInfo.UNKNOWN_VERSION, version.getFullVersion()); } @Test public void unknownVersionAsNull() { Version version = Version.parse(null); assertEquals(BuildInfo.UNKNOWN_VERSION, version.getFullVersion()); } @Test public void unknownVersionAsEmptyString() { Version version = Version.parse(""); assertEquals(BuildInfo.UNKNOWN_VERSION, version.getFullVersion()); } @Test public void initVersionFromWrongStringResultsInUnknownVersion() { Version version = Version.parse("${version}"); assertEquals(BuildInfo.UNKNOWN_VERSION, version.getFullVersion()); } @Test public void versionOneDigit() { String versionText = "1"; Version version = Version.parse(versionText); assertEquals(versionText, version.getFullVersion()); assertEquals(1, version.getMajor()); assertEquals(0, version.getMinor()); assertEquals(0, version.getPatch()); assertFalse(version.isDevelopmentVersion()); } @Test public void versionTwoDigits() { String versionText = "1.2"; Version version = Version.parse(versionText); assertEquals(versionText, version.getFullVersion()); assertEquals(1, version.getMajor()); assertEquals(2, version.getMinor()); assertEquals(0, version.getPatch()); assertFalse(version.isDevelopmentVersion()); } @Test public void versionThreeDigits() { String versionText = "1.2.3"; Version version = Version.parse(versionText); assertEquals(versionText, version.getFullVersion()); assertEquals(1, version.getMajor()); assertEquals(2, version.getMinor()); assertEquals(3, version.getPatch()); assertFalse(version.isDevelopmentVersion()); } @Test public void versionOneDigitDevVersion() { String versionText = "1dev"; Version version = Version.parse(versionText); assertEquals(versionText, version.getFullVersion()); assertEquals(1, version.getMajor()); assertEquals(0, version.getMinor()); assertEquals(0, version.getPatch()); assertTrue(version.isDevelopmentVersion()); } @Test public void versionTwoDigitDevVersion() { String versionText = "1.2dev"; Version version = Version.parse(versionText); assertEquals(versionText, version.getFullVersion()); assertEquals(1, version.getMajor()); assertEquals(2, version.getMinor()); assertEquals(0, version.getPatch()); assertTrue(version.isDevelopmentVersion()); } @Test public void versionThreeDigitDevVersion() { String versionText = "1.2.3dev"; Version version = Version.parse(versionText); assertEquals(versionText, version.getFullVersion()); assertEquals(1, version.getMajor()); assertEquals(2, version.getMinor()); assertEquals(3, version.getPatch()); assertTrue(version.isDevelopmentVersion()); } @Test public void validVersionIsNotNewerThanUnknownVersion() { // Reason: unknown version should only happen for developer builds where we don't want an update notification Version unknownVersion = Version.parse(BuildInfo.UNKNOWN_VERSION); Version validVersion = Version.parse("4.2"); assertFalse(validVersion.isNewerThan(unknownVersion)); } @Test public void unknownVersionIsNotNewerThanValidVersion() { Version unknownVersion = Version.parse(BuildInfo.UNKNOWN_VERSION); Version validVersion = Version.parse("4.2"); assertFalse(unknownVersion.isNewerThan(validVersion)); } @Test public void versionNewerThan() { Version olderVersion = Version.parse("2.4"); Version newerVersion = Version.parse("4.2"); assertTrue(newerVersion.isNewerThan(olderVersion)); } @Test public void versionNotNewerThan() { Version olderVersion = Version.parse("2.4"); Version newerVersion = Version.parse("4.2"); assertFalse(olderVersion.isNewerThan(newerVersion)); } @Test public void versionNotNewerThanSameVersion() { Version version1 = Version.parse("4.2"); Version version2 = Version.parse("4.2"); assertFalse(version1.isNewerThan(version2)); } @Test public void versionNewerThanDevTwoDigits() { Version older = Version.parse("4.2"); Version newer = Version.parse("4.3dev"); assertTrue(newer.isNewerThan(older)); } @Test public void versionNewerThanDevVersion() { Version older = Version.parse("1.2dev"); Version newer = Version.parse("1.2"); assertTrue(newer.isNewerThan(older)); assertFalse(older.isNewerThan(newer)); } @Test public void versionNewerThanDevThreeDigits() { Version older = Version.parse("4.2.1"); Version newer = Version.parse("4.3dev"); assertTrue(newer.isNewerThan(older)); } @Test public void versionNewerMinor() { Version older = Version.parse("4.1"); Version newer = Version.parse("4.2.1"); assertTrue(newer.isNewerThan(older)); } @Test public void versionNotNewerMinor() { Version older = Version.parse("4.1"); Version newer = Version.parse("4.2.1"); assertFalse(older.isNewerThan(newer)); } @Test public void versionNewerPatch() { Version older = Version.parse("4.2.1"); Version newer = Version.parse("4.2.2"); assertTrue(newer.isNewerThan(older)); } @Test public void versionNotNewerPatch() { Version older = Version.parse("4.2.1"); Version newer = Version.parse("4.2.2"); assertFalse(older.isNewerThan(newer)); } @Test public void versionNewerDevelopmentNumber() { Version older = Version.parse("4.2-beta1"); Version newer = Version.parse("4.2-beta2"); assertFalse(older.isNewerThan(newer)); } @Test public void versionNotNewerThanSameVersionWithBeta() { Version version1 = Version.parse("4.2-beta2"); Version version2 = Version.parse("4.2-beta2"); assertFalse(version2.isNewerThan(version1)); } @Test public void equalVersionsNotNewer() { Version version1 = Version.parse("4.2.2"); Version version2 = Version.parse("4.2.2"); assertFalse(version1.isNewerThan(version2)); } @Test public void changelogOfDevelopmentVersionWithDash() { Version version = Version.parse("4.0-dev"); assertEquals("https://github.com/JabRef/jabref/blob/main/CHANGELOG.md#unreleased", version.getChangelogUrl()); } @Test public void changelogOfDevelopmentVersionWithoutDash() { Version version = Version.parse("3.7dev"); assertEquals("https://github.com/JabRef/jabref/blob/main/CHANGELOG.md#unreleased", version.getChangelogUrl()); } @Test public void changelogOfDevelopmentStageSubNumber() { Version version1 = Version.parse("4.0"); Version version2 = Version.parse("4.0-beta"); Version version3 = Version.parse("4.0-beta2"); Version version4 = Version.parse("4.0-beta3"); assertEquals("https://github.com/JabRef/jabref/blob/v4.0/CHANGELOG.md", version1.getChangelogUrl()); assertEquals("https://github.com/JabRef/jabref/blob/v4.0-beta/CHANGELOG.md", version2.getChangelogUrl()); assertEquals("https://github.com/JabRef/jabref/blob/v4.0-beta2/CHANGELOG.md", version3.getChangelogUrl()); assertEquals("https://github.com/JabRef/jabref/blob/v4.0-beta3/CHANGELOG.md", version4.getChangelogUrl()); } @Test public void changelogWithTwoDigits() { Version version = Version.parse("3.4"); assertEquals("https://github.com/JabRef/jabref/blob/v3.4/CHANGELOG.md", version.getChangelogUrl()); } @Test public void changelogWithThreeDigits() { Version version = Version.parse("3.4.1"); assertEquals("https://github.com/JabRef/jabref/blob/v3.4.1/CHANGELOG.md", version.getChangelogUrl()); } @Test public void versionNull() { String versionText = null; Version version = Version.parse(versionText); assertEquals(BuildInfo.UNKNOWN_VERSION, version.getFullVersion()); } @Test public void versionEmpty() { String versionText = ""; Version version = Version.parse(versionText); assertEquals(BuildInfo.UNKNOWN_VERSION, version.getFullVersion()); } @Test public void betaNewerThanAlpha() { Version older = Version.parse("2.7-alpha"); Version newer = Version.parse("2.7-beta"); assertTrue(newer.isNewerThan(older)); } @Test public void stableNewerThanBeta() { Version older = Version.parse("2.8-alpha"); Version newer = Version.parse("2.8"); assertTrue(newer.isNewerThan(older)); } @Test public void alphaShouldBeUpdatedToBeta() { Version alpha = Version.parse("2.8-alpha"); Version beta = Version.parse("2.8-beta"); assertTrue(alpha.shouldBeUpdatedTo(beta)); } @Test public void betaShouldBeUpdatedToStable() { Version beta = Version.parse("2.8-beta"); Version stable = Version.parse("2.8"); assertTrue(beta.shouldBeUpdatedTo(stable)); } @Test public void stableShouldNotBeUpdatedToAlpha() { Version stable = Version.parse("2.8"); Version alpha = Version.parse("2.9-alpha"); assertFalse(stable.shouldBeUpdatedTo(alpha)); } @Test public void stableShouldNotBeUpdatedToBeta() { Version stable = Version.parse("3.8.2"); Version beta = Version.parse("4.0-beta"); assertFalse(stable.shouldBeUpdatedTo(beta)); } @Test public void alphaShouldBeUpdatedToStables() { Version alpha = Version.parse("2.8-alpha"); Version stable = Version.parse("2.8"); List<Version> availableVersions = Arrays.asList(Version.parse("2.8-beta"), stable); assertEquals(Optional.of(stable), alpha.shouldBeUpdatedTo(availableVersions)); } @Test public void ciSuffixShouldBeRemoved() { Version v50ci = Version.parse("5.0-ci.1"); assertEquals("5.0", v50ci.getFullVersion()); } @Test public void ciSuffixShouldBeRemovedIfDateIsPresent() { Version v50ci = Version.parse("5.0-ci.1--2020-03-06--289142f"); assertEquals("5.0--2020-03-06--289142f", v50ci.getFullVersion()); } @Test @FetcherTest @DisabledOnCIServer("GitHub puts a low rate limit on unauthenticated calls") public void getAllAvailableVersionsReturnsSomething() throws Exception { assertNotEquals(Collections.emptyList(), Version.getAllAvailableVersions()); } }
11,561
33.410714
118
java
null
jabref-main/src/test/java/org/jabref/logic/util/io/BackupFileUtilTest.java
package org.jabref.logic.util.io; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.jabref.logic.util.BackupFileType; import org.jabref.logic.util.OS; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import org.mockito.MockedStatic; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; public class BackupFileUtilTest { Path backupDir; @BeforeEach void setup(@TempDir Path tempDir) { backupDir = tempDir.resolve("backup"); } @Test void uniqueFilePrefix() { // We cannot test for a concrete hash code, because hashing implementation differs from environment to environment assertNotEquals("", BackupFileUtil.getUniqueFilePrefix(Path.of("test.bib"))); } @Test void getPathOfBackupFileAndCreateDirectoryReturnsAppDirectoryInCaseOfNoError() { String start = OS.getNativeDesktop().getBackupDirectory().toString(); backupDir = OS.getNativeDesktop().getBackupDirectory(); String result = BackupFileUtil.getPathForNewBackupFileAndCreateDirectory(Path.of("test.bib"), BackupFileType.BACKUP, backupDir).toString(); // We just check the prefix assertEquals(start, result.substring(0, start.length())); } @Test void getPathOfBackupFileAndCreateDirectoryReturnsSameDirectoryInCaseOfException() { backupDir = OS.getNativeDesktop().getBackupDirectory(); try (MockedStatic<Files> files = Mockito.mockStatic(Files.class, Answers.RETURNS_DEEP_STUBS)) { files.when(() -> Files.createDirectories(OS.getNativeDesktop().getBackupDirectory())) .thenThrow(new IOException()); Path testPath = Path.of("tmp", "test.bib"); Path result = BackupFileUtil.getPathForNewBackupFileAndCreateDirectory(testPath, BackupFileType.BACKUP, backupDir); // The intended fallback behavior is to put the .bak file in the same directory as the .bib file assertEquals(Path.of("tmp", "test.bib.bak"), result); } } }
2,236
38.245614
147
java
null
jabref-main/src/test/java/org/jabref/logic/util/io/CitationKeyBasedFileFinderTest.java
package org.jabref.logic.util.io; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class CitationKeyBasedFileFinderTest { private BibEntry entry; private Path rootDir; private Path graphicsDir; private Path pdfsDir; private Path jpgFile; private Path pdfFile; @BeforeEach void setUp(@TempDir Path temporaryFolder) throws IOException { entry = new BibEntry(StandardEntryType.Article); entry.setCitationKey("HipKro03"); rootDir = temporaryFolder; Path subDir = Files.createDirectory(rootDir.resolve("Organization Science")); pdfsDir = Files.createDirectory(rootDir.resolve("pdfs")); Files.createFile(subDir.resolve("HipKro03 - Hello.pdf")); Files.createFile(rootDir.resolve("HipKro03 - Hello.pdf")); Path pdfSubSubDir = Files.createDirectory(pdfsDir.resolve("sub")); pdfFile = Files.createFile(pdfSubSubDir.resolve("HipKro03-sub.pdf")); Files.createDirectory(rootDir.resolve("2002")); Path dir2003 = Files.createDirectory(rootDir.resolve("2003")); Files.createFile(dir2003.resolve("Paper by HipKro03.pdf")); Path dirTest = Files.createDirectory(rootDir.resolve("test")); Files.createFile(dirTest.resolve(".TEST")); Files.createFile(dirTest.resolve("TEST[")); Files.createFile(dirTest.resolve("TE.ST")); Files.createFile(dirTest.resolve("foo.dat")); graphicsDir = Files.createDirectory(rootDir.resolve("graphicsDir")); Path graphicsSubDir = Files.createDirectories(graphicsDir.resolve("subDir")); jpgFile = Files.createFile(graphicsSubDir.resolve("HipKro03 test.jpg")); Files.createFile(graphicsSubDir.resolve("HipKro03 test.png")); } @Test void findAssociatedFilesInSubDirectories() throws Exception { List<String> extensions = Arrays.asList("jpg", "pdf"); List<Path> dirs = Arrays.asList(graphicsDir, pdfsDir); FileFinder fileFinder = new CitationKeyBasedFileFinder(false); List<Path> results = fileFinder.findAssociatedFiles(entry, dirs, extensions); assertEquals(Arrays.asList(jpgFile, pdfFile), results); } @Test void findAssociatedFilesIgnoresFilesStartingWithKeyButContinueWithText() throws Exception { Files.createFile(pdfsDir.resolve("HipKro03a - Hello second paper.pdf")); FileFinder fileFinder = new CitationKeyBasedFileFinder(false); List<Path> results = fileFinder.findAssociatedFiles(entry, Collections.singletonList(pdfsDir), Collections.singletonList("pdf")); assertEquals(Collections.singletonList(pdfFile), results); } @Test void findAssociatedFilesFindsFilesStartingWithKey() throws Exception { Path secondPdfFile = Files.createFile(pdfsDir.resolve("HipKro03_Hello second paper.pdf")); FileFinder fileFinder = new CitationKeyBasedFileFinder(false); List<Path> results = fileFinder.findAssociatedFiles(entry, Collections.singletonList(pdfsDir), Collections.singletonList("pdf")); assertEquals(Arrays.asList(secondPdfFile, pdfFile), results); } @Test void findAssociatedFilesInNonExistingDirectoryFindsNothing() throws Exception { List<String> extensions = Arrays.asList("jpg", "pdf"); List<Path> dirs = Collections.singletonList(rootDir.resolve("asdfasdf/asdfasdf")); CitationKeyBasedFileFinder fileFinder = new CitationKeyBasedFileFinder(false); List<Path> results = fileFinder.findAssociatedFiles(entry, dirs, extensions); assertEquals(Collections.emptyList(), results); } @Test void findAssociatedFilesWithUnsafeCharactersStartWithSearch() throws Exception { BibEntry entryWithUnsafeCitationKey = new BibEntry(StandardEntryType.Article); entryWithUnsafeCitationKey.setCitationKey("?test"); Path testFile = Files.createFile(pdfsDir.resolve("_test_file.pdf")); FileFinder fileFinder = new CitationKeyBasedFileFinder(false); List<Path> results = fileFinder.findAssociatedFiles(entryWithUnsafeCitationKey, Collections.singletonList(pdfsDir), Collections.singletonList("pdf")); assertEquals(Collections.singletonList(testFile), results); } @Test void findAssociatedFilesWithUnsafeCharactersExactSearch() throws Exception { BibEntry entryWithUnsafeCitationKey = new BibEntry(StandardEntryType.Article); entryWithUnsafeCitationKey.setCitationKey("test:test/*test?"); Path testFile = Files.createFile(pdfsDir.resolve("test_test__test_.pdf")); FileFinder fileFinder = new CitationKeyBasedFileFinder(true); List<Path> results = fileFinder.findAssociatedFiles(entryWithUnsafeCitationKey, Collections.singletonList(pdfsDir), Collections.singletonList("pdf")); assertNotEquals(Collections.singletonList(testFile), results); } }
5,333
40.030769
158
java
null
jabref-main/src/test/java/org/jabref/logic/util/io/FileHistoryTest.java
package org.jabref.logic.util.io; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class FileHistoryTest { private FileHistory history; @BeforeEach void setUp() { history = FileHistory.of(Collections.emptyList()); } @Test void newItemsAreAddedInRightOrder() { history.newFile(Path.of("aa")); history.newFile(Path.of("bb")); assertEquals(Arrays.asList(Path.of("bb"), Path.of("aa")), history); } @Test void itemsAlreadyInListIsMovedToTop() { history.newFile(Path.of("aa")); history.newFile(Path.of("bb")); history.newFile(Path.of("aa")); assertEquals(Arrays.asList(Path.of("aa"), Path.of("bb")), history); } @Test void removeItemsLeavesOtherItemsInRightOrder() { history.newFile(Path.of("aa")); history.newFile(Path.of("bb")); history.newFile(Path.of("cc")); history.removeItem(Path.of("bb")); assertEquals(Arrays.asList(Path.of("cc"), Path.of("aa")), history); } @Test void sizeTest() { assertEquals(0, history.size()); history.newFile(Path.of("aa")); assertEquals(1, history.size()); history.newFile(Path.of("bb")); assertEquals(2, history.size()); } @Test void isEmptyTest() { assertTrue(history.isEmpty()); history.newFile(Path.of("aa")); assertFalse(history.isEmpty()); } @Test void getFileAtTest() { history.newFile(Path.of("aa")); history.newFile(Path.of("bb")); history.newFile(Path.of("cc")); assertEquals(Path.of("bb"), history.get(1)); } }
1,941
25.243243
75
java
null
jabref-main/src/test/java/org/jabref/logic/util/io/FileNameUniquenessTest.java
package org.jabref.logic.util.io; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.jabref.gui.DialogService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; public class FileNameUniquenessTest { @TempDir protected Path tempDir; @Test public void testGetNonOverWritingFileNameReturnsSameName() throws IOException { assertFalse(Files.exists(tempDir.resolve("sameFile.txt"))); String outputFileName = FileNameUniqueness.getNonOverWritingFileName(tempDir, "sameFile.txt"); assertEquals("sameFile.txt", outputFileName); } @Test public void testGetNonOverWritingFileNameReturnsUniqueNameOver1Conflict() throws IOException { Path dummyFilePath1 = tempDir.resolve("differentFile.txt"); Files.createFile(dummyFilePath1); String outputFileName = FileNameUniqueness.getNonOverWritingFileName(tempDir, "differentFile.txt"); assertEquals("differentFile (1).txt", outputFileName); } @Test public void testGetNonOverWritingFileNameReturnsUniqueNameOverNConflicts() throws IOException { Path dummyFilePath1 = tempDir.resolve("manyfiles.txt"); Path dummyFilePath2 = tempDir.resolve("manyfiles (1).txt"); Files.createFile(dummyFilePath1); Files.createFile(dummyFilePath2); String outputFileName = FileNameUniqueness.getNonOverWritingFileName(tempDir, "manyfiles.txt"); assertEquals("manyfiles (2).txt", outputFileName); } @Test public void testIsDuplicatedFileWithNoSimilarNames() throws IOException { DialogService dialogService = mock(DialogService.class); String filename1 = "file1.txt"; Path filePath1 = tempDir.resolve(filename1); Files.createFile(filePath1); boolean isDuplicate = FileNameUniqueness.isDuplicatedFile(tempDir, filePath1, dialogService); assertFalse(isDuplicate); } @Test public void testIsDuplicatedFileWithOneSimilarNames() throws IOException { DialogService dialogService = mock(DialogService.class); String filename1 = "file.txt"; String filename2 = "file (1).txt"; Path filePath1 = tempDir.resolve(filename1); Path filePath2 = tempDir.resolve(filename2); Files.createFile(filePath1); Files.createFile(filePath2); boolean isDuplicate = FileNameUniqueness.isDuplicatedFile(tempDir, filePath2, dialogService); assertTrue(isDuplicate); } @Test public void testTaseDuplicateMarksReturnsOrignalFileName1() throws IOException { String fileName1 = "abc def (1)"; String fileName2 = FileNameUniqueness.eraseDuplicateMarks(fileName1); assertEquals("abc def", fileName2); } @Test public void testTaseDuplicateMarksReturnsOrignalFileName2() throws IOException { String fileName1 = "abc (def) gh (1)"; String fileName2 = FileNameUniqueness.eraseDuplicateMarks(fileName1); assertEquals("abc (def) gh", fileName2); } @Test public void testTaseDuplicateMarksReturnsSameName1() throws IOException { String fileName1 = "abc def (g)"; String fileName2 = FileNameUniqueness.eraseDuplicateMarks(fileName1); assertEquals("abc def (g)", fileName2); } @Test public void testTaseDuplicateMarksReturnsSameName2() throws IOException { String fileName1 = "abc def"; String fileName2 = FileNameUniqueness.eraseDuplicateMarks(fileName1); assertEquals("abc def", fileName2); } }
3,807
35.266667
107
java
null
jabref-main/src/test/java/org/jabref/logic/util/io/FileUtilTest.java
package org.jabref.logic.util.io; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.util.OS; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @AllowedToUseLogic("uses OS from logic package") class FileUtilTest { private final Path nonExistingTestPath = Path.of("nonExistingTestPath"); private Path existingTestFile; private Path otherExistingTestFile; private Path rootDir; @BeforeEach void setUpViewModel(@TempDir Path temporaryFolder) throws IOException { rootDir = temporaryFolder; Path subDir = rootDir.resolve("1"); Files.createDirectory(subDir); existingTestFile = subDir.resolve("existingTestFile.txt"); Files.createFile(existingTestFile); Files.write(existingTestFile, "existingTestFile.txt".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); otherExistingTestFile = subDir.resolve("otherExistingTestFile.txt"); Files.createFile(otherExistingTestFile); Files.write(otherExistingTestFile, "otherExistingTestFile.txt".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); } @Test void extensionBakAddedCorrectly() { assertEquals(Path.of("demo.bib.bak"), FileUtil.addExtension(Path.of("demo.bib"), ".bak")); } @Test void extensionBakAddedCorrectlyToAFileContainedInTmpDirectory() { assertEquals(Path.of("tmp", "demo.bib.bak"), FileUtil.addExtension(Path.of("tmp", "demo.bib"), ".bak")); } @Test void testGetLinkedFileNameDefaultFullTitle() { String fileNamePattern = "[citationkey] - [fulltitle]"; BibEntry entry = new BibEntry(); entry.setCitationKey("1234"); entry.setField(StandardField.TITLE, "mytitle"); assertEquals("1234 - mytitle", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetLinkedFileNameDefaultWithLowercaseTitle() { String fileNamePattern = "[citationkey] - [title:lower]"; BibEntry entry = new BibEntry(); entry.setCitationKey("1234"); entry.setField(StandardField.TITLE, "mytitle"); assertEquals("1234 - mytitle", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetLinkedFileNameBibTeXKey() { String fileNamePattern = "[citationkey]"; BibEntry entry = new BibEntry(); entry.setCitationKey("1234"); entry.setField(StandardField.TITLE, "mytitle"); assertEquals("1234", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetLinkedFileNameNoPattern() { String fileNamePattern = ""; BibEntry entry = new BibEntry(); entry.setCitationKey("1234"); entry.setField(StandardField.TITLE, "mytitle"); assertEquals("1234", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetDefaultFileNameNoPatternNoBibTeXKey() { String fileNamePattern = ""; BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "mytitle"); assertEquals("default", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetLinkedFileNameGetKeyIfEmptyField() { String fileNamePattern = "[title]"; BibEntry entry = new BibEntry(); entry.setCitationKey("1234"); assertEquals("1234", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetLinkedFileNameGetDefaultIfEmptyFieldNoKey() { String fileNamePattern = "[title]"; BibEntry entry = new BibEntry(); assertEquals("default", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetLinkedFileNameByYearAuthorFirstpage() { String fileNamePattern = "[year]_[auth]_[firstpage]"; BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "O. Kitsune"); entry.setField(StandardField.YEAR, "1868"); entry.setField(StandardField.PAGES, "567-579"); assertEquals("1868_Kitsune_567", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern)); } @Test void testGetFileExtensionSimpleFile() { assertEquals("pdf", FileUtil.getFileExtension(Path.of("test.pdf")).get()); } @Test void testGetFileExtensionMultipleDotsFile() { assertEquals("pdf", FileUtil.getFileExtension(Path.of("te.st.PdF")).get()); } @Test void testGetFileExtensionNoExtensionFile() { assertFalse(FileUtil.getFileExtension(Path.of("JustTextNotASingleDot")).isPresent()); } @Test void testGetFileExtensionNoExtension2File() { assertFalse(FileUtil.getFileExtension(Path.of(".StartsWithADotIsNotAnExtension")).isPresent()); } @Test void getFileExtensionWithSimpleString() { assertEquals("pdf", FileUtil.getFileExtension("test.pdf").get()); } @Test void getFileExtensionTrimsAndReturnsInLowercase() { assertEquals("pdf", FileUtil.getFileExtension("test.PdF ").get()); } @Test void getFileExtensionWithMultipleDotsString() { assertEquals("pdf", FileUtil.getFileExtension("te.st.PdF ").get()); } @Test void getFileExtensionWithNoDotReturnsEmptyExtension() { assertEquals(Optional.empty(), FileUtil.getFileExtension("JustTextNotASingleDot")); } @Test void getFileExtensionWithDotAtStartReturnsEmptyExtension() { assertEquals(Optional.empty(), FileUtil.getFileExtension(".StartsWithADotIsNotAnExtension")); } @Test void getFileNameWithSimpleString() { assertEquals("test", FileUtil.getBaseName("test.pdf")); } @Test void getFileNameWithMultipleDotsString() { assertEquals("te.st", FileUtil.getBaseName("te.st.PdF ")); } @Test void uniquePathSubstrings() { List<String> paths = List.of("C:/uniquefile.bib", "C:/downloads/filename.bib", "C:/mypaper/bib/filename.bib", "C:/external/mypaper/bib/filename.bib", ""); List<String> uniqPath = List.of("uniquefile.bib", "downloads/filename.bib", "C:/mypaper/bib/filename.bib", "external/mypaper/bib/filename.bib", ""); List<String> result = FileUtil.uniquePathSubstrings(paths); assertEquals(uniqPath, result); } @Test void testUniquePathFragmentWithSameSuffix() { List<String> dirs = List.of("/users/jabref/bibliography.bib", "/users/jabref/koppor-bibliograsphy.bib"); assertEquals(Optional.of("bibliography.bib"), FileUtil.getUniquePathFragment(dirs, Path.of("/users/jabref/bibliography.bib"))); } @Test void testUniquePathFragmentWithSameSuffixAndLongerName() { List<String> dirs = List.of("/users/jabref/bibliography.bib", "/users/jabref/koppor-bibliography.bib"); assertEquals(Optional.of("koppor-bibliography.bib"), FileUtil.getUniquePathFragment(dirs, Path.of("/users/jabref/koppor-bibliography.bib"))); } @Test void testCopyFileFromEmptySourcePathToEmptyDestinationPathWithOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, nonExistingTestPath, true)); } @Test void testCopyFileFromEmptySourcePathToEmptyDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, nonExistingTestPath, false)); } @Test void testCopyFileFromEmptySourcePathToExistDestinationPathWithOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, existingTestFile, true)); } @Test void testCopyFileFromEmptySourcePathToExistDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(nonExistingTestPath, existingTestFile, false)); } @Test void testCopyFileFromExistSourcePathToExistDestinationPathWithOverrideExistFile() { assertTrue(FileUtil.copyFile(existingTestFile, existingTestFile, true)); } @Test void testCopyFileFromExistSourcePathToExistDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(existingTestFile, existingTestFile, false)); } @Test void testCopyFileFromExistSourcePathToOtherExistDestinationPathWithOverrideExistFile() { assertTrue(FileUtil.copyFile(existingTestFile, otherExistingTestFile, true)); } @Test void testCopyFileFromExistSourcePathToOtherExistDestinationPathWithoutOverrideExistFile() { assertFalse(FileUtil.copyFile(existingTestFile, otherExistingTestFile, false)); } @Test void testCopyFileSuccessfulWithOverrideExistFile() throws IOException { Path subDir = rootDir.resolve("2"); Files.createDirectory(subDir); Path temp = subDir.resolve("existingTestFile.txt"); Files.createFile(temp); FileUtil.copyFile(existingTestFile, temp, true); assertEquals(Files.readAllLines(existingTestFile, StandardCharsets.UTF_8), Files.readAllLines(temp, StandardCharsets.UTF_8)); } @Test void testCopyFileSuccessfulWithoutOverrideExistFile() throws IOException { Path subDir = rootDir.resolve("2"); Files.createDirectory(subDir); Path temp = subDir.resolve("existingTestFile.txt"); Files.createFile(temp); FileUtil.copyFile(existingTestFile, temp, false); assertNotEquals(Files.readAllLines(existingTestFile, StandardCharsets.UTF_8), Files.readAllLines(temp, StandardCharsets.UTF_8)); } @Test void validFilenameShouldNotAlterValidFilename() { assertEquals("somename.pdf", FileUtil.getValidFileName("somename.pdf")); } @Test void validFilenameWithoutExtension() { assertEquals("somename", FileUtil.getValidFileName("somename")); } @Test void validFilenameShouldBeMaximum255Chars() { String longestValidFilename = Stream.generate(() -> String.valueOf('1')).limit(FileUtil.MAXIMUM_FILE_NAME_LENGTH - 4).collect(Collectors.joining()) + ".pdf"; String longerFilename = Stream.generate(() -> String.valueOf('1')).limit(260).collect(Collectors.joining()) + ".pdf"; assertEquals(longestValidFilename, FileUtil.getValidFileName(longerFilename)); } @Test void invalidFilenameWithoutExtension() { String longestValidFilename = Stream.generate(() -> String.valueOf('1')).limit(FileUtil.MAXIMUM_FILE_NAME_LENGTH).collect(Collectors.joining()); String longerFilename = Stream.generate(() -> String.valueOf('1')).limit(260).collect(Collectors.joining()); assertEquals(longestValidFilename, FileUtil.getValidFileName(longerFilename)); } @Test void testGetLinkedDirNameDefaultFullTitle() { String fileDirPattern = "PDF/[year]/[auth]/[citationkey] - [fulltitle]"; BibEntry entry = new BibEntry(); entry.setCitationKey("1234"); entry.setField(StandardField.TITLE, "mytitle"); entry.setField(StandardField.YEAR, "1998"); entry.setField(StandardField.AUTHOR, "A. Åuthör and Author, Bete"); assertEquals("PDF/1998/Åuthör/1234 - mytitle", FileUtil.createDirNameFromPattern(null, entry, fileDirPattern)); } @Test void testGetLinkedDirNamePatternEmpty() { BibEntry entry = new BibEntry(); entry.setCitationKey("1234"); entry.setField(StandardField.TITLE, "mytitle"); entry.setField(StandardField.YEAR, "1998"); entry.setField(StandardField.AUTHOR, "A. Åuthör and Author, Bete"); assertEquals("", FileUtil.createDirNameFromPattern(null, entry, "")); } @Test void testIsBibFile() throws IOException { Path bibFile = Files.createFile(rootDir.resolve("test.bib")); assertTrue(FileUtil.isBibFile(bibFile)); } @Test void testIsNotBibFile() throws IOException { Path bibFile = Files.createFile(rootDir.resolve("test.pdf")); assertFalse(FileUtil.isBibFile(bibFile)); } @Test void testFindinPath() { Optional<Path> resultPath1 = FileUtil.findSingleFileRecursively("existingTestFile.txt", rootDir); assertEquals(resultPath1.get().toString(), existingTestFile.toString()); } @Test void testFindInListOfPath() { // due to the added workaround for old JabRef behavior as both path starts with the same name they are considered equal List<Path> paths = List.of(existingTestFile, otherExistingTestFile, rootDir); List<Path> resultPaths = List.of(existingTestFile); List<Path> result = FileUtil.findListOfFiles("existingTestFile.txt", paths); assertEquals(resultPaths, result); } @Test public void extractFileExtension() { final String filePath = FileUtilTest.class.getResource("pdffile.pdf").getPath(); assertEquals(Optional.of("pdf"), FileUtil.getFileExtension(filePath)); } @Test public void fileExtensionFromUrl() { final String filePath = "https://link.springer.com/content/pdf/10.1007%2Fs40955-018-0121-9.pdf"; assertEquals(Optional.of("pdf"), FileUtil.getFileExtension(filePath)); } @Test public void testFileNameEmpty() { Path path = Path.of("/"); assertEquals(Optional.of(path), FileUtil.find("", path)); } @ParameterizedTest @ValueSource(strings = {"*", "?", ">", "\""}) public void testFileNameIllegal(String fileName) { Path path = Path.of("/"); assertEquals(Optional.empty(), FileUtil.find(fileName, path)); } @Test public void testFindsFileInDirectory(@TempDir Path temp) throws Exception { Path firstFilePath = temp.resolve("files"); Files.createDirectories(firstFilePath); Path firstFile = Files.createFile(firstFilePath.resolve("test.pdf")); assertEquals(Optional.of(firstFile), FileUtil.find("test.pdf", temp.resolve("files"))); } @Test public void testFindsFileStartingWithTheSameDirectory(@TempDir Path temp) throws Exception { Path firstFilePath = temp.resolve("files"); Files.createDirectories(firstFilePath); Path firstFile = Files.createFile(firstFilePath.resolve("test.pdf")); assertEquals(Optional.of(firstFile), FileUtil.find("files/test.pdf", temp.resolve("files"))); } @Test public void testDoesNotFindsFileStartingWithTheSameDirectoryHasASubdirectory(@TempDir Path temp) throws Exception { Path firstFilesPath = temp.resolve("files"); Path secondFilesPath = firstFilesPath.resolve("files"); Files.createDirectories(secondFilesPath); Path testFile = secondFilesPath.resolve("test.pdf"); Files.createFile(testFile); assertEquals(Optional.of(testFile.toAbsolutePath()), FileUtil.find("files/test.pdf", firstFilesPath)); } public void testCTemp() { String fileName = "c:\\temp.pdf"; if (OS.WINDOWS) { assertFalse(FileUtil.detectBadFileName(fileName)); } else { assertTrue(FileUtil.detectBadFileName(fileName)); } } @ParameterizedTest @ValueSource(strings = {"/mnt/tmp/test.pdf"}) public void legalPaths(String fileName) { assertFalse(FileUtil.detectBadFileName(fileName)); } @ParameterizedTest @ValueSource(strings = {"te{}mp.pdf"}) public void illegalPaths(String fileName) { assertTrue(FileUtil.detectBadFileName(fileName)); } }
16,402
36.62156
165
java
null
jabref-main/src/test/java/org/jabref/logic/util/io/RegExpBasedFileFinderTest.java
package org.jabref.logic.util.io; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class RegExpBasedFileFinderTest { private static final List<String> PDF_EXTENSION = Collections.singletonList("pdf"); private static final List<String> FILE_NAMES = List.of( "ACM_IEEE-CS.pdf", "pdfInDatabase.pdf", "Regexp from [A-Z].pdf", "directory/subdirectory/2003_Hippel_209.pdf", "directory/subdirectory/2017_Gražulis_726.pdf", "directory/subdirectory/pdfInSubdirectory.pdf", "directory/subdirectory/GUO ea - INORG CHEM COMMUN 2010 - Ferroelectric Metal Organic Framework (MOF).pdf" ); private Path directory; private BibEntry entry; @BeforeEach void setUp(@TempDir Path tempDir) throws Exception { entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setCitationKey("HipKro03"); entry.setField(StandardField.AUTHOR, "Eric von Hippel and Georg von Krogh"); entry.setField(StandardField.TITLE, "Open Source Software and the \"Private-Collective\" Innovation Model: Issues for Organization Science"); entry.setField(StandardField.JOURNAL, "Organization Science"); entry.setField(StandardField.YEAR, "2003"); entry.setField(StandardField.VOLUME, "14"); entry.setField(StandardField.PAGES, "209--223"); entry.setField(StandardField.NUMBER, "2"); entry.setField(StandardField.ADDRESS, "Institute for Operations Research and the Management Sciences (INFORMS), Linthicum, Maryland, USA"); entry.setField(StandardField.DOI, "http://dx.doi.org/10.1287/orsc.14.2.209.14992"); entry.setField(StandardField.ISSN, "1526-5455"); entry.setField(StandardField.PUBLISHER, "INFORMS"); // Create default directories and files directory = tempDir; Files.createDirectories(directory.resolve("directory/subdirectory")); for (String fileName : FILE_NAMES) { Files.createFile(directory.resolve(fileName)); } } @Test void testFindFiles() throws Exception { // given BibEntry localEntry = new BibEntry(StandardEntryType.Article).withCitationKey("pdfInDatabase"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[citationkey].*\\\\.[extension]", ','); // when List<Path> result = fileFinder.findAssociatedFiles(localEntry, List.of(directory), PDF_EXTENSION); List<Path> expected = List.of(directory.resolve("pdfInDatabase.pdf")); // then assertEquals(expected, result); } @Test void testYearAuthFirstPageFindFiles() throws Exception { // given RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[year]_[auth]_[firstpage].*\\\\.[extension]", ','); // when List<Path> result = fileFinder.findAssociatedFiles(entry, List.of(directory), PDF_EXTENSION); List<Path> expected = List.of(directory.resolve("directory/subdirectory/2003_Hippel_209.pdf")); // then assertEquals(expected, result); } @Test void findAssociatedFilesFindFileContainingBracketsFromBracketedExpression() throws Exception { var bibEntry = new BibEntry().withField(StandardField.TITLE, "Regexp from [A-Z]"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("[TITLE]\\\\.[extension]", ','); List<Path> result = fileFinder.findAssociatedFiles(bibEntry, List.of(directory), PDF_EXTENSION); List<Path> pdfFile = List.of(directory.resolve("Regexp from [A-Z].pdf")); assertEquals(pdfFile, result); } @Test void findAssociatedFilesFindCleanedFileFromBracketedExpression() throws Exception { var bibEntry = new BibEntry().withField(StandardField.JOURNAL, "ACM/IEEE-CS"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("[JOURNAL]\\\\.[extension]", ','); List<Path> result = fileFinder.findAssociatedFiles(bibEntry, List.of(directory), PDF_EXTENSION); List<Path> pdfFile = List.of(directory.resolve("ACM_IEEE-CS.pdf")); assertEquals(pdfFile, result); } @Test void findAssociatedFilesFindFileContainingParenthesizesFromBracketedExpression() throws Exception { var bibEntry = new BibEntry().withCitationKey("Guo_ICC_2010") .withField(StandardField.TITLE, "Ferroelectric Metal Organic Framework (MOF)") .withField(StandardField.AUTHOR, "Guo, M. and Cai, H.-L. and Xiong, R.-G.") .withField(StandardField.JOURNAL, "Inorganic Chemistry Communications") .withField(StandardField.YEAR, "2010"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/.*[TITLE].*\\\\.[extension]", ','); List<Path> result = fileFinder.findAssociatedFiles(bibEntry, List.of(directory), PDF_EXTENSION); List<Path> pdfFile = List.of(directory.resolve("directory/subdirectory/GUO ea - INORG CHEM COMMUN 2010 - Ferroelectric Metal Organic Framework (MOF).pdf")); assertEquals(pdfFile, result); } @Test void testAuthorWithDiacritics() throws Exception { // given BibEntry localEntry = new BibEntry(StandardEntryType.Article).withCitationKey("Grazulis2017"); localEntry.setField(StandardField.YEAR, "2017"); localEntry.setField(StandardField.AUTHOR, "Gražulis, Saulius and O. Kitsune"); localEntry.setField(StandardField.PAGES, "726--729"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[year]_[auth]_[firstpage]\\\\.[extension]", ','); // when List<Path> result = fileFinder.findAssociatedFiles(localEntry, List.of(directory), PDF_EXTENSION); List<Path> expected = List.of(directory.resolve("directory/subdirectory/2017_Gražulis_726.pdf")); // then assertEquals(expected, result); } @Test void testFindFileInSubdirectory() throws Exception { // given BibEntry localEntry = new BibEntry(StandardEntryType.Article); localEntry.setCitationKey("pdfInSubdirectory"); localEntry.setField(StandardField.YEAR, "2017"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("**/[citationkey].*\\\\.[extension]", ','); // when List<Path> result = fileFinder.findAssociatedFiles(localEntry, List.of(directory), PDF_EXTENSION); List<Path> expected = List.of(directory.resolve("directory/subdirectory/pdfInSubdirectory.pdf")); // then assertEquals(expected, result); } @Test void testFindFileNonRecursive() throws Exception { // given BibEntry localEntry = new BibEntry(StandardEntryType.Article); localEntry.setCitationKey("pdfInSubdirectory"); localEntry.setField(StandardField.YEAR, "2017"); RegExpBasedFileFinder fileFinder = new RegExpBasedFileFinder("*/[citationkey].*\\\\.[extension]", ','); // when List<Path> result = fileFinder.findAssociatedFiles(localEntry, List.of(directory), PDF_EXTENSION); // then assertTrue(result.isEmpty()); } }
7,722
42.632768
164
java
null
jabref-main/src/test/java/org/jabref/logic/util/strings/StringLengthComparatorTest.java
package org.jabref.logic.util.strings; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class StringLengthComparatorTest { private StringLengthComparator slc; @BeforeEach public void setUp() { slc = new StringLengthComparator(); } @ParameterizedTest @MethodSource("tests") void compareStringLength(int comparisonResult, String firstString, String secondString) { assertEquals(comparisonResult, slc.compare(firstString, secondString)); } private static Stream<Arguments> tests() { return Stream.of( Arguments.of(-1, "AAA", "AA"), Arguments.of(0, "AA", "AA"), Arguments.of(1, "AA", "AAA"), // empty strings Arguments.of(-1, "A", ""), Arguments.of(0, "", ""), Arguments.of(1, "", "A"), // backslash Arguments.of(-1, "\\\\", "A"), Arguments.of(0, "\\", "A"), Arguments.of(0, "\\", "\\"), Arguments.of(0, "A", "\\"), Arguments.of(1, "A", "\\\\"), // empty string + backslash Arguments.of(-1, "\\", ""), Arguments.of(1, "", "\\")); } }
1,511
29.24
93
java
null
jabref-main/src/test/java/org/jabref/logic/util/strings/StringManipulatorTest.java
package org.jabref.logic.util.strings; import java.util.stream.Stream; import org.jabref.model.util.ResultingStringState; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class StringManipulatorTest { @Test public void testCapitalizePreservesNewlines() { int caretPosition = 5; // Position of the caret, between the two ll in the first hellO" String input = "hello\n\nhELLO"; String expectedResult = "hello\n\nHello"; ResultingStringState textOutput = StringManipulator.capitalize(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testUppercasePreservesSpace() { int caretPosition = 3; // Position of the caret, between the two ll in the first hello String input = "hello hello"; String expectedResult = "helLO hello"; ResultingStringState textOutput = StringManipulator.uppercase(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testUppercasePreservesNewlines() { int caretPosition = 3; // Position of the caret, between the two ll in the first hello String input = "hello\nhello"; String expectedResult = "helLO\nhello"; ResultingStringState textOutput = StringManipulator.uppercase(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testUppercasePreservesTab() { int caretPosition = 3; // Position of the caret, between the two ll in the first hello String input = "hello\thello"; String expectedResult = "helLO\thello"; ResultingStringState textOutput = StringManipulator.uppercase(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testUppercasePreservesDoubleSpace() { int caretPosition = 5; // Position of the caret, at the first space String input = "hello hello"; String expectedResult = "hello HELLO"; ResultingStringState textOutput = StringManipulator.uppercase(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testUppercaseIgnoresTrailingWhitespace() { int caretPosition = 5; // First space String input = "hello "; String expectedResult = "hello "; ResultingStringState textOutput = StringManipulator.uppercase(caretPosition, input); assertEquals(expectedResult, textOutput.text); // Expected caret position is right after the last space, which is index 7 assertEquals(7, textOutput.caretPosition); } @Test public void testKillWordTrimsTrailingWhitespace() { int caretPosition = 5; // First space String input = "hello "; String expectedResult = "hello"; ResultingStringState textOutput = StringManipulator.killWord(caretPosition, input); assertEquals(expectedResult, textOutput.text); assertEquals(caretPosition, textOutput.caretPosition); } @Test public void testBackwardsKillWordTrimsPreceedingWhitespace() { int caretPosition = 1; // Second space String input = " hello"; // One space should be preserved since we are deleting everything preceding the second space. String expectedResult = " hello"; ResultingStringState textOutput = StringManipulator.backwardKillWord(caretPosition, input); assertEquals(expectedResult, textOutput.text); // The caret should have been moved to the start. assertEquals(0, textOutput.caretPosition); } @Test public void testUppercasePreservesMixedSpaceNewLineTab() { int caretPosition = 5; // Position of the caret, after first hello String input = "hello \n\thello"; String expectedResult = "hello \n\tHELLO"; ResultingStringState textOutput = StringManipulator.uppercase(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testLowercaseEditsTheNextWord() { int caretPosition = 5; // Position of the caret, right at the space String input = "hello HELLO"; String expectedResult = "hello hello"; ResultingStringState textOutput = StringManipulator.lowercase(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testKillWordRemovesFromPositionUpToNextWord() { int caretPosition = 3; // Position of the caret, between the two "ll in the first hello" String input = "hello hello"; String expectedResult = "hel hello"; ResultingStringState textOutput = StringManipulator.killWord(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testKillWordRemovesNextWordIfPositionIsInSpace() { int caretPosition = 5; // Position of the caret, after the first hello" String input = "hello person"; String expectedResult = "hello"; ResultingStringState textOutput = StringManipulator.killWord(caretPosition, input); assertEquals(expectedResult, textOutput.text); } @Test public void testKillPreviousWord() { int caretPosition = 8; int expectedPosition = 6; String input = "hello person"; String expectedResult = "hello rson"; ResultingStringState result = StringManipulator.backwardKillWord(caretPosition, input); assertEquals(expectedResult, result.text); assertEquals(expectedPosition, result.caretPosition); } @ParameterizedTest @MethodSource("wordBoundaryTestData") void testGetNextWordBoundary(String text, int caretPosition, int expectedPosition, StringManipulator.Direction direction) { int result = StringManipulator.getNextWordBoundary(caretPosition, text, direction); assertEquals(expectedPosition, result); } private static Stream<Arguments> wordBoundaryTestData() { return Stream.of( Arguments.of("hello person", 3, 0, StringManipulator.Direction.PREVIOUS), Arguments.of("hello person", 12, 6, StringManipulator.Direction.PREVIOUS), Arguments.of("hello person", 0, 0, StringManipulator.Direction.PREVIOUS), Arguments.of("hello person", 0, 5, StringManipulator.Direction.NEXT), Arguments.of("hello person", 5, 12, StringManipulator.Direction.NEXT), Arguments.of("hello person", 12, 12, StringManipulator.Direction.NEXT)); } }
6,805
42.075949
127
java
null
jabref-main/src/test/java/org/jabref/logic/util/strings/StringSimilarityTest.java
package org.jabref.logic.util.strings; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class StringSimilarityTest { private StringSimilarity similarityChecker = new StringSimilarity(); @ParameterizedTest(name = "a={0}, b={1}, result={2}") @CsvSource({ "'', '', true", // same empty strings "a, a, true", // same one-letter strings "a, '', true", // one string is empty and similarity < threshold (4) "'', a, true", // one string is empty and similarity < threshold (4) "abcd, '', true", // one string is empty and similarity == threshold (4) "'', abcd, true", // one string is empty and similarity == threshold (4) "abcde, '', false", // one string is empty and similarity > threshold (4) "'', abcde, false", // one string is empty and similarity > threshold (4) "abcdef, abcdef, true", // same multi-letter strings "abcdef, abc, true", // no empty strings and similarity < threshold (4) "abcdef, ab, true", // no empty strings and similarity == threshold (4) "abcdef, a, false" // no empty string sand similarity > threshold (4) }) public void testStringSimilarity(String a, String b, String expectedResult) { assertEquals(Boolean.valueOf(expectedResult), similarityChecker.isSimilar(a, b)); } }
1,501
47.451613
89
java
null
jabref-main/src/test/java/org/jabref/logic/xmp/XmpUtilReaderTest.java
package org.jabref.logic.xmp; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.schema.DublinCoreSchemaCustom; import org.jabref.model.util.DummyFileUpdateMonitor; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.DublinCoreSchema; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class XmpUtilReaderTest { private XmpPreferences xmpPreferences; private BibtexImporter testImporter; private final XmpUtilReader xmpUtilReader = new XmpUtilReader(); /** * Create a temporary PDF-file with a single empty page. */ @BeforeEach void setUp() { xmpPreferences = mock(XmpPreferences.class); // The code assumes privacy filters to be off when(xmpPreferences.shouldUseXmpPrivacyFilter()).thenReturn(false); when(xmpPreferences.getKeywordSeparator()).thenReturn(','); testImporter = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); } /** * Tests reading of dublinCore metadata. */ @Test void testReadArticleDublinCoreReadRawXmp() throws IOException, URISyntaxException { Path path = Path.of(XmpUtilShared.class.getResource("article_dublinCore_without_day.pdf").toURI()); List<XMPMetadata> meta = xmpUtilReader.readRawXmp(path); DublinCoreSchema dcSchema = DublinCoreSchemaCustom.copyDublinCoreSchema(meta.get(0).getDublinCoreSchema()); DublinCoreExtractor dcExtractor = new DublinCoreExtractor(dcSchema, xmpPreferences, new BibEntry()); Optional<BibEntry> entry = dcExtractor.extractBibtexEntry(); Path bibFile = Path.of(XmpUtilShared.class.getResource("article_dublinCore_without_day.bib").toURI()); List<BibEntry> expected = testImporter.importDatabase(bibFile).getDatabase().getEntries(); assertEquals(expected, Collections.singletonList(entry.get())); } /** * Tests reading of dublinCore metadata. */ @Test void testReadArticleDublinCoreReadXmp() throws IOException, URISyntaxException { Path pathPdf = Path.of(XmpUtilShared.class.getResource("article_dublinCore.pdf").toURI()); List<BibEntry> entries = xmpUtilReader.readXmp(pathPdf, xmpPreferences); Path bibFile = Path.of(XmpUtilShared.class.getResource("article_dublinCore.bib").toURI()); List<BibEntry> expected = testImporter.importDatabase(bibFile).getDatabase().getEntries(); expected.forEach(bibEntry -> bibEntry.setFiles(Arrays.asList( new LinkedFile("", Path.of("paper.pdf"), "PDF"), new LinkedFile("", pathPdf.toAbsolutePath(), "PDF")) )); assertEquals(expected, entries); } @Test void testReadArticleDublinCoreReadXmpPartialDate() throws IOException, URISyntaxException { Path pathPdf = Path.of(XmpUtilShared.class.getResource("article_dublinCore_partial_date.pdf").toURI()); List<BibEntry> entries = xmpUtilReader.readXmp(pathPdf, xmpPreferences); Path bibFile = Path.of(XmpUtilShared.class.getResource("article_dublinCore_partial_date.bib").toURI()); List<BibEntry> expected = testImporter.importDatabase(bibFile).getDatabase().getEntries(); expected.forEach(bibEntry -> bibEntry.setFiles(List.of( new LinkedFile("", pathPdf.toAbsolutePath(), "PDF")) )); assertEquals(expected, entries); } /** * Tests an pdf file with an empty metadata section. */ @Test void testReadEmtpyMetadata() throws IOException, URISyntaxException { List<BibEntry> entries = xmpUtilReader.readXmp(Path.of(XmpUtilShared.class.getResource("empty_metadata.pdf").toURI()), xmpPreferences); assertEquals(Collections.emptyList(), entries); } /** * Test non XMP metadata. Metadata are included in the PDInformation */ @Test void testReadPDMetadata() throws IOException, URISyntaxException { Path pathPdf = Path.of(XmpUtilShared.class.getResource("PD_metadata.pdf").toURI()); List<BibEntry> entries = xmpUtilReader.readXmp(pathPdf, xmpPreferences); Path bibFile = Path.of(XmpUtilShared.class.getResource("PD_metadata.bib").toURI()); List<BibEntry> expected = testImporter.importDatabase(bibFile).getDatabase().getEntries(); expected.forEach(bibEntry -> bibEntry.setFiles(List.of( new LinkedFile("", pathPdf.toAbsolutePath(), "PDF")) )); assertEquals(expected, entries); } /** * Tests an pdf file with metadata which has no description section. */ @Test void testReadNoDescriptionMetadata() throws IOException, URISyntaxException { List<BibEntry> entries = xmpUtilReader.readXmp(Path.of(XmpUtilShared.class.getResource("no_description_metadata.pdf").toURI()), xmpPreferences); assertEquals(Collections.emptyList(), entries); } }
5,478
39.88806
152
java
null
jabref-main/src/test/java/org/jabref/logic/xmp/XmpUtilWriterTest.java
package org.jabref.logic.xmp; import java.nio.file.Path; import java.util.List; import org.jabref.logic.exporter.XmpExporterTest; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Date; import org.jabref.model.entry.Month; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.jabref.logic.xmp.DublinCoreExtractor.DC_COVERAGE; import static org.jabref.logic.xmp.DublinCoreExtractor.DC_RIGHTS; import static org.jabref.logic.xmp.DublinCoreExtractor.DC_SOURCE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * This tests the writing to a PDF. If the creation of the RDF content should be checked, please head to {@link XmpExporterTest} */ class XmpUtilWriterTest { @TempDir private Path tempDir; private final BibEntry olly2018 = new BibEntry(StandardEntryType.Article) .withCitationKey("Olly2018") .withField(StandardField.AUTHOR, "Olly and Johannes") .withField(StandardField.TITLE, "Stefan's palace") .withField(StandardField.JOURNAL, "Test Journal") .withField(StandardField.VOLUME, "1") .withField(StandardField.NUMBER, "1") .withField(StandardField.PAGES, "1-2") .withMonth(Month.MARCH) .withField(StandardField.ISSN, "978-123-123") .withField(StandardField.NOTE, "NOTE") .withField(StandardField.ABSTRACT, "ABSTRACT") .withField(StandardField.COMMENT, "COMMENT") .withField(StandardField.DOI, "10/3212.3123") .withField(StandardField.FILE, ":article_dublinCore.pdf:PDF") .withField(StandardField.GROUPS, "NO") .withField(StandardField.HOWPUBLISHED, "online") .withField(StandardField.KEYWORDS, "k1, k2") .withField(StandardField.OWNER, "me") .withField(StandardField.REVIEW, "review") .withField(StandardField.URL, "https://www.olly2018.edu"); private final BibEntry toral2006 = new BibEntry(StandardEntryType.InProceedings) .withField(StandardField.AUTHOR, "Antonio Toral and Rafael Munoz") .withField(StandardField.TITLE, "A proposal to automatically build and maintain gazetteers for Named Entity Recognition by using Wikipedia") .withField(StandardField.BOOKTITLE, "Proceedings of EACL") .withField(StandardField.PAGES, "56--61") .withField(StandardField.EPRINTTYPE, "asdf") .withField(StandardField.OWNER, "Ich") .withField(StandardField.URL, "www.url.de"); private final BibEntry vapnik2000 = new BibEntry(StandardEntryType.Book) .withCitationKey("vapnik2000") .withField(StandardField.TITLE, "The Nature of Statistical Learning Theory") .withField(StandardField.PUBLISHER, "Springer Science + Business Media") .withField(StandardField.AUTHOR, "Vladimir N. Vapnik") .withField(StandardField.DOI, "10.1007/978-1-4757-3264-1") .withField(StandardField.OWNER, "Ich") .withField(StandardField.LANGUAGE, "English, Japanese") .withDate(new Date(2000, 5)) .withField(new UnknownField(DC_COVERAGE), "coverageField") .withField(new UnknownField(DC_SOURCE), "JabRef") .withField(new UnknownField(DC_RIGHTS), "Right To X"); private XmpPreferences xmpPreferences; @BeforeEach void setUp() { xmpPreferences = mock(XmpPreferences.class); when(xmpPreferences.getKeywordSeparator()).thenReturn(','); // The code assumes privacy filters to be off when(xmpPreferences.shouldUseXmpPrivacyFilter()).thenReturn(false); } /** * Test for writing a PDF file with a single DublinCore metadata entry. */ void singleEntryWorks(BibEntry entry) throws Exception { Path pdfFile = this.createDefaultFile("JabRef_writeSingle.pdf", tempDir); new XmpUtilWriter(xmpPreferences).writeXmp(pdfFile.toAbsolutePath(), entry, null); List<BibEntry> entriesWritten = new XmpUtilReader().readXmp(pdfFile, xmpPreferences); BibEntry entryWritten = entriesWritten.get(0); entryWritten.clearField(StandardField.FILE); entry.clearField(StandardField.FILE); assertEquals(List.of(entry), entriesWritten); } @Test void olly2018Works() throws Exception { singleEntryWorks(olly2018); } @Test void toral2006Works() throws Exception { singleEntryWorks(toral2006); } @Test void vapnik2000Works() throws Exception { singleEntryWorks(vapnik2000); } @Test void testWriteTwoBibEntries(@TempDir Path tempDir) throws Exception { Path pdfFile = this.createDefaultFile("JabRef_writeTwo.pdf", tempDir); List<BibEntry> entries = List.of(olly2018, toral2006); new XmpUtilWriter(xmpPreferences).writeXmp(pdfFile.toAbsolutePath(), entries, null); List<BibEntry> entryList = new XmpUtilReader().readXmp(pdfFile.toAbsolutePath(), xmpPreferences); // the file field is not written - and the read file field contains the PDF file name // thus, we do not need to compare entries.forEach(entry -> entry.clearField(StandardField.FILE)); entryList.forEach(entry -> entry.clearField(StandardField.FILE)); assertEquals(entries, entryList); } @Test void testWriteThreeBibEntries(@TempDir Path tempDir) throws Exception { Path pdfFile = this.createDefaultFile("JabRef_writeThree.pdf", tempDir); List<BibEntry> entries = List.of(olly2018, vapnik2000, toral2006); new XmpUtilWriter(xmpPreferences).writeXmp(pdfFile.toAbsolutePath(), entries, null); List<BibEntry> entryList = new XmpUtilReader().readXmp(pdfFile.toAbsolutePath(), xmpPreferences); // the file field is not written - and the read file field contains the PDF file name // thus, we do not need to compare entries.forEach(entry -> entry.clearField(StandardField.FILE)); entryList.forEach(entry -> entry.clearField(StandardField.FILE)); assertEquals(entries, entryList); } @Test void proctingBracesAreRemovedAtTitle(@TempDir Path tempDir) throws Exception { Path pdfFile = this.createDefaultFile("JabRef_writeBraces.pdf", tempDir); BibEntry original = new BibEntry() .withField(StandardField.TITLE, "Some {P}rotected {T}erm"); new XmpUtilWriter(xmpPreferences).writeXmp(pdfFile.toAbsolutePath(), List.of(original), null); List<BibEntry> entryList = new XmpUtilReader().readXmp(pdfFile.toAbsolutePath(), xmpPreferences); entryList.forEach(entry -> entry.clearField(StandardField.FILE)); BibEntry expected = new BibEntry() .withField(StandardField.TITLE, "Some Protected Term"); assertEquals(List.of(expected), entryList); } @Test void proctingBracesAreKeptAtPages(@TempDir Path tempDir) throws Exception { Path pdfFile = this.createDefaultFile("JabRef_writeBraces.pdf", tempDir); BibEntry original = new BibEntry() .withField(StandardField.PAGES, "{55}-{99}"); new XmpUtilWriter(xmpPreferences).writeXmp(pdfFile.toAbsolutePath(), List.of(original), null); List<BibEntry> entryList = new XmpUtilReader().readXmp(pdfFile.toAbsolutePath(), xmpPreferences); entryList.forEach(entry -> entry.clearField(StandardField.FILE)); assertEquals(List.of(original), entryList); } @Test void doubleDashAtPageNumberIsKept(@TempDir Path tempDir) throws Exception { Path pdfFile = this.createDefaultFile("JabRef_writeBraces.pdf", tempDir); BibEntry original = new BibEntry() .withField(StandardField.PAGES, "2--33"); new XmpUtilWriter(xmpPreferences).writeXmp(pdfFile.toAbsolutePath(), List.of(original), null); List<BibEntry> entryList = new XmpUtilReader().readXmp(pdfFile.toAbsolutePath(), xmpPreferences); entryList.forEach(entry -> entry.clearField(StandardField.FILE)); assertEquals(List.of(original), entryList); } @Test void singleEntry(@TempDir Path tempDir) throws Exception { Path pdfFile = this.createDefaultFile("JabRef.pdf", tempDir); new XmpUtilWriter(xmpPreferences).writeXmp(pdfFile.toAbsolutePath(), List.of(vapnik2000), null); List<BibEntry> entryList = new XmpUtilReader().readXmp(pdfFile.toAbsolutePath(), xmpPreferences); vapnik2000.clearField(StandardField.FILE); entryList.forEach(entry -> entry.clearField(StandardField.FILE)); assertEquals(List.of(vapnik2000), entryList); } /** * Creates a temporary PDF-file with a single empty page. */ private Path createDefaultFile(String fileName, Path tempDir) throws Exception { // create a default PDF Path pdfFile = tempDir.resolve(fileName); try (PDDocument pdf = new PDDocument()) { // Need a single page to open in Acrobat pdf.addPage(new PDPage()); pdf.save(pdfFile.toAbsolutePath().toString()); } return pdfFile; } }
9,578
43.553488
152
java
null
jabref-main/src/test/java/org/jabref/migrations/ConvertLegacyExplicitGroupsTest.java
package org.jabref.migrations; import java.util.Collections; import java.util.Optional; import org.jabref.logic.importer.ParserResult; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.groups.AllEntriesGroup; import org.jabref.model.groups.ExplicitGroup; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.GroupTreeNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ConvertLegacyExplicitGroupsTest { private PostOpenMigration action; private BibEntry entry; private ExplicitGroup group; @BeforeEach void setUp() throws Exception { action = new ConvertLegacyExplicitGroups(); entry = new BibEntry(); entry.setCitationKey("Entry1"); group = new ExplicitGroup("TestGroup", GroupHierarchyType.INCLUDING, ','); group.addLegacyEntryKey("Entry1"); } @Test void performActionWritesGroupMembershipInEntry() throws Exception { ParserResult parserResult = generateParserResult(GroupTreeNode.fromGroup(group)); action.performMigration(parserResult); assertEquals(Optional.of("TestGroup"), entry.getField(StandardField.GROUPS)); } @Test void performActionClearsLegacyKeys() throws Exception { ParserResult parserResult = generateParserResult(GroupTreeNode.fromGroup(group)); action.performMigration(parserResult); assertEquals(Collections.emptyList(), group.getLegacyEntryKeys()); } @Test void performActionWritesGroupMembershipInEntryForComplexGroupTree() throws Exception { GroupTreeNode root = GroupTreeNode.fromGroup(new AllEntriesGroup("")); root.addSubgroup(new ExplicitGroup("TestGroup2", GroupHierarchyType.INCLUDING, ',')); root.addSubgroup(group); ParserResult parserResult = generateParserResult(root); action.performMigration(parserResult); assertEquals(Optional.of("TestGroup"), entry.getField(StandardField.GROUPS)); } private ParserResult generateParserResult(GroupTreeNode groupRoot) { ParserResult parserResult = new ParserResult(Collections.singletonList(entry)); parserResult.getMetaData().setGroups(groupRoot); return parserResult; } }
2,383
32.577465
93
java
null
jabref-main/src/test/java/org/jabref/migrations/ConvertMarkingToGroupsTest.java
package org.jabref.migrations; import java.util.Collections; import java.util.Optional; import org.jabref.logic.groups.DefaultGroupsFactory; import org.jabref.logic.importer.ParserResult; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.groups.ExplicitGroup; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.GroupTreeNode; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ConvertMarkingToGroupsTest { @Test void performMigrationForSingleEntry() { BibEntry entry = new BibEntry() .withField(InternalField.MARKED_INTERNAL, "[Nicolas:6]"); ParserResult parserResult = new ParserResult(Collections.singleton(entry)); new ConvertMarkingToGroups().performMigration(parserResult); GroupTreeNode rootExpected = GroupTreeNode.fromGroup(DefaultGroupsFactory.getAllEntriesGroup()); GroupTreeNode markings = rootExpected.addSubgroup(new ExplicitGroup("Markings", GroupHierarchyType.INCLUDING, ',')); markings.addSubgroup(new ExplicitGroup("Nicolas:6", GroupHierarchyType.INCLUDING, ',')); assertEquals(Optional.empty(), entry.getField(InternalField.MARKED_INTERNAL)); assertEquals(Optional.of(rootExpected), parserResult.getMetaData().getGroups()); } }
1,393
38.828571
124
java
null
jabref-main/src/test/java/org/jabref/migrations/MergeReviewIntoCommentActionMigrationTest.java
package org.jabref.migrations; import java.util.Collections; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class MergeReviewIntoCommentActionMigrationTest { private MergeReviewIntoCommentMigration action; private BibEntry entry; private BibEntry expectedEntry; @BeforeEach public void setUp() { action = new MergeReviewIntoCommentMigration(); entry = createMinimalBibEntry(); expectedEntry = createMinimalBibEntry(); } @Test public void noFields() { ParserResult actualParserResult = new ParserResult(Collections.singletonList(entry)); action.performMigration(actualParserResult); assertEquals(entry, actualParserResult.getDatabase().getEntryByCitationKey("Entry1").get()); } @Test public void reviewField() { entry.setField(StandardField.REVIEW, "My Review"); ParserResult actualParserResult = new ParserResult(Collections.singletonList(entry)); expectedEntry.setField(StandardField.COMMENT, "My Review"); action.performMigration(actualParserResult); assertEquals(expectedEntry, actualParserResult.getDatabase().getEntryByCitationKey("Entry1").get()); } @Test public void commentField() { entry.setField(StandardField.COMMENT, "My Comment"); ParserResult actualParserResult = new ParserResult(Collections.singletonList(entry)); action.performMigration(actualParserResult); assertEquals(entry, actualParserResult.getDatabase().getEntryByCitationKey("Entry1").get()); } @Test public void multiLineReviewField() { String commentString = "My Review\n\nSecond Paragraph\n\nThird Paragraph"; entry.setField(StandardField.REVIEW, commentString); ParserResult actualParserResult = new ParserResult(Collections.singletonList(entry)); expectedEntry.setField(StandardField.COMMENT, commentString); action.performMigration(actualParserResult); assertEquals(expectedEntry, actualParserResult.getDatabase().getEntryByCitationKey("Entry1").get()); } @Test @Disabled("Re-enable if the MergeReviewIntoCommentMigration.mergeCommentFieldIfPresent() does not block and wait for user input.") public void reviewAndCommentField() { entry.setField(StandardField.REVIEW, "My Review"); entry.setField(StandardField.COMMENT, "My Comment"); ParserResult actualParserResult = new ParserResult(Collections.singletonList(entry)); expectedEntry.setField(StandardField.COMMENT, "My Comment\n" + Localization.lang("Review") + ":\nMy Review"); action.performMigration(actualParserResult); assertEquals(expectedEntry, actualParserResult.getDatabase().getEntryByCitationKey("Entry1").get()); } private BibEntry createMinimalBibEntry() { BibEntry entry = new BibEntry(); entry.setCitationKey("Entry1"); entry.setField(StandardField.TITLE, "A random entry!"); entry.setField(StandardField.AUTHOR, "JabRef DEVELOPERS"); return entry; } }
3,391
33.969072
134
java
null
jabref-main/src/test/java/org/jabref/migrations/PreferencesMigrationsTest.java
package org.jabref.migrations; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.prefs.Preferences; import org.jabref.preferences.JabRefPreferences; import com.github.javakeyring.Keyring; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import org.mockito.MockedStatic; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class PreferencesMigrationsTest { private JabRefPreferences prefs; private Preferences mainPrefsNode; private final String[] oldStylePatterns = new String[]{"\\bibtexkey", "\\bibtexkey\\begin{title} - \\format[RemoveBrackets]{\\title}\\end{title}"}; private final String[] newStylePatterns = new String[]{"[citationkey]", "[citationkey] - [title]"}; @BeforeEach void setUp() { prefs = mock(JabRefPreferences.class, Answers.RETURNS_DEEP_STUBS); mainPrefsNode = mock(Preferences.class); } @Test void testOldStyleBibtexkeyPattern0() { when(prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN)).thenReturn(oldStylePatterns[0]); when(mainPrefsNode.get(JabRefPreferences.IMPORT_FILENAMEPATTERN, null)).thenReturn(oldStylePatterns[0]); when(prefs.hasKey(JabRefPreferences.IMPORT_FILENAMEPATTERN)).thenReturn(true); PreferencesMigrations.upgradeImportFileAndDirePatterns(prefs, mainPrefsNode); verify(prefs).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[0]); verify(mainPrefsNode).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[0]); } @Test void testOldStyleBibtexkeyPattern1() { when(prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN)).thenReturn(oldStylePatterns[1]); when(mainPrefsNode.get(JabRefPreferences.IMPORT_FILENAMEPATTERN, null)).thenReturn(oldStylePatterns[1]); when(prefs.hasKey(JabRefPreferences.IMPORT_FILENAMEPATTERN)).thenReturn(true); PreferencesMigrations.upgradeImportFileAndDirePatterns(prefs, mainPrefsNode); verify(prefs).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[1]); verify(mainPrefsNode).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, newStylePatterns[1]); } @Test void testArbitraryBibtexkeyPattern() { String arbitraryPattern = "[anyUserPrividedString]"; when(prefs.get(JabRefPreferences.IMPORT_FILENAMEPATTERN)).thenReturn(arbitraryPattern); when(mainPrefsNode.get(JabRefPreferences.IMPORT_FILENAMEPATTERN, null)).thenReturn(arbitraryPattern); PreferencesMigrations.upgradeImportFileAndDirePatterns(prefs, mainPrefsNode); verify(prefs, never()).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, arbitraryPattern); verify(mainPrefsNode, never()).put(JabRefPreferences.IMPORT_FILENAMEPATTERN, arbitraryPattern); } @Test void testPreviewStyleReviewToComment() { String oldPreviewStyle = "<font face=\"sans-serif\">__NEWLINE__" + "Customized preview style using reviews and comments:__NEWLINE__" + "\\begin{review}<BR><BR><b>Review: </b> \\format[HTMLChars]{\\review} \\end{review}__NEWLINE__" + "\\begin{comment} Something: \\format[HTMLChars]{\\comment} special \\end{comment}__NEWLINE__" + "</font>__NEWLINE__"; String newPreviewStyle = "<font face=\"sans-serif\">__NEWLINE__" + "Customized preview style using reviews and comments:__NEWLINE__" + "\\begin{comment}<BR><BR><b>Comment: </b> \\format[Markdown,HTMLChars]{\\comment} \\end{comment}__NEWLINE__" + "\\begin{comment} Something: \\format[Markdown,HTMLChars]{\\comment} special \\end{comment}__NEWLINE__" + "</font>__NEWLINE__"; when(prefs.get(JabRefPreferences.PREVIEW_STYLE)).thenReturn(oldPreviewStyle); PreferencesMigrations.upgradePreviewStyle(prefs); verify(prefs).put(JabRefPreferences.PREVIEW_STYLE, newPreviewStyle); } @Test void testUpgradeColumnPreferencesAlreadyMigrated() { List<String> columnNames = Arrays.asList("entrytype", "author/editor", "title", "year", "journal/booktitle", "citationkey", "printed"); List<String> columnWidths = Arrays.asList("75", "300", "470", "60", "130", "100", "30"); when(prefs.getStringList(JabRefPreferences.COLUMN_NAMES)).thenReturn(columnNames); when(prefs.getStringList(JabRefPreferences.COLUMN_WIDTHS)).thenReturn(columnWidths); PreferencesMigrations.upgradeColumnPreferences(prefs); verify(prefs, never()).put(JabRefPreferences.COLUMN_NAMES, "anyString"); verify(prefs, never()).put(JabRefPreferences.COLUMN_WIDTHS, "anyString"); } @Test void testUpgradeColumnPreferencesFromWithoutTypes() { List<String> columnNames = Arrays.asList("entrytype", "author/editor", "title", "year", "journal/booktitle", "citationkey", "printed"); List<String> columnWidths = Arrays.asList("75", "300", "470", "60", "130", "100", "30"); List<String> updatedNames = Arrays.asList("groups", "files", "linked_id", "field:entrytype", "field:author/editor", "field:title", "field:year", "field:journal/booktitle", "field:citationkey", "special:printed"); List<String> updatedWidths = Arrays.asList("28", "28", "28", "75", "300", "470", "60", "130", "100", "30"); List<String> newSortTypes = Arrays.asList("ASCENDING", "ASCENDING", "ASCENDING", "ASCENDING", "ASCENDING", "ASCENDING", "ASCENDING", "ASCENDING", "ASCENDING", "ASCENDING"); when(prefs.getStringList(JabRefPreferences.COLUMN_NAMES)).thenReturn(columnNames); when(prefs.getStringList(JabRefPreferences.COLUMN_WIDTHS)).thenReturn(columnWidths); PreferencesMigrations.upgradeColumnPreferences(prefs); verify(prefs).putStringList(JabRefPreferences.COLUMN_NAMES, updatedNames); verify(prefs).putStringList(JabRefPreferences.COLUMN_WIDTHS, updatedWidths); verify(prefs).putStringList(JabRefPreferences.COLUMN_SORT_TYPES, newSortTypes); } @Test void testChangeColumnPreferencesVariableNamesFor51() { List<String> columnNames = Arrays.asList("entrytype", "author/editor", "title", "year", "journal/booktitle", "citationkey", "printed"); List<String> columnWidths = Arrays.asList("75", "300", "470", "60", "130", "100", "30"); // The variable names have to be hardcoded, because they have changed between 5.0 and 5.1 when(prefs.getStringList("columnNames")).thenReturn(columnNames); when(prefs.getStringList("columnWidths")).thenReturn(columnWidths); when(prefs.getStringList("mainTableColumnSortTypes")).thenReturn(columnNames); when(prefs.getStringList("mainTableColumnSortOrder")).thenReturn(columnWidths); when(prefs.getStringList(JabRefPreferences.COLUMN_NAMES)).thenReturn(Collections.emptyList()); when(prefs.getStringList(JabRefPreferences.COLUMN_WIDTHS)).thenReturn(Collections.emptyList()); when(prefs.getStringList(JabRefPreferences.COLUMN_SORT_TYPES)).thenReturn(Collections.emptyList()); when(prefs.getStringList(JabRefPreferences.COLUMN_SORT_ORDER)).thenReturn(Collections.emptyList()); PreferencesMigrations.changeColumnVariableNamesFor51(prefs); verify(prefs).putStringList(JabRefPreferences.COLUMN_NAMES, columnNames); verify(prefs).putStringList(JabRefPreferences.COLUMN_WIDTHS, columnWidths); verify(prefs).putStringList(JabRefPreferences.COLUMN_NAMES, columnNames); verify(prefs).putStringList(JabRefPreferences.COLUMN_WIDTHS, columnWidths); } @Test void testChangeColumnPreferencesVariableNamesBackwardsCompatibility() { List<String> columnNames = Arrays.asList("entrytype", "author/editor", "title", "year", "journal/booktitle", "citationkey", "printed"); List<String> columnWidths = Arrays.asList("75", "300", "470", "60", "130", "100", "30"); // The variable names have to be hardcoded, because they have changed between 5.0 and 5.1 when(prefs.getStringList("columnNames")).thenReturn(columnNames); when(prefs.getStringList("columnWidths")).thenReturn(columnWidths); when(prefs.getStringList("mainTableColumnSortTypes")).thenReturn(columnNames); when(prefs.getStringList("mainTableColumnSortOrder")).thenReturn(columnWidths); when(prefs.getStringList(JabRefPreferences.COLUMN_NAMES)).thenReturn(Collections.emptyList()); when(prefs.getStringList(JabRefPreferences.COLUMN_WIDTHS)).thenReturn(Collections.emptyList()); when(prefs.getStringList(JabRefPreferences.COLUMN_SORT_TYPES)).thenReturn(Collections.emptyList()); when(prefs.getStringList(JabRefPreferences.COLUMN_SORT_ORDER)).thenReturn(Collections.emptyList()); PreferencesMigrations.upgradeColumnPreferences(prefs); verify(prefs, never()).put("columnNames", "anyString"); verify(prefs, never()).put("columnWidths", "anyString"); verify(prefs, never()).put("mainTableColumnSortTypes", "anyString"); verify(prefs, never()).put("mainTableColumnSortOrder", "anyString"); } @Test void testRestoreColumnVariablesForBackwardCompatibility() { List<String> updatedNames = Arrays.asList("groups", "files", "linked_id", "field:entrytype", "field:author/editor", "field:title", "field:year", "field:journal/booktitle", "field:citationkey", "special:printed"); List<String> columnNames = Arrays.asList("entrytype", "author/editor", "title", "year", "journal/booktitle", "citationkey", "printed"); List<String> columnWidths = Arrays.asList("100", "100", "100", "100", "100", "100", "100"); when(prefs.getStringList(JabRefPreferences.COLUMN_NAMES)).thenReturn(updatedNames); when(prefs.get(JabRefPreferences.MAIN_FONT_SIZE)).thenReturn("11.2"); PreferencesMigrations.restoreVariablesForBackwardCompatibility(prefs); verify(prefs).putStringList("columnNames", columnNames); verify(prefs).putStringList("columnWidths", columnWidths); verify(prefs).put("columnSortTypes", ""); verify(prefs).put("columnSortOrder", ""); verify(prefs).putInt(JabRefPreferences.MAIN_FONT_SIZE, 11); } @Test void testMoveApiKeysToKeyRing() throws Exception { final String V5_9_FETCHER_CUSTOM_KEY_NAMES = "fetcherCustomKeyNames"; final String V5_9_FETCHER_CUSTOM_KEYS = "fetcherCustomKeys"; final Keyring keyring = mock(Keyring.class); when(prefs.getStringList(V5_9_FETCHER_CUSTOM_KEY_NAMES)).thenReturn(List.of("FetcherA", "FetcherB", "FetcherC")); when(prefs.getStringList(V5_9_FETCHER_CUSTOM_KEYS)).thenReturn(List.of("KeyA", "KeyB", "KeyC")); when(prefs.getInternalPreferences().getUserAndHost()).thenReturn("user-host"); try (MockedStatic<Keyring> keyringFactory = Mockito.mockStatic(Keyring.class, Answers.RETURNS_DEEP_STUBS)) { keyringFactory.when(Keyring::create).thenReturn(keyring); PreferencesMigrations.moveApiKeysToKeyring(prefs); verify(keyring).setPassword(eq("org.jabref.customapikeys"), eq("FetcherA"), any()); verify(keyring).setPassword(eq("org.jabref.customapikeys"), eq("FetcherB"), any()); verify(keyring).setPassword(eq("org.jabref.customapikeys"), eq("FetcherC"), any()); verify(prefs).deleteKey(V5_9_FETCHER_CUSTOM_KEYS); } } }
11,731
52.327273
220
java
null
jabref-main/src/test/java/org/jabref/migrations/SpecialFieldsToSeparateFieldsTest.java
package org.jabref.migrations; import java.util.List; import java.util.stream.Stream; import org.jabref.logic.importer.ParserResult; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; class SpecialFieldsToSeparateFieldsTest { @ParameterizedTest @MethodSource("provideKeywordFieldPairs") public void migrateToCorrectField(SpecialField field, String fieldInKeyword, BibEntry expected) { BibEntry entry = new BibEntry().withField(StandardField.KEYWORDS, fieldInKeyword); new SpecialFieldsToSeparateFields(',').performMigration(new ParserResult(List.of(entry))); assertEquals(expected, entry); } @Test public void noKewordToMigrate() { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(StandardField.KEYWORDS, "tdd"); BibEntry expected = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(StandardField.KEYWORDS, "tdd"); new SpecialFieldsToSeparateFields(',').performMigration(new ParserResult(List.of(entry))); assertEquals(expected, entry); } @Test public void noKeywordToMigrateButDuplicateKeywords() { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(StandardField.KEYWORDS, "asdf, asdf, asdf"); BibEntry expected = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(StandardField.KEYWORDS, "asdf, asdf, asdf"); new SpecialFieldsToSeparateFields(',').performMigration(new ParserResult(List.of(entry))); assertEquals(expected, entry); } @Test public void migrateMultipleSpecialFields() { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(StandardField.KEYWORDS, "printed, prio1"); BibEntry expected = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(SpecialField.PRINTED, "printed") .withField(SpecialField.PRIORITY, "prio1"); new SpecialFieldsToSeparateFields(',').performMigration(new ParserResult(List.of(entry))); assertEquals(expected, entry); } @Test public void migrateSpecialFieldsMixedWithKeyword() { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(StandardField.KEYWORDS, "tdd, prio1, SE"); BibEntry expected = new BibEntry().withField(StandardField.AUTHOR, "JabRef") .withField(StandardField.KEYWORDS, "tdd, SE") .withField(SpecialField.PRIORITY, "prio1"); new SpecialFieldsToSeparateFields(',').performMigration(new ParserResult(List.of(entry))); assertEquals(expected, entry); } private static Stream<Arguments> provideKeywordFieldPairs() { return Stream.of( Arguments.of( SpecialField.PRINTED, "printed", new BibEntry().withField(SpecialField.PRINTED, "printed") ), Arguments.of( SpecialField.PRIORITY, "prio1", new BibEntry().withField(SpecialField.PRIORITY, "prio1") ), Arguments.of( SpecialField.QUALITY, "qualityAssured", new BibEntry().withField(SpecialField.QUALITY, "qualityAssured") ), Arguments.of( SpecialField.RANKING, "rank2", new BibEntry().withField(SpecialField.RANKING, "rank2") ), Arguments.of( SpecialField.READ_STATUS, "skimmed", new BibEntry().withField(SpecialField.READ_STATUS, "skimmed") ), Arguments.of( SpecialField.RELEVANCE, "relevant", new BibEntry().withField(SpecialField.RELEVANCE, "relevant") ) ); } }
4,494
41.809524
128
java
null
jabref-main/src/test/java/org/jabref/model/FieldChangeTest.java
package org.jabref.model; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class FieldChangeTest { private BibEntry entry = new BibEntry() .withField(StandardField.DOI, "foo"); private BibEntry entryOther = new BibEntry(); private FieldChange fc = new FieldChange(entry, StandardField.DOI, "foo", "bar"); @Test void fieldChangeOnNullEntryNotAllowed() { assertThrows(NullPointerException.class, () -> new FieldChange(null, StandardField.DOI, "foo", "bar")); } @Test void fieldChangeOnNullFieldNotAllowed() { assertThrows(NullPointerException.class, () -> new FieldChange(entry, null, "foo", "bar")); } @Test void blankFieldChangeNotAllowed() { assertThrows(NullPointerException.class, () -> new FieldChange(null, null, null, null)); } @Test void equalFieldChange() { FieldChange fcBlankNewValue = new FieldChange(entry, StandardField.DOI, "foo", null); assertNotEquals(fc, fcBlankNewValue); } @Test void selfEqualsFieldchangeSameParameters() { FieldChange fcBlankNewValue = new FieldChange(entry, StandardField.DOI, "foo", "bar"); assertEquals(fc, fcBlankNewValue); } @Test void selfEqualsFieldchangeDifferentOldValue() { FieldChange fcBlankNewValue = new FieldChange(entry, StandardField.DOI, null, "bar"); assertNotEquals(fc, fcBlankNewValue); } @Test void selfEqualsFieldchangeDifferentEntry() { FieldChange fcBlankNewValue = new FieldChange(entryOther, StandardField.DOI, "foo", "bar"); assertNotEquals(fc, fcBlankNewValue); } @Test void fieldChangeDoesNotEqualString() { assertNotEquals(fc, "foo"); } @Test void fieldChangeEqualsItSelf() { assertEquals(fc, fc); } @Test void differentFieldChangeIsNotEqual() { FieldChange fcOther = new FieldChange(entryOther, StandardField.DOI, "fooX", "barX"); assertNotEquals(fc, fcOther); } }
2,276
29.77027
111
java
null
jabref-main/src/test/java/org/jabref/model/TreeNodeTest.java
package org.jabref.model; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class TreeNodeTest { Consumer<TreeNodeTestData.TreeNodeMock> subscriber; @BeforeEach public void setUp() { subscriber = mock(Consumer.class); } @Test public void constructorChecksThatClassImplementsCorrectInterface() { assertThrows(UnsupportedOperationException.class, WrongTreeNodeImplementation::new); } @Test public void constructorExceptsCorrectImplementation() { TreeNodeTestData.TreeNodeMock treeNode = new TreeNodeTestData.TreeNodeMock(); assertNotNull(treeNode); } @Test public void newTreeNodeHasNoParentOrChildren() { TreeNodeTestData.TreeNodeMock treeNode = new TreeNodeTestData.TreeNodeMock(); assertEquals(Optional.empty(), treeNode.getParent()); assertEquals(Collections.emptyList(), treeNode.getChildren()); assertNotNull(treeNode); } @Test public void getIndexedPathFromRootReturnsEmptyListForRoot() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertEquals(Collections.emptyList(), root.getIndexedPathFromRoot()); } @Test public void getIndexedPathFromRootSimplePath() { assertEquals(Arrays.asList(1, 0), TreeNodeTestData.getNodeInSimpleTree().getIndexedPathFromRoot()); } @Test public void getIndexedPathFromRootComplexPath() { assertEquals(Arrays.asList(2, 1, 0), TreeNodeTestData.getNodeInComplexTree().getIndexedPathFromRoot()); } @Test public void getDescendantSimplePath() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInSimpleTree(root); assertEquals(node, root.getDescendant(Arrays.asList(1, 0)).get()); } @Test public void getDescendantComplexPath() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); assertEquals(node, root.getDescendant(Arrays.asList(2, 1, 0)).get()); } @Test public void getDescendantNonExistentReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.getNodeInComplexTree(root); assertEquals(Optional.empty(), root.getDescendant(Arrays.asList(1, 100, 0))); } @Test public void getPositionInParentForRootThrowsException() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertThrows(UnsupportedOperationException.class, root::getPositionInParent); } @Test public void getPositionInParentSimpleTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); assertEquals(2, node.getPositionInParent()); } @Test public void getIndexOfNonExistentChildReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertEquals(Optional.empty(), root.getIndexOfChild(new TreeNodeTestData.TreeNodeMock())); } @Test public void getIndexOfChild() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); assertEquals((Integer) 2, root.getIndexOfChild(node).get()); } @Test public void getLevelOfRoot() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertEquals(0, root.getLevel()); } @Test public void getLevelInSimpleTree() { assertEquals(2, TreeNodeTestData.getNodeInSimpleTree().getLevel()); } @Test public void getLevelInComplexTree() { assertEquals(3, TreeNodeTestData.getNodeInComplexTree().getLevel()); } @Test public void getChildCountInSimpleTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.getNodeInSimpleTree(root); assertEquals(2, root.getNumberOfChildren()); } @Test public void getChildCountInComplexTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.getNodeInComplexTree(root); assertEquals(4, root.getNumberOfChildren()); } @Test public void moveToAddsAsLastChildInSimpleTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInSimpleTree(root); node.moveTo(root); assertEquals((Integer) 2, root.getIndexOfChild(node).get()); } @Test public void moveToAddsAsLastChildInComplexTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); node.moveTo(root); assertEquals((Integer) 4, root.getIndexOfChild(node).get()); } @Test public void moveToChangesParent() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInSimpleTree(root); node.moveTo(root); assertEquals(root, node.getParent().get()); } @Test public void moveToInSameLevelAddsAtEnd() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock(); root.addChild(child1); root.addChild(child2); child1.moveTo(root); assertEquals(Arrays.asList(child2, child1), root.getChildren()); } @Test public void moveToInSameLevelWhenNodeWasBeforeTargetIndex() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child3 = new TreeNodeTestData.TreeNodeMock(); root.addChild(child1); root.addChild(child2); root.addChild(child3); child1.moveTo(root, 1); assertEquals(Arrays.asList(child2, child1, child3), root.getChildren()); } @Test public void moveToInSameLevelWhenNodeWasAfterTargetIndex() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child3 = new TreeNodeTestData.TreeNodeMock(); root.addChild(child1); root.addChild(child2); root.addChild(child3); child3.moveTo(root, 1); assertEquals(Arrays.asList(child1, child3, child2), root.getChildren()); } @Test public void getPathFromRootInSimpleTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInSimpleTree(root); List<TreeNodeTestData.TreeNodeMock> path = node.getPathFromRoot(); assertEquals(3, path.size()); assertEquals(root, path.get(0)); assertEquals(node, path.get(2)); } @Test public void getPathFromRootInComplexTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); List<TreeNodeTestData.TreeNodeMock> path = node.getPathFromRoot(); assertEquals(4, path.size()); assertEquals(root, path.get(0)); assertEquals(node, path.get(3)); } @Test public void getPreviousSiblingReturnsCorrect() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); root.addChild(new TreeNodeTestData.TreeNodeMock()); TreeNodeTestData.TreeNodeMock previous = new TreeNodeTestData.TreeNodeMock(); root.addChild(previous); TreeNodeTestData.TreeNodeMock node = new TreeNodeTestData.TreeNodeMock(); root.addChild(node); root.addChild(new TreeNodeTestData.TreeNodeMock()); assertEquals(previous, node.getPreviousSibling().get()); } @Test public void getPreviousSiblingForRootReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertEquals(Optional.empty(), root.getPreviousSibling()); } @Test public void getPreviousSiblingForNonexistentReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = new TreeNodeTestData.TreeNodeMock(); root.addChild(node); assertEquals(Optional.empty(), node.getPreviousSibling()); } @Test public void getNextSiblingReturnsCorrect() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); root.addChild(new TreeNodeTestData.TreeNodeMock()); TreeNodeTestData.TreeNodeMock node = new TreeNodeTestData.TreeNodeMock(); root.addChild(node); TreeNodeTestData.TreeNodeMock next = new TreeNodeTestData.TreeNodeMock(); root.addChild(next); root.addChild(new TreeNodeTestData.TreeNodeMock()); assertEquals(next, node.getNextSibling().get()); } @Test public void getNextSiblingForRootReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertEquals(Optional.empty(), root.getNextSibling()); } @Test public void getNextSiblingForNonexistentReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = new TreeNodeTestData.TreeNodeMock(); root.addChild(node); assertEquals(Optional.empty(), node.getPreviousSibling()); } @Test public void getParentReturnsCorrect() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); assertEquals(root, node.getParent().get()); } @Test public void getParentForRootReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertEquals(Optional.empty(), root.getParent()); } @Test public void getChildAtReturnsCorrect() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); assertEquals(node, root.getChildAt(2).get()); } @Test public void getChildAtInvalidIndexReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); root.addChild(new TreeNodeTestData.TreeNodeMock()); root.addChild(new TreeNodeTestData.TreeNodeMock()); assertEquals(Optional.empty(), root.getChildAt(10)); } @Test public void getRootReturnsTrueForRoot() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertTrue(root.isRoot()); } @Test public void getRootReturnsFalseForChild() { assertFalse(TreeNodeTestData.getNodeInSimpleTree().isRoot()); } @Test public void nodeIsAncestorOfItself() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertTrue(root.isAncestorOf(root)); } @Test public void isAncestorOfInSimpleTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInSimpleTree(root); assertTrue(root.isAncestorOf(node)); } @Test public void isAncestorOfInComplexTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); assertTrue(root.isAncestorOf(node)); } @Test public void getRootOfSingleNode() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertEquals(root, root.getRoot()); } @Test public void getRootInSimpleTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInSimpleTree(root); assertEquals(root, node.getRoot()); } @Test public void getRootInComplexTree() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); assertEquals(root, node.getRoot()); } @Test public void isLeafIsCorrectForRootWithoutChildren() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); assertTrue(root.isLeaf()); } @Test public void removeFromParentSetsParentToEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); node.removeFromParent(); assertEquals(Optional.empty(), node.getParent()); } @Test public void removeFromParentRemovesNodeFromChildrenCollection() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); node.removeFromParent(); assertFalse(root.getChildren().contains(node)); } @Test public void removeAllChildrenSetsParentOfChildToEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); root.removeAllChildren(); assertEquals(Optional.empty(), node.getParent()); } @Test public void removeAllChildrenRemovesAllNodesFromChildrenCollection() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.getNodeAsChild(root); root.removeAllChildren(); assertEquals(Collections.emptyList(), root.getChildren()); } @Test public void getFirstChildAtReturnsCorrect() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = new TreeNodeTestData.TreeNodeMock(); root.addChild(node); assertEquals(node, root.getFirstChild().get()); } @Test public void getFirstChildAtLeafReturnsEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock leaf = TreeNodeTestData.getNodeAsChild(root); assertEquals(Optional.empty(), leaf.getFirstChild()); } @Test public void isNodeDescendantInFirstLevel() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child = TreeNodeTestData.getNodeAsChild(root); assertTrue(root.isNodeDescendant(child)); } @Test public void isNodeDescendantInComplex() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock descendant = TreeNodeTestData.getNodeInComplexTree(root); assertTrue(root.isNodeDescendant(descendant)); } @Test public void getChildrenReturnsAllChildren() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock(); root.addChild(child1); root.addChild(child2); assertEquals(Arrays.asList(child1, child2), root.getChildren()); } @Test public void removeChildSetsParentToEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); root.removeChild(node); assertEquals(Optional.empty(), node.getParent()); } @Test public void removeChildRemovesNodeFromChildrenCollection() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); root.removeChild(node); assertFalse(root.getChildren().contains(node)); } @Test public void removeChildIndexSetsParentToEmpty() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); root.removeChild(2); assertEquals(Optional.empty(), node.getParent()); } @Test public void removeChildIndexRemovesNodeFromChildrenCollection() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); root.removeChild(2); assertFalse(root.getChildren().contains(node)); } @Test public void addThrowsExceptionIfNodeHasParent() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); assertThrows(UnsupportedOperationException.class, () -> root.addChild(node)); } @Test public void moveAllChildrenToAddsAtSpecifiedPosition() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = new TreeNodeTestData.TreeNodeMock(); root.addChild(node); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock(); node.addChild(child1); node.addChild(child2); node.moveAllChildrenTo(root, 0); assertEquals(Arrays.asList(child1, child2, node), root.getChildren()); } @Test public void moveAllChildrenToChangesParent() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = new TreeNodeTestData.TreeNodeMock(); root.addChild(node); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock(); node.addChild(child1); node.addChild(child2); node.moveAllChildrenTo(root, 0); assertEquals(root, child1.getParent().get()); assertEquals(root, child2.getParent().get()); } @Test public void moveAllChildrenToDescendantThrowsException() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); assertThrows(UnsupportedOperationException.class, () -> root.moveAllChildrenTo(node, 0)); } @Test public void sortChildrenSortsInFirstLevel() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock("a"); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock("b"); TreeNodeTestData.TreeNodeMock child3 = new TreeNodeTestData.TreeNodeMock("c"); root.addChild(child2); root.addChild(child3); root.addChild(child1); root.sortChildren((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()), false); assertEquals(Arrays.asList(child1, child2, child3), root.getChildren()); } @Test public void sortChildrenRecursiveSortsInDeeperLevel() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInSimpleTree(root); TreeNodeTestData.TreeNodeMock child1 = new TreeNodeTestData.TreeNodeMock("a"); TreeNodeTestData.TreeNodeMock child2 = new TreeNodeTestData.TreeNodeMock("b"); TreeNodeTestData.TreeNodeMock child3 = new TreeNodeTestData.TreeNodeMock("c"); node.addChild(child2); node.addChild(child3); node.addChild(child1); root.sortChildren((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()), true); assertEquals(Arrays.asList(child1, child2, child3), node.getChildren()); } @Test public void copySubtreeCopiesChildren() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeAsChild(root); TreeNodeTestData.TreeNodeMock copiedRoot = root.copySubtree(); assertEquals(Optional.empty(), copiedRoot.getParent()); assertFalse(copiedRoot.getChildren().contains(node)); assertEquals(root.getNumberOfChildren(), copiedRoot.getNumberOfChildren()); } @Test public void addChildSomewhereInTreeInvokesChangeEvent() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); root.subscribeToDescendantChanged(subscriber); node.addChild(new TreeNodeTestData.TreeNodeMock()); verify(subscriber).accept(node); } @Test public void moveNodeSomewhereInTreeInvokesChangeEvent() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); TreeNodeTestData.TreeNodeMock oldParent = node.getParent().get(); root.subscribeToDescendantChanged(subscriber); node.moveTo(root); verify(subscriber).accept(root); verify(subscriber).accept(oldParent); } @Test public void removeChildSomewhereInTreeInvokesChangeEvent() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); TreeNodeTestData.TreeNodeMock child = node.addChild(new TreeNodeTestData.TreeNodeMock()); root.subscribeToDescendantChanged(subscriber); node.removeChild(child); verify(subscriber).accept(node); } @Test public void removeChildIndexSomewhereInTreeInvokesChangeEvent() { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock(); TreeNodeTestData.TreeNodeMock node = TreeNodeTestData.getNodeInComplexTree(root); node.addChild(new TreeNodeTestData.TreeNodeMock()); root.subscribeToDescendantChanged(subscriber); node.removeChild(0); verify(subscriber).accept(node); } @Test public void findChildrenWithSameName() throws Exception { TreeNodeTestData.TreeNodeMock root = new TreeNodeTestData.TreeNodeMock("A"); TreeNodeTestData.TreeNodeMock childB = root.addChild(new TreeNodeTestData.TreeNodeMock("B")); TreeNodeTestData.TreeNodeMock node = childB.addChild(new TreeNodeTestData.TreeNodeMock("A")); TreeNodeTestData.TreeNodeMock childA = root.addChild(new TreeNodeTestData.TreeNodeMock("A")); assertEquals(Arrays.asList(root, node, childA), root.findChildrenSatisfying(treeNode -> "A".equals(treeNode.getName()))); } private static class WrongTreeNodeImplementation extends TreeNode<TreeNodeTestData.TreeNodeMock> { // This class is a wrong derived class of TreeNode<T> // since it does not extends TreeNode<WrongTreeNodeImplementation> // See test constructorChecksThatClassImplementsCorrectInterface public WrongTreeNodeImplementation() { super(TreeNodeTestData.TreeNodeMock.class); } @Override public TreeNodeTestData.TreeNodeMock copyNode() { return null; } } }
25,139
38.219969
129
java
null
jabref-main/src/test/java/org/jabref/model/TreeNodeTestData.java
package org.jabref.model; public class TreeNodeTestData { /** * Gets the marked node in the following tree: Root A A (= parent) B (<-- this) */ public static TreeNodeMock getNodeInSimpleTree(TreeNodeMock root) { root.addChild(new TreeNodeMock()); TreeNodeMock parent = new TreeNodeMock(); root.addChild(parent); TreeNodeMock node = new TreeNodeMock(); parent.addChild(node); return node; } public static TreeNodeMock getNodeInSimpleTree() { return getNodeInSimpleTree(new TreeNodeMock()); } /** * Gets the marked node in the following tree: Root A A A (= grand parent) B B (= parent) C (<-- this) D (= child) C * C C B B A */ public static TreeNodeMock getNodeInComplexTree(TreeNodeMock root) { root.addChild(new TreeNodeMock()); root.addChild(new TreeNodeMock()); TreeNodeMock grandParent = new TreeNodeMock(); root.addChild(grandParent); root.addChild(new TreeNodeMock()); grandParent.addChild(new TreeNodeMock()); TreeNodeMock parent = new TreeNodeMock(); grandParent.addChild(parent); grandParent.addChild(new TreeNodeMock()); grandParent.addChild(new TreeNodeMock()); TreeNodeMock node = new TreeNodeMock(); parent.addChild(node); parent.addChild(new TreeNodeMock()); parent.addChild(new TreeNodeMock()); parent.addChild(new TreeNodeMock()); node.addChild(new TreeNodeMock()); return node; } public static TreeNodeMock getNodeInComplexTree() { return getNodeInComplexTree(new TreeNodeMock()); } /** * Gets the marked in the following tree: Root A A A (<- this) A */ public static TreeNodeMock getNodeAsChild(TreeNodeMock root) { root.addChild(new TreeNodeMock()); root.addChild(new TreeNodeMock()); TreeNodeMock node = new TreeNodeMock(); root.addChild(node); root.addChild(new TreeNodeMock()); return node; } /** * This is just a dummy class deriving from TreeNode&lt;T> so that we can test the generic class */ public static class TreeNodeMock extends TreeNode<TreeNodeMock> { private String name; public TreeNodeMock() { this(""); } public TreeNodeMock(String name) { super(TreeNodeMock.class); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "TreeNodeMock{" + "name='" + name + '\'' + '}'; } @Override public TreeNodeMock copyNode() { return new TreeNodeMock(name); } } }
2,910
28.11
120
java
null
jabref-main/src/test/java/org/jabref/model/database/BibDatabaseContextTest.java
package org.jabref.model.database; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.util.OS; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.types.IEEETranEntryType; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.FilePreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @AllowedToUseLogic("Needs access to OS class") class BibDatabaseContextTest { private Path currentWorkingDir; private FilePreferences fileDirPrefs; @BeforeEach void setUp() { fileDirPrefs = mock(FilePreferences.class); currentWorkingDir = Path.of(System.getProperty("user.dir")); when(fileDirPrefs.shouldStoreFilesRelativeToBibFile()).thenReturn(true); } @Test void getFileDirectoriesWithEmptyDbParent() { BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(Path.of("biblio.bib")); assertEquals(Collections.singletonList(currentWorkingDir), database.getFileDirectories(fileDirPrefs)); } @Test void getFileDirectoriesWithRelativeDbParent() { Path file = Path.of("relative/subdir").resolve("biblio.bib"); BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), database.getFileDirectories(fileDirPrefs)); } @Test void getFileDirectoriesWithRelativeDottedDbParent() { Path file = Path.of("./relative/subdir").resolve("biblio.bib"); BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), database.getFileDirectories(fileDirPrefs)); } @Test void getFileDirectoriesWithAbsoluteDbParent() { Path file = Path.of("/absolute/subdir").resolve("biblio.bib"); BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); assertEquals(Collections.singletonList(currentWorkingDir.resolve(file.getParent())), database.getFileDirectories(fileDirPrefs)); } @Test void getFileDirectoriesWithRelativeMetadata() { Path file = Path.of("/absolute/subdir").resolve("biblio.bib"); BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); database.getMetaData().setDefaultFileDirectory("../Literature"); // first directory is the metadata // the bib file location is not included, because only the library-configured directories should be searched and the fallback should be the global directory. assertEquals(List.of(Path.of("/absolute/Literature").toAbsolutePath()), database.getFileDirectories(fileDirPrefs)); } @Test void getFileDirectoriesWithMetadata() { Path file = Path.of("/absolute/subdir").resolve("biblio.bib"); BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(file); database.getMetaData().setDefaultFileDirectory("Literature"); // first directory is the metadata // the bib file location is not included, because only the library-configured directories should be searched and the fallback should be the global directory. assertEquals(List.of(Path.of("/absolute/subdir/Literature").toAbsolutePath()), database.getFileDirectories(fileDirPrefs)); } @Test void getUserFileDirectoryIfAllAreEmpty() { when(fileDirPrefs.shouldStoreFilesRelativeToBibFile()).thenReturn(false); Path userDirJabRef = OS.getNativeDesktop().getDefaultFileChooserDirectory(); when(fileDirPrefs.getMainFileDirectory()).thenReturn(Optional.of(userDirJabRef)); BibDatabaseContext database = new BibDatabaseContext(); database.setDatabasePath(Path.of("biblio.bib")); assertEquals(Collections.singletonList(userDirJabRef), database.getFileDirectories(fileDirPrefs)); } @Test void testTypeBasedOnDefaultBiblatex() { BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(new BibDatabase(), new MetaData()); assertEquals(BibDatabaseMode.BIBLATEX, bibDatabaseContext.getMode()); bibDatabaseContext.setMode(BibDatabaseMode.BIBLATEX); assertEquals(BibDatabaseMode.BIBLATEX, bibDatabaseContext.getMode()); } @Test void testTypeBasedOnDefaultBibtex() { BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(new BibDatabase(), new MetaData()); assertEquals(BibDatabaseMode.BIBLATEX, bibDatabaseContext.getMode()); bibDatabaseContext.setMode(BibDatabaseMode.BIBTEX); assertEquals(BibDatabaseMode.BIBTEX, bibDatabaseContext.getMode()); } @Test void testTypeBasedOnInferredModeBiblatex() { BibDatabase db = new BibDatabase(); BibEntry e1 = new BibEntry(IEEETranEntryType.Electronic); db.insertEntry(e1); BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(db); assertEquals(BibDatabaseMode.BIBLATEX, bibDatabaseContext.getMode()); } @Test void testGetFullTextIndexPathWhenPathIsNull() { BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(); bibDatabaseContext.setDatabasePath(null); Path expectedPath = OS.getNativeDesktop().getFulltextIndexBaseDirectory().resolve("unsaved"); Path actualPath = bibDatabaseContext.getFulltextIndexPath(); assertEquals(expectedPath, actualPath); } @Test void testGetFullTextIndexPathWhenPathIsNotNull() { Path existingPath = Path.of("some_path.bib"); BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(); bibDatabaseContext.setDatabasePath(existingPath); Path expectedPath = OS.getNativeDesktop().getFulltextIndexBaseDirectory().resolve(existingPath.hashCode() + ""); Path actualPath = bibDatabaseContext.getFulltextIndexPath(); assertEquals(expectedPath, actualPath); } }
6,406
39.295597
165
java
null
jabref-main/src/test/java/org/jabref/model/database/BibDatabaseModeDetectionTest.java
package org.jabref.model.database; import java.util.Arrays; import java.util.List; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class BibDatabaseModeDetectionTest { private static final EntryType UNKNOWN_TYPE = new UnknownEntryType("unknowntype"); @Test public void detectBiblatex() { List<BibEntry> entries = Arrays.asList(new BibEntry(StandardEntryType.MvBook)); assertEquals(BibDatabaseMode.BIBLATEX, BibDatabaseModeDetection.inferMode(new BibDatabase(entries))); } @Test public void detectUndistinguishableAsBibtex() { BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setField(StandardField.TITLE, "My cool paper"); List<BibEntry> entries = Arrays.asList(entry); assertEquals(BibDatabaseMode.BIBTEX, BibDatabaseModeDetection.inferMode(new BibDatabase(entries))); } @Test public void detectMixedModeAsBiblatex() { BibEntry bibtex = new BibEntry(StandardEntryType.Article); bibtex.setField(StandardField.JOURNAL, "IEEE Trans. Services Computing"); BibEntry biblatex = new BibEntry(StandardEntryType.Article); biblatex.setField(StandardField.TRANSLATOR, "Stefan Kolb"); List<BibEntry> entries = Arrays.asList(bibtex, biblatex); assertEquals(BibDatabaseMode.BIBTEX, BibDatabaseModeDetection.inferMode(new BibDatabase(entries))); } @Test public void detectUnknownTypeAsBibtex() { BibEntry entry = new BibEntry(UNKNOWN_TYPE); List<BibEntry> entries = Arrays.asList(entry); assertEquals(BibDatabaseMode.BIBTEX, BibDatabaseModeDetection.inferMode(new BibDatabase(entries))); } @Test public void ignoreUnknownTypesForBibtexDecision() { BibEntry custom = new BibEntry(UNKNOWN_TYPE); BibEntry bibtex = new BibEntry(StandardEntryType.Article); BibEntry biblatex = new BibEntry(StandardEntryType.Article); List<BibEntry> entries = Arrays.asList(custom, bibtex, biblatex); assertEquals(BibDatabaseMode.BIBTEX, BibDatabaseModeDetection.inferMode(new BibDatabase(entries))); } @Test public void ignoreUnknownTypesForBiblatexDecision() { BibEntry custom = new BibEntry(UNKNOWN_TYPE); BibEntry bibtex = new BibEntry(StandardEntryType.Article); BibEntry biblatex = new BibEntry(StandardEntryType.MvBook); List<BibEntry> entries = Arrays.asList(custom, bibtex, biblatex); assertEquals(BibDatabaseMode.BIBLATEX, BibDatabaseModeDetection.inferMode(new BibDatabase(entries))); } }
2,876
37.36
109
java
null
jabref-main/src/test/java/org/jabref/model/database/BibDatabaseTest.java
package org.jabref.model.database; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibtexString; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.event.EventListenerTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class BibDatabaseTest { private BibDatabase database; private final BibtexString bibtexString = new BibtexString("DSP", "Digital Signal Processing"); @BeforeEach void setUp() { database = new BibDatabase(); } @Test void insertEntryAddsEntryToEntriesList() { BibEntry entry = new BibEntry(); database.insertEntry(entry); assertEquals(1, database.getEntries().size()); assertEquals(1, database.getEntryCount()); assertEquals(entry, database.getEntries().get(0)); } @Test void containsEntryIdFindsEntry() { BibEntry entry = new BibEntry(); assertFalse(database.containsEntryWithId(entry.getId())); database.insertEntry(entry); assertTrue(database.containsEntryWithId(entry.getId())); } @Test void insertEntryWithSameIdDoesNotThrowException() { BibEntry entry0 = new BibEntry(); database.insertEntry(entry0); BibEntry entry1 = new BibEntry(); entry1.setId(entry0.getId()); database.insertEntry(entry1); } @Test void removeEntryRemovesEntryFromEntriesList() { BibEntry entry = new BibEntry(); database.insertEntry(entry); database.removeEntry(entry); assertEquals(Collections.emptyList(), database.getEntries()); assertFalse(database.containsEntryWithId(entry.getId())); } @Test void removeSomeEntriesRemovesThoseEntriesFromEntriesList() { BibEntry entry1 = new BibEntry(); BibEntry entry2 = new BibEntry(); BibEntry entry3 = new BibEntry(); List<BibEntry> allEntries = Arrays.asList(entry1, entry2, entry3); database.insertEntries(allEntries); List<BibEntry> entriesToDelete = Arrays.asList(entry1, entry3); database.removeEntries(entriesToDelete); assertEquals(Collections.singletonList(entry2), database.getEntries()); assertFalse(database.containsEntryWithId(entry1.getId())); assertTrue(database.containsEntryWithId(entry2.getId())); assertFalse(database.containsEntryWithId(entry3.getId())); } @Test void removeAllEntriesRemovesAllEntriesFromEntriesList() { List<BibEntry> allEntries = new ArrayList<>(); BibEntry entry1 = new BibEntry(); BibEntry entry2 = new BibEntry(); BibEntry entry3 = new BibEntry(); allEntries.add(entry1); allEntries.add(entry2); allEntries.add(entry3); database.removeEntries(allEntries); assertEquals(Collections.emptyList(), database.getEntries()); assertFalse(database.containsEntryWithId(entry1.getId())); assertFalse(database.containsEntryWithId(entry2.getId())); assertFalse(database.containsEntryWithId(entry3.getId())); } @Test void insertNullEntryThrowsException() { assertThrows(NullPointerException.class, () -> database.insertEntry(null)); } @Test void removeNullEntryThrowsException() { assertThrows(NullPointerException.class, () -> database.removeEntry(null)); } @Test void emptyDatabaseHasNoStrings() { assertEquals(Collections.emptySet(), database.getStringKeySet()); assertTrue(database.hasNoStrings()); } @Test void databaseHasStringAfterInsertion() { database.addString(bibtexString); assertFalse(database.hasNoStrings()); } @Test void databaseStringKeySetIncreasesAfterStringInsertion() { assertEquals(0, database.getStringKeySet().size()); database.addString(bibtexString); assertEquals(1, database.getStringKeySet().size()); } @Test void databaseStringCountIncreasesAfterStringInsertion() { assertEquals(0, database.getStringCount()); database.addString(bibtexString); assertEquals(1, database.getStringCount()); } @Test void databaseContainsNewStringInStringValues() { database.addString(bibtexString); assertTrue(database.getStringValues().contains(bibtexString)); } @Test void retrieveInsertedStringById() { database.addString(bibtexString); assertTrue(database.getStringKeySet().contains(bibtexString.getId())); } @Test void stringIsNotModifiedAfterInsertion() { database.addString(bibtexString); assertEquals(bibtexString, database.getString(bibtexString.getId())); } @Test void databaseHasNoStringsAfterRemoval() { database.addString(bibtexString); assertFalse(database.hasNoStrings()); database.removeString(bibtexString.getId()); assertTrue(database.hasNoStrings()); } @Test void stringKeySizeIsEmptyAfterRemoval() { database.addString(bibtexString); database.removeString(bibtexString.getId()); assertEquals(0, database.getStringKeySet().size()); } @Test void stringCountIsZeroAfterRemoval() { database.addString(bibtexString); assertEquals(1, database.getStringCount()); database.removeString(bibtexString.getId()); assertEquals(0, database.getStringCount()); } @Test void stringValuesDoesNotContainStringAfterRemoval() { database.addString(bibtexString); assertTrue(database.getStringValues().contains(bibtexString)); database.removeString(bibtexString.getId()); assertFalse(database.getStringValues().contains(bibtexString)); } @Test void stringKeySetDoesNotContainStringIdAfterRemoval() { database.addString(bibtexString); assertTrue(database.getStringKeySet().contains(bibtexString.getId())); database.removeString(bibtexString.getId()); assertFalse(database.getStringKeySet().contains(bibtexString.getId())); } @Test void databaseReturnsNullForRemovedString() { database.addString(bibtexString); assertEquals(bibtexString, database.getString(bibtexString.getId())); database.removeString(bibtexString.getId()); assertNull(database.getString(bibtexString.getId())); } @Test void hasStringLabelFindsString() { database.addString(bibtexString); assertTrue(database.hasStringByName("DSP")); assertFalse(database.hasStringByName("VLSI")); } @Test void setSingleStringAsCollection() { List<BibtexString> strings = Arrays.asList(bibtexString); database.setStrings(strings); assertEquals(Optional.of(bibtexString), database.getStringByName("DSP")); } @Test void setStringAsCollectionWithUpdatedContentThrowsKeyCollisionException() { BibtexString newContent = new BibtexString("DSP", "ABCD"); List<BibtexString> strings = Arrays.asList(bibtexString, newContent); assertThrows(KeyCollisionException.class, () -> database.setStrings(strings)); } @Test void setStringAsCollectionWithNewContent() { BibtexString vlsi = new BibtexString("VLSI", "Very Large Scale Integration"); List<BibtexString> strings = Arrays.asList(bibtexString, vlsi); database.setStrings(strings); assertEquals(Optional.of(bibtexString), database.getStringByName("DSP")); assertEquals(Optional.of(vlsi), database.getStringByName("VLSI")); } @Test void addSameStringLabelTwiceThrowsKeyCollisionException() { database.addString(bibtexString); final BibtexString finalString = new BibtexString("DSP", "Digital Signal Processor"); assertThrows(KeyCollisionException.class, () -> database.addString(finalString)); } @Test void addSameStringIdTwiceThrowsKeyCollisionException() { BibtexString string = new BibtexString("DSP", "Digital Signal Processing"); string.setId("duplicateid"); database.addString(string); final BibtexString finalString = new BibtexString("VLSI", "Very Large Scale Integration"); finalString.setId("duplicateid"); assertThrows(KeyCollisionException.class, () -> database.addString(finalString)); } @Test void insertEntryPostsAddedEntryEvent() { BibEntry expectedEntry = new BibEntry(); EventListenerTest tel = new EventListenerTest(); database.registerListener(tel); database.insertEntry(expectedEntry); assertEquals(Collections.singletonList(expectedEntry), tel.getAddedEntries()); assertEquals(expectedEntry, tel.getFirstInsertedEntry()); } @Test void insertMultipleEntriesPostsAddedEntryEvent() { BibEntry firstEntry = new BibEntry(); BibEntry secondEntry = new BibEntry(); EventListenerTest tel = new EventListenerTest(); database.registerListener(tel); database.insertEntries(firstEntry, secondEntry); assertEquals(firstEntry, tel.getFirstInsertedEntry()); assertEquals(Arrays.asList(firstEntry, secondEntry), tel.getAddedEntries()); } @Test void removeEntriesPostsRemovedEntriesEvent() { BibEntry entry1 = new BibEntry(); BibEntry entry2 = new BibEntry(); List<BibEntry> expectedEntries = Arrays.asList(entry1, entry2); EventListenerTest tel = new EventListenerTest(); database.insertEntries(expectedEntries); database.registerListener(tel); database.removeEntries(expectedEntries); List<BibEntry> actualEntry = tel.getRemovedEntries(); assertEquals(expectedEntries, actualEntry); } @Test void changingEntryPostsChangeEntryEvent() { BibEntry entry = new BibEntry(); EventListenerTest tel = new EventListenerTest(); database.insertEntry(entry); database.registerListener(tel); entry.setField(new UnknownField("test"), "some value"); assertEquals(entry, tel.getChangedEntry()); } @Test void correctKeyCountOne() { BibEntry entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); } @Test void correctKeyCountTwo() { BibEntry entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); assertEquals(2, database.getNumberOfCitationKeyOccurrences("AAA")); } @Test void correctKeyCountAfterRemoving() { BibEntry entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); database.removeEntry(entry); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); } @Test void circularStringResolving() { BibtexString string = new BibtexString("AAA", "#BBB#"); database.addString(string); string = new BibtexString("BBB", "#AAA#"); database.addString(string); assertEquals("AAA", database.resolveForStrings("#AAA#")); assertEquals("BBB", database.resolveForStrings("#BBB#")); } @Test void circularStringResolvingLongerCycle() { BibtexString string = new BibtexString("AAA", "#BBB#"); database.addString(string); string = new BibtexString("BBB", "#CCC#"); database.addString(string); string = new BibtexString("CCC", "#DDD#"); database.addString(string); string = new BibtexString("DDD", "#AAA#"); database.addString(string); assertEquals("AAA", database.resolveForStrings("#AAA#")); assertEquals("BBB", database.resolveForStrings("#BBB#")); assertEquals("CCC", database.resolveForStrings("#CCC#")); assertEquals("DDD", database.resolveForStrings("#DDD#")); } @Test void resolveForStringsMonth() { assertEquals("January", database.resolveForStrings("#jan#")); } @Test void resolveForStringsSurroundingContent() { BibtexString string = new BibtexString("AAA", "aaa"); database.addString(string); assertEquals("aaaaaAAA", database.resolveForStrings("aa#AAA#AAA")); } @Test void resolveForStringsOddHashMarkAtTheEnd() { BibtexString string = new BibtexString("AAA", "aaa"); database.addString(string); assertEquals("AAAaaaAAA#", database.resolveForStrings("AAA#AAA#AAA#")); } @Test void getUsedStrings() { BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "#AAA#"); BibtexString tripleA = new BibtexString("AAA", "Some other #BBB#"); BibtexString tripleB = new BibtexString("BBB", "Some more text"); BibtexString tripleC = new BibtexString("CCC", "Even more text"); Set<BibtexString> stringSet = new HashSet<>(); stringSet.add(tripleA); stringSet.add(tripleB); database.addString(tripleA); database.addString(tripleB); database.addString(tripleC); database.insertEntry(entry); Set<BibtexString> usedStrings = new HashSet<>(database.getUsedStrings(Arrays.asList(entry))); assertEquals(stringSet, usedStrings); } @Test void getUsedStringsSingleString() { BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "#AAA#"); BibtexString tripleA = new BibtexString("AAA", "Some other text"); BibtexString tripleB = new BibtexString("BBB", "Some more text"); List<BibtexString> strings = new ArrayList<>(1); strings.add(tripleA); database.addString(tripleA); database.addString(tripleB); database.insertEntry(entry); List<BibtexString> usedStrings = (List<BibtexString>) database.getUsedStrings(Arrays.asList(entry)); assertEquals(strings, usedStrings); } @Test void getUsedStringsNoString() { BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "Oscar Gustafsson"); BibtexString string = new BibtexString("AAA", "Some other text"); database.addString(string); database.insertEntry(entry); Collection<BibtexString> usedStrings = database.getUsedStrings(Arrays.asList(entry)); assertEquals(Collections.emptyList(), usedStrings); } @Test void getEntriesSortedWithTwoEntries() { BibEntry entryB = new BibEntry(StandardEntryType.Article); entryB.setId("2"); BibEntry entryA = new BibEntry(StandardEntryType.Article); entryB.setId("1"); database.insertEntries(entryB, entryA); assertEquals(Arrays.asList(entryA, entryB), database.getEntriesSorted(Comparator.comparing(BibEntry::getId))); } @Test void preambleIsEmptyIfNotSet() { assertEquals(Optional.empty(), database.getPreamble()); } @Test void setPreambleWorks() { database.setPreamble("Oh yeah!"); assertEquals(Optional.of("Oh yeah!"), database.getPreamble()); } }
16,040
33.720779
118
java
null
jabref-main/src/test/java/org/jabref/model/database/DuplicationCheckerTest.java
package org.jabref.model.database; import org.jabref.model.entry.BibEntry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class DuplicationCheckerTest { private BibDatabase database; @BeforeEach void setUp() { database = new BibDatabase(); } @Test void addEntry() { BibEntry entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); } @Test void addAndRemoveEntry() { BibEntry entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); database.removeEntry(entry); assertEquals(0, database.getNumberOfCitationKeyOccurrences("AAA")); } @Test void changeCiteKey() { BibEntry entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); entry.setCitationKey("BBB"); assertEquals(0, database.getNumberOfCitationKeyOccurrences("AAA")); assertEquals(1, database.getNumberOfCitationKeyOccurrences("BBB")); } @Test void setCiteKeySameKeyDifferentEntries() { BibEntry entry0 = new BibEntry(); entry0.setCitationKey("AAA"); database.insertEntry(entry0); BibEntry entry1 = new BibEntry(); entry1.setCitationKey("BBB"); database.insertEntry(entry1); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); assertEquals(1, database.getNumberOfCitationKeyOccurrences("BBB")); entry1.setCitationKey("AAA"); assertEquals(2, database.getNumberOfCitationKeyOccurrences("AAA")); assertEquals(0, database.getNumberOfCitationKeyOccurrences("BBB")); } @Test void removeMultipleCiteKeys() { BibEntry entry0 = new BibEntry(); entry0.setCitationKey("AAA"); database.insertEntry(entry0); BibEntry entry1 = new BibEntry(); entry1.setCitationKey("AAA"); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setCitationKey("AAA"); database.insertEntry(entry2); assertEquals(3, database.getNumberOfCitationKeyOccurrences("AAA")); database.removeEntry(entry2); assertEquals(2, database.getNumberOfCitationKeyOccurrences("AAA")); database.removeEntry(entry1); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); database.removeEntry(entry0); assertEquals(0, database.getNumberOfCitationKeyOccurrences("AAA")); } @Test void addEmptyCiteKey() { BibEntry entry = new BibEntry(); entry.setCitationKey(""); database.insertEntry(entry); assertEquals(0, database.getNumberOfCitationKeyOccurrences("")); } @Test void removeEmptyCiteKey() { BibEntry entry = new BibEntry(); entry.setCitationKey("AAA"); database.insertEntry(entry); assertEquals(1, database.getNumberOfCitationKeyOccurrences("AAA")); entry.setCitationKey(""); database.removeEntry(entry); assertEquals(0, database.getNumberOfCitationKeyOccurrences("AAA")); } }
3,461
31.055556
75
java
null
jabref-main/src/test/java/org/jabref/model/database/KeyChangeListenerTest.java
package org.jabref.model.database; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class KeyChangeListenerTest { private BibDatabase db; private BibEntry entry1; private BibEntry entry2; private BibEntry entry3; private BibEntry entry4; @BeforeEach public void setUp() { db = new BibDatabase(); entry1 = new BibEntry(); entry1.setCitationKey("Entry1"); entry1.setField(StandardField.CROSSREF, "Entry4"); db.insertEntry(entry1); entry2 = new BibEntry(); entry2.setCitationKey("Entry2"); entry2.setField(StandardField.RELATED, "Entry1,Entry3"); db.insertEntry(entry2); entry3 = new BibEntry(); entry3.setCitationKey("Entry3"); entry3.setField(StandardField.RELATED, "Entry1,Entry2,Entry3"); db.insertEntry(entry3); entry4 = new BibEntry(); entry4.setCitationKey("Entry4"); db.insertEntry(entry4); } @Test public void testCrossrefChanged() { assertEquals(Optional.of("Entry4"), entry1.getField(StandardField.CROSSREF)); entry4.setCitationKey("Banana"); assertEquals(Optional.of("Banana"), entry1.getField(StandardField.CROSSREF)); } @Test public void testRelatedChanged() { assertEquals(Optional.of("Entry1,Entry3"), entry2.getField(StandardField.RELATED)); entry1.setCitationKey("Banana"); assertEquals(Optional.of("Banana,Entry3"), entry2.getField(StandardField.RELATED)); } @Test public void testRelatedChangedInSameEntry() { assertEquals(Optional.of("Entry1,Entry2,Entry3"), entry3.getField(StandardField.RELATED)); entry3.setCitationKey("Banana"); assertEquals(Optional.of("Entry1,Entry2,Banana"), entry3.getField(StandardField.RELATED)); } @Test public void testCrossrefRemoved() { entry4.clearField(InternalField.KEY_FIELD); assertEquals(Optional.empty(), entry1.getField(StandardField.CROSSREF)); } @Test public void testCrossrefEntryRemoved() { db.removeEntry(entry4); assertEquals(Optional.empty(), entry1.getField(StandardField.CROSSREF)); } @Test public void testRelatedEntryRemoved() { db.removeEntry(entry1); assertEquals(Optional.of("Entry3"), entry2.getField(StandardField.RELATED)); } @Test public void testRelatedAllEntriesRemoved() { List<BibEntry> entries = Arrays.asList(entry1, entry3); db.removeEntries(entries); assertEquals(Optional.empty(), entry2.getField(StandardField.RELATED)); } }
2,928
30.159574
98
java
null
jabref-main/src/test/java/org/jabref/model/entry/AuthorListTest.java
package org.jabref.model.entry; import java.util.Arrays; import java.util.Collections; import java.util.Optional; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class AuthorListTest { /* Examples are similar to page 4 in [BibTeXing by Oren Patashnik](https://ctan.org/tex-archive/biblio/bibtex/contrib/doc/) */ private static final Author MUHAMMAD_ALKHWARIZMI = new Author("Mu{\\d{h}}ammad", "M.", null, "al-Khw{\\={a}}rizm{\\={i}}", null); private static final Author CORRADO_BOHM = new Author("Corrado", "C.", null, "B{\\\"o}hm", null); private static final Author KURT_GODEL = new Author("Kurt", "K.", null, "G{\\\"{o}}del", null); private static final Author BANU_MOSA = new Author(null, null, null, "{The Ban\\={u} M\\={u}s\\={a} brothers}", null); private static final AuthorList EMPTY_AUTHOR = AuthorList.of(Collections.emptyList()); private static final AuthorList ONE_AUTHOR_WITH_LATEX = AuthorList.of(MUHAMMAD_ALKHWARIZMI); private static final AuthorList TWO_AUTHORS_WITH_LATEX = AuthorList.of(MUHAMMAD_ALKHWARIZMI, CORRADO_BOHM); private static final AuthorList THREE_AUTHORS_WITH_LATEX = AuthorList.of(MUHAMMAD_ALKHWARIZMI, CORRADO_BOHM, KURT_GODEL); private static final AuthorList ONE_INSTITUTION_WITH_LATEX = AuthorList.of(BANU_MOSA); private static final AuthorList ONE_INSTITUTION_WITH_STARTING_PARANTHESIS = AuthorList.of(new Author( null, null, null, "{{\\L{}}ukasz Micha\\l{}}", null)); private static final AuthorList TWO_INSTITUTIONS_WITH_LATEX = AuthorList.of(BANU_MOSA, BANU_MOSA); private static final AuthorList MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX = AuthorList.of(BANU_MOSA, CORRADO_BOHM); public static int size(String bibtex) { return AuthorList.parse(bibtex).getNumberOfAuthors(); } @Test public void testFixAuthorNatbib() { assertEquals("", AuthorList.fixAuthorNatbib("")); assertEquals("Smith", AuthorList.fixAuthorNatbib("John Smith")); assertEquals("Smith and Black Brown", AuthorList .fixAuthorNatbib("John Smith and Black Brown, Peter")); assertEquals("von Neumann et al.", AuthorList .fixAuthorNatbib("John von Neumann and John Smith and Black Brown, Peter")); } @Test public void getAsNatbibLatexFreeEmptyAuthorStringForEmptyInput() { assertEquals("", EMPTY_AUTHOR.latexFree().getAsNatbib()); } @Test public void getAsNatbibLatexFreeUnicodeOneAuthorNameFromLatex() { assertEquals("al-Khwārizmī", ONE_AUTHOR_WITH_LATEX.latexFree().getAsNatbib()); } @Test public void getAsNatbibLatexFreeUnicodeTwoAuthorNamesFromLatex() { assertEquals("al-Khwārizmī and Böhm", TWO_AUTHORS_WITH_LATEX.latexFree().getAsNatbib()); } @Test public void getAsNatbibLatexFreeUnicodeAuthorEtAlFromLatex() { assertEquals("al-Khwārizmī et al.", THREE_AUTHORS_WITH_LATEX.latexFree().getAsNatbib()); } @Test public void getAsNatbibLatexFreeUnicodeOneInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsNatbib()); } @Test public void getAsNatbibLatexFreeUnicodeTwoInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsNatbib()); } @Test public void getAsNatbibLatexFreeUnicodeMixedAuthorsFromLatex() { assertEquals("The Banū Mūsā brothers and Böhm", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsNatbib()); } @Test public void getAsNatbibLatexFreeOneInstitutionWithParanthesisAtStart() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsNatbib()); } @Test public void parseCachesOneAuthor() { // Test caching in authorCache. AuthorList authorList = AuthorList.parse("John Smith"); assertSame(authorList, AuthorList.parse("John Smith")); assertNotSame(authorList, AuthorList.parse("Smith")); } @Test public void parseCachesOneLatexFreeAuthor() { // Test caching in authorCache. AuthorList authorList = AuthorList.parse("John Smith").latexFree(); assertSame(authorList, AuthorList.parse("John Smith").latexFree()); assertNotSame(authorList, AuthorList.parse("Smith").latexFree()); } @Test public void testFixAuthorFirstNameFirstCommas() { // No Commas assertEquals("", AuthorList.fixAuthorFirstNameFirstCommas("", true, false)); assertEquals("", AuthorList.fixAuthorFirstNameFirstCommas("", false, false)); assertEquals("John Smith", AuthorList.fixAuthorFirstNameFirstCommas("John Smith", false, false)); assertEquals("J. Smith", AuthorList.fixAuthorFirstNameFirstCommas("John Smith", true, false)); // Check caching assertEquals(AuthorList.fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, false), AuthorList .fixAuthorFirstNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, false)); assertEquals("John Smith and Peter Black Brown", AuthorList .fixAuthorFirstNameFirstCommas("John Smith and Black Brown, Peter", false, false)); assertEquals("J. Smith and P. Black Brown", AuthorList.fixAuthorFirstNameFirstCommas( "John Smith and Black Brown, Peter", true, false)); // Method description is different from code -> additional comma // there assertEquals("John von Neumann, John Smith and Peter Black Brown", AuthorList .fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", false, false)); assertEquals("J. von Neumann, J. Smith and P. Black Brown", AuthorList .fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, false)); assertEquals("J. P. von Neumann", AuthorList.fixAuthorFirstNameFirstCommas( "John Peter von Neumann", true, false)); // Oxford Commas assertEquals("", AuthorList.fixAuthorFirstNameFirstCommas("", true, true)); assertEquals("", AuthorList.fixAuthorFirstNameFirstCommas("", false, true)); assertEquals("John Smith", AuthorList.fixAuthorFirstNameFirstCommas("John Smith", false, true)); assertEquals("J. Smith", AuthorList.fixAuthorFirstNameFirstCommas("John Smith", true, true)); // Check caching assertEquals(AuthorList.fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, true), AuthorList .fixAuthorFirstNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, true)); assertEquals("John Smith and Peter Black Brown", AuthorList .fixAuthorFirstNameFirstCommas("John Smith and Black Brown, Peter", false, true)); assertEquals("J. Smith and P. Black Brown", AuthorList.fixAuthorFirstNameFirstCommas( "John Smith and Black Brown, Peter", true, true)); // Method description is different than code -> additional comma // there assertEquals("John von Neumann, John Smith, and Peter Black Brown", AuthorList .fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", false, true)); assertEquals("J. von Neumann, J. Smith, and P. Black Brown", AuthorList .fixAuthorFirstNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, true)); assertEquals("J. P. von Neumann", AuthorList.fixAuthorFirstNameFirstCommas( "John Peter von Neumann", true, true)); } @Test public void getAsFirstLastNamesLatexFreeEmptyAuthorStringForEmptyInputAbbreviate() { assertEquals("", EMPTY_AUTHOR.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeOneAuthorNameFromLatexAbbreviate() { assertEquals("M. al-Khwārizmī", ONE_AUTHOR_WITH_LATEX.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeTwoAuthorNamesFromLatexAbbreviate() { assertEquals("M. al-Khwārizmī and C. Böhm", TWO_AUTHORS_WITH_LATEX.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeTwoAuthorNamesFromLatexAbbreviateAndOxfordComma() { assertEquals("M. al-Khwārizmī and C. Böhm", TWO_AUTHORS_WITH_LATEX.latexFree().getAsFirstLastNames(true, true)); } @Test public void getAsFirstLastNamesLatexFreeThreeUnicodeAuthorsFromLatexAbbreviate() { assertEquals("M. al-Khwārizmī, C. Böhm and K. Gödel", THREE_AUTHORS_WITH_LATEX.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeThreeUnicodeAuthorsFromLatexAbbreviateAndOxfordComma() { assertEquals("M. al-Khwārizmī, C. Böhm, and K. Gödel", THREE_AUTHORS_WITH_LATEX.latexFree().getAsFirstLastNames(true, true)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeOneInsitutionNameFromLatexAbbreviate() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeTwoInsitutionNameFromLatexAbbreviate() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeMixedAuthorsFromLatexAbbreviate() { assertEquals("The Banū Mūsā brothers and C. Böhm", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeOneInstitutionWithParanthesisAtStartAbbreviate() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsFirstLastNames(true, false)); } @Test public void getAsFirstLastNamesLatexFreeEmptyAuthorStringForEmptyInput() { assertEquals("", EMPTY_AUTHOR.latexFree().getAsFirstLastNames(false, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeOneAuthorNameFromLatex() { assertEquals("Muḥammad al-Khwārizmī", ONE_AUTHOR_WITH_LATEX.latexFree().getAsFirstLastNames(false, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeTwoAuthorNamesFromLatex() { assertEquals("Muḥammad al-Khwārizmī and Corrado Böhm", TWO_AUTHORS_WITH_LATEX.latexFree().getAsFirstLastNames(false, false)); } @Test public void getAsFirstLastNamesLatexFreeThreeUnicodeAuthorsFromLatex() { assertEquals("Muḥammad al-Khwārizmī, Corrado Böhm and Kurt Gödel", THREE_AUTHORS_WITH_LATEX.latexFree().getAsFirstLastNames(false, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeOneInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsFirstLastNames(false, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeTwoInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsFirstLastNames(false, false)); } @Test public void getAsFirstLastNamesLatexFreeUnicodeMixedAuthorsFromLatex() { assertEquals("The Banū Mūsā brothers and Corrado Böhm", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsFirstLastNames(false, false)); } @Test public void getAsFirstLastNamesLatexFreeOneInstitutionWithParanthesisAtStart() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsFirstLastNames(false, false)); } @Test public void testFixAuthorFirstNameFirst() { assertEquals("John Smith", AuthorList.fixAuthorFirstNameFirst("John Smith")); assertEquals("John Smith and Peter Black Brown", AuthorList .fixAuthorFirstNameFirst("John Smith and Black Brown, Peter")); assertEquals("John von Neumann and John Smith and Peter Black Brown", AuthorList .fixAuthorFirstNameFirst("John von Neumann and John Smith and Black Brown, Peter")); assertEquals("First von Last, Jr. III", AuthorList .fixAuthorFirstNameFirst("von Last, Jr. III, First")); // Check caching assertEquals(AuthorList .fixAuthorFirstNameFirst("John von Neumann and John Smith and Black Brown, Peter"), AuthorList .fixAuthorFirstNameFirst("John von Neumann and John Smith and Black Brown, Peter")); } @Test public void testFixAuthorLastNameFirstCommasNoComma() { // No commas before and assertEquals("", AuthorList.fixAuthorLastNameFirstCommas("", true, false)); assertEquals("", AuthorList.fixAuthorLastNameFirstCommas("", false, false)); assertEquals("Smith, John", AuthorList.fixAuthorLastNameFirstCommas("John Smith", false, false)); assertEquals("Smith, J.", AuthorList.fixAuthorLastNameFirstCommas("John Smith", true, false)); String a = AuthorList.fixAuthorLastNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, false); String b = AuthorList.fixAuthorLastNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, false); // Check caching assertEquals(a, b); assertEquals("Smith, John and Black Brown, Peter", AuthorList.fixAuthorLastNameFirstCommas("John Smith and Black Brown, Peter", false, false)); assertEquals("Smith, J. and Black Brown, P.", AuthorList.fixAuthorLastNameFirstCommas("John Smith and Black Brown, Peter", true, false)); assertEquals("von Neumann, John, Smith, John and Black Brown, Peter", AuthorList .fixAuthorLastNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", false, false)); assertEquals("von Neumann, J., Smith, J. and Black Brown, P.", AuthorList .fixAuthorLastNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, false)); assertEquals("von Neumann, J. P.", AuthorList.fixAuthorLastNameFirstCommas("John Peter von Neumann", true, false)); } @Test public void testFixAuthorLastNameFirstCommasOxfordComma() { // Oxford Commas assertEquals("", AuthorList.fixAuthorLastNameFirstCommas("", true, true)); assertEquals("", AuthorList.fixAuthorLastNameFirstCommas("", false, true)); assertEquals("Smith, John", AuthorList.fixAuthorLastNameFirstCommas("John Smith", false, true)); assertEquals("Smith, J.", AuthorList.fixAuthorLastNameFirstCommas("John Smith", true, true)); String a = AuthorList.fixAuthorLastNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, true); String b = AuthorList.fixAuthorLastNameFirstCommas("John von Neumann and John Smith and Black Brown, Peter", true, true); // Check caching assertEquals(a, b); // assertSame(a, b); assertEquals("Smith, John and Black Brown, Peter", AuthorList .fixAuthorLastNameFirstCommas("John Smith and Black Brown, Peter", false, true)); assertEquals("Smith, J. and Black Brown, P.", AuthorList.fixAuthorLastNameFirstCommas( "John Smith and Black Brown, Peter", true, true)); assertEquals("von Neumann, John, Smith, John, and Black Brown, Peter", AuthorList .fixAuthorLastNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", false, true)); assertEquals("von Neumann, J., Smith, J., and Black Brown, P.", AuthorList .fixAuthorLastNameFirstCommas( "John von Neumann and John Smith and Black Brown, Peter", true, true)); assertEquals("von Neumann, J. P.", AuthorList.fixAuthorLastNameFirstCommas( "John Peter von Neumann", true, true)); } @Test public void getAsLastFirstNamesLatexFreeEmptyAuthorStringForEmptyInputAbbr() { assertEquals("", EMPTY_AUTHOR.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneAuthorNameFromLatexAbbr() { assertEquals("al-Khwārizmī, M.", ONE_AUTHOR_WITH_LATEX.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoAuthorNamesFromLatexAbbr() { assertEquals("al-Khwārizmī, M. and Böhm, C.", TWO_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeThreeUnicodeAuthorsFromLatexAbbr() { assertEquals("al-Khwārizmī, M., Böhm, C. and Gödel, K.", THREE_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneInsitutionNameFromLatexAbbr() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoInsitutionNameFromLatexAbbr() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeMixedAuthorsFromLatexAbbr() { assertEquals("The Banū Mūsā brothers and Böhm, C.", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeOneInstitutionWithParanthesisAtStartAbbr() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsLastFirstNames(true, false)); } @Test public void getAsLastFirstNamesLatexFreeEmptyAuthorStringForEmptyInput() { assertEquals("", EMPTY_AUTHOR.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneAuthorNameFromLatex() { assertEquals("al-Khwārizmī, Muḥammad", ONE_AUTHOR_WITH_LATEX.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoAuthorNamesFromLatex() { assertEquals("al-Khwārizmī, Muḥammad and Böhm, Corrado", TWO_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeThreeUnicodeAuthorsFromLatex() { assertEquals("al-Khwārizmī, Muḥammad, Böhm, Corrado and Gödel, Kurt", THREE_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeMixedAuthorsFromLatex() { assertEquals("The Banū Mūsā brothers and Böhm, Corrado", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeOneInstitutionWithParanthesisAtStart() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsLastFirstNames(false, false)); } @Test public void getAsLastFirstNamesLatexFreeEmptyAuthorStringForEmptyInputAbbrOxfordComma() { assertEquals("", EMPTY_AUTHOR.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneAuthorNameFromLatexAbbrOxfordComma() { assertEquals("al-Khwārizmī, M.", ONE_AUTHOR_WITH_LATEX.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoAuthorNamesFromLatexAbbrOxfordComma() { assertEquals("al-Khwārizmī, M. and Böhm, C.", TWO_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeThreeUnicodeAuthorsFromLatexAbbrOxfordComma() { assertEquals("al-Khwārizmī, M., Böhm, C., and Gödel, K.", THREE_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneInsitutionNameFromLatexAbbrOxfordComma() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoInsitutionNameFromLatexAbbrOxfordComma() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeMixedAuthorsFromLatexAbbrOxfordComma() { assertEquals("The Banū Mūsā brothers and Böhm, C.", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeOneInstitutionWithParanthesisAtStartAbbrOxfordComma() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsLastFirstNames(true, true)); } @Test public void getAsLastFirstNamesLatexFreeEmptyAuthorStringForEmptyInputOxfordComma() { assertEquals("", EMPTY_AUTHOR.latexFree().getAsLastFirstNames(false, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneAuthorNameFromLatexOxfordComma() { assertEquals("al-Khwārizmī, Muḥammad", ONE_AUTHOR_WITH_LATEX.latexFree().getAsLastFirstNames(false, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoAuthorNamesFromLatexOxfordComma() { assertEquals("al-Khwārizmī, Muḥammad and Böhm, Corrado", TWO_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(false, true)); } @Test public void getAsLastFirstNamesLatexFreeThreeUnicodeAuthorsFromLatexOxfordComma() { assertEquals("al-Khwārizmī, Muḥammad, Böhm, Corrado, and Gödel, Kurt", THREE_AUTHORS_WITH_LATEX.latexFree().getAsLastFirstNames(false, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeOneInsitutionNameFromLatexOxfordComma() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(false, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeTwoInsitutionNameFromLatexOxfordComma() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsLastFirstNames(false, true)); } @Test public void getAsLastFirstNamesLatexFreeUnicodeMixedAuthorsFromLatexOxfordComma() { assertEquals("The Banū Mūsā brothers and Böhm, Corrado", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsLastFirstNames(false, true)); } @Test public void getAsLastFirstNamesLatexFreeOneInstitutionWithParanthesisAtStartOxfordComma() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsLastFirstNames(false, true)); } @Test public void testFixAuthorLastNameFirst() { // Test helper method assertEquals("Smith, John", AuthorList.fixAuthorLastNameFirst("John Smith")); assertEquals("Smith, John and Black Brown, Peter", AuthorList .fixAuthorLastNameFirst("John Smith and Black Brown, Peter")); assertEquals("von Neumann, John and Smith, John and Black Brown, Peter", AuthorList .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter")); assertEquals("von Last, Jr, First", AuthorList .fixAuthorLastNameFirst("von Last, Jr ,First")); assertEquals(AuthorList .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter"), AuthorList .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter")); // Test Abbreviation == false assertEquals("Smith, John", AuthorList.fixAuthorLastNameFirst("John Smith", false)); assertEquals("Smith, John and Black Brown, Peter", AuthorList.fixAuthorLastNameFirst( "John Smith and Black Brown, Peter", false)); assertEquals("von Neumann, John and Smith, John and Black Brown, Peter", AuthorList .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter", false)); assertEquals("von Last, Jr, First", AuthorList.fixAuthorLastNameFirst( "von Last, Jr ,First", false)); assertEquals(AuthorList.fixAuthorLastNameFirst( "John von Neumann and John Smith and Black Brown, Peter", false), AuthorList .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter", false)); // Test Abbreviate == true assertEquals("Smith, J.", AuthorList.fixAuthorLastNameFirst("John Smith", true)); assertEquals("Smith, J. and Black Brown, P.", AuthorList.fixAuthorLastNameFirst( "John Smith and Black Brown, Peter", true)); assertEquals("von Neumann, J. and Smith, J. and Black Brown, P.", AuthorList.fixAuthorLastNameFirst( "John von Neumann and John Smith and Black Brown, Peter", true)); assertEquals("von Last, Jr, F.", AuthorList.fixAuthorLastNameFirst("von Last, Jr ,First", true)); assertEquals(AuthorList.fixAuthorLastNameFirst( "John von Neumann and John Smith and Black Brown, Peter", true), AuthorList .fixAuthorLastNameFirst("John von Neumann and John Smith and Black Brown, Peter", true)); } @Test public void testFixAuthorLastNameOnlyCommas() { // No comma before and assertEquals("", AuthorList.fixAuthorLastNameOnlyCommas("", false)); assertEquals("Smith", AuthorList.fixAuthorLastNameOnlyCommas("John Smith", false)); assertEquals("Smith", AuthorList.fixAuthorLastNameOnlyCommas("Smith, Jr, John", false)); assertEquals(AuthorList.fixAuthorLastNameOnlyCommas( "John von Neumann and John Smith and Black Brown, Peter", false), AuthorList .fixAuthorLastNameOnlyCommas("John von Neumann and John Smith and Black Brown, Peter", false)); assertEquals("von Neumann, Smith and Black Brown", AuthorList .fixAuthorLastNameOnlyCommas( "John von Neumann and John Smith and Black Brown, Peter", false)); // Oxford Comma assertEquals("", AuthorList.fixAuthorLastNameOnlyCommas("", true)); assertEquals("Smith", AuthorList.fixAuthorLastNameOnlyCommas("John Smith", true)); assertEquals("Smith", AuthorList.fixAuthorLastNameOnlyCommas("Smith, Jr, John", true)); assertEquals(AuthorList.fixAuthorLastNameOnlyCommas( "John von Neumann and John Smith and Black Brown, Peter", true), AuthorList .fixAuthorLastNameOnlyCommas("John von Neumann and John Smith and Black Brown, Peter", true)); assertEquals("von Neumann, Smith, and Black Brown", AuthorList .fixAuthorLastNameOnlyCommas( "John von Neumann and John Smith and Black Brown, Peter", true)); } @Test public void getAsLastNamesLatexFreeUnicodeOneAuthorNameFromLatex() { assertEquals("al-Khwārizmī", ONE_AUTHOR_WITH_LATEX.latexFree().getAsLastNames(false)); } @Test public void getAsLastNamesLatexFreeUnicodeTwoAuthorNamesFromLatex() { assertEquals("al-Khwārizmī and Böhm", TWO_AUTHORS_WITH_LATEX.latexFree().getAsLastNames(false)); } @Test public void getAsLastNamesLatexFreeUnicodeTwoAuthorNamesFromLatexUsingOxfordComma() { assertEquals("al-Khwārizmī and Böhm", TWO_AUTHORS_WITH_LATEX.latexFree().getAsLastNames(true)); } @Test public void getAsLastNamesLatexFreeUnicodeThreeAuthorsFromLatex() { assertEquals("al-Khwārizmī, Böhm and Gödel", THREE_AUTHORS_WITH_LATEX.latexFree().getAsLastNames(false)); } @Test public void getAsLastNamesLatexFreeUnicodeThreeAuthorsFromLatexUsingOxfordComma() { assertEquals("al-Khwārizmī, Böhm, and Gödel", THREE_AUTHORS_WITH_LATEX.latexFree().getAsLastNames(true)); } @Test public void getAsLastNamesLatexFreeUnicodeOneInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers", ONE_INSTITUTION_WITH_LATEX.latexFree().getAsLastNames(false)); } @Test public void getAsLastNamesLatexFreeUnicodeTwoInsitutionNameFromLatex() { assertEquals("The Banū Mūsā brothers and The Banū Mūsā brothers", TWO_INSTITUTIONS_WITH_LATEX.latexFree().getAsLastNames(false)); } @Test public void getAsLastNamesLatexFreeUnicodeMixedAuthorsFromLatex() { assertEquals("The Banū Mūsā brothers and Böhm", MIXED_AUTHOR_AND_INSTITUTION_WITH_LATEX.latexFree().getAsLastNames(false)); } @Test public void getAsLastNamesLatexFreeOneInstitutionWithParanthesisAtStart() { assertEquals("Łukasz Michał", ONE_INSTITUTION_WITH_STARTING_PARANTHESIS.latexFree().getAsLastNames(false)); } @Test public void testFixAuthorForAlphabetization() { assertEquals("Smith, J.", AuthorList.fixAuthorForAlphabetization("John Smith")); assertEquals("Neumann, J.", AuthorList.fixAuthorForAlphabetization("John von Neumann")); assertEquals("Neumann, J.", AuthorList.fixAuthorForAlphabetization("J. von Neumann")); assertEquals( "Neumann, J. and Smith, J. and Black Brown, Jr., P.", AuthorList .fixAuthorForAlphabetization("John von Neumann and John Smith and de Black Brown, Jr., Peter")); } @Test public void testSize() { assertEquals(0, AuthorListTest.size("")); assertEquals(1, AuthorListTest.size("Bar")); assertEquals(1, AuthorListTest.size("Foo Bar")); assertEquals(1, AuthorListTest.size("Foo von Bar")); assertEquals(1, AuthorListTest.size("von Bar, Foo")); assertEquals(1, AuthorListTest.size("Bar, Foo")); assertEquals(1, AuthorListTest.size("Bar, Jr., Foo")); assertEquals(1, AuthorListTest.size("Bar, Foo")); assertEquals(2, AuthorListTest.size("John Neumann and Foo Bar")); assertEquals(2, AuthorListTest.size("John von Neumann and Bar, Jr, Foo")); assertEquals(3, AuthorListTest.size("John von Neumann and John Smith and Black Brown, Peter")); StringBuilder s = new StringBuilder("John von Neumann"); for (int i = 0; i < 25; i++) { assertEquals(i + 1, AuthorListTest.size(s.toString())); s.append(" and Albert Einstein"); } } @Test public void testIsEmpty() { assertTrue(AuthorList.parse("").isEmpty()); assertFalse(AuthorList.parse("Bar").isEmpty()); } @Test public void testGetEmptyAuthor() { assertThrows(Exception.class, () -> AuthorList.parse("").getAuthor(0)); } @Test public void testGetAuthor() { Author author = AuthorList.parse("John Smith and von Neumann, Jr, John").getAuthor(0); assertEquals(Optional.of("John"), author.getFirst()); assertEquals(Optional.of("J."), author.getFirstAbbr()); assertEquals("John Smith", author.getFirstLast(false)); assertEquals("J. Smith", author.getFirstLast(true)); assertEquals(Optional.empty(), author.getJr()); assertEquals(Optional.of("Smith"), author.getLast()); assertEquals("Smith, John", author.getLastFirst(false)); assertEquals("Smith, J.", author.getLastFirst(true)); assertEquals("Smith", author.getLastOnly()); assertEquals("Smith, J.", author.getNameForAlphabetization()); assertEquals(Optional.empty(), author.getVon()); author = AuthorList.parse("Peter Black Brown").getAuthor(0); assertEquals(Optional.of("Peter Black"), author.getFirst()); assertEquals(Optional.of("P. B."), author.getFirstAbbr()); assertEquals("Peter Black Brown", author.getFirstLast(false)); assertEquals("P. B. Brown", author.getFirstLast(true)); assertEquals(Optional.empty(), author.getJr()); assertEquals(Optional.empty(), author.getVon()); author = AuthorList.parse("John Smith and von Neumann, Jr, John").getAuthor(1); assertEquals(Optional.of("John"), author.getFirst()); assertEquals(Optional.of("J."), author.getFirstAbbr()); assertEquals("John von Neumann, Jr", author.getFirstLast(false)); assertEquals("J. von Neumann, Jr", author.getFirstLast(true)); assertEquals(Optional.of("Jr"), author.getJr()); assertEquals(Optional.of("Neumann"), author.getLast()); assertEquals("von Neumann, Jr, John", author.getLastFirst(false)); assertEquals("von Neumann, Jr, J.", author.getLastFirst(true)); assertEquals("von Neumann", author.getLastOnly()); assertEquals("Neumann, Jr, J.", author.getNameForAlphabetization()); assertEquals(Optional.of("von"), author.getVon()); } @Test public void testCompanyAuthor() { Author author = AuthorList.parse("{JabRef Developers}").getAuthor(0); Author expected = new Author(null, null, null, "JabRef Developers", null); assertEquals(expected, author); } @Test public void testCompanyAuthorAndPerson() { Author company = new Author(null, null, null, "JabRef Developers", null); Author person = new Author("Stefan", "S.", null, "Kolb", null); assertEquals(Arrays.asList(company, person), AuthorList.parse("{JabRef Developers} and Stefan Kolb").getAuthors()); } @Test public void testCompanyAuthorWithLowerCaseWord() { Author author = AuthorList.parse("{JabRef Developers on Fire}").getAuthor(0); Author expected = new Author(null, null, null, "JabRef Developers on Fire", null); assertEquals(expected, author); } @Test public void testAbbreviationWithRelax() { Author author = AuthorList.parse("{\\relax Ch}ristoph Cholera").getAuthor(0); Author expected = new Author("{\\relax Ch}ristoph", "{\\relax Ch}.", null, "Cholera", null); assertEquals(expected, author); } @Test public void testGetAuthorsNatbib() { assertEquals("", AuthorList.parse("").getAsNatbib()); assertEquals("Smith", AuthorList.parse("John Smith").getAsNatbib()); assertEquals("Smith and Black Brown", AuthorList.parse( "John Smith and Black Brown, Peter").getAsNatbib()); assertEquals("von Neumann et al.", AuthorList.parse( "John von Neumann and John Smith and Black Brown, Peter").getAsNatbib()); /* * [ 1465610 ] (Double-)Names containing hyphen (-) not handled correctly */ assertEquals("Last-Name et al.", AuthorList.parse( "First Second Last-Name" + " and John Smith and Black Brown, Peter").getAsNatbib()); // Test caching AuthorList al = AuthorList .parse("John von Neumann and John Smith and Black Brown, Peter"); assertEquals(al.getAsNatbib(), al.getAsNatbib()); } @Test public void testGetAuthorsLastOnly() { // No comma before and assertEquals("", AuthorList.parse("").getAsLastNames(false)); assertEquals("Smith", AuthorList.parse("John Smith").getAsLastNames(false)); assertEquals("Smith", AuthorList.parse("Smith, Jr, John").getAsLastNames( false)); assertEquals("von Neumann, Smith and Black Brown", AuthorList.parse( "John von Neumann and John Smith and Black Brown, Peter").getAsLastNames(false)); // Oxford comma assertEquals("", AuthorList.parse("").getAsLastNames(true)); assertEquals("Smith", AuthorList.parse("John Smith").getAsLastNames(true)); assertEquals("Smith", AuthorList.parse("Smith, Jr, John").getAsLastNames( true)); assertEquals("von Neumann, Smith, and Black Brown", AuthorList.parse( "John von Neumann and John Smith and Black Brown, Peter").getAsLastNames(true)); assertEquals("von Neumann and Smith", AuthorList.parse("John von Neumann and John Smith").getAsLastNames(false)); } @Test public void testGetAuthorsLastFirstNoComma() { // No commas before and AuthorList al; al = AuthorList.parse(""); assertEquals("", al.getAsLastFirstNames(true, false)); assertEquals("", al.getAsLastFirstNames(false, false)); al = AuthorList.parse("John Smith"); assertEquals("Smith, John", al.getAsLastFirstNames(false, false)); assertEquals("Smith, J.", al.getAsLastFirstNames(true, false)); al = AuthorList.parse("John Smith and Black Brown, Peter"); assertEquals("Smith, John and Black Brown, Peter", al.getAsLastFirstNames(false, false)); assertEquals("Smith, J. and Black Brown, P.", al.getAsLastFirstNames(true, false)); al = AuthorList.parse("John von Neumann and John Smith and Black Brown, Peter"); // Method description is different than code -> additional comma // there assertEquals("von Neumann, John, Smith, John and Black Brown, Peter", al.getAsLastFirstNames(false, false)); assertEquals("von Neumann, J., Smith, J. and Black Brown, P.", al.getAsLastFirstNames(true, false)); al = AuthorList.parse("John Peter von Neumann"); assertEquals("von Neumann, J. P.", al.getAsLastFirstNames(true, false)); } @Test public void testGetAuthorsLastFirstOxfordComma() { // Oxford comma AuthorList al; al = AuthorList.parse(""); assertEquals("", al.getAsLastFirstNames(true, true)); assertEquals("", al.getAsLastFirstNames(false, true)); al = AuthorList.parse("John Smith"); assertEquals("Smith, John", al.getAsLastFirstNames(false, true)); assertEquals("Smith, J.", al.getAsLastFirstNames(true, true)); al = AuthorList.parse("John Smith and Black Brown, Peter"); assertEquals("Smith, John and Black Brown, Peter", al.getAsLastFirstNames(false, true)); assertEquals("Smith, J. and Black Brown, P.", al.getAsLastFirstNames(true, true)); al = AuthorList.parse("John von Neumann and John Smith and Black Brown, Peter"); assertEquals("von Neumann, John, Smith, John, and Black Brown, Peter", al .getAsLastFirstNames(false, true)); assertEquals("von Neumann, J., Smith, J., and Black Brown, P.", al.getAsLastFirstNames( true, true)); al = AuthorList.parse("John Peter von Neumann"); assertEquals("von Neumann, J. P.", al.getAsLastFirstNames(true, true)); } @Test public void testGetAuthorsLastFirstAnds() { assertEquals("Smith, John", AuthorList.parse("John Smith").getAsLastFirstNamesWithAnd( false)); assertEquals("Smith, John and Black Brown, Peter", AuthorList.parse( "John Smith and Black Brown, Peter").getAsLastFirstNamesWithAnd(false)); assertEquals("von Neumann, John and Smith, John and Black Brown, Peter", AuthorList .parse("John von Neumann and John Smith and Black Brown, Peter") .getAsLastFirstNamesWithAnd(false)); assertEquals("von Last, Jr, First", AuthorList.parse("von Last, Jr ,First") .getAsLastFirstNamesWithAnd(false)); assertEquals("Smith, J.", AuthorList.parse("John Smith").getAsLastFirstNamesWithAnd( true)); assertEquals("Smith, J. and Black Brown, P.", AuthorList.parse( "John Smith and Black Brown, Peter").getAsLastFirstNamesWithAnd(true)); assertEquals("von Neumann, J. and Smith, J. and Black Brown, P.", AuthorList.parse( "John von Neumann and John Smith and Black Brown, Peter").getAsLastFirstNamesWithAnd(true)); assertEquals("von Last, Jr, F.", AuthorList.parse("von Last, Jr ,First") .getAsLastFirstNamesWithAnd(true)); } @Test public void testGetAuthorsFirstFirst() { AuthorList al; al = AuthorList.parse(""); assertEquals("", al.getAsFirstLastNames(true, false)); assertEquals("", al.getAsFirstLastNames(false, false)); assertEquals("", al.getAsFirstLastNames(true, true)); assertEquals("", al.getAsFirstLastNames(false, true)); al = AuthorList.parse("John Smith"); assertEquals("John Smith", al.getAsFirstLastNames(false, false)); assertEquals("J. Smith", al.getAsFirstLastNames(true, false)); assertEquals("John Smith", al.getAsFirstLastNames(false, true)); assertEquals("J. Smith", al.getAsFirstLastNames(true, true)); al = AuthorList.parse("John Smith and Black Brown, Peter"); assertEquals("John Smith and Peter Black Brown", al.getAsFirstLastNames(false, false)); assertEquals("J. Smith and P. Black Brown", al.getAsFirstLastNames(true, false)); assertEquals("John Smith and Peter Black Brown", al.getAsFirstLastNames(false, true)); assertEquals("J. Smith and P. Black Brown", al.getAsFirstLastNames(true, true)); al = AuthorList.parse("John von Neumann and John Smith and Black Brown, Peter"); assertEquals("John von Neumann, John Smith and Peter Black Brown", al.getAsFirstLastNames( false, false)); assertEquals("J. von Neumann, J. Smith and P. Black Brown", al.getAsFirstLastNames(true, false)); assertEquals("John von Neumann, John Smith, and Peter Black Brown", al .getAsFirstLastNames(false, true)); assertEquals("J. von Neumann, J. Smith, and P. Black Brown", al.getAsFirstLastNames(true, true)); al = AuthorList.parse("John Peter von Neumann"); assertEquals("John Peter von Neumann", al.getAsFirstLastNames(false, false)); assertEquals("John Peter von Neumann", al.getAsFirstLastNames(false, true)); assertEquals("J. P. von Neumann", al.getAsFirstLastNames(true, false)); assertEquals("J. P. von Neumann", al.getAsFirstLastNames(true, true)); } @Test public void testGetAuthorsFirstFirstAnds() { assertEquals("John Smith", AuthorList.parse("John Smith") .getAsFirstLastNamesWithAnd()); assertEquals("John Smith and Peter Black Brown", AuthorList.parse( "John Smith and Black Brown, Peter").getAsFirstLastNamesWithAnd()); assertEquals("John von Neumann and John Smith and Peter Black Brown", AuthorList .parse("John von Neumann and John Smith and Black Brown, Peter") .getAsFirstLastNamesWithAnd()); assertEquals("First von Last, Jr. III", AuthorList .parse("von Last, Jr. III, First").getAsFirstLastNamesWithAnd()); } @Test public void testGetAuthorsForAlphabetization() { assertEquals("Smith, J.", AuthorList.parse("John Smith") .getForAlphabetization()); assertEquals("Neumann, J.", AuthorList.parse("John von Neumann") .getForAlphabetization()); assertEquals("Neumann, J.", AuthorList.parse("J. von Neumann") .getForAlphabetization()); assertEquals("Neumann, J. and Smith, J. and Black Brown, Jr., P.", AuthorList .parse("John von Neumann and John Smith and de Black Brown, Jr., Peter") .getForAlphabetization()); } @Test public void testRemoveStartAndEndBraces() { assertEquals("{A}bbb{c}", AuthorList.parse("{A}bbb{c}").getAsLastNames(false)); assertEquals("Vall{\\'e}e Poussin", AuthorList.parse("{Vall{\\'e}e Poussin}").getAsLastNames(false)); assertEquals("Poussin", AuthorList.parse("{Vall{\\'e}e} {Poussin}").getAsLastNames(false)); assertEquals("Poussin", AuthorList.parse("Vall{\\'e}e Poussin").getAsLastNames(false)); assertEquals("Lastname", AuthorList.parse("Firstname {Lastname}").getAsLastNames(false)); assertEquals("Firstname Lastname", AuthorList.parse("{Firstname Lastname}").getAsLastNames(false)); } @Test public void createCorrectInitials() { assertEquals(Optional.of("J. G."), AuthorList.parse("Hornberg, Johann Gottfried").getAuthor(0).getFirstAbbr()); } @Test public void parseNameWithBracesAroundFirstName() throws Exception { // TODO: Be more intelligent and abbreviate the first name correctly Author expected = new Author("Tse-tung", "{Tse-tung}.", null, "Mao", null); assertEquals(AuthorList.of(expected), AuthorList.parse("{Tse-tung} Mao")); } @Test public void parseNameWithBracesAroundLastName() throws Exception { Author expected = new Author("Hans", "H.", null, "van den Bergen", null); assertEquals(AuthorList.of(expected), AuthorList.parse("{van den Bergen}, Hans")); } @Test public void parseNameWithHyphenInFirstName() throws Exception { Author expected = new Author("Tse-tung", "T.-t.", null, "Mao", null); assertEquals(AuthorList.of(expected), AuthorList.parse("Tse-tung Mao")); } @Test public void parseNameWithHyphenInLastName() throws Exception { Author expected = new Author("Firstname", "F.", null, "Bailey-Jones", null); assertEquals(AuthorList.of(expected), AuthorList.parse("Firstname Bailey-Jones")); } @Test public void parseNameWithHyphenInLastNameWithInitials() throws Exception { Author expected = new Author("E. S.", "E. S.", null, "El-{M}allah", null); assertEquals(AuthorList.of(expected), AuthorList.parse("E. S. El-{M}allah")); } @Test public void parseNameWithHyphenInLastNameWithEscaped() throws Exception { Author expected = new Author("E. S.", "E. S.", null, "{K}ent-{B}oswell", null); assertEquals(AuthorList.of(expected), AuthorList.parse("E. S. {K}ent-{B}oswell")); } @Test public void parseNameWithHyphenInLastNameWhenLastNameGivenFirst() throws Exception { // TODO: Fix abbreviation to be "A." Author expected = new Author("ʿAbdallāh", "ʿ.", null, "al-Ṣāliḥ", null); assertEquals(AuthorList.of(expected), AuthorList.parse("al-Ṣāliḥ, ʿAbdallāh")); } @Test public void parseNameWithBraces() throws Exception { Author expected = new Author("H{e}lene", "H.", null, "Fiaux", null); assertEquals(AuthorList.of(expected), AuthorList.parse("H{e}lene Fiaux")); } @Test public void parseFirstNameFromFirstAuthorMultipleAuthorsWithLatexNames() throws Exception { assertEquals("Mu{\\d{h}}ammad", AuthorList.parse("Mu{\\d{h}}ammad al-Khw{\\={a}}rizm{\\={i}} and Corrado B{\\\"o}hm") .getAuthor(0).getFirst().orElse(null)); } @Test public void parseFirstNameFromSecondAuthorMultipleAuthorsWithLatexNames() throws Exception { assertEquals("Corrado", AuthorList.parse("Mu{\\d{h}}ammad al-Khw{\\={a}}rizm{\\={i}} and Corrado B{\\\"o}hm") .getAuthor(1).getFirst().orElse(null)); } @Test public void parseLastNameFromFirstAuthorMultipleAuthorsWithLatexNames() throws Exception { assertEquals("al-Khw{\\={a}}rizm{\\={i}}", AuthorList.parse("Mu{\\d{h}}ammad al-Khw{\\={a}}rizm{\\={i}} and Corrado B{\\\"o}hm") .getAuthor(0).getLast().orElse(null)); } @Test public void parseLastNameFromSecondAuthorMultipleAuthorsWithLatexNames() throws Exception { assertEquals("B{\\\"o}hm", AuthorList.parse("Mu{\\d{h}}ammad al-Khw{\\={a}}rizm{\\={i}} and Corrado B{\\\"o}hm") .getAuthor(1).getLast().orElse(null)); } @Test public void parseInstitutionAuthorWithLatexNames() throws Exception { assertEquals("The Ban\\={u} M\\={u}s\\={a} brothers", AuthorList.parse("{The Ban\\={u} M\\={u}s\\={a} brothers}").getAuthor(0).getLast().orElse(null)); } @Test public void parseRetrieveCachedAuthorListAfterGarbageCollection() throws Exception { final String uniqueAuthorName = "Osvaldo Iongi"; AuthorList author = AuthorList.parse(uniqueAuthorName); System.gc(); assertSame(author, AuthorList.parse(uniqueAuthorName)); } @Test public void parseGarbageCollectAuthorListForUnreachableKey() throws Exception { final String uniqueAuthorName = "Fleur Hornbach"; // Note that "new String()" is needed, uniqueAuthorName is a reference to a String literal AuthorList uniqueAuthor = AuthorList.parse(new String(uniqueAuthorName)); System.gc(); assertNotSame(uniqueAuthor, AuthorList.parse(uniqueAuthorName)); } @Test public void parseGarbageCollectUnreachableInstitution() throws Exception { final String uniqueInstitutionName = "{Unique LLC}"; // Note that "new String()" is needed, uniqueAuthorName is a reference to a String literal AuthorList uniqueInstitution = AuthorList.parse(new String(uniqueInstitutionName)); System.gc(); assertNotSame(uniqueInstitution, AuthorList.parse(uniqueInstitutionName)); } /** * This tests an unreachable key issue addressed in [#6552](https://github.com/JabRef/jabref/pull/6552). The test is incorrect BibTeX but is handled by the parser and common in practice. */ @Test public void parseCacheAuthorsWithTwoOrMoreCommasAndWithSpaceInAllParts() throws Exception { final String uniqueAuthorsNames = "Basil Dankworth, Gianna Birdwhistle, Cosmo Berrycloth"; AuthorList uniqueAuthors = AuthorList.parse(uniqueAuthorsNames); System.gc(); assertSame(uniqueAuthors, AuthorList.parse(uniqueAuthorsNames)); } /** * This tests an unreachable key issue addressed in [#6552](https://github.com/JabRef/jabref/pull/6552). */ @Test public void parseCacheAuthorsWithTwoOrMoreCommasAndWithoutSpaceInAllParts() throws Exception { final String uniqueAuthorsNames = "Dankworth, Jr., Braelynn"; AuthorList uniqueAuthors = AuthorList.parse(uniqueAuthorsNames); System.gc(); assertSame(uniqueAuthors, AuthorList.parse(uniqueAuthorsNames)); } /** * This tests the issue described at https://github.com/JabRef/jabref/pull/2669#issuecomment-288519458 */ @Test public void correctNamesWithOneComma() throws Exception { Author expected = new Author("Alexander der Große", "A. d. G.", null, "Canon der Barbar", null); assertEquals(AuthorList.of(expected), AuthorList.parse("Canon der Barbar, Alexander der Große")); expected = new Author("Alexander H. G.", "A. H. G.", null, "Rinnooy Kan", null); assertEquals(AuthorList.of(expected), AuthorList.parse("Rinnooy Kan, Alexander H. G.")); expected = new Author("Alexander Hendrik George", "A. H. G.", null, "Rinnooy Kan", null); assertEquals(AuthorList.of(expected), AuthorList.parse("Rinnooy Kan, Alexander Hendrik George")); expected = new Author("José María", "J. M.", null, "Rodriguez Fernandez", null); assertEquals(AuthorList.of(expected), AuthorList.parse("Rodriguez Fernandez, José María")); } @Test public void equalsFalseDifferentOrder() { Author firstAuthor = new Author("A", null, null, null, null); Author secondAuthor = new Author("B", null, null, null, null); AuthorList firstAuthorList = AuthorList.of(firstAuthor, secondAuthor); AuthorList secondAuthorList = AuthorList.of(secondAuthor, firstAuthor); assertNotEquals(firstAuthorList, secondAuthorList); } @Test public void equalsFalseWhenNotAuthorList() { assertNotEquals(AuthorList.of(new Author(null, null, null, null, null)), new Author(null, null, null, null, null)); } @Test public void equalsTrueReflexive() { AuthorList authorList = AuthorList.of(new Author(null, null, null, null, null)); assertEquals(authorList, authorList); } @Test public void equalsTrueSymmetric() { AuthorList firstAuthorList = AuthorList.of(new Author("A", null, null, null, null)); AuthorList secondAuthorList = AuthorList.of(new Author("A", null, null, null, null)); assertEquals(firstAuthorList, secondAuthorList); assertEquals(secondAuthorList, firstAuthorList); } @Test public void equalsTrueTransitive() { AuthorList firstAuthorList = AuthorList.of(new Author("A", null, null, null, null)); AuthorList secondAuthorList = AuthorList.of(new Author("A", null, null, null, null)); AuthorList thirdAuthorList = AuthorList.of(new Author("A", null, null, null, null)); assertEquals(firstAuthorList, secondAuthorList); assertEquals(secondAuthorList, thirdAuthorList); assertEquals(firstAuthorList, thirdAuthorList); } @Test public void equalsTrueConsistent() { AuthorList firstAuthorList = AuthorList.of(new Author("A", null, null, null, null)); AuthorList secondAuthorList = AuthorList.of(new Author("A", null, null, null, null)); assertEquals(firstAuthorList, secondAuthorList); assertEquals(firstAuthorList, secondAuthorList); assertEquals(firstAuthorList, secondAuthorList); } @Test public void equalsFalseForNull() { assertNotEquals(null, AuthorList.of(new Author(null, null, null, null, null))); } @Test public void hashCodeConsistent() { AuthorList authorList = AuthorList.of(new Author(null, null, null, null, null)); assertEquals(authorList.hashCode(), authorList.hashCode()); } @Test public void hashCodeNotConstant() { AuthorList firstAuthorList = AuthorList.of(new Author("A", null, null, null, null)); AuthorList secondAuthorList = AuthorList.of(new Author("B", null, null, null, null)); assertNotEquals(firstAuthorList.hashCode(), secondAuthorList.hashCode()); } }
56,814
45.68447
190
java
null
jabref-main/src/test/java/org/jabref/model/entry/AuthorTest.java
package org.jabref.model.entry; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertEquals; class AuthorTest { @Test void addDotIfAbbreviationAddDot() { assertEquals("O.", Author.addDotIfAbbreviation("O")); assertEquals("A. O.", Author.addDotIfAbbreviation("AO")); assertEquals("A. O.", Author.addDotIfAbbreviation("AO.")); assertEquals("A. O.", Author.addDotIfAbbreviation("A.O.")); assertEquals("A.-O.", Author.addDotIfAbbreviation("A-O")); } @Test void addDotIfAbbreviationDoesNotAddMultipleSpaces() { assertEquals("A. O.", Author.addDotIfAbbreviation("A O")); } @ParameterizedTest @ValueSource(strings = {"O.", "A. O.", "A.-O.", "O. Moore", "A. O. Moore", "O. von Moore", "A.-O. Moore", "Moore, O.", "Moore, O., Jr.", "Moore, A. O.", "Moore, A.-O.", "MEmre", "{\\'{E}}douard", "J{\\\"o}rg", "Moore, O. and O. Moore", "Moore, O. and O. Moore and Moore, O. O."}) void addDotIfAbbreviationDoNotAddDot(String input) { assertEquals(input, Author.addDotIfAbbreviation(input)); } @ParameterizedTest @NullAndEmptySource void addDotIfAbbreviationIfNameIsNullOrEmpty(String input) { assertEquals(input, Author.addDotIfAbbreviation(input)); } @ParameterizedTest @ValueSource(strings = {"asdf", "a"}) void addDotIfAbbreviationLowerCaseLetters(String input) { assertEquals(input, Author.addDotIfAbbreviation(input)); } @Test void addDotIfAbbreviationStartWithUpperCaseAndHyphen() { assertEquals("A.-melia", Author.addDotIfAbbreviation("A-melia")); } @Test void addDotIfAbbreviationEndsWithUpperCaseLetter() { assertEquals("AmeliA", Author.addDotIfAbbreviation("AmeliA")); } @Test void addDotIfAbbreviationEndsWithUpperCaseLetterSpaced() { assertEquals("Ameli A.", Author.addDotIfAbbreviation("Ameli A")); } @Test void addDotIfAbbreviationEndsWithWhiteSpaced() { assertEquals("Ameli", Author.addDotIfAbbreviation("Ameli ")); } @Test void addDotIfAbbreviationEndsWithDoubleAbbreviation() { assertEquals("Ameli A. A.", Author.addDotIfAbbreviation("Ameli AA")); } @ParameterizedTest @ValueSource(strings = {"1", "1 23"}) void addDotIfAbbreviationIfStartsWithNumber(String input) { assertEquals(input, Author.addDotIfAbbreviation(input)); } }
2,725
33.506329
94
java
null
jabref-main/src/test/java/org/jabref/model/entry/BibEntryTest.java
package org.jabref.model.entry; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import org.jabref.model.FieldChange; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldPriority; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import com.google.common.collect.Sets; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT; @Execution(CONCURRENT) class BibEntryTest { private BibEntry entry = new BibEntry(); @Test void testDefaultConstructor() { assertEquals(StandardEntryType.Misc, entry.getType()); assertNotNull(entry.getId()); assertFalse(entry.getField(StandardField.AUTHOR).isPresent()); } @Test void settingTypeToNullThrowsException() { assertThrows(NullPointerException.class, () -> entry.setType(null)); } @Test void setNullFieldThrowsNPE() { assertThrows(NullPointerException.class, () -> entry.setField(null)); } @Test void getFieldIsCaseInsensitive() throws Exception { entry.setField(new UnknownField("TeSt"), "value"); assertEquals(Optional.of("value"), entry.getField(new UnknownField("tEsT"))); } @Test void getFieldWorksWithBibFieldAsWell() throws Exception { entry.setField(StandardField.AUTHOR, "value"); assertEquals(Optional.of("value"), entry.getField(new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT).field())); } @Test void newBibEntryIsUnchanged() { assertFalse(entry.hasChanged()); } @Test void setFieldLeadsToAChangedEntry() throws Exception { entry.setField(StandardField.AUTHOR, "value"); assertTrue(entry.hasChanged()); } @Test void setFieldWorksWithBibFieldAsWell() throws Exception { entry.setField(new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT).field(), "value"); assertEquals(Optional.of("value"), entry.getField(StandardField.AUTHOR)); } @Test void clonedBibEntryHasUniqueID() throws Exception { BibEntry entryClone = (BibEntry) entry.clone(); assertNotEquals(entry.getId(), entryClone.getId()); } @Test void clonedBibEntryWithMiscTypeHasOriginalChangedFlag() throws Exception { BibEntry entryClone = (BibEntry) entry.clone(); assertFalse(entryClone.hasChanged()); } @Test void clonedBibEntryWithBookTypeAndOneFieldHasOriginalChangedFlag() throws Exception { entry = new BibEntry(StandardEntryType.Book).withField(StandardField.AUTHOR, "value"); BibEntry entryClone = (BibEntry) entry.clone(); assertFalse(entryClone.hasChanged()); } @Test void setAndGetAreConsistentForMonth() throws Exception { entry.setField(StandardField.MONTH, "may"); assertEquals(Optional.of("may"), entry.getField(StandardField.MONTH)); } @Test void setAndGetAreConsistentForCapitalizedMonth() throws Exception { entry.setField(StandardField.MONTH, "May"); assertEquals(Optional.of("May"), entry.getField(StandardField.MONTH)); } @Test void setAndGetAreConsistentForMonthString() throws Exception { entry.setField(StandardField.MONTH, "#may#"); assertEquals(Optional.of("#may#"), entry.getField(StandardField.MONTH)); } @Test void monthCorrectlyReturnedForMonth() throws Exception { entry.setField(StandardField.MONTH, "may"); assertEquals(Optional.of(Month.MAY), entry.getMonth()); } @Test void monthCorrectlyReturnedForCapitalizedMonth() throws Exception { entry.setField(StandardField.MONTH, "May"); assertEquals(Optional.of(Month.MAY), entry.getMonth()); } @Test void monthCorrectlyReturnedForMonthString() throws Exception { entry.setField(StandardField.MONTH, "#may#"); assertEquals(Optional.of(Month.MAY), entry.getMonth()); } @Test void monthCorrectlyReturnedForMonthMay() throws Exception { entry.setMonth(Month.MAY); assertEquals(Optional.of(Month.MAY), entry.getMonth()); } @Test void monthFieldCorrectlyReturnedForMonthMay() throws Exception { entry.setMonth(Month.MAY); assertEquals(Optional.of("#may#"), entry.getField(StandardField.MONTH)); } @Test void getFieldOrAliasDateWithYearNumericalMonthString() { entry.setField(StandardField.YEAR, "2003"); entry.setField(StandardField.MONTH, "3"); assertEquals(Optional.of("2003-03"), entry.getFieldOrAlias(StandardField.DATE)); } @Test void getFieldOrAliasDateWithYearAbbreviatedMonth() { entry.setField(StandardField.YEAR, "2003"); entry.setField(StandardField.MONTH, "#mar#"); assertEquals(Optional.of("2003-03"), entry.getFieldOrAlias(StandardField.DATE)); } @Test void getFieldOrAliasDateWithYearAbbreviatedMonthString() { entry.setField(StandardField.YEAR, "2003"); entry.setField(StandardField.MONTH, "mar"); assertEquals(Optional.of("2003-03"), entry.getFieldOrAlias(StandardField.DATE)); } @Test void getFieldOrAliasDateWithOnlyYear() { entry.setField(StandardField.YEAR, "2003"); assertEquals(Optional.of("2003"), entry.getFieldOrAlias(StandardField.DATE)); } @Test void getFieldOrAliasYearWithDateYYYY() { entry.setField(StandardField.DATE, "2003"); assertEquals(Optional.of("2003"), entry.getFieldOrAlias(StandardField.YEAR)); } @Test void getFieldOrAliasYearWithDateYYYYMM() { entry.setField(StandardField.DATE, "2003-03"); assertEquals(Optional.of("2003"), entry.getFieldOrAlias(StandardField.YEAR)); } @Test void getFieldOrAliasYearWithDateYYYYMMDD() { entry.setField(StandardField.DATE, "2003-03-30"); assertEquals(Optional.of("2003"), entry.getFieldOrAlias(StandardField.YEAR)); } @Test void getFieldOrAliasMonthWithDateYYYYReturnsNull() { entry.setField(StandardField.DATE, "2003"); assertEquals(Optional.empty(), entry.getFieldOrAlias(StandardField.MONTH)); } @Test void getFieldOrAliasMonthWithDateYYYYMM() { entry.setField(StandardField.DATE, "2003-03"); assertEquals(Optional.of("#mar#"), entry.getFieldOrAlias(StandardField.MONTH)); } @Test void getFieldOrAliasMonthWithDateYYYYMMDD() { entry.setField(StandardField.DATE, "2003-03-30"); assertEquals(Optional.of("#mar#"), entry.getFieldOrAlias(StandardField.MONTH)); } @Test void getFieldOrAliasLatexFreeAlreadyFreeValueIsUnchanged() { entry.setField(StandardField.TITLE, "A Title Without any LaTeX commands"); assertEquals(Optional.of("A Title Without any LaTeX commands"), entry.getFieldOrAliasLatexFree(StandardField.TITLE)); } @Test void getFieldOrAliasLatexFreeAlreadyFreeAliasValueIsUnchanged() { entry.setField(StandardField.JOURNAL, "A Title Without any LaTeX commands"); assertEquals(Optional.of("A Title Without any LaTeX commands"), entry.getFieldOrAliasLatexFree(StandardField.JOURNALTITLE)); } @Test void getFieldOrAliasLatexFreeBracesAreRemoved() { entry.setField(StandardField.TITLE, "{A Title with some {B}ra{C}es}"); assertEquals(Optional.of("A Title with some BraCes"), entry.getFieldOrAliasLatexFree(StandardField.TITLE)); } @Test void getFieldOrAliasLatexFreeBracesAreRemovedFromAlias() { entry.setField(StandardField.JOURNAL, "{A Title with some {B}ra{C}es}"); assertEquals(Optional.of("A Title with some BraCes"), entry.getFieldOrAliasLatexFree(StandardField.JOURNALTITLE)); } @Test void getFieldOrAliasLatexFreeComplexConversionInAlias() { entry.setField(StandardField.JOURNAL, "A 32~{mA} {$\\Sigma\\Delta$}-modulator"); assertEquals(Optional.of("A 32 mA ΣΔ-modulator"), entry.getFieldOrAliasLatexFree(StandardField.JOURNALTITLE)); } @Test void testGetAndAddToLinkedFileList() { List<LinkedFile> files = entry.getFiles(); files.add(new LinkedFile("", Path.of(""), "")); entry.setFiles(files); assertEquals(Arrays.asList(new LinkedFile("", Path.of(""), "")), entry.getFiles()); } @Test void replaceOfLinkWorks() throws Exception { List<LinkedFile> files = new ArrayList<>(); String urlAsString = "https://www.example.org/file.pdf"; files.add(new LinkedFile(new URL(urlAsString), "")); entry.setFiles(files); LinkedFile linkedFile = new LinkedFile("", Path.of("file.pdf", ""), ""); entry.replaceDownloadedFile(urlAsString, linkedFile); assertEquals(List.of(linkedFile), entry.getFiles()); } @Test void testGetEmptyKeywords() { KeywordList actual = entry.getKeywords(','); assertEquals(new KeywordList(), actual); } @Test void testGetSingleKeywords() { entry.addKeyword("kw", ','); KeywordList actual = entry.getKeywords(','); assertEquals(new KeywordList(new Keyword("kw")), actual); } @Test void settingCiteKeyLeadsToCorrectCiteKey() { assertFalse(entry.hasCitationKey()); entry.setCitationKey("Einstein1931"); assertEquals(Optional.of("Einstein1931"), entry.getCitationKey()); } @Test void settingCiteKeyLeadsToHasCiteKy() { assertFalse(entry.hasCitationKey()); entry.setCitationKey("Einstein1931"); assertTrue(entry.hasCitationKey()); } @Test void clearFieldWorksForAuthor() { entry.setField(StandardField.AUTHOR, "Albert Einstein"); entry.clearField(StandardField.AUTHOR); assertEquals(Optional.empty(), entry.getField(StandardField.AUTHOR)); } @Test void setFieldWorksForAuthor() { entry.setField(StandardField.AUTHOR, "Albert Einstein"); assertEquals(Optional.of("Albert Einstein"), entry.getField(StandardField.AUTHOR)); } @Test void allFieldsPresentDefault() { BibEntry e = new BibEntry(StandardEntryType.Article); e.setField(StandardField.AUTHOR, "abc"); e.setField(StandardField.TITLE, "abc"); e.setField(StandardField.JOURNAL, "abc"); List<OrFields> requiredFields = new ArrayList<>(); requiredFields.add(new OrFields(StandardField.AUTHOR)); requiredFields.add(new OrFields(StandardField.TITLE)); assertTrue(e.allFieldsPresent(requiredFields, null)); requiredFields.add(new OrFields(StandardField.YEAR)); assertFalse(e.allFieldsPresent(requiredFields, null)); } @Test void allFieldsPresentOr() { BibEntry e = new BibEntry(StandardEntryType.Article); e.setField(StandardField.AUTHOR, "abc"); e.setField(StandardField.TITLE, "abc"); e.setField(StandardField.JOURNAL, "abc"); List<OrFields> requiredFields = new ArrayList<>(); requiredFields.add(new OrFields(StandardField.JOURNAL, StandardField.YEAR)); assertTrue(e.allFieldsPresent(requiredFields, null)); requiredFields.add(new OrFields(StandardField.YEAR, StandardField.ADDRESS)); assertFalse(e.allFieldsPresent(requiredFields, null)); } @Test void isNullCiteKeyThrowsNPE() { BibEntry e = new BibEntry(StandardEntryType.Article); assertThrows(NullPointerException.class, () -> e.setCitationKey(null)); } @Test void isEmptyCiteKey() { BibEntry e = new BibEntry(StandardEntryType.Article); assertFalse(e.hasCitationKey()); e.setCitationKey(""); assertFalse(e.hasCitationKey()); e.setCitationKey("key"); assertTrue(e.hasCitationKey()); e.clearField(InternalField.KEY_FIELD); assertFalse(e.hasCitationKey()); } @Test void identicObjectsareEqual() throws Exception { BibEntry otherEntry = entry; assertTrue(entry.equals(otherEntry)); } @Test void compareToNullObjectIsFalse() throws Exception { assertFalse(entry.equals(null)); } @Test void compareToDifferentClassIsFalse() throws Exception { assertFalse(entry.equals(new Object())); } @Test void compareIsTrueWhenIdAndFieldsAreEqual() throws Exception { entry.setId("1"); entry.setField(new UnknownField("key"), "value"); BibEntry otherEntry = new BibEntry(); otherEntry.setId("1"); assertNotEquals(entry, otherEntry); otherEntry.setField(new UnknownField("key"), "value"); assertEquals(entry, otherEntry); } @Test void addNullKeywordThrowsNPE() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); assertThrows(NullPointerException.class, () -> entry.addKeyword((Keyword) null, ',')); } @Test void putNullKeywordListThrowsNPE() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); assertThrows(NullPointerException.class, () -> entry.putKeywords((KeywordList) null, ',')); } @Test void putNullKeywordSeparatorThrowsNPE() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); assertThrows(NullPointerException.class, () -> entry.putKeywords(Arrays.asList("A", "B"), null)); } @Test void testGetSeparatedKeywordsAreCorrect() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); assertEquals(new KeywordList("Foo", "Bar"), entry.getKeywords(',')); } @Test void testAddKeywordIsCorrect() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.addKeyword("FooBar", ','); assertEquals(new KeywordList("Foo", "Bar", "FooBar"), entry.getKeywords(',')); } @Test void testAddKeywordHasChanged() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.addKeyword("FooBar", ','); assertTrue(entry.hasChanged()); } @Test void testAddKeywordTwiceYiedsOnlyOne() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.addKeyword("FooBar", ','); entry.addKeyword("FooBar", ','); assertEquals(new KeywordList("Foo", "Bar", "FooBar"), entry.getKeywords(',')); } @Test void addKeywordIsCaseSensitive() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.addKeyword("FOO", ','); assertEquals(new KeywordList("Foo", "Bar", "FOO"), entry.getKeywords(',')); } @Test void testAddKeywordWithDifferentCapitalizationChanges() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.addKeyword("FOO", ','); assertTrue(entry.hasChanged()); } @Test void testAddKeywordEmptyKeywordIsNotAdded() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.addKeyword("", ','); assertEquals(new KeywordList("Foo", "Bar"), entry.getKeywords(',')); } @Test void testAddKeywordEmptyKeywordNotChanged() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.setChanged(false); entry.addKeyword("", ','); assertFalse(entry.hasChanged()); } @Test void texNewBibEntryHasNoKeywords() { assertTrue(entry.getKeywords(',').isEmpty()); } @Test void texNewBibEntryHasNoKeywordsEvenAfterAddingEmptyKeyword() { entry.addKeyword("", ','); assertTrue(entry.getKeywords(',').isEmpty()); } @Test void texNewBibEntryAfterAddingEmptyKeywordNotChanged() { entry.addKeyword("", ','); assertFalse(entry.hasChanged()); } @Test void testAddKeywordsWorksAsExpected() { entry.addKeywords(Arrays.asList("Foo", "Bar"), ','); assertEquals(new KeywordList("Foo", "Bar"), entry.getKeywords(',')); } @Test void testPutKeywordsOverwritesOldKeywords() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.putKeywords(Arrays.asList("Yin", "Yang"), ','); assertEquals(new KeywordList("Yin", "Yang"), entry.getKeywords(',')); } @Test void testPutKeywordsHasChanged() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.putKeywords(Arrays.asList("Yin", "Yang"), ','); assertTrue(entry.hasChanged()); } @Test void testPutKeywordsPutEmpyListErasesPreviousKeywords() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.putKeywords(Collections.emptyList(), ','); assertTrue(entry.getKeywords(',').isEmpty()); } @Test void testPutKeywordsPutEmpyListHasChanged() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.putKeywords(Collections.emptyList(), ','); assertTrue(entry.hasChanged()); } @Test void testPutKeywordsPutEmpyListToEmptyBibentry() { entry.putKeywords(Collections.emptyList(), ','); assertTrue(entry.getKeywords(',').isEmpty()); } @Test void testPutKeywordsPutEmpyListToEmptyBibentryNotChanged() { entry.putKeywords(Collections.emptyList(), ','); assertFalse(entry.hasChanged()); } @Test void putKeywordsToEmptyReturnsNoChange() { Optional<FieldChange> change = entry.putKeywords(Collections.emptyList(), ','); assertEquals(Optional.empty(), change); } @Test void clearKeywordsReturnsChange() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); Optional<FieldChange> change = entry.putKeywords(Collections.emptyList(), ','); assertEquals(Optional.of(new FieldChange(entry, StandardField.KEYWORDS, "Foo, Bar", null)), change); } @Test void changeKeywordsReturnsChange() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); Optional<FieldChange> change = entry.putKeywords(Arrays.asList("Test", "FooTest"), ','); assertEquals(Optional.of(new FieldChange(entry, StandardField.KEYWORDS, "Foo, Bar", "Test, FooTest")), change); } @Test void putKeywordsToSameReturnsNoChange() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); Optional<FieldChange> change = entry.putKeywords(Arrays.asList("Foo", "Bar"), ','); assertEquals(Optional.empty(), change); } @Test void getKeywordsReturnsParsedKeywordListFromKeywordsField() { entry.setField(StandardField.KEYWORDS, "w1, w2a w2b, w3"); assertEquals(new KeywordList("w1", "w2a w2b", "w3"), entry.getKeywords(',')); } @Test void removeKeywordsOnEntryWithoutKeywordsDoesNothing() { Optional<FieldChange> change = entry.removeKeywords(SpecialField.RANKING.getKeyWords(), ','); assertEquals(Optional.empty(), change); } @Test void removeKeywordsWithEmptyListDoesNothing() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.putKeywords(Arrays.asList("kw1", "kw2"), ','); Optional<FieldChange> change = entry.removeKeywords(new KeywordList(), ','); assertEquals(Optional.empty(), change); } @Test void removeKeywordsWithNonExistingKeywordsDoesNothing() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.putKeywords(Arrays.asList("kw1", "kw2"), ','); Optional<FieldChange> change = entry.removeKeywords(KeywordList.parse("kw3, kw4", ','), ','); assertEquals(Optional.empty(), change); assertEquals(Sets.newHashSet("kw1", "kw2"), entry.getKeywords(',').toStringList()); } @Test void removeKeywordsWithExistingKeywordsRemovesThem() { entry.setField(StandardField.KEYWORDS, "Foo, Bar"); entry.putKeywords(Arrays.asList("kw1", "kw2", "kw3"), ','); Optional<FieldChange> change = entry.removeKeywords(KeywordList.parse("kw1, kw2", ','), ','); assertTrue(change.isPresent()); assertEquals(KeywordList.parse("kw3", ','), entry.getKeywords(',')); } @Test void keywordListCorrectlyConstructedForThreeKeywords() { entry.addKeyword("kw", ','); entry.addKeyword("kw2", ','); entry.addKeyword("kw3", ','); KeywordList actual = entry.getKeywords(','); assertEquals(new KeywordList(new Keyword("kw"), new Keyword("kw2"), new Keyword("kw3")), actual); } @Test void testGetEmptyResolvedKeywords() { BibDatabase database = new BibDatabase(); entry.setField(StandardField.CROSSREF, "entry2"); database.insertEntry(entry); BibEntry entry2 = new BibEntry(); entry2.setCitationKey("entry2"); database.insertEntry(entry2); KeywordList actual = entry.getResolvedKeywords(',', database); assertEquals(new KeywordList(), actual); } @Test void testGetSingleResolvedKeywords() { BibDatabase database = new BibDatabase(); entry.setField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry(); entry2.setCitationKey("entry2"); entry2.addKeyword("kw", ','); database.insertEntry(entry2); database.insertEntry(entry); KeywordList actual = entry.getResolvedKeywords(',', database); assertEquals(new KeywordList(new Keyword("kw")), actual); } @Test void testGetResolvedKeywords() { BibDatabase database = new BibDatabase(); entry.setField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry(); entry2.setCitationKey("entry2"); entry2.addKeyword("kw", ','); entry2.addKeyword("kw2", ','); entry2.addKeyword("kw3", ','); database.insertEntry(entry2); database.insertEntry(entry); KeywordList actual = entry.getResolvedKeywords(',', database); assertEquals(new KeywordList(new Keyword("kw"), new Keyword("kw2"), new Keyword("kw3")), actual); } @Test void settingTitleFieldsLeadsToChangeFlagged() { entry.setField(StandardField.AUTHOR, "value"); assertTrue(entry.hasChanged()); } @Test void builderReturnsABibEntryNotChangedFlagged() { entry = new BibEntry().withField(StandardField.AUTHOR, "value"); assertFalse(entry.hasChanged()); } @Test void mergeEntriesWithNoOverlap() { BibEntry expected = new BibEntry() .withField(StandardField.AUTHOR, "Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.EPRINT, "1234.56789") .withField(StandardField.DATE, "1970-01-01"); BibEntry copyEntry = (BibEntry) entry.clone(); BibEntry otherEntry = new BibEntry(); copyEntry.setField(Map.of( StandardField.AUTHOR, "Test Author", StandardField.TITLE, "Test Title")); otherEntry.setField(Map.of( StandardField.EPRINT, "1234.56789", StandardField.DATE, "1970-01-01" )); copyEntry.mergeWith(otherEntry); assertEquals(expected.getFields(), copyEntry.getFields()); } @Test void mergeEntriesWithOverlap() { BibEntry expected = new BibEntry() .withField(StandardField.AUTHOR, "Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.DATE, "1970-01-01"); BibEntry copyEntry = (BibEntry) entry.clone(); BibEntry otherEntry = new BibEntry(); copyEntry.setField(Map.of( StandardField.AUTHOR, "Test Author", StandardField.TITLE, "Test Title")); otherEntry.setField(Map.of( StandardField.AUTHOR, "Another Test Author", StandardField.DATE, "1970-01-01" )); copyEntry.mergeWith(otherEntry); assertEquals(expected.getFields(), copyEntry.getFields()); } @Test void mergeEntriesWithNoOverlapAndNonExistingPriorityFields() { BibEntry expected = new BibEntry() .withField(StandardField.AUTHOR, "Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.EPRINT, "1234.56789") .withField(StandardField.DATE, "1970-01-01"); BibEntry copyEntry = (BibEntry) entry.clone(); BibEntry otherEntry = new BibEntry(); copyEntry.setField(Map.of( StandardField.AUTHOR, "Test Author", StandardField.TITLE, "Test Title")); otherEntry.setField(Map.of( StandardField.EPRINT, "1234.56789", StandardField.DATE, "1970-01-01" )); Set<Field> otherPrioritizedFields = Set.of(StandardField.VOLUME, StandardField.KEYWORDS); copyEntry.mergeWith(otherEntry, otherPrioritizedFields); assertEquals(expected.getFields(), copyEntry.getFields()); } @Test void mergeEntriesWithNoOverlapAndExistingPriorityFields() { BibEntry expected = new BibEntry() .withField(StandardField.AUTHOR, "Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.EPRINT, "1234.56789") .withField(StandardField.DATE, "1970-01-01"); BibEntry copyEntry = (BibEntry) entry.clone(); BibEntry otherEntry = new BibEntry(); copyEntry.setField(Map.of( StandardField.AUTHOR, "Test Author", StandardField.TITLE, "Test Title")); otherEntry.setField(Map.of( StandardField.EPRINT, "1234.56789", StandardField.DATE, "1970-01-01" )); Set<Field> otherPrioritizedFields = Set.of(StandardField.AUTHOR, StandardField.EPRINT); copyEntry.mergeWith(otherEntry, otherPrioritizedFields); assertEquals(expected.getFields(), copyEntry.getFields()); } @Test void mergeEntriesWithOverlapAndPriorityGivenToNonOverlappingField() { BibEntry expected = new BibEntry() .withField(StandardField.AUTHOR, "Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.DATE, "1970-01-01"); BibEntry copyEntry = (BibEntry) entry.clone(); BibEntry otherEntry = new BibEntry(); copyEntry.setField(Map.of( StandardField.AUTHOR, "Test Author", StandardField.TITLE, "Test Title")); otherEntry.setField(Map.of( StandardField.AUTHOR, "Another Test Author", StandardField.DATE, "1970-01-01" )); Set<Field> otherPrioritizedFields = Set.of(StandardField.TITLE, StandardField.DATE); copyEntry.mergeWith(otherEntry, otherPrioritizedFields); assertEquals(expected.getFields(), copyEntry.getFields()); } @Test void mergeEntriesWithOverlapAndPriorityGivenToOverlappingField() { BibEntry expected = new BibEntry() .withField(StandardField.AUTHOR, "Another Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.DATE, "1970-01-01"); BibEntry copyEntry = (BibEntry) entry.clone(); BibEntry otherEntry = new BibEntry(); copyEntry.setField(Map.of( StandardField.AUTHOR, "Test Author", StandardField.TITLE, "Test Title")); otherEntry.setField(Map.of( StandardField.AUTHOR, "Another Test Author", StandardField.DATE, "1970-01-01" )); Set<Field> otherPrioritizedFields = Set.of(StandardField.AUTHOR, StandardField.DATE); copyEntry.mergeWith(otherEntry, otherPrioritizedFields); assertEquals(expected.getFields(), copyEntry.getFields()); } public static Stream<BibEntry> isEmpty() { return Stream.of( new BibEntry(), new BibEntry(StandardEntryType.Book), new BibEntry().withField(StandardField.OWNER, "test"), new BibEntry().withField(StandardField.CREATIONDATE, "test"), new BibEntry() .withField(StandardField.OWNER, "test") .withField(StandardField.CREATIONDATE, "test"), // source: https://github.com/JabRef/jabref/issues/8645 new BibEntry() .withField(StandardField.OWNER, "mlep") .withField(StandardField.CREATIONDATE, "2022-04-05T10:41:54")); } @ParameterizedTest @MethodSource void isEmpty(BibEntry entry) { assertTrue(entry.isEmpty()); } public static Stream<BibEntry> isNotEmpty() { return Stream.of( new BibEntry().withCitationKey("test"), new BibEntry().withField(StandardField.AUTHOR, "test") ); } @ParameterizedTest @MethodSource void isNotEmpty(BibEntry entry) { assertFalse(entry.isEmpty()); } }
30,021
34.32
132
java
null
jabref-main/src/test/java/org/jabref/model/entry/BibEntryTypesManagerTest.java
package org.jabref.model.entry; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.TreeSet; import java.util.stream.Collectors; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.logic.exporter.MetaDataSerializer; import org.jabref.logic.importer.util.MetaDataParser; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.FieldPriority; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.BiblatexAPAEntryTypeDefinitions; import org.jabref.model.entry.types.BiblatexEntryTypeDefinitions; import org.jabref.model.entry.types.BiblatexSoftwareEntryTypeDefinitions; import org.jabref.model.entry.types.BibtexEntryTypeDefinitions; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.IEEETranEntryTypeDefinitions; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @AllowedToUseLogic("Requires MetaDataSerializer and MetaDataParser for parsing tests") class BibEntryTypesManagerTest { private static final EntryType UNKNOWN_TYPE = new UnknownEntryType("unknownType"); private static final EntryType CUSTOM_TYPE = new UnknownEntryType("customType"); private BibEntryType newCustomType; private BibEntryType overwrittenStandardType; private BibEntryTypesManager entryTypesManager; @BeforeEach void setUp() { newCustomType = new BibEntryType( CUSTOM_TYPE, List.of(new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT)), Collections.emptySet()); overwrittenStandardType = new BibEntryType( StandardEntryType.Article, List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT)), Collections.emptySet()); entryTypesManager = new BibEntryTypesManager(); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void isCustomOrModifiedTypeReturnsTrueForModifiedStandardEntryType(BibDatabaseMode mode) { entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); assertTrue(entryTypesManager.isCustomOrModifiedType(overwrittenStandardType, mode)); } @Test void allTypesBibtexAreCorrect() { TreeSet<BibEntryType> defaultTypes = new TreeSet<>(BibtexEntryTypeDefinitions.ALL); defaultTypes.addAll(IEEETranEntryTypeDefinitions.ALL); assertEquals(defaultTypes, entryTypesManager.getAllTypes(BibDatabaseMode.BIBTEX)); } @Test void allTypesBiblatexAreCorrect() { TreeSet<BibEntryType> defaultTypes = new TreeSet<>(BiblatexEntryTypeDefinitions.ALL); defaultTypes.addAll(BiblatexSoftwareEntryTypeDefinitions.ALL); defaultTypes.addAll(BiblatexAPAEntryTypeDefinitions.ALL); assertEquals(defaultTypes, entryTypesManager.getAllTypes(BibDatabaseMode.BIBLATEX)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void unknownTypeIsNotFound(BibDatabaseMode mode) { assertEquals(Optional.empty(), entryTypesManager.enrich(UNKNOWN_TYPE, mode)); assertFalse(entryTypesManager.isCustomType(UNKNOWN_TYPE, mode)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void newCustomEntryTypeFound(BibDatabaseMode mode) { entryTypesManager.addCustomOrModifiedType(newCustomType, mode); assertEquals(Optional.of(newCustomType), entryTypesManager.enrich(CUSTOM_TYPE, mode)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void registeredBibEntryTypeIsContainedInListOfCustomizedEntryTypes(BibDatabaseMode mode) { entryTypesManager.addCustomOrModifiedType(newCustomType, mode); assertEquals(Collections.singletonList(newCustomType), entryTypesManager.getAllCustomTypes(mode)); } @Test void registerBibEntryTypeDoesNotAffectOtherMode() { entryTypesManager.addCustomOrModifiedType(newCustomType, BibDatabaseMode.BIBTEX); assertFalse(entryTypesManager.getAllTypes(BibDatabaseMode.BIBLATEX).contains(newCustomType)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void overwriteBibEntryTypeFields(BibDatabaseMode mode) { entryTypesManager.addCustomOrModifiedType(newCustomType, mode); BibEntryType newBibEntryTypeTitle = new BibEntryType( CUSTOM_TYPE, Collections.singleton(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT)), Collections.emptySet()); entryTypesManager.addCustomOrModifiedType(newBibEntryTypeTitle, mode); assertEquals(Optional.of(newBibEntryTypeTitle), entryTypesManager.enrich(CUSTOM_TYPE, mode)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void overwriteStandardTypeRequiredFields(BibDatabaseMode mode) { entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); assertEquals(Optional.of(overwrittenStandardType), entryTypesManager.enrich(overwrittenStandardType.getType(), mode)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void registeredCustomizedStandardEntryTypeIsNotContainedInListOfCustomEntryTypes(BibDatabaseMode mode) { entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); assertEquals(Collections.emptyList(), entryTypesManager.getAllCustomTypes(mode)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void standardTypeIsStillAccessibleIfOverwritten(BibDatabaseMode mode) { entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); assertFalse(entryTypesManager.isCustomType(overwrittenStandardType.getType(), mode)); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void testsModifyingArticle(BibDatabaseMode mode) { overwrittenStandardType = new BibEntryType( StandardEntryType.Article, List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), new BibField(new UnknownField("langid"), FieldPriority.IMPORTANT), new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), Collections.emptySet()); entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); assertEquals(Collections.singletonList(overwrittenStandardType), entryTypesManager.getAllTypes(mode).stream().filter(t -> "article".equals(t.getType().getName())).collect(Collectors.toList())); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void testsModifyingArticleWithParsing(BibDatabaseMode mode) { overwrittenStandardType = new BibEntryType( StandardEntryType.Article, List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), new BibField(new UnknownField("langid"), FieldPriority.IMPORTANT), new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), Collections.emptySet()); entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); String serialized = MetaDataSerializer.serializeCustomEntryTypes(overwrittenStandardType); Optional<BibEntryType> type = MetaDataParser.parseCustomEntryType(serialized); assertEquals(Optional.of(overwrittenStandardType), type); } @ParameterizedTest @EnumSource(BibDatabaseMode.class) void testsModifyingArticleWithParsingKeepsListOrder(BibDatabaseMode mode) { overwrittenStandardType = new BibEntryType( StandardEntryType.Article, List.of(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), new BibField(StandardField.NUMBER, FieldPriority.IMPORTANT), new BibField(new UnknownField("langid"), FieldPriority.IMPORTANT), new BibField(StandardField.COMMENT, FieldPriority.IMPORTANT)), Collections.emptySet()); entryTypesManager.addCustomOrModifiedType(overwrittenStandardType, mode); String serialized = MetaDataSerializer.serializeCustomEntryTypes(overwrittenStandardType); Optional<BibEntryType> type = MetaDataParser.parseCustomEntryType(serialized); assertEquals(overwrittenStandardType.getOptionalFields(), type.get().getOptionalFields()); } }
9,709
49.572917
201
java
null
jabref-main/src/test/java/org/jabref/model/entry/BibtexStringTest.java
package org.jabref.model.entry; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class BibtexStringTest { @Test public void initalizationWorksCorrectly() { // Instantiate BibtexString bs = new BibtexString("AAA", "An alternative action"); assertEquals("AAA", bs.getName()); assertEquals("An alternative action", bs.getContent()); assertEquals(BibtexString.Type.OTHER, bs.getType()); } @Test public void idIsUpdatedAtSetId() { // Instantiate BibtexString bs = new BibtexString("AAA", "An alternative action"); bs.setId("ID"); assertEquals("ID", bs.getId()); } @Test public void cloningDoesNotChangeContents() { BibtexString bs = new BibtexString("AAA", "An alternative action"); bs.setId("ID"); BibtexString bs2 = (BibtexString) bs.clone(); assertEquals(bs.getId(), bs2.getId()); assertEquals(bs.getName(), bs2.getName()); assertEquals(bs.getContent(), bs2.getContent()); assertEquals(bs.getType(), bs2.getType()); } @Test public void clonedBibtexStringEqualsOriginalString() { BibtexString bibtexString = new BibtexString("AAA", "An alternative action"); bibtexString.setId("ID"); BibtexString clone = (BibtexString) bibtexString.clone(); assertEquals(bibtexString, clone); } @Test public void usingTheIdGeneratorDoesNotHitTheOriginalId() { // Instantiate BibtexString bs = new BibtexString("AAA", "An alternative action"); bs.setId("ID"); BibtexString bs2 = (BibtexString) bs.clone(); bs2.setId(IdGenerator.next()); assertNotEquals(bs.getId(), bs2.getId()); } @Test public void settingFieldsInACloneWorks() { // Instantiate BibtexString bs = new BibtexString("AAA", "An alternative action"); bs.setId("ID"); BibtexString bs2 = (BibtexString) bs.clone(); bs2.setId(IdGenerator.next()); bs2.setName("aOG"); assertEquals(BibtexString.Type.AUTHOR, bs2.getType()); bs2.setContent("Oscar Gustafsson"); assertEquals("aOG", bs2.getName()); assertEquals("Oscar Gustafsson", bs2.getContent()); } @Test public void modifyingACloneDoesNotModifyTheOriginalEntry() { // Instantiate BibtexString original = new BibtexString("AAA", "An alternative action"); original.setId("ID"); BibtexString clone = (BibtexString) original.clone(); clone.setId(IdGenerator.next()); clone.setName("aOG"); clone.setContent("Oscar Gustafsson"); assertEquals("AAA", original.getName()); assertEquals("An alternative action", original.getContent()); } @Test public void getContentNeverReturnsNull() { BibtexString bs = new BibtexString("SomeName", null); assertNotNull(bs.getContent()); } @Test public void authorTypeCorrectlyDetermined() { // Source of the example: https://docs.jabref.org/fields/strings BibtexString bibtexString = new BibtexString("aKopp", "KoppOliver"); assertEquals(BibtexString.Type.AUTHOR, bibtexString.getType()); } @Test public void institutionTypeCorrectlyDetermined() { // Source of the example: https://docs.jabref.org/fields/strings BibtexString bibtexString = new BibtexString("iMIT", "{Massachusetts Institute of Technology ({MIT})}"); assertEquals(BibtexString.Type.INSTITUTION, bibtexString.getType()); } @Test public void otherTypeCorrectlyDeterminedForLowerCase() { // Source of the example: https://docs.jabref.org/fields/strings BibtexString bibtexString = new BibtexString("anct", "Anecdote"); assertEquals(BibtexString.Type.OTHER, bibtexString.getType()); } @Test public void otherTypeCorrectlyDeterminedForUpperCase() { // Source of the example: https://docs.jabref.org/fields/strings BibtexString bibtexString = new BibtexString("lTOSCA", "Topology and Orchestration Specification for Cloud Applications"); assertEquals(BibtexString.Type.OTHER, bibtexString.getType()); } }
4,400
33.928571
130
java
null
jabref-main/src/test/java/org/jabref/model/entry/CanonicalBibEntryTest.java
package org.jabref.model.entry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class CanonicalBibEntryTest { @Test void canonicalRepresentationIsCorrectForStringMonth() { BibEntry entry = new BibEntry(); entry.setMonth(Month.MAY); assertEquals("@misc{,\n" + " month = {#may#},\n" + " _jabref_shared = {sharedId: -1, version: 1}\n" + "}", CanonicalBibEntry.getCanonicalRepresentation(entry)); } @Test public void simpleCanonicalRepresentation() { BibEntry e = new BibEntry(StandardEntryType.Article); e.setCitationKey("key"); e.setField(StandardField.AUTHOR, "abc"); e.setField(StandardField.TITLE, "def"); e.setField(StandardField.JOURNAL, "hij"); String canonicalRepresentation = CanonicalBibEntry.getCanonicalRepresentation(e); assertEquals("@article{key,\n author = {abc},\n journal = {hij},\n title = {def},\n _jabref_shared = {sharedId: -1, version: 1}\n}", canonicalRepresentation); } @Test public void canonicalRepresentationWithNewlines() { BibEntry e = new BibEntry(StandardEntryType.Article); e.setCitationKey("key"); e.setField(StandardField.ABSTRACT, "line 1\nline 2"); String canonicalRepresentation = CanonicalBibEntry.getCanonicalRepresentation(e); assertEquals("@article{key,\n abstract = {line 1\nline 2},\n _jabref_shared = {sharedId: -1, version: 1}\n}", canonicalRepresentation); } }
1,694
38.418605
145
java
null
jabref-main/src/test/java/org/jabref/model/entry/CrossrefTest.java
package org.jabref.model.entry; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.IEEETranEntryType; import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class CrossrefTest { private BibEntry parent; private BibEntry child; private BibDatabase db; @BeforeEach void setup() { parent = new BibEntry(StandardEntryType.Proceedings); parent.setCitationKey("parent"); parent.setField(StandardField.IDS, "parent_IDS"); parent.setField(StandardField.XREF, "parent_XREF"); parent.setField(StandardField.ENTRYSET, "parent_ENTRYSET"); parent.setField(StandardField.RELATED, "parent_RELATED"); parent.setField(StandardField.SORTKEY, "parent_SORTKEY"); parent.setField(StandardField.AUTHOR, "parent_AUTHOR"); parent.setField(StandardField.TITLE, "parent_TITLE"); parent.setField(StandardField.SUBTITLE, "parent_SUBTITLE"); parent.setField(StandardField.TITLEADDON, "parent_TITLEADDON"); parent.setField(StandardField.SHORTTITLE, "parent_SHORTTITLE"); child = new BibEntry(StandardEntryType.InProceedings); child.setField(StandardField.CROSSREF, "parent"); db = new BibDatabase(Arrays.asList(parent, child)); } @ParameterizedTest @EnumSource(value = StandardField.class, names = {"IDS", "XREF", "ENTRYSET", "RELATED", "SORTKEY"}) void forbiddenFields(StandardField field) { Optional<String> childField = child.getResolvedFieldOrAlias(field, db); assertTrue(childField.isEmpty()); } @ParameterizedTest @MethodSource("authorInheritanceSource") void authorInheritance(EntryType parentType, EntryType childType) { parent.setType(parentType); child.setType(childType); assertEquals( parent.getResolvedFieldOrAlias(StandardField.AUTHOR, null), child.getResolvedFieldOrAlias(StandardField.AUTHOR, db) ); assertEquals( parent.getResolvedFieldOrAlias(StandardField.AUTHOR, null), child.getResolvedFieldOrAlias(StandardField.BOOKAUTHOR, db) ); } private static Stream<Arguments> authorInheritanceSource() { return Stream.of( Arguments.of(StandardEntryType.MvBook, StandardEntryType.InBook), Arguments.of(StandardEntryType.MvBook, StandardEntryType.BookInBook), Arguments.of(StandardEntryType.MvBook, StandardEntryType.SuppBook), Arguments.of(StandardEntryType.Book, StandardEntryType.InBook), Arguments.of(StandardEntryType.Book, StandardEntryType.BookInBook), Arguments.of(StandardEntryType.Book, StandardEntryType.SuppBook) ); } @ParameterizedTest @MethodSource("mainTitleInheritanceSource") void mainTitleInheritance(EntryType parentType, EntryType childType) { parent.setType(parentType); child.setType(childType); assertEquals( parent.getResolvedFieldOrAlias(StandardField.TITLE, null), child.getResolvedFieldOrAlias(StandardField.MAINTITLE, db) ); assertEquals( parent.getResolvedFieldOrAlias(StandardField.SUBTITLE, null), child.getResolvedFieldOrAlias(StandardField.MAINSUBTITLE, db) ); assertEquals( parent.getResolvedFieldOrAlias(StandardField.TITLEADDON, null), child.getResolvedFieldOrAlias(StandardField.MAINTITLEADDON, db) ); } private static Stream<Arguments> mainTitleInheritanceSource() { return Stream.of( Arguments.of(StandardEntryType.MvBook, StandardEntryType.Book), Arguments.of(StandardEntryType.MvBook, StandardEntryType.InBook), Arguments.of(StandardEntryType.MvBook, StandardEntryType.BookInBook), Arguments.of(StandardEntryType.MvBook, StandardEntryType.SuppBook), Arguments.of(StandardEntryType.MvCollection, StandardEntryType.Collection), Arguments.of(StandardEntryType.MvCollection, StandardEntryType.InCollection), Arguments.of(StandardEntryType.MvCollection, StandardEntryType.SuppCollection), Arguments.of(StandardEntryType.MvProceedings, StandardEntryType.Proceedings), Arguments.of(StandardEntryType.MvProceedings, StandardEntryType.InProceedings), Arguments.of(StandardEntryType.MvReference, StandardEntryType.Reference), Arguments.of(StandardEntryType.MvReference, StandardEntryType.InReference) ); } @ParameterizedTest @MethodSource("bookTitleInheritanceSource") void bookTitleInheritance(EntryType parentType, EntryType childType) { parent.setType(parentType); child.setType(childType); assertEquals( parent.getResolvedFieldOrAlias(StandardField.TITLE, null), child.getResolvedFieldOrAlias(StandardField.BOOKTITLE, db) ); assertEquals( parent.getResolvedFieldOrAlias(StandardField.SUBTITLE, null), child.getResolvedFieldOrAlias(StandardField.BOOKSUBTITLE, db) ); assertEquals( parent.getResolvedFieldOrAlias(StandardField.TITLEADDON, null), child.getResolvedFieldOrAlias(StandardField.BOOKTITLEADDON, db) ); } private static Stream<Arguments> bookTitleInheritanceSource() { return Stream.of( Arguments.of(StandardEntryType.Book, StandardEntryType.InBook), Arguments.of(StandardEntryType.Book, StandardEntryType.BookInBook), Arguments.of(StandardEntryType.Book, StandardEntryType.SuppBook), Arguments.of(StandardEntryType.Collection, StandardEntryType.InCollection), Arguments.of(StandardEntryType.Collection, StandardEntryType.SuppCollection), Arguments.of(StandardEntryType.Reference, StandardEntryType.InReference), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings) ); } @ParameterizedTest @MethodSource("journalTitleInheritanceSource") void journalTitleInheritance(EntryType parentType, EntryType childType) { parent.setType(parentType); child.setType(childType); assertEquals( parent.getResolvedFieldOrAlias(StandardField.TITLE, null), child.getResolvedFieldOrAlias(StandardField.JOURNALTITLE, db) ); assertEquals( parent.getResolvedFieldOrAlias(StandardField.SUBTITLE, null), child.getResolvedFieldOrAlias(StandardField.JOURNALSUBTITLE, db) ); } private static Stream<Arguments> journalTitleInheritanceSource() { return Stream.of( Arguments.of(IEEETranEntryType.Periodical, StandardEntryType.Article), Arguments.of(IEEETranEntryType.Periodical, StandardEntryType.SuppPeriodical) ); } @ParameterizedTest @MethodSource("noTitleInheritanceSource") void noTitleInheritance(EntryType parentType, EntryType childType) { parent.setType(parentType); child.setType(childType); assertTrue(child.getResolvedFieldOrAlias(StandardField.TITLE, db).isEmpty()); assertTrue(child.getResolvedFieldOrAlias(StandardField.SUBTITLE, db).isEmpty()); assertTrue(child.getResolvedFieldOrAlias(StandardField.TITLEADDON, db).isEmpty()); assertTrue(child.getResolvedFieldOrAlias(StandardField.SHORTTITLE, db).isEmpty()); } private static Stream<Arguments> noTitleInheritanceSource() { return Stream.of( Arguments.of(StandardEntryType.MvBook, StandardEntryType.Book), Arguments.of(StandardEntryType.MvBook, StandardEntryType.InBook), Arguments.of(StandardEntryType.MvBook, StandardEntryType.BookInBook), Arguments.of(StandardEntryType.MvBook, StandardEntryType.SuppBook), Arguments.of(StandardEntryType.MvCollection, StandardEntryType.Collection), Arguments.of(StandardEntryType.MvCollection, StandardEntryType.InCollection), Arguments.of(StandardEntryType.MvCollection, StandardEntryType.SuppCollection), Arguments.of(StandardEntryType.MvProceedings, StandardEntryType.Proceedings), Arguments.of(StandardEntryType.MvProceedings, StandardEntryType.InProceedings), Arguments.of(StandardEntryType.MvReference, StandardEntryType.Reference), Arguments.of(StandardEntryType.MvReference, StandardEntryType.InReference), Arguments.of(StandardEntryType.Book, StandardEntryType.InBook), Arguments.of(StandardEntryType.Book, StandardEntryType.BookInBook), Arguments.of(StandardEntryType.Book, StandardEntryType.SuppBook), Arguments.of(StandardEntryType.Collection, StandardEntryType.InCollection), Arguments.of(StandardEntryType.Collection, StandardEntryType.SuppCollection), Arguments.of(StandardEntryType.Reference, StandardEntryType.InReference), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings) ); } @ParameterizedTest @MethodSource("sameNameInheritance") void sameNameInheritance(EntryType parentType, EntryType childType, StandardField field) { parent.setType(parentType); child.setType(childType); assertTrue(parent.setField(field, "parent_FIELD").isPresent()); assertEquals( parent.getResolvedFieldOrAlias(field, null), child.getResolvedFieldOrAlias(field, db) ); } private static Stream<Arguments> sameNameInheritance() { return Stream.of( Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ABSTRACT), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ADDENDUM), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ADDRESS), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.AFTERWORD), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ANNOTE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ANNOTATION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ANNOTATOR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ARCHIVEPREFIX), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ASSIGNEE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.AUTHOR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.BOOKPAGINATION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.CHAPTER), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.COMMENTATOR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.COMMENT), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.DATE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.DAY), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.DAYFILED), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.DOI), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITOR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITORA), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITORB), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITORC), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITORTYPE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITORATYPE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITORBTYPE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EDITORCTYPE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EID), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EPRINT), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EPRINTCLASS), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EPRINTTYPE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EVENTDATE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EVENTTITLE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.EVENTTITLEADDON), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.FILE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.FOREWORD), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.FOLDER), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.GENDER), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.HOLDER), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.HOWPUBLISHED), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.INSTITUTION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.INTRODUCTION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ISBN), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ISRN), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ISSN), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ISSUE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ISSUETITLE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ISSUESUBTITLE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.JOURNAL), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.KEY), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.KEYWORDS), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.LANGUAGE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.LOCATION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.MONTH), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.MONTHFILED), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.NAMEADDON), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.NATIONALITY), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.NOTE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.NUMBER), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ORGANIZATION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ORIGDATE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.ORIGLANGUAGE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PAGES), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PAGETOTAL), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PAGINATION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PART), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PDF), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PMID), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PS), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PUBLISHER), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PUBSTATE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.PRIMARYCLASS), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.REPORTNO), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.REVIEW), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.REVISION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.SCHOOL), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.SERIES), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.SHORTAUTHOR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.SHORTEDITOR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.SORTNAME), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.TRANSLATOR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.TYPE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.URI), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.URL), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.URLDATE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.VENUE), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.VERSION), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.VOLUME), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.VOLUMES), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.YEAR), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.YEARFILED), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.MR_NUMBER), Arguments.of(StandardEntryType.Proceedings, StandardEntryType.InProceedings, StandardField.XDATA) ); } }
21,432
65.151235
124
java
null
jabref-main/src/test/java/org/jabref/model/entry/DateTest.java
package org.jabref.model.entry; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.time.Year; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.Temporal; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class DateTest { private static Stream<Arguments> validDates() { return Stream.of( Arguments.of(LocalDateTime.of(2018, Month.OCTOBER, 3, 7, 24), "2018-10-03T07:24"), Arguments.of(LocalDateTime.of(2018, Month.OCTOBER, 3, 17, 2), "2018-10-03T17:2"), Arguments.of(LocalDateTime.of(2018, Month.OCTOBER, 3, 7, 24), "2018-10-03T7:24"), Arguments.of(LocalDateTime.of(2018, Month.OCTOBER, 3, 7, 7), "2018-10-03T7:7"), Arguments.of(LocalDateTime.of(2018, Month.OCTOBER, 3, 7, 0), "2018-10-03T07"), Arguments.of(LocalDateTime.of(2018, Month.OCTOBER, 3, 7, 0), "2018-10-03T7"), Arguments.of(LocalDate.of(2009, Month.JANUARY, 15), "2009-1-15"), Arguments.of(YearMonth.of(2009, Month.NOVEMBER), "2009-11"), Arguments.of(LocalDate.of(2012, Month.JANUARY, 15), "15-1-2012"), Arguments.of(YearMonth.of(2012, Month.JANUARY), "1-2012"), Arguments.of(YearMonth.of(2015, Month.SEPTEMBER), "9/2015"), Arguments.of(YearMonth.of(2015, Month.SEPTEMBER), "09/2015"), Arguments.of(YearMonth.of(2015, Month.SEPTEMBER), "9/15"), Arguments.of(LocalDate.of(2015, Month.SEPTEMBER, 1), "September 1, 2015"), Arguments.of(YearMonth.of(2015, Month.SEPTEMBER), "September, 2015"), Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), "15.1.2015"), Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), "2015.1.15"), Arguments.of(Year.of(2015), "2015"), Arguments.of(YearMonth.of(2020, Month.JANUARY), "Jan, 2020"), Arguments.of(LocalDate.of(2015, Month.OCTOBER, 15), "2015.10.15"), Arguments.of(LocalDate.of(-10000, Month.OCTOBER, 15), "-10000-10-15"), Arguments.of(YearMonth.of(2015, Month.NOVEMBER), "2015/11"), Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), "15 January 2015") ); } @ParameterizedTest @MethodSource("validDates") void parseByDatePattern(Temporal expected, String provided) { assertEquals(Optional.of(new Date(expected)), Date.parse(provided)); } private static Stream<Arguments> validDateRanges() { return Stream.of( Arguments.of(Year.of(2014), Year.of(2017), "2014/2017"), Arguments.of(YearMonth.of(2015, Month.JANUARY), YearMonth.of(2015, Month.FEBRUARY), "2015-01/2015-02"), Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "2015-01-15/2015-02-25"), Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "2015-01-15 / 2015-02-25"), Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "15 January 2015/25 February 2015"), Arguments.of(LocalDate.of(2015, Month.JANUARY, 15), LocalDate.of(2015, Month.FEBRUARY, 25), "15 January 2015 / 25 February 2015") ); } @ParameterizedTest @MethodSource("validDateRanges") void parseByDatePatternRange(Temporal expectedRangeStart, Temporal expectedRangeEnd, String provided) { assertEquals(Optional.of(new Date(expectedRangeStart, expectedRangeEnd)), Date.parse(provided)); } private static Stream<Arguments> invalidCornerCases() { return Stream.of( Arguments.of("", "input value not empty"), Arguments.of("32-06-2014", "day of month exists [1]"), Arguments.of("00-06-2014", "day of month exists [2]"), Arguments.of("30-13-2014", "month exists [1]"), Arguments.of("30-00-2014", "month exists [2]") ); } @ParameterizedTest @MethodSource("invalidCornerCases") void nonExistentDates(String invalidDate, String errorMessage) { assertEquals(Optional.empty(), Date.parse(invalidDate), errorMessage); } @Test void parseZonedTime() { Optional<Date> expected = Optional.of( new Date(ZonedDateTime.of( LocalDateTime.of(2018, Month.OCTOBER, 3, 7, 24, 14), ZoneId.from(ZoneOffset.ofHours(3))) ) ); assertEquals(expected, Date.parse("2018-10-03T07:24:14+03:00")); assertNotEquals(expected, Date.parse("2018-10-03T07:24:14+02:00")); } @Test void parseDateNull() { assertThrows(NullPointerException.class, () -> Date.parse(null)); } }
5,327
47.436364
142
java
null
jabref-main/src/test/java/org/jabref/model/entry/EntryLinkListTest.java
package org.jabref.model.entry; import java.util.List; import java.util.Optional; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class EntryLinkListTest { private static final String KEY = "test"; private BibDatabase database; private List<ParsedEntryLink> links; private ParsedEntryLink link; private BibEntry source; private BibEntry target; @BeforeEach public void before() { database = new BibDatabase(); links = EntryLinkList.parse(KEY, database); link = links.get(0); source = create("source"); target = create("target"); } private BibEntry create(String citeKey) { BibEntry entry = new BibEntry() .withCitationKey(citeKey); database.insertEntry(entry); return entry; } @Test public void givenFieldValueAndDatabaseWhenParsingThenExpectKey() { assertEquals(KEY, link.getKey()); } @Test public void givenFieldValueAndDatabaseWhenParsingThenExpectDataBase() { assertEquals(database, link.getDatabase()); } @Test public void givenFieldValueAndDatabaseWhenParsingThenExpectEmptyLinkedEntry() { assertEquals(Optional.empty(), link.getLinkedEntry()); } @Test public void givenFieldValueAndDatabaseWhenParsingThenExpectLink() { ParsedEntryLink expected = new ParsedEntryLink(KEY, database); assertEquals(expected, link); } @Test public void givenBibEntryWhenParsingThenExpectLink() { ParsedEntryLink expected = new ParsedEntryLink(new BibEntry().withCitationKey("key")); assertFalse(expected.getLinkedEntry().isEmpty()); } @Test public void givenNullFieldValueAndDatabaseWhenParsingThenExpectLinksIsEmpty() { links = EntryLinkList.parse(null, database); assertTrue(links.isEmpty()); } @Test public void givenTargetAndSourceWhenSourceCrossrefTargetThenSourceCrossrefsTarget() { source.setField(StandardField.CROSSREF, "target"); assertSourceCrossrefsTarget(target, source); } private void assertSourceCrossrefsTarget(BibEntry target, BibEntry source) { Optional<String> sourceCrossref = source.getField(StandardField.CROSSREF); Optional<String> targetCiteKey = target.getCitationKey(); assertEquals(sourceCrossref, targetCiteKey); } }
2,686
29.885057
92
java
null
jabref-main/src/test/java/org/jabref/model/entry/EntryTypeFactoryTest.java
package org.jabref.model.entry; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.entry.types.IEEETranEntryType; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class EntryTypeFactoryTest { @Test public void testParseEntryTypePatent() { EntryType patent = IEEETranEntryType.Patent; assertEquals(patent, EntryTypeFactory.parse("patent")); } }
505
25.631579
63
java
null
jabref-main/src/test/java/org/jabref/model/entry/IdGeneratorTest.java
package org.jabref.model.entry; import java.util.HashSet; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; public class IdGeneratorTest { @Test public void testCreateNeutralId() { HashSet<String> set = new HashSet<>(); for (int i = 0; i < 10000; i++) { String string = IdGenerator.next(); assertFalse(set.contains(string)); set.add(string); } } }
470
21.428571
59
java
null
jabref-main/src/test/java/org/jabref/model/entry/KeywordListTest.java
package org.jabref.model.entry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class KeywordListTest { private KeywordList keywords; @BeforeEach public void setUp() throws Exception { keywords = new KeywordList(); keywords.add("keywordOne"); keywords.add("keywordTwo"); } @Test public void parseEmptyStringReturnsEmptyList() throws Exception { assertEquals(new KeywordList(), KeywordList.parse("", ',')); } @Test public void parseOneWordReturnsOneKeyword() throws Exception { assertEquals(new KeywordList("keywordOne"), KeywordList.parse("keywordOne", ',')); } @Test public void parseTwoWordReturnsTwoKeywords() throws Exception { assertEquals(new KeywordList("keywordOne", "keywordTwo"), KeywordList.parse("keywordOne, keywordTwo", ',')); } @Test public void parseTwoWordReturnsTwoKeywordsWithoutSpace() throws Exception { assertEquals(new KeywordList("keywordOne", "keywordTwo"), KeywordList.parse("keywordOne,keywordTwo", ',')); } @Test public void parseTwoWordReturnsTwoKeywordsWithDifferentDelimiter() throws Exception { assertEquals(new KeywordList("keywordOne", "keywordTwo"), KeywordList.parse("keywordOne| keywordTwo", '|')); } @Test public void parseWordsWithWhitespaceReturnsOneKeyword() throws Exception { assertEquals(new KeywordList("keyword and one"), KeywordList.parse("keyword and one", ',')); } @Test public void parseWordsWithWhitespaceAndCommaReturnsTwoKeyword() throws Exception { assertEquals(new KeywordList("keyword and one", "and two"), KeywordList.parse("keyword and one, and two", ',')); } @Test public void parseIgnoresDuplicates() throws Exception { assertEquals(new KeywordList("keywordOne", "keywordTwo"), KeywordList.parse("keywordOne, keywordTwo, keywordOne", ',')); } @Test public void parseTakeDelimiterNotRegexWhite() throws Exception { assertEquals(new KeywordList("keywordOne keywordTwo", "keywordThree"), KeywordList.parse("keywordOne keywordTwoskeywordThree", 's')); } @Test public void parseWordsWithBracketsReturnsOneKeyword() throws Exception { assertEquals(new KeywordList("[a] keyword"), KeywordList.parse("[a] keyword", ',')); } @Test public void asStringAddsSpaceAfterDelimiter() throws Exception { assertEquals("keywordOne, keywordTwo", keywords.getAsString(',')); } @Test public void parseHierarchicalChain() throws Exception { Keyword expected = Keyword.of("Parent", "Node", "Child"); assertEquals(new KeywordList(expected), KeywordList.parse("Parent > Node > Child", ',', '>')); } @Test public void parseTwoHierarchicalChains() throws Exception { Keyword expectedOne = Keyword.of("Parent1", "Node1", "Child1"); Keyword expectedTwo = Keyword.of("Parent2", "Node2", "Child2"); assertEquals(new KeywordList(expectedOne, expectedTwo), KeywordList.parse("Parent1 > Node1 > Child1, Parent2 > Node2 > Child2", ',', '>')); } @Test public void mergeTwoIdenticalKeywordsShouldReturnOnKeyword() { assertEquals(new KeywordList("JabRef"), KeywordList.merge("JabRef", "JabRef", ',')); } @Test public void mergeOneEmptyKeywordAnAnotherNonEmptyShouldReturnTheNonEmptyKeyword() { assertEquals(new KeywordList("JabRef"), KeywordList.merge("", "JabRef", ',')); } @Test public void mergeTwoDistinctKeywordsShouldReturnTheTwoKeywordsMerged() { assertEquals(new KeywordList("Figma", "JabRef"), KeywordList.merge("Figma", "JabRef", ',')); assertEquals(new KeywordList("JabRef", "Figma"), KeywordList.merge("Figma", "JabRef", ',')); } @Test public void mergeTwoListsOfKeywordsShouldReturnTheKeywordsMerged() { assertEquals(new KeywordList("Figma", "Adobe", "JabRef", "Eclipse", "JetBrains"), KeywordList.merge("Figma, Adobe, JetBrains, Eclipse", "Adobe, JabRef", ',')); } }
4,278
34.957983
167
java
null
jabref-main/src/test/java/org/jabref/model/entry/KeywordTest.java
package org.jabref.model.entry; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class KeywordTest { @Test public void getPathFromRootAsStringForSimpleChain() throws Exception { Keyword keywordChain = Keyword.of("A", "B", "C"); assertEquals("A > B", keywordChain.getChild().get().getPathFromRootAsString('>')); } @Test public void getAllSubchainsAsStringForSimpleChain() throws Exception { Keyword keywordChain = Keyword.of("A", "B", "C"); Set<String> expected = new HashSet<>(); expected.add("A"); expected.add("A > B"); expected.add("A > B > C"); assertEquals(expected, keywordChain.getAllSubchainsAsString('>')); } }
817
27.206897
90
java
null
jabref-main/src/test/java/org/jabref/model/entry/MonthTest.java
package org.jabref.model.entry; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.params.provider.Arguments.arguments; public class MonthTest { @ParameterizedTest @MethodSource({"parseShortName", "parseBibtexName", "parseFullName", "parseTwoDigitNumber", "parseNumber", "parseShortNameGerman", "parseFullNameGerman", "parseShortNameGermanLowercase", "parseSpecialCases"}) void parseCorrectly(Optional<Month> expected, String input) { assertEquals(expected, Month.parse(input)); } private static Stream<Arguments> parseShortName() { return Stream.of( arguments(Optional.of(Month.JANUARY), "jan"), arguments(Optional.of(Month.FEBRUARY), "feb"), arguments(Optional.of(Month.MARCH), "mar"), arguments(Optional.of(Month.APRIL), "apr"), arguments(Optional.of(Month.MAY), "may"), arguments(Optional.of(Month.JUNE), "jun"), arguments(Optional.of(Month.JULY), "jul"), arguments(Optional.of(Month.AUGUST), "aug"), arguments(Optional.of(Month.SEPTEMBER), "sep"), arguments(Optional.of(Month.OCTOBER), "oct"), arguments(Optional.of(Month.NOVEMBER), "nov"), arguments(Optional.of(Month.DECEMBER), "dec") ); } private static Stream<Arguments> parseBibtexName() { return Stream.of( arguments(Optional.of(Month.JANUARY), "#jan#"), arguments(Optional.of(Month.FEBRUARY), "#feb#"), arguments(Optional.of(Month.MARCH), "#mar#"), arguments(Optional.of(Month.APRIL), "#apr#"), arguments(Optional.of(Month.MAY), "#may#"), arguments(Optional.of(Month.JUNE), "#jun#"), arguments(Optional.of(Month.JULY), "#jul#"), arguments(Optional.of(Month.AUGUST), "#aug#"), arguments(Optional.of(Month.SEPTEMBER), "#sep#"), arguments(Optional.of(Month.OCTOBER), "#oct#"), arguments(Optional.of(Month.NOVEMBER), "#nov#"), arguments(Optional.of(Month.DECEMBER), "#dec#") ); } private static Stream<Arguments> parseFullName() { return Stream.of( arguments(Optional.of(Month.JANUARY), "January"), arguments(Optional.of(Month.FEBRUARY), "February"), arguments(Optional.of(Month.MARCH), "March"), arguments(Optional.of(Month.APRIL), "April"), arguments(Optional.of(Month.MAY), "May"), arguments(Optional.of(Month.JUNE), "June"), arguments(Optional.of(Month.JULY), "July"), arguments(Optional.of(Month.AUGUST), "August"), arguments(Optional.of(Month.SEPTEMBER), "September"), arguments(Optional.of(Month.OCTOBER), "October"), arguments(Optional.of(Month.NOVEMBER), "November"), arguments(Optional.of(Month.DECEMBER), "December") ); } private static Stream<Arguments> parseTwoDigitNumber() { return Stream.of( arguments(Optional.of(Month.JANUARY), "01"), arguments(Optional.of(Month.FEBRUARY), "02"), arguments(Optional.of(Month.MARCH), "03"), arguments(Optional.of(Month.APRIL), "04"), arguments(Optional.of(Month.MAY), "05"), arguments(Optional.of(Month.JUNE), "06"), arguments(Optional.of(Month.JULY), "07"), arguments(Optional.of(Month.AUGUST), "08"), arguments(Optional.of(Month.SEPTEMBER), "09"), arguments(Optional.of(Month.OCTOBER), "10"), arguments(Optional.of(Month.NOVEMBER), "11"), arguments(Optional.of(Month.DECEMBER), "12") ); } private static Stream<Arguments> parseNumber() { return Stream.of( arguments(Optional.of(Month.JANUARY), "1"), arguments(Optional.of(Month.FEBRUARY), "2"), arguments(Optional.of(Month.MARCH), "3"), arguments(Optional.of(Month.APRIL), "4"), arguments(Optional.of(Month.MAY), "5"), arguments(Optional.of(Month.JUNE), "6"), arguments(Optional.of(Month.JULY), "7"), arguments(Optional.of(Month.AUGUST), "8"), arguments(Optional.of(Month.SEPTEMBER), "9"), arguments(Optional.of(Month.OCTOBER), "10"), arguments(Optional.of(Month.NOVEMBER), "11"), arguments(Optional.of(Month.DECEMBER), "12") ); } private static Stream<Arguments> parseShortNameGerman() { return Stream.of( arguments(Optional.of(Month.JANUARY), "Jan"), arguments(Optional.of(Month.FEBRUARY), "Feb"), arguments(Optional.of(Month.MARCH), "Mär"), arguments(Optional.of(Month.MARCH), "Mae"), arguments(Optional.of(Month.APRIL), "Apr"), arguments(Optional.of(Month.MAY), "Mai"), arguments(Optional.of(Month.JUNE), "Jun"), arguments(Optional.of(Month.JULY), "Jul"), arguments(Optional.of(Month.AUGUST), "Aug"), arguments(Optional.of(Month.SEPTEMBER), "Sep"), arguments(Optional.of(Month.OCTOBER), "Okt"), arguments(Optional.of(Month.NOVEMBER), "Nov"), arguments(Optional.of(Month.DECEMBER), "Dez") ); } private static Stream<Arguments> parseFullNameGerman() { return Stream.of( arguments(Optional.of(Month.JANUARY), "Januar"), arguments(Optional.of(Month.FEBRUARY), "Februar"), arguments(Optional.of(Month.MARCH), "März"), arguments(Optional.of(Month.MARCH), "Maerz"), arguments(Optional.of(Month.APRIL), "April"), arguments(Optional.of(Month.MAY), "Mai"), arguments(Optional.of(Month.JUNE), "Juni"), arguments(Optional.of(Month.JULY), "Juli"), arguments(Optional.of(Month.AUGUST), "August"), arguments(Optional.of(Month.SEPTEMBER), "September"), arguments(Optional.of(Month.OCTOBER), "Oktober"), arguments(Optional.of(Month.NOVEMBER), "November"), arguments(Optional.of(Month.DECEMBER), "Dezember") ); } private static Stream<Arguments> parseShortNameGermanLowercase() { return Stream.of( arguments(Optional.of(Month.JANUARY), "jan"), arguments(Optional.of(Month.FEBRUARY), "feb"), arguments(Optional.of(Month.MARCH), "mär"), arguments(Optional.of(Month.MARCH), "mae"), arguments(Optional.of(Month.APRIL), "apr"), arguments(Optional.of(Month.MAY), "mai"), arguments(Optional.of(Month.JUNE), "jun"), arguments(Optional.of(Month.JULY), "jul"), arguments(Optional.of(Month.AUGUST), "aug"), arguments(Optional.of(Month.SEPTEMBER), "sep"), arguments(Optional.of(Month.OCTOBER), "okt"), arguments(Optional.of(Month.NOVEMBER), "nov"), arguments(Optional.of(Month.DECEMBER), "dez") ); } private static Stream<Arguments> parseSpecialCases() { return Stream.of( arguments(Optional.empty(), ";lkjasdf"), arguments(Optional.empty(), "3.2"), arguments(Optional.empty(), "#test#"), arguments(Optional.empty(), "8,"), arguments(Optional.empty(), "") ); } @ParameterizedTest @MethodSource("parseGermanShortMonthTest") public void parseGermanShortMonthTest(Optional<Month> expected, String input) { assertEquals(expected, Month.parseGermanShortMonth(input)); } private static Stream<Arguments> parseGermanShortMonthTest() { return Stream.of( arguments(Optional.of(Month.JANUARY), "jan"), arguments(Optional.of(Month.JANUARY), "januar"), arguments(Optional.of(Month.FEBRUARY), "feb"), arguments(Optional.of(Month.FEBRUARY), "februar"), arguments(Optional.of(Month.MARCH), "mär"), arguments(Optional.of(Month.MARCH), "mae"), arguments(Optional.of(Month.MARCH), "märz"), arguments(Optional.of(Month.MARCH), "maerz"), arguments(Optional.of(Month.APRIL), "apr"), arguments(Optional.of(Month.APRIL), "april"), arguments(Optional.of(Month.MAY), "mai"), arguments(Optional.of(Month.JUNE), "jun"), arguments(Optional.of(Month.JUNE), "juni"), arguments(Optional.of(Month.JULY), "jul"), arguments(Optional.of(Month.JULY), "juli"), arguments(Optional.of(Month.AUGUST), "aug"), arguments(Optional.of(Month.AUGUST), "august"), arguments(Optional.of(Month.SEPTEMBER), "sep"), arguments(Optional.of(Month.SEPTEMBER), "september"), arguments(Optional.of(Month.OCTOBER), "okt"), arguments(Optional.of(Month.OCTOBER), "oktober"), arguments(Optional.of(Month.NOVEMBER), "nov"), arguments(Optional.of(Month.NOVEMBER), "november"), arguments(Optional.of(Month.DECEMBER), "dez"), arguments(Optional.of(Month.DECEMBER), "dezember") ); } @ParameterizedTest @MethodSource("getMonthByNumberTest") public void getMonthByNumberTest(Optional<Month> expected, int input) { assertEquals(expected, Month.getMonthByNumber(input)); } private static Stream<Arguments> getMonthByNumberTest() { return Stream.of( arguments(Optional.empty(), -1), arguments(Optional.empty(), 0), arguments(Optional.of(Month.JANUARY), 1), arguments(Optional.of(Month.FEBRUARY), 2), arguments(Optional.of(Month.MARCH), 3), arguments(Optional.of(Month.APRIL), 4), arguments(Optional.of(Month.MAY), 5), arguments(Optional.of(Month.JUNE), 6), arguments(Optional.of(Month.JULY), 7), arguments(Optional.of(Month.AUGUST), 8), arguments(Optional.of(Month.SEPTEMBER), 9), arguments(Optional.of(Month.OCTOBER), 10), arguments(Optional.of(Month.NOVEMBER), 11), arguments(Optional.of(Month.DECEMBER), 12), arguments(Optional.empty(), 13), arguments(Optional.empty(), 14) ); } @ParameterizedTest @MethodSource({"parseShortName", "getMonthByShortNameSpecialCases"}) public void getMonthByShortNameLowercaseTest(Optional<Month> expected, String input) { assertEquals(expected, Month.getMonthByShortName(input)); } private static Stream<Arguments> getMonthByShortNameSpecialCases() { return Stream.of( arguments(Optional.of(Month.JANUARY), "jan"), arguments(Optional.of(Month.JANUARY), "Jan"), arguments(Optional.of(Month.JANUARY), "JAN"), arguments(Optional.empty(), ""), arguments(Optional.empty(), "dez"), arguments(Optional.empty(), "+*ç%&/()=.,:;-${}![]^'?~¦@#°§¬|¢äüö") ); } @ParameterizedTest @MethodSource("getShortNameTest") public void getShortNameTest(String expected, Month month) { assertEquals(expected, month.getShortName()); } private static Stream<Arguments> getShortNameTest() { return Stream.of( arguments("jan", Month.JANUARY), arguments("feb", Month.FEBRUARY), arguments("mar", Month.MARCH), arguments("apr", Month.APRIL), arguments("may", Month.MAY), arguments("jun", Month.JUNE), arguments("jul", Month.JULY), arguments("aug", Month.AUGUST), arguments("sep", Month.SEPTEMBER), arguments("oct", Month.OCTOBER), arguments("nov", Month.NOVEMBER), arguments("dec", Month.DECEMBER) ); } @ParameterizedTest @MethodSource("getJabRefFormatTest") public void getJabRefFormatTest(String expected, Month month) { assertEquals(expected, month.getJabRefFormat()); } private static Stream<Arguments> getJabRefFormatTest() { return Stream.of( arguments("#jan#", Month.JANUARY), arguments("#feb#", Month.FEBRUARY), arguments("#mar#", Month.MARCH), arguments("#apr#", Month.APRIL), arguments("#may#", Month.MAY), arguments("#jun#", Month.JUNE), arguments("#jul#", Month.JULY), arguments("#aug#", Month.AUGUST), arguments("#sep#", Month.SEPTEMBER), arguments("#oct#", Month.OCTOBER), arguments("#nov#", Month.NOVEMBER), arguments("#dec#", Month.DECEMBER) ); } @ParameterizedTest @MethodSource("getNumberTest") public void getNumberTest(int expected, Month month) { assertEquals(expected, month.getNumber()); } private static Stream<Arguments> getNumberTest() { return Stream.of( arguments(1, Month.JANUARY), arguments(2, Month.FEBRUARY), arguments(3, Month.MARCH), arguments(4, Month.APRIL), arguments(5, Month.MAY), arguments(6, Month.JUNE), arguments(7, Month.JULY), arguments(8, Month.AUGUST), arguments(9, Month.SEPTEMBER), arguments(10, Month.OCTOBER), arguments(11, Month.NOVEMBER), arguments(12, Month.DECEMBER) ); } @ParameterizedTest @MethodSource("getFullNameTest") public void getFullNameTest(String expected, Month month) { assertEquals(expected, month.getFullName()); } private static Stream<Arguments> getFullNameTest() { return Stream.of( arguments("January", Month.JANUARY), arguments("February", Month.FEBRUARY), arguments("March", Month.MARCH), arguments("April", Month.APRIL), arguments("May", Month.MAY), arguments("June", Month.JUNE), arguments("July", Month.JULY), arguments("August", Month.AUGUST), arguments("September", Month.SEPTEMBER), arguments("October", Month.OCTOBER), arguments("November", Month.NOVEMBER), arguments("December", Month.DECEMBER) ); } @ParameterizedTest @MethodSource("getTwoDigitNumberTest") public void getTwoDigitNumberTest(String expected, Month month) { assertEquals(expected, month.getTwoDigitNumber()); } private static Stream<Arguments> getTwoDigitNumberTest() { return Stream.of( arguments("01", Month.JANUARY), arguments("02", Month.FEBRUARY), arguments("03", Month.MARCH), arguments("04", Month.APRIL), arguments("05", Month.MAY), arguments("06", Month.JUNE), arguments("07", Month.JULY), arguments("08", Month.AUGUST), arguments("09", Month.SEPTEMBER), arguments("10", Month.OCTOBER), arguments("11", Month.NOVEMBER), arguments("12", Month.DECEMBER) ); } }
16,276
43.594521
212
java
null
jabref-main/src/test/java/org/jabref/model/entry/field/BibFieldTest.java
package org.jabref.model.entry.field; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class BibFieldTest { @Test void bibFieldsConsideredEqualIfUnderlyingFieldIsEqual() { assertEquals(new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT), new BibField(StandardField.AUTHOR, FieldPriority.DETAIL)); } @Test void bibFieldsConsideredNotEqualIfUnderlyingFieldNotEqual() { assertNotEquals(new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT), new BibField(StandardField.TITLE, FieldPriority.IMPORTANT)); } }
673
32.7
145
java
null
jabref-main/src/test/java/org/jabref/model/entry/field/FieldFactoryTest.java
package org.jabref.model.entry.field; import java.util.stream.Stream; import org.jabref.model.entry.types.BiblatexApaEntryType; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class FieldFactoryTest { @Test void testOrFieldsTwoTerms() { assertEquals("Aaa/Bbb", FieldFactory.serializeOrFields(new UnknownField("aaa"), new UnknownField("bbb"))); } @Test void testOrFieldsThreeTerms() { assertEquals("Aaa/Bbb/Ccc", FieldFactory.serializeOrFields(new UnknownField("aaa"), new UnknownField("bbb"), new UnknownField("ccc"))); } private static Stream<Arguments> fieldsWithoutFieldProperties() { return Stream.of( // comment fields Arguments.of(new UserSpecificCommentField("user1"), "comment-user1"), Arguments.of(new UserSpecificCommentField("other-user-id"), "comment-other-user-id"), // unknown field Arguments.of(new UnknownField("cased", "cAsEd"), "cAsEd") ); } @ParameterizedTest @MethodSource void fieldsWithoutFieldProperties(Field expected, String name) { assertEquals(expected, FieldFactory.parseField(name)); } @Test void testDoesNotParseApaFieldWithoutEntryType() { assertNotEquals(BiblatexApaField.ARTICLE, FieldFactory.parseField("article")); } @Test void testDoesParseApaFieldWithEntryType() { assertEquals(BiblatexApaField.ARTICLE, FieldFactory.parseField(BiblatexApaEntryType.Constitution, "article")); } }
1,805
33.730769
143
java
null
jabref-main/src/test/java/org/jabref/model/entry/field/SpecialFieldTest.java
package org.jabref.model.entry.field; import java.util.Optional; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class SpecialFieldTest { @Test public void getSpecialFieldInstanceFromFieldNameValid() { assertEquals(Optional.of(SpecialField.RANKING), SpecialField.fromName("ranking")); } @Test public void getSpecialFieldInstanceFromFieldNameEmptyForInvalidField() { assertEquals(Optional.empty(), SpecialField.fromName("title")); } }
551
24.090909
76
java