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/bst/util/BstPurifierTest.java
package org.jabref.logic.bst.util; 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 BstPurifierTest { @ParameterizedTest @MethodSource("provideTestStrings") public void testPurify(String expected, String toBePurified) { assertEquals(expected, BstPurifier.purify(toBePurified)); } private static Stream<Arguments> provideTestStrings() { return Stream.of( Arguments.of("i", "i"), Arguments.of("0I ", "0I~ "), Arguments.of("Hi Hi ", "Hi Hi "), Arguments.of("oe", "{\\oe}"), Arguments.of("Hi oeHi ", "Hi {\\oe }Hi "), Arguments.of("Jonathan Meyer and Charles Louis Xavier Joseph de la Vallee Poussin", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin"), Arguments.of("e", "{\\'e}"), Arguments.of("Edouard Masterly", "{\\'{E}}douard Masterly"), Arguments.of("Ulrich Underwood and Ned Net and Paul Pot", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot") ); } }
1,311
38.757576
176
java
null
jabref-main/src/test/java/org/jabref/logic/bst/util/BstTextPrefixerTest.java
package org.jabref.logic.bst.util; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class BstTextPrefixerTest { @Test public void testPrefix() { assertPrefix("i", "i"); assertPrefix("0I~ ", "0I~ "); assertPrefix("Hi Hi", "Hi Hi "); assertPrefix("{\\oe}", "{\\oe}"); assertPrefix("Hi {\\oe }H", "Hi {\\oe }Hi "); assertPrefix("Jonat", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin"); assertPrefix("{\\'e}", "{\\'e}"); assertPrefix("{\\'{E}}doua", "{\\'{E}}douard Masterly"); assertPrefix("Ulric", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot"); } private static void assertPrefix(final String string, final String string2) { assertEquals(string, BstTextPrefixer.textPrefix(5, string2)); } }
899
33.615385
106
java
null
jabref-main/src/test/java/org/jabref/logic/bst/util/BstWidthCalculatorTest.java
package org.jabref.logic.bst.util; 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; /** * How to create these test using Bibtex: * <p/> * Execute this charWidth.bst with the following charWidth.aux: * <p/> * <p/> * <code> * ENTRY{}{}{} * FUNCTION{test} * { * "i" width$ int.to.str$ write$ newline$ * "0I~ " width$ int.to.str$ write$ newline$ * "Hi Hi " width$ int.to.str$ write$ newline$ * "{\oe}" width$ int.to.str$ write$ newline$ * "Hi {\oe }Hi " width$ int.to.str$ write$ newline$ * } * READ * EXECUTE{test} * </code> * <p/> * <code> * \bibstyle{charWidth} * \citation{canh05} * \bibdata{test} * \bibcite{canh05}{CMM{$^{+}$}05} * </code> */ public class BstWidthCalculatorTest { @ParameterizedTest @MethodSource("provideTestWidth") public void testWidth(int i, String str) { assertEquals(i, BstWidthCalculator.width(str)); } private static Stream<Arguments> provideTestWidth() { return Stream.of( Arguments.of(278, "i"), Arguments.of(1639, "0I~ "), Arguments.of(2612, "Hi Hi "), Arguments.of(778, "{\\oe}"), Arguments.of(3390, "Hi {\\oe }Hi "), Arguments.of(444, "{\\'e}"), Arguments.of(19762, "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot"), Arguments.of(7861, "{\\'{E}}douard Masterly"), Arguments.of(30514, "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin") ); } @ParameterizedTest @MethodSource("provideTestGetCharWidth") public void testGetCharWidth(int i, Character c) { assertEquals(i, BstWidthCalculator.getCharWidth(c)); } private static Stream<Arguments> provideTestGetCharWidth() { return Stream.of( Arguments.of(500, '0'), Arguments.of(361, 'I'), Arguments.of(500, '~'), Arguments.of(500, '}'), Arguments.of(278, ' ') ); } }
2,243
28.526316
111
java
null
jabref-main/src/test/java/org/jabref/logic/citationkeypattern/AbstractCitationKeyPatternTest.java
package org.jabref.logic.citationkeypattern; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; @Execution(ExecutionMode.CONCURRENT) class AbstractCitationKeyPatternTest { @Test void AbstractCitationKeyPatternParse() throws Exception { AbstractCitationKeyPattern pattern = mock(AbstractCitationKeyPattern.class, Mockito.CALLS_REAL_METHODS); pattern.setDefaultValue("[field1]spacer1[field2]spacer2[field3]"); List<String> expectedPattern = List.of( "[field1]spacer1[field2]spacer2[field3]", "[", "field1", "]", "spacer1", "[", "field2", "]", "spacer2", "[", "field3", "]" ); assertEquals(expectedPattern, pattern.getDefaultValue()); } @Test void AbstractCitationKeyPatternParseEmptySpacer() throws Exception { AbstractCitationKeyPattern pattern = mock(AbstractCitationKeyPattern.class, Mockito.CALLS_REAL_METHODS); pattern.setDefaultValue("[field1][field2]spacer2[field3]"); List<String> expectedPattern = List.of( "[field1][field2]spacer2[field3]", "[", "field1", "]", "[", "field2", "]", "spacer2", "[", "field3", "]" ); assertEquals(expectedPattern, pattern.getDefaultValue()); } }
1,710
28
112
java
null
jabref-main/src/test/java/org/jabref/logic/citationkeypattern/BracketedPatternTest.java
package org.jabref.logic.citationkeypattern; import java.util.stream.Stream; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibtexString; 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.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; 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; /** * Tests based on a BibEntry are contained in {@link CitationKeyGeneratorTest} */ @Execution(ExecutionMode.CONCURRENT) class BracketedPatternTest { private BibEntry bibentry; private BibDatabase database; private BibEntry dbentry; @BeforeEach void setUp() { bibentry = new BibEntry().withField(StandardField.AUTHOR, "O. Kitsune") .withField(StandardField.YEAR, "2017") .withField(StandardField.PAGES, "213--216"); dbentry = new BibEntry(StandardEntryType.Article) .withCitationKey("HipKro03") .withField(StandardField.AUTHOR, "Eric von Hippel and Georg von Krogh") .withField(StandardField.TITLE, "Open Source Software and the \"Private-Collective\" Innovation Model: Issues for Organization Science") .withField(StandardField.JOURNAL, "Organization Science") .withField(StandardField.YEAR, "2003") .withField(StandardField.VOLUME, "14") .withField(StandardField.PAGES, "209--223") .withField(StandardField.NUMBER, "2") .withField(StandardField.ADDRESS, "Institute for Operations Research and the Management Sciences (INFORMS), Linthicum, Maryland, USA") .withField(StandardField.DOI, "http://dx.doi.org/10.1287/orsc.14.2.209.14992") .withField(StandardField.ISSN, "1526-5455") .withField(StandardField.PUBLISHER, "INFORMS"); database = new BibDatabase(); database.insertEntry(dbentry); } static Stream<Arguments> allAuthors() { return Stream.of( Arguments.of("ArtemenkoEtAl", "Alexander Artemenko and others"), Arguments.of("AachenEtAl", "Aachen and others"), Arguments.of("AachenBerlinEtAl", "Aachen and Berlin and others"), Arguments.of("AachenBerlinChemnitzEtAl", "Aachen and Berlin and Chemnitz and others"), Arguments.of("AachenBerlinChemnitzDüsseldorf", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("AachenBerlinChemnitzDüsseldorfEtAl", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("AachenBerlinChemnitzDüsseldorfEssen", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("AachenBerlinChemnitzDüsseldorfEssenEtAl", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void allAuthors(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.allAuthors(list)); } static Stream<Arguments> authorsAlpha() { return Stream.of( Arguments.of("A+", "Alexander Artemenko and others"), Arguments.of("A+", "Aachen and others"), Arguments.of("AB+", "Aachen and Berlin and others"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and others"), Arguments.of("ABCD", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void authorsAlpha(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.authorsAlpha(list)); } /** * Tests [authorIni] */ static Stream<Arguments> oneAuthorPlusInitials() { return Stream.of( Arguments.of("Aalst", "Wil van der Aalst"), Arguments.of("AalstL", "Wil van der Aalst and Tammo van Lessen"), Arguments.of("Newto", "I. Newton"), Arguments.of("NewtoM", "I. Newton and J. Maxwell"), Arguments.of("NewtoME", "I. Newton and J. Maxwell and A. Einstein"), Arguments.of("NewtoMEB", "I. Newton and J. Maxwell and A. Einstein and N. Bohr"), Arguments.of("NewtoMEBU", "I. Newton and J. Maxwell and A. Einstein and N. Bohr and Harry Unknown"), Arguments.of("Aache+", "Aachen and others"), Arguments.of("AacheB", "Aachen and Berlin"), Arguments.of("AacheB+", "Aachen and Berlin and others"), Arguments.of("AacheBC", "Aachen and Berlin and Chemnitz"), Arguments.of("AacheBC+", "Aachen and Berlin and Chemnitz and others"), Arguments.of("AacheBCD", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("AacheBCD+", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("AacheBCDE", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("AacheBCDE+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void oneAuthorPlusInitials(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.oneAuthorPlusInitials(list)); } static Stream<Arguments> authShort() { return Stream.of( Arguments.of("Newton", "Isaac Newton"), Arguments.of("NM", "Isaac Newton and James Maxwell"), Arguments.of("NME", "Isaac Newton and James Maxwell and Albert Einstein"), Arguments.of("NME+", "Isaac Newton and James Maxwell and Albert Einstein and N. Bohr"), Arguments.of("Aachen", "Aachen"), Arguments.of("A+", "Aachen and others"), Arguments.of("AB", "Aachen and Berlin"), Arguments.of("AB+", "Aachen and Berlin and others"), Arguments.of("ABC", "Aachen and Berlin and Chemnitz"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and others"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void authIni1(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.authIniN(list, 1)); } static Stream<Arguments> authIni1() { return Stream.of( Arguments.of("N", "Isaac Newton"), Arguments.of("N", "Isaac Newton and James Maxwell"), Arguments.of("N", "Isaac Newton and James Maxwell and Albert Einstein"), Arguments.of("N", "Isaac Newton and James Maxwell and Albert Einstein and N. Bohr"), Arguments.of("A", "Aachen"), Arguments.of("A", "Aachen and others"), Arguments.of("A", "Aachen and Berlin"), Arguments.of("A", "Aachen and Berlin and others"), Arguments.of("A", "Aachen and Berlin and Chemnitz"), Arguments.of("A", "Aachen and Berlin and Chemnitz and others"), Arguments.of("A", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("A", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("A", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("A", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void authIni2(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.authIniN(list, 2)); } static Stream<Arguments> authIni2() { return Stream.of( Arguments.of("Ne", "Isaac Newton"), Arguments.of("NM", "Isaac Newton and James Maxwell"), Arguments.of("N+", "Isaac Newton and James Maxwell and Albert Einstein"), Arguments.of("N+", "Isaac Newton and James Maxwell and Albert Einstein and N. Bohr"), Arguments.of("Aa", "Aachen"), Arguments.of("A+", "Aachen and others"), Arguments.of("AB", "Aachen and Berlin"), Arguments.of("A+", "Aachen and Berlin and others"), Arguments.of("A+", "Aachen and Berlin and Chemnitz"), Arguments.of("D+", "John Doe and Donald Smith and Will Wonder"), Arguments.of("A+", "Aachen and Berlin and Chemnitz and others"), Arguments.of("A+", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("A+", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("A+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("A+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void authIni4(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.authIniN(list, 4)); } static Stream<Arguments> authIni4() { return Stream.of( Arguments.of("Newt", "Isaac Newton"), Arguments.of("NeMa", "Isaac Newton and James Maxwell"), Arguments.of("NeME", "Isaac Newton and James Maxwell and Albert Einstein"), Arguments.of("NMEB", "Isaac Newton and James Maxwell and Albert Einstein and N. Bohr"), Arguments.of("Aach", "Aachen"), Arguments.of("Aac+", "Aachen and others"), Arguments.of("AaBe", "Aachen and Berlin"), Arguments.of("AaB+", "Aachen and Berlin and others"), Arguments.of("AaBC", "Aachen and Berlin and Chemnitz"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and others"), Arguments.of("ABCD", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("ABC+", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void authEtAlDotDotEal(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.authEtal(list, ".", ".etal")); } static Stream<Arguments> authEtAlDotDotEal() { return Stream.of( Arguments.of("Newton", "Isaac Newton"), Arguments.of("Newton.Maxwell", "Isaac Newton and James Maxwell"), Arguments.of("Newton.etal", "Isaac Newton and James Maxwell and Albert Einstein"), Arguments.of("Newton.etal", "Isaac Newton and James Maxwell and Albert Einstein and N. Bohr"), Arguments.of("Aachen", "Aachen"), Arguments.of("Aachen.etal", "Aachen and others"), Arguments.of("Aachen.Berlin", "Aachen and Berlin"), Arguments.of("Aachen.etal", "Aachen and Berlin and others"), Arguments.of("Aachen.etal", "Aachen and Berlin and Chemnitz"), Arguments.of("Aachen.etal", "Aachen and Berlin and Chemnitz and others"), Arguments.of("Aachen.etal", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("Aachen.etal", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("Aachen.etal", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("Aachen.etal", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void authAuthEa(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.authAuthEa(list)); } static Stream<Arguments> authAuthEa() { return Stream.of( Arguments.of("Newton", "Isaac Newton"), Arguments.of("Newton.Maxwell", "Isaac Newton and James Maxwell"), Arguments.of("Newton.Maxwell.ea", "Isaac Newton and James Maxwell and Albert Einstein"), Arguments.of("Newton.Maxwell.ea", "Isaac Newton and James Maxwell and Albert Einstein and N. Bohr"), Arguments.of("Aachen", "Aachen"), Arguments.of("Aachen.ea", "Aachen and others"), Arguments.of("Aachen.Berlin", "Aachen and Berlin"), Arguments.of("Aachen.Berlin.ea", "Aachen and Berlin and others"), Arguments.of("Aachen.Berlin.ea", "Aachen and Berlin and Chemnitz"), Arguments.of("Aachen.Berlin.ea", "Aachen and Berlin and Chemnitz and others"), Arguments.of("Aachen.Berlin.ea", "Aachen and Berlin and Chemnitz and Düsseldorf"), Arguments.of("Aachen.Berlin.ea", "Aachen and Berlin and Chemnitz and Düsseldorf and others"), Arguments.of("Aachen.Berlin.ea", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen"), Arguments.of("Aachen.Berlin.ea", "Aachen and Berlin and Chemnitz and Düsseldorf and Essen and others")); } @ParameterizedTest @MethodSource void authShort(String expected, AuthorList list) { assertEquals(expected, BracketedPattern.authShort(list)); } @ParameterizedTest @CsvSource({ "'Newton', '[auth]', 'Isaac Newton'", "'Newton', '[authFirstFull]', 'Isaac Newton'", "'I', '[authForeIni]', 'Isaac Newton'", "'Newton', '[auth.etal]', 'Isaac Newton'", "'Newton', '[authEtAl]', 'Isaac Newton'", "'Newton', '[auth.auth.ea]', 'Isaac Newton'", "'Newton', '[authors]', 'Isaac Newton'", "'Newton', '[authors2]', 'Isaac Newton'", "'Ne', '[authIni2]', 'Isaac Newton'", "'New', '[auth3]', 'Isaac Newton'", "'New', '[auth3_1]', 'Isaac Newton'", "'Newton', '[authshort]', 'Isaac Newton'", "'New', '[authorsAlpha]', 'Isaac Newton'", "'Newton', '[authorLast]', 'Isaac Newton'", "'I', '[authorLastForeIni]', 'Isaac Newton'", "'Agency', '[authors]', 'European Union Aviation Safety Agency'", "'EUASA', '[authors]', '{European Union Aviation Safety Agency}'" }) void testAuthorFieldMarkers(String expectedCitationKey, String pattern, String author) { BibEntry bibEntry = new BibEntry().withField(StandardField.AUTHOR, author); BracketedPattern bracketedPattern = new BracketedPattern(pattern); assertEquals(expectedCitationKey, bracketedPattern.expand(bibEntry)); } private static Stream<Arguments> expandBracketsWithFallback() { return Stream.of( Arguments.of("auth", "[title:(auth)]"), Arguments.of("auth2021", "[title:(auth[YEAR])]"), Arguments.of("not2021", "[title:(not[YEAR])]"), Arguments.of("", "[title:([YEAR)]"), Arguments.of(")]", "[title:(YEAR])]"), Arguments.of("2105.02891", "[title:([EPRINT:([YEAR])])]"), Arguments.of("2021", "[title:([auth:([YEAR])])]") ); } @ParameterizedTest @MethodSource() void expandBracketsWithFallback(String expandResult, String pattern) { BibEntry bibEntry = new BibEntry() .withField(StandardField.YEAR, "2021").withField(StandardField.EPRINT, "2105.02891"); BracketedPattern bracketedPattern = new BracketedPattern(pattern); assertEquals(expandResult, bracketedPattern.expand(bibEntry)); } @Test void bibentryExpansionTest() { BracketedPattern pattern = new BracketedPattern("[year]_[auth]_[firstpage]"); assertEquals("2017_Kitsune_213", pattern.expand(bibentry)); } @Test void nullDatabaseExpansionTest() { BibDatabase another_database = null; BracketedPattern pattern = new BracketedPattern("[year]_[auth]_[firstpage]"); assertEquals("2017_Kitsune_213", pattern.expand(bibentry, another_database)); } @Test void pureauthReturnsAuthorIfEditorIsAbsent() { BibDatabase emptyDatabase = new BibDatabase(); BracketedPattern pattern = new BracketedPattern("[pureauth]"); assertEquals("Kitsune", pattern.expand(bibentry, emptyDatabase)); } @Test void pureauthReturnsAuthorIfEditorIsPresent() { BibDatabase emptyDatabase = new BibDatabase(); BracketedPattern pattern = new BracketedPattern("[pureauth]"); bibentry.setField(StandardField.EDITOR, "Editorlastname, Editorfirstname"); assertEquals("Kitsune", pattern.expand(bibentry, emptyDatabase)); } @Test void pureauthReturnsEmptyStringIfAuthorIsAbsent() { BibDatabase emptyDatabase = new BibDatabase(); BracketedPattern pattern = new BracketedPattern("[pureauth]"); bibentry.clearField(StandardField.AUTHOR); assertEquals("", pattern.expand(bibentry, emptyDatabase)); } @Test void pureauthReturnsEmptyStringIfAuthorIsAbsentAndEditorIsPresent() { BibDatabase emptyDatabase = new BibDatabase(); BracketedPattern pattern = new BracketedPattern("[pureauth]"); bibentry.clearField(StandardField.AUTHOR); bibentry.setField(StandardField.EDITOR, "Editorlastname, Editorfirstname"); assertEquals("", pattern.expand(bibentry, emptyDatabase)); } @Test void emptyDatabaseExpansionTest() { BibDatabase another_database = new BibDatabase(); BracketedPattern pattern = new BracketedPattern("[year]_[auth]_[firstpage]"); assertEquals("2017_Kitsune_213", pattern.expand(bibentry, another_database)); } @Test void databaseWithStringsExpansionTest() { BibDatabase another_database = new BibDatabase(); BibtexString string = new BibtexString("sgr", "Saulius Gražulis"); another_database.addString(string); bibentry = new BibEntry() .withField(StandardField.AUTHOR, "#sgr#") .withField(StandardField.YEAR, "2017") .withField(StandardField.PAGES, "213--216"); BracketedPattern pattern = new BracketedPattern("[year]_[auth]_[firstpage]"); assertEquals("2017_Gražulis_213", pattern.expand(bibentry, another_database)); } @Test void unbalancedBracketsExpandToSomething() { BracketedPattern pattern = new BracketedPattern("[year]_[auth_[firstpage]"); assertNotEquals("", pattern.expand(bibentry)); } @Test void unbalancedLastBracketExpandsToSomething() { BracketedPattern pattern = new BracketedPattern("[year]_[auth]_[firstpage"); assertNotEquals("", pattern.expand(bibentry)); } @Test void entryTypeExpansionTest() { BracketedPattern pattern = new BracketedPattern("[entrytype]:[year]_[auth]_[pages]"); assertEquals("Misc:2017_Kitsune_213--216", pattern.expand(bibentry)); } @Test void entryTypeExpansionLowercaseTest() { BracketedPattern pattern = new BracketedPattern("[entrytype:lower]:[year]_[auth]_[firstpage]"); assertEquals("misc:2017_Kitsune_213", pattern.expand(bibentry)); } @Test void suppliedBibentryBracketExpansionTest() { BibDatabase another_database = null; BracketedPattern pattern = new BracketedPattern("[year]_[auth]_[firstpage]"); BibEntry another_bibentry = new BibEntry() .withField(StandardField.AUTHOR, "Gražulis, Saulius") .withField(StandardField.YEAR, "2017") .withField(StandardField.PAGES, "213--216"); assertEquals("2017_Gražulis_213", pattern.expand(another_bibentry, ';', another_database)); } @Test void nullBibentryBracketExpansionTest() { BibDatabase another_database = null; BibEntry another_bibentry = null; BracketedPattern pattern = new BracketedPattern("[year]_[auth]_[firstpage]"); assertThrows(NullPointerException.class, () -> pattern.expand(another_bibentry, ';', another_database)); } @Test void bracketedExpressionDefaultConstructorTest() { BibDatabase another_database = null; BracketedPattern pattern = new BracketedPattern(); assertThrows(NullPointerException.class, () -> pattern.expand(bibentry, ';', another_database)); } @Test void unknownKeyExpandsToEmptyString() { assertEquals("", BracketedPattern.expandBrackets("[unknownkey]", ';', dbentry, database)); } @Test void emptyPatternAndEmptyModifierExpandsToEmptyString() { assertEquals("", BracketedPattern.expandBrackets("[:]", ';', dbentry, database)); } @Test void emptyPatternAndValidModifierExpandsToEmptyString() { Character separator = ';'; assertEquals("", BracketedPattern.expandBrackets("[:lower]", separator, dbentry, database)); } @Test void bibtexkeyPatternExpandsToCitationKey() { Character separator = ';'; assertEquals("HipKro03", BracketedPattern.expandBrackets("[bibtexkey]", separator, dbentry, database)); } @Test void citationKeyPatternExpandsToCitationKey() { Character separator = ';'; assertEquals("HipKro03", BracketedPattern.expandBrackets("[citationkey]", separator, dbentry, database)); } @Test void citationKeyPatternWithEmptyModifierExpandsToBibTeXKey() { assertEquals("HipKro03", BracketedPattern.expandBrackets("[citationkey:]", ';', dbentry, database)); } @Test void authorPatternTreatsVonNamePrefixCorrectly() { assertEquals("Eric von Hippel and Georg von Krogh", BracketedPattern.expandBrackets("[author]", ';', dbentry, database)); } @Test void lowerFormatterWorksOnVonNamePrefixes() { assertEquals("eric von hippel and georg von krogh", BracketedPattern.expandBrackets("[author:lower]", ';', dbentry, database)); } @Test void testResolvedFieldAndFormat() { BibEntry child = new BibEntry().withField(StandardField.CROSSREF, "HipKro03"); database.insertEntry(child); Character separator = ';'; assertEquals("Eric von Hippel and Georg von Krogh", BracketedPattern.expandBrackets("[author]", separator, child, database)); assertEquals("", BracketedPattern.expandBrackets("[unknownkey]", separator, child, database)); assertEquals("", BracketedPattern.expandBrackets("[:]", separator, child, database)); assertEquals("", BracketedPattern.expandBrackets("[:lower]", separator, child, database)); assertEquals("eric von hippel and georg von krogh", BracketedPattern.expandBrackets("[author:lower]", separator, child, database)); // the citation key is not inherited assertEquals("", BracketedPattern.expandBrackets("[citationkey]", separator, child, database)); assertEquals("", BracketedPattern.expandBrackets("[citationkey:]", separator, child, database)); } @Test void testResolvedParentNotInDatabase() { BibEntry child = new BibEntry() .withField(StandardField.CROSSREF, "HipKro03"); database.removeEntry(dbentry); database.insertEntry(child); assertEquals("", BracketedPattern.expandBrackets("[author]", ';', child, database)); } @Test void regularExpressionReplace() { assertEquals("2003-JabRef Science", BracketedPattern.expandBrackets("[year]-[journal:regex(\"Organization\",\"JabRef\")]", ';', dbentry, database)); } @Test void regularExpressionWithBrackets() { assertEquals("2003-JabRef Science", BracketedPattern.expandBrackets("[year]-[journal:regex(\"[OX]rganization\",\"JabRef\")]", ';', dbentry, database)); } @Test void testEmptyBrackets() { assertEquals("2003-Organization Science", BracketedPattern.expandBrackets("[year][]-[journal]", ';', dbentry, database)); } /** * Test the [:truncate] modifier */ @Test void expandBracketsChainsTwoTruncateModifiers() { assertEquals("Open", BracketedPattern.expandBrackets("[fulltitle:truncate6:truncate5]", ';', dbentry, database)); } @Test void expandBracketsDoesNotTruncateWithoutAnArgumentToTruncateModifier() { assertEquals("Open Source Software and the \"Private-Collective\" Innovation Model: Issues for Organization Science", BracketedPattern.expandBrackets("[fulltitle:truncate]", ';', dbentry, database)); } @Test void expandBracketsWithAuthorStartingWithBrackets() { // Issue https://github.com/JabRef/jabref/issues/3920 BibEntry bibEntry = new BibEntry() .withField(StandardField.AUTHOR, "Patrik {\\v{S}}pan{\\v{e}}l and Kseniya Dryahina and David Smith"); assertEquals("ŠpanělEtAl", BracketedPattern.expandBrackets("[authEtAl:latex_to_unicode]", null, bibEntry, null)); } @Test void expandBracketsWithModifierContainingRegexCharacterClass() { BibEntry bibEntry = new BibEntry().withField(StandardField.TITLE, "Wickedness:Managing"); assertEquals("Wickedness.Managing", BracketedPattern.expandBrackets("[title:regex(\"[:]+\",\".\")]", null, bibEntry, null)); } @Test void expandBracketsEmptyStringFromEmptyBrackets() { BibEntry bibEntry = new BibEntry(); assertEquals("", BracketedPattern.expandBrackets("[]", null, bibEntry, null)); } @Test void expandBracketsInstitutionAbbreviationFromProvidedAbbreviation() { BibEntry bibEntry = new BibEntry() .withField(StandardField.AUTHOR, "{European Union Aviation Safety Agency ({EUASABRACKET})}"); assertEquals("EUASABRACKET", BracketedPattern.expandBrackets("[auth]", null, bibEntry, null)); } @Test void expandBracketsInstitutionAbbreviationForAuthorContainingUnion() { BibEntry bibEntry = new BibEntry() .withField(StandardField.AUTHOR, "{European Union Aviation Safety Agency}"); assertEquals("EUASA", BracketedPattern.expandBrackets("[auth]", null, bibEntry, null)); } @Test void expandBracketsLastNameForAuthorStartingWithOnlyLastNameStartingWithLowerCase() { BibEntry bibEntry = new BibEntry() .withField(StandardField.AUTHOR, "{eBay}"); assertEquals("eBay", BracketedPattern.expandBrackets("[auth]", null, bibEntry, null)); } @Test void expandBracketsLastNameWithChineseCharacters() { BibEntry bibEntry = new BibEntry() .withField(StandardField.AUTHOR, "杨秀群"); assertEquals("杨秀群", BracketedPattern.expandBrackets("[auth]", null, bibEntry, null)); } @Test void expandBracketsUnmodifiedStringFromLongFirstPageNumber() { BibEntry bibEntry = new BibEntry() .withField(StandardField.PAGES, "2325967120921344"); assertEquals("2325967120921344", BracketedPattern.expandBrackets("[firstpage]", null, bibEntry, null)); } @Test void expandBracketsUnmodifiedStringFromLongLastPageNumber() { BibEntry bibEntry = new BibEntry() .withField(StandardField.PAGES, "2325967120921344"); assertEquals("2325967120921344", BracketedPattern.expandBrackets("[lastpage]", null, bibEntry, null)); } @Test void expandBracketsWithTestCasesFromRegExpBasedFileFinder() { BibEntry entry = new BibEntry(StandardEntryType.Article) .withCitationKey("HipKro03") .withField(StandardField.AUTHOR, "Eric von Hippel and Georg von Krogh") .withField(StandardField.TITLE, "Open Source Software and the \"Private-Collective\" Innovation Model: Issues for Organization Science") .withField(StandardField.JOURNAL, "Organization Science") .withField(StandardField.YEAR, "2003") .withField(StandardField.VOLUME, "14") .withField(StandardField.PAGES, "209--223") .withField(StandardField.NUMBER, "2") .withField(StandardField.ADDRESS, "Institute for Operations Research and the Management Sciences (INFORMS), Linthicum, Maryland, USA") .withField(StandardField.DOI, "http://dx.doi.org/10.1287/orsc.14.2.209.14992") .withField(StandardField.ISSN, "1526-5455") .withField(StandardField.PUBLISHER, "INFORMS"); BibDatabase database = new BibDatabase(); database.insertEntry(entry); assertEquals("", BracketedPattern.expandBrackets("", ',', entry, database)); assertEquals("dropped", BracketedPattern.expandBrackets("drop[unknownkey]ped", ',', entry, database)); assertEquals("Eric von Hippel and Georg von Krogh", BracketedPattern.expandBrackets("[author]", ',', entry, database)); assertEquals("Eric von Hippel and Georg von Krogh are two famous authors.", BracketedPattern.expandBrackets("[author] are two famous authors.", ',', entry, database)); assertEquals("Eric von Hippel and Georg von Krogh are two famous authors.", BracketedPattern.expandBrackets("[author] are two famous authors.", ',', entry, database)); assertEquals( "Eric von Hippel and Georg von Krogh have published Open Source Software and the \"Private-Collective\" Innovation Model: Issues for Organization Science in Organization Science.", BracketedPattern.expandBrackets("[author] have published [fulltitle] in [journal].", ',', entry, database)); assertEquals( "Eric von Hippel and Georg von Krogh have published Open Source Software and the \"Private Collective\" Innovation Model: Issues for Organization Science in Organization Science.", BracketedPattern.expandBrackets("[author] have published [title] in [journal].", ',', entry, database)); } @Test void expandBracketsWithoutProtectiveBracesUsingUnprotectTermsModifier() { BibEntry bibEntry = new BibEntry() .withField(StandardField.JOURNAL, "{ACS} Medicinal Chemistry Letters"); assertEquals("ACS Medicinal Chemistry Letters", BracketedPattern.expandBrackets("[JOURNAL:unprotect_terms]", null, bibEntry, null)); } @ParameterizedTest @CsvSource({ "'Newton', '[edtr]', 'Isaac Newton'", "'I', '[edtrForeIni]', 'Isaac Newton'", "'Newton', '[editors]', 'Isaac Newton'", "'Ne', '[edtrIni2]', 'Isaac Newton'", "'New', '[edtr3]', 'Isaac Newton'", "'Newton', '[edtr7]', 'Isaac Newton'", "'New', '[edtr3_1]', 'Isaac Newton'", "'Newton.Maxwell', '[edtr.edtr.ea]', 'Isaac Newton and James Maxwell'", "'Newton', '[edtrshort]', 'Isaac Newton'", "'Newton', '[editorLast]', 'Isaac Newton'", "'I', '[editorLastForeIni]', 'Isaac Newton'", "'EUASA', '[editors]', '{European Union Aviation Safety Agency}'" }) void testEditorFieldMarkers(String expectedCitationKey, String pattern, String editor) { BibEntry bibEntry = new BibEntry().withField(StandardField.EDITOR, editor); BracketedPattern bracketedPattern = new BracketedPattern(pattern); assertEquals(expectedCitationKey, bracketedPattern.expand(bibEntry)); } }
32,807
46.755459
196
java
null
jabref-main/src/test/java/org/jabref/logic/citationkeypattern/CitationKeyGeneratorTest.java
package org.jabref.logic.citationkeypattern; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.database.BibDatabase; 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.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; import static org.jabref.logic.citationkeypattern.CitationKeyGenerator.DEFAULT_UNWANTED_CHARACTERS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; /** * Tests whole citation key patterns such as <code>[authorsAlpha][year]</code>. * The concrete patterns such as <code>authorsAlpha</code> should better be tested at {@link BracketedPatternTest}. * * Concurrent execution leads to issues on GitHub actions. */ class CitationKeyGeneratorTest { private static final BibEntry AUTHOR_EMPTY = createABibEntryAuthor(""); private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1 = "Isaac Newton"; private static final BibEntry AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1 = createABibEntryAuthor(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1); private static final BibEntry AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2 = createABibEntryAuthor("Isaac Newton and James Maxwell"); private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3 = "Isaac Newton and James Maxwell and Albert Einstein"; private static final BibEntry AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3 = createABibEntryAuthor(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3); private static final String AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_AND_OTHERS_COUNT_3 = "Isaac Newton and James Maxwell and others"; private static final BibEntry AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_AND_OTHERS_COUNT_3 = createABibEntryAuthor(AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_AND_OTHERS_COUNT_3); private static final BibEntry AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1 = createABibEntryAuthor("Wil van der Aalst"); private static final BibEntry AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2 = createABibEntryAuthor("Wil van der Aalst and Tammo van Lessen"); private static final BibEntry AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1 = createABibEntryAuthor("I. Newton"); private static final BibEntry AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2 = createABibEntryAuthor("I. Newton and J. Maxwell"); private static final BibEntry AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3 = createABibEntryAuthor("I. Newton and J. Maxwell and A. Einstein"); private static final BibEntry AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4 = createABibEntryAuthor("I. Newton and J. Maxwell and A. Einstein and N. Bohr"); private static final BibEntry AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5 = createABibEntryAuthor("I. Newton and J. Maxwell and A. Einstein and N. Bohr and Harry Unknown"); private static final String TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH = "application migration effort in the cloud - the case of cloud platforms"; private static final String TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON = "{BPEL} conformance in open source engines: the case of static analysis"; private static final String TITLE_STRING_CASED = "Process Viewing Patterns"; private static final String TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD = "BPMN Conformance in Open Source Engines"; private static final String TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING = "The Difference Between Graph-Based and Block-Structured Business Process Modelling Languages"; private static final String TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON = "Cloud Computing: The Next Revolution in IT"; private static final String TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD = "Towards Choreography-based Process Distribution in the Cloud"; private static final String TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS = "On the Measurement of Design-Time Adaptability for Process-Based Systems "; private static final String AUTHSHORT = "[authshort]"; private static final String AUTHNOFMTH = "[auth%d_%d]"; private static final String AUTHFOREINI = "[authForeIni]"; private static final String AUTHFIRSTFULL = "[authFirstFull]"; private static final String AUTHORS = "[authors]"; private static final String AUTHORSALPHA = "[authorsAlpha]"; private static final String AUTHORLAST = "[authorLast]"; private static final String AUTHORLASTFOREINI = "[authorLastForeIni]"; private static final String AUTHORINI = "[authorIni]"; private static final String AUTHORN = "[authors%d]"; private static final String AUTHETAL = "[authEtAl]"; private static final String AUTH_ETAL = "[auth.etal]"; private static final String AUTHAUTHEA = "[auth.auth.ea]"; private static ImportFormatPreferences importFormatPreferences; @BeforeEach void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } private static BibEntry createABibEntryAuthor(String author) { return new BibEntry().withField(StandardField.AUTHOR, author); } static String generateKey(BibEntry entry, String pattern) { return generateKey(entry, pattern, new BibDatabase()); } static String generateKey(BibEntry entry, String pattern, BibDatabase database) { GlobalCitationKeyPattern keyPattern = GlobalCitationKeyPattern.fromPattern(pattern); CitationKeyPatternPreferences patternPreferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A, "", "", DEFAULT_UNWANTED_CHARACTERS, keyPattern, "", ','); return new CitationKeyGenerator(keyPattern, database, patternPreferences).generateKey(entry); } @Test void testAndInAuthorName() throws ParseException { Optional<BibEntry> entry0 = BibtexParser.singleFromString("@ARTICLE{kohn, author={Simon Holland}}", importFormatPreferences); assertEquals("Holland", CitationKeyGenerator.cleanKey(generateKey(entry0.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testCrossrefAndInAuthorNames() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry().withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.AUTHOR, "Simon Holland"); database.insertEntry(entry1); database.insertEntry(entry2); assertEquals("Holland", CitationKeyGenerator.cleanKey(generateKey(entry1, "[auth]", database), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testAndAuthorNames() throws ParseException { String bibtexString = "@ARTICLE{whatevery, author={Mari D. Herland and Mona-Iren Hauge and Ingeborg M. Helgeland}}"; Optional<BibEntry> entry = BibtexParser.singleFromString(bibtexString, importFormatPreferences); assertEquals("HerlandHaugeHelgeland", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[authors3]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testCrossrefAndAuthorNames() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.AUTHOR, "Mari D. Herland and Mona-Iren Hauge and Ingeborg M. Helgeland"); database.insertEntry(entry1); database.insertEntry(entry2); assertEquals("HerlandHaugeHelgeland", CitationKeyGenerator.cleanKey(generateKey(entry1, "[authors3]", database), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testSpecialLatexCharacterInAuthorName() throws ParseException { Optional<BibEntry> entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={Simon Popovi\\v{c}ov\\'{a}}}", importFormatPreferences); assertEquals("Popovicova", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @ParameterizedTest(name = "bibtexString={0}, expectedResult={1}") @CsvSource(quoteCharacter = '"', textBlock = """ # see https://sourceforge.net/forum/message.php?msg_id=4498555 "@ARTICLE{kohn, author={Andreas Köning}, year={2000}}", "Koe", # Accent ague: Á á Ć ć É é Í í Ĺ ĺ Ń ń Ó ó Ŕ ŕ Ś ś Ú ú Ý ý Ź ź "@ARTICLE{kohn, author={Andreas Áöning}, year={2000}}", "Aoe", "@ARTICLE{kohn, author={Andreas Éöning}, year={2000}}", "Eoe", "@ARTICLE{kohn, author={Andreas Íöning}, year={2000}}", "Ioe", "@ARTICLE{kohn, author={Andreas Ĺöning}, year={2000}}", "Loe", "@ARTICLE{kohn, author={Andreas Ńöning}, year={2000}}", "Noe", "@ARTICLE{kohn, author={Andreas Óöning}, year={2000}}", "Ooe", "@ARTICLE{kohn, author={Andreas Ŕöning}, year={2000}}", "Roe", "@ARTICLE{kohn, author={Andreas Śöning}, year={2000}}", "Soe", "@ARTICLE{kohn, author={Andreas Úöning}, year={2000}}", "Uoe", "@ARTICLE{kohn, author={Andreas Ýöning}, year={2000}}", "Yoe", "@ARTICLE{kohn, author={Andreas Źöning}, year={2000}}", "Zoe", # Accent grave: À È Ì Ò Ù "@ARTICLE{kohn, author={Andreas Àöning}, year={2000}}", "Aoe", "@ARTICLE{kohn, author={Andreas Èöning}, year={2000}}", "Eoe", "@ARTICLE{kohn, author={Andreas Ìöning}, year={2000}}", "Ioe", "@ARTICLE{kohn, author={Andreas Òöning}, year={2000}}", "Ooe", "@ARTICLE{kohn, author={Andreas Ùöning}, year={2000}}", "Uoe", # Special cases "@ARTICLE{kohn, author={Oraib Al-Ketan}, year={2000}}", "AlK", "@ARTICLE{kohn, author={Andrés D'Alessandro}, year={2000}}", "DAl", "@ARTICLE{kohn, author={Andrés Aʹrnold}, year={2000}}", "Arn" """ ) void testMakeLabelAndCheckLegalKeys(String bibtexString, String expectedResult) throws ParseException { Optional<BibEntry> bibEntry = BibtexParser.singleFromString(bibtexString, importFormatPreferences); String citationKey = generateKey(bibEntry.orElse(null), "[auth3]", new BibDatabase()); String cleanedKey = CitationKeyGenerator.cleanKey(citationKey, DEFAULT_UNWANTED_CHARACTERS); assertEquals(expectedResult, cleanedKey); } @Test void testFirstAuthor() { assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, "[auth]")); assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, "[auth]")); // https://sourceforge.net/forum/message.php?msg_id=4498555 assertEquals("Koening", generateKey(createABibEntryAuthor("K{\\\"o}ning"), "[auth]")); assertEquals("", generateKey(createABibEntryAuthor(""), "[auth]")); } @Test void testUniversity() throws ParseException { Optional<BibEntry> entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Link{\\\"{o}}ping University}}}", importFormatPreferences); assertEquals("UniLinkoeping", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } /** * Tests if cleanKey replaces Non-ASCII chars. There are quite a few chars that should be replaced. Perhaps there is * a better method than the current. * <p> * not tested/ not in hashmap UNICODE_CHARS: * {@code * Ł ł Ő ő Ű ű Ŀ ŀ Ħ ħ Ð ð Þ þ Œ œ Æ æ Ø ø Å å Ə ə Đ đ Ů ů Ǣ ǣ ǖ ǘ ǚ ǜ * Ǣ ǣ ǖ ǘ ǚ ǜ * Đ đ Ů ů * Ł ł Ő ő Ű ű Ŀ ŀ Ħ ħ Ð ð Þ þ Œ œ Æ æ Ø ø Å å Ə ə * } * * @see CitationKeyGenerator#cleanKey(String, String) */ @ParameterizedTest(name = "accents={0}, expectedResult={1}") @CsvSource(quoteCharacter = '"', textBlock = """ "ÀàÈèÌìÒòÙù  â Ĉ ĉ Ê ê Ĝ ĝ Ĥ ĥ Î î Ĵ ĵ Ô ô Ŝ ŝ Û û Ŵ ŵ Ŷ ŷ", "AaEeIiOoUuAaCcEeGgHhIiJjOoSsUuWwYy", "ÄäËëÏïÖöÜüŸÿ", "AeaeEeIiOeoeUeueYy", "ÅåŮů", "AaaaUu", "Ç ç Ģ ģ Ķ ķ Ļ ļ Ņ ņ Ŗ ŗ Ş ş Ţ ţ", "CcGgKkLlNnRrSsTt", "Ă ă Ĕ ĕ Ğ ğ Ĭ ĭ Ŏ ŏ Ŭ ŭ", "AaEeGgIiOoUu", "Ċ ċ Ė ė Ġ ġ İ ı Ż ż", "CcEeGgIiZz", "Ą ą Ę ę Į į Ǫ ǫ Ų ų", "AaEeIiOoUu", # O or Q? o or q? "Ā ā Ē ē Ī ī Ō ō Ū ū Ȳ ȳ", "AaEeIiOoUuYy", "Ǎ ǎ Č č Ď ď Ě ě Ǐ ǐ Ľ ľ Ň ň Ǒ ǒ Ř ř Š š Ť ť Ǔ ǔ Ž ž", "AaCcDdEeIiLlNnOoRrSsTtUuZz", "ÃãẼẽĨĩÑñÕõŨũỸỹ", "AaEeIiNnOoUuYy", "Ḍ ḍ Ḥ ḥ Ḷ ḷ Ḹ ḹ Ṃ ṃ Ṇ ṇ Ṛ ṛ Ṝ ṝ Ṣ ṣ Ṭ ṭ", "DdHhLlLlMmNnRrRrSsTt", "À à È è Ì ì Ò ò Ù ù  â Ĉ ĉ Ê ê Ĝ ĝ Ĥ ĥ Î î Ĵ ĵ Ô ô Ŝ ŝ Û û Ŵ ŵ Ŷ ŷ Ä ä Ë ë Ï ï Ö ö Ü ü Ÿ ÿ ", "AaEeIiOoUuAaCcEeGgHhIiJjOoSsUuWwYyAeaeEeIiOeoeUeueYy", "à ã Ẽ ẽ Ĩ ĩ Ñ ñ Õ õ Ũ ũ Ỹ ỹ Ç ç Ģ ģ Ķ ķ Ļ ļ Ņ ņ Ŗ ŗ Ş ş Ţ ţ", "AaEeIiNnOoUuYyCcGgKkLlNnRrSsTt", " Ǎ ǎ Č č Ď ď Ě ě Ǐ ǐ Ľ ľ Ň ň Ǒ ǒ Ř ř Š š Ť ť Ǔ ǔ Ž ž ", "AaCcDdEeIiLlNnOoRrSsTtUuZz", "Ā ā Ē ē Ī ī Ō ō Ū ū Ȳ ȳ", "AaEeIiOoUuYy", "Ă ă Ĕ ĕ Ğ ğ Ĭ ĭ Ŏ ŏ Ŭ ŭ ", "AaEeGgIiOoUu", "Ả ả Ẻ ẻ Ỉ ỉ Ỏ ỏ Ủ ủ Ỷ ỷ", "AaEeIiOoUuYy", "Ḛ ḛ Ḭ ḭ Ṵ ṵ", "EeIiUu", "Ċ ċ Ė ė Ġ ġ İ ı Ż ż Ą ą Ę ę Į į Ǫ ǫ Ų ų ", "CcEeGgIiZzAaEeIiOoUu", "Ḍ ḍ Ḥ ḥ Ḷ ḷ Ḹ ḹ Ṃ ṃ Ṇ ṇ Ṛ ṛ Ṝ ṝ Ṣ ṣ Ṭ ṭ ", "DdHhLlLlMmNnRrRrSsTt" """ ) void testCheckLegalKey(String accents, String expectedResult) { assertEquals(expectedResult, CitationKeyGenerator.cleanKey(accents, DEFAULT_UNWANTED_CHARACTERS)); } @Test void testcrossrefUniversity() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.AUTHOR, "{Link{\\\"{o}}ping University}"); database.insertEntry(entry1); database.insertEntry(entry2); assertEquals("UniLinkoeping", CitationKeyGenerator.cleanKey(generateKey(entry1, "[auth]", database), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testDepartment() throws ParseException { Optional<BibEntry> entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Link{\\\"{o}}ping University, Department of Electrical Engineering}}}", importFormatPreferences); assertEquals("UniLinkoepingEE", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testcrossrefDepartment() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.AUTHOR, "{Link{\\\"{o}}ping University, Department of Electrical Engineering}"); database.insertEntry(entry1); database.insertEntry(entry2); assertEquals("UniLinkoepingEE", CitationKeyGenerator.cleanKey(generateKey(entry1, "[auth]", database), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testSchool() throws ParseException { Optional<BibEntry> entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Link{\\\"{o}}ping University, School of Computer Engineering}}}", importFormatPreferences); assertEquals("UniLinkoepingCE", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @Test void generateKeyAbbreviateCorporateAuthorDepartmentWithoutAcademicInstitute() throws ParseException { Optional<BibEntry> entry = BibtexParser.singleFromString( "@ARTICLE{null, author={{Department of Localhost NullGenerators}}}", importFormatPreferences); assertEquals("DLN", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @Test void generateKeyAbbreviateCorporateAuthorSchoolWithoutAcademicInstitute() throws ParseException { Optional<BibEntry> entry = BibtexParser.singleFromString( "@ARTICLE{null, author={{The School of Null}}}", importFormatPreferences); assertEquals("SchoolNull", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testcrossrefSchool() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.AUTHOR, "{Link{\\\"{o}}ping University, School of Computer Engineering}"); database.insertEntry(entry1); database.insertEntry(entry2); assertEquals("UniLinkoepingCE", CitationKeyGenerator.cleanKey(generateKey(entry1, "[auth]", database), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testInstituteOfTechnology() throws ParseException { Optional<BibEntry> entry = BibtexParser.singleFromString( "@ARTICLE{kohn, author={{Massachusetts Institute of Technology}}}", importFormatPreferences); assertEquals("MIT", CitationKeyGenerator.cleanKey(generateKey(entry.orElse(null), "[auth]", new BibDatabase()), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testcrossrefInstituteOfTechnology() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.AUTHOR, "{Massachusetts Institute of Technology}"); database.insertEntry(entry1); database.insertEntry(entry2); assertEquals("MIT", CitationKeyGenerator.cleanKey(generateKey(entry1, "[auth]", database), DEFAULT_UNWANTED_CHARACTERS)); } @Test void testAuthIniN() { assertEquals("", generateKey(AUTHOR_EMPTY, "[authIni4]")); assertEquals("Newt", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, "[authIni4]")); assertEquals("NeMa", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, "[authIni4]")); assertEquals("NeME", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, "[authIni4]")); assertEquals("NMEB", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, "[authIni4]")); assertEquals("NME+", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, "[authIni4]")); assertEquals("N", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, "[authIni1]")); assertEquals("", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, "[authIni0]")); assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, "[authIni6]")); assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, "[authIni7]")); } @Test void testAuthIniNEmptyReturnsEmpty() { assertEquals("", generateKey(AUTHOR_EMPTY, "[authIni1]")); } /** * Tests [auth.auth.ea] */ @Test void authAuthEa() { assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1, AUTHAUTHEA)); assertEquals("Newton.Maxwell", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2, AUTHAUTHEA)); assertEquals("Newton.Maxwell.ea", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3, AUTHAUTHEA)); } @Test void testAuthEaEmptyReturnsEmpty() { assertEquals("", generateKey(AUTHOR_EMPTY, AUTHAUTHEA)); } /** * Tests the [auth.etal] and [authEtAl] patterns */ @Test void testAuthEtAl() { // tests taken from the comments // [auth.etal] assertEquals("Newton.etal", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3, AUTH_ETAL)); assertEquals("Newton.Maxwell", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2, AUTH_ETAL)); // [authEtAl] assertEquals("NewtonEtAl", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3, AUTHETAL)); assertEquals("NewtonMaxwell", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2, AUTHETAL)); } /** * Test the [authshort] pattern */ @Test void testAuthShort() { // tests taken from the comments assertEquals("NME+", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, AUTHSHORT)); assertEquals("NME", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, AUTHSHORT)); assertEquals("NM", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, AUTHSHORT)); assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, AUTHSHORT)); } @Test void testAuthShortEmptyReturnsEmpty() { assertEquals("", generateKey(AUTHOR_EMPTY, AUTHSHORT)); } /** * Test the [authN_M] pattern */ @Test void authNM() { assertEquals("N", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, String.format(AUTHNOFMTH, 1, 1))); assertEquals("Max", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, String.format(AUTHNOFMTH, 3, 2))); assertEquals("New", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, String.format(AUTHNOFMTH, 3, 1))); assertEquals("Bo", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, String.format(AUTHNOFMTH, 2, 4))); assertEquals("Bohr", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, String.format(AUTHNOFMTH, 6, 4))); assertEquals("Aal", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1, String.format(AUTHNOFMTH, 3, 1))); assertEquals("Less", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2, String.format(AUTHNOFMTH, 4, 2))); assertEquals("", generateKey(AUTHOR_EMPTY, String.format(AUTHNOFMTH, 2, 4))); } /** * Tests [authForeIni] */ @Test void firstAuthorForenameInitials() { assertEquals("I", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, AUTHFOREINI)); assertEquals("I", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, AUTHFOREINI)); assertEquals("I", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1, AUTHFOREINI)); assertEquals("I", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2, AUTHFOREINI)); } /** * Tests [authFirstFull] */ @Test void firstAuthorVonAndLast() { assertEquals("vanderAalst", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1, AUTHFIRSTFULL)); assertEquals("vanderAalst", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2, AUTHFIRSTFULL)); } @Test void firstAuthorVonAndLastNoVonInName() { assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1, AUTHFIRSTFULL)); assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_2, AUTHFIRSTFULL)); } /** * Tests [authors] */ @Test void testAllAuthors() { assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, AUTHORS)); assertEquals("NewtonMaxwell", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, AUTHORS)); assertEquals("NewtonMaxwellEinstein", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, AUTHORS)); } static Stream<Arguments> testAuthorsAlpha() { return Stream.of( Arguments.of("New", AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, AUTHORSALPHA), Arguments.of("NM", AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, AUTHORSALPHA), Arguments.of("NME", AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, AUTHORSALPHA), Arguments.of("NMEB", AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, AUTHORSALPHA), Arguments.of("NME+", AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, AUTHORSALPHA), Arguments.of("vdAal", AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1, AUTHORSALPHA), Arguments.of("vdAvL", AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2, AUTHORSALPHA), Arguments.of("NM+", AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_AND_OTHERS_COUNT_3, AUTHORSALPHA) ); } @ParameterizedTest @MethodSource void testAuthorsAlpha(String expected, BibEntry entry, String pattern) { assertEquals(expected, generateKey(entry, pattern)); } /** * Tests [authorLast] */ @Test void lastAuthor() { assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, AUTHORLAST)); assertEquals("Maxwell", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, AUTHORLAST)); assertEquals("Einstein", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, AUTHORLAST)); assertEquals("Bohr", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, AUTHORLAST)); assertEquals("Unknown", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, AUTHORLAST)); assertEquals("Aalst", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1, AUTHORLAST)); assertEquals("Lessen", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2, AUTHORLAST)); } /** * Tests [authorLastForeIni] */ @Test void lastAuthorForenameInitials() { assertEquals("I", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, AUTHORLASTFOREINI)); assertEquals("J", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, AUTHORLASTFOREINI)); assertEquals("A", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, AUTHORLASTFOREINI)); assertEquals("N", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, AUTHORLASTFOREINI)); assertEquals("H", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, AUTHORLASTFOREINI)); assertEquals("W", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1, AUTHORLASTFOREINI)); assertEquals("T", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2, AUTHORLASTFOREINI)); } /** * Tests [authorIni] */ @Test void oneAuthorPlusIni() { assertEquals("Newto", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, AUTHORINI)); assertEquals("NewtoM", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, AUTHORINI)); assertEquals("NewtoME", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, AUTHORINI)); assertEquals("NewtoMEB", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, AUTHORINI)); assertEquals("NewtoMEBU", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_5, AUTHORINI)); assertEquals("Aalst", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_1, AUTHORINI)); assertEquals("AalstL", generateKey(AUTHOR_FIRSTNAME_FULL_LASTNAME_FULL_WITH_VAN_COUNT_2, AUTHORINI)); } /** * Tests the [authorsN] pattern. -> [authors1] */ @Test void testNAuthors1() { assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, String.format(AUTHORN, 1))); assertEquals("NewtonEtAl", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, String.format(AUTHORN, 1))); assertEquals("NewtonEtAl", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, String.format(AUTHORN, 1))); assertEquals("NewtonEtAl", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, String.format(AUTHORN, 1))); } @Test void testNAuthors1EmptyReturnEmpty() { assertEquals("", generateKey(AUTHOR_EMPTY, String.format(AUTHORN, 1))); } /** * Tests the [authorsN] pattern. -> [authors3] */ @Test void testNAuthors3() { assertEquals("Newton", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_1, String.format(AUTHORN, 3))); assertEquals("NewtonMaxwell", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_2, String.format(AUTHORN, 3))); assertEquals("NewtonMaxwellEinstein", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_3, String.format(AUTHORN, 3))); assertEquals("NewtonMaxwellEinsteinEtAl", generateKey(AUTHOR_FIRSTNAME_INITIAL_LASTNAME_FULL_COUNT_4, String.format(AUTHORN, 3))); } @Test void testFirstPage() { assertEquals("7", CitationKeyGenerator.firstPage("7--27")); assertEquals("27", CitationKeyGenerator.firstPage("--27")); assertEquals("", CitationKeyGenerator.firstPage("")); assertEquals("42", CitationKeyGenerator.firstPage("42--111")); assertEquals("7", CitationKeyGenerator.firstPage("7,41,73--97")); assertEquals("7", CitationKeyGenerator.firstPage("41,7,73--97")); assertEquals("43", CitationKeyGenerator.firstPage("43+")); } @SuppressWarnings("ConstantConditions") @Test void testFirstPageNull() { assertThrows(NullPointerException.class, () -> CitationKeyGenerator.firstPage(null)); } @Test void testPagePrefix() { assertEquals("L", CitationKeyGenerator.pagePrefix("L7--27")); assertEquals("L--", CitationKeyGenerator.pagePrefix("L--27")); assertEquals("L", CitationKeyGenerator.pagePrefix("L")); assertEquals("L", CitationKeyGenerator.pagePrefix("L42--111")); assertEquals("L", CitationKeyGenerator.pagePrefix("L7,L41,L73--97")); assertEquals("L", CitationKeyGenerator.pagePrefix("L41,L7,L73--97")); assertEquals("L", CitationKeyGenerator.pagePrefix("L43+")); assertEquals("", CitationKeyGenerator.pagePrefix("7--27")); assertEquals("--", CitationKeyGenerator.pagePrefix("--27")); assertEquals("", CitationKeyGenerator.pagePrefix("")); assertEquals("", CitationKeyGenerator.pagePrefix("42--111")); assertEquals("", CitationKeyGenerator.pagePrefix("7,41,73--97")); assertEquals("", CitationKeyGenerator.pagePrefix("41,7,73--97")); assertEquals("", CitationKeyGenerator.pagePrefix("43+")); } @SuppressWarnings("ConstantConditions") @Test void testPagePrefixNull() { assertThrows(NullPointerException.class, () -> CitationKeyGenerator.pagePrefix(null)); } @Test void testLastPage() { assertEquals("27", CitationKeyGenerator.lastPage("7--27")); assertEquals("27", CitationKeyGenerator.lastPage("--27")); assertEquals("", CitationKeyGenerator.lastPage("")); assertEquals("111", CitationKeyGenerator.lastPage("42--111")); assertEquals("97", CitationKeyGenerator.lastPage("7,41,73--97")); assertEquals("97", CitationKeyGenerator.lastPage("7,41,97--73")); assertEquals("43", CitationKeyGenerator.lastPage("43+")); assertEquals("0", CitationKeyGenerator.lastPage("00--0")); assertEquals("1", CitationKeyGenerator.lastPage("1--1")); } @SuppressWarnings("ConstantConditions") @Test void testLastPageNull() { assertThrows(NullPointerException.class, () -> CitationKeyGenerator.lastPage(null)); } /** * Tests [veryShortTitle] */ @Test void veryShortTitle() { // veryShortTitle is getTitleWords with "1" as count int count = 1; assertEquals("application", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH))); assertEquals("BPEL", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords( TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON))); assertEquals("Process", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED))); assertEquals("BPMN", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD))); assertEquals("Difference", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING))); assertEquals("Cloud", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator .removeSmallWords(TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON))); assertEquals("Towards", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD))); assertEquals("Measurement", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator .removeSmallWords(TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS))); } /** * Tests [shortTitle] */ @Test void shortTitle() { // shortTitle is getTitleWords with "3" as count and removed small words int count = 3; assertEquals("application migration effort", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH))); assertEquals("BPEL conformance open", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON))); assertEquals("Process Viewing Patterns", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED))); assertEquals("BPMN Conformance Open", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD))); assertEquals("Difference Graph Based", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING))); assertEquals("Cloud Computing: Next", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON))); assertEquals("Towards Choreography based", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD))); assertEquals("Measurement Design Time", CitationKeyGenerator.getTitleWords(count, CitationKeyGenerator.removeSmallWords(TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS))); } /** * Tests [camel] */ @Test void camel() { // camel capitalises and concatenates all the words of the title assertEquals("ApplicationMigrationEffortInTheCloudTheCaseOfCloudPlatforms", CitationKeyGenerator.getCamelizedTitle(TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH)); assertEquals("BPELConformanceInOpenSourceEnginesTheCaseOfStaticAnalysis", CitationKeyGenerator.getCamelizedTitle( TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON)); assertEquals("ProcessViewingPatterns", CitationKeyGenerator.getCamelizedTitle(TITLE_STRING_CASED)); assertEquals("BPMNConformanceInOpenSourceEngines", CitationKeyGenerator.getCamelizedTitle(TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD)); assertEquals("TheDifferenceBetweenGraphBasedAndBlockStructuredBusinessProcessModellingLanguages", CitationKeyGenerator.getCamelizedTitle( TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING)); assertEquals("CloudComputingTheNextRevolutionInIT", CitationKeyGenerator.getCamelizedTitle(TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON)); assertEquals("TowardsChoreographyBasedProcessDistributionInTheCloud", CitationKeyGenerator.getCamelizedTitle(TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD)); assertEquals("OnTheMeasurementOfDesignTimeAdaptabilityForProcessBasedSystems", CitationKeyGenerator.getCamelizedTitle(TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS)); } /** * Tests [title] */ @Test void title() { // title capitalises the significant words of the title // for the title case the concatenation happens at formatting, which is tested in MakeLabelWithDatabaseTest.java assertEquals("Application Migration Effort in the Cloud the Case of Cloud Platforms", CitationKeyGenerator .camelizeSignificantWordsInTitle(TITLE_STRING_ALL_LOWER_FOUR_SMALL_WORDS_ONE_EN_DASH)); assertEquals("BPEL Conformance in Open Source Engines: the Case of Static Analysis", CitationKeyGenerator.camelizeSignificantWordsInTitle( TITLE_STRING_ALL_LOWER_FIRST_WORD_IN_BRACKETS_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON)); assertEquals("Process Viewing Patterns", CitationKeyGenerator.camelizeSignificantWordsInTitle(TITLE_STRING_CASED)); assertEquals("BPMN Conformance in Open Source Engines", CitationKeyGenerator .camelizeSignificantWordsInTitle(TITLE_STRING_CASED_ONE_UPPER_WORD_ONE_SMALL_WORD)); assertEquals("The Difference between Graph Based and Block Structured Business Process Modelling Languages", CitationKeyGenerator.camelizeSignificantWordsInTitle( TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AT_THE_BEGINNING)); assertEquals("Cloud Computing: the Next Revolution in IT", CitationKeyGenerator.camelizeSignificantWordsInTitle( TITLE_STRING_CASED_TWO_SMALL_WORDS_SMALL_WORD_AFTER_COLON)); assertEquals("Towards Choreography Based Process Distribution in the Cloud", CitationKeyGenerator .camelizeSignificantWordsInTitle(TITLE_STRING_CASED_TWO_SMALL_WORDS_ONE_CONNECTED_WORD)); assertEquals("On the Measurement of Design Time Adaptability for Process Based Systems", CitationKeyGenerator.camelizeSignificantWordsInTitle( TITLE_STRING_CASED_FOUR_SMALL_WORDS_TWO_CONNECTED_WORDS)); } @Test void keywordNKeywordsSeparatedBySpace() { BibEntry entry = new BibEntry().withField(StandardField.KEYWORDS, "w1, w2a w2b, w3"); assertEquals("w1", generateKey(entry, "[keyword1]")); // check keywords with space assertEquals("w2aw2b", generateKey(entry, "[keyword2]")); // check out of range assertEquals("", generateKey(entry, "[keyword4]")); } @Test void crossrefkeywordNKeywordsSeparatedBySpace() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2"); database.insertEntry(entry2); database.insertEntry(entry1); entry2.setField(StandardField.KEYWORDS, "w1, w2a w2b, w3"); assertEquals("w1", generateKey(entry1, "[keyword1]", database)); } @Test void keywordsNKeywordsSeparatedBySpace() { BibEntry entry = new BibEntry().withField(StandardField.KEYWORDS, "w1, w2a w2b, w3"); // all keywords assertEquals("w1w2aw2bw3", generateKey(entry, "[keywords]")); // check keywords with space assertEquals("w1w2aw2b", generateKey(entry, "[keywords2]")); // check out of range assertEquals("w1w2aw2bw3", generateKey(entry, "[keywords55]")); } @Test void crossrefkeywordsNKeywordsSeparatedBySpace() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.KEYWORDS, "w1, w2a w2b, w3"); database.insertEntry(entry2); database.insertEntry(entry1); assertEquals("w1w2aw2bw3", generateKey(entry1, "[keywords]", database)); } @Test void testCheckLegalKeyUnwantedCharacters() { assertEquals("AAAA", CitationKeyGenerator.cleanKey("AA AA", DEFAULT_UNWANTED_CHARACTERS)); assertEquals("SPECIALCHARS", CitationKeyGenerator.cleanKey("SPECIAL CHARS#{\\\"}~,", DEFAULT_UNWANTED_CHARACTERS)); assertEquals("", CitationKeyGenerator.cleanKey("\n\t\r", DEFAULT_UNWANTED_CHARACTERS)); } @Test void testCheckLegalKeyNoUnwantedCharacters() { assertEquals("AAAA", CitationKeyGenerator.cleanKey("AA AA", "")); assertEquals("SPECIALCHARS^", CitationKeyGenerator.cleanKey("SPECIAL CHARS#{\\\"}~,^", "")); assertEquals("", CitationKeyGenerator.cleanKey("\n\t\r", "")); } @Test void testCheckLegalNullInNullOut() { assertThrows(NullPointerException.class, () -> CitationKeyGenerator.cleanKey(null, DEFAULT_UNWANTED_CHARACTERS)); assertThrows(NullPointerException.class, () -> CitationKeyGenerator.cleanKey(null, DEFAULT_UNWANTED_CHARACTERS)); } @Test void testApplyModifiers() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "Green Scheduling of Whatever"); assertEquals("GSo", generateKey(entry, "[shorttitleINI]")); assertEquals("GreenSchedulingWhatever", generateKey(entry, "[shorttitle]", new BibDatabase())); } @Test void testcrossrefShorttitle() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.TITLE, "Green Scheduling of Whatever"); database.insertEntry(entry2); database.insertEntry(entry1); assertEquals("GreenSchedulingWhatever", generateKey(entry1, "[shorttitle]", database)); } @Test void testcrossrefShorttitleInitials() { BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry() .withField(StandardField.CROSSREF, "entry2"); BibEntry entry2 = new BibEntry() .withCitationKey("entry2") .withField(StandardField.TITLE, "Green Scheduling of Whatever"); database.insertEntry(entry2); database.insertEntry(entry1); assertEquals("GSo", generateKey(entry1, "[shorttitleINI]", database)); } @Test void generateKeyStripsColonFromTitle() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "Green Scheduling of: Whatever"); assertEquals("GreenSchedulingOfWhatever", generateKey(entry, "[title]")); } @Test void generateKeyStripsApostropheFromTitle() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "Green Scheduling of `Whatever`"); assertEquals("GreenSchedulingofWhatever", generateKey(entry, "[title]")); } @Test void generateKeyWithOneModifier() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "The Interesting Title"); assertEquals("theinterestingtitle", generateKey(entry, "[title:lower]")); } @Test void generateKeyWithTwoModifiers() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "The Interesting Title"); assertEquals("theinterestingtitle", generateKey(entry, "[title:lower:(_)]")); } @Test void generateKeyWithTitleCapitalizeModifier() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "the InTeresting title longer than THREE words"); assertEquals("TheInterestingTitleLongerThanThreeWords", generateKey(entry, "[title:capitalize]")); } @Test void generateKeyWithShortTitleCapitalizeModifier() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "the InTeresting title longer than THREE words"); assertEquals("InterestingTitleLonger", generateKey(entry, "[shorttitle:capitalize]")); } @Test void generateKeyWithTitleTitleCaseModifier() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "A title WITH some of The key words"); assertEquals("ATitlewithSomeoftheKeyWords", generateKey(entry, "[title:titlecase]")); } @Test void generateKeyWithShortTitleTitleCaseModifier() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "the InTeresting title longer than THREE words"); assertEquals("InterestingTitleLonger", generateKey(entry, "[shorttitle:titlecase]")); } @Test void generateKeyWithTitleSentenceCaseModifier() { BibEntry entry = new BibEntry().withField(StandardField.TITLE, "A title WITH some of The key words"); assertEquals("Atitlewithsomeofthekeywords", generateKey(entry, "[title:sentencecase]")); } @Test void generateKeyWithAuthUpperYearShortTitleCapitalizeModifier() { BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1) .withField(StandardField.YEAR, "2019") .withField(StandardField.TITLE, "the InTeresting title longer than THREE words"); assertEquals("NEWTON2019InterestingTitleLonger", generateKey(entry, "[auth:upper][year][shorttitle:capitalize]")); } @Test void generateKeyWithYearAuthUpperTitleSentenceCaseModifier() { BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_3) .withField(StandardField.YEAR, "2019") .withField(StandardField.TITLE, "the InTeresting title longer than THREE words"); assertEquals("NewtonMaxwellEtAl_2019_TheInterestingTitleLongerThanThreeWords", generateKey(entry, "[authors2]_[year]_[title:capitalize]")); } @Test void generateKeyWithMinusInCitationStyleOutsideAField() { BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, AUTHOR_STRING_FIRSTNAME_FULL_LASTNAME_FULL_COUNT_1) .withField(StandardField.YEAR, "2019"); assertEquals("Newton2019", generateKey(entry, "[auth]-[year]")); } @Test void generateKeyWithWithFirstNCharacters() { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Newton, Isaac") .withField(StandardField.YEAR, "2019"); assertEquals("newt2019", generateKey(entry, "[auth4:lower]-[year]")); } @Test void generateKeyCorrectKeyLengthWithTruncateModifierAndUnicode() { BibEntry bibEntry = new BibEntry().withField(StandardField.AUTHOR, "Gödel, Kurt"); assertEquals(2, generateKey(bibEntry, "[auth:truncate2]").length()); } @Test void generateKeyCorrectKeyLengthWithAuthNofMthAndUnicode() { BibEntry bibEntry = new BibEntry().withField(StandardField.AUTHOR, "Gödel, Kurt"); assertEquals(4, generateKey(bibEntry, "[auth4_1]").length()); } @Test void generateKeyWithNonNormalizedUnicode() { BibEntry bibEntry = new BibEntry().withField(StandardField.TITLE, "Modèle et outil pour soutenir la scénarisation pédagogique de MOOC connectivistes"); assertEquals("Modele", generateKey(bibEntry, "[veryshorttitle]")); } @Test void generateKeyWithModifierContainingRegexCharacterClass() { BibEntry bibEntry = new BibEntry().withField(StandardField.TITLE, "Wickedness Managing"); assertEquals("WM", generateKey(bibEntry, "[title:regex(\"[a-z]+\",\"\")]")); } @Test void generateKeyDoesNotModifyTheKeyWithIncorrectRegexReplacement() { String pattern = "[title]"; GlobalCitationKeyPattern keyPattern = GlobalCitationKeyPattern.fromPattern(pattern); CitationKeyPatternPreferences patternPreferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A, "[", // Invalid regexp "", DEFAULT_UNWANTED_CHARACTERS, keyPattern, "", ','); BibEntry bibEntry = new BibEntry().withField(StandardField.TITLE, "Wickedness Managing"); assertEquals("WickednessManaging", new CitationKeyGenerator(keyPattern, new BibDatabase(), patternPreferences).generateKey(bibEntry)); } @Test void generateKeyWithFallbackField() { BibEntry bibEntry = new BibEntry().withField(StandardField.YEAR, "2021"); assertEquals("2021", generateKey(bibEntry, "[title:([EPRINT:([YEAR])])]")); } @Test void generateKeyWithLowercaseAuthorLastnameUseVonPart() { BibEntry entry = createABibEntryAuthor("Stéphane d'Ascoli"); entry.setField(StandardField.YEAR, "2021"); assertEquals("dAscoli2021", generateKey(entry, "[auth][year]")); } @Test void generateKeyWithLowercaseAuthorWithVonAndLastname() { BibEntry entry = createABibEntryAuthor("Michiel van den Brekel"); entry.setField(StandardField.YEAR, "2021"); assertEquals("Brekel2021", generateKey(entry, "[auth][year]")); } @Test void generateKeyCorrectKeyWithAndOthersAtTheEnd() { BibEntry entry = createABibEntryAuthor("Alexander Artemenko and others"); entry.setField(StandardField.YEAR, "2019"); assertEquals("Artemenko2019", generateKey(entry, "[auth][year]")); } }
52,383
48.3258
192
java
null
jabref-main/src/test/java/org/jabref/logic/citationkeypattern/MakeLabelWithDatabaseTest.java
package org.jabref.logic.citationkeypattern; import java.util.Optional; import org.jabref.model.database.BibDatabase; 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.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import static org.jabref.logic.citationkeypattern.CitationKeyGenerator.DEFAULT_UNWANTED_CHARACTERS; import static org.junit.jupiter.api.Assertions.assertEquals; @Execution(ExecutionMode.CONCURRENT) class MakeLabelWithDatabaseTest { private BibDatabase database; private CitationKeyPatternPreferences preferences; private GlobalCitationKeyPattern pattern; private DatabaseCitationKeyPattern bibtexKeyPattern; private BibEntry entry; @BeforeEach void setUp() { database = new BibDatabase(); entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "John Doe"); entry.setField(StandardField.YEAR, "2016"); entry.setField(StandardField.TITLE, "An awesome paper on JabRef"); database.insertEntry(entry); pattern = GlobalCitationKeyPattern.fromPattern("[auth][year]"); bibtexKeyPattern = new DatabaseCitationKeyPattern(pattern); preferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A, "", "", DEFAULT_UNWANTED_CHARACTERS, pattern, "", ','); } @Test void generateDefaultKey() { new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe2016"), entry.getCitationKey()); } @Test void generateDefaultKeyAlreadyExistsDuplicatesStartAtA() { CitationKeyGenerator keyGenerator = new CitationKeyGenerator(bibtexKeyPattern, database, preferences); keyGenerator.generateAndSetKey(entry); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "John Doe"); entry2.setField(StandardField.YEAR, "2016"); keyGenerator.generateAndSetKey(entry2); assertEquals(Optional.of("Doe2016a"), entry2.getCitationKey()); } @Test void generateDefaultKeyAlwaysLetter() { preferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.ALWAYS, "", "", DEFAULT_UNWANTED_CHARACTERS, pattern, "", ','); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe2016a"), entry.getCitationKey()); } @Test void generateDefaultKeyAlwaysLetterAlreadyExistsDuplicatesStartAtB() { preferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.ALWAYS, "", "", DEFAULT_UNWANTED_CHARACTERS, pattern, "", ','); CitationKeyGenerator keyGenerator = new CitationKeyGenerator(bibtexKeyPattern, database, preferences); keyGenerator.generateAndSetKey(entry); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "John Doe"); entry2.setField(StandardField.YEAR, "2016"); keyGenerator.generateAndSetKey(entry2); assertEquals(Optional.of("Doe2016b"), entry2.getCitationKey()); } @Test void generateDefaultKeyStartDuplicatesAtB() { preferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_B, "", "", DEFAULT_UNWANTED_CHARACTERS, pattern, "", ','); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe2016"), entry.getCitationKey()); } @Test void generateDefaultKeyAlreadyExistsDuplicatesStartAtB() { preferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_B, "", "", DEFAULT_UNWANTED_CHARACTERS, pattern, "", ','); CitationKeyGenerator keyGenerator = new CitationKeyGenerator(bibtexKeyPattern, database, preferences); keyGenerator.generateAndSetKey(entry); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "John Doe"); entry2.setField(StandardField.YEAR, "2016"); keyGenerator.generateAndSetKey(entry2); assertEquals(Optional.of("Doe2016b"), entry2.getCitationKey()); } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test void generateDefaultKeyAlreadyExistsManyDuplicates() { CitationKeyGenerator keyGenerator = new CitationKeyGenerator(bibtexKeyPattern, database, preferences); keyGenerator.generateAndSetKey(entry); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "John Doe"); entry2.setField(StandardField.YEAR, "2016"); entry2.setCitationKey(entry.getCitationKey().get()); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "John Doe"); entry3.setField(StandardField.YEAR, "2016"); entry3.setCitationKey(entry.getCitationKey().get()); database.insertEntry(entry3); keyGenerator.generateAndSetKey(entry3); assertEquals(Optional.of("Doe2016a"), entry3.getCitationKey()); } @SuppressWarnings("OptionalGetWithoutIsPresent") @Test void generateDefaultKeyFirstTwoAlreadyExists() { CitationKeyGenerator keyGenerator = new CitationKeyGenerator(bibtexKeyPattern, database, preferences); keyGenerator.generateAndSetKey(entry); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "John Doe"); entry2.setField(StandardField.YEAR, "2016"); keyGenerator.generateAndSetKey(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "John Doe"); entry3.setField(StandardField.YEAR, "2016"); entry3.setCitationKey(entry.getCitationKey().get()); database.insertEntry(entry3); keyGenerator.generateAndSetKey(entry3); assertEquals(Optional.of("Doe2016b"), entry3.getCitationKey()); } @Test void generateKeyAuthLowerModified() { bibtexKeyPattern.setDefaultValue("[auth:lower][year]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("doe2016"), entry.getCitationKey()); } @Test void generateKeyAuthUpperModified() { bibtexKeyPattern.setDefaultValue("[auth:upper][year]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("DOE2016"), entry.getCitationKey()); } @Test void generateKeyAuthTitleCaseModified() { bibtexKeyPattern.setDefaultValue("[auth:title_case][year]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe2016"), entry.getCitationKey()); } @Test void generateKeyAuthSentenceCaseModified() { bibtexKeyPattern.setDefaultValue("[auth:sentence_case][year]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe2016"), entry.getCitationKey()); } @Test void generateKeyAuthCapitalizeModified() { bibtexKeyPattern.setDefaultValue("[auth:capitalize][year]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe2016"), entry.getCitationKey()); } @Test void generateDefaultKeyFixedValue() { bibtexKeyPattern.setDefaultValue("[auth]Test[year]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("DoeTest2016"), entry.getCitationKey()); } @Test void generateKeyShortYear() { bibtexKeyPattern.setDefaultValue("[shortyear]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("16"), entry.getCitationKey()); } @Test void generateKeyAuthN() { bibtexKeyPattern.setDefaultValue("[auth2]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Do"), entry.getCitationKey()); } @Test void generateKeyAuthNShortName() { bibtexKeyPattern.setDefaultValue("[auth10]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe"), entry.getCitationKey()); } @Test void generateKeyEmptyField() { entry = new BibEntry(); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.empty(), entry.getCitationKey()); } @Test void generateKeyEmptyFieldDefaultText() { bibtexKeyPattern.setDefaultValue("[author:(No Author Provided)]"); entry.clearField(StandardField.AUTHOR); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("NoAuthorProvided"), entry.getCitationKey()); } @Test void generateKeyEmptyFieldNoColonInDefaultText() { bibtexKeyPattern.setDefaultValue("[author:(Problem:No Author Provided)]"); entry.clearField(StandardField.AUTHOR); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("ProblemNoAuthorProvided"), entry.getCitationKey()); } @Test void generateKeyTitle() { bibtexKeyPattern.setDefaultValue("[title]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AnAwesomePaperonJabRef"), entry.getCitationKey()); } @Test void generateKeyTitleAbbr() { bibtexKeyPattern.setDefaultValue("[title:abbr]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AAPoJ"), entry.getCitationKey()); } @Test void generateKeyShorttitle() { bibtexKeyPattern.setDefaultValue("[shorttitle]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("awesomepaperJabRef"), entry.getCitationKey()); } @Test void generateKeyShorttitleLowerModified() { bibtexKeyPattern.setDefaultValue("[shorttitle:lower]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("awesomepaperjabref"), entry.getCitationKey()); } @Test void generateKeyShorttitleUpperModified() { bibtexKeyPattern.setDefaultValue("[shorttitle:upper]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AWESOMEPAPERJABREF"), entry.getCitationKey()); } @Test void generateKeyShorttitleTitleCaseModified() { bibtexKeyPattern.setDefaultValue("[shorttitle:title_case]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AwesomePaperJabref"), entry.getCitationKey()); } @Test void generateKeyShorttitleSentenceCaseModified() { bibtexKeyPattern.setDefaultValue("[shorttitle:sentence_case]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Awesomepaperjabref"), entry.getCitationKey()); } @Test void generateKeyShorttitleCapitalizeModified() { bibtexKeyPattern.setDefaultValue("[shorttitle:capitalize]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AwesomePaperJabref"), entry.getCitationKey()); } @Test void generateKeyVeryshorttitle() { bibtexKeyPattern.setDefaultValue("[veryshorttitle]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("awesome"), entry.getCitationKey()); } @Test void generateKeyVeryshorttitleLowerModified() { bibtexKeyPattern.setDefaultValue("[veryshorttitle:lower]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("awesome"), entry.getCitationKey()); } @Test void generateKeyVeryshorttitleUpperModified() { bibtexKeyPattern.setDefaultValue("[veryshorttitle:upper]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AWESOME"), entry.getCitationKey()); } @Test void generateKeyVeryshorttitleTitleCaseModified() { bibtexKeyPattern.setDefaultValue("[veryshorttitle:title_case]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Awesome"), entry.getCitationKey()); } @Test void generateKeyVeryshorttitleSentenceCaseModified() { bibtexKeyPattern.setDefaultValue("[veryshorttitle:sentence_case]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Awesome"), entry.getCitationKey()); } @Test void generateKeyVeryshorttitleCapitalizeModified() { bibtexKeyPattern.setDefaultValue("[veryshorttitle:capitalize]"); entry.setField(StandardField.TITLE, "An aweSOme Paper on JabRef"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Awesome"), entry.getCitationKey()); } @Test void generateKeyShorttitleINI() { bibtexKeyPattern.setDefaultValue("[shorttitleINI]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Aap"), entry.getCitationKey()); } @Test void generateKeyCamel() { bibtexKeyPattern.setDefaultValue("[camel]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AnAwesomePaperOnJabRef"), entry.getCitationKey()); } @Test void generateKeyAuthNM() { bibtexKeyPattern.setDefaultValue("[auth4_3]"); entry.setField(StandardField.AUTHOR, "John Doe and Donald Smith and Will Wonder"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Wond"), entry.getCitationKey()); } @Test void generateKeyAuthNMLargeN() { bibtexKeyPattern.setDefaultValue("[auth20_3]"); entry.setField(StandardField.AUTHOR, "John Doe and Donald Smith and Will Wonder"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Wonder"), entry.getCitationKey()); } @Test void generateKeyAuthNMLargeM() { bibtexKeyPattern.setDefaultValue("[auth2_4]"); entry.setField(StandardField.AUTHOR, "John Doe and Donald Smith and Will Wonder"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.empty(), entry.getCitationKey()); } @Test void generateKeyAuthNMLargeMReallyReturnsEmptyString() { bibtexKeyPattern.setDefaultValue("[auth2_4][year]"); entry.setField(StandardField.AUTHOR, "John Doe and Donald Smith and Will Wonder"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("2016"), entry.getCitationKey()); } @Test void generateKeyRegExReplace() { preferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A, "2", "3", DEFAULT_UNWANTED_CHARACTERS, pattern, "", ','); bibtexKeyPattern.setDefaultValue("[auth][year]"); entry.setField(StandardField.AUTHOR, "John Doe and Donald Smith and Will Wonder"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Doe3016"), entry.getCitationKey()); } @Test void generateKeyAuthIni() { bibtexKeyPattern.setDefaultValue("[authIni2]"); entry.setField(StandardField.AUTHOR, "John Doe and Donald Smith and Will Wonder"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("D+"), entry.getCitationKey()); } @Test void generateKeyAuthIniMany() { bibtexKeyPattern.setDefaultValue("[authIni10]"); entry.setField(StandardField.AUTHOR, "John Doe and Donald Smith and Will Wonder"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("DoeSmiWon"), entry.getCitationKey()); } @Test void generateKeyTitleRegexe() { bibtexKeyPattern.setDefaultValue("[title:regex(\" \",\"-\")]"); entry.setField(StandardField.TITLE, "Please replace the spaces"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("PleaseReplacetheSpaces"), entry.getCitationKey()); } @Test void generateKeyTitleTitleCase() { bibtexKeyPattern.setDefaultValue("[title:title_case]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AnAwesomePaperonJabref"), entry.getCitationKey()); } @Test void generateKeyTitleCapitalize() { bibtexKeyPattern.setDefaultValue("[title:capitalize]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AnAwesomePaperOnJabref"), entry.getCitationKey()); } @Test void generateKeyTitleSentenceCase() { bibtexKeyPattern.setDefaultValue("[title:sentence_case]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Anawesomepaperonjabref"), entry.getCitationKey()); } @Test void generateKeyTitleTitleCaseAbbr() { bibtexKeyPattern.setDefaultValue("[title:title_case:abbr]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AAPoJ"), entry.getCitationKey()); } @Test void generateKeyTitleCapitalizeAbbr() { bibtexKeyPattern.setDefaultValue("[title:capitalize:abbr]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("AAPOJ"), entry.getCitationKey()); } @Test void generateKeyTitleSentenceCaseAbbr() { bibtexKeyPattern.setDefaultValue("[title:sentence_case:abbr]"); new CitationKeyGenerator(bibtexKeyPattern, database, preferences).generateAndSetKey(entry); assertEquals(Optional.of("Aapoj"), entry.getCitationKey()); } }
21,476
40.865497
110
java
null
jabref-main/src/test/java/org/jabref/logic/citationkeypattern/MakeLabelWithoutDatabaseTest.java
package org.jabref.logic.citationkeypattern; import java.util.Collections; import javafx.beans.property.SimpleObjectProperty; import org.jabref.model.database.BibDatabase; 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.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import static org.junit.jupiter.api.Assertions.assertEquals; @Execution(ExecutionMode.CONCURRENT) class MakeLabelWithoutDatabaseTest { private CitationKeyGenerator citationKeyGenerator; @BeforeEach void setUp() { GlobalCitationKeyPattern keyPattern = new GlobalCitationKeyPattern(Collections.emptyList()); keyPattern.setDefaultValue("[auth]"); CitationKeyPatternPreferences patternPreferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A, "", "", CitationKeyGenerator.DEFAULT_UNWANTED_CHARACTERS, keyPattern, "", new SimpleObjectProperty<>(',')); citationKeyGenerator = new CitationKeyGenerator(keyPattern, new BibDatabase(), patternPreferences); } @Test void makeAuthorLabelForFileSearch() { BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, "John Doe") .withField(StandardField.YEAR, "2016") .withField(StandardField.TITLE, "An awesome paper on JabRef"); String label = citationKeyGenerator.generateKey(entry); assertEquals("Doe", label); } @Test void makeEditorLabelForFileSearch() { BibEntry entry = new BibEntry() .withField(StandardField.EDITOR, "John Doe") .withField(StandardField.YEAR, "2016") .withField(StandardField.TITLE, "An awesome paper on JabRef"); String label = citationKeyGenerator.generateKey(entry); assertEquals("Doe", label); } }
2,150
32.609375
107
java
null
jabref-main/src/test/java/org/jabref/logic/citationstyle/CitationStyleCacheTest.java
package org.jabref.logic.citationstyle; import java.util.List; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; class CitationStyleCacheTest { private BibEntry bibEntry; private List<BibEntry> entries; private BibDatabase database; private BibDatabaseContext databaseContext; private CitationStyleCache csCache; @Test void getCitationForTest() { BibEntry bibEntry = new BibEntry().withCitationKey("test"); List<BibEntry> entries = List.of(bibEntry); BibDatabase database = new BibDatabase(entries); BibDatabaseContext databaseContext = new BibDatabaseContext(database); CitationStyleCache csCache = new CitationStyleCache(databaseContext); assertNotNull(csCache.getCitationFor(bibEntry)); } }
928
28.03125
74
java
null
jabref-main/src/test/java/org/jabref/logic/citationstyle/CitationStyleGeneratorTest.java
package org.jabref.logic.citationstyle; import java.util.List; import java.util.stream.Stream; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.TestEntry; 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.BibEntryTypesManager; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; 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 CitationStyleGeneratorTest { private final BibEntryTypesManager bibEntryTypesManager = new BibEntryTypesManager(); @Test void testACMCitation() { BibDatabaseContext context = new BibDatabaseContext(new BibDatabase(List.of(TestEntry.getTestEntry()))); context.setMode(BibDatabaseMode.BIBLATEX); List<CitationStyle> styleList = CitationStyle.discoverCitationStyles(); CitationStyle style = styleList.stream().filter(e -> "ACM SIGGRAPH".equals(e.getTitle())).findAny().orElse(null); String citation = CitationStyleGenerator.generateCitation(TestEntry.getTestEntry(), style.getSource(), CitationStyleOutputFormat.HTML, context, new BibEntryTypesManager()); // if the acm-siggraph.csl citation style changes this has to be modified String expected = " <div class=\"csl-entry\">" + "<span style=\"font-variant: small-caps\">Smith, B., Jones, B., and Williams, J.</span> 2016. Title of the test entry. <span style=\"font-style: italic\">BibTeX Journal</span> <span style=\"font-style: italic\">34</span>, 3, 45&ndash;67." + "</div>\n" + ""; assertEquals(expected, citation); } @Test void testAPACitation() { BibDatabaseContext context = new BibDatabaseContext(new BibDatabase(List.of(TestEntry.getTestEntry()))); context.setMode(BibDatabaseMode.BIBLATEX); List<CitationStyle> styleList = CitationStyle.discoverCitationStyles(); CitationStyle style = styleList.stream().filter(e -> "American Psychological Association 7th edition".equals(e.getTitle())).findAny().orElse(null); String citation = CitationStyleGenerator.generateCitation(TestEntry.getTestEntry(), style.getSource(), CitationStyleOutputFormat.HTML, context, new BibEntryTypesManager()); // if the apa-7th-citation.csl citation style changes this has to be modified String expected = " <div class=\"csl-entry\">" + "Smith, B., Jones, B., &amp; Williams, J. (2016). Title of the test entry. <span style=\"font-style: italic\">BibTeX Journal</span>, <span style=\"font-style: italic\">34</span>(3), 45&ndash;67. https://doi.org/10.1001/bla.blubb" + "</div>\n" + ""; assertEquals(expected, citation); } @Test void testIgnoreNewLine() { BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "Last, First and\nDoe, Jane"); // if the default citation style changes this has to be modified String expected = " <div class=\"csl-entry\">\n" + " <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">F. Last and J. Doe, </div>\n" + " </div>\n"; String citation = CitationStyleGenerator.generateCitation(entry, CitationStyle.getDefault(), bibEntryTypesManager); assertEquals(expected, citation); } @Test void testIgnoreCarriageReturnNewLine() { BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "Last, First and\r\nDoe, Jane"); // if the default citation style changes this has to be modified String expected = " <div class=\"csl-entry\">\n" + " <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">F. Last and J. Doe, </div>\n" + " </div>\n"; String citation = CitationStyleGenerator.generateCitation(entry, CitationStyle.getDefault(), bibEntryTypesManager); assertEquals(expected, citation); } @Test void testMissingCitationStyle() { String expected = Localization.lang("Cannot generate preview based on selected citation style."); String citation = CitationStyleGenerator.generateCitation(new BibEntry(), "faulty citation style", bibEntryTypesManager); assertEquals(expected, citation); } @Test void testHtmlFormat() { String expectedCitation = " <div class=\"csl-entry\">\n" + " <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">B. Smith, B. Jones, and J. Williams, &ldquo;Title of the test entry,&rdquo; <span style=\"font-style: italic\">BibTeX Journal</span>, vol. 34, no. 3, pp. 45&ndash;67, Jul. 2016, doi: 10.1001/bla.blubb.</div>\n" + " </div>\n"; BibEntry entry = TestEntry.getTestEntry(); String style = CitationStyle.getDefault().getSource(); CitationStyleOutputFormat format = CitationStyleOutputFormat.HTML; String actualCitation = CitationStyleGenerator.generateCitation(entry, style, format, new BibDatabaseContext(), bibEntryTypesManager); assertEquals(expectedCitation, actualCitation); } @Test void testTextFormat() { String expectedCitation = "[1]B. Smith, B. Jones, and J. Williams, “Title of the test entry,” BibTeX Journal, vol. 34, no. 3, pp. 45–67, Jul. 2016, doi: 10.1001/bla.blubb.\n"; BibEntry entry = TestEntry.getTestEntry(); String style = CitationStyle.getDefault().getSource(); CitationStyleOutputFormat format = CitationStyleOutputFormat.TEXT; String actualCitation = CitationStyleGenerator.generateCitation(entry, style, format, new BibDatabaseContext(new BibDatabase(List.of(entry))), bibEntryTypesManager); assertEquals(expectedCitation, actualCitation); } @Test void testHandleDiacritics() { BibEntry entry = new BibEntry(); // We need to escape the backslash as well, because the slash is part of the LaTeX expression entry.setField(StandardField.AUTHOR, "L{\\\"a}st, First and Doe, Jane"); // if the default citation style changes this has to be modified. // in this case ä was added to check if it is formatted appropriately String expected = " <div class=\"csl-entry\">\n" + " <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">F. L&auml;st and J. Doe, </div>\n" + " </div>\n"; String citation = CitationStyleGenerator.generateCitation(entry, CitationStyle.getDefault(), bibEntryTypesManager); assertEquals(expected, citation); } @Test void testHandleAmpersand() { String expectedCitation = "[1]B. Smith, B. Jones, and J. Williams, “Famous quote: “&TitleTest&” - that is it,” BibTeX Journal, vol. 34, no. 3, pp. 45–67, Jul. 2016, doi: 10.1001/bla.blubb.\n"; BibEntry entry = TestEntry.getTestEntry(); entry.setField(StandardField.TITLE, "Famous quote: “&TitleTest&” - that is it"); String style = CitationStyle.getDefault().getSource(); CitationStyleOutputFormat format = CitationStyleOutputFormat.TEXT; String actualCitation = CitationStyleGenerator.generateCitation(entry, style, format, new BibDatabaseContext(), bibEntryTypesManager); assertEquals(expectedCitation, actualCitation); } @Test void testHandleCrossRefFields() { BibEntry firstEntry = new BibEntry(StandardEntryType.InCollection) .withCitationKey("smit2021") .withField(StandardField.AUTHOR, "Smith, Bob") .withField(StandardField.TITLE, "An article") .withField(StandardField.PAGES, "1-10") .withField(StandardField.CROSSREF, "jone2021"); BibEntry secondEntry = new BibEntry(StandardEntryType.Book) .withCitationKey("jone2021") .withField(StandardField.EDITOR, "Jones, John") .withField(StandardField.PUBLISHER, "Great Publisher") .withField(StandardField.TITLE, "A book") .withField(StandardField.YEAR, "2021") .withField(StandardField.ADDRESS, "Somewhere"); String expectedCitation = "[1]B. Smith, “An article,” J. Jones, Ed., Somewhere: Great Publisher, 2021, pp. 1–10.\n"; BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(new BibDatabase(List.of(firstEntry, secondEntry))); String style = CitationStyle.getDefault().getSource(); String actualCitation = CitationStyleGenerator.generateCitation(firstEntry, style, CitationStyleOutputFormat.TEXT, bibDatabaseContext, bibEntryTypesManager); assertEquals(expectedCitation, actualCitation); } static Stream<Arguments> testCslMapping() { // if the default citation style changes this has to be modified return Stream.of( Arguments.of( "[1]F. Last and J. Doe, no. 28.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Last, First and\nDoe, Jane") .withField(StandardField.NUMBER, "28"), "ieee.csl"), Arguments.of( "[1]F. Last and J. Doe, no. 7.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Last, First and\nDoe, Jane") .withField(StandardField.ISSUE, "7"), "ieee.csl"), Arguments.of( "[1]F. Last and J. Doe, no. 28.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Last, First and Doe, Jane") .withField(StandardField.NUMBER, "28"), "ieee.csl"), Arguments.of( "[1]F. Last and J. Doe, no. 28.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Last, First and\nDoe, Jane") .withField(StandardField.ISSUE, "7") .withField(StandardField.NUMBER, "28"), "ieee.csl"), Arguments.of( "[1]F. Last and J. Doe, no. 7, Art. no. e0270533.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Last, First and\nDoe, Jane") .withField(StandardField.ISSUE, "7") .withField(StandardField.EID, "e0270533"), "ieee.csl"), Arguments.of( "[1]F. Last and J. Doe, no. 33, pp. 7–8.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Last, First and\nDoe, Jane") .withField(StandardField.PAGES, "7--8") .withField(StandardField.ISSUE, "33"), "ieee.csl"), Arguments.of( "Foo, B. (n.d.). volume + issue + number + pages. Bib(La)TeX Journal, 1(3number), 45–67.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67") .withField(StandardField.TITLE, "volume + issue + number + pages") .withField(StandardField.VOLUME, "1") .withField(StandardField.COMMENT, "The issue field does not exist in Bibtex standard, therefore there is no need to render it (The issue field exists in biblatex standard though)") .withField(StandardField.ISSUE, "9issue"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). volume + issue + pages. Bib(La)TeX Journal, 1(9), 45–67.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.PAGES, "45--67") .withField(StandardField.TITLE, "volume + issue + pages") .withField(StandardField.VOLUME, "1") .withField(StandardField.COMMENT, "The issue field does not exist in Bibtex standard, therefore there is no need to render it (The issue field exists in biblatex standard though.). Since, for this entry, there is no number field present and therefore no data will be overwriten, enabling the user to be able to move the data within the issue field to the number field via cleanup action is something worth pursuing.") .withField(StandardField.ISSUE, "9"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). volume + pages. Bib(La)TeX Journal, 1, 45–67.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.PAGES, "45--67") .withField(StandardField.TITLE, "volume + pages") .withField(StandardField.VOLUME, "1"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). number. Bib(La)TeX Journal, 3number.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.TITLE, "number"), "apa.csl"), // The issue field does not exist in bibtex standard, therefore there is no need to render it (it exists in biblatex standard though). Since, for this entry, there is no number field present and therefore no data will be overwriten, enabling the user to be able to move the data within the issue field to the number field via cleanup action is something worth pursuing. Arguments.of( "Foo, B. (n.d.). issue + pages. Bib(La)TeX Journal, 9, 45–67.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.PAGES, "45--67") .withField(StandardField.TITLE, "issue + pages") .withField(StandardField.ISSUE, "9"), "apa.csl"), // The issue field does not exist in bibtex standard, therefore there is no need to render it (it exists in biblatex standard though) Arguments.of( "Foo, B. (n.d.). issue + number. Bib(La)TeX Journal, 3number.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.TITLE, "issue + number") .withField(StandardField.ISSUE, "9issue"), "apa.csl"), // The issue field does not exist in bibtex standard, therefore there is no need to render it (it exists in biblatex standard though) Arguments.of( "Foo, B. (n.d.). issue + number + pages. Bib(La)TeX Journal, 3number, 45–67.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67") .withField(StandardField.TITLE, "issue + number + pages") .withField(StandardField.ISSUE, "9issue"), "apa.csl"), // "Article number" is not a field that exists in Bibtex standard. Printing the article number in the pages field is a workaround. Some Journals have opted to put the article number into the pages field. APA 7th Style recommends following procedure: If the journal article has an article number instead of a page range, include the word "Article" and then the article number instead of the page range. Question: Should it be rendered WITH Article or WITHOUT the Word Article in Front? I guess without? Arguments.of( "Foo, B. (n.d.). number + pages. Bib(La)TeX Journal, 3number, Article 777.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "Article 777") .withField(StandardField.TITLE, "number + pages") .withField(StandardField.COMMENT, "number + article-number WITH the word article instead of pagerange"), "apa.csl"), // "The issue field does not exist in bibtex standard, therefore there is no need to render it (it exists in biblatex standard though). Since, for this entry, there is no number field present and therefore no data will be overwriten, enabling the user to be able to move the data within the issue field to the number field via cleanup action is something worth pursuing." Arguments.of( "Foo, B. (n.d.). issue. Bib(La)TeX Journal, 9issue.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "issue") .withField(StandardField.ISSUE, "9issue"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). number + pages. Bib(La)TeX Journal, 3number, 45–67.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "Bib(La)TeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67") .withField(StandardField.TITLE, "number + pages"), "apa.csl"), // "Article number" is not a field that exists in Bibtex standard. Printing the article number in the pages field is a workaround. Some Journals have opted to put the article number into the pages field. APA 7th Style recommends following procedure: If the journal article has an article number instead of a page range, include the word "Article" and then the article number instead of the page range. Question: Should it be rendered WITH Article or WITHOUT the Word Article in Front? I guess without? Arguments.of( "Foo, B. (n.d.). number + pages. BibTeX Journal, 3number, 777e23.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "BibTeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "777e23") .withField(StandardField.TITLE, "number + pages") .withField(StandardField.COMMENT, "number + article-number WITHOUT the word article instead of pagerange"), "apa.csl"), // Not rendering the "eid" field here, is correct. The "eid" field(short for: electronic identifier) does not exist in Bibtex standard. It exists in Biblatex standard though and is the field, in which the "article number" should be entered into. "Article number" is a field that does not exist in Bibtex and also not in Biblatex standard. As a workaround, some Journals have opted to put the article number into the pages field. APA 7th Style recommends following procedure: "If the journal article has an article number instead of a page range, include the word "Article" and then the article number instead of the page range." - Source: https://apastyle.apa.org/style-grammar-guidelines/references/examples/journal-article-references#2. Additionally the APA style (7th edition) created by the CSL community "prints the issue (= the "number" field" in Biblatex) whenever it is in the data and the number (= the "eid" field in Biblatex) when no page range is present, entirely independent of the issue number" - Source: https://github.com/citation-style-language/styles/issues/5827#issuecomment-1006011280). I personally think the "eid" field SHOULD be rendered here SOMEWHERE, maybe even IN ADDITION to the page range, because we have the data, right? Why not show it? - But this is just my humble opinion and may not be coherent with the current APA Style 7th edition. Not rendering the "issue" field here is sufficient for APA 7th edition. Under current circumstances the "number" field takes priority over the "issue" field (see https://github.com/JabRef/jabref/issues/8372#issuecomment-1023768144). [Keyword: IS RENDERING BOTH VIABLE?]. Ideally, they would coexist: "Roughly speaking number subdivides volume and issue is much closer to subdividing year. I don't think I would want to say that issue is subordinate to number or vice versa. They sort of operate on a similar level." (Source: https://github.com/plk/biblatex/issues/726#issuecomment-1010264258) Arguments.of( "Foo, B. (n.d.). eid + issue + number + pages. BibTeX Journal, 3number, 45–67.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "BibTeX Journal") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67") .withField(StandardField.TITLE, "eid + issue + number + pages") .withField(StandardField.EID, "6eid") .withField(StandardField.ISSUE, "9issue"), "apa.csl"), /* Not rendering the "eid" field here, is correct. The "eid" field(= electronic identifier) does not exist in Bibtex standard. Since, for this entry, there is no pages field present and therefore no data will be overwritten, enabling the user to be able to move the data within the eid scala.annotation.meta.field to the pages scala.annotation.meta.field via cleanup action is something worth pursuing. Not rendering the "issue" field here is correct. The "issue" field does not exist in Bibtex standard. Since, for this entry, there is no number field present and therefore no data will be overwritten, enabling the user to be able to move the data within the issue field to the number field via cleanup action is something worth pursuing. */ Arguments.of( "Foo, B. (n.d.). eid + issue. BibTeX Journal, 9issue, Article 6eid.\n", BibDatabaseMode.BIBTEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNAL, "BibTeX Journal") .withField(StandardField.TITLE, "eid + issue") .withField(StandardField.COMMENT, "") .withField(StandardField.EID, "Article 6eid") .withField(StandardField.ISSUE, "9issue"), "apa.csl"), /* Not rendering the "eid" field here, is sufficient, but contested practice. This statement is based on the following reasoning: "eid" (in long: electronic identifier) is the field, which should be used to enter the "article number", when using the Biblatex standard. Both "eid" and "article number" do not exist in the older Bibtex standard. As a workaround, some Journals and publishers have opted to put the article number into the pages field. APA 7th Style recommends following procedure: "If the journal article has an article number instead of a page range, include the word "Article" and then the article number instead of the page range." - Source: https://apastyle.apa.org/style-grammar-guidelines/references/examples/journal-article-references#2. Additionally the APA style (7th edition) created by the CSL community "prints the issue [= the "number" field" in both Biblatex and Bibtex] whenever it is in the data and the number [= the "eid" field in Biblatex] when no page range is present, entirely independent of the issue number" - Source: https://github.com/citation-style-language/styles/issues/5827#issuecomment-1006011280. I personally think the "eid" field SHOULD be rendered here SOMEWHERE, maybe even IN ADDITION to the page range, because we have the data, right? Why not show it? - But this is just my humble opinion and may not be coherent with the current APA Style 7th edition. Not rendering the "issue" field here is sufficient for APA 7th edition. Under current circumstances the "number" field takes priority over the "issue" field (see https://github.com/JabRef/jabref/issues/8372#issuecomment-1023768144). [Keyword: IS RENDERING BOTH VIABLE?]. Ideally, they would coexist: "Roughly speaking number subdivides volume and issue is much closer to subdividing year. I don't think I would want to say that issue is subordinate to number or vice versa. They sort of operate on a similar level." (Source: https://github.com/plk/biblatex/issues/726#issuecomment-1010264258) */ Arguments.of( "Foo, B. (n.d.). volume + issue + number + pages + eid. Bib(La)TeX Journal, 1(3number), Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "volume + issue + number + pages + eid") .withField(StandardField.EID, "6eid") .withField(StandardField.ISSUE, "9issue") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67") .withField(StandardField.VOLUME, "1"), "apa.csl"), // eid field will always be prefixed with article Arguments.of( "Foo, B. (n.d.). volume + issue + pages + eid. Bib(La)TeX Journal, 1(9issue), Article Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "volume + issue + pages + eid") .withField(StandardField.EID, "Article 6eid") .withField(StandardField.ISSUE, "9issue") .withField(StandardField.PAGES, "45--67") .withField(StandardField.VOLUME, "1"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). volume + number + pages + eid. Bib(La)TeX Journal, 1(3number), Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "volume + number + pages + eid") .withField(StandardField.EID, "6eid") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67") .withField(StandardField.VOLUME, "1"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid + issue. Bib(La)TeX Journal, 9issue, Article Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid + issue") .withField(StandardField.EID, "Article 6eid") .withField(StandardField.ISSUE, "9issue"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid + issue + pages. Bib(La)TeX Journal, 9issue, Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid + issue + pages") .withField(StandardField.EID, "6eid") .withField(StandardField.ISSUE, "9issue") .withField(StandardField.PAGES, "45--67"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid + issue + number. Bib(La)TeX Journal, 3number, Article Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid + issue + number") .withField(StandardField.EID, "Article 6eid") .withField(StandardField.ISSUE, "9issue") .withField(StandardField.NUMBER, "3number"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid + issue + number + pages. Bib(La)TeX Journal, 3number, Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid + issue + number + pages") .withField(StandardField.EID, "6eid") .withField(StandardField.ISSUE, "9issue") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid + pages. Bib(La)TeX Journal, Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid + pages") .withField(StandardField.EID, "6eid") .withField(StandardField.PAGES, "45--67"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid. Bib(La)TeX Journal, Article Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid") .withField(StandardField.EID, "Article 6eid"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). volume + number + eid. Bib(La)TeX Journal, 1(3number), Article Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "volume + number + eid") .withField(StandardField.EID, "Article 6eid") .withField(StandardField.NUMBER, "3number") .withField(StandardField.VOLUME, "1"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). volume + pages + eid. Bib(La)TeX Journal, 1, Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "volume + pages + eid") .withField(StandardField.EID, "6eid") .withField(StandardField.PAGES, "45--67") .withField(StandardField.VOLUME, "1"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid + number. Bib(La)TeX Journal, 3number, Article Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid + number") .withField(StandardField.EID, "Article 6eid") .withField(StandardField.NUMBER, "3number"), "apa.csl"), Arguments.of( "Foo, B. (n.d.). eid + number + pages. Bib(La)TeX Journal, 3number, Article 6eid.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "eid + number + pages") .withField(StandardField.EID, "6eid") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67"), "apa.csl"), // Not rendering the "issue" field here is sufficient for APA Style (7th edition). Under current circumstances the "number" field takes priority over the "issue" field (see https://github.com/JabRef/jabref/issues/8372#issuecomment-1023768144). [Keyword: IS RENDERING BOTH VIABLE?]. Ideally, they would coexist: "Roughly speaking number subdivides volume and issue is much closer to subdividing year. I don't think I would want to say that issue is subordinate to number or vice versa. They sort of operate on a similar level." (Source: https://github.com/plk/biblatex/issues/726#issuecomment-1010264258) Arguments.of( "Foo, B. (n.d.). issue + number. Bib(La)TeX Journal, 3number.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "issue + number") .withField(StandardField.ISSUE, "9issue") .withField(StandardField.NUMBER, "3number"), "apa.csl"), // Not rendering the "issue" field here is sufficient for APA 7th edition. Under current circumstances the "number" field takes priority over the "issue" field (see https://github.com/JabRef/jabref/issues/8372#issuecomment-1023768144). [Keyword: IS RENDERING BOTH VIABLE?]. Ideally, they would coexist: "Roughly speaking number subdivides volume and issue is much closer to subdividing year. I don't think I would want to say that issue is subordinate to number or vice versa. They sort of operate on a similar level." (Source: https://github.com/plk/biblatex/issues/726#issuecomment-1010264258) Arguments.of( "Foo, B. (n.d.). issue + number + pages. Bib(La)TeX Journal, 3number, 45–67.\n", BibDatabaseMode.BIBLATEX, new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Foo, Bar") .withField(StandardField.JOURNALTITLE, "Bib(La)TeX Journal") .withField(StandardField.TITLE, "issue + number + pages") .withField(StandardField.ISSUE, "9issue") .withField(StandardField.NUMBER, "3number") .withField(StandardField.PAGES, "45--67"), "apa.csl") ); } @ParameterizedTest @MethodSource void testCslMapping(String expected, BibDatabaseMode mode, BibEntry entry, String cslFileName) throws Exception { BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(new BibDatabase(List.of(entry))); bibDatabaseContext.setMode(mode); String citation = CitationStyleGenerator.generateCitation( entry, CitationStyle.createCitationStyleFromFile(cslFileName).orElseThrow().getSource(), CitationStyleOutputFormat.TEXT, bibDatabaseContext, bibEntryTypesManager); assertEquals(expected, citation); } }
42,470
70.984746
1,980
java
null
jabref-main/src/test/java/org/jabref/logic/citationstyle/CitationStyleTest.java
package org.jabref.logic.citationstyle; import java.util.List; import org.jabref.logic.util.TestEntry; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntryTypesManager; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class CitationStyleTest { @Test void getDefault() throws Exception { assertNotNull(CitationStyle.getDefault()); } @Test void testDefaultCitation() { BibDatabaseContext context = new BibDatabaseContext(new BibDatabase(List.of(TestEntry.getTestEntry()))); context.setMode(BibDatabaseMode.BIBLATEX); String citation = CitationStyleGenerator.generateCitation(TestEntry.getTestEntry(), CitationStyle.getDefault().getSource(), CitationStyleOutputFormat.HTML, context, new BibEntryTypesManager()); // if the default citation style changes this has to be modified String expected = """ <div class="csl-entry"> <div class="csl-left-margin">[1]</div><div class="csl-right-inline">B. Smith, B. Jones, and J. Williams, &ldquo;Title of the test entry,&rdquo; <span style="font-style: italic">BibTeX Journal</span>, vol. 34, no. 3, pp. 45&ndash;67, Jul. 2016, doi: 10.1001/bla.blubb.</div> </div> """; assertEquals(expected, citation); } @Test void testDiscoverCitationStylesNotNull() throws Exception { List<CitationStyle> styleList = CitationStyle.discoverCitationStyles(); assertNotNull(styleList); } }
1,744
37.777778
293
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/BibtexBiblatexRoundtripTest.java
package org.jabref.logic.cleanup; 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.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class BibtexBiblatexRoundtripTest { private BibEntry bibtex; private BibEntry biblatex; @BeforeEach void setUp() { bibtex = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Frame, J. S. and Robinson, G. de B. and Thrall, R. M.") .withField(StandardField.TITLE, "The hook graphs of the symmetric groups") .withField(StandardField.JOURNAL, "Canadian J. Math.") .withField(new UnknownField("fjournal"), "Canadian Journal of Mathematics. Journal Canadien de Math\\'ematiques") .withField(StandardField.VOLUME, "6") .withField(StandardField.YEAR, "1954") .withField(StandardField.PAGES, "316--324") .withField(StandardField.ISSN, "0008-414X") .withField(new UnknownField("mrclass"), "20.0X") .withField(StandardField.MR_NUMBER, "0062127") .withField(new UnknownField("mrreviewer"), "D. E. Littlewood"); biblatex = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Frame, J. S. and Robinson, G. de B. and Thrall, R. M.") .withField(StandardField.TITLE, "The hook graphs of the symmetric groups") .withField(StandardField.JOURNALTITLE, "Canadian J. Math.") .withField(new UnknownField("fjournal"), "Canadian Journal of Mathematics. Journal Canadien de Math\\'ematiques") .withField(StandardField.VOLUME, "6") .withField(StandardField.DATE, "1954") .withField(StandardField.PAGES, "316--324") .withField(StandardField.ISSN, "0008-414X") .withField(new UnknownField("mrclass"), "20.0X") .withField(StandardField.MR_NUMBER, "0062127") .withField(new UnknownField("mrreviewer"), "D. E. Littlewood"); } @Test void roundTripBibtexToBiblatexIsIdentity() { BibEntry clone = (BibEntry) bibtex.clone(); new ConvertToBiblatexCleanup().cleanup(clone); assertEquals(biblatex, clone); new ConvertToBibtexCleanup().cleanup(clone); assertEquals(bibtex, clone); } @Test void roundTripBiblatexToBibtexIsIdentity() { BibEntry clone = (BibEntry) biblatex.clone(); new ConvertToBibtexCleanup().cleanup(clone); assertEquals(bibtex, clone); new ConvertToBiblatexCleanup().cleanup(clone); assertEquals(biblatex, clone); } }
2,913
41.852941
129
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java
package org.jabref.logic.cleanup; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Optional; import org.jabref.logic.bibtex.FileFieldWriter; import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter; import org.jabref.logic.formatter.bibtexfields.LatexCleanupFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizeDateFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizeMonthFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import org.jabref.logic.formatter.bibtexfields.UnitsToLatexFormatter; import org.jabref.logic.formatter.casechanger.ProtectTermsFormatter; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.protectedterms.ProtectedTermsPreferences; import org.jabref.model.FieldChange; 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.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.CleanupPreferences; import org.jabref.preferences.FilePreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class CleanupWorkerTest { private final CleanupPreferences emptyPreset = new CleanupPreferences(EnumSet.noneOf(CleanupPreferences.CleanupStep.class)); private CleanupWorker worker; // Ensure that the folder stays the same for all tests. // By default, @TempDir creates a new folder for each usage private Path bibFolder; // Currently, this directory is created below the bibFolder private Path pdfPath; @BeforeEach void setUp(@TempDir Path bibFolder) throws IOException { this.bibFolder = bibFolder; pdfPath = bibFolder.resolve("ARandomlyNamedFolder"); Files.createDirectory(pdfPath); MetaData metaData = new MetaData(); metaData.setDefaultFileDirectory(pdfPath.toAbsolutePath().toString()); BibDatabaseContext context = new BibDatabaseContext(new BibDatabase(), metaData); Files.createFile(bibFolder.resolve("test.bib")); context.setDatabasePath(bibFolder.resolve("test.bib")); FilePreferences fileDirPrefs = mock(FilePreferences.class, Answers.RETURNS_SMART_NULLS); // Search and store files relative to bib file overwrites all other dirs when(fileDirPrefs.shouldStoreFilesRelativeToBibFile()).thenReturn(true); worker = new CleanupWorker(context, fileDirPrefs, mock(TimestampPreferences.class)); } @Test void cleanupWithNullPresetThrowsException() { assertThrows(NullPointerException.class, () -> worker.cleanup(null, new BibEntry())); } @Test void cleanupNullEntryThrowsException() { assertThrows(NullPointerException.class, () -> worker.cleanup(emptyPreset, null)); } @Test void cleanupDoesNothingByDefault(@TempDir Path bibFolder) throws IOException { BibEntry entry = new BibEntry(); entry.setCitationKey("Toot"); entry.setField(StandardField.PDF, "aPdfFile"); entry.setField(new UnknownField("some"), "1st"); entry.setField(StandardField.DOI, "http://dx.doi.org/10.1016/0001-8708(80)90035-3"); entry.setField(StandardField.MONTH, "01"); entry.setField(StandardField.PAGES, "1-2"); entry.setField(StandardField.DATE, "01/1999"); entry.setField(StandardField.PDF, "aPdfFile"); entry.setField(StandardField.ISSN, "aPsFile"); entry.setField(StandardField.FILE, "link::"); entry.setField(StandardField.JOURNAL, "test"); entry.setField(StandardField.TITLE, "<b>hallo</b> units 1 A case AlGaAs and latex $\\alpha$$\\beta$"); entry.setField(StandardField.ABSTRACT, "Réflexions"); Path path = bibFolder.resolve("ARandomlyNamedFile"); Files.createFile(path); LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); List<FieldChange> changes = worker.cleanup(emptyPreset, entry); assertEquals(Collections.emptyList(), changes); } @Test void upgradeExternalLinksMoveFromPdfToFile() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_UPGRADE_EXTERNAL_LINKS); BibEntry entry = new BibEntry(); entry.setField(StandardField.PDF, "aPdfFile"); worker.cleanup(preset, entry); assertEquals(Optional.empty(), entry.getField(StandardField.PDF)); assertEquals(Optional.of("aPdfFile:aPdfFile:PDF"), entry.getField(StandardField.FILE)); } @Test void upgradeExternalLinksMoveFromPsToFile() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_UPGRADE_EXTERNAL_LINKS); BibEntry entry = new BibEntry(); entry.setField(StandardField.PS, "aPsFile"); worker.cleanup(preset, entry); assertEquals(Optional.empty(), entry.getField(StandardField.PDF)); assertEquals(Optional.of("aPsFile:aPsFile:PostScript"), entry.getField(StandardField.FILE)); } @Test void cleanupDoiRemovesLeadingHttp() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_DOI); BibEntry entry = new BibEntry(); entry.setField(StandardField.DOI, "http://dx.doi.org/10.1016/0001-8708(80)90035-3"); worker.cleanup(preset, entry); assertEquals(Optional.of("10.1016/0001-8708(80)90035-3"), entry.getField(StandardField.DOI)); } @Test void cleanupDoiReturnsChanges() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_DOI); BibEntry entry = new BibEntry(); entry.setField(StandardField.DOI, "http://dx.doi.org/10.1016/0001-8708(80)90035-3"); List<FieldChange> changes = worker.cleanup(preset, entry); FieldChange expectedChange = new FieldChange(entry, StandardField.DOI, "http://dx.doi.org/10.1016/0001-8708(80)90035-3", "10.1016/0001-8708(80)90035-3"); assertEquals(Collections.singletonList(expectedChange), changes); } @Test void cleanupDoiFindsDoiInURLFieldAndMoveItToDOIField() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_DOI); BibEntry entry = new BibEntry(); entry.setField(StandardField.URL, "http://dx.doi.org/10.1016/0001-8708(80)90035-3"); worker.cleanup(preset, entry); assertEquals(Optional.of("10.1016/0001-8708(80)90035-3"), entry.getField(StandardField.DOI)); assertEquals(Optional.empty(), entry.getField(StandardField.URL)); } @Test void cleanupDoiReturnsChangeWhenDoiInURLField() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_DOI); BibEntry entry = new BibEntry(); entry.setField(StandardField.URL, "http://dx.doi.org/10.1016/0001-8708(80)90035-3"); List<FieldChange> changes = worker.cleanup(preset, entry); List<FieldChange> changeList = new ArrayList<>(); changeList.add(new FieldChange(entry, StandardField.DOI, null, "10.1016/0001-8708(80)90035-3")); changeList.add(new FieldChange(entry, StandardField.URL, "http://dx.doi.org/10.1016/0001-8708(80)90035-3", null)); assertEquals(changeList, changes); } @Test void cleanupMonthChangesNumberToBibtex() { CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.MONTH, new NormalizeMonthFormatter())))); BibEntry entry = new BibEntry(); entry.setField(StandardField.MONTH, "01"); worker.cleanup(preset, entry); assertEquals(Optional.of("#jan#"), entry.getField(StandardField.MONTH)); } @Test void cleanupPageNumbersConvertsSingleDashToDouble() { CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter())))); BibEntry entry = new BibEntry(); entry.setField(StandardField.PAGES, "1-2"); worker.cleanup(preset, entry); assertEquals(Optional.of("1--2"), entry.getField(StandardField.PAGES)); } @Test void cleanupDatesConvertsToCorrectFormat() { CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.DATE, new NormalizeDateFormatter())))); BibEntry entry = new BibEntry(); entry.setField(StandardField.DATE, "01/1999"); worker.cleanup(preset, entry); assertEquals(Optional.of("1999-01"), entry.getField(StandardField.DATE)); } @Test void cleanupFixFileLinksMovesSingleDescriptionToLink() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.FIX_FILE_LINKS); BibEntry entry = new BibEntry(); entry.setField(StandardField.FILE, "link::"); worker.cleanup(preset, entry); assertEquals(Optional.of(":link:"), entry.getField(StandardField.FILE)); } @Test void cleanupMoveFilesMovesFileFromSubfolder(@TempDir Path bibFolder) throws IOException { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.MOVE_PDF); Path path = bibFolder.resolve("AnotherRandomlyNamedFolder"); Files.createDirectory(path); Path tempFile = Files.createFile(path.resolve("test.pdf")); BibEntry entry = new BibEntry(); LinkedFile fileField = new LinkedFile("", tempFile.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); worker.cleanup(preset, entry); LinkedFile newFileField = new LinkedFile("", tempFile.getFileName(), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @Test void cleanupRelativePathsConvertAbsoluteToRelativePath() throws IOException { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.MAKE_PATHS_RELATIVE); Path path = pdfPath.resolve("AnotherRandomlyNamedFile"); Files.createFile(path); BibEntry entry = new BibEntry(); LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); worker.cleanup(preset, entry); LinkedFile newFileField = new LinkedFile("", path.getFileName(), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @Test void cleanupRenamePdfRenamesRelativeFile() throws IOException { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.RENAME_PDF); Path path = pdfPath.resolve("AnotherRandomlyNamedFile.tmp"); Files.createFile(path); BibEntry entry = new BibEntry() .withCitationKey("Toot"); LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); worker.cleanup(preset, entry); LinkedFile newFileField = new LinkedFile("", Path.of("Toot.tmp"), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @Test void cleanupHtmlToLatexConvertsEpsilonToLatex() { CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.TITLE, new HtmlToLatexFormatter())))); BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "&Epsilon;"); worker.cleanup(preset, entry); assertEquals(Optional.of("{{$\\Epsilon$}}"), entry.getField(StandardField.TITLE)); } @Test void cleanupUnitsConvertsOneAmpereToLatex() { CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.TITLE, new UnitsToLatexFormatter())))); BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "1 A"); worker.cleanup(preset, entry); assertEquals(Optional.of("1~{A}"), entry.getField(StandardField.TITLE)); } @Test void cleanupCasesAddsBracketAroundAluminiumGalliumArsenid() { ProtectedTermsLoader protectedTermsLoader = new ProtectedTermsLoader( new ProtectedTermsPreferences(ProtectedTermsLoader.getInternalLists(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); assertNotEquals(Collections.emptyList(), protectedTermsLoader.getProtectedTerms()); CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(true, Collections .singletonList(new FieldFormatterCleanup(StandardField.TITLE, new ProtectTermsFormatter(protectedTermsLoader))))); BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "AlGaAs"); worker.cleanup(preset, entry); assertEquals(Optional.of("{AlGaAs}"), entry.getField(StandardField.TITLE)); } @Test void cleanupLatexMergesTwoLatexMathEnvironments() { CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter())))); BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "$\\alpha$$\\beta$"); worker.cleanup(preset, entry); assertEquals(Optional.of("$\\alpha\\beta$"), entry.getField(StandardField.TITLE)); } @Test void convertToBiblatexMovesAddressToLocation() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CONVERT_TO_BIBLATEX); BibEntry entry = new BibEntry(); entry.setField(StandardField.ADDRESS, "test"); worker.cleanup(preset, entry); assertEquals(Optional.empty(), entry.getField(StandardField.ADDRESS)); assertEquals(Optional.of("test"), entry.getField(StandardField.LOCATION)); } @Test void convertToBiblatexMovesJournalToJournalTitle() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CONVERT_TO_BIBLATEX); BibEntry entry = new BibEntry(); entry.setField(StandardField.JOURNAL, "test"); worker.cleanup(preset, entry); assertEquals(Optional.empty(), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("test"), entry.getField(StandardField.JOURNALTITLE)); } @Test void cleanupWithDisabledFieldFormatterChangesNothing() { CleanupPreferences preset = new CleanupPreferences(new FieldFormatterCleanups(false, Collections.singletonList(new FieldFormatterCleanup(StandardField.MONTH, new NormalizeMonthFormatter())))); BibEntry entry = new BibEntry(); entry.setField(StandardField.MONTH, "01"); worker.cleanup(preset, entry); assertEquals(Optional.of("01"), entry.getField(StandardField.MONTH)); } }
16,334
45.671429
161
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/ConvertToBiblatexCleanupTest.java
package org.jabref.logic.cleanup; import java.util.Optional; 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; public class ConvertToBiblatexCleanupTest { private ConvertToBiblatexCleanup worker; @BeforeEach public void setUp() { worker = new ConvertToBiblatexCleanup(); } @Test public void cleanupMovesYearMonthToDate() { BibEntry entry = new BibEntry(); entry.setField(StandardField.YEAR, "2011"); entry.setField(StandardField.MONTH, "#jan#"); worker.cleanup(entry); assertEquals(Optional.empty(), entry.getField(StandardField.YEAR)); assertEquals(Optional.empty(), entry.getField(StandardField.MONTH)); assertEquals(Optional.of("2011-01"), entry.getField(StandardField.DATE)); } @Test public void cleanupWithDateAlreadyPresentAndDifferentFromYearDoesNothing() { BibEntry entry = new BibEntry(); entry.setField(StandardField.YEAR, "2011"); entry.setField(StandardField.MONTH, "#jan#"); entry.setField(StandardField.DATE, "2012-01"); worker.cleanup(entry); assertEquals(Optional.of("2011"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("#jan#"), entry.getField(StandardField.MONTH)); assertEquals(Optional.of("2012-01"), entry.getField(StandardField.DATE)); } @Test public void cleanupWithDateAlreadyPresentAndDifferentFromMonthDoesNothing() { BibEntry entry = new BibEntry(); entry.setField(StandardField.YEAR, "2011"); entry.setField(StandardField.MONTH, "#jan#"); entry.setField(StandardField.DATE, "2011-02"); worker.cleanup(entry); assertEquals(Optional.of("2011"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("#jan#"), entry.getField(StandardField.MONTH)); assertEquals(Optional.of("2011-02"), entry.getField(StandardField.DATE)); } @Test public void cleanupWithEmptyDateDoesNothing() { BibEntry entry = new BibEntry(); entry.setField(StandardField.YEAR, ""); entry.setField(StandardField.MONTH, ""); entry.setField(StandardField.DATE, ""); worker.cleanup(entry); assertEquals(Optional.empty(), entry.getField(StandardField.YEAR)); assertEquals(Optional.empty(), entry.getField(StandardField.MONTH)); assertEquals(Optional.empty(), entry.getField(StandardField.DATE)); } @Test public void cleanupWithDateAlreadyPresentAndEqualsToYearAndMonth() { BibEntry entry = new BibEntry(); entry.setField(StandardField.YEAR, "2011"); entry.setField(StandardField.MONTH, "#jan#"); entry.setField(StandardField.DATE, "2011-01"); worker.cleanup(entry); assertEquals(Optional.empty(), entry.getField(StandardField.YEAR)); assertEquals(Optional.empty(), entry.getField(StandardField.MONTH)); assertEquals(Optional.of("2011-01"), entry.getField(StandardField.DATE)); } @Test public void cleanupMovesJournalToJournaltitle() { BibEntry entry = new BibEntry().withField(StandardField.JOURNAL, "Best of JabRef"); worker.cleanup(entry); assertEquals(Optional.empty(), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("Best of JabRef"), entry.getField(StandardField.JOURNALTITLE)); } }
3,564
34.29703
96
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/ConvertToBibtexCleanupTest.java
package org.jabref.logic.cleanup; import java.util.Optional; 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; public class ConvertToBibtexCleanupTest { private ConvertToBibtexCleanup worker; @BeforeEach public void setUp() { worker = new ConvertToBibtexCleanup(); } @Test public void cleanupMovesDateToYearAndMonth() { BibEntry entry = new BibEntry().withField(StandardField.DATE, "2011-01"); worker.cleanup(entry); assertEquals(Optional.empty(), entry.getField(StandardField.DATE)); assertEquals(Optional.of("2011"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("#jan#"), entry.getField(StandardField.MONTH)); } @Test public void cleanupWithYearAlreadyPresentDoesNothing() { BibEntry entry = new BibEntry(); entry.setField(StandardField.YEAR, "2011"); entry.setField(StandardField.DATE, "2012"); worker.cleanup(entry); assertEquals(Optional.of("2011"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("2012"), entry.getField(StandardField.DATE)); } @Test public void cleanupMovesJournaltitleToJournal() { BibEntry entry = new BibEntry().withField(StandardField.JOURNALTITLE, "Best of JabRef"); worker.cleanup(entry); assertEquals(Optional.empty(), entry.getField(StandardField.JOURNALTITLE)); assertEquals(Optional.of("Best of JabRef"), entry.getField(StandardField.JOURNAL)); } @Test public void cleanUpDoesntMoveFileField() { String fileField = ":Ambriola2006 - On the Systematic Analysis of Natural Language Requirements with CIRCE.pdf:PDF"; BibEntry entry = new BibEntry().withField(StandardField.FILE, fileField); worker.cleanup(entry); assertEquals(Optional.of(fileField), entry.getField(StandardField.FILE)); } }
2,074
30.923077
124
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/DoiCleanupTest.java
package org.jabref.logic.cleanup; import java.util.stream.Stream; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; 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 DoiCleanupTest { @ParameterizedTest @MethodSource("provideDoiForAllLowers") public void testChangeDoi(BibEntry expected, BibEntry doiInfoField) { DoiCleanup cleanUp = new DoiCleanup(); cleanUp.cleanup(doiInfoField); assertEquals(expected, doiInfoField); } private static Stream<Arguments> provideDoiForAllLowers() { UnknownField unknownField = new UnknownField("ee"); BibEntry doiResult = new BibEntry().withField(StandardField.DOI, "10.1145/2594455"); return Stream.of( // cleanup for Doi field only Arguments.of(doiResult, new BibEntry().withField( StandardField.URL, "https://doi.org/10.1145/2594455")), // cleanup with Doi and URL to all entries Arguments.of(doiResult, new BibEntry() .withField(StandardField.DOI, "10.1145/2594455") .withField(StandardField.URL, "https://doi.org/10.1145/2594455") .withField(StandardField.NOTE, "https://doi.org/10.1145/2594455") .withField(unknownField, "https://doi.org/10.1145/2594455")), // cleanup with Doi and no URL to entries Arguments.of( new BibEntry() .withField(StandardField.DOI, "10.1145/2594455") .withField(StandardField.NOTE, "This is a random note to this Doi") .withField(unknownField, "This is a random ee field for this Doi"), new BibEntry() .withField(StandardField.DOI, "10.1145/2594455") .withField(StandardField.NOTE, "This is a random note to this Doi") .withField(unknownField, "This is a random ee field for this Doi")), // cleanup with spaced Doi Arguments.of(doiResult, new BibEntry() .withField(StandardField.DOI, "10.1145 / 2594455")), // cleanup just Note field with URL Arguments.of(doiResult, new BibEntry() .withField(StandardField.NOTE, "https://doi.org/10.1145/2594455")), // cleanup just ee field with URL Arguments.of(doiResult, new BibEntry() .withField(unknownField, "https://doi.org/10.1145/2594455")), // cleanup of url encoded chars Arguments.of(new BibEntry() .withField(StandardField.DOI, "10.18726/2018_3"), new BibEntry() .withField(unknownField, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3"))); } }
3,217
43.694444
109
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/DoiDecodeCleanupTest.java
package org.jabref.logic.cleanup; import java.util.stream.Stream; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; 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 DoiDecodeCleanupTest { @ParameterizedTest @MethodSource("provideDoiForAllLowers") public void testChangeDoi(BibEntry expected, BibEntry doiInfoField) { DoiCleanup cleanUp = new DoiCleanup(); cleanUp.cleanup(doiInfoField); assertEquals(expected, doiInfoField); } private static Stream<Arguments> provideDoiForAllLowers() { UnknownField unknownField = new UnknownField("ee"); BibEntry doiResult = new BibEntry().withField(StandardField.DOI, "10.18726/2018_3"); return Stream.of( // cleanup for Doi field only Arguments.of(doiResult, new BibEntry().withField( StandardField.URL, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3")), // cleanup with Doi and URL to all entries Arguments.of(doiResult, new BibEntry() .withField(StandardField.DOI, "10.18726/2018%7B%5Ctextunderscore%7D3") .withField(StandardField.URL, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3") .withField(StandardField.NOTE, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3") .withField(unknownField, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3")), // cleanup with Doi and no URL to entries Arguments.of( new BibEntry() .withField(StandardField.DOI, "10.18726/2018_3") .withField(StandardField.NOTE, "This is a random note to this Doi") .withField(unknownField, "This is a random ee field for this Doi"), new BibEntry() .withField(StandardField.DOI, "10.18726/2018_3") .withField(StandardField.NOTE, "This is a random note to this Doi") .withField(unknownField, "This is a random ee field for this Doi")), // cleanup with spaced Doi Arguments.of(doiResult, new BibEntry() .withField(StandardField.DOI, "10.18726/2018%7B%5Ctextunderscore%7D3")), // cleanup just Note field with URL Arguments.of(doiResult, new BibEntry() .withField(StandardField.NOTE, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3")), // cleanup just ee field with URL Arguments.of(doiResult, new BibEntry() .withField(unknownField, "https://doi.org/10.18726/2018%7B%5Ctextunderscore%7D3")) ); } }
3,080
44.985075
113
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/EprintCleanupTest.java
package org.jabref.logic.cleanup; 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; class EprintCleanupTest { @Test void cleanupCompleteEntry() { BibEntry input = new BibEntry() .withField(StandardField.JOURNALTITLE, "arXiv:1502.05795 [math]") .withField(StandardField.NOTE, "arXiv: 1502.05795") .withField(StandardField.URL, "http://arxiv.org/abs/1502.05795") .withField(StandardField.URLDATE, "2018-09-07TZ"); BibEntry expected = new BibEntry() .withField(StandardField.EPRINT, "1502.05795") .withField(StandardField.EPRINTCLASS, "math") .withField(StandardField.EPRINTTYPE, "arxiv"); EprintCleanup cleanup = new EprintCleanup(); cleanup.cleanup(input); assertEquals(expected, input); } }
1,000
31.290323
81
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/FieldFormatterCleanupTest.java
package org.jabref.logic.cleanup; import java.util.HashMap; import java.util.Map; import org.jabref.logic.formatter.bibtexfields.UnicodeToLatexFormatter; import org.jabref.logic.formatter.casechanger.UpperCaseFormatter; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.InternalField; 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 static org.junit.jupiter.api.Assertions.assertEquals; public class FieldFormatterCleanupTest { private BibEntry entry; private Map<Field, String> fieldMap; @BeforeEach public void setUp() { fieldMap = new HashMap<>(); entry = new BibEntry(); entry.setType(StandardEntryType.Article); fieldMap.put(StandardField.TITLE, "JabRef"); fieldMap.put(StandardField.BOOKTITLE, "JabRefBook"); fieldMap.put(StandardField.YEAR, "twohundredsixteen"); fieldMap.put(StandardField.MONTH, "october"); fieldMap.put(StandardField.ABSTRACT, "JabRefAbstract"); fieldMap.put(StandardField.DOI, "jabrefdoi"); fieldMap.put(StandardField.ISSN, "jabrefissn"); entry.setField(fieldMap); } @Test public void testInternalAllField() throws Exception { FieldFormatterCleanup cleanup = new FieldFormatterCleanup(InternalField.INTERNAL_ALL_FIELD, new UpperCaseFormatter()); cleanup.cleanup(entry); assertEquals(fieldMap.get(StandardField.TITLE).toUpperCase(), entry.getField(StandardField.TITLE).get()); assertEquals(fieldMap.get(StandardField.BOOKTITLE).toUpperCase(), entry.getField(StandardField.BOOKTITLE).get()); assertEquals(fieldMap.get(StandardField.YEAR).toUpperCase(), entry.getField(StandardField.YEAR).get()); assertEquals(fieldMap.get(StandardField.MONTH).toUpperCase(), entry.getField(StandardField.MONTH).get()); assertEquals(fieldMap.get(StandardField.ABSTRACT).toUpperCase(), entry.getField(StandardField.ABSTRACT).get()); assertEquals(fieldMap.get(StandardField.DOI).toUpperCase(), entry.getField(StandardField.DOI).get()); assertEquals(fieldMap.get(StandardField.ISSN).toUpperCase(), entry.getField(StandardField.ISSN).get()); } @Test public void testInternalAllTextFieldsField() throws Exception { FieldFormatterCleanup cleanup = new FieldFormatterCleanup(InternalField.INTERNAL_ALL_TEXT_FIELDS_FIELD, new UpperCaseFormatter()); cleanup.cleanup(entry); assertEquals(fieldMap.get(StandardField.TITLE).toUpperCase(), entry.getField(StandardField.TITLE).get()); assertEquals(fieldMap.get(StandardField.BOOKTITLE).toUpperCase(), entry.getField(StandardField.BOOKTITLE).get()); assertEquals(fieldMap.get(StandardField.YEAR), entry.getField(StandardField.YEAR).get()); assertEquals(fieldMap.get(StandardField.MONTH), entry.getField(StandardField.MONTH).get()); assertEquals(fieldMap.get(StandardField.ABSTRACT).toUpperCase(), entry.getField(StandardField.ABSTRACT).get()); assertEquals(fieldMap.get(StandardField.DOI), entry.getField(StandardField.DOI).get()); assertEquals(fieldMap.get(StandardField.ISSN), entry.getField(StandardField.ISSN).get()); } @Test public void testCleanupAllFieldsIgnoresKeyField() throws Exception { FieldFormatterCleanup cleanup = new FieldFormatterCleanup(InternalField.INTERNAL_ALL_FIELD, new UnicodeToLatexFormatter()); entry.setField(InternalField.KEY_FIELD, "François-Marie Arouet"); // Contains ç, not in Basic Latin cleanup.cleanup(entry); assertEquals("François-Marie Arouet", entry.getField(InternalField.KEY_FIELD).get()); } @Test public void testCleanupAllTextFieldsIgnoresKeyField() throws Exception { FieldFormatterCleanup cleanup = new FieldFormatterCleanup(InternalField.INTERNAL_ALL_TEXT_FIELDS_FIELD, new UnicodeToLatexFormatter()); entry.setField(InternalField.KEY_FIELD, "François-Marie Arouet"); // Contains ç, not in Basic Latin cleanup.cleanup(entry); assertEquals("François-Marie Arouet", entry.getField(InternalField.KEY_FIELD).get()); } @Test public void testCleanupKeyFieldCleansUpKeyField() throws Exception { FieldFormatterCleanup cleanup = new FieldFormatterCleanup(InternalField.KEY_FIELD, new UnicodeToLatexFormatter()); entry.setField(InternalField.KEY_FIELD, "François-Marie Arouet"); // Contains ç, not in Basic Latin cleanup.cleanup(entry); assertEquals("Fran{\\c{c}}ois-Marie Arouet", entry.getField(InternalField.KEY_FIELD).get()); } }
4,751
49.021053
143
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/FieldFormatterCleanupsTest.java
package org.jabref.logic.cleanup; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.formatter.IdentityFormatter; import org.jabref.logic.formatter.bibtexfields.EscapeAmpersandsFormatter; import org.jabref.logic.formatter.bibtexfields.EscapeDollarSignFormatter; import org.jabref.logic.formatter.bibtexfields.EscapeUnderscoresFormatter; import org.jabref.logic.formatter.bibtexfields.LatexCleanupFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizeDateFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizeMonthFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import org.jabref.logic.formatter.casechanger.LowerCaseFormatter; import org.jabref.logic.layout.format.ReplaceUnicodeLigaturesFormatter; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; 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 static org.junit.jupiter.api.Assertions.assertEquals; public class FieldFormatterCleanupsTest { private BibEntry entry; @BeforeEach public void setUp() { entry = new BibEntry(StandardEntryType.InProceedings) .withCitationKey("6055279") .withField(StandardField.TITLE, "Educational session 1") .withField(StandardField.BOOKTITLE, "Custom Integrated Circuits Conference (CICC), 2011 IEEE") .withField(StandardField.YEAR, "2011") .withField(StandardField.MONTH, "Sept.") .withField(StandardField.PAGES, "1-7") .withField(StandardField.ABSTRACT, "Start of the above-titled section of the conference proceedings record.") .withField(StandardField.DOI, "10.1109/CICC.2011.6055279") .withField(StandardField.ISSN, "0886-5930"); } @Test public void checkSimpleUseCase() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("title[identity]")); FieldFormatterCleanup identityInTitle = new FieldFormatterCleanup(StandardField.TITLE, new IdentityFormatter()); assertEquals(Collections.singletonList(identityInTitle), actions.getConfiguredActions()); actions.applySaveActions(entry); assertEquals(Optional.of("Educational session 1"), entry.getField(StandardField.TITLE)); } @Test public void invalidSaveActionSting() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("title")); assertEquals(Collections.emptyList(), actions.getConfiguredActions()); actions.applySaveActions(entry); assertEquals(Optional.of("Educational session 1"), entry.getField(StandardField.TITLE)); } @Test public void checkLowerCaseSaveAction() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("title[lower_case]")); FieldFormatterCleanup lowerCaseTitle = new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()); assertEquals(Collections.singletonList(lowerCaseTitle), actions.getConfiguredActions()); actions.applySaveActions(entry); assertEquals(Optional.of("educational session 1"), entry.getField(StandardField.TITLE)); } @Test public void checkTwoSaveActionsForOneField() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("title[lower_case,identity]")); FieldFormatterCleanup lowerCaseTitle = new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()); FieldFormatterCleanup identityInTitle = new FieldFormatterCleanup(StandardField.TITLE, new IdentityFormatter()); assertEquals(Arrays.asList(lowerCaseTitle, identityInTitle), actions.getConfiguredActions()); actions.applySaveActions(entry); assertEquals(Optional.of("educational session 1"), entry.getField(StandardField.TITLE)); } @Test public void checkThreeSaveActionsForOneField() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("title[lower_case,identity,normalize_date]")); FieldFormatterCleanup lowerCaseTitle = new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()); FieldFormatterCleanup identityInTitle = new FieldFormatterCleanup(StandardField.TITLE, new IdentityFormatter()); FieldFormatterCleanup normalizeDatesInTitle = new FieldFormatterCleanup(StandardField.TITLE, new NormalizeDateFormatter()); assertEquals(Arrays.asList(lowerCaseTitle, identityInTitle, normalizeDatesInTitle), actions.getConfiguredActions()); actions.applySaveActions(entry); assertEquals(Optional.of("educational session 1"), entry.getField(StandardField.TITLE)); } @Test public void checkMultipleSaveActions() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("pages[normalize_page_numbers]title[lower_case]")); List<FieldFormatterCleanup> formatterCleanups = actions.getConfiguredActions(); FieldFormatterCleanup normalizePages = new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()); FieldFormatterCleanup lowerCaseTitle = new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()); assertEquals(Arrays.asList(normalizePages, lowerCaseTitle), formatterCleanups); actions.applySaveActions(entry); assertEquals(Optional.of("educational session 1"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("1--7"), entry.getField(StandardField.PAGES)); } @Test public void checkMultipleSaveActionsWithMultipleFormatters() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("pages[normalize_page_numbers,normalize_date]title[lower_case]")); List<FieldFormatterCleanup> formatterCleanups = actions.getConfiguredActions(); FieldFormatterCleanup normalizePages = new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()); FieldFormatterCleanup normalizeDatesInPages = new FieldFormatterCleanup(StandardField.PAGES, new NormalizeDateFormatter()); FieldFormatterCleanup lowerCaseTitle = new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()); assertEquals(Arrays.asList(normalizePages, normalizeDatesInPages, lowerCaseTitle), formatterCleanups); actions.applySaveActions(entry); assertEquals(Optional.of("educational session 1"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("1--7"), entry.getField(StandardField.PAGES)); } @Test public void clearFormatterRemovesField() { FieldFormatterCleanups actions = new FieldFormatterCleanups(true, FieldFormatterCleanups.parse("month[clear]")); actions.applySaveActions(entry); assertEquals(Optional.empty(), entry.getField(StandardField.MONTH)); } @Test void parserKeepsSaveActions() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" month[normalize_month] pages[normalize_page_numbers] title[escapeAmpersands,escapeDollarSign,escapeUnderscores,latex_cleanup] booktitle[escapeAmpersands,escapeDollarSign,escapeUnderscores,latex_cleanup] publisher[escapeAmpersands,escapeDollarSign,escapeUnderscores,latex_cleanup] journal[escapeAmpersands,escapeDollarSign,escapeUnderscores,latex_cleanup] abstract[escapeAmpersands,escapeDollarSign,escapeUnderscores,latex_cleanup] """); List<FieldFormatterCleanup> expected = new ArrayList<>(30); expected.add(new FieldFormatterCleanup(StandardField.MONTH, new NormalizeMonthFormatter())); expected.add(new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter())); for (Field field : List.of(StandardField.TITLE, StandardField.BOOKTITLE, StandardField.PUBLISHER, StandardField.JOURNAL, StandardField.ABSTRACT)) { expected.add(new FieldFormatterCleanup(field, new EscapeAmpersandsFormatter())); expected.add(new FieldFormatterCleanup(field, new EscapeDollarSignFormatter())); expected.add(new FieldFormatterCleanup(field, new EscapeUnderscoresFormatter())); expected.add(new FieldFormatterCleanup(field, new LatexCleanupFormatter())); } assertEquals(expected, fieldFormatterCleanups); } @Test void parserParsesLatexCleanupFormatter() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" title[latex_cleanup] """); assertEquals( List.of(new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter())), fieldFormatterCleanups); } @Test void parserParsesTwoFormatters() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" title[escapeUnderscores,latex_cleanup] """); assertEquals( List.of( new FieldFormatterCleanup(StandardField.TITLE, new EscapeUnderscoresFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter()) ), fieldFormatterCleanups); } @Test void parserParsesFourFormatters() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" title[escapeAmpersands,escapeDollarSign,escapeUnderscores,latex_cleanup] """); assertEquals( List.of( new FieldFormatterCleanup(StandardField.TITLE, new EscapeAmpersandsFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new EscapeDollarSignFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new EscapeUnderscoresFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter()) ), fieldFormatterCleanups); } @Test void parserParsesTwoFormattersWithCommas() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" title[escapeUnderscores,latex_cleanup] booktitle[escapeAmpersands,escapeDollarSign] """); assertEquals( List.of( new FieldFormatterCleanup(StandardField.TITLE, new EscapeUnderscoresFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeAmpersandsFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeDollarSignFormatter()) ), fieldFormatterCleanups); } @Test void parserParsesTwoFormattersOneWithComma() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" pages[normalize_page_numbers] booktitle[escapeAmpersands,escapeDollarSign] """); assertEquals( List.of( new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeAmpersandsFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeDollarSignFormatter()) ), fieldFormatterCleanups); } @Test void parserParsesThreeFormattersTwoWithComma() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" pages[normalize_page_numbers] title[escapeUnderscores,latex_cleanup] booktitle[escapeAmpersands,escapeDollarSign] """); assertEquals( List.of( new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new EscapeUnderscoresFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeAmpersandsFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeDollarSignFormatter()) ), fieldFormatterCleanups); } @Test void parserWithTwoAndThree() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" title[escapeAmpersands,escapeUnderscores,latex_cleanup] booktitle[escapeAmpersands,escapeUnderscores,latex_cleanup] """); List<FieldFormatterCleanup> expected = new ArrayList<>(30); for (Field field : List.of(StandardField.TITLE, StandardField.BOOKTITLE)) { expected.add(new FieldFormatterCleanup(field, new EscapeAmpersandsFormatter())); expected.add(new FieldFormatterCleanup(field, new EscapeUnderscoresFormatter())); expected.add(new FieldFormatterCleanup(field, new LatexCleanupFormatter())); } assertEquals(expected, fieldFormatterCleanups); } @Test void parserWithFourEntries() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" title[escapeUnderscores,latex_cleanup] booktitle[escapeAmpersands,escapeUnderscores,latex_cleanup] """); assertEquals( List.of( new FieldFormatterCleanup(StandardField.TITLE, new EscapeUnderscoresFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeAmpersandsFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeUnderscoresFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new LatexCleanupFormatter()) ), fieldFormatterCleanups); } @Test void parserTest() { List<FieldFormatterCleanup> fieldFormatterCleanups = FieldFormatterCleanups.parse(""" title[escapeAmpersands,escapeUnderscores,latex_cleanup] booktitle[escapeAmpersands,latex_cleanup] """); assertEquals( List.of( new FieldFormatterCleanup(StandardField.TITLE, new EscapeAmpersandsFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new EscapeUnderscoresFormatter()), new FieldFormatterCleanup(StandardField.TITLE, new LatexCleanupFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new EscapeAmpersandsFormatter()), new FieldFormatterCleanup(StandardField.BOOKTITLE, new LatexCleanupFormatter()) ), fieldFormatterCleanups); } @Test void getMetaDataStringWorks() { assertEquals(""" pages[normalize_page_numbers] date[normalize_date] month[normalize_month] all-text-fields[replace_unicode_ligatures] """, FieldFormatterCleanups.getMetaDataString(FieldFormatterCleanups.DEFAULT_SAVE_ACTIONS, "\n")); } @Test void parsingOfDefaultSaveActions() { assertEquals(FieldFormatterCleanups.DEFAULT_SAVE_ACTIONS, FieldFormatterCleanups.parse(""" pages[normalize_page_numbers] date[normalize_date] month[normalize_month] all-text-fields[replace_unicode_ligatures] """)); } @Test void formatterFromString() { assertEquals(new ReplaceUnicodeLigaturesFormatter(), FieldFormatterCleanups.getFormatterFromString("replace_unicode_ligatures")); } }
16,702
48.563798
155
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/ISSNCleanupTest.java
package org.jabref.logic.cleanup; import java.util.Optional; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.CleanupPreferences; 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; public class ISSNCleanupTest { private CleanupWorker worker; @BeforeEach public void setUp() { worker = new CleanupWorker( mock(BibDatabaseContext.class), mock(FilePreferences.class), mock(TimestampPreferences.class)); } @Test public void cleanupISSNReturnsCorrectISSN() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_ISSN); BibEntry entry = new BibEntry(); entry.setField(StandardField.ISSN, "0123-4567"); worker.cleanup(preset, entry); assertEquals(Optional.of("0123-4567"), entry.getField(StandardField.ISSN)); } @Test public void cleanupISSNAddsMissingDash() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_ISSN); BibEntry entry = new BibEntry(); entry.setField(StandardField.ISSN, "01234567"); worker.cleanup(preset, entry); assertEquals(Optional.of("0123-4567"), entry.getField(StandardField.ISSN)); } @Test public void cleanupISSNJunkStaysJunk() { CleanupPreferences preset = new CleanupPreferences(CleanupPreferences.CleanupStep.CLEAN_UP_ISSN); BibEntry entry = new BibEntry(); entry.setField(StandardField.ISSN, "Banana"); worker.cleanup(preset, entry); assertEquals(Optional.of("Banana"), entry.getField(StandardField.ISSN)); } }
2,009
32.5
105
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/MoveFilesCleanupTest.java
package org.jabref.logic.cleanup; 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 java.util.Optional; import org.jabref.logic.bibtex.FileFieldWriter; import org.jabref.model.FieldChange; 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.field.StandardField; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.FilePreferences; 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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class MoveFilesCleanupTest { private Path defaultFileFolder; private Path fileBefore; private MoveFilesCleanup cleanup; private BibEntry entry; private FilePreferences filePreferences; private BibDatabaseContext databaseContext; @BeforeEach void setUp(@TempDir Path bibFolder) throws IOException { // The folder where the files should be moved to defaultFileFolder = bibFolder.resolve("pdf"); Files.createDirectory(defaultFileFolder); // The folder where the files are located originally Path fileFolder = bibFolder.resolve("files"); Files.createDirectory(fileFolder); fileBefore = fileFolder.resolve("test.pdf"); Files.createFile(fileBefore); MetaData metaData = new MetaData(); metaData.setDefaultFileDirectory(defaultFileFolder.toAbsolutePath().toString()); databaseContext = new BibDatabaseContext(new BibDatabase(), metaData); Files.createFile(bibFolder.resolve("test.bib")); databaseContext.setDatabasePath(bibFolder.resolve("test.bib")); entry = new BibEntry(); entry.setCitationKey("Toot"); entry.setField(StandardField.TITLE, "test title"); entry.setField(StandardField.YEAR, "1989"); LinkedFile fileField = new LinkedFile("", fileBefore.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); filePreferences = mock(FilePreferences.class); when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(false); // Biblocation as Primary overwrites all other dirs, therefore we set it to false here cleanup = new MoveFilesCleanup(databaseContext, filePreferences); } @Test void movesFile() { when(filePreferences.getFileDirectoryPattern()).thenReturn(""); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("test.pdf"); assertEquals( Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test void movesFileWithMulitpleLinked() { LinkedFile fileField = new LinkedFile("", fileBefore.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(Arrays.asList( new LinkedFile("", Path.of(""), ""), fileField, new LinkedFile("", Path.of(""), "")))); when(filePreferences.getFileDirectoryPattern()).thenReturn(""); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("test.pdf"); assertEquals( Optional.of(FileFieldWriter.getStringRepresentation( Arrays.asList( new LinkedFile("", Path.of(""), ""), new LinkedFile("", Path.of("test.pdf"), ""), new LinkedFile("", Path.of(""), "")))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test void movesFileWithFileDirPattern() { when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]"); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("Misc").resolve("test.pdf"); assertEquals( Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("Misc/test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test void doesNotMoveFileWithEmptyFileDirPattern() { when(filePreferences.getFileDirectoryPattern()).thenReturn(""); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("test.pdf"); assertEquals( Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test void movesFileWithSubdirectoryPattern() { when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]/[year]/[auth]"); cleanup.cleanup(entry); Path fileAfter = defaultFileFolder.resolve("Misc").resolve("1989").resolve("test.pdf"); assertEquals( Optional.of(FileFieldWriter.getStringRepresentation(new LinkedFile("", Path.of("Misc/1989/test.pdf"), ""))), entry.getField(StandardField.FILE)); assertFalse(Files.exists(fileBefore)); assertTrue(Files.exists(fileAfter)); } @Test void movesFileWithNoDirectory() { databaseContext.setMetaData(new MetaData()); when(filePreferences.getFileDirectoryPattern()).thenReturn(""); List<FieldChange> changes = cleanup.cleanup(entry); assertEquals(Collections.emptyList(), changes); } }
6,236
39.764706
171
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java
package org.jabref.logic.cleanup; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Optional; import org.jabref.logic.bibtex.FileFieldWriter; 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.field.StandardField; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.FilePreferences; 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.mockito.Mockito.mock; import static org.mockito.Mockito.when; class RenamePdfCleanupTest { private BibEntry entry; private FilePreferences filePreferences; private RenamePdfCleanup cleanup; // Ensure that the folder stays the same for all tests. By default @TempDir creates a new folder for each usage private Path testFolder; @BeforeEach void setUp(@TempDir Path testFolder) { this.testFolder = testFolder; Path path = testFolder.resolve("test.bib"); MetaData metaData = new MetaData(); BibDatabaseContext context = new BibDatabaseContext(new BibDatabase(), metaData); context.setDatabasePath(path); entry = new BibEntry(); entry.setCitationKey("Toot"); filePreferences = mock(FilePreferences.class); when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(true); // Set Biblocation as Primary Directory, otherwise the tmp folders won't be cleaned up correctly cleanup = new RenamePdfCleanup(false, context, filePreferences); } /** * Test for #466 */ @Test void cleanupRenamePdfRenamesFileEvenIfOnlyDifferenceIsCase() throws IOException { Path path = testFolder.resolve("toot.tmp"); Files.createFile(path); LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]"); cleanup.cleanup(entry); LinkedFile newFileField = new LinkedFile("", Path.of("Toot.tmp"), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @Test void cleanupRenamePdfRenamesWithMultipleFiles() throws IOException { Path path = testFolder.resolve("Toot.tmp"); Files.createFile(path); entry.setField(StandardField.TITLE, "test title"); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation( Arrays.asList( new LinkedFile("", Path.of(""), ""), new LinkedFile("", path.toAbsolutePath(), ""), new LinkedFile("", Path.of(""), "")))); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey] - [fulltitle]"); cleanup.cleanup(entry); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation( Arrays.asList( new LinkedFile("", Path.of(""), ""), new LinkedFile("", Path.of("Toot - test title.tmp"), ""), new LinkedFile("", Path.of(""), "")))), entry.getField(StandardField.FILE)); } @Test void cleanupRenamePdfRenamesFileStartingWithCitationKey() throws IOException { Path path = testFolder.resolve("Toot.tmp"); Files.createFile(path); LinkedFile fileField = new LinkedFile("", path.toAbsolutePath(), ""); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); entry.setField(StandardField.TITLE, "test title"); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey] - [fulltitle]"); cleanup.cleanup(entry); LinkedFile newFileField = new LinkedFile("", Path.of("Toot - test title.tmp"), ""); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } @Test void cleanupRenamePdfRenamesFileInSameFolder() throws IOException { Path path = testFolder.resolve("Toot.pdf"); Files.createFile(path); LinkedFile fileField = new LinkedFile("", Path.of("Toot.pdf"), "PDF"); entry.setField(StandardField.FILE, FileFieldWriter.getStringRepresentation(fileField)); entry.setField(StandardField.TITLE, "test title"); when(filePreferences.getFileNamePattern()).thenReturn("[citationkey] - [fulltitle]"); cleanup.cleanup(entry); LinkedFile newFileField = new LinkedFile("", Path.of("Toot - test title.pdf"), "PDF"); assertEquals(Optional.of(FileFieldWriter.getStringRepresentation(newFileField)), entry.getField(StandardField.FILE)); } }
5,078
39.959677
180
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/TimeStampToCreationDateTest.java
package org.jabref.logic.cleanup; import java.util.List; import java.util.stream.Stream; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; 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; class TimeStampToCreationDateTest { private static final Field CUSTOM_TIME_STAMP_FIELD = new UnknownField("dateOfCreation"); private final TimestampPreferences timestampPreferences = Mockito.mock(TimestampPreferences.class); public void makeMockReturnCustomField() { Mockito.when(timestampPreferences.getTimestampField()).then(invocation -> CUSTOM_TIME_STAMP_FIELD); } public void makeMockReturnStandardField() { Mockito.when(timestampPreferences.getTimestampField()).then(invocation -> StandardField.TIMESTAMP); } public static Stream<Arguments> standardFieldToCreationDate() { return Stream.of( Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-09-10T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2018-09-10") ), Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2020-12-24T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2020-12-24") ), Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2020-12-31T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2020-12-31") ) ); } /** * Tests migration to creationdate if the users uses the default ISO yyyy-mm-dd format and the standard timestamp field */ @ParameterizedTest @MethodSource("standardFieldToCreationDate") public void withStandardFieldToCreationDate(BibEntry expected, BibEntry input) { makeMockReturnStandardField(); TimeStampToCreationDate migrator = new TimeStampToCreationDate(timestampPreferences); migrator.cleanup(input); assertEquals(expected, input); } public static Stream<Arguments> customFieldToCreationDate() { return Stream.of( Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-09-10T00:00:00"), new BibEntry().withField(CUSTOM_TIME_STAMP_FIELD, "2018-09-10") ), Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2020-12-24T00:00:00"), new BibEntry().withField(CUSTOM_TIME_STAMP_FIELD, "2020-12-24") ), Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2020-12-31T00:00:00"), new BibEntry().withField(CUSTOM_TIME_STAMP_FIELD, "2020-12-31") ) ); } /** * Tests migration to creationdate if the users uses the default ISO yyyy-mm-dd format and a custom timestamp field */ @ParameterizedTest @MethodSource("customFieldToCreationDate") public void withCustomFieldToCreationDate(BibEntry expected, BibEntry input) { makeMockReturnCustomField(); TimeStampToCreationDate migrator = new TimeStampToCreationDate(timestampPreferences); migrator.cleanup(input); assertEquals(expected, input); } public static Stream<Arguments> entriesMigratedToCreationDateFromDifferentFormats() { return Stream.of( // M/y Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-01T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "1/18") ), Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-02-01T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2/2018") ), Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-03-01T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "03/2018") ), // MMMM, yyyy Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-01T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "January, 2018") ), // MMMM dd, yyyy Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-02T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "January 2, 2018") ), Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-12T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "January 12, 2018") ), // dd-MM-yyyy Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-02T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2-1-2018") ), // Double digit day/month Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-12T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "12-01-2018") ), // d.M.uuuu Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-02T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2.1.2018") ), // Double digit day/month Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-12T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "12.01.2018") ), // uuuu.M.d Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-02T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2018.1.2") ), // Double digit day/month Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-12T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2018.01.12") ), // MMM, uuuu Arguments.of( new BibEntry().withField(StandardField.CREATIONDATE, "2018-01-01T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "Jan, 2018") )); } /** * Tests migration of different timestamp formats with the standard timestamp field */ @ParameterizedTest @MethodSource("entriesMigratedToCreationDateFromDifferentFormats") public void withDifferentFormats(BibEntry expected, BibEntry input) { makeMockReturnStandardField(); TimeStampToCreationDate migrator = new TimeStampToCreationDate(timestampPreferences); ParserResult parserResult = new ParserResult(List.of(input)); migrator.cleanup(input); assertEquals(expected, input); } }
7,949
43.166667
123
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/TimeStampToModificationDateTest.java
package org.jabref.logic.cleanup; import java.util.stream.Stream; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; 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; class TimeStampToModificationDateTest { private static Field customTimeStampField = new UnknownField("dateOfCreation"); private TimestampPreferences timestampPreferences = Mockito.mock(TimestampPreferences.class); public void makeMockReturnCustomField() { Mockito.when(timestampPreferences.getTimestampField()).then(invocation -> customTimeStampField); } public void makeMockReturnStandardField() { Mockito.when(timestampPreferences.getTimestampField()).then(invocation -> StandardField.TIMESTAMP); } public static Stream<Arguments> standardFieldToModificationDate() { return Stream.of( Arguments.of( new BibEntry().withField(StandardField.MODIFICATIONDATE, "2018-09-10T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2018-09-10") ), Arguments.of( new BibEntry().withField(StandardField.MODIFICATIONDATE, "2020-12-24T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2020-12-24") ), Arguments.of( new BibEntry().withField(StandardField.MODIFICATIONDATE, "2020-12-31T00:00:00"), new BibEntry().withField(StandardField.TIMESTAMP, "2020-12-31") ) ); } /** * Tests migration to field "modificationdate" if the users uses the default ISO yyyy-mm-dd format and the standard timestamp field */ @ParameterizedTest @MethodSource("standardFieldToModificationDate") public void withStandardFieldToModificationDate(BibEntry expected, BibEntry input) { makeMockReturnStandardField(); TimeStampToModificationDate migrator = new TimeStampToModificationDate(timestampPreferences); migrator.cleanup(input); assertEquals(expected, input); } public static Stream<Arguments> customFieldToModificationDate() { return Stream.of( Arguments.of( new BibEntry().withField(StandardField.MODIFICATIONDATE, "2018-09-10T00:00:00"), new BibEntry().withField(customTimeStampField, "2018-09-10") ), Arguments.of( new BibEntry().withField(StandardField.MODIFICATIONDATE, "2020-12-24T00:00:00"), new BibEntry().withField(customTimeStampField, "2020-12-24") ), Arguments.of( new BibEntry().withField(StandardField.MODIFICATIONDATE, "2020-12-31T00:00:00"), new BibEntry().withField(customTimeStampField, "2020-12-31") ) ); } /** * Tests migration to field "modificationdate" if the users uses the default ISO yyyy-mm-dd format and a custom timestamp field */ @ParameterizedTest @MethodSource("customFieldToModificationDate") public void withCustomFieldToModificationDate(BibEntry expected, BibEntry input) { makeMockReturnCustomField(); TimeStampToModificationDate migrator = new TimeStampToModificationDate(timestampPreferences); migrator.cleanup(input); assertEquals(expected, input); } }
3,842
41.7
135
java
null
jabref-main/src/test/java/org/jabref/logic/cleanup/URLCleanupTest.java
package org.jabref.logic.cleanup; import java.util.stream.Stream; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; 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 URLCleanupTest { @ParameterizedTest @MethodSource("provideURL") public void testChangeURL(BibEntry expected, BibEntry urlInputField) { URLCleanup cleanUp = new URLCleanup(); cleanUp.cleanup(urlInputField); assertEquals(expected, urlInputField); } private static Stream<Arguments> provideURL() { return Stream.of( // Input Note field has two arguments stored , with the latter being a url. Arguments.of( new BibEntry().withField(StandardField.URL, "https://hdl.handle.net/10442/hedi/6089") .withField(StandardField.NOTE, "this is a note"), new BibEntry().withField(StandardField.NOTE, "this is a note, \\url{https://hdl.handle.net/10442/hedi/6089}")), // Input Note field has two arguments stored, with the former being a url. Arguments.of( new BibEntry().withField(StandardField.URL, "https://hdl.handle.net/10442/hedi/6089") .withField(StandardField.NOTE, "this is a note"), new BibEntry().withField(StandardField.NOTE, "\\url{https://hdl.handle.net/10442/hedi/6089}, this is a note")), // Input Note field has more than one URLs stored. Arguments.of( new BibEntry().withField(StandardField.URL, "https://hdl.handle.net/10442/hedi/6089") .withField(StandardField.NOTE, "\\url{http://142.42.1.1:8080}"), new BibEntry().withField(StandardField.NOTE, "\\url{https://hdl.handle.net/10442/hedi/6089}, " + "\\url{http://142.42.1.1:8080}")), // Input entry holds the same URL both in Note and Url field. Arguments.of( new BibEntry().withField(StandardField.URL, "https://hdl.handle.net/10442/hedi/6089"), new BibEntry().withField(StandardField.NOTE, "\\url{https://hdl.handle.net/10442/hedi/6089}") .withField(StandardField.URL, "https://hdl.handle.net/10442/hedi/6089")), // Input Note field has several values stored. Arguments.of( new BibEntry().withField(StandardField.URL, "https://example.org") .withField(StandardField.NOTE, "cited by Kramer, 2002."), new BibEntry().withField(StandardField.NOTE, "\\url{https://example.org}, cited by Kramer, 2002.")), /* * Several input URL types (e.g, not secure protocol, password included for * authentication, IP address, port etc.) to be correctly identified. */ Arguments.of( new BibEntry().withField(StandardField.URL, "https://hdl.handle.net/10442/hedi/6089"), new BibEntry().withField(StandardField.NOTE, "\\url{https://hdl.handle.net/10442/hedi/6089}")), Arguments.of( new BibEntry().withField(StandardField.URL, "http://hdl.handle.net/10442/hedi/6089"), new BibEntry().withField(StandardField.NOTE, "\\url{http://hdl.handle.net/10442/hedi/6089}")), Arguments.of( new BibEntry().withField(StandardField.URL, "http://userid:password@example.com:8080"), new BibEntry().withField(StandardField.NOTE, "\\url{http://userid:password@example.com:8080}")), Arguments.of( new BibEntry().withField(StandardField.URL, "http://142.42.1.1:8080"), new BibEntry().withField(StandardField.NOTE, "\\url{http://142.42.1.1:8080}")), Arguments.of( new BibEntry().withField(StandardField.URL, "http://☺.damowmow.com"), new BibEntry().withField(StandardField.NOTE, "\\url{http://☺.damowmow.com}")), Arguments.of( new BibEntry().withField(StandardField.URL, "http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com"), new BibEntry().withField(StandardField.NOTE, "\\url{http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com}")), Arguments.of( new BibEntry().withField(StandardField.URL, "https://www.example.com/foo/?bar=baz&inga=42&quux"), new BibEntry().withField(StandardField.NOTE, "\\url{https://www.example.com/foo/?bar=baz&inga=42&quux}")), Arguments.of( new BibEntry().withField(StandardField.URL, "https://www.example.com/foo/?bar=baz&inga=42&quux"), new BibEntry().withField(StandardField.NOTE, "https://www.example.com/foo/?bar=baz&inga=42&quux")), // Expected entry returns formatted the url-date in the Urldate field. Arguments.of( new BibEntry().withField(StandardField.URL, "http://142.42.1.1:8080") .withField(StandardField.URLDATE, "2021-01-15"), new BibEntry().withField(StandardField.NOTE, "\\url{http://142.42.1.1:8080}, accessed on January 15, 2021")), // Input entry doesn't hold any URL in the Note field. Arguments.of( new BibEntry().withField(StandardField.NOTE, "Accessed on 2015-01-15"), new BibEntry().withField(StandardField.NOTE, "Accessed on 2015-01-15")), // Input entry has multiple url-dates stored in the Note field. Arguments.of( new BibEntry().withField(StandardField.URL, "http://142.42.1.1:8080") .withField(StandardField.URLDATE, "2021-01-15") .withField(StandardField.NOTE, "visited on February 12, 2017"), new BibEntry().withField(StandardField.NOTE, "\\url{http://142.42.1.1:8080}, accessed on January 15, 2021, visited on February 12, 2017")), // Input entry holds the same url-date in both Note and Urldate field. Arguments.of( new BibEntry().withField(StandardField.URL, "http://142.42.1.1:8080") .withField(StandardField.URLDATE, "2015-01-15"), new BibEntry().withField(StandardField.NOTE, "\\url{http://142.42.1.1:8080}, visited on 2015.01.15") .withField(StandardField.URLDATE, "2015-01-15")), // Input Note field has several values stored. Arguments.of( new BibEntry().withField(StandardField.URL, "https://example.org") .withField(StandardField.URLDATE, "2023-04-11") .withField(StandardField.NOTE, "cited by Kramer"), new BibEntry().withField(StandardField.NOTE, "\\url{https://example.org}, cited by Kramer, accessed on 2023-04-11")) ); } }
8,882
49.186441
130
java
null
jabref-main/src/test/java/org/jabref/logic/crawler/CrawlerTest.java
package org.jabref.logic.crawler; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.exporter.SaveConfiguration; import org.jabref.logic.git.SlrGitHandler; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.metadata.SaveOrder; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.jabref.testutils.category.FetcherTest; import org.eclipse.jgit.api.Git; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.jabref.logic.citationkeypattern.CitationKeyGenerator.DEFAULT_UNWANTED_CHARACTERS; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Integration test of the components used for SLR support * Marked as FetcherTest as it calls fetcher */ @FetcherTest class CrawlerTest { @TempDir Path tempRepositoryDirectory; ImportFormatPreferences importFormatPreferences; ImporterPreferences importerPreferences; SaveConfiguration saveConfiguration; BibEntryTypesManager entryTypesManager; SlrGitHandler gitHandler = mock(SlrGitHandler.class, Answers.RETURNS_DEFAULTS); String hashCodeQuantum = String.valueOf("Quantum".hashCode()); String hashCodeCloudComputing = String.valueOf("Cloud Computing".hashCode()); PreferencesService preferencesService = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS); /** * Set up mocks and copies the study definition file into the test repository */ @BeforeEach public void setUp() throws Exception { setUpRepository(); CitationKeyPatternPreferences citationKeyPatternPreferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A, "", "", DEFAULT_UNWANTED_CHARACTERS, GlobalCitationKeyPattern.fromPattern("[auth][year]"), "", ','); importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); importerPreferences = mock(ImporterPreferences.class); saveConfiguration = mock(SaveConfiguration.class, Answers.RETURNS_DEEP_STUBS); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); when(saveConfiguration.useMetadataSaveOrder()).thenReturn(true); when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); when(preferencesService.getCitationKeyPatternPreferences()).thenReturn(citationKeyPatternPreferences); entryTypesManager = new BibEntryTypesManager(); } private void setUpRepository() throws Exception { Git git = Git.init() .setDirectory(tempRepositoryDirectory.toFile()) .call(); setUpTestStudyDefinitionFile(); git.add() .addFilepattern(".") .call(); git.commit() .setMessage("Initialize") .call(); git.close(); } private void setUpTestStudyDefinitionFile() throws Exception { Path destination = tempRepositoryDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME); URL studyDefinition = this.getClass().getResource(StudyRepository.STUDY_DEFINITION_FILE_NAME); FileUtil.copyFile(Path.of(studyDefinition.toURI()), destination, false); } @Test public void testWhetherAllFilesAreCreated() throws Exception { Crawler testCrawler = new Crawler(getPathToStudyDefinitionFile(), gitHandler, preferencesService, entryTypesManager, new DummyFileUpdateMonitor()); testCrawler.performCrawl(); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeQuantum + " - Quantum"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeCloudComputing + " - Cloud Computing"))); List<String> filesToAssert = List.of("ArXiv.bib", "Springer.bib", "result.bib", "Medline_PubMed.bib"); filesToAssert.forEach( fileName -> { assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeQuantum + " - Quantum", fileName))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeCloudComputing + " - Cloud Computing", fileName))); }); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), "studyResult.bib"))); } private Path getPathToStudyDefinitionFile() { return tempRepositoryDirectory; } }
5,373
40.338462
147
java
null
jabref-main/src/test/java/org/jabref/logic/crawler/StudyCatalogToFetcherConverterTest.java
package org.jabref.logic.crawler; import java.net.URL; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import javafx.collections.FXCollections; import org.jabref.logic.exporter.SaveConfiguration; import org.jabref.logic.git.SlrGitHandler; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.metadata.SaveOrder; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class StudyCatalogToFetcherConverterTest { SaveConfiguration saveConfiguration; PreferencesService preferencesService; BibEntryTypesManager entryTypesManager; SlrGitHandler gitHandler; @TempDir Path tempRepositoryDirectory; @BeforeEach void setUpMocks() { preferencesService = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS); saveConfiguration = mock(SaveConfiguration.class, Answers.RETURNS_DEEP_STUBS); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); when(saveConfiguration.useMetadataSaveOrder()).thenReturn(true); when(preferencesService.getBibEntryPreferences().getKeywordSeparator()).thenReturn(','); when(preferencesService.getImporterPreferences().getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); entryTypesManager = new BibEntryTypesManager(); gitHandler = mock(SlrGitHandler.class, Answers.RETURNS_DEFAULTS); } @Test public void getActiveFetcherInstances() throws Exception { Path studyDefinition = tempRepositoryDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME); copyTestStudyDefinitionFileIntoDirectory(studyDefinition); StudyRepository studyRepository = new StudyRepository( tempRepositoryDirectory, gitHandler, preferencesService, new DummyFileUpdateMonitor(), entryTypesManager); StudyCatalogToFetcherConverter converter = new StudyCatalogToFetcherConverter( studyRepository.getActiveLibraryEntries(), mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), mock(ImporterPreferences.class)); List<SearchBasedFetcher> result = converter.getActiveFetchers(); Assertions.assertEquals( List.of("Springer", "ArXiv", "Medline/PubMed"), result.stream().map(SearchBasedFetcher::getName).collect(Collectors.toList()) ); } private void copyTestStudyDefinitionFileIntoDirectory(Path destination) throws Exception { URL studyDefinition = this.getClass().getResource(StudyRepository.STUDY_DEFINITION_FILE_NAME); FileUtil.copyFile(Path.of(studyDefinition.toURI()), destination, false); } }
3,285
40.594937
118
java
null
jabref-main/src/test/java/org/jabref/logic/crawler/StudyRepositoryTest.java
package org.jabref.logic.crawler; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.database.DatabaseMerger; import org.jabref.logic.exporter.SaveConfiguration; import org.jabref.logic.git.SlrGitHandler; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.study.FetchResult; import org.jabref.model.study.QueryResult; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.preferences.LibraryPreferences; import org.jabref.preferences.PreferencesService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.jabref.logic.citationkeypattern.CitationKeyGenerator.DEFAULT_UNWANTED_CHARACTERS; 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; class StudyRepositoryTest { private static final String NON_EXISTING_DIRECTORY = "nonExistingTestRepositoryDirectory"; CitationKeyPatternPreferences citationKeyPatternPreferences; PreferencesService preferencesService; LibraryPreferences libraryPreferences; ImportFormatPreferences importFormatPreferences; SaveConfiguration saveConfiguration; BibEntryTypesManager entryTypesManager; @TempDir Path tempRepositoryDirectory; StudyRepository studyRepository; SlrGitHandler gitHandler = mock(SlrGitHandler.class, Answers.RETURNS_DEFAULTS); String hashCodeQuantum = String.valueOf("Quantum".hashCode()); String hashCodeCloudComputing = String.valueOf("Cloud Computing".hashCode()); String hashCodeSoftwareEngineering = String.valueOf("\"Software Engineering\"".hashCode()); /** * Set up mocks */ @BeforeEach public void setUpMocks() throws Exception { libraryPreferences = mock(LibraryPreferences.class, Answers.RETURNS_DEEP_STUBS); saveConfiguration = mock(SaveConfiguration.class, Answers.RETURNS_DEEP_STUBS); importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); preferencesService = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS); citationKeyPatternPreferences = new CitationKeyPatternPreferences( false, false, false, CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A, "", "", DEFAULT_UNWANTED_CHARACTERS, GlobalCitationKeyPattern.fromPattern("[auth][year]"), "", ','); when(preferencesService.getCitationKeyPatternPreferences()).thenReturn(citationKeyPatternPreferences); when(preferencesService.getImporterPreferences().getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); when(preferencesService.getImportFormatPreferences()).thenReturn(importFormatPreferences); when(preferencesService.getTimestampPreferences().getTimestampField()).then(invocation -> StandardField.TIMESTAMP); entryTypesManager = new BibEntryTypesManager(); getTestStudyRepository(); } @Test void providePathToNonExistentRepositoryThrowsException() { Path nonExistingRepositoryDirectory = tempRepositoryDirectory.resolve(NON_EXISTING_DIRECTORY); assertThrows(IOException.class, () -> new StudyRepository( nonExistingRepositoryDirectory, gitHandler, preferencesService, new DummyFileUpdateMonitor(), entryTypesManager)); } /** * Tests whether the file structure of the repository is created correctly from the study definitions file. */ @Test void repositoryStructureCorrectlyCreated() { // When repository is instantiated the directory structure is created assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeQuantum + " - Quantum"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeCloudComputing + " - Cloud Computing"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeSoftwareEngineering + " - Software Engineering"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeQuantum + " - Quantum", "ArXiv.bib"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeCloudComputing + " - Cloud Computing", "ArXiv.bib"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeSoftwareEngineering + " - Software Engineering", "ArXiv.bib"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeQuantum + " - Quantum", "Springer.bib"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeCloudComputing + " - Cloud Computing", "Springer.bib"))); assertTrue(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeSoftwareEngineering + " - Software Engineering", "Springer.bib"))); assertFalse(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeQuantum + " - Quantum", "IEEEXplore.bib"))); assertFalse(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeCloudComputing + " - Cloud Computing", "IEEEXplore.bib"))); assertFalse(Files.exists(Path.of(tempRepositoryDirectory.toString(), hashCodeSoftwareEngineering + " - Software Engineering", "IEEEXplore.bib"))); } /** * This tests whether the repository returns the stored bib entries correctly. */ @Test void bibEntriesCorrectlyStored() throws Exception { setUpTestResultFile(); List<BibEntry> result = studyRepository.getFetcherResultEntries("Quantum", "ArXiv").getEntries(); assertEquals(getArXivQuantumMockResults(), result); } @Test void fetcherResultsPersistedCorrectly() throws Exception { List<QueryResult> mockResults = getMockResults(); studyRepository.persist(mockResults); assertEquals(getArXivQuantumMockResults(), getTestStudyRepository().getFetcherResultEntries("Quantum", "ArXiv").getEntries()); assertEquals(getSpringerQuantumMockResults(), getTestStudyRepository().getFetcherResultEntries("Quantum", "Springer").getEntries()); assertEquals(getSpringerCloudComputingMockResults(), getTestStudyRepository().getFetcherResultEntries("Cloud Computing", "Springer").getEntries()); } @Test void mergedResultsPersistedCorrectly() throws Exception { List<QueryResult> mockResults = getMockResults(); List<BibEntry> expected = new ArrayList<>(); expected.addAll(getArXivQuantumMockResults()); expected.add(getSpringerQuantumMockResults().get(1)); expected.add(getSpringerQuantumMockResults().get(2)); studyRepository.persist(mockResults); // All Springer results are duplicates for "Quantum" assertEquals(expected, getTestStudyRepository().getQueryResultEntries("Quantum").getEntries()); assertEquals(getSpringerCloudComputingMockResults(), getTestStudyRepository().getQueryResultEntries("Cloud Computing").getEntries()); } @Test void studyResultsPersistedCorrectly() throws Exception { List<QueryResult> mockResults = getMockResults(); studyRepository.persist(mockResults); assertEquals(new HashSet<>(getNonDuplicateBibEntryResult().getEntries()), new HashSet<>(getTestStudyRepository().getStudyResultEntries().getEntries())); } private StudyRepository getTestStudyRepository() throws Exception { setUpTestStudyDefinitionFile(); studyRepository = new StudyRepository( tempRepositoryDirectory, gitHandler, preferencesService, new DummyFileUpdateMonitor(), entryTypesManager); return studyRepository; } /** * Copies the study definition file into the test repository */ private void setUpTestStudyDefinitionFile() throws Exception { Path destination = tempRepositoryDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME); URL studyDefinition = this.getClass().getResource(StudyRepository.STUDY_DEFINITION_FILE_NAME); FileUtil.copyFile(Path.of(studyDefinition.toURI()), destination, false); } /** * This overwrites the existing result file in the repository with a result file containing multiple BibEntries. * The repository has to exist before this method is called. */ private void setUpTestResultFile() throws Exception { Path queryDirectory = Path.of(tempRepositoryDirectory.toString(), hashCodeQuantum + " - Quantum"); Path resultFileLocation = Path.of(queryDirectory.toString(), "ArXiv" + ".bib"); URL resultFile = this.getClass().getResource("ArXivQuantumMock.bib"); FileUtil.copyFile(Path.of(resultFile.toURI()), resultFileLocation, true); resultFileLocation = Path.of(queryDirectory.toString(), "Springer" + ".bib"); resultFile = this.getClass().getResource("SpringerQuantumMock.bib"); FileUtil.copyFile(Path.of(resultFile.toURI()), resultFileLocation, true); } private BibDatabase getNonDuplicateBibEntryResult() { BibDatabase mockResults = new BibDatabase(getSpringerCloudComputingMockResults()); DatabaseMerger merger = new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()); merger.merge(mockResults, new BibDatabase(getSpringerQuantumMockResults())); merger.merge(mockResults, new BibDatabase(getArXivQuantumMockResults())); return mockResults; } private List<QueryResult> getMockResults() { QueryResult resultQuantum = new QueryResult("Quantum", List.of( new FetchResult("ArXiv", new BibDatabase(stripCitationKeys(getArXivQuantumMockResults()))), new FetchResult("Springer", new BibDatabase(stripCitationKeys(getSpringerQuantumMockResults()))))); QueryResult resultCloudComputing = new QueryResult("Cloud Computing", List.of(new FetchResult("Springer", new BibDatabase(getSpringerCloudComputingMockResults())))); return List.of(resultQuantum, resultCloudComputing); } /** * Strips the citation key from fetched entries as these normally do not have a citation key */ private List<BibEntry> stripCitationKeys(List<BibEntry> entries) { entries.forEach(bibEntry -> bibEntry.setCitationKey("")); return entries; } private List<BibEntry> getArXivQuantumMockResults() { BibEntry entry1 = new BibEntry() .withCitationKey("Blaha") .withField(StandardField.AUTHOR, "Stephen Blaha") .withField(StandardField.TITLE, "Quantum Computers and Quantum Computer Languages: Quantum Assembly Language and Quantum C Language"); entry1.setType(StandardEntryType.Article); BibEntry entry2 = new BibEntry() .withCitationKey("Kaye") .withField(StandardField.AUTHOR, "Phillip Kaye and Michele Mosca") .withField(StandardField.TITLE, "Quantum Networks for Generating Arbitrary Quantum States"); entry2.setType(StandardEntryType.Article); BibEntry entry3 = new BibEntry() .withCitationKey("Watrous") .withField(StandardField.AUTHOR, "John Watrous") .withField(StandardField.TITLE, "Quantum Computational Complexity"); entry3.setType(StandardEntryType.Article); return List.of(entry1, entry2, entry3); } private List<BibEntry> getSpringerQuantumMockResults() { // This is a duplicate of entry 1 of ArXiv BibEntry entry1 = new BibEntry() .withCitationKey("Blaha") .withField(StandardField.AUTHOR, "Stephen Blaha") .withField(StandardField.TITLE, "Quantum Computers and Quantum Computer Languages: Quantum Assembly Language and Quantum C Language"); entry1.setType(StandardEntryType.Article); BibEntry entry2 = new BibEntry() .withCitationKey("Kroeger") .withField(StandardField.AUTHOR, "H. Kröger") .withField(StandardField.TITLE, "Nonlinear Dynamics In Quantum Physics -- Quantum Chaos and Quantum Instantons"); entry2.setType(StandardEntryType.Article); BibEntry entry3 = new BibEntry() .withField(StandardField.AUTHOR, "Zieliński, Cezary") .withField(StandardField.TITLE, "Automatic Control, Robotics, and Information Processing"); entry3.setType(StandardEntryType.Article); CitationKeyGenerator citationKeyGenerator = new CitationKeyGenerator(new BibDatabaseContext(), citationKeyPatternPreferences); citationKeyGenerator.generateAndSetKey(entry3); return List.of(entry1, entry2, entry3); } private List<BibEntry> getSpringerCloudComputingMockResults() { BibEntry entry1 = new BibEntry() .withCitationKey("Gritzalis") .withField(StandardField.AUTHOR, "Gritzalis, Dimitris and Stergiopoulos, George and Vasilellis, Efstratios and Anagnostopoulou, Argiro") .withField(StandardField.TITLE, "Readiness Exercises: Are Risk Assessment Methodologies Ready for the Cloud?"); entry1.setType(StandardEntryType.Article); BibEntry entry2 = new BibEntry() .withCitationKey("Rangras") .withField(StandardField.AUTHOR, "Rangras, Jimit and Bhavsar, Sejal") .withField(StandardField.TITLE, "Design of Framework for Disaster Recovery in Cloud Computing"); entry2.setType(StandardEntryType.Article); return List.of(entry1, entry2); } }
14,893
51.815603
173
java
null
jabref-main/src/test/java/org/jabref/logic/crawler/StudyYamlParserTest.java
package org.jabref.logic.crawler; import java.net.URL; import java.nio.file.Path; import java.util.List; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.study.Study; import org.jabref.model.study.StudyDatabase; import org.jabref.model.study.StudyQuery; 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; class StudyYamlParserTest { @TempDir static Path testDirectory; Study expectedStudy; @BeforeEach void setupStudy() throws Exception { Path destination = testDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME); URL studyDefinition = StudyYamlParser.class.getResource(StudyRepository.STUDY_DEFINITION_FILE_NAME); FileUtil.copyFile(Path.of(studyDefinition.toURI()), destination, true); List<String> authors = List.of("Jab Ref"); String studyName = "TestStudyName"; List<String> researchQuestions = List.of("Question1", "Question2"); List<StudyQuery> queryEntries = List.of(new StudyQuery("Quantum"), new StudyQuery("Cloud Computing"), new StudyQuery("\"Software Engineering\"")); List<StudyDatabase> libraryEntries = List.of(new StudyDatabase("Springer", true), new StudyDatabase("ArXiv", true), new StudyDatabase("Medline/PubMed", true), new StudyDatabase("IEEEXplore", false)); expectedStudy = new Study(authors, studyName, researchQuestions, queryEntries, libraryEntries); } @Test public void parseStudyFileSuccessfully() throws Exception { Study study = new StudyYamlParser().parseStudyYamlFile(testDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME)); assertEquals(expectedStudy, study); } @Test public void writeStudyFileSuccessfully() throws Exception { new StudyYamlParser().writeStudyYamlFile(expectedStudy, testDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME)); Study study = new StudyYamlParser().parseStudyYamlFile(testDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME)); assertEquals(expectedStudy, study); } @Test public void readsJabRef57StudySuccessfully() throws Exception { // The field "last-search-date" was removed // If the field is "just" removed from the datamodel, one gets following exception: // com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "last-search-date" (class org.jabref.model.study.Study), not marked as ignorable (5 known properties: "authors", "research-questions", "queries", "title", "databases"]) // This tests ensures that this exception does not occur URL studyDefinition = StudyYamlParser.class.getResource("study-jabref-5.7.yml"); Study study = new StudyYamlParser().parseStudyYamlFile(Path.of(studyDefinition.toURI())); assertEquals(expectedStudy, study); } }
2,993
45.78125
266
java
null
jabref-main/src/test/java/org/jabref/logic/database/DatabaseMergerTest.java
package org.jabref.logic.database; import java.util.List; import java.util.stream.Collectors; import org.jabref.logic.bibtex.comparator.BibtexStringComparator; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibtexString; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; 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.jabref.model.metadata.ContentSelector; import org.jabref.model.metadata.MetaData; 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 DatabaseMergerTest { private ImportFormatPreferences importFormatPreferences; @BeforeEach void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); } @Test void mergeAddsNonDuplicateEntries() { // Entries 1 and 2 are identical BibEntry entry1 = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Phillip Kaye and Michele Mosca") .withField(StandardField.TITLE, "Quantum Networks for Generating Arbitrary Quantum States"); BibEntry entry2 = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Phillip Kaye and Michele Mosca") .withField(StandardField.TITLE, "Quantum Networks for Generating Arbitrary Quantum States"); BibEntry entry3 = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Stephen Blaha") .withField(StandardField.TITLE, "Quantum Computers and Quantum Computer Languages: Quantum Assembly Language and Quantum C Language"); BibDatabase database = new BibDatabase(List.of(entry1)); BibDatabase other = new BibDatabase(List.of(entry2, entry3)); new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).merge(database, other); assertEquals(List.of(entry1, entry3), database.getEntries()); } @Test void mergeAddsWithDuplicateEntries() { // Entries 1 and 2 are identical, Entries 3 and 4 are identical BibEntry entry1 = new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Joshua Bloch") .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.ISBN, "0-201-31005-8"); BibEntry entry2 = new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Joshua J. Bloch") .withField(StandardField.TITLE, "Effective Java:Programming Language Guide") .withField(StandardField.ISBN, "0-201-31005-8") .withField(StandardField.YEAR, "2001") .withField(StandardField.EDITION, "1"); BibEntry entry3 = new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Joshua J. Bloch") .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.ISBN, "978-0-321-35668-0") .withField(StandardField.YEAR, "2008") .withField(StandardField.EDITION, "2"); BibEntry entry4 = new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Joshua Bloch") .withField(StandardField.TITLE, "Effective Java:Programming Language Guide") .withField(StandardField.ISBN, "978-0-321-35668-0"); BibDatabase database = new BibDatabase(List.of(entry1, entry4)); BibDatabase other = new BibDatabase(List.of(entry2, entry3)); new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).merge(database, other); assertEquals(List.of(entry1, entry4), database.getEntries()); } @Test void mergeBibTexStringsWithSameNameAreImportedWithModifiedName() { BibtexString targetString = new BibtexString("name", "content1"); // BibTeXStrings that are imported from two sources (same name different content) BibtexString sourceString1 = new BibtexString("name", "content2"); BibtexString sourceString2 = new BibtexString("name", "content3"); // The expected source BibTeXStrings after import (different name, different content) BibtexString importedBibTeXString1 = new BibtexString("name_1", "content2"); BibtexString importedBibTeXString2 = new BibtexString("name_2", "content3"); BibDatabase target = new BibDatabase(); BibDatabase source1 = new BibDatabase(); BibDatabase source2 = new BibDatabase(); target.addString(targetString); source1.addString(sourceString1); source2.addString(sourceString2); new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).mergeStrings(target, source1); new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).mergeStrings(target, source2); // Use string representation to compare since the id will not match List<String> resultStringsSorted = target.getStringValues() .stream() .map(BibtexString::toString) .sorted() .collect(Collectors.toList()); assertEquals(List.of(targetString.toString(), importedBibTeXString1.toString(), importedBibTeXString2.toString()), resultStringsSorted); } @Test void mergeBibTexStringsWithSameNameAndContentAreIgnored() { BibtexString targetString1 = new BibtexString("name1", "content1"); BibtexString targetString2 = new BibtexString("name2", "content2"); // BibTeXStrings that are imported (equivalent to target strings) BibtexString sourceString1 = new BibtexString("name1", "content1"); BibtexString sourceString2 = new BibtexString("name2", "content2"); BibDatabase target = new BibDatabase(); BibDatabase source = new BibDatabase(); target.addString(targetString1); target.addString(targetString2); source.addString(sourceString1); source.addString(sourceString2); new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).mergeStrings(target, source); List<BibtexString> resultStringsSorted = target.getStringValues() .stream() .sorted(new BibtexStringComparator(false)::compare) .collect(Collectors.toList()); assertEquals(List.of(targetString1, targetString2), resultStringsSorted); } @Test void mergeMetaDataWithoutAllEntriesGroup() { MetaData target = new MetaData(); target.addContentSelector(new ContentSelector(StandardField.AUTHOR, List.of("Test Author"))); GroupTreeNode targetRootGroup = new GroupTreeNode(new ExplicitGroup("targetGroup", GroupHierarchyType.INDEPENDENT, ',')); target.setGroups(targetRootGroup); MetaData other = new MetaData(); GroupTreeNode otherRootGroup = new GroupTreeNode(new ExplicitGroup("otherGroup", GroupHierarchyType.INCLUDING, ',')); other.setGroups(otherRootGroup); other.addContentSelector(new ContentSelector(StandardField.TITLE, List.of("Test Title"))); List<ContentSelector> expectedContentSelectors = List.of(new ContentSelector(StandardField.AUTHOR, List.of("Test Author")), new ContentSelector(StandardField.TITLE, List.of("Test Title"))); new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).mergeMetaData(target, other, "unknown", List.of()); // Assert that content selectors are all merged assertEquals(expectedContentSelectors, target.getContentSelectorList()); // Assert that groups of other are children of root node of target assertEquals(targetRootGroup, target.getGroups().get()); assertEquals(target.getGroups().get().getChildren().size(), 1); assertEquals(otherRootGroup, target.getGroups().get().getChildren().get(0)); } @Test void mergeMetaDataWithAllEntriesGroup() { MetaData target = new MetaData(); target.addContentSelector(new ContentSelector(StandardField.AUTHOR, List.of("Test Author"))); GroupTreeNode targetRootGroup = new GroupTreeNode(new AllEntriesGroup("targetGroup")); target.setGroups(targetRootGroup); MetaData other = new MetaData(); GroupTreeNode otherRootGroup = new GroupTreeNode(new AllEntriesGroup("otherGroup")); other.setGroups(otherRootGroup); other.addContentSelector(new ContentSelector(StandardField.TITLE, List.of("Test Title"))); List<ContentSelector> expectedContentSelectors = List.of(new ContentSelector(StandardField.AUTHOR, List.of("Test Author")), new ContentSelector(StandardField.TITLE, List.of("Test Title"))); GroupTreeNode expectedImportedGroupNode = new GroupTreeNode(new ExplicitGroup("Imported unknown", GroupHierarchyType.INDEPENDENT, ';')); new DatabaseMerger(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).mergeMetaData(target, other, "unknown", List.of()); // Assert that groups of other are children of root node of target assertEquals(targetRootGroup, target.getGroups().get()); assertEquals(target.getGroups().get().getChildren().size(), 1); assertEquals(expectedImportedGroupNode, target.getGroups().get().getChildren().get(0)); assertEquals(expectedContentSelectors, target.getContentSelectorList()); } }
10,179
51.746114
150
java
null
jabref-main/src/test/java/org/jabref/logic/database/DuplicateCheckTest.java
package org.jabref.logic.database; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.entry.field.Field; 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 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 DuplicateCheckTest { private BibEntry simpleArticle; private BibEntry unrelatedArticle; private BibEntry simpleInbook; private BibEntry simpleIncollection; private DuplicateCheck duplicateChecker; @BeforeEach public void setUp() { simpleArticle = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Single Author") .withField(StandardField.TITLE, "A serious paper about something") .withField(StandardField.YEAR, "2017"); unrelatedArticle = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Completely Different") .withField(StandardField.TITLE, "Holy Moly Uffdada und Trallalla") .withField(StandardField.YEAR, "1992"); simpleInbook = new BibEntry(StandardEntryType.InBook) .withField(StandardField.TITLE, "Alice in Wonderland") .withField(StandardField.AUTHOR, "Charles Lutwidge Dodgson") .withField(StandardField.CHAPTER, "Chapter One – Down the Rabbit Hole") .withField(StandardField.LANGUAGE, "English") .withField(StandardField.PUBLISHER, "Macmillan") .withField(StandardField.YEAR, "1865"); simpleIncollection = new BibEntry(StandardEntryType.InCollection) .withField(StandardField.TITLE, "Innovation and Intellectual Property Rights") .withField(StandardField.AUTHOR, "Ove Grandstrand") .withField(StandardField.BOOKTITLE, "The Oxford Handbook of Innovation") .withField(StandardField.PUBLISHER, "Oxford University Press") .withField(StandardField.YEAR, "2004"); duplicateChecker = new DuplicateCheck(new BibEntryTypesManager()); } @Test public void testDuplicateDetection() { BibEntry one = new BibEntry(StandardEntryType.Article); BibEntry two = new BibEntry(StandardEntryType.Article); one.setField(StandardField.AUTHOR, "Billy Bob"); two.setField(StandardField.AUTHOR, "Billy Bob"); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); two.setField(StandardField.AUTHOR, "James Joyce"); assertFalse(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); two.setField(StandardField.AUTHOR, "Billy Bob"); two.setType(StandardEntryType.Book); assertFalse(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); two.setType(StandardEntryType.Article); one.setField(StandardField.YEAR, "2005"); two.setField(StandardField.YEAR, "2005"); one.setField(StandardField.TITLE, "A title"); two.setField(StandardField.TITLE, "A title"); one.setField(StandardField.JOURNAL, "A"); two.setField(StandardField.JOURNAL, "A"); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); assertEquals(1.01, DuplicateCheck.compareEntriesStrictly(one, two), 0.01); two.setField(StandardField.JOURNAL, "B"); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); assertEquals(0.75, DuplicateCheck.compareEntriesStrictly(one, two), 0.01); two.setField(StandardField.JOURNAL, "A"); one.setField(StandardField.NUMBER, "1"); two.setField(StandardField.VOLUME, "21"); one.setField(StandardField.PAGES, "334--337"); two.setField(StandardField.PAGES, "334--337"); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); two.setField(StandardField.NUMBER, "1"); one.setField(StandardField.VOLUME, "21"); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); two.setField(StandardField.VOLUME, "22"); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); two.setField(StandardField.JOURNAL, "B"); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); one.setField(StandardField.JOURNAL, ""); two.setField(StandardField.JOURNAL, ""); assertTrue(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); two.setField(StandardField.TITLE, "Another title"); assertFalse(duplicateChecker.isDuplicate(one, two, BibDatabaseMode.BIBTEX)); } @Test public void testWordCorrelation() { String d1 = "Characterization of Calanus finmarchicus habitat in the North Sea"; String d2 = "Characterization of Calunus finmarchicus habitat in the North Sea"; String d3 = "Characterization of Calanus glacialissss habitat in the South Sea"; assertEquals(1.0, (DuplicateCheck.correlateByWords(d1, d2)), 0.01); assertEquals(0.78, (DuplicateCheck.correlateByWords(d1, d3)), 0.01); assertEquals(0.78, (DuplicateCheck.correlateByWords(d2, d3)), 0.01); } @Test public void twoUnrelatedEntriesAreNoDuplicates() { assertFalse(duplicateChecker.isDuplicate(simpleArticle, unrelatedArticle, BibDatabaseMode.BIBTEX)); } @Test public void twoUnrelatedEntriesWithDifferentDoisAreNoDuplicates() { simpleArticle.setField(StandardField.DOI, "10.1016/j.is.2004.02.002"); unrelatedArticle.setField(StandardField.DOI, "10.1016/j.is.2004.02.00X"); assertFalse(duplicateChecker.isDuplicate(simpleArticle, unrelatedArticle, BibDatabaseMode.BIBTEX)); } @Test public void twoUnrelatedEntriesWithEqualDoisAreDuplicates() { simpleArticle.setField(StandardField.DOI, "10.1016/j.is.2004.02.002"); unrelatedArticle.setField(StandardField.DOI, "10.1016/j.is.2004.02.002"); assertTrue(duplicateChecker.isDuplicate(simpleArticle, unrelatedArticle, BibDatabaseMode.BIBTEX)); } @Test public void twoUnrelatedEntriesWithEqualPmidAreDuplicates() { simpleArticle.setField(StandardField.PMID, "12345678"); unrelatedArticle.setField(StandardField.PMID, "12345678"); assertTrue(duplicateChecker.isDuplicate(simpleArticle, unrelatedArticle, BibDatabaseMode.BIBTEX)); } @Test public void twoUnrelatedEntriesWithEqualEprintAreDuplicates() { simpleArticle.setField(StandardField.EPRINT, "12345678"); unrelatedArticle.setField(StandardField.EPRINT, "12345678"); assertTrue(duplicateChecker.isDuplicate(simpleArticle, unrelatedArticle, BibDatabaseMode.BIBTEX)); } @Test public void twoEntriesWithSameDoiButDifferentTypesAreDuplicates() { simpleArticle.setField(StandardField.DOI, "10.1016/j.is.2004.02.002"); BibEntry duplicateWithDifferentType = (BibEntry) simpleArticle.clone(); duplicateWithDifferentType.setType(StandardEntryType.InCollection); assertTrue(duplicateChecker.isDuplicate(simpleArticle, duplicateWithDifferentType, BibDatabaseMode.BIBTEX)); } @Test public void twoEntriesWithDoiContainingUnderscoresAreNotEqual() { simpleArticle.setField(StandardField.DOI, "10.1016/j.is.2004.02.002"); // An underscore in a DOI can indicate a totally different DOI unrelatedArticle.setField(StandardField.DOI, "10.1016/j.is.2004.02.0_02"); BibEntry duplicateWithDifferentType = unrelatedArticle; duplicateWithDifferentType.setType(StandardEntryType.InCollection); assertFalse(duplicateChecker.isDuplicate(simpleArticle, duplicateWithDifferentType, BibDatabaseMode.BIBTEX)); } @Test public void twoEntriesWithSameISBNButDifferentTypesAreDuplicates() { simpleArticle.setField(StandardField.ISBN, "0-123456-47-9"); unrelatedArticle.setField(StandardField.ISBN, "0-123456-47-9"); BibEntry duplicateWithDifferentType = unrelatedArticle; duplicateWithDifferentType.setType(StandardEntryType.InCollection); assertTrue(duplicateChecker.isDuplicate(simpleArticle, duplicateWithDifferentType, BibDatabaseMode.BIBTEX)); } @Test public void twoInbooksWithDifferentChaptersAreNotDuplicates() { twoEntriesWithDifferentSpecificFieldsAreNotDuplicates(simpleInbook, StandardField.CHAPTER, "Chapter One – Down the Rabbit Hole", "Chapter Two – The Pool of Tears"); } @Test public void twoInbooksWithDifferentPagesAreNotDuplicates() { twoEntriesWithDifferentSpecificFieldsAreNotDuplicates(simpleInbook, StandardField.PAGES, "1-20", "21-40"); } @Test public void twoIncollectionsWithDifferentChaptersAreNotDuplicates() { twoEntriesWithDifferentSpecificFieldsAreNotDuplicates(simpleIncollection, StandardField.CHAPTER, "10", "9"); } @Test public void twoIncollectionsWithDifferentPagesAreNotDuplicates() { twoEntriesWithDifferentSpecificFieldsAreNotDuplicates(simpleIncollection, StandardField.PAGES, "1-20", "21-40"); } private void twoEntriesWithDifferentSpecificFieldsAreNotDuplicates(final BibEntry cloneable, final Field field, final String firstValue, final String secondValue) { final BibEntry entry1 = (BibEntry) cloneable.clone(); entry1.setField(field, firstValue); final BibEntry entry2 = (BibEntry) cloneable.clone(); entry2.setField(field, secondValue); assertFalse(duplicateChecker.isDuplicate(entry1, entry2, BibDatabaseMode.BIBTEX)); } @Test public void inbookWithoutChapterCouldBeDuplicateOfInbookWithChapter() { final BibEntry inbook1 = (BibEntry) simpleInbook.clone(); final BibEntry inbook2 = (BibEntry) simpleInbook.clone(); inbook2.setField(StandardField.CHAPTER, ""); assertTrue(duplicateChecker.isDuplicate(inbook1, inbook2, BibDatabaseMode.BIBTEX)); assertTrue(duplicateChecker.isDuplicate(inbook2, inbook1, BibDatabaseMode.BIBTEX)); } @Test public void twoBooksWithDifferentEditionsAreNotDuplicates() { BibEntry editionOne = new BibEntry(StandardEntryType.Book); editionOne.setField(StandardField.TITLE, "Effective Java"); editionOne.setField(StandardField.AUTHOR, "Bloch, Joshua"); editionOne.setField(StandardField.PUBLISHER, "Prentice Hall"); editionOne.setField(StandardField.DATE, "2001"); editionOne.setField(StandardField.EDITION, "1"); BibEntry editionTwo = new BibEntry(StandardEntryType.Book); editionTwo.setField(StandardField.TITLE, "Effective Java"); editionTwo.setField(StandardField.AUTHOR, "Bloch, Joshua"); editionTwo.setField(StandardField.PUBLISHER, "Prentice Hall"); editionTwo.setField(StandardField.DATE, "2008"); editionTwo.setField(StandardField.EDITION, "2"); assertFalse(duplicateChecker.isDuplicate(editionOne, editionTwo, BibDatabaseMode.BIBTEX)); } @Test public void sameBooksWithMissingEditionAreDuplicates() { BibEntry editionOne = new BibEntry(StandardEntryType.Book); editionOne.setField(StandardField.TITLE, "Effective Java"); editionOne.setField(StandardField.AUTHOR, "Bloch, Joshua"); editionOne.setField(StandardField.PUBLISHER, "Prentice Hall"); editionOne.setField(StandardField.DATE, "2001"); BibEntry editionTwo = new BibEntry(StandardEntryType.Book); editionTwo.setField(StandardField.TITLE, "Effective Java"); editionTwo.setField(StandardField.AUTHOR, "Bloch, Joshua"); editionTwo.setField(StandardField.PUBLISHER, "Prentice Hall"); editionTwo.setField(StandardField.DATE, "2008"); assertTrue(duplicateChecker.isDuplicate(editionOne, editionTwo, BibDatabaseMode.BIBTEX)); } @Test public void sameBooksWithPartiallyMissingEditionAreDuplicates() { BibEntry editionOne = new BibEntry(StandardEntryType.Book); editionOne.setField(StandardField.TITLE, "Effective Java"); editionOne.setField(StandardField.AUTHOR, "Bloch, Joshua"); editionOne.setField(StandardField.PUBLISHER, "Prentice Hall"); editionOne.setField(StandardField.DATE, "2001"); BibEntry editionTwo = new BibEntry(StandardEntryType.Book); editionTwo.setField(StandardField.TITLE, "Effective Java"); editionTwo.setField(StandardField.AUTHOR, "Bloch, Joshua"); editionTwo.setField(StandardField.PUBLISHER, "Prentice Hall"); editionTwo.setField(StandardField.DATE, "2008"); editionTwo.setField(StandardField.EDITION, "2"); assertTrue(duplicateChecker.isDuplicate(editionOne, editionTwo, BibDatabaseMode.BIBTEX)); } @Test public void sameBooksWithDifferentEditionsAreNotDuplicates() { BibEntry editionTwo = new BibEntry(StandardEntryType.Book); editionTwo.setCitationKey("Sutton17reinfLrnIntroBook"); editionTwo.setField(StandardField.TITLE, "Reinforcement learning:An introduction"); editionTwo.setField(StandardField.PUBLISHER, "MIT Press"); editionTwo.setField(StandardField.YEAR, "2017"); editionTwo.setField(StandardField.AUTHOR, "Sutton, Richard S and Barto, Andrew G"); editionTwo.setField(StandardField.ADDRESS, "Cambridge, MA.USA"); editionTwo.setField(StandardField.EDITION, "Second"); editionTwo.setField(StandardField.JOURNAL, "MIT Press"); editionTwo.setField(StandardField.URL, "https://webdocs.cs.ualberta.ca/~sutton/book/the-book-2nd.html"); BibEntry editionOne = new BibEntry(StandardEntryType.Book); editionOne.setCitationKey("Sutton98reinfLrnIntroBook"); editionOne.setField(StandardField.TITLE, "Reinforcement learning: An introduction"); editionOne.setField(StandardField.PUBLISHER, "MIT press Cambridge"); editionOne.setField(StandardField.YEAR, "1998"); editionOne.setField(StandardField.AUTHOR, "Sutton, Richard S and Barto, Andrew G"); editionOne.setField(StandardField.VOLUME, "1"); editionOne.setField(StandardField.NUMBER, "1"); editionOne.setField(StandardField.EDITION, "First"); assertFalse(duplicateChecker.isDuplicate(editionOne, editionTwo, BibDatabaseMode.BIBTEX)); } @Test void compareOfTwoEntriesWithSameContentAndLfEndingsReportsNoDifferences() throws Exception { BibEntry entryOne = new BibEntry().withField(StandardField.COMMENT, "line1\n\nline3\n\nline5"); BibEntry entryTwo = new BibEntry().withField(StandardField.COMMENT, "line1\n\nline3\n\nline5"); assertTrue(duplicateChecker.isDuplicate(entryOne, entryTwo, BibDatabaseMode.BIBTEX)); } @Test void compareOfTwoEntriesWithSameContentAndCrLfEndingsReportsNoDifferences() throws Exception { BibEntry entryOne = new BibEntry().withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5"); BibEntry entryTwo = new BibEntry().withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5"); assertTrue(duplicateChecker.isDuplicate(entryOne, entryTwo, BibDatabaseMode.BIBTEX)); } @Test void compareOfTwoEntriesWithSameContentAndMixedLineEndingsReportsNoDifferences() throws Exception { BibEntry entryOne = new BibEntry().withField(StandardField.COMMENT, "line1\n\nline3\n\nline5"); BibEntry entryTwo = new BibEntry().withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5"); assertTrue(duplicateChecker.isDuplicate(entryOne, entryTwo, BibDatabaseMode.BIBTEX)); } }
16,246
48.084592
120
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/AtomicFileOutputStreamTest.java
package org.jabref.logic.exporter; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import com.google.common.base.Strings; 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.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; class AtomicFileOutputStreamTest { private static final String FIFTY_CHARS = Strings.repeat("1234567890", 5); private static final String FIVE_THOUSAND_CHARS = Strings.repeat("A", 5_000); @Test public void normalSaveWorks(@TempDir Path tempDir) throws Exception { Path out = tempDir.resolve("normal-save.txt"); Files.writeString(out, FIFTY_CHARS); try (AtomicFileOutputStream atomicFileOutputStream = new AtomicFileOutputStream(out)) { InputStream inputStream = new ByteArrayInputStream(FIVE_THOUSAND_CHARS.getBytes()); inputStream.transferTo(atomicFileOutputStream); } // Written file still has the contents as before the error assertEquals(FIVE_THOUSAND_CHARS, Files.readString(out)); } @Test public void originalContentExistsAtWriteError(@TempDir Path tempDir) throws Exception { Path pathToTestFile = tempDir.resolve("error-during-save.txt"); Files.writeString(pathToTestFile, FIFTY_CHARS); Path pathToTmpFile = tempDir.resolve("error-during-save.txt.tmp"); try (FileOutputStream outputStream = new FileOutputStream(pathToTmpFile.toFile())) { FileOutputStream spiedOutputStream = spy(outputStream); doAnswer(invocation -> { // by writing one byte, we ensure that the `.tmp` file is created outputStream.write(((byte[]) invocation.getRawArguments()[0])[0]); outputStream.flush(); throw new IOException(); }).when(spiedOutputStream) .write(Mockito.any(byte[].class), anyInt(), anyInt()); assertThrows(IOException.class, () -> { try (AtomicFileOutputStream atomicFileOutputStream = new AtomicFileOutputStream(pathToTestFile, pathToTmpFile, spiedOutputStream, false); InputStream inputStream = new ByteArrayInputStream(FIVE_THOUSAND_CHARS.getBytes())) { inputStream.transferTo(atomicFileOutputStream); } }); } // Written file still has the contents as before the error assertEquals(FIFTY_CHARS, Files.readString(pathToTestFile)); } }
2,833
40.072464
153
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java
package org.jabref.logic.exporter; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.citationkeypattern.AbstractCitationKeyPattern; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.citationkeypattern.DatabaseCitationKeyPattern; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.cleanup.FieldFormatterCleanup; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.logic.formatter.casechanger.LowerCaseFormatter; import org.jabref.logic.formatter.casechanger.TitleCaseFormatter; import org.jabref.logic.formatter.casechanger.UpperCaseFormatter; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.Importer; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.logic.importer.fileformat.BibtexImporterTest; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.util.OS; 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.BibEntryType; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.entry.BibtexString; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.FieldPriority; import org.jabref.model.entry.field.OrFields; 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.jabref.model.groups.AllEntriesGroup; import org.jabref.model.groups.ExplicitGroup; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.GroupTreeNode; import org.jabref.model.metadata.MetaData; import org.jabref.model.metadata.SaveOrder; import org.jabref.model.util.DummyFileUpdateMonitor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; 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; /** * Tests for reading can be found at {@link org.jabref.logic.importer.fileformat.BibtexImporterTest} */ public class BibtexDatabaseWriterTest { private BibtexDatabaseWriter databaseWriter; private BibDatabase database; private MetaData metaData; private BibDatabaseContext bibtexContext; private ImportFormatPreferences importFormatPreferences; private SaveConfiguration saveConfiguration; private FieldPreferences fieldPreferences; private CitationKeyPatternPreferences citationKeyPatternPreferences; private BibEntryTypesManager entryTypesManager; private StringWriter stringWriter; private BibWriter bibWriter; @BeforeEach void setUp() { fieldPreferences = new FieldPreferences(true, Collections.emptyList(), Collections.emptyList()); saveConfiguration = mock(SaveConfiguration.class, Answers.RETURNS_DEEP_STUBS); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); when(saveConfiguration.useMetadataSaveOrder()).thenReturn(true); citationKeyPatternPreferences = mock(CitationKeyPatternPreferences.class, Answers.RETURNS_DEEP_STUBS); entryTypesManager = new BibEntryTypesManager(); stringWriter = new StringWriter(); bibWriter = new BibWriter(stringWriter, OS.NEWLINE); databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); database = new BibDatabase(); metaData = new MetaData(); bibtexContext = new BibDatabaseContext(database, metaData); importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.fieldPreferences()).thenReturn(fieldPreferences); } @Test void writeWithNullContextThrowsException() throws Exception { assertThrows(NullPointerException.class, () -> databaseWriter.savePartOfDatabase(null, Collections.emptyList())); } @Test void writeWithNullEntriesThrowsException() throws Exception { assertThrows(NullPointerException.class, () -> databaseWriter.savePartOfDatabase(bibtexContext, null)); } @Test void writeEncodingUsAsciiWhenSetInPreferencesAndHeader() throws Exception { metaData.setEncoding(StandardCharsets.US_ASCII); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("% Encoding: US-ASCII" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEncodingWindows1252WhenSetInPreferencesAndHeader() throws Exception { metaData.setEncoding(Charset.forName("windows-1252")); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("% Encoding: windows-1252" + OS.NEWLINE, stringWriter.toString()); } @Test void writePreamble() throws Exception { database.setPreamble("Test preamble"); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@Preamble{Test preamble}" + OS.NEWLINE, stringWriter.toString()); } @Test void writePreambleAndEncoding() throws Exception { metaData.setEncoding(StandardCharsets.US_ASCII); database.setPreamble("Test preamble"); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("% Encoding: US-ASCII" + OS.NEWLINE + OS.NEWLINE + "@Preamble{Test preamble}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEntry() throws Exception { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); database.insertEntry(entry); databaseWriter.savePartOfDatabase(bibtexContext, Collections.singletonList(entry)); assertEquals("@Article{," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEntryWithDuplicateKeywords() throws Exception { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.KEYWORDS, "asdf,asdf,asdf"); database.insertEntry(entry); databaseWriter.savePartOfDatabase(bibtexContext, Collections.singletonList(entry)); assertEquals("@Article{," + OS.NEWLINE + " keywords = {asdf,asdf,asdf}," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void putKeyWordsRemovesDuplicateKeywordsIsVisibleDuringWrite() throws Exception { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.putKeywords(List.of("asdf", "asdf", "asdf"), ','); database.insertEntry(entry); databaseWriter.savePartOfDatabase(bibtexContext, Collections.singletonList(entry)); assertEquals("@Article{," + OS.NEWLINE + " keywords = {asdf}," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEncodingAndEntry() throws Exception { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); database.insertEntry(entry); metaData.setEncoding(StandardCharsets.US_ASCII); databaseWriter.savePartOfDatabase(bibtexContext, Collections.singletonList(entry)); assertEquals( "% Encoding: US-ASCII" + OS.NEWLINE + OS.NEWLINE + "@Article{," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEpilogue() throws Exception { database.setEpilog("Test epilog"); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("Test epilog" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEpilogueAndEncoding() throws Exception { database.setEpilog("Test epilog"); metaData.setEncoding(StandardCharsets.US_ASCII); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("% Encoding: US-ASCII" + OS.NEWLINE + OS.NEWLINE + "Test epilog" + OS.NEWLINE, stringWriter.toString()); } @Test void utf8EncodingWrittenIfExplicitlyDefined() throws Exception { metaData.setEncoding(StandardCharsets.UTF_8); metaData.setEncodingExplicitlySupplied(true); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("% Encoding: UTF-8" + OS.NEWLINE, stringWriter.toString()); } @Test void utf8EncodingNotWrittenIfNotExplicitlyDefined() throws Exception { metaData.setEncoding(StandardCharsets.UTF_8); metaData.setEncodingExplicitlySupplied(false); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("", stringWriter.toString()); } @Test void writeMetadata() throws Exception { DatabaseCitationKeyPattern bibtexKeyPattern = new DatabaseCitationKeyPattern(mock(GlobalCitationKeyPattern.class)); bibtexKeyPattern.setDefaultValue("test"); metaData.setCiteKeyPattern(bibtexKeyPattern); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@Comment{jabref-meta: keypatterndefault:test;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeMetadataAndEncoding() throws Exception { DatabaseCitationKeyPattern bibtexKeyPattern = new DatabaseCitationKeyPattern(mock(GlobalCitationKeyPattern.class)); bibtexKeyPattern.setDefaultValue("test"); metaData.setCiteKeyPattern(bibtexKeyPattern); metaData.setEncoding(StandardCharsets.US_ASCII); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("% Encoding: US-ASCII" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: keypatterndefault:test;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeGroups() throws Exception { GroupTreeNode groupRoot = GroupTreeNode.fromGroup(new AllEntriesGroup("")); groupRoot.addSubgroup(new ExplicitGroup("test", GroupHierarchyType.INCLUDING, ',')); metaData.setGroups(groupRoot); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); // @formatter:off assertEquals("@Comment{jabref-meta: grouping:" + OS.NEWLINE + "0 AllEntriesGroup:;" + OS.NEWLINE + "1 StaticGroup:test\\;2\\;1\\;\\;\\;\\;;" + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); // @formatter:on } @Test void writeGroupsAndEncoding() throws Exception { GroupTreeNode groupRoot = GroupTreeNode.fromGroup(new AllEntriesGroup("")); groupRoot.addChild(GroupTreeNode.fromGroup(new ExplicitGroup("test", GroupHierarchyType.INCLUDING, ','))); metaData.setGroups(groupRoot); metaData.setEncoding(StandardCharsets.US_ASCII); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); // @formatter:off assertEquals( "% Encoding: US-ASCII" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: grouping:" + OS.NEWLINE + "0 AllEntriesGroup:;" + OS.NEWLINE + "1 StaticGroup:test\\;2\\;1\\;\\;\\;\\;;" + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); // @formatter:on } @Test void writeString() throws Exception { database.addString(new BibtexString("name", "content")); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@String{name = {content}}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeStringAndEncoding() throws Exception { metaData.setEncoding(StandardCharsets.US_ASCII); database.addString(new BibtexString("name", "content")); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("% Encoding: US-ASCII" + OS.NEWLINE + OS.NEWLINE + "@String{name = {content}}" + OS.NEWLINE, stringWriter.toString()); } @Test void doNotWriteUtf8StringAndEncoding() throws Exception { database.addString(new BibtexString("name", "content")); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@String{name = {content}}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEntryWithCustomizedTypeAlsoWritesTypeDeclaration() throws Exception { EntryType customizedType = new UnknownEntryType("customizedType"); BibEntryType customizedBibType = new BibEntryType( customizedType, Arrays.asList( new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT), new BibField(StandardField.DATE, FieldPriority.IMPORTANT), new BibField(StandardField.YEAR, FieldPriority.IMPORTANT), new BibField(StandardField.MONTH, FieldPriority.IMPORTANT), new BibField(StandardField.PUBLISHER, FieldPriority.IMPORTANT)), Arrays.asList( new OrFields(StandardField.TITLE), new OrFields(StandardField.AUTHOR), new OrFields(StandardField.DATE))); entryTypesManager.addCustomOrModifiedType(customizedBibType, BibDatabaseMode.BIBTEX); BibEntry entry = new BibEntry(customizedType).withCitationKey("key"); // needed to get a proper serialization entry.setChanged(true); database.insertEntry(entry); bibtexContext.setMode(BibDatabaseMode.BIBTEX); databaseWriter.saveDatabase(bibtexContext); assertEquals("@Customizedtype{key," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: databaseType:bibtex;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-entrytype: customizedtype: req[title;author;date] opt[year;month;publisher]}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeCustomizedTypesInAlphabeticalOrder() throws Exception { EntryType customizedType = new UnknownEntryType("customizedType"); EntryType otherCustomizedType = new UnknownEntryType("otherCustomizedType"); BibEntryType customizedBibType = new BibEntryType( customizedType, Collections.singletonList(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT)), Collections.singletonList(new OrFields(StandardField.TITLE))); BibEntryType otherCustomizedBibType = new BibEntryType( otherCustomizedType, Collections.singletonList(new BibField(StandardField.TITLE, FieldPriority.IMPORTANT)), Collections.singletonList(new OrFields(StandardField.TITLE))); entryTypesManager.addCustomOrModifiedType(otherCustomizedBibType, BibDatabaseMode.BIBTEX); entryTypesManager.addCustomOrModifiedType(customizedBibType, BibDatabaseMode.BIBTEX); BibEntry entry = new BibEntry(customizedType); BibEntry otherEntry = new BibEntry(otherCustomizedType); database.insertEntry(otherEntry); database.insertEntry(entry); bibtexContext.setMode(BibDatabaseMode.BIBTEX); databaseWriter.savePartOfDatabase(bibtexContext, List.of(entry, otherEntry)); assertEquals( "@Customizedtype{," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Othercustomizedtype{," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: databaseType:bibtex;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-entrytype: customizedtype: req[title] opt[]}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-entrytype: othercustomizedtype: req[title] opt[]}" + OS.NEWLINE, stringWriter.toString()); } @Test void roundtripWithArticleMonths() throws Exception { Path testBibtexFile = Path.of("src/test/resources/testbib/articleWithMonths.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile)); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(Files.readString(testBibtexFile, encoding), stringWriter.toString()); } @Test void roundtripUtf8EncodingHeaderRemoved() throws Exception { // @formatter:off String bibtexEntry = OS.NEWLINE + "% Encoding: UTF8" + OS.NEWLINE + OS.NEWLINE + "@Article{," + OS.NEWLINE + " author = {Foo Bar}," + OS.NEWLINE + " journal = {International Journal of Something}," + OS.NEWLINE + " note = {some note}," + OS.NEWLINE + " number = {1}," + OS.NEWLINE + "}" + OS.NEWLINE; // @formatter:on ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); databaseWriter.saveDatabase(context); // @formatter:off String expected = "@Article{," + OS.NEWLINE + " author = {Foo Bar}," + OS.NEWLINE + " journal = {International Journal of Something}," + OS.NEWLINE + " note = {some note}," + OS.NEWLINE + " number = {1}," + OS.NEWLINE + "}" + OS.NEWLINE; // @formatter:on assertEquals(expected, stringWriter.toString()); } @Test void roundtripWin1252HeaderKept(@TempDir Path bibFolder) throws Exception { Path testFile = Path.of(BibtexImporterTest.class.getResource("encoding-windows-1252-with-header.bib").toURI()); ParserResult result = new BibtexImporter(importFormatPreferences, new DummyFileUpdateMonitor()).importDatabase(testFile); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); Path pathToFile = bibFolder.resolve("JabRef.bib"); Path file = Files.createFile(pathToFile); Charset charset = Charset.forName("windows-1252"); try (BufferedWriter fileWriter = Files.newBufferedWriter(file, charset)) { BibWriter bibWriter = new BibWriter(fileWriter, context.getDatabase().getNewLineSeparator()); BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.saveDatabase(context); } assertEquals(Files.readString(testFile, charset), Files.readString(file, charset)); } @Test void roundtripUtf8HeaderKept(@TempDir Path bibFolder) throws Exception { Path testFile = Path.of(BibtexImporterTest.class.getResource("encoding-utf-8-with-header-with-databasetypecomment.bib").toURI()); ParserResult result = new BibtexImporter(importFormatPreferences, new DummyFileUpdateMonitor()).importDatabase(testFile); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); Path pathToFile = bibFolder.resolve("JabRef.bib"); Path file = Files.createFile(pathToFile); Charset charset = StandardCharsets.UTF_8; try (BufferedWriter fileWriter = Files.newBufferedWriter(file, charset)) { BibWriter bibWriter = new BibWriter(fileWriter, context.getDatabase().getNewLineSeparator()); BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.saveDatabase(context); } assertEquals(Files.readString(testFile, charset), Files.readString(file, charset)); } @Test void roundtripNotExplicitUtf8HeaderNotInsertedDuringWrite(@TempDir Path bibFolder) throws Exception { Path testFile = Path.of(BibtexImporterTest.class.getResource("encoding-utf-8-without-header-with-databasetypecomment.bib").toURI()); ParserResult result = new BibtexImporter(importFormatPreferences, new DummyFileUpdateMonitor()).importDatabase(testFile); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); Path pathToFile = bibFolder.resolve("JabRef.bib"); Path file = Files.createFile(pathToFile); Charset charset = StandardCharsets.UTF_8; try (BufferedWriter fileWriter = Files.newBufferedWriter(file, charset)) { BibWriter bibWriter = new BibWriter(fileWriter, context.getDatabase().getNewLineSeparator()); BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.saveDatabase(context); } assertEquals(Files.readString(testFile, charset), Files.readString(file, charset)); } @Test void roundtripWithComplexBib() throws Exception { Path testBibtexFile = Path.of("src/test/resources/testbib/complex.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile)); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); BibWriter bibWriter = new BibWriter(stringWriter, context.getDatabase().getNewLineSeparator()); BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(Files.readString(testBibtexFile, encoding), stringWriter.toString()); } @Test void roundtripWithUserComment() throws Exception { Path testBibtexFile = Path.of("src/test/resources/testbib/bibWithUserComments.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile)); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(Files.readString(testBibtexFile, encoding), stringWriter.toString()); } @Test void roundtripWithOneUserCommentAndEntryChange() throws Exception { String bibEntry = "@Comment this in an unbracketed comment that should be preserved as well\n" + "\n" + "This is some arbitrary user comment that should be preserved\n" + "\n" + "@InProceedings{1137631,\n" + " author = {Mr. Author},\n" + "}\n"; // read in bibtex string ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibEntry)); BibEntry entry = result.getDatabase().getEntryByCitationKey("1137631").get(); entry.setField(StandardField.AUTHOR, "Mr. Author"); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); // we need a new writer because "\n" instead of "OS.NEWLINE" bibWriter = new BibWriter(stringWriter, "\n"); databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(bibEntry, stringWriter.toString()); } @Test void roundtripWithTwoEntriesAndOneUserCommentAndEntryChange() throws Exception { String bibEntry = "@Article{test,}\n" + "\n" + "@Comment this in an unbracketed comment that should be preserved as well\n" + "\n" + "This is some arbitrary user comment that should be preserved\n" + "\n" + "@InProceedings{1137631,\n" + " author = {Mr. Author},\n" + "}\n"; // read in bibtex string ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibEntry)); BibEntry entry = result.getDatabase().getEntryByCitationKey("1137631").get(); entry.setField(StandardField.AUTHOR, "Mr. Author"); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); // we need a new writer because "\n" instead of "OS.NEWLINE" bibWriter = new BibWriter(stringWriter, "\n"); databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(bibEntry, stringWriter.toString()); } @Test void roundtripWithUserCommentAndEntryChange() throws Exception { Path testBibtexFile = Path.of("src/test/resources/testbib/bibWithUserComments.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile)); BibEntry entry = result.getDatabase().getEntryByCitationKey("1137631").get(); entry.setField(StandardField.AUTHOR, "Mr. Author"); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(Files.readString(Path.of("src/test/resources/testbib/bibWithUserCommentAndEntryChange.bib"), encoding), stringWriter.toString()); } @Test void roundtripWithUserCommentBeforeStringAndChange() throws Exception { Path testBibtexFile = Path.of("src/test/resources/testbib/complex.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile)); for (BibtexString string : result.getDatabase().getStringValues()) { // Mark them as changed string.setContent(string.getContent()); } BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(Files.readString(testBibtexFile, encoding), stringWriter.toString()); } @Test void roundtripWithUnknownMetaData() throws Exception { Path testBibtexFile = Path.of("src/test/resources/testbib/unknownMetaData.bib"); Charset encoding = StandardCharsets.UTF_8; ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile)); BibDatabaseContext context = new BibDatabaseContext(result.getDatabase(), result.getMetaData()); databaseWriter.savePartOfDatabase(context, result.getDatabase().getEntries()); assertEquals(Files.readString(testBibtexFile, encoding), stringWriter.toString()); } @Test void writeSavedSerializationOfEntryIfUnchanged() throws Exception { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Mr. author"); entry.setParsedSerialization("presaved serialization"); entry.setChanged(false); database.insertEntry(entry); databaseWriter.savePartOfDatabase(bibtexContext, Collections.singletonList(entry)); assertEquals("presaved serialization" + OS.NEWLINE, stringWriter.toString()); } @Test void reformatEntryIfAskedToDoSo() throws Exception { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Mr. author"); entry.setParsedSerialization("wrong serialization"); entry.setChanged(false); database.insertEntry(entry); when(saveConfiguration.shouldReformatFile()).thenReturn(true); databaseWriter.savePartOfDatabase(bibtexContext, Collections.singletonList(entry)); assertEquals("@Article{," + OS.NEWLINE + " author = {Mr. author}," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeSavedSerializationOfStringIfUnchanged() throws Exception { BibtexString string = new BibtexString("name", "content"); string.setParsedSerialization("serialization"); database.addString(string); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("serialization" + OS.NEWLINE, stringWriter.toString()); } @Test void reformatStringIfAskedToDoSo() throws Exception { BibtexString string = new BibtexString("name", "content"); string.setParsedSerialization("wrong serialization"); database.addString(string); when(saveConfiguration.shouldReformatFile()).thenReturn(true); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@String{name = {content}}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeSaveActions() throws Exception { FieldFormatterCleanups saveActions = new FieldFormatterCleanups(true, Arrays.asList( new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()), new FieldFormatterCleanup(StandardField.JOURNAL, new TitleCaseFormatter()), new FieldFormatterCleanup(StandardField.DAY, new UpperCaseFormatter()))); metaData.setSaveActions(saveActions); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); // The order should be kept (the cleanups are a list, not a set) assertEquals("@Comment{jabref-meta: saveActions:enabled;" + OS.NEWLINE + "title[lower_case]" + OS.NEWLINE + "journal[title_case]" + OS.NEWLINE + "day[upper_case]" + OS.NEWLINE + ";}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeSaveOrderConfig() throws Exception { SaveOrder saveOrder = new SaveOrder(SaveOrder.OrderType.SPECIFIED, List.of(new SaveOrder.SortCriterion(StandardField.AUTHOR, false), new SaveOrder.SortCriterion(StandardField.YEAR, true), new SaveOrder.SortCriterion(StandardField.ABSTRACT, false))); metaData.setSaveOrderConfig(saveOrder); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@Comment{jabref-meta: saveOrderConfig:specified;author;false;year;true;abstract;false;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeCustomKeyPattern() throws Exception { AbstractCitationKeyPattern pattern = new DatabaseCitationKeyPattern(mock(GlobalCitationKeyPattern.class)); pattern.setDefaultValue("test"); pattern.addCitationKeyPattern(StandardEntryType.Article, "articleTest"); metaData.setCiteKeyPattern(pattern); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@Comment{jabref-meta: keypattern_article:articleTest;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: keypatterndefault:test;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeBiblatexMode() throws Exception { metaData.setMode(BibDatabaseMode.BIBLATEX); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@Comment{jabref-meta: databaseType:biblatex;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeProtectedFlag() throws Exception { metaData.markAsProtected(); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@Comment{jabref-meta: protectedFlag:true;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeFileDirectories() throws Exception { metaData.setDefaultFileDirectory("\\Literature\\"); metaData.setUserFileDirectory("defaultOwner-user", "D:\\Documents"); metaData.setLatexFileDirectory("defaultOwner-user", Path.of("D:\\Latex")); databaseWriter.savePartOfDatabase(bibtexContext, Collections.emptyList()); assertEquals("@Comment{jabref-meta: fileDirectory:\\\\Literature\\\\;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory-defaultOwner-user:D:\\\\Documents;}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: fileDirectoryLatex-defaultOwner-user:D:\\\\Latex;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEntriesSorted() throws Exception { SaveOrder saveOrder = new SaveOrder(SaveOrder.OrderType.SPECIFIED, List.of(new SaveOrder.SortCriterion(StandardField.AUTHOR, false), new SaveOrder.SortCriterion(StandardField.YEAR, true), new SaveOrder.SortCriterion(StandardField.ABSTRACT, false))); metaData.setSaveOrderConfig(saveOrder); BibEntry firstEntry = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "A") .withField(StandardField.YEAR, "2010") .withChanged(true); BibEntry secondEntry = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "A") .withField(StandardField.YEAR, "2000") .withChanged(true); BibEntry thirdEntry = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "B") .withField(StandardField.YEAR, "2000") .withChanged(true); database.insertEntries(secondEntry, thirdEntry, firstEntry); databaseWriter.savePartOfDatabase(bibtexContext, database.getEntries()); assertEquals("@Article{," + OS.NEWLINE + " author = {A}," + OS.NEWLINE + " year = {2010}," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Article{," + OS.NEWLINE + " author = {A}," + OS.NEWLINE + " year = {2000}," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Article{," + OS.NEWLINE + " author = {B}," + OS.NEWLINE + " year = {2000}," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Comment{jabref-meta: saveOrderConfig:specified;author;false;year;true;abstract;false;}" + OS.NEWLINE, stringWriter.toString()); } @Test void writeEntriesInOriginalOrderWhenNoSaveOrderConfigIsSetInMetadata() throws Exception { BibEntry firstEntry = new BibEntry(); firstEntry.setType(StandardEntryType.Article); firstEntry.setField(StandardField.AUTHOR, "A"); firstEntry.setField(StandardField.YEAR, "2010"); BibEntry secondEntry = new BibEntry(); secondEntry.setType(StandardEntryType.Article); secondEntry.setField(StandardField.AUTHOR, "B"); secondEntry.setField(StandardField.YEAR, "2000"); BibEntry thirdEntry = new BibEntry(); thirdEntry.setType(StandardEntryType.Article); thirdEntry.setField(StandardField.AUTHOR, "A"); thirdEntry.setField(StandardField.YEAR, "2000"); database.insertEntry(firstEntry); database.insertEntry(secondEntry); database.insertEntry(thirdEntry); databaseWriter.savePartOfDatabase(bibtexContext, database.getEntries()); assertEquals("@Article{," + OS.NEWLINE + " author = {A}," + OS.NEWLINE + " year = {2010}," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Article{," + OS.NEWLINE + " author = {B}," + OS.NEWLINE + " year = {2000}," + OS.NEWLINE + "}" + OS.NEWLINE + OS.NEWLINE + "@Article{," + OS.NEWLINE + " author = {A}," + OS.NEWLINE + " year = {2000}," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void trimFieldContents() throws IOException { BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setField(StandardField.NOTE, " some note \t"); database.insertEntry(entry); databaseWriter.saveDatabase(bibtexContext); assertEquals("@Article{," + OS.NEWLINE + " note = {some note}," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void newlineAtEndOfAbstractFieldIsDeleted() throws Exception { String text = "lorem ipsum lorem ipsum" + OS.NEWLINE + "lorem ipsum lorem ipsum"; BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setField(StandardField.ABSTRACT, text + OS.NEWLINE); database.insertEntry(entry); databaseWriter.saveDatabase(bibtexContext); assertEquals("@Article{," + OS.NEWLINE + " abstract = {" + text + "}," + OS.NEWLINE + "}" + OS.NEWLINE, stringWriter.toString()); } @Test void roundtripWithContentSelectorsAndUmlauts() throws Exception { String encodingHeader = "% Encoding: UTF-8" + OS.NEWLINE + OS.NEWLINE; String commentEntry = "@Comment{jabref-meta: selector_journal:Test {\\\\\"U}mlaut;}" + OS.NEWLINE; String fileContent = encodingHeader + commentEntry; Charset encoding = StandardCharsets.UTF_8; ParserResult firstParse = new BibtexParser(importFormatPreferences).parse(new StringReader(fileContent)); BibDatabaseContext context = new BibDatabaseContext(firstParse.getDatabase(), firstParse.getMetaData()); databaseWriter.savePartOfDatabase(context, firstParse.getDatabase().getEntries()); assertEquals(commentEntry, stringWriter.toString()); } @Test void saveAlsoSavesSecondModification() throws Exception { // @formatter:off String bibtexEntry = OS.NEWLINE + "@Article{test," + OS.NEWLINE + " Author = {Foo Bar}," + OS.NEWLINE + " Journal = {International Journal of Something}," + OS.NEWLINE + " Note = {some note}," + OS.NEWLINE + " Number = {1}," + OS.NEWLINE + "}"; // @formatter:on // read in bibtex string ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); ParserResult firstParse = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = firstParse.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); // modify entry entry.setField(StandardField.AUTHOR, "BlaBla"); BibDatabaseContext context = new BibDatabaseContext(firstParse.getDatabase(), firstParse.getMetaData()); context.setMode(BibDatabaseMode.BIBTEX); databaseWriter.savePartOfDatabase(context, firstParse.getDatabase().getEntries()); // modify entry a second time entry.setField(StandardField.AUTHOR, "Test"); // write a second time stringWriter = new StringWriter(); bibWriter = new BibWriter(stringWriter, OS.NEWLINE); databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.savePartOfDatabase(context, firstParse.getDatabase().getEntries()); assertEquals("@Article{test," + OS.NEWLINE + " author = {Test}," + OS.NEWLINE + " journal = {International Journal of Something}," + OS.NEWLINE + " note = {some note}," + OS.NEWLINE + " number = {1}," + OS.NEWLINE + "}" + OS.NEWLINE + "" + OS.NEWLINE + "@Comment{jabref-meta: databaseType:bibtex;}" + OS.NEWLINE, stringWriter.toString()); } @Test void saveReturnsToOriginalEntryWhenEntryIsFlaggedUnchanged() throws Exception { // @formatter:off String bibtexEntry = "@Article{test," + OS.NEWLINE + " Author = {Foo Bar}," + OS.NEWLINE + " Journal = {International Journal of Something}," + OS.NEWLINE + " Number = {1}," + OS.NEWLINE + " Note = {some note}," + OS.NEWLINE + "}" + OS.NEWLINE; // @formatter:on // read in bibtex string ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); ParserResult firstParse = new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor()).parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = firstParse.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); // modify entry entry.setField(StandardField.AUTHOR, "BlaBla"); // flag unchanged entry.setChanged(false); // write entry BibDatabaseContext context = new BibDatabaseContext(firstParse.getDatabase(), firstParse.getMetaData()); databaseWriter.savePartOfDatabase(context, firstParse.getDatabase().getEntries()); assertEquals(bibtexEntry, stringWriter.toString()); } @Test void saveReturnsToOriginalEntryWhenEntryIsFlaggedUnchangedEvenInThePresenceOfSavedModifications() throws Exception { // @formatter:off String bibtexEntry = "@Article{test," + OS.NEWLINE + " Author = {Foo Bar}," + OS.NEWLINE + " Journal = {International Journal of Something}," + OS.NEWLINE + " Note = {some note}," + OS.NEWLINE + " Number = {1}," + OS.NEWLINE + "}" + OS.NEWLINE; // @formatter:on // read in bibtex string ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); ParserResult firstParse = new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor()).parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = firstParse.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); // modify entry entry.setField(StandardField.AUTHOR, "BlaBla"); BibDatabaseContext context = new BibDatabaseContext(firstParse.getDatabase(), firstParse.getMetaData()); databaseWriter.savePartOfDatabase(context, firstParse.getDatabase().getEntries()); // modify entry a second time entry.setField(StandardField.AUTHOR, "Test"); entry.setChanged(false); // write a second time stringWriter = new StringWriter(); bibWriter = new BibWriter(stringWriter, OS.NEWLINE); databaseWriter = new BibtexDatabaseWriter( bibWriter, saveConfiguration, fieldPreferences, citationKeyPatternPreferences, entryTypesManager); databaseWriter.savePartOfDatabase(context, firstParse.getDatabase().getEntries()); // returns tu original entry, not to the last saved one assertEquals(bibtexEntry, stringWriter.toString()); } }
47,178
44.01813
158
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/CsvExportFormatTest.java
package org.jabref.logic.exporter; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.metadata.SaveOrder; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CsvExportFormatTest { public BibDatabaseContext databaseContext; private Exporter exportFormat; @BeforeEach public void setUp() { SaveConfiguration saveConfiguration = mock(SaveConfiguration.class); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); exportFormat = new TemplateExporter( "OpenOffice/LibreOffice CSV", "oocsv", "openoffice-csv", "openoffice", StandardFileType.CSV, mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS), saveConfiguration); databaseContext = new BibDatabaseContext(); } @AfterEach public void tearDown() { exportFormat = null; } @Test public void testPerformExportForSingleAuthor(@TempDir Path testFolder) throws Exception { Path path = testFolder.resolve("ThisIsARandomlyNamedFile"); BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Someone, Van Something"); List<BibEntry> entries = List.of(entry); exportFormat.export(databaseContext, path, entries); List<String> lines = Files.readAllLines(path); assertEquals(2, lines.size()); assertEquals( "10,\"\",\"\",\"Someone, Van Something\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", lines.get(1)); } @Test public void testPerformExportForMultipleAuthors(@TempDir Path testFolder) throws Exception { Path path = testFolder.resolve("ThisIsARandomlyNamedFile"); BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "von Neumann, John and Smith, John and Black Brown, Peter"); List<BibEntry> entries = List.of(entry); exportFormat.export(databaseContext, path, entries); List<String> lines = Files.readAllLines(path); assertEquals(2, lines.size()); assertEquals( "10,\"\",\"\",\"von Neumann, John; Smith, John; Black Brown, Peter\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", lines.get(1)); } @Test public void testPerformExportForSingleEditor(@TempDir Path testFolder) throws Exception { Path path = testFolder.resolve("ThisIsARandomlyNamedFile"); File tmpFile = path.toFile(); BibEntry entry = new BibEntry().withField(StandardField.EDITOR, "Someone, Van Something"); List<BibEntry> entries = List.of(entry); exportFormat.export(databaseContext, tmpFile.toPath(), entries); List<String> lines = Files.readAllLines(tmpFile.toPath()); assertEquals(2, lines.size()); assertEquals( "10,\"\",\"\",\"\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Someone, Van Something\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", lines.get(1)); } @Test public void testPerformExportForMultipleEditors(@TempDir Path testFolder) throws Exception { Path path = testFolder.resolve("ThisIsARandomlyNamedFile"); File tmpFile = path.toFile(); BibEntry entry = new BibEntry(); entry.setField(StandardField.EDITOR, "von Neumann, John and Smith, John and Black Brown, Peter"); List<BibEntry> entries = List.of(entry); exportFormat.export(databaseContext, tmpFile.toPath(), entries); List<String> lines = Files.readAllLines(tmpFile.toPath()); assertEquals(2, lines.size()); assertEquals( "10,\"\",\"\",\"\",\"\",\"\",,,\"\",\"\",,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"von Neumann, John; Smith, John; Black Brown, Peter\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"", lines.get(1)); } }
4,715
39.307692
209
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/DocBook5ExporterTest.java
package org.jabref.logic.exporter; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; import java.util.Collections; import java.util.List; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.metadata.SaveOrder; 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.xmlunit.builder.Input; import org.xmlunit.builder.Input.Builder; import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DocBook5ExporterTest { public BibDatabaseContext databaseContext; public Charset charset; public List<BibEntry> entries; private Path xmlFile; private Exporter exporter; @BeforeEach void setUp() throws URISyntaxException { SaveConfiguration saveConfiguration = mock(SaveConfiguration.class); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); exporter = new TemplateExporter( "DocBook 5.1", "docbook5", "docbook5", null, StandardFileType.XML, mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS), saveConfiguration); LocalDate myDate = LocalDate.of(2018, 1, 1); xmlFile = Path.of(DocBook5ExporterTest.class.getResource("Docbook5ExportFormat.xml").toURI()); databaseContext = new BibDatabaseContext(); charset = StandardCharsets.UTF_8; BibEntry entry = new BibEntry(StandardEntryType.Book); entry.setField(StandardField.TITLE, "my paper title"); entry.setField(StandardField.AUTHOR, "Stefan Kolb and Tobias Diez"); entry.setField(StandardField.ISBN, "1-2-34"); entry.setCitationKey("mykey"); entry.setDate(new org.jabref.model.entry.Date(myDate)); entries = Collections.singletonList(entry); } @Test void testPerformExportForSingleEntry(@TempDir Path testFolder) throws Exception { Path path = testFolder.resolve("ThisIsARandomlyNamedFile"); exporter.export(databaseContext, path, entries); Builder control = Input.from(Files.newInputStream(xmlFile)); Builder test = Input.from(Files.newInputStream(path)); assertThat(test, CompareMatcher.isSimilarTo(control) .normalizeWhitespace() .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); } }
3,162
36.211765
138
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/DocbookExporterTest.java
package org.jabref.logic.exporter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.metadata.SaveOrder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DocbookExporterTest { public BibDatabaseContext databaseContext = new BibDatabaseContext(); public Charset charset = StandardCharsets.UTF_8; private Exporter exportFormat; @BeforeEach public void setUp() { SaveConfiguration saveConfiguration = mock(SaveConfiguration.class); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); exportFormat = new TemplateExporter( "DocBook 4", "docbook4", "docbook4", null, StandardFileType.XML, mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS), saveConfiguration); } @Test public void testCorruptedTitleBraces(@TempDir Path testFolder) throws Exception { Path tmpFile = testFolder.resolve("testBraces"); BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Peptidomics of the larval {{{D}rosophila melanogaster}} central nervous system."); List<BibEntry> entries = Arrays.asList(entry); exportFormat.export(databaseContext, tmpFile, entries); List<String> lines = Files.readAllLines(tmpFile); assertEquals(20, lines.size()); assertEquals(" <citetitle pubwork=\"article\">Peptidomics of the larval Drosophila melanogaster central nervous system.</citetitle>", lines.get(9)); } @Test public void testCorruptedTitleUnicode(@TempDir Path testFolder) throws Exception { Path tmpFile = testFolder.resolve("testBraces"); BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Insect neuropeptide bursicon homodimers induce innate immune and stress genes during molting by activating the {NF}-$\\kappa$B transcription factor Relish."); List<BibEntry> entries = Arrays.asList(entry); exportFormat.export(databaseContext, tmpFile, entries); List<String> lines = Files.readAllLines(tmpFile); assertEquals(20, lines.size()); assertEquals(" <citetitle pubwork=\"article\">Insect neuropeptide bursicon homodimers induce innate immune and stress genes during molting by activating the NF&#45;&#954;B transcription factor Relish.</citetitle>", lines.get(9)); } }
3,104
37.8125
239
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/EmbeddedBibFilePdfExporterTest.java
package org.jabref.logic.exporter; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.journals.JournalAbbreviationRepository; 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.BibEntryTypesManager; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.Month; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.preferences.FilePreferences; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; 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.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class EmbeddedBibFilePdfExporterTest { @TempDir static Path tempDir; private static BibEntry olly2018 = new BibEntry(StandardEntryType.Article); private static BibEntry toral2006 = new BibEntry(StandardEntryType.Article); private static BibEntry vapnik2000 = new BibEntry(StandardEntryType.Article); private EmbeddedBibFilePdfExporter exporter; private BibDatabaseContext databaseContext; private BibDatabase dataBase; private JournalAbbreviationRepository abbreviationRepository; private FilePreferences filePreferences; private static void initBibEntries() throws IOException { olly2018.setCitationKey("Olly2018"); olly2018.setField(StandardField.AUTHOR, "Olly and Johannes"); olly2018.setField(StandardField.TITLE, "Stefan's palace"); olly2018.setField(StandardField.JOURNAL, "Test Journal"); olly2018.setField(StandardField.VOLUME, "1"); olly2018.setField(StandardField.NUMBER, "1"); olly2018.setField(StandardField.PAGES, "1-2"); olly2018.setMonth(Month.MARCH); olly2018.setField(StandardField.ISSN, "978-123-123"); olly2018.setField(StandardField.NOTE, "NOTE"); olly2018.setField(StandardField.ABSTRACT, "ABSTRACT"); olly2018.setField(StandardField.COMMENT, "COMMENT"); olly2018.setField(StandardField.DOI, "10/3212.3123"); olly2018.setField(StandardField.FILE, ":article_dublinCore.pdf:PDF"); olly2018.setField(StandardField.GROUPS, "NO"); olly2018.setField(StandardField.HOWPUBLISHED, "online"); olly2018.setField(StandardField.KEYWORDS, "k1, k2"); olly2018.setField(StandardField.OWNER, "me"); olly2018.setField(StandardField.REVIEW, "review"); olly2018.setField(StandardField.URL, "https://www.olly2018.edu"); LinkedFile linkedFile = createDefaultLinkedFile("existing.pdf", tempDir); olly2018.setFiles(List.of(linkedFile)); toral2006.setField(StandardField.AUTHOR, "Toral, Antonio and Munoz, Rafael"); toral2006.setField(StandardField.TITLE, "A proposal to automatically build and maintain gazetteers for Named Entity Recognition by using Wikipedia"); toral2006.setField(StandardField.BOOKTITLE, "Proceedings of EACL"); toral2006.setField(StandardField.PAGES, "56--61"); toral2006.setField(StandardField.EPRINTTYPE, "asdf"); toral2006.setField(StandardField.OWNER, "Ich"); toral2006.setField(StandardField.URL, "www.url.de"); toral2006.setFiles(List.of(new LinkedFile("non-existing", "path/to/nowhere.pdf", "PDF"))); vapnik2000.setCitationKey("vapnik2000"); vapnik2000.setField(StandardField.TITLE, "The Nature of Statistical Learning Theory"); vapnik2000.setField(StandardField.PUBLISHER, "Springer Science + Business Media"); vapnik2000.setField(StandardField.AUTHOR, "Vladimir N. Vapnik"); vapnik2000.setField(StandardField.DOI, "10.1007/978-1-4757-3264-1"); vapnik2000.setField(StandardField.OWNER, "Ich"); } /** * Create a temporary PDF-file with a single empty page. */ @BeforeEach void setUp() throws IOException { abbreviationRepository = mock(JournalAbbreviationRepository.class); filePreferences = mock(FilePreferences.class); when(filePreferences.getUserAndHost()).thenReturn(tempDir.toAbsolutePath().toString()); when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(false); BibDatabaseMode bibDatabaseMode = BibDatabaseMode.BIBTEX; BibEntryTypesManager bibEntryTypesManager = new BibEntryTypesManager(); FieldPreferences fieldPreferences = new FieldPreferences( true, List.of(StandardField.MONTH), Collections.emptyList()); exporter = new EmbeddedBibFilePdfExporter(bibDatabaseMode, bibEntryTypesManager, fieldPreferences); databaseContext = new BibDatabaseContext(); dataBase = databaseContext.getDatabase(); initBibEntries(); dataBase.insertEntry(olly2018); dataBase.insertEntry(toral2006); dataBase.insertEntry(vapnik2000); } @ParameterizedTest @MethodSource("provideBibEntriesWithValidPdfFileLinks") void successfulExportToAllFilesOfEntry(BibEntry bibEntryWithValidPdfFileLink) throws Exception { assertTrue(exporter.exportToAllFilesOfEntry(databaseContext, filePreferences, bibEntryWithValidPdfFileLink, List.of(olly2018), abbreviationRepository)); } @ParameterizedTest @MethodSource("provideBibEntriesWithInvalidPdfFileLinks") void unsuccessfulExportToAllFilesOfEntry(BibEntry bibEntryWithValidPdfFileLink) throws Exception { assertFalse(exporter.exportToAllFilesOfEntry(databaseContext, filePreferences, bibEntryWithValidPdfFileLink, List.of(olly2018), abbreviationRepository)); } public static Stream<Arguments> provideBibEntriesWithValidPdfFileLinks() { return Stream.of(Arguments.of(olly2018)); } public static Stream<Arguments> provideBibEntriesWithInvalidPdfFileLinks() { return Stream.of(Arguments.of(vapnik2000), Arguments.of(toral2006)); } @ParameterizedTest @MethodSource("providePathsToValidPDFs") void successfulExportToFileByPath(Path path) throws Exception { assertTrue(exporter.exportToFileByPath(databaseContext, dataBase, filePreferences, path, abbreviationRepository)); } @ParameterizedTest @MethodSource("providePathsToInvalidPDFs") void unsuccessfulExportToFileByPath(Path path) throws Exception { assertFalse(exporter.exportToFileByPath(databaseContext, dataBase, filePreferences, path, abbreviationRepository)); } public static Stream<Arguments> providePathsToValidPDFs() { return Stream.of(Arguments.of(tempDir.resolve("existing.pdf").toAbsolutePath())); } public static Stream<Arguments> providePathsToInvalidPDFs() throws IOException { LinkedFile existingFileThatIsNotLinked = createDefaultLinkedFile("notlinked.pdf", tempDir); return Stream.of( Arguments.of(Path.of("")), Arguments.of(tempDir.resolve("path/to/nowhere.pdf").toAbsolutePath()), Arguments.of(Path.of(existingFileThatIsNotLinked.getLink()))); } private static LinkedFile createDefaultLinkedFile(String fileName, Path tempDir) throws IOException { Path pdfFile = tempDir.resolve(fileName); try (PDDocument pdf = new PDDocument()) { pdf.addPage(new PDPage()); pdf.save(pdfFile.toAbsolutePath().toString()); } return new LinkedFile("A linked pdf", pdfFile, "PDF"); } }
8,013
44.534091
161
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/ExporterTest.java
package org.jabref.logic.exporter; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import javafx.collections.FXCollections; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.metadata.SaveOrder; import org.jabref.preferences.PreferencesService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; 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 ExporterTest { public BibDatabaseContext databaseContext; public List<BibEntry> entries; @BeforeEach public void setUp() { databaseContext = new BibDatabaseContext(); entries = Collections.emptyList(); } private static Stream<Object[]> exportFormats() { PreferencesService preferencesService = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS); when(preferencesService.getExportPreferences().getExportSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); when(preferencesService.getExportPreferences().getCustomExporters()).thenReturn(FXCollections.emptyObservableList()); ExporterFactory exporterFactory = ExporterFactory.create( preferencesService, mock(BibEntryTypesManager.class)); Collection<Object[]> result = new ArrayList<>(); for (Exporter format : exporterFactory.getExporters()) { result.add(new Object[]{format, format.getName()}); } return result.stream(); } @ParameterizedTest @MethodSource("exportFormats") public void testExportingEmptyDatabaseYieldsEmptyFile(Exporter exportFormat, String name, @TempDir Path testFolder) throws Exception { Path tmpFile = testFolder.resolve("ARandomlyNamedFile"); Files.createFile(tmpFile); exportFormat.export(databaseContext, tmpFile, entries); assertEquals(Collections.emptyList(), Files.readAllLines(tmpFile)); } @ParameterizedTest @MethodSource("exportFormats") public void testExportingNullDatabaseThrowsNPE(Exporter exportFormat, String name, @TempDir Path testFolder) { assertThrows(NullPointerException.class, () -> { Path tmpFile = testFolder.resolve("ARandomlyNamedFile"); Files.createFile(tmpFile); exportFormat.export(null, tmpFile, entries); }); } }
2,851
36.526316
138
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/GroupSerializerTest.java
package org.jabref.logic.exporter; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import javafx.scene.paint.Color; import org.jabref.logic.auxparser.DefaultAuxParser; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.StandardField; import org.jabref.model.groups.AllEntriesGroup; import org.jabref.model.groups.AutomaticGroup; import org.jabref.model.groups.AutomaticKeywordGroup; import org.jabref.model.groups.AutomaticPersonsGroup; import org.jabref.model.groups.ExplicitGroup; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.GroupTreeNode; import org.jabref.model.groups.GroupTreeNodeTest; import org.jabref.model.groups.KeywordGroup; import org.jabref.model.groups.RegexKeywordGroup; import org.jabref.model.groups.SearchGroup; import org.jabref.model.groups.TexGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.MetaData; 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; class GroupSerializerTest { private GroupSerializer groupSerializer; @BeforeEach void setUp() throws Exception { groupSerializer = new GroupSerializer(); } @Test void serializeSingleAllEntriesGroup() { AllEntriesGroup group = new AllEntriesGroup(""); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 AllEntriesGroup:"), serialization); } @Test void serializeSingleExplicitGroup() { ExplicitGroup group = new ExplicitGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, ','); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 StaticGroup:myExplicitGroup;0;1;;;;"), serialization); } @Test void serializeSingleExplicitGroupWithIconAndDescription() { ExplicitGroup group = new ExplicitGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, ','); group.setIconName("test icon"); group.setExpanded(true); group.setColor(Color.ALICEBLUE); group.setDescription("test description"); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 StaticGroup:myExplicitGroup;0;1;0xf0f8ffff;test icon;test description;"), serialization); } @Test // For https://github.com/JabRef/jabref/issues/1681 void serializeSingleExplicitGroupWithEscapedSlash() { ExplicitGroup group = new ExplicitGroup("B{\\\"{o}}hmer", GroupHierarchyType.INDEPENDENT, ','); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 StaticGroup:B{\\\\\"{o}}hmer;0;1;;;;"), serialization); } @Test void serializeSingleSimpleKeywordGroup() { WordKeywordGroup group = new WordKeywordGroup("name", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, "test", false, ',', false); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 KeywordGroup:name;0;keywords;test;0;0;1;;;;"), serialization); } @Test void serializeSingleRegexKeywordGroup() { KeywordGroup group = new RegexKeywordGroup("myExplicitGroup", GroupHierarchyType.REFINING, StandardField.AUTHOR, "asdf", false); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 KeywordGroup:myExplicitGroup;1;author;asdf;0;1;1;;;;"), serialization); } @Test void serializeSingleSearchGroup() { SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, "author=harrer", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION)); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 SearchGroup:myExplicitGroup;0;author=harrer;1;1;1;;;;"), serialization); } @Test void serializeSingleSearchGroupWithRegex() { SearchGroup group = new SearchGroup("myExplicitGroup", GroupHierarchyType.INCLUDING, "author=\"harrer\"", EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE)); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 SearchGroup:myExplicitGroup;2;author=\"harrer\";1;0;1;;;;"), serialization); } @Test void serializeSingleAutomaticKeywordGroup() { AutomaticGroup group = new AutomaticKeywordGroup("myAutomaticGroup", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ',', '>'); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 AutomaticKeywordGroup:myAutomaticGroup;0;keywords;,;>;1;;;;"), serialization); } @Test void serializeSingleAutomaticPersonGroup() { AutomaticPersonsGroup group = new AutomaticPersonsGroup("myAutomaticGroup", GroupHierarchyType.INDEPENDENT, StandardField.AUTHOR); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 AutomaticPersonsGroup:myAutomaticGroup;0;author;1;;;;"), serialization); } @Test void serializeSingleTexGroup() throws Exception { TexGroup group = TexGroup.create("myTexGroup", GroupHierarchyType.INDEPENDENT, Path.of("path", "To", "File"), new DefaultAuxParser(new BibDatabase()), new MetaData()); List<String> serialization = groupSerializer.serializeTree(GroupTreeNode.fromGroup(group)); assertEquals(Collections.singletonList("0 TexGroup:myTexGroup;0;path/To/File;1;;;;"), serialization); } @Test void getTreeAsStringInSimpleTree() throws Exception { GroupTreeNode root = GroupTreeNodeTest.getRoot(); GroupTreeNodeTest.getNodeInSimpleTree(root); List<String> expected = Arrays.asList( "0 AllEntriesGroup:", "1 StaticGroup:ExplicitA;2;1;;;;", "1 StaticGroup:ExplicitParent;0;1;;;;", "2 StaticGroup:ExplicitNode;1;1;;;;" ); assertEquals(expected, groupSerializer.serializeTree(root)); } @Test void getTreeAsStringInComplexTree() throws Exception { GroupTreeNode root = GroupTreeNodeTest.getRoot(); GroupTreeNodeTest.getNodeInComplexTree(root); List<String> expected = Arrays.asList( "0 AllEntriesGroup:", "1 SearchGroup:SearchA;2;searchExpression;1;0;1;;;;", "1 StaticGroup:ExplicitA;2;1;;;;", "1 StaticGroup:ExplicitGrandParent;0;1;;;;", "2 StaticGroup:ExplicitB;1;1;;;;", "2 KeywordGroup:KeywordParent;0;keywords;searchExpression;1;0;1;;;;", "3 KeywordGroup:KeywordNode;0;keywords;searchExpression;1;0;1;;;;", "4 StaticGroup:ExplicitChild;1;1;;;;", "3 SearchGroup:SearchC;2;searchExpression;1;0;1;;;;", "3 StaticGroup:ExplicitC;1;1;;;;", "3 KeywordGroup:KeywordC;0;keywords;searchExpression;1;0;1;;;;", "2 SearchGroup:SearchB;2;searchExpression;1;0;1;;;;", "2 KeywordGroup:KeywordB;0;keywords;searchExpression;1;0;1;;;;", "1 KeywordGroup:KeywordA;0;keywords;searchExpression;1;0;1;;;;" ); assertEquals(expected, groupSerializer.serializeTree(root)); } }
7,973
47.621951
208
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java
package org.jabref.logic.exporter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.metadata.SaveOrder; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class HtmlExportFormatTest { public BibDatabaseContext databaseContext; public Charset charset; public List<BibEntry> entries; private Exporter exportFormat; @BeforeEach public void setUp() { SaveConfiguration saveConfiguration = mock(SaveConfiguration.class); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); exportFormat = new TemplateExporter("HTML", "html", "html", null, StandardFileType.HTML, mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS), saveConfiguration); databaseContext = new BibDatabaseContext(); charset = StandardCharsets.UTF_8; BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "my paper title"); entry.setField(StandardField.AUTHOR, "Stefan Kolb"); entry.setCitationKey("mykey"); entries = List.of(entry); } @AfterEach public void tearDown() { exportFormat = null; } @Test public void emitWellFormedHtml(@TempDir Path testFolder) throws Exception { Path path = testFolder.resolve("ThisIsARandomlyNamedFile"); exportFormat.export(databaseContext, path, entries); List<String> lines = Files.readAllLines(path); assertEquals("</html>", lines.get(lines.size() - 1)); } }
2,252
32.626866
91
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/MSBibExportFormatFilesTest.java
package org.jabref.logic.exporter; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.xmlunit.matchers.CompareMatcher.isSimilarTo; public class MSBibExportFormatFilesTest { private static Path resourceDir; public BibDatabaseContext databaseContext; public Charset charset; private Path exportedFile; private MSBibExporter exporter; private BibtexImporter testImporter; static Stream<String> fileNames() throws IOException, URISyntaxException { // we have to point it to one existing file, otherwise it will return the default class path resourceDir = Path.of(MSBibExportFormatFilesTest.class.getResource("MsBibExportFormatTest1.bib").toURI()).getParent(); try (Stream<Path> stream = Files.list(resourceDir)) { return stream.map(n -> n.getFileName().toString()) .filter(n -> n.endsWith(".bib")) .filter(n -> n.startsWith("MsBib")) .collect(Collectors.toList()) .stream(); } } @BeforeEach void setUp(@TempDir Path testFolder) throws Exception { databaseContext = new BibDatabaseContext(); charset = StandardCharsets.UTF_8; exporter = new MSBibExporter(); Path path = testFolder.resolve("ARandomlyNamedFile.tmp"); exportedFile = Files.createFile(path); testImporter = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); } @ParameterizedTest(name = "{index} file={0}") @MethodSource("fileNames") void testPerformExport(String filename) throws IOException, SaveException { String xmlFileName = filename.replace(".bib", ".xml"); Path expectedFile = resourceDir.resolve(xmlFileName); Path importFile = resourceDir.resolve(filename); BibDatabaseContext contextFromImport = testImporter.importDatabase(importFile).getDatabaseContext(); List<BibEntry> entries = contextFromImport.getEntries(); contextFromImport.getDatabase().getStringValues().forEach(this.databaseContext.getDatabase()::addString); exporter.export(databaseContext, exportedFile, entries); String expected = String.join("\n", Files.readAllLines(expectedFile)); String actual = String.join("\n", Files.readAllLines(exportedFile)); // The order of elements changes from Windows to Travis environment somehow // The order does not really matter, so we ignore it. // Source: https://stackoverflow.com/a/16540679/873282 assertThat(expected, isSimilarTo(actual) .ignoreWhitespace() .normalizeWhitespace() .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))); } }
3,726
41.83908
137
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/MetaDataSerializerTest.java
package org.jabref.logic.exporter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import java.util.stream.Stream; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.cleanup.FieldFormatterCleanup; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.logic.formatter.casechanger.LowerCaseFormatter; import org.jabref.logic.importer.util.MetaDataParser; import org.jabref.logic.util.OS; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypeBuilder; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.FieldPriority; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.metadata.ContentSelector; import org.jabref.model.metadata.MetaData; 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 MetaDataSerializerTest { private static final EntryType CUSTOM_TYPE = new UnknownEntryType("customType"); private MetaData metaData; private GlobalCitationKeyPattern pattern; private BibEntryType newCustomType; @BeforeEach public void setUp() { metaData = new MetaData(); pattern = GlobalCitationKeyPattern.fromPattern("[auth][year]"); newCustomType = new BibEntryType( CUSTOM_TYPE, List.of(new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT)), Collections.emptySet()); } @Test public void serializeNewMetadataReturnsEmptyMap() { assertEquals(Collections.emptyMap(), MetaDataSerializer.getSerializedStringMap(metaData, pattern)); } @Test public void serializeSingleSaveAction() { FieldFormatterCleanups saveActions = new FieldFormatterCleanups(true, Collections.singletonList(new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter()))); metaData.setSaveActions(saveActions); Map<String, String> expectedSerialization = new TreeMap<>(); expectedSerialization.put("saveActions", "enabled;" + OS.NEWLINE + "title[lower_case]" + OS.NEWLINE + ";"); assertEquals(expectedSerialization, MetaDataSerializer.getSerializedStringMap(metaData, pattern)); } @Test public void serializeSingleContentSelectors() { List<String> values = List.of( "approved", "captured", "received", "status"); metaData.addContentSelector(new ContentSelector(StandardField.PUBSTATE, values)); Map<String, String> expectedSerialization = new TreeMap<>(); expectedSerialization.put("selector_pubstate", "approved;captured;received;status;"); assertEquals(expectedSerialization, MetaDataSerializer.getSerializedStringMap(metaData, pattern)); } @Test void testParsingEmptyOrFieldsReturnsEmptyCollections() { String serialized = MetaDataSerializer.serializeCustomEntryTypes(newCustomType); Optional<BibEntryType> type = MetaDataParser.parseCustomEntryType(serialized); assertEquals(Collections.emptySet(), type.get().getRequiredFields()); } @Test void testParsingEmptyOptionalFieldsFieldsReturnsEmptyCollections() { newCustomType = new BibEntryType( CUSTOM_TYPE, Collections.emptySet(), Collections.singleton(new OrFields(StandardField.AUTHOR))); String serialized = MetaDataSerializer.serializeCustomEntryTypes(newCustomType); Optional<BibEntryType> type = MetaDataParser.parseCustomEntryType(serialized); assertEquals(Collections.emptySet(), type.get().getOptionalFields()); } /** * Code clone of {@link org.jabref.logic.importer.util.MetaDataParserTest#parseCustomizedEntryType()} */ public static Stream<Arguments> serializeCustomizedEntryType() { return Stream.of( Arguments.of( new BibEntryTypeBuilder() .withType(new UnknownEntryType("test")) .withRequiredFields(StandardField.AUTHOR, StandardField.TITLE), "jabref-entrytype: test: req[author;title] opt[]" ), Arguments.of( new BibEntryTypeBuilder() .withType(new UnknownEntryType("test")) .withRequiredFields(StandardField.AUTHOR) .withImportantFields(StandardField.TITLE), "jabref-entrytype: test: req[author] opt[title]" ), Arguments.of( new BibEntryTypeBuilder() .withType(new UnknownEntryType("test")) .withRequiredFields(UnknownField.fromDisplayName("Test1"), UnknownField.fromDisplayName("Test2")), "jabref-entrytype: test: req[Test1;Test2] opt[]" ), Arguments.of( new BibEntryTypeBuilder() .withType(new UnknownEntryType("test")) .withRequiredFields(UnknownField.fromDisplayName("tEST"), UnknownField.fromDisplayName("tEsT2")), "jabref-entrytype: test: req[tEST;tEsT2] opt[]" ) ); } @ParameterizedTest @MethodSource void serializeCustomizedEntryType(BibEntryTypeBuilder bibEntryTypeBuilder, String expected) { assertEquals(expected, MetaDataSerializer.serializeCustomEntryTypes(bibEntryTypeBuilder.build())); } }
6,168
41.840278
130
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/ModsExportFormatFilesTest.java
package org.jabref.logic.exporter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; import org.jabref.logic.bibtex.BibEntryAssert; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.logic.importer.fileformat.ModsImporter; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.preferences.BibEntryPreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ModsExportFormatFilesTest { private static final Logger LOGGER = LoggerFactory.getLogger(ModsExportFormatFilesTest.class); private static Path resourceDir; public Charset charset; private BibDatabaseContext databaseContext; private Path exportedFile; private ModsExporter exporter; private BibtexImporter bibtexImporter; private ModsImporter modsImporter; private Path importFile; public static Stream<String> fileNames() throws Exception { resourceDir = Path.of(MSBibExportFormatFilesTest.class.getResource("ModsExportFormatTestAllFields.bib").toURI()).getParent(); LOGGER.debug("Mods export resouce dir {}", resourceDir); try (Stream<Path> stream = Files.list(resourceDir)) { return stream.map(n -> n.getFileName().toString()).filter(n -> n.endsWith(".bib")) .filter(n -> n.startsWith("Mods")).toList().stream(); } } @BeforeEach public void setUp(@TempDir Path testFolder) throws Exception { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences()).thenReturn(mock(BibEntryPreferences.class)); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); databaseContext = new BibDatabaseContext(); charset = StandardCharsets.UTF_8; exporter = new ModsExporter(); bibtexImporter = new BibtexImporter(importFormatPreferences, new DummyFileUpdateMonitor()); modsImporter = new ModsImporter(importFormatPreferences); Path path = testFolder.resolve("ARandomlyNamedFile.tmp"); Files.createFile(path); exportedFile = path.toAbsolutePath(); } @ParameterizedTest @MethodSource("fileNames") public final void testPerformExport(String filename) throws Exception { importFile = Path.of(ModsExportFormatFilesTest.class.getResource(filename).toURI()); String xmlFileName = filename.replace(".bib", ".xml"); List<BibEntry> entries = bibtexImporter.importDatabase(importFile).getDatabase().getEntries(); Path expectedFile = Path.of(ModsExportFormatFilesTest.class.getResource(xmlFileName).toURI()); exporter.export(databaseContext, exportedFile, entries); assertEquals( String.join("\n", Files.readAllLines(expectedFile)), String.join("\n", Files.readAllLines(exportedFile))); } @ParameterizedTest @MethodSource("fileNames") public final void testExportAsModsAndThenImportAsMods(String filename) throws Exception { importFile = Path.of(ModsExportFormatFilesTest.class.getResource(filename).toURI()); List<BibEntry> entries = bibtexImporter.importDatabase(importFile).getDatabase().getEntries(); exporter.export(databaseContext, exportedFile, entries); BibEntryAssert.assertEquals(entries, exportedFile, modsImporter); } @ParameterizedTest @MethodSource("fileNames") public final void testImportAsModsAndExportAsMods(String filename) throws Exception { importFile = Path.of(ModsExportFormatFilesTest.class.getResource(filename).toURI()); String xmlFileName = filename.replace(".bib", ".xml"); Path xmlFile = Path.of(ModsExportFormatFilesTest.class.getResource(xmlFileName).toURI()); List<BibEntry> entries = modsImporter.importDatabase(xmlFile).getDatabase().getEntries(); exporter.export(databaseContext, exportedFile, entries); assertEquals( String.join("\n", Files.readAllLines(xmlFile)), String.join("\n", Files.readAllLines(exportedFile))); } }
4,817
42.017857
133
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java
package org.jabref.logic.exporter; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.util.DummyFileUpdateMonitor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; public class ModsExportFormatTest { private ModsExporter modsExportFormat; private BibDatabaseContext databaseContext; @BeforeEach public void setUp() throws Exception { databaseContext = new BibDatabaseContext(); modsExportFormat = new ModsExporter(); new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); Path.of(ModsExportFormatTest.class.getResource("ModsExportFormatTestAllFields.bib").toURI()); } @Test public final void exportForNoEntriesWritesNothing(@TempDir Path tempFile) throws Exception { Path file = tempFile.resolve("ThisIsARandomlyNamedFile"); Files.createFile(file); modsExportFormat.export(databaseContext, tempFile, Collections.emptyList()); assertEquals(Collections.emptyList(), Files.readAllLines(file)); } }
1,485
35.243902
122
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/MsBibExportFormatTest.java
package org.jabref.logic.exporter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; 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; public class MsBibExportFormatTest { public BibDatabaseContext databaseContext; public MSBibExporter msBibExportFormat; @BeforeEach public void setUp() throws Exception { databaseContext = new BibDatabaseContext(); msBibExportFormat = new MSBibExporter(); } @Test public final void testPerformExportWithNoEntry(@TempDir Path tempFile) throws IOException, SaveException { Path path = tempFile.resolve("ThisIsARandomlyNamedFile"); Files.createFile(path); List<BibEntry> entries = Collections.emptyList(); msBibExportFormat.export(databaseContext, path, entries); assertEquals(Collections.emptyList(), Files.readAllLines(path)); } }
1,168
29.763158
110
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/OpenOfficeDocumentCreatorTest.java
package org.jabref.logic.exporter; import java.io.FileInputStream; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.jabref.model.database.BibDatabaseContext; 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 org.xmlunit.builder.Input; import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher; import static org.hamcrest.MatcherAssert.assertThat; public class OpenOfficeDocumentCreatorTest { public BibDatabaseContext databaseContext; public Charset charset; public List<BibEntry> entries; private Path xmlFile; private Exporter exporter; @BeforeEach void setUp() throws URISyntaxException { xmlFile = Path.of(OpenOfficeDocumentCreatorTest.class.getResource("OldOpenOfficeCalcExportFormatContentSingleEntry.xml").toURI()); exporter = new OpenOfficeDocumentCreator(); databaseContext = new BibDatabaseContext(); charset = StandardCharsets.UTF_8; BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setField(StandardField.ADDRESS, "New York, NY, USA"); entry.setField(StandardField.TITLE, "Design and usability in security systems: daily life as a context of use?"); entry.setField(StandardField.AUTHOR, "Tony Clear"); entry.setField(StandardField.ISSN, "0097-8418"); entry.setField(StandardField.DOI, "http://doi.acm.org/10.1145/820127.820136"); entry.setField(StandardField.JOURNAL, "SIGCSE Bull."); entry.setField(StandardField.NUMBER, "4"); entry.setField(StandardField.PAGES, "13--14"); entry.setField(StandardField.PUBLISHER, "ACM"); entry.setField(StandardField.VOLUME, "34"); entry.setField(StandardField.YEAR, "2002"); entries = Collections.singletonList(entry); } @Test void testPerformExportForSingleEntry(@TempDir Path testFolder) throws Exception { Path zipPath = testFolder.resolve("OpenOfficeRandomNamedFile"); exporter.export(databaseContext, zipPath, entries); Path unzipFolder = testFolder.resolve("unzipFolder"); unzipContentXml(zipPath, testFolder.resolve(unzipFolder)); Path contentXmlPath = unzipFolder.resolve("content.xml"); Input.Builder control = Input.from(Files.newInputStream(xmlFile)); Input.Builder test = Input.from(Files.newInputStream(contentXmlPath)); // for debugging purposes // Path testPath = xmlFile.resolveSibling("test.xml"); // Files.copy(Files.newInputStream(contentXmlPath), testPath, StandardCopyOption.REPLACE_EXISTING); assertThat(test, CompareMatcher.isSimilarTo(control) .normalizeWhitespace() .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText)).throwComparisonFailure()); } private static void unzipContentXml(Path zipFile, Path unzipFolder) throws IOException { try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile.toFile()))) { ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { boolean isContentXml = "content.xml".equals(zipEntry.getName()); Path newPath = zipSlipProtect(zipEntry, unzipFolder); if (isContentXml) { if (newPath.getParent() != null) { if (Files.notExists(newPath.getParent())) { Files.createDirectories(newPath.getParent()); } } Files.copy(zis, newPath, StandardCopyOption.REPLACE_EXISTING); } zipEntry = zis.getNextEntry(); } zis.closeEntry(); } } // protect zip slip attack: https://snyk.io/research/zip-slip-vulnerability private static Path zipSlipProtect(ZipEntry zipEntry, Path targetDir) throws IOException { Path targetDirResolved = targetDir.resolve(zipEntry.getName()); Path normalizePath = targetDirResolved.normalize(); if (!normalizePath.startsWith(targetDir)) { throw new IOException("Bad zip entry: " + zipEntry.getName()); } return normalizePath; } }
4,833
39.283333
138
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/XmpExporterTest.java
package org.jabref.logic.exporter; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.xmp.XmpPreferences; import org.jabref.model.database.BibDatabaseContext; 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 static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class XmpExporterTest { private Exporter exporter; private final BibDatabaseContext databaseContext = new BibDatabaseContext(); private final XmpPreferences xmpPreferences = mock(XmpPreferences.class); @BeforeEach public void setUp() { exporter = new XmpExporter(xmpPreferences); } @Test public void exportSingleEntry(@TempDir Path testFolder) throws Exception { Path file = testFolder.resolve("ThisIsARandomlyNamedFile"); Files.createFile(file); BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "Alan Turing"); exporter.export(databaseContext, file, Collections.singletonList(entry)); String actual = String.join("\n", Files.readAllLines(file)); // we are using \n to join, so we need it in the expected string as well, \r\n would fail String expected = """ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about=""> <dc:creator> <rdf:Seq> <rdf:li>Alan Turing</rdf:li> </rdf:Seq> </dc:creator> <dc:format>application/pdf</dc:format> <dc:type> <rdf:Bag> <rdf:li>Misc</rdf:li> </rdf:Bag> </dc:type> </rdf:Description> </rdf:RDF> """.stripTrailing(); assertEquals(expected, actual); } @Test public void writeMultipleEntriesInASingleFile(@TempDir Path testFolder) throws Exception { Path file = testFolder.resolve("ThisIsARandomlyNamedFile"); Files.createFile(file); BibEntry entryTuring = new BibEntry(); entryTuring.setField(StandardField.AUTHOR, "Alan Turing"); BibEntry entryArmbrust = new BibEntry(); entryArmbrust.setField(StandardField.AUTHOR, "Michael Armbrust"); entryArmbrust.setCitationKey("Armbrust2010"); exporter.export(databaseContext, file, Arrays.asList(entryTuring, entryArmbrust)); String actual = String.join("\n", Files.readAllLines(file)); // we are using \n to join, so we need it in the expected string as well, \r\n would fail String expected = """ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about=""> <dc:creator> <rdf:Seq> <rdf:li>Alan Turing</rdf:li> </rdf:Seq> </dc:creator> <dc:format>application/pdf</dc:format> <dc:type> <rdf:Bag> <rdf:li>Misc</rdf:li> </rdf:Bag> </dc:type> </rdf:Description> <rdf:Description xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about=""> <dc:creator> <rdf:Seq> <rdf:li>Michael Armbrust</rdf:li> </rdf:Seq> </dc:creator> <dc:relation> <rdf:Bag> <rdf:li>bibtex/citationkey/Armbrust2010</rdf:li> </rdf:Bag> </dc:relation> <dc:format>application/pdf</dc:format> <dc:type> <rdf:Bag> <rdf:li>Misc</rdf:li> </rdf:Bag> </dc:type> </rdf:Description> </rdf:RDF> """.stripTrailing(); assertEquals(expected, actual); } @Test public void writeMultipleEntriesInDifferentFiles(@TempDir Path testFolder) throws Exception { // set path to the one where the exporter produces several files Path file = testFolder.resolve(XmpExporter.XMP_SPLIT_DIRECTORY_INDICATOR); Files.createFile(file); BibEntry entryTuring = new BibEntry() .withField(StandardField.AUTHOR, "Alan Turing"); BibEntry entryArmbrust = new BibEntry() .withField(StandardField.AUTHOR, "Michael Armbrust") .withCitationKey("Armbrust2010"); exporter.export(databaseContext, file, List.of(entryTuring, entryArmbrust)); // Nothing written in given file List<String> lines = Files.readAllLines(file); assertEquals(Collections.emptyList(), lines); // turing contains the turing entry only Path fileTuring = Path.of(file.getParent().toString(), entryTuring.getId() + "_null.xmp"); // we are using \n to join, so we need it in the expected string as well, \r\n would fail String actualTuring = String.join("\n", Files.readAllLines(fileTuring)); String expectedTuring = """ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about=""> <dc:creator> <rdf:Seq> <rdf:li>Alan Turing</rdf:li> </rdf:Seq> </dc:creator> <dc:format>application/pdf</dc:format> <dc:type> <rdf:Bag> <rdf:li>Misc</rdf:li> </rdf:Bag> </dc:type> </rdf:Description> </rdf:RDF> """.stripTrailing(); assertEquals(expectedTuring, actualTuring); // armbrust contains the armbrust entry only Path fileArmbrust = Path.of(file.getParent().toString(), entryArmbrust.getId() + "_Armbrust2010.xmp"); // we are using \n to join, so we need it in the expected string as well, \r\n would fail String actualArmbrust = String.join("\n", Files.readAllLines(fileArmbrust)); String expectedArmbrust = """ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about=""> <dc:creator> <rdf:Seq> <rdf:li>Michael Armbrust</rdf:li> </rdf:Seq> </dc:creator> <dc:relation> <rdf:Bag> <rdf:li>bibtex/citationkey/Armbrust2010</rdf:li> </rdf:Bag> </dc:relation> <dc:format>application/pdf</dc:format> <dc:type> <rdf:Bag> <rdf:li>Misc</rdf:li> </rdf:Bag> </dc:type> </rdf:Description> </rdf:RDF> """.stripTrailing(); assertEquals(expectedArmbrust, actualArmbrust); } @Test public void exportSingleEntryWithPrivacyFilter(@TempDir Path testFolder) throws Exception { when(xmpPreferences.getXmpPrivacyFilter()).thenReturn(FXCollections.observableSet(Collections.singleton(StandardField.AUTHOR))); when(xmpPreferences.shouldUseXmpPrivacyFilter()).thenReturn(true); Path file = testFolder.resolve("ThisIsARandomlyNamedFile"); Files.createFile(file); BibEntry entry = new BibEntry() .withField(StandardField.AUTHOR, "Alan Turing"); exporter.export(databaseContext, file, Collections.singletonList(entry)); String actual = String.join("\n", Files.readAllLines(file)); String expected = """ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about=""> <dc:format>application/pdf</dc:format> <dc:type> <rdf:Bag> <rdf:li>Misc</rdf:li> </rdf:Bag> </dc:type> </rdf:Description> </rdf:RDF> """.stripTrailing(); assertEquals(expected, actual); } }
9,325
41.584475
158
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/XmpPdfExporterTest.java
package org.jabref.logic.exporter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import javafx.beans.property.SimpleObjectProperty; import org.jabref.logic.importer.fileformat.PdfXmpImporter; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.xmp.XmpPreferences; 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.Month; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.preferences.FilePreferences; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; 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.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class XmpPdfExporterTest { @TempDir static Path tempDir; private static BibEntry olly2018 = new BibEntry(StandardEntryType.Article); private static BibEntry toral2006 = new BibEntry(StandardEntryType.Article); private static BibEntry vapnik2000 = new BibEntry(StandardEntryType.Article); private PdfXmpImporter importer; private XmpPdfExporter exporter; private XmpPreferences xmpPreferences; private Charset encoding; private BibDatabaseContext databaseContext; private BibDatabase dataBase; private JournalAbbreviationRepository abbreviationRepository; private FilePreferences filePreferences; private static void initBibEntries() throws IOException { olly2018.setCitationKey("Olly2018"); olly2018.setField(StandardField.AUTHOR, "Olly and Johannes"); olly2018.setField(StandardField.TITLE, "Stefan's palace"); olly2018.setField(StandardField.JOURNAL, "Test Journal"); olly2018.setField(StandardField.VOLUME, "1"); olly2018.setField(StandardField.NUMBER, "1"); olly2018.setField(StandardField.PAGES, "1-2"); olly2018.setMonth(Month.MARCH); olly2018.setField(StandardField.ISSN, "978-123-123"); olly2018.setField(StandardField.NOTE, "NOTE"); olly2018.setField(StandardField.ABSTRACT, "ABSTRACT"); olly2018.setField(StandardField.COMMENT, "COMMENT"); olly2018.setField(StandardField.DOI, "10/3212.3123"); olly2018.setField(StandardField.FILE, ":article_dublinCore.pdf:PDF"); olly2018.setField(StandardField.GROUPS, "NO"); olly2018.setField(StandardField.HOWPUBLISHED, "online"); olly2018.setField(StandardField.KEYWORDS, "k1, k2"); olly2018.setField(StandardField.OWNER, "me"); olly2018.setField(StandardField.REVIEW, "review"); olly2018.setField(StandardField.URL, "https://www.olly2018.edu"); LinkedFile linkedFile = createDefaultLinkedFile("existing.pdf", tempDir); olly2018.setFiles(List.of(linkedFile)); toral2006.setField(StandardField.AUTHOR, "Toral, Antonio and Munoz, Rafael"); toral2006.setField(StandardField.TITLE, "A proposal to automatically build and maintain gazetteers for Named Entity Recognition by using Wikipedia"); toral2006.setField(StandardField.BOOKTITLE, "Proceedings of EACL"); toral2006.setField(StandardField.PAGES, "56--61"); toral2006.setField(StandardField.EPRINTTYPE, "asdf"); toral2006.setField(StandardField.OWNER, "Ich"); toral2006.setField(StandardField.URL, "www.url.de"); toral2006.setFiles(List.of(new LinkedFile("non-existing", "path/to/nowhere.pdf", "PDF"))); vapnik2000.setCitationKey("vapnik2000"); vapnik2000.setField(StandardField.TITLE, "The Nature of Statistical Learning Theory"); vapnik2000.setField(StandardField.PUBLISHER, "Springer Science + Business Media"); vapnik2000.setField(StandardField.AUTHOR, "Vladimir N. Vapnik"); vapnik2000.setField(StandardField.DOI, "10.1007/978-1-4757-3264-1"); vapnik2000.setField(StandardField.OWNER, "Ich"); } /** * Create a temporary PDF-file with a single empty page. */ @BeforeEach void setUp() throws IOException { abbreviationRepository = mock(JournalAbbreviationRepository.class); xmpPreferences = new XmpPreferences(false, Collections.emptySet(), new SimpleObjectProperty<>(',')); encoding = Charset.defaultCharset(); filePreferences = mock(FilePreferences.class); when(filePreferences.getUserAndHost()).thenReturn(tempDir.toAbsolutePath().toString()); when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(false); importer = new PdfXmpImporter(xmpPreferences); exporter = new XmpPdfExporter(xmpPreferences); databaseContext = new BibDatabaseContext(); dataBase = databaseContext.getDatabase(); initBibEntries(); dataBase.insertEntry(olly2018); dataBase.insertEntry(toral2006); dataBase.insertEntry(vapnik2000); } @ParameterizedTest @MethodSource("provideBibEntriesWithValidPdfFileLinks") void successfulExportToAllFilesOfEntry(BibEntry bibEntryWithValidPdfFileLink) throws Exception { assertTrue(exporter.exportToAllFilesOfEntry(databaseContext, filePreferences, bibEntryWithValidPdfFileLink, List.of(olly2018), abbreviationRepository)); } @ParameterizedTest @MethodSource("provideBibEntriesWithInvalidPdfFileLinks") void unsuccessfulExportToAllFilesOfEntry(BibEntry bibEntryWithValidPdfFileLink) throws Exception { assertFalse(exporter.exportToAllFilesOfEntry(databaseContext, filePreferences, bibEntryWithValidPdfFileLink, List.of(olly2018), abbreviationRepository)); } public static Stream<Arguments> provideBibEntriesWithValidPdfFileLinks() { return Stream.of(Arguments.of(olly2018)); } public static Stream<Arguments> provideBibEntriesWithInvalidPdfFileLinks() { return Stream.of(Arguments.of(vapnik2000), Arguments.of(toral2006)); } @ParameterizedTest @MethodSource("providePathsToValidPDFs") void successfulExportToFileByPath(Path path) throws Exception { assertTrue(exporter.exportToFileByPath(databaseContext, dataBase, filePreferences, path, abbreviationRepository)); } @ParameterizedTest @MethodSource("providePathsToInvalidPDFs") void unsuccessfulExportToFileByPath(Path path) throws Exception { assertFalse(exporter.exportToFileByPath(databaseContext, dataBase, filePreferences, path, abbreviationRepository)); } public static Stream<Arguments> providePathsToValidPDFs() { return Stream.of(Arguments.of(tempDir.resolve("existing.pdf").toAbsolutePath())); } public static Stream<Arguments> providePathsToInvalidPDFs() throws IOException { LinkedFile existingFileThatIsNotLinked = createDefaultLinkedFile("notlinked.pdf", tempDir); return Stream.of( Arguments.of(Path.of("")), Arguments.of(tempDir.resolve("path/to/nowhere.pdf").toAbsolutePath()), Arguments.of(Path.of(existingFileThatIsNotLinked.getLink()))); } private static LinkedFile createDefaultLinkedFile(String fileName, Path tempDir) throws IOException { Path pdfFile = tempDir.resolve(fileName); try (PDDocument pdf = new PDDocument()) { pdf.addPage(new PDPage()); pdf.save(pdfFile.toAbsolutePath().toString()); } return new LinkedFile("A linked pdf", pdfFile, "PDF"); } }
7,972
43.541899
161
java
null
jabref-main/src/test/java/org/jabref/logic/exporter/YamlExporterTest.java
package org.jabref.logic.exporter; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.metadata.SaveOrder; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class YamlExporterTest { private static Exporter yamlExporter; private static BibDatabaseContext databaseContext; @BeforeAll static void setUp() { SaveConfiguration saveConfiguration = mock(SaveConfiguration.class); when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder()); yamlExporter = new TemplateExporter( "CSL YAML", "yaml", "yaml", null, StandardFileType.YAML, mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS), saveConfiguration, BlankLineBehaviour.DELETE_BLANKS); databaseContext = new BibDatabaseContext(); } @Test public final void exportForNoEntriesWritesNothing(@TempDir Path tempFile) throws Exception { Path file = tempFile.resolve("ThisIsARandomlyNamedFile"); Files.createFile(file); yamlExporter.export(databaseContext, tempFile, Collections.emptyList()); assertEquals(Collections.emptyList(), Files.readAllLines(file)); } @Test public final void exportsCorrectContent(@TempDir Path tempFile) throws Exception { BibEntry entry = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.URL, "http://example.com") .withField(StandardField.DATE, "2020-10-14"); Path file = tempFile.resolve("RandomFileName"); Files.createFile(file); yamlExporter.export(databaseContext, file, Collections.singletonList(entry)); List<String> expected = List.of( "---", "references:", "- id: test", " type: article", " author:", " - literal: \"Test Author\"", " title: \"Test Title\"", " issued: 2020-10-14", " url: http://example.com", "---"); assertEquals(expected, Files.readAllLines(file)); } @Test public final void formatsContentCorrect(@TempDir Path tempFile) throws Exception { BibEntry entry = new BibEntry(StandardEntryType.Misc) .withCitationKey("test") .withField(StandardField.AUTHOR, "Test Author") .withField(StandardField.TITLE, "Test Title") .withField(StandardField.URL, "http://example.com") .withField(StandardField.DATE, "2020-10-14"); Path file = tempFile.resolve("RandomFileName"); Files.createFile(file); yamlExporter.export(databaseContext, file, Collections.singletonList(entry)); List<String> expected = List.of( "---", "references:", "- id: test", " type: no-type", " author:", " - literal: \"Test Author\"", " title: \"Test Title\"", " issued: 2020-10-14", " url: http://example.com", "---"); assertEquals(expected, Files.readAllLines(file)); } @Test void passesModifiedCharset(@TempDir Path tempFile) throws Exception { BibEntry entry = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "谷崎 潤一郎") .withField(StandardField.TITLE, "細雪") .withField(StandardField.URL, "http://example.com") .withField(StandardField.DATE, "2020-10-14"); Path file = tempFile.resolve("RandomFileName"); Files.createFile(file); yamlExporter.export(databaseContext, file, Collections.singletonList(entry)); List<String> expected = List.of( "---", "references:", "- id: test", " type: article", " author:", " - literal: \"谷崎 潤一郎\"", " title: \"細雪\"", " issued: 2020-10-14", " url: http://example.com", "---"); assertEquals(expected, Files.readAllLines(file)); } @Test void passesModifiedCharsetNull(@TempDir Path tempFile) throws Exception { BibEntry entry = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "谷崎 潤一郎") .withField(StandardField.TITLE, "細雪") .withField(StandardField.URL, "http://example.com") .withField(StandardField.DATE, "2020-10-14"); Path file = tempFile.resolve("RandomFileName"); Files.createFile(file); yamlExporter.export(databaseContext, file, Collections.singletonList(entry)); List<String> expected = List.of( "---", "references:", "- id: test", " type: article", " author:", " - literal: \"谷崎 潤一郎\"", " title: \"細雪\"", " issued: 2020-10-14", " url: http://example.com", "---"); assertEquals(expected, Files.readAllLines(file)); } }
6,145
35.802395
96
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/FormatterTest.java
package org.jabref.logic.formatter; import java.util.Collections; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.cleanup.Formatter; import org.jabref.logic.formatter.casechanger.ProtectTermsFormatter; import org.jabref.logic.formatter.minifier.TruncateFormatter; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.protectedterms.ProtectedTermsPreferences; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; 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; class FormatterTest { private static ProtectedTermsLoader protectedTermsLoader; @BeforeAll static void setUp() { protectedTermsLoader = new ProtectedTermsLoader( new ProtectedTermsPreferences(ProtectedTermsLoader.getInternalLists(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); } /** * When a new formatter is added by copy and pasting another formatter, it may happen that the <code>getKey()</code> * method is not adapted. This results in duplicate keys, which this test tests for. */ @Test public void allFormatterKeysAreUnique() { // idea for uniqueness checking by https://stackoverflow.com/a/44032568/873282 assertEquals(Collections.emptyList(), getFormatters().collect(Collectors.groupingBy( Formatter::getKey, Collectors.counting())) .entrySet().stream() .filter(e -> e.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toList())); } @ParameterizedTest @MethodSource("getFormatters") void getNameReturnsNotNull(Formatter formatter) { assertNotNull(formatter.getName()); } @ParameterizedTest @MethodSource("getFormatters") void getNameReturnsNotEmpty(Formatter formatter) { assertNotEquals("", formatter.getName()); } @ParameterizedTest @MethodSource("getFormatters") void getKeyReturnsNotNull(Formatter formatter) { assertNotNull(formatter.getKey()); } @ParameterizedTest @MethodSource("getFormatters") void getKeyReturnsNotEmpty(Formatter formatter) { assertNotEquals("", formatter.getKey()); } @ParameterizedTest @MethodSource("getFormatters") void formatOfNullThrowsException(Formatter formatter) { assertThrows(NullPointerException.class, () -> formatter.format(null)); } @ParameterizedTest @MethodSource("getFormatters") void formatOfEmptyStringReturnsEmpty(Formatter formatter) { assertEquals("", formatter.format("")); } @ParameterizedTest @MethodSource("getFormatters") void formatNotReturnsNull(Formatter formatter) { assertNotNull(formatter.format("string")); } @ParameterizedTest @MethodSource("getFormatters") void getDescriptionAlwaysNonEmpty(Formatter formatter) { assertFalse(formatter.getDescription().isEmpty()); } @ParameterizedTest @MethodSource("getFormatters") void getExampleInputAlwaysNonEmpty(Formatter formatter) { assertFalse(formatter.getExampleInput().isEmpty()); } public static Stream<Formatter> getFormatters() { // all classes implementing {@link net.sf.jabref.model.cleanup.Formatter} // Alternative: Use reflection - https://github.com/ronmamo/reflections // @formatter:off return Stream.concat( Formatters.getAll().stream(), // following formatters are not contained in the list of all formatters, because // - the IdentityFormatter is not offered to the user, // - the ProtectTermsFormatter needs more configuration, // - the TruncateFormatter needs setup, Stream.of( new IdentityFormatter(), new ProtectTermsFormatter(protectedTermsLoader), new TruncateFormatter(0))); // @formatter:on } }
4,587
36
120
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/IdentityFormatterTest.java
package org.jabref.logic.formatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class IdentityFormatterTest { private IdentityFormatter formatter; @BeforeEach public void setUp() { formatter = new IdentityFormatter(); } @Test public void formatExample() { assertEquals("JabRef", formatter.format(formatter.getExampleInput())); } }
585
22.44
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/AddBracesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ class AddBracesFormatterTest { private AddBracesFormatter formatter; @BeforeEach public void setUp() { formatter = new AddBracesFormatter(); } @Test public void formatAddsSingleEnclosingBraces() { assertEquals("{test}", formatter.format("test")); } @Test public void formatKeepsUnmatchedBracesAtBeginning() { assertEquals("{test", formatter.format("{test")); } @Test public void formatKeepsUnmatchedBracesAtEnd() { assertEquals("test}", formatter.format("test}")); } @Test public void formatKeepsShortString() { assertEquals("t", formatter.format("t")); } @Test public void formatKeepsEmptyString() { assertEquals("", formatter.format("")); } @Test public void formatKeepsDoubleEnclosingBraces() { assertEquals("{{test}}", formatter.format("{{test}}")); } @Test public void formatKeepsTripleEnclosingBraces() { assertEquals("{{{test}}}", formatter.format("{{{test}}}")); } @Test public void formatKeepsNonMatchingBraces() { assertEquals("{A} and {B}", formatter.format("{A} and {B}")); } @Test public void formatKeepsOnlyMatchingBraces() { assertEquals("{{A} and {B}}", formatter.format("{{A} and {B}}")); } @Test public void formatDoesNotRemoveBracesInBrokenString() { // We opt here for a conservative approach although one could argue that "A} and {B}" is also a valid return assertEquals("{A} and {B}}", formatter.format("{A} and {B}}")); } @Test public void formatExample() { assertEquals("{In CDMA}", formatter.format(formatter.getExampleInput())); } @Test public void formatStringWithMinimalRequiredLength() { assertEquals("{AB}", formatter.format("AB")); } }
2,146
25.506173
116
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/CleanupUrlFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ class CleanupUrlFormatterTest { private CleanupUrlFormatter formatter; @BeforeEach void setUp() { formatter = new CleanupUrlFormatter(); } @Test void removeSpecialSymbolsFromURLLink() { assertEquals("http://wikipedia.org", formatter.format("http%3A%2F%2Fwikipedia.org")); } @Test void extractURLFormLink() { assertEquals("http://wikipedia.org", formatter.format("away.php?to=http%3A%2F%2Fwikipedia.org&a=snippet")); } @Test void validUrlUnmodified() { assertEquals("http://wikipedia.org", formatter.format("http://wikipedia.org")); } @Test void latexCommandsNotRemoved() { 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")); } @Test void urlencodedSlashesAreAlsoConverted() { // the caller has to pay attention that this does not happen assertEquals("jabref.org/test/test", formatter.format("jabref.org/test%2Ftest")); } @Test void formatExample() { assertEquals("http://www.focus.de/" + "gesundheit/ratgeber/herz/test/lebenserwartung-werden-sie-100-jahre-alt_aid_363828.html", formatter.format(formatter.getExampleInput())); } @Test void shouldNotReplacePlusOperatorAsASignInURL() { assertEquals( "https://www.chicago.gov/content/dam/city/depts/cdot/Red Light Cameras/2022/Sutton+Tilahun_Chicago-Camera-Ticket_Exec Summary-Final-Jan10.pdf", formatter.format("https://www.chicago.gov/content/dam/city/depts/cdot/Red Light Cameras/2022/Sutton+Tilahun_Chicago-Camera-Ticket_Exec Summary-Final-Jan10.pdf") ); } }
2,184
33.68254
247
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/ClearFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class ClearFormatterTest { private ClearFormatter formatter; @BeforeEach public void setUp() { formatter = new ClearFormatter(); } /** * Check whether the clear formatter really returns the empty string for the empty string */ @Test public void formatReturnsEmptyForEmptyString() throws Exception { assertEquals("", formatter.format("")); } /** * Check whether the clear formatter really returns the empty string for some string */ @Test public void formatReturnsEmptyForSomeString() throws Exception { assertEquals("", formatter.format("test")); } @Test public void formatExample() { assertEquals("", formatter.format(formatter.getExampleInput())); } }
1,071
25.146341
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/EscapeAmpersandsFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class EscapeAmpersandsFormatterTest { private EscapeAmpersandsFormatter formatter; @BeforeEach void setUp() { formatter = new EscapeAmpersandsFormatter(); } @Test void formatReturnsSameTextIfNoAmpersandsPresent() throws Exception { assertEquals("Lorem ipsum", formatter.format("Lorem ipsum")); } @Test void formatEscapesAmpersandsIfPresent() throws Exception { assertEquals("Lorem\\&ipsum", formatter.format("Lorem&ipsum")); } @Test void formatExample() { assertEquals("Text \\& with \\&ampersands", formatter.format(formatter.getExampleInput())); } @Test void formatReturnsSameTextInNewUserDefinedLatexCommandIfNoAmpersandsPresent() throws Exception { assertEquals("\\newcommand[1]{Lorem ipsum}", formatter.format("\\newcommand[1]{Lorem ipsum}")); } @Test void formatReturnsSameTextInLatexCommandIfOneAmpersandPresent() throws Exception { assertEquals("\\textbf{Lorem\\&ipsum}", formatter.format("\\textbf{Lorem\\&ipsum}")); } }
1,250
28.785714
103
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/EscapeDollarSignFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; 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; class EscapeDollarSignFormatterTest { private EscapeDollarSignFormatter formatter = new EscapeDollarSignFormatter(); private static Stream<Arguments> correctlyFormats() { return Stream.of( // formatReturnsSameTextIfNoDollarSignPresent Arguments.of("Lorem ipsum", "Lorem ipsum"), // formatEscapesDollarSignIfPresent Arguments.of("Lorem\\$ipsum", "Lorem$ipsum"), // keeps escapings Arguments.of("Lorem\\$ipsum", "Lorem\\$ipsum"), Arguments.of("Dollar sign: 1x: \\$ 2x: \\$\\$ 3x: \\$\\$\\$", "Dollar sign: 1x: \\$ 2x: \\$\\$ 3x: \\$\\$\\$"), // mixed field Arguments.of("Dollar sign: 1x: \\$ 2x: \\$\\$ 3x: \\$\\$\\$", "Dollar sign: 1x: $ 2x: $$ 3x: $$$") ); } @ParameterizedTest @MethodSource void correctlyFormats(String expected, String input) throws Exception { assertEquals(expected, formatter.format(input)); } @Test void formatExample() { assertEquals("Text\\$with\\$dollar\\$sign", formatter.format(formatter.getExampleInput())); } }
1,499
35.585366
127
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/EscapeUnderscoresFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class EscapeUnderscoresFormatterTest { private EscapeUnderscoresFormatter formatter; @BeforeEach void setUp() { formatter = new EscapeUnderscoresFormatter(); } @Test void formatReturnsSameTextIfNoUnderscoresPresent() throws Exception { assertEquals("Lorem ipsum", formatter.format("Lorem ipsum")); } @Test void formatEscapesUnderscoresIfPresent() throws Exception { assertEquals("Lorem\\_ipsum", formatter.format("Lorem_ipsum")); } @Test void formatExample() { assertEquals("Text\\_with\\_underscores", formatter.format(formatter.getExampleInput())); } }
833
25.0625
97
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToLatexFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class HtmlToLatexFormatterTest { private HtmlToLatexFormatter formatter; @BeforeEach public void setUp() { formatter = new HtmlToLatexFormatter(); } @Test public void formatWithoutHtmlCharactersReturnsSameString() { assertEquals("abc", formatter.format("abc")); } @Test public void formatMultipleHtmlCharacters() { assertEquals("{{\\aa}}{\\\"{a}}{\\\"{o}}", formatter.format("&aring;&auml;&ouml;")); } @Test public void formatCombinedAccent() { assertEquals("{\\'{\\i}}", formatter.format("i&#x301;")); } @Test public void testBasic() { assertEquals("aaa", formatter.format("aaa")); } @Test public void testHTML() { assertEquals("{\\\"{a}}", formatter.format("&auml;")); assertEquals("{\\\"{a}}", formatter.format("&#228;")); assertEquals("{\\\"{a}}", formatter.format("&#xe4;")); assertEquals("{{$\\Epsilon$}}", formatter.format("&Epsilon;")); } @Test public void testHTMLRemoveTags() { assertEquals("aaa", formatter.format("<b>aaa</b>")); } @Test public void testHTMLCombiningAccents() { assertEquals("{\\\"{a}}", formatter.format("a&#776;")); assertEquals("{\\\"{a}}", formatter.format("a&#x308;")); assertEquals("{\\\"{a}}b", formatter.format("a&#776;b")); assertEquals("{\\\"{a}}b", formatter.format("a&#x308;b")); } @Test public void keepsSingleLessThan() { String text = "(p < 0.01)"; assertEquals(text, formatter.format(text)); } @Test public void formatExample() { assertEquals("JabRef", formatter.format(formatter.getExampleInput())); } }
2,020
27.069444
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/HtmlToUnicodeFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; 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 HtmlToUnicodeFormatterTest { private HtmlToUnicodeFormatter formatter; private static Stream<Arguments> data() { return Stream.of( Arguments.of("abc", "abc"), Arguments.of("åäö", "&aring;&auml;&ouml;"), Arguments.of("í", "i&#x301;"), Arguments.of("Ε", "&Epsilon;"), Arguments.of("ä", "&auml;"), Arguments.of("ä", "&#228;"), Arguments.of("ä", "&#xe4;"), Arguments.of("ñ", "&#241;"), Arguments.of("aaa", "<p>aaa</p>"), Arguments.of("bread & butter", "<b>bread</b> &amp; butter")); } @BeforeEach public void setUp() { formatter = new HtmlToUnicodeFormatter(); } @ParameterizedTest @MethodSource("data") void testFormatterWorksCorrectly(String expected, String input) { assertEquals(expected, formatter.format(input)); } }
1,396
33.073171
86
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/LatexCleanupFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class LatexCleanupFormatterTest { private LatexCleanupFormatter formatter; @BeforeEach void setUp() { formatter = new LatexCleanupFormatter(); } @Test void test() { assertEquals("$\\alpha\\beta$", formatter.format("$\\alpha$$\\beta$")); assertEquals("{VLSI DSP}", formatter.format("{VLSI} {DSP}")); assertEquals("\\textbf{VLSI} {DSP}", formatter.format("\\textbf{VLSI} {DSP}")); assertEquals("A ${\\Delta\\Sigma}$ modulator for {FPGA DSP}", formatter.format("A ${\\Delta}$${\\Sigma}$ modulator for {FPGA} {DSP}")); } @Test void preservePercentSign() { assertEquals("\\%", formatter.format("%")); } @Test void escapePercentSignOnlyOnce() { assertEquals("\\%", formatter.format("\\%")); } @Test void escapePercentSignOnlnyOnceWithNumber() { assertEquals("50\\%", formatter.format("50\\%")); } @Test void formatExample() { assertEquals("{VLSI DSP}", formatter.format(formatter.getExampleInput())); } }
1,259
26.391304
89
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeDateFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class NormalizeDateFormatterTest { private NormalizeDateFormatter formatter; @BeforeEach public void setUp() { formatter = new NormalizeDateFormatter(); } @Test public void formatDateYYYYMM0D() { assertEquals("2015-11-08", formatter.format("2015-11-08")); } @Test public void formatDateYYYYM0D() { assertEquals("2015-01-08", formatter.format("2015-1-08")); } @Test public void formatDateYYYYMD() { assertEquals("2015-01-08", formatter.format("2015-1-8")); } @Test public void formatDateYYYYMM() { assertEquals("2015-11", formatter.format("2015-11")); } @Test public void formatDateYYYYM() { assertEquals("2015-01", formatter.format("2015-1")); } @Test public void formatDateMMYY() { assertEquals("2015-11", formatter.format("11/15")); } @Test public void formatDateMYY() { assertEquals("2015-01", formatter.format("1/15")); } @Test public void formatDate0MYY() { assertEquals("2015-01", formatter.format("01/15")); } @Test public void formatDateMMYYYY() { assertEquals("2015-11", formatter.format("11/2015")); } @Test public void formatDateMYYYY() { assertEquals("2015-01", formatter.format("1/2015")); } @Test public void formatDate0MYYYY() { assertEquals("2015-01", formatter.format("01/2015")); } @Test public void formatDateMMMDDCommaYYYY() { assertEquals("2015-11-08", formatter.format("November 08, 2015")); } @Test public void formatDateMMMDCommaYYYY() { assertEquals("2015-11-08", formatter.format("November 8, 2015")); } @Test public void formatDateMMMCommaYYYY() { assertEquals("2015-11", formatter.format("November, 2015")); } @Test public void formatDate0DdotMMdotYYYY() { assertEquals("2015-11-08", formatter.format("08.11.2015")); } @Test public void formatDateDdotMMdotYYYY() { assertEquals("2015-11-08", formatter.format("8.11.2015")); } @Test public void formatDateDDdotMMdotYYYY() { assertEquals("2015-11-15", formatter.format("15.11.2015")); } @Test public void formatDate0Ddot0MdotYYYY() { assertEquals("2015-01-08", formatter.format("08.01.2015")); } @Test public void formatDateDdot0MdotYYYY() { assertEquals("2015-01-08", formatter.format("8.01.2015")); } @Test public void formatDateDDdot0MdotYYYY() { assertEquals("2015-01-15", formatter.format("15.01.2015")); } @Test public void formatDate0DdotMdotYYYY() { assertEquals("2015-01-08", formatter.format("08.1.2015")); } @Test public void formatDateDdotMdotYYYY() { assertEquals("2015-01-08", formatter.format("8.1.2015")); } @Test public void formatDateDDdotMdotYYYY() { assertEquals("2015-01-15", formatter.format("15.1.2015")); } @Test public void formatExample() { assertEquals("2003-11-29", formatter.format(formatter.getExampleInput())); } }
3,452
23.664286
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeEnDashesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class NormalizeEnDashesFormatterTest { private NormalizeEnDashesFormatter formatter; @BeforeEach public void setUp() { formatter = new NormalizeEnDashesFormatter(); } @Test public void formatExample() { assertEquals("Winery -- A Modeling Tool for TOSCA-based Cloud Applications", formatter.format(formatter.getExampleInput())); } @Test public void formatExampleOfChangelog() { assertEquals("Example -- illustrative", formatter.format("Example - illustrative")); } @Test public void dashesWithinWordsAreKept() { assertEquals("Example-illustrative", formatter.format("Example-illustrative")); } @Test public void dashesPreceededByASpaceAreKept() { assertEquals("Example -illustrative", formatter.format("Example -illustrative")); } @Test public void dashesFollowedByASpaceAreKept() { assertEquals("Example- illustrative", formatter.format("Example- illustrative")); } @Test public void dashAtTheBeginningIsKept() { assertEquals("- illustrative", formatter.format("- illustrative")); } @Test public void dashAtTheEndIsKept() { assertEquals("Example-", formatter.format("Example-")); } }
1,557
27.327273
132
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeMonthFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class NormalizeMonthFormatterTest { private NormalizeMonthFormatter formatter; @BeforeEach public void setUp() { formatter = new NormalizeMonthFormatter(); } @Test public void formatExample() { assertEquals("#dec#", formatter.format(formatter.getExampleInput())); } @Test public void plainAprilShouldBeApril() { assertEquals("#apr#", formatter.format("#apr#")); } }
734
23.5
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizeNamesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class NormalizeNamesFormatterTest { private NormalizeNamesFormatter formatter; @BeforeEach public void setUp() { formatter = new NormalizeNamesFormatter(); } @Test public void testNormalizeAuthorList() { assertEquals("Bilbo, Staci D.", formatter.format("Staci D Bilbo")); assertEquals("Bilbo, Staci D.", formatter.format("Staci D. Bilbo")); assertEquals("Bilbo, Staci D. and Smith, S. H. and Schwarz, Jaclyn M.", formatter.format("Staci D Bilbo and Smith SH and Jaclyn M Schwarz")); assertEquals("Ølver, M. A.", formatter.format("Ølver MA")); assertEquals("Ølver, M. A. and Øie, G. G. and Øie, G. G. and Alfredsen, J. Å. Å. and Alfredsen, Jo and Olsen, Y. Y. and Olsen, Y. Y.", formatter.format("Ølver MA; GG Øie; Øie GG; Alfredsen JÅÅ; Jo Alfredsen; Olsen Y.Y. and Olsen YY.")); assertEquals("Ølver, M. A. and Øie, G. G. and Øie, G. G. and Alfredsen, J. Å. Å. and Alfredsen, Jo and Olsen, Y. Y. and Olsen, Y. Y.", formatter.format("Ølver MA; GG Øie; Øie GG; Alfredsen JÅÅ; Jo Alfredsen; Olsen Y.Y.; Olsen YY.")); assertEquals("Alver, Morten and Alver, Morten O. and Alfredsen, J. A. and Olsen, Y. Y.", formatter.format("Alver, Morten and Alver, Morten O and Alfredsen, JA and Olsen, Y.Y.")); assertEquals("Alver, M. A. and Alfredsen, J. A. and Olsen, Y. Y.", formatter.format("Alver, MA; Alfredsen, JA; Olsen Y.Y.")); assertEquals("Kolb, Stefan and Lenhard, J{\\\"o}rg and Wirtz, Guido", formatter.format("Kolb, Stefan and J{\\\"o}rg Lenhard and Wirtz, Guido")); } @Test public void twoAuthorsSeperatedByColon() { assertEquals("Bilbo, Staci and Alver, Morten", formatter.format("Staci Bilbo; Morten Alver")); } @Test public void threeAuthorsSeperatedByColon() { assertEquals("Bilbo, Staci and Alver, Morten and Name, Test", formatter.format("Staci Bilbo; Morten Alver; Test Name")); } // Test for https://github.com/JabRef/jabref/issues/318 @Test public void threeAuthorsSeperatedByAnd() { assertEquals("Kolb, Stefan and Lenhard, J{\\\"o}rg and Wirtz, Guido", formatter.format("Stefan Kolb and J{\\\"o}rg Lenhard and Guido Wirtz")); } // Test for https://github.com/JabRef/jabref/issues/318 @Test public void threeAuthorsSeperatedByAndWithDash() { assertEquals("Jian, Heng-Yu and Xu, Z. and Chang, M.-C. F.", formatter.format("Heng-Yu Jian and Xu, Z. and Chang, M.-C.F.")); } // Test for https://github.com/JabRef/jabref/issues/318 @Test public void threeAuthorsSeperatedByAndWithLatex() { assertEquals("Gustafsson, Oscar and DeBrunner, Linda S. and DeBrunner, Victor and Johansson, H{\\aa}kan", formatter.format("Oscar Gustafsson and Linda S. DeBrunner and Victor DeBrunner and H{\\aa}kan Johansson")); } @Test public void lastThenInitial() { assertEquals("Smith, S.", formatter.format("Smith S")); } @Test public void lastThenInitials() { assertEquals("Smith, S. H.", formatter.format("Smith SH")); } @Test public void initialThenLast() { assertEquals("Smith, S.", formatter.format("S Smith")); } @Test public void initialDotThenLast() { assertEquals("Smith, S.", formatter.format("S. Smith")); } @Test public void initialsThenLast() { assertEquals("Smith, S. H.", formatter.format("SH Smith")); } @Test public void lastThenJuniorThenFirst() { assertEquals("Name, della, first", formatter.format("Name, della, first")); } @Test public void testConcatenationOfAuthorsWithCommas() { assertEquals("Ali Babar, M. and Dingsøyr, T. and Lago, P. and van der Vliet, H.", formatter.format("Ali Babar, M., Dingsøyr, T., Lago, P., van der Vliet, H.")); assertEquals("Ali Babar, M.", formatter.format("Ali Babar, M.")); } @Test public void testOddCountOfCommas() { assertEquals("Ali Babar, M., Dingsøyr T. Lago P.", formatter.format("Ali Babar, M., Dingsøyr, T., Lago P.")); } @Test public void formatExample() { assertEquals("Einstein, Albert and Turing, Alan", formatter.format(formatter.getExampleInput())); } @Test public void testNameAffixe() { assertEquals("Surname, jr, First and Surname2, First2", formatter.format("Surname, jr, First, Surname2, First2")); } @Test public void testAvoidSpecialCharacter() { assertEquals("Surname, {, First; Surname2, First2", formatter.format("Surname, {, First; Surname2, First2")); } @Test public void testAndInName() { assertEquals("Surname and , First, Surname2 First2", formatter.format("Surname, and , First, Surname2, First2")); } @Test public void testMultipleNameAffixes() { assertEquals("Mair, Jr, Daniel and Brühl, Sr, Daniel", formatter.format("Mair, Jr, Daniel, Brühl, Sr, Daniel")); } @Test public void testCommaSeperatedNames() { assertEquals("Bosoi, Cristina and Oliveira, Mariana and Sanchez, Rafael Ochoa and Tremblay, Mélanie and TenHave, Gabrie and Deutz, Nicoolas and Rose, Christopher F. and Bemeur, Chantal", formatter.format("Cristina Bosoi, Mariana Oliveira, Rafael Ochoa Sanchez, Mélanie Tremblay, Gabrie TenHave, Nicoolas Deutz, Christopher F. Rose, Chantal Bemeur")); } @Test public void testMultipleSpaces() { assertEquals("Bosoi, Cristina and Oliveira, Mariana and Sanchez, Rafael Ochoa and Tremblay, Mélanie and TenHave, Gabrie and Deutz, Nicoolas and Rose, Christopher F. and Bemeur, Chantal", formatter.format("Cristina Bosoi, Mariana Oliveira, Rafael Ochoa Sanchez , Mélanie Tremblay , Gabrie TenHave, Nicoolas Deutz, Christopher F. Rose, Chantal Bemeur")); } @Test public void testAvoidPreposition() { assertEquals("von Zimmer, Hans and van Oberbergern, Michael and zu Berger, Kevin", formatter.format("Hans von Zimmer, Michael van Oberbergern, Kevin zu Berger")); } @Test public void testPreposition() { assertEquals("von Zimmer, Hans and van Oberbergern, Michael and zu Berger, Kevin", formatter.format("Hans von Zimmer, Michael van Oberbergern, Kevin zu Berger")); } @Test public void testOneCommaUntouched() { assertEquals("Canon der Barbar, Alexander der Große", formatter.format("Canon der Barbar, Alexander der Große")); } @Test public void testAvoidNameAffixes() { assertEquals("der Barbar, Canon and der Große, Alexander and der Alexander, Peter", formatter.format("Canon der Barbar, Alexander der Große, Peter der Alexander")); } @Test public void testUpperCaseSensitiveList() { assertEquals("der Barbar, Canon and der Große, Alexander", formatter.format("Canon der Barbar AND Alexander der Große")); assertEquals("der Barbar, Canon and der Große, Alexander", formatter.format("Canon der Barbar aNd Alexander der Große")); assertEquals("der Barbar, Canon and der Große, Alexander", formatter.format("Canon der Barbar AnD Alexander der Große")); } @Test public void testSemiCorrectNamesWithSemicolon() { assertEquals("Last, First and Last2, First2 and Last3, First3", formatter.format("Last, First; Last2, First2; Last3, First3")); assertEquals("Last, Jr, First and Last2, First2", formatter.format("Last, Jr, First; Last2, First2")); assertEquals("Last, First and Last2, First2 and Last3, First3 and Last4, First4", formatter.format("Last, First; Last2, First2; Last3, First3; First4 Last4")); assertEquals("Last and Last2, First2 and Last3, First3 and Last4, First4", formatter.format("Last; Last2, First2; Last3, First3; Last4, First4")); } }
8,137
43.228261
194
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/NormalizePagesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class NormalizePagesFormatterTest { private NormalizePagesFormatter formatter; @BeforeEach public void setUp() { formatter = new NormalizePagesFormatter(); } private static Stream<Arguments> tests() { return Stream.of( // formatSinglePageResultsInNoChange Arguments.of("1", "1"), // formatPageNumbers Arguments.of("1--2", "1-2"), // endash Arguments.of("1--2", "1\u20132"), // emdash Arguments.of("1--2", "1\u20142"), // formatPageNumbersCommaSeparated Arguments.of("1,2,3", "1,2,3"), // formatPageNumbersPlusRange Arguments.of("43+", "43+"), // ignoreWhitespaceInPageNumbers Arguments.of("1--2", " 1 - 2 "), // removeWhitespaceSinglePage Arguments.of("1", " 1 "), // removeWhitespacePageRange Arguments.of("1--2", " 1 -- 2 "), // ignoreWhitespaceInPageNumbersWithDoubleDash Arguments.of("43--103", "43 -- 103"), // keepCorrectlyFormattedPageNumbers Arguments.of("1--2", "1--2"), // three dashes get two dashes Arguments.of("1--2", "1---2"), // formatPageNumbersRemoveUnexpectedLiterals Arguments.of("1--2", "{1}-{2}"), // formatPageNumbersRegexNotMatching Arguments.of("12", "12"), // special case, where -- is also put into Arguments.of("some--text", "some-text"), Arguments.of("pages 1--50", "pages 1-50"), Arguments.of("--43", "-43"), // keep arbitrary text Arguments.of("some-text-with-dashes", "some-text-with-dashes"), Arguments.of("{A}", "{A}"), Arguments.of("43+", "43+"), Arguments.of("Invalid", "Invalid"), // doNotRemoveLetters Arguments.of("R1--R50", "R1-R50"), // replaceLongDashWithDoubleDash Arguments.of("1--50", "1 \u2014 50"), // removePagePrefix Arguments.of("50", "p.50"), // removePagesPrefix Arguments.of("50", "pp.50"), // keep & Arguments.of("40&50", "40&50"), // formatACMPages // This appears in https://doi.org/10.1145/1658373.1658375 Arguments.of("2:1--2:33", "2:1-2:33"), // keepFormattedACMPages // This appears in https://doi.org/10.1145/1658373.1658375 Arguments.of("2:1--2:33", "2:1--2:33"), // formatExample Arguments.of("1--2", new NormalizePagesFormatter().getExampleInput()), // replaceDashWithMinus Arguments.of("R404--R405", "R404–R405")); } @ParameterizedTest @MethodSource("tests") public void test(String expected, String input) { assertEquals(expected, formatter.format(input)); } }
3,696
31.147826
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/OrdinalsToSuperscriptFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class OrdinalsToSuperscriptFormatterTest { private OrdinalsToSuperscriptFormatter formatter; @BeforeEach public void setUp() { formatter = new OrdinalsToSuperscriptFormatter(); } @Test public void replacesSuperscript() { expectCorrect("1st", "1\\textsuperscript{st}"); expectCorrect("2nd", "2\\textsuperscript{nd}"); expectCorrect("3rd", "3\\textsuperscript{rd}"); expectCorrect("4th", "4\\textsuperscript{th}"); expectCorrect("21th", "21\\textsuperscript{th}"); } @Test public void replaceSuperscriptsIgnoresCase() { expectCorrect("1st", "1\\textsuperscript{st}"); expectCorrect("1ST", "1\\textsuperscript{ST}"); expectCorrect("1sT", "1\\textsuperscript{sT}"); } @Test public void replaceSuperscriptsInMultilineStrings() { expectCorrect( "replace on 1st line\nand on 2nd line.", "replace on 1\\textsuperscript{st} line\nand on 2\\textsuperscript{nd} line." ); } @Test public void replaceAllSuperscripts() { expectCorrect( "1st 2nd 3rd 4th", "1\\textsuperscript{st} 2\\textsuperscript{nd} 3\\textsuperscript{rd} 4\\textsuperscript{th}" ); } @Test public void ignoreSuperscriptsInsideWords() { expectCorrect("1st 1stword words1st inside1stwords", "1\\textsuperscript{st} 1stword words1st inside1stwords"); } @Test public void formatExample() { assertEquals("11\\textsuperscript{th}", formatter.format(formatter.getExampleInput())); } private void expectCorrect(String input, String expected) { assertEquals(expected, formatter.format(input)); } }
2,043
29.969697
119
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/RegexFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class RegexFormatterTest { private RegexFormatter formatter; @Test void spacesReplacedCorrectly() { formatter = new RegexFormatter("(\" \",\"-\")"); assertEquals("replace-all-spaces", formatter.format("replace all spaces")); } @Test void protectedSpacesNotReplacedInSingleProtectedBlock() { formatter = new RegexFormatter("(\" \",\"-\")"); assertEquals("replace-spaces-{not these ones}", formatter.format("replace spaces {not these ones}")); } @Test void protectedSpacesNotReplacedInTwoProtectedBlocks() { formatter = new RegexFormatter("(\" \",\"-\")"); assertEquals("replace-spaces-{not these ones}-{or these ones}-but-these-ones", formatter.format("replace spaces {not these ones} {or these ones} but these ones")); } @Test void escapedBracesAreNotReplaced() { formatter = new RegexFormatter("(\" \",\"-\")"); assertEquals("replace-spaces-\\{-these-ones\\}-and-these-ones", formatter.format("replace spaces \\{ these ones\\} and these ones")); } @Test void escapedBracesAreNotReplacedInTwoCases() { formatter = new RegexFormatter("(\" \",\"-\")"); assertEquals("replace-spaces-\\{-these-ones\\},-these-ones,-and-\\{-these-ones\\}", formatter.format("replace spaces \\{ these ones\\}, these ones, and \\{ these ones\\}")); } @Test void escapedBracesAreNotReplacedAndProtectionStillWorks() { formatter = new RegexFormatter("(\" \",\"-\")"); assertEquals("replace-spaces-{not these ones},-these-ones,-and-\\{-these-ones\\}", formatter.format("replace spaces {not these ones}, these ones, and \\{ these ones\\}")); } @Test void formatExample() { formatter = new RegexFormatter("(\" \",\"-\")"); assertEquals("Please-replace-the-spaces", formatter.format(formatter.getExampleInput())); } @Test void formatCanRemoveMatchesWithEmptyReplacement() { formatter = new RegexFormatter("(\"[A-Z]\",\"\")"); assertEquals("abc", formatter.format("AaBbCc")); } @Test void constructorWithInvalidConstructorArgumentReturnUnchangedString() { formatter = new RegexFormatter("(\"\",\"\""); assertEquals("AaBbCc", formatter.format("AaBbCc")); } @Test void constructorWithEmptyStringArgumentReturnUnchangedString() { formatter = new RegexFormatter(""); assertEquals("AaBbCc", formatter.format("AaBbCc")); } @Test void constructorAllowsSpacesBetweenQuotes() { formatter = new RegexFormatter("(\"[A-Z]\", \"\")"); assertEquals("abc", formatter.format("AaBbCc")); } @Test void formatWithSyntaxErrorReturnUnchangedString() { formatter = new RegexFormatter("(\"(\", \"\")"); assertEquals("AaBbCc", formatter.format("AaBbCc")); } }
3,006
35.228916
181
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveBracesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class RemoveBracesFormatterTest { private RemoveBracesFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveBracesFormatter(); } @Test public void formatRemovesSingleEnclosingBraces() { assertEquals("test", formatter.format("{test}")); } @Test public void formatKeepsUnmatchedBracesAtBeginning() { assertEquals("{test", formatter.format("{test")); } @Test public void formatKeepsUnmatchedBracesAtEnd() { assertEquals("test}", formatter.format("test}")); } @Test public void formatKeepsShortString() { assertEquals("t", formatter.format("t")); } @Test public void formatRemovesBracesOnly() { assertEquals("", formatter.format("{}")); } @Test public void formatKeepsEmptyString() { assertEquals("", formatter.format("")); } @Test public void formatRemovesDoubleEnclosingBraces() { assertEquals("test", formatter.format("{{test}}")); } @Test public void formatRemovesTripleEnclosingBraces() { assertEquals("test", formatter.format("{{{test}}}")); } @Test public void formatKeepsNonMatchingBraces() { assertEquals("{A} and {B}", formatter.format("{A} and {B}")); } @Test public void formatRemovesOnlyMatchingBraces() { assertEquals("{A} and {B}", formatter.format("{{A} and {B}}")); } @Test public void formatDoesNotRemoveBracesInBrokenString() { // We opt here for a conservative approach although one could argue that "A} and {B}" is also a valid return assertEquals("{A} and {B}}", formatter.format("{A} and {B}}")); } @Test public void formatExample() { assertEquals("In CDMA", formatter.format(formatter.getExampleInput())); } }
2,139
25.419753
116
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveDigitsFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoveDigitsFormatterTest { private RemoveDigitsFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveDigitsFormatter(); } @Test public void doNothingIfSingleSpace() { assertEquals("one digit", formatter.format("one 1 digit")); } @Test public void doNothingIfNoSpace() { assertEquals("two digits", formatter.format("two 01 digits")); } @Test public void removeAllButOneSpacesIfTwo() { assertEquals("no digits", formatter.format("no digits")); } }
761
22.8125
70
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveHyphenatedNewlinesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoveHyphenatedNewlinesFormatterTest { private RemoveHyphenatedNewlinesFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveHyphenatedNewlinesFormatter(); } @Test public void removeHyphensBeforeNewlines() { assertEquals("water", formatter.format("wa-\nter")); assertEquals("water", formatter.format("wa-\r\nter")); assertEquals("water", formatter.format("wa-\rter")); } @Test public void withoutHyphensUnmodified() { assertEquals("water", formatter.format("water")); } @Test public void removeHyphensBeforePlatformSpecificNewlines() { String newLine = String.format("%n"); assertEquals("water", formatter.format("wa-" + newLine + "ter")); } }
983
27.114286
73
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveNewlinesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoveNewlinesFormatterTest { private RemoveNewlinesFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveNewlinesFormatter(); } @Test public void removeCarriageReturnLineFeed() { assertEquals("rn linebreak", formatter.format("rn\r\nlinebreak")); } @Test public void removeCarriageReturn() { assertEquals("r linebreak", formatter.format("r\rlinebreak")); } @Test public void removeLineFeed() { assertEquals("n linebreak", formatter.format("n\nlinebreak")); } @Test public void withoutNewLineUnmodified() { assertEquals("no linebreak", formatter.format("no linebreak")); } @Test public void removePlatformSpecificNewLine() { String newLine = String.format("%n"); assertEquals("linebreak on current platform", formatter.format("linebreak on" + newLine + "current platform")); } }
1,143
25
119
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/RemoveRedundantSpacesFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoveRedundantSpacesFormatterTest { private RemoveRedundantSpacesFormatter formatter; @BeforeEach public void setUp() { formatter = new RemoveRedundantSpacesFormatter(); } @Test public void doNothingIfSingleSpace() { assertEquals("single space", formatter.format("single space")); } @Test public void doNothingIfNoSpace() { assertEquals("nospace", formatter.format("nospace")); } @Test public void removeAllButOneSpacesIfTwo() { assertEquals("two spaces", formatter.format("two spaces")); } @Test public void removeAllButOneSpacesIfThree() { assertEquals("three spaces", formatter.format("three spaces")); } }
926
24.054054
73
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/ReplaceTabsBySpaceFormaterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class ReplaceTabsBySpaceFormaterTest { private ReplaceTabsBySpaceFormater formatter; @BeforeEach public void setUp() { formatter = new ReplaceTabsBySpaceFormater(); } @Test public void removeSingleTab() { assertEquals("single tab", formatter.format("single\ttab")); } @Test public void removeMultipleTabs() { assertEquals("multiple tabs", formatter.format("multiple\t\ttabs")); } @Test public void doNothingIfNoTab() { assertEquals("notab", formatter.format("notab")); } }
759
22.030303
76
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/ReplaceWithEscapedDoubleQuotesTest.java
package org.jabref.logic.formatter.bibtexfields; import org.jabref.logic.layout.format.ReplaceWithEscapedDoubleQuotes; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class ReplaceWithEscapedDoubleQuotesTest { private ReplaceWithEscapedDoubleQuotes formatter; @BeforeEach public void setUp() { formatter = new ReplaceWithEscapedDoubleQuotes(); } @Test public void replacingSingleDoubleQuote() { assertEquals("single \"\"double quote", formatter.format("single \"double quote")); } @Test public void replacingMultipleDoubleQuote() { assertEquals("multiple \"\"double\"\" quote", formatter.format("multiple \"double\" quote")); } @Test public void replacingSingleDoubleQuoteHavingCommas() { assertEquals("this \"\"is\"\", a test", formatter.format("this \"is\", a test")); } @Test public void doNothing() { assertEquals("this is a test", formatter.format("this is a test")); } }
1,091
27
101
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/ShortenDOIFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @FetcherTest class ShortenDOIFormatterTest { private ShortenDOIFormatter formatter; @BeforeEach public void setUp() { formatter = new ShortenDOIFormatter(); } @Test public void formatDoi() { assertEquals("10/adc", formatter.format("10.1006/jmbi.1998.2354")); } @Test public void invalidDoiIsKept() { assertEquals("invalid-doi", formatter.format("invalid-doi")); } }
674
21.5
75
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/TrimWhitespaceFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class TrimWhitespaceFormatterTest { private TrimWhitespaceFormatter formatter; @BeforeEach public void setUp() { formatter = new TrimWhitespaceFormatter(); } @Test public void removeHorizontalTabulations() { assertEquals("whitespace", formatter.format("\twhitespace")); assertEquals("whitespace", formatter.format("whitespace\t")); assertEquals("whitespace", formatter.format("\twhitespace\t\t")); } @Test public void removeLineFeeds() { assertEquals("whitespace", formatter.format("\nwhitespace")); assertEquals("whitespace", formatter.format("whitespace\n")); assertEquals("whitespace", formatter.format("\nwhitespace\n\n")); } @Test public void removeFormFeeds() { assertEquals("whitespace", formatter.format("\fwhitespace")); assertEquals("whitespace", formatter.format("whitespace\f")); assertEquals("whitespace", formatter.format("\fwhitespace\f\f")); } @Test public void removeCarriageReturnFeeds() { assertEquals("whitespace", formatter.format("\rwhitespace")); assertEquals("whitespace", formatter.format("whitespace\r")); assertEquals("whitespace", formatter.format("\rwhitespace\r\r")); } @Test public void removeSeparatorSpaces() { assertEquals("whitespace", formatter.format(" whitespace")); assertEquals("whitespace", formatter.format("whitespace ")); assertEquals("whitespace", formatter.format(" whitespace ")); } @Test public void removeMixedWhitespaceChars() { assertEquals("whitespace", formatter.format(" \r\t\fwhitespace")); assertEquals("whitespace", formatter.format("whitespace \n \r")); assertEquals("whitespace", formatter.format(" \f\t whitespace \r \n")); } }
2,037
32.966667
82
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeConverterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class UnicodeConverterTest { private UnicodeToLatexFormatter formatter; @BeforeEach public void setUp() { formatter = new UnicodeToLatexFormatter(); } @Test public void testBasic() { assertEquals("aaa", formatter.format("aaa")); } @Test public void testUnicodeCombiningAccents() { assertEquals("{\\\"{a}}", formatter.format("a\u0308")); assertEquals("{\\\"{a}}b", formatter.format("a\u0308b")); } @Test public void testUnicode() { assertEquals("{\\\"{a}}", formatter.format("ä")); assertEquals("{{$\\Epsilon$}}", formatter.format("\u0395")); } @Test public void testUnicodeSingle() { assertEquals("a", formatter.format("a")); } }
1,056
24.166667
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/UnicodeToLatexFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; 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; class UnicodeToLatexFormatterTest { private UnicodeToLatexFormatter formatter; @BeforeEach void setUp() { formatter = new UnicodeToLatexFormatter(); } private static Stream<Arguments> testCases() { return Stream.of( Arguments.of("", ""), // empty string input Arguments.of("abc", "abc"), // non unicode input Arguments.of("{{\\aa}}{\\\"{a}}{\\\"{o}}", "\u00E5\u00E4\u00F6"), // multiple unicodes input Arguments.of("", "\u0081"), // high code point unicode, boundary case: cp = 129 Arguments.of("€", "\u0080"), // high code point unicode, boundary case: cp = 128 < 129 Arguments.of("M{\\\"{o}}nch", new UnicodeToLatexFormatter().getExampleInput())); } @ParameterizedTest() @MethodSource("testCases") void testFormat(String expectedResult, String input) { assertEquals(expectedResult, formatter.format(input)); } }
1,378
36.27027
117
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/bibtexfields/UnitsToLatexFormatterTest.java
package org.jabref.logic.formatter.bibtexfields; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class UnitsToLatexFormatterTest { private UnitsToLatexFormatter formatter; @BeforeEach public void setUp() { formatter = new UnitsToLatexFormatter(); } @Test public void test() { assertEquals("1~{A}", formatter.format("1 A")); assertEquals("1\\mbox{-}{mA}", formatter.format("1-mA")); } @Test public void formatExample() { assertEquals("1~{Hz}", formatter.format(formatter.getExampleInput())); } }
774
24
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/casechanger/CapitalizeFormatterTest.java
package org.jabref.logic.formatter.casechanger; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class CapitalizeFormatterTest { private CapitalizeFormatter formatter; @BeforeEach public void setUp() { formatter = new CapitalizeFormatter(); } @Test public void formatExample() { assertEquals("I Have {a} Dream", formatter.format(formatter.getExampleInput())); } @ParameterizedTest(name = "input={0}, formattedStr={1}") @CsvSource(value = { "{}, {}", // {} "{upper, {upper", // unmatched braces "upper, Upper", // single word lower case "Upper, Upper", // single word correct "UPPER, Upper", // single word upper case "upper each first, Upper Each First", // multiple words lower case "Upper Each First, Upper Each First", // multiple words correct "UPPER EACH FIRST, Upper Each First", // multiple words upper case "upper each First, Upper Each First", // multiple words in lower and upper case "{u}pp{e}r, {u}pp{e}r", // single word lower case with {} "{U}pp{e}r, {U}pp{e}r", // single word correct with {} "{U}PP{E}R, {U}pp{E}r", // single word upper case with {} "upper each {NOT} first, Upper Each {NOT} First", // multiple words lower case with {} "Upper {E}ach {NOT} First, Upper {E}ach {NOT} First", // multiple words correct with {} "UPPER {E}ACH {NOT} FIRST, Upper {E}ach {NOT} First", // multiple words upper case with {} "upper each first {NOT} {this}, Upper Each First {NOT} {this}", // multiple words in lower and upper case with {} "upper each first {N}OT {t}his, Upper Each First {N}ot {t}his", // multiple words in lower and upper case with {} part 2 "upper-each-first, Upper-Each-First", // multiple words lower case with - "Upper-Each-First, Upper-Each-First", // multiple words correct with - "Upper-each-First, Upper-Each-First", // multiple words in lower and upper case with - "UPPER-EACH-FIRST, Upper-Each-First", // multiple words upper case with - "{u}pper-each-{f}irst, {u}pper-Each-{f}irst", // multiple words lower case with {} and - "-upper, -Upper", // single word with - "-{u}pper, -{u}pper", // single word with {} and - }) public void testInputs(String input, String expectedResult) { String formattedStr = formatter.format(input); assertEquals(expectedResult, formattedStr); } }
2,890
48
132
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/casechanger/LowerCaseFormatterTest.java
package org.jabref.logic.formatter.casechanger; import java.util.stream.Stream; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class LowerCaseFormatterTest { private LowerCaseFormatter formatter; @BeforeEach public void setUp() { formatter = new LowerCaseFormatter(); } @ParameterizedTest @MethodSource("provideStringsForFormat") public void test(String expected, String input) { assertEquals(expected, formatter.format(input)); } private static Stream<Arguments> provideStringsForFormat() { return Stream.of( Arguments.of("lower", "lower"), Arguments.of("lower", "LOWER"), Arguments.of("lower {UPPER}", "LOWER {UPPER}"), Arguments.of("lower {U}pper", "LOWER {U}PPER") ); } @Test public void formatExample() { assertEquals("kde {Amarok}", formatter.format(formatter.getExampleInput())); } }
1,315
28.244444
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/casechanger/ProtectTermsFormatterTest.java
package org.jabref.logic.formatter.casechanger; import java.util.Collections; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.protectedterms.ProtectedTermsPreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class ProtectTermsFormatterTest { private ProtectTermsFormatter formatter; @BeforeEach public void setUp() { formatter = new ProtectTermsFormatter( new ProtectedTermsLoader(new ProtectedTermsPreferences(ProtectedTermsLoader.getInternalLists(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList()))); } @Test public void testSingleWord() { assertEquals("{VLSI}", formatter.format("VLSI")); } @Test public void testDoNotProtectAlreadyProtected() { assertEquals("{VLSI}", formatter.format("{VLSI}")); } @Test public void testCaseSensitivity() { assertEquals("VLsI", formatter.format("VLsI")); } @Test public void formatExample() { assertEquals("In {CDMA}", formatter.format(formatter.getExampleInput())); } @Test public void testCorrectOrderingOfTerms() { assertEquals("{3GPP} {3G}", formatter.format("3GPP 3G")); } @Test public void test() { assertEquals("{VLSI} {VLSI}", formatter.format("VLSI {VLSI}")); assertEquals("{BPEL}", formatter.format("{BPEL}")); assertEquals("{Testing BPEL Engine Performance: A Survey}", formatter.format("{Testing BPEL Engine Performance: A Survey}")); } }
1,790
28.85
111
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/casechanger/SentenceCaseFormatterTest.java
package org.jabref.logic.formatter.casechanger; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class SentenceCaseFormatterTest { private SentenceCaseFormatter formatter; @BeforeEach public void setUp() { formatter = new SentenceCaseFormatter(); } private static Stream<Arguments> testData() { return Stream.of( Arguments.of("Upper first", "upper First"), Arguments.of("Upper first", "uPPER FIRST"), Arguments.of("Upper {NOT} first", "upper {NOT} FIRST"), Arguments.of("Upper {N}ot first", "upper {N}OT FIRST"), Arguments.of("Whose music? A sociology of musical language", "Whose music? a sociology of musical language"), Arguments.of("Bibliographic software. A comparison.", "bibliographic software. a comparison."), Arguments.of("England’s monitor; The history of the separation", "England’s Monitor; the History of the Separation"), Arguments.of("Dr. schultz: a dentist turned bounty hunter.", "Dr. schultz: a dentist turned bounty hunter."), Arguments.of("Wetting-and-drying", "wetting-and-drying"), Arguments.of("Example case. {EXCLUDED SENTENCE.}", "Example case. {EXCLUDED SENTENCE.}"), Arguments.of("I have {Aa} dream", new SentenceCaseFormatter().getExampleInput())); } @ParameterizedTest @MethodSource("testData") public void test(String expected, String input) { assertEquals(expected, formatter.format(input)); } }
2,074
39.686275
98
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/casechanger/TitleCaseFormatterTest.java
package org.jabref.logic.formatter.casechanger; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class TitleCaseFormatterTest { private TitleCaseFormatter formatter; @BeforeEach public void setUp() { formatter = new TitleCaseFormatter(); } private static Stream<Arguments> testData() { return Stream.of( Arguments.of("Upper Each First", "upper each first"), Arguments.of("Upper Each First", "upper eACH first"), Arguments.of("An Upper Each First And", "an upper each first and"), Arguments.of("An Upper Each First And", "an upper each first AND"), Arguments.of("An Upper Each of the and First And", "an upper each of the and first and"), Arguments.of("An Upper Each of the and First And", "an upper each of the AND first and"), Arguments.of("An Upper Each of: The and First And", "an upper each of: the and first and"), Arguments.of("An Upper First with and without {CURLY} {brackets}", "AN UPPER FIRST WITH AND WITHOUT {CURLY} {brackets}"), Arguments.of("An Upper First with {A}nd without {C}urly {b}rackets", "AN UPPER FIRST WITH {A}ND WITHOUT {C}URLY {b}rackets"), Arguments.of("{b}rackets {b}rac{K}ets Brack{E}ts", "{b}RaCKeTS {b}RaC{K}eTS bRaCK{E}ts"), Arguments.of("Two Experiences Designing for Effective Security", "Two experiences designing for effective security"), Arguments.of("Bibliographic Software. A Comparison.", "bibliographic software. a comparison."), Arguments.of("Bibliographic Software. {A COMPARISON.}", "bibliographic software. {A COMPARISON.}"), Arguments.of("--Test~Ing Dash--Like Characters", "--test~ing dash--like characters"), Arguments.of("-⸗Test⸗Ing Dash〰Like Cha᐀᐀Racters", "-⸗test⸗ing dash〰like cha᐀᐀racters"), Arguments.of("︲︲Test־Ing Dash⁓⁓Like Characters", "︲︲test־ing dash⁓⁓like characters"), Arguments.of("⁻⁻Test−Ing Dash⸻Like Characters", "⁻⁻test−ing dash⸻like characters"), Arguments.of("--Test〰Ing M-U~L゠T︱I⁓P︲L--~~︲E Dash⸻-Like Characters", "--test〰ing M-u~l゠t︱i⁓p︲l--~~︲e dASH⸻-likE charACTErs"), Arguments.of("--Wetting-and-Drying M-U~L゠T︱I⁓P︲L--~~︲E Dash⸻-Like Characters", "--wetting-and-drying M-u~l゠t︱i⁓p︲l--~~︲e dASH⸻-likE charACTErs"), Arguments.of("Kinetic Studies on Enzyme-Catalyzed Reactions: Oxidation of Glucose, Decomposition of Hydrogen Peroxide and Their Combination", "kinetic studies on enzyme-catalyzed reactions: oxidation of glucose, decomposition of hydrogen peroxide and their combination"), Arguments.of("{BPMN} Conformance in Open Source Engines", new TitleCaseFormatter().getExampleInput())); } @ParameterizedTest @MethodSource("testData") public void test(String expected, String input) { assertEquals(expected, formatter.format(input)); } }
3,784
51.569444
157
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/casechanger/UnprotectTermsFormatterTest.java
package org.jabref.logic.formatter.casechanger; import java.io.IOException; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class UnprotectTermsFormatterTest { private UnprotectTermsFormatter formatter; @BeforeEach public void setUp() { formatter = new UnprotectTermsFormatter(); } private static Stream<Arguments> terms() throws IOException { return Stream.of( Arguments.of("", ""), Arguments.of("VLSI", "{VLSI}"), Arguments.of("VLsI", "VLsI"), Arguments.of("VLSI", "VLSI"), Arguments.of("VLSI VLSI", "{VLSI} {VLSI}"), Arguments.of("BPEL", "{BPEL}"), Arguments.of("3GPP 3G", "{3GPP} {3G}"), Arguments.of("{A} and {B}}", "{A} and {B}}"), Arguments.of("Testing BPEL Engine Performance: A Survey", "{Testing BPEL Engine Performance: A Survey}"), Arguments.of("Testing BPEL Engine Performance: A Survey", "Testing {BPEL} Engine Performance: A Survey"), Arguments.of("Testing BPEL Engine Performance: A Survey", "{Testing {BPEL} Engine Performance: A Survey}"), Arguments.of("In CDMA", new UnprotectTermsFormatter().getExampleInput())); } @ParameterizedTest @MethodSource("terms") public void test(String expected, String toFormat) { assertEquals(expected, formatter.format(toFormat)); } }
1,805
37.425532
123
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/casechanger/UpperCaseFormatterTest.java
package org.jabref.logic.formatter.casechanger; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class UpperCaseFormatterTest { private UpperCaseFormatter formatter = new UpperCaseFormatter(); @ParameterizedTest @MethodSource("upperCaseTests") public void upperCaseTest(String expectedFormat, String inputFormat) { assertEquals(expectedFormat, formatter.format(inputFormat)); } private static Stream<Arguments> upperCaseTests() { return Stream.of( Arguments.of("LOWER", "LOWER"), Arguments.of("UPPER", "upper"), Arguments.of("UPPER", "UPPER"), Arguments.of("UPPER {lower}", "upper {lower}"), Arguments.of("UPPER {l}OWER", "upper {l}ower"), Arguments.of("1", "1"), Arguments.of("!", "!") ); } @Test public void formatExample() { assertEquals("KDE {Amarok}", formatter.format(formatter.getExampleInput())); } }
1,349
31.142857
95
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/minifier/MinifyNameListFormatterTest.java
package org.jabref.logic.formatter.minifier; 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; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class MinifyNameListFormatterTest { private MinifyNameListFormatter formatter; @BeforeEach public void setUp() { formatter = new MinifyNameListFormatter(); } @ParameterizedTest @MethodSource("provideAuthorNames") void minifyAuthorNames(String expectedAuthorNames, String originalAuthorNames) { assertEquals(expectedAuthorNames, formatter.format(originalAuthorNames)); } private static Stream<Arguments> provideAuthorNames() { return Stream.of( Arguments.of("Simon Harrer", "Simon Harrer"), Arguments.of("Simon Harrer and others", "Simon Harrer and others"), Arguments.of("Simon Harrer and Jörg Lenhard", "Simon Harrer and Jörg Lenhard"), Arguments.of("Simon Harrer and others", "Simon Harrer and Jörg Lenhard and Guido Wirtz"), Arguments.of("Simon Harrer and others", "Simon Harrer and Jörg Lenhard and Guido Wirtz and others"), Arguments.of("Stefan Kolb and others", new MinifyNameListFormatter().getExampleInput()) ); } }
1,556
36.97561
116
java
null
jabref-main/src/test/java/org/jabref/logic/formatter/minifier/TruncateFormatterTest.java
package org.jabref.logic.formatter.minifier; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests in addition to the general tests from {@link org.jabref.logic.formatter.FormatterTest} */ public class TruncateFormatterTest { private final String TITLE = "A Title"; @Test void formatWorksWith0Index() { TruncateFormatter formatter = new TruncateFormatter(0); assertEquals("", formatter.format(TITLE)); } @Test void formatRemovesTrailingWhitespace() { TruncateFormatter formatter = new TruncateFormatter(2); assertEquals("A", formatter.format(TITLE)); } @Test void formatKeepsInternalWhitespace() { TruncateFormatter formatter = new TruncateFormatter(3); assertEquals("A T", formatter.format(TITLE)); } @Test void formatWorksWith9999Length() { TruncateFormatter formatter = new TruncateFormatter(9999); assertEquals(TITLE, formatter.format(TITLE)); } @Test void formatIgnoresNegativeIndex() { TruncateFormatter formatter = new TruncateFormatter(-1); assertEquals(TITLE, formatter.format(TITLE)); } @Test void formatWorksWithEmptyString() { TruncateFormatter formatter = new TruncateFormatter(9999); assertEquals("", formatter.format("")); } @Test void formatThrowsExceptionNullString() { TruncateFormatter formatter = new TruncateFormatter(9999); assertThrows(NullPointerException.class, () -> formatter.format(null)); } }
1,649
28.464286
95
java
null
jabref-main/src/test/java/org/jabref/logic/git/GitHandlerTest.java
package org.jabref.logic.git; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.revwalk.RevCommit; 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; class GitHandlerTest { @TempDir Path repositoryPath; private GitHandler gitHandler; @BeforeEach public void setUpGitHandler() { gitHandler = new GitHandler(repositoryPath); } @Test void checkoutNewBranch() throws IOException, GitAPIException { gitHandler.checkoutBranch("testBranch"); try (Git git = Git.open(repositoryPath.toFile())) { assertEquals("testBranch", git.getRepository().getBranch()); } } @Test void createCommitOnCurrentBranch() throws IOException, GitAPIException { try (Git git = Git.open(repositoryPath.toFile())) { // Create commit Files.createFile(Path.of(repositoryPath.toString(), "Test.txt")); gitHandler.createCommitOnCurrentBranch("TestCommit", false); AnyObjectId head = git.getRepository().resolve(Constants.HEAD); Iterator<RevCommit> log = git.log() .add(head) .call().iterator(); assertEquals("TestCommit", log.next().getFullMessage()); assertEquals("Initial commit", log.next().getFullMessage()); } } @Test void getCurrentlyCheckedOutBranch() throws IOException { assertEquals("main", gitHandler.getCurrentlyCheckedOutBranch()); } }
1,892
31.084746
77
java
null
jabref-main/src/test/java/org/jabref/logic/git/SlrGitHandlerTest.java
package org.jabref.logic.git; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; class SlrGitHandlerTest { private static final Logger LOGGER = LoggerFactory.getLogger(SlrGitHandlerTest.class); @TempDir Path repositoryPath; private SlrGitHandler gitHandler; @BeforeEach public void setUpGitHandler() { gitHandler = new SlrGitHandler(repositoryPath); } @Test void calculateDiffOnBranch() throws IOException, GitAPIException { String expectedPatch = "diff --git a/TestFolder/Test1.txt b/TestFolder/Test1.txt\n" + "index 74809e3..2ae1945 100644\n" + "--- a/TestFolder/Test1.txt\n" + "+++ b/TestFolder/Test1.txt\n" + "@@ -1 +1,2 @@\n" + "+This is a new line of text 2\n" + " This is a new line of text\n"; gitHandler.checkoutBranch("branch1"); Files.createDirectory(Path.of(repositoryPath.toString(), "TestFolder")); Files.createFile(Path.of(repositoryPath.toString(), "TestFolder", "Test1.txt")); Files.writeString(Path.of(repositoryPath.toString(), "TestFolder", "Test1.txt"), "This is a new line of text\n"); gitHandler.createCommitOnCurrentBranch("Commit 1 on branch1", false); Files.createFile(Path.of(repositoryPath.toString(), "Test2.txt")); Files.writeString(Path.of(repositoryPath.toString(), "TestFolder", "Test1.txt"), "This is a new line of text 2\n" + Files.readString(Path.of(repositoryPath.toString(), "TestFolder", "Test1.txt"))); gitHandler.createCommitOnCurrentBranch("Commit 2 on branch1", false); LOGGER.debug(gitHandler.calculatePatchOfNewSearchResults("branch1")); assertEquals(expectedPatch, gitHandler.calculatePatchOfNewSearchResults("branch1")); } @Test void calculatePatch() throws IOException, GitAPIException { Map<Path, String> expected = new HashMap<>(); expected.put(Path.of(repositoryPath.toString(), "TestFolder", "Test1.txt"), "This is a new line of text 2"); Map<Path, String> result = gitHandler.parsePatchForAddedEntries( "diff --git a/TestFolder/Test1.txt b/TestFolder/Test1.txt\n" + "index 74809e3..2ae1945 100644\n" + "--- a/TestFolder/Test1.txt\n" + "+++ b/TestFolder/Test1.txt\n" + "@@ -1 +1,2 @@\n" + "+This is a new line of text 2\n" + " This is a new line of text"); assertEquals(expected, result); } @Test void applyPatch() throws IOException, GitAPIException { gitHandler.checkoutBranch("branch1"); Files.createFile(Path.of(repositoryPath.toString(), "Test1.txt")); gitHandler.createCommitOnCurrentBranch("Commit on branch1", false); gitHandler.checkoutBranch("branch2"); Files.createFile(Path.of(repositoryPath.toString(), "Test2.txt")); Files.writeString(Path.of(repositoryPath.toString(), "Test1.txt"), "This is a new line of text"); gitHandler.createCommitOnCurrentBranch("Commit on branch2.", false); gitHandler.checkoutBranch("branch1"); gitHandler.appendLatestSearchResultsOntoCurrentBranch("TestMessage", "branch2"); assertEquals("This is a new line of text", Files.readString(Path.of(repositoryPath.toString(), "Test1.txt"))); } }
3,859
42.863636
205
java
null
jabref-main/src/test/java/org/jabref/logic/help/HelpFileTest.java
package org.jabref.logic.help; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.stream.Stream; import org.jabref.logic.net.URLDownload; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; class HelpFileTest { private final String jabrefHelp = "https://docs.jabref.org/"; static Stream<HelpFile> getAllHelpFiles() { return Arrays.stream(HelpFile.values()); } @ParameterizedTest @MethodSource("getAllHelpFiles") void referToValidPage(HelpFile help) throws IOException { URL url = new URL(jabrefHelp + help.getPageName()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setRequestProperty("User-Agent", URLDownload.USER_AGENT); assertEquals(200, http.getResponseCode(), "Wrong URL: " + url.toString()); } }
997
29.242424
82
java
null
jabref-main/src/test/java/org/jabref/logic/importer/AuthorListParserTest.java
package org.jabref.logic.importer; import java.util.stream.Stream; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; 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 AuthorListParserTest { AuthorListParser parser = new AuthorListParser(); private static Stream<Arguments> parseSingleAuthorCorrectly() { return Stream.of( Arguments.of("王, 军", new Author("军", "军.", null, "王", null)), Arguments.of("Doe, John", new Author("John", "J.", null, "Doe", null)), Arguments.of("von Berlichingen zu Hornberg, Johann Gottfried", new Author("Johann Gottfried", "J. G.", "von", "Berlichingen zu Hornberg", null)), Arguments.of("{Robert and Sons, Inc.}", new Author(null, null, null, "Robert and Sons, Inc.", null)), Arguments.of("al-Ṣāliḥ, Abdallāh", new Author("Abdallāh", "A.", null, "al-Ṣāliḥ", null)), Arguments.of("de la Vallée Poussin, Jean Charles Gabriel", new Author("Jean Charles Gabriel", "J. C. G.", "de la", "Vallée Poussin", null)), Arguments.of("de la Vallée Poussin, J. C. G.", new Author("J. C. G.", "J. C. G.", "de la", "Vallée Poussin", null)), Arguments.of("{K}ent-{B}oswell, E. S.", new Author("E. S.", "E. S.", null, "{K}ent-{B}oswell", null)), Arguments.of("Uhlenhaut, N Henriette", new Author("N Henriette", "N. H.", null, "Uhlenhaut", null)), Arguments.of("Nu{\\~{n}}ez, Jose", new Author("Jose", "J.", null, "Nu{\\~{n}}ez", null)), // parseAuthorWithFirstNameAbbreviationContainingUmlaut Arguments.of("{\\OE}rjan Umlauts", new Author("{\\OE}rjan", "{\\OE}.", null, "Umlauts", null)) ); } @ParameterizedTest @MethodSource void parseSingleAuthorCorrectly(String authorsString, Author authorsParsed) { assertEquals(AuthorList.of(authorsParsed), parser.parse(authorsString)); } private static Stream<Arguments> parseMultipleCorrectly() { return Stream.of( Arguments.of( AuthorList.of( new Author("Alexander", "A.", null, "Artemenko", null), Author.OTHERS ), "Alexander Artemenko and others") ); } @ParameterizedTest @MethodSource void parseMultipleCorrectly(AuthorList expected, String authorsString) { assertEquals(expected, parser.parse(authorsString)); } }
2,729
46.068966
161
java
null
jabref-main/src/test/java/org/jabref/logic/importer/BibDatabaseFilesTest.java
package org.jabref.logic.importer; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.database.BibDatabase; 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 BibDatabaseFilesTest { private ImportFormatPreferences importFormatPreferences; @BeforeEach public void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test public void resolveStrings() throws IOException { try (FileInputStream stream = new FileInputStream("src/test/resources/org/jabref/util/twente.bib"); InputStreamReader fr = new InputStreamReader(stream, StandardCharsets.UTF_8)) { ParserResult result = new BibtexParser(importFormatPreferences).parse(fr); BibDatabase db = result.getDatabase(); assertEquals("Arvind", db.resolveForStrings("#Arvind#")); assertEquals("Patterson, David", db.resolveForStrings("#Patterson#")); assertEquals("Arvind and Patterson, David", db.resolveForStrings("#Arvind# and #Patterson#")); // Strings that are not found return just the given string. assertEquals("#unknown#", db.resolveForStrings("#unknown#")); } } }
1,562
34.522727
107
java
null
jabref-main/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java
package org.jabref.logic.importer; import java.util.Collection; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.DummyFileUpdateMonitor; 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.assertNotNull; import static org.mockito.Mockito.mock; class DatabaseFileLookupTest { private BibDatabase database; private Collection<BibEntry> entries; private BibEntry entry1; private BibEntry entry2; @BeforeEach void setUp() throws Exception { ParserResult result = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()) .importDatabase(ImportDataTest.UNLINKED_FILES_TEST_BIB); database = result.getDatabase(); entries = database.getEntries(); entry1 = database.getEntryByCitationKey("entry1").get(); entry2 = database.getEntryByCitationKey("entry2").get(); } /** * Tests the prerequisites of this test-class itself. */ @Test void testTestDatabase() { assertEquals(2, database.getEntryCount()); assertEquals(2, entries.size()); assertNotNull(entry1); assertNotNull(entry2); } }
1,468
29.604167
143
java
null
jabref-main/src/test/java/org/jabref/logic/importer/FulltextFetchersTest.java
package org.jabref.logic.importer; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Optional; import java.util.Set; import org.jabref.logic.importer.fetcher.TrustLevel; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest public class FulltextFetchersTest { private BibEntry entry = new BibEntry(); @Test public void acceptPdfUrls() throws MalformedURLException { URL pdfUrl = new URL("http://docs.oasis-open.org/wsbpel/2.0/OS/wsbpel-v2.0-OS.pdf"); FulltextFetcher finder = e -> Optional.of(pdfUrl); FulltextFetchers fetcher = new FulltextFetchers(Set.of(finder)); assertEquals(Optional.of(pdfUrl), fetcher.findFullTextPDF(entry)); } @Test public void rejectNonPdfUrls() throws MalformedURLException { URL pdfUrl = new URL("https://github.com/JabRef/jabref/blob/master/README.md"); FulltextFetcher finder = e -> Optional.of(pdfUrl); FulltextFetchers fetcher = new FulltextFetchers(Set.of(finder)); assertEquals(Optional.empty(), fetcher.findFullTextPDF(entry)); } @Test public void noTrustLevel() throws MalformedURLException { URL pdfUrl = new URL("http://docs.oasis-open.org/wsbpel/2.0/OS/wsbpel-v2.0-OS.pdf"); FulltextFetcher finder = e -> Optional.of(pdfUrl); FulltextFetchers fetcher = new FulltextFetchers(Set.of(finder)); assertEquals(Optional.of(pdfUrl), fetcher.findFullTextPDF(entry)); } @Test public void higherTrustLevelWins() throws IOException, FetcherException { FulltextFetcher finderHigh = mock(FulltextFetcher.class); when(finderHigh.getTrustLevel()).thenReturn(TrustLevel.SOURCE); final URL highUrl = new URL("http://docs.oasis-open.org/wsbpel/2.0/OS/wsbpel-v2.0-OS.pdf"); when(finderHigh.findFullText(entry)).thenReturn(Optional.of(highUrl)); FulltextFetcher finderLow = mock(FulltextFetcher.class); when(finderLow.getTrustLevel()).thenReturn(TrustLevel.UNKNOWN); final URL lowUrl = new URL("http://docs.oasis-open.org/opencsa/sca-bpel/sca-bpel-1.1-spec-cd-01.pdf"); when(finderLow.findFullText(entry)).thenReturn(Optional.of(lowUrl)); FulltextFetchers fetcher = new FulltextFetchers(Set.of(finderLow, finderHigh)); // set an (arbitrary) DOI to the test entry to skip side effects inside the "findFullTextPDF" method entry.setField(StandardField.DOI, "10.5220/0007903201120130"); assertEquals(Optional.of(highUrl), fetcher.findFullTextPDF(entry)); } }
2,865
39.366197
110
java
null
jabref-main/src/test/java/org/jabref/logic/importer/ImportDataTest.java
package org.jabref.logic.importer; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class ImportDataTest { public static final Path FILE_IN_DATABASE = Path.of("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/pdfInDatabase.pdf"); public static final Path FILE_NOT_IN_DATABASE = Path.of("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/pdfNotInDatabase.pdf"); public static final Path EXISTING_FOLDER = Path.of("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder"); public static final Path NOT_EXISTING_FOLDER = Path.of("notexistingfolder"); public static final Path NOT_EXISTING_PDF = Path.of("src/test/resources/org/jabref/logic/importer/unlinkedFilesTestFolder/null.pdf"); public static final Path UNLINKED_FILES_TEST_BIB = Path.of("src/test/resources/org/jabref/util/unlinkedFilesTestBib.bib"); /** * Tests the testing environment. */ @Test void testTestingEnvironment() { assertTrue(Files.exists(ImportDataTest.EXISTING_FOLDER), "EXISTING_FOLDER does not exist"); assertTrue(Files.isDirectory(ImportDataTest.EXISTING_FOLDER), "EXISTING_FOLDER is not a directory"); assertTrue(Files.exists(ImportDataTest.FILE_IN_DATABASE), "FILE_IN_DATABASE does not exist"); assertTrue(Files.isRegularFile(ImportDataTest.FILE_IN_DATABASE), "FILE_IN_DATABASE is not a regular file"); assertTrue(Files.exists(ImportDataTest.FILE_NOT_IN_DATABASE), "FILE_NOT_IN_DATABASE does not exist"); assertTrue(Files.isRegularFile(ImportDataTest.FILE_NOT_IN_DATABASE), "FILE_NOT_IN_DATABASE is not a regular file"); assertFalse(Files.exists(ImportDataTest.NOT_EXISTING_FOLDER), "NOT_EXISTING_FOLDER exists"); assertFalse(Files.exists(ImportDataTest.NOT_EXISTING_PDF), "NOT_EXISTING_PDF exists"); } }
2,023
52.263158
153
java
null
jabref-main/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java
package org.jabref.logic.importer; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Stream; import javafx.collections.FXCollections; import org.jabref.model.util.DummyFileUpdateMonitor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; 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 ImportFormatReaderIntegrationTest { private ImportFormatReader reader; @BeforeEach void setUp() { ImporterPreferences importerPreferences = mock(ImporterPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importerPreferences.getCustomImporters()).thenReturn(FXCollections.emptyObservableSet()); reader = new ImportFormatReader( importerPreferences, mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); } @ParameterizedTest @MethodSource("importFormats") void testImportUnknownFormat(String resource, String format, int count) throws Exception { Path file = Path.of(ImportFormatReaderIntegrationTest.class.getResource(resource).toURI()); ImportFormatReader.UnknownFormatImport unknownFormat = reader.importUnknownFormat(file, new DummyFileUpdateMonitor()); assertEquals(count, unknownFormat.parserResult().getDatabase().getEntryCount()); } @ParameterizedTest @MethodSource("importFormats") void testImportFormatFromFile(String resource, String format, int count) throws Exception { Path file = Path.of(ImportFormatReaderIntegrationTest.class.getResource(resource).toURI()); assertEquals(count, reader.importFromFile(format, file).getDatabase().getEntries().size()); } @ParameterizedTest @MethodSource("importFormats") void testImportUnknownFormatFromString(String resource, String format, int count) throws Exception { Path file = Path.of(ImportFormatReaderIntegrationTest.class.getResource(resource).toURI()); String data = Files.readString(file); assertEquals(count, reader.importUnknownFormat(data).parserResult().getDatabase().getEntries().size()); } private static Stream<Object[]> importFormats() { Collection<Object[]> result = new ArrayList<>(); result.add(new Object[]{"fileformat/RisImporterTest1.ris", "ris", 1}); result.add(new Object[]{"fileformat/IsiImporterTest1.isi", "isi", 1}); result.add(new Object[]{"fileformat/SilverPlatterImporterTest1.txt", "silverplatter", 1}); result.add(new Object[]{"fileformat/RepecNepImporterTest2.txt", "repecnep", 1}); result.add(new Object[]{"fileformat/OvidImporterTest3.txt", "ovid", 1}); result.add(new Object[]{"fileformat/Endnote.entries.enw", "refer", 5}); result.add(new Object[]{"fileformat/MsBibImporterTest4.xml", "msbib", 1}); result.add(new Object[]{"fileformat/MsBibImporterTest4.bib", "bibtex", 1}); return result.stream(); } }
3,230
43.875
126
java
null
jabref-main/src/test/java/org/jabref/logic/importer/ImportFormatReaderParameterlessTest.java
package org.jabref.logic.importer; import java.nio.file.Path; import javafx.collections.FXCollections; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateMonitor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ImportFormatReaderParameterlessTest { private ImportFormatReader reader; private final FileUpdateMonitor fileMonitor = new DummyFileUpdateMonitor(); @BeforeEach void setUp() { ImporterPreferences importerPreferences = mock(ImporterPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importerPreferences.getCustomImporters()).thenReturn(FXCollections.emptyObservableSet()); ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); reader = new ImportFormatReader(importerPreferences, importFormatPreferences, fileMonitor); } @Test void importUnknownFormatThrowsExceptionIfNoMatchingImporterWasFound() throws Exception { Path file = Path.of(ImportFormatReaderParameterlessTest.class.getResource("fileformat/emptyFile.xml").toURI()); assertThrows(ImportException.class, () -> reader.importUnknownFormat(file, fileMonitor)); } @Test void importUnknownFormatThrowsExceptionIfPathIsNull() { assertThrows(NullPointerException.class, () -> reader.importUnknownFormat(null, fileMonitor)); } @Test void importUnknownFormatThrowsExceptionIfDataIsNull() { assertThrows(NullPointerException.class, () -> reader.importUnknownFormat(null)); } @Test void importFromFileWithUnknownFormatThrowsException() { assertThrows(ImportException.class, () -> reader.importFromFile("someunknownformat", Path.of("somepath"))); } }
1,968
36.865385
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/ImporterTest.java
package org.jabref.logic.importer; import java.io.BufferedReader; import java.util.regex.Pattern; import java.util.stream.Stream; import org.jabref.logic.importer.fileformat.BiblioscapeImporter; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.logic.importer.fileformat.CitaviXmlImporter; import org.jabref.logic.importer.fileformat.CopacImporter; import org.jabref.logic.importer.fileformat.EndnoteImporter; import org.jabref.logic.importer.fileformat.InspecImporter; import org.jabref.logic.importer.fileformat.IsiImporter; import org.jabref.logic.importer.fileformat.MedlineImporter; import org.jabref.logic.importer.fileformat.MedlinePlainImporter; import org.jabref.logic.importer.fileformat.ModsImporter; import org.jabref.logic.importer.fileformat.MsBibImporter; import org.jabref.logic.importer.fileformat.OvidImporter; import org.jabref.logic.importer.fileformat.PdfContentImporter; import org.jabref.logic.importer.fileformat.PdfXmpImporter; import org.jabref.logic.importer.fileformat.RepecNepImporter; import org.jabref.logic.importer.fileformat.RisImporter; import org.jabref.logic.importer.fileformat.SilverPlatterImporter; import org.jabref.logic.xmp.XmpPreferences; import org.jabref.model.util.DummyFileUpdateMonitor; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; import org.mockito.Mockito; 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.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ImporterTest { @ParameterizedTest @MethodSource("instancesToTest") public void isRecognizedFormatWithNullForBufferedReaderThrowsException(Importer format) { assertThrows(NullPointerException.class, () -> format.isRecognizedFormat((BufferedReader) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void isRecognizedFormatWithNullForStringThrowsException(Importer format) { assertThrows(NullPointerException.class, () -> format.isRecognizedFormat((String) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void importDatabaseWithNullForBufferedReaderThrowsException(Importer format) { assertThrows(NullPointerException.class, () -> format.importDatabase((BufferedReader) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void importDatabaseWithNullForStringThrowsException(Importer format) { assertThrows(NullPointerException.class, () -> format.importDatabase((String) null)); } @ParameterizedTest @MethodSource("instancesToTest") public void getFormatterNameDoesNotReturnNull(Importer format) { assertNotNull(format.getName()); } @ParameterizedTest @MethodSource("instancesToTest") public void getFileTypeDoesNotReturnNull(Importer format) { assertNotNull(format.getFileType()); } @ParameterizedTest @MethodSource("instancesToTest") public void getIdDoesNotReturnNull(Importer format) { assertNotNull(format.getId()); } @ParameterizedTest @MethodSource("instancesToTest") public void getIdDoesNotContainWhitespace(Importer format) { Pattern whitespacePattern = Pattern.compile("\\s"); assertFalse(whitespacePattern.matcher(format.getId()).find()); } @ParameterizedTest @MethodSource("instancesToTest") public void getIdStripsSpecialCharactersAndConvertsToLowercase(Importer format) { Importer importer = mock(Importer.class, Mockito.CALLS_REAL_METHODS); when(importer.getName()).thenReturn("*Test-Importer"); assertEquals("testimporter", importer.getId()); } @ParameterizedTest @MethodSource("instancesToTest") public void getDescriptionDoesNotReturnNull(Importer format) { assertNotNull(format.getDescription()); } public static Stream<Importer> instancesToTest() { // all classes implementing {@link Importer} // sorted alphabetically ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); XmpPreferences xmpPreferences = mock(XmpPreferences.class); // @formatter:off return Stream.of( new BiblioscapeImporter(), new BibtexImporter(importFormatPreferences, new DummyFileUpdateMonitor()), new CopacImporter(), new EndnoteImporter(importFormatPreferences), new InspecImporter(), new IsiImporter(), new MedlineImporter(), new MedlinePlainImporter(), new ModsImporter(importFormatPreferences), new MsBibImporter(), new OvidImporter(), new PdfContentImporter(importFormatPreferences), new PdfXmpImporter(xmpPreferences), new RepecNepImporter(importFormatPreferences), new RisImporter(), new SilverPlatterImporter(), new CitaviXmlImporter() ); // @formatter:on } }
5,465
39.791045
122
java