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/importer/OpenDatabaseTest.java
package org.jabref.logic.importer; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Collection; 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.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.LibraryPreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; class OpenDatabaseTest { private final Charset defaultEncoding = StandardCharsets.UTF_8; private LibraryPreferences libraryPreferences; private ImportFormatPreferences importFormatPreferences; private final Path bibNoHeader; private final Path bibWrongHeader; private final Path bibHeader; private final Path bibHeaderAndSignature; private final Path bibEncodingWithoutNewline; private final FileUpdateMonitor fileMonitor = new DummyFileUpdateMonitor(); OpenDatabaseTest() throws URISyntaxException { bibNoHeader = Path.of(OpenDatabaseTest.class.getResource("headerless.bib").toURI()); bibWrongHeader = Path.of(OpenDatabaseTest.class.getResource("wrong-header.bib").toURI()); bibHeader = Path.of(OpenDatabaseTest.class.getResource("encoding-header.bib").toURI()); bibHeaderAndSignature = Path.of(OpenDatabaseTest.class.getResource("jabref-header.bib").toURI()); bibEncodingWithoutNewline = Path.of(OpenDatabaseTest.class.getResource("encodingWithoutNewline.bib").toURI()); } @BeforeEach void setUp() { libraryPreferences = mock(LibraryPreferences.class, Answers.RETURNS_DEEP_STUBS); importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test void useFallbackEncodingIfNoHeader() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibNoHeader, importFormatPreferences, fileMonitor); assertEquals(defaultEncoding, result.getMetaData().getEncoding().get()); } @Test void useFallbackEncodingIfUnknownHeader() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibWrongHeader, importFormatPreferences, fileMonitor); assertEquals(defaultEncoding, result.getMetaData().getEncoding().get()); } @Test void useSpecifiedEncoding() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibHeader, importFormatPreferences, fileMonitor); assertEquals(defaultEncoding, result.getMetaData().getEncoding().get()); } @Test void useSpecifiedEncodingWithSignature() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibHeaderAndSignature, importFormatPreferences, fileMonitor); assertEquals(defaultEncoding, result.getMetaData().getEncoding().get()); } @Test void entriesAreParsedNoHeader() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibNoHeader, importFormatPreferences, fileMonitor); BibDatabase db = result.getDatabase(); // Entry assertEquals(1, db.getEntryCount()); assertEquals(Optional.of("2014"), db.getEntryByCitationKey("1").get().getField(StandardField.YEAR)); } @Test void entriesAreParsedHeader() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibHeader, importFormatPreferences, fileMonitor); BibDatabase db = result.getDatabase(); // Entry assertEquals(1, db.getEntryCount()); assertEquals(Optional.of("2014"), db.getEntryByCitationKey("1").get().getField(StandardField.YEAR)); } @Test void entriesAreParsedHeaderAndSignature() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibHeaderAndSignature, importFormatPreferences, fileMonitor); BibDatabase db = result.getDatabase(); // Entry assertEquals(1, db.getEntryCount()); assertEquals(Optional.of("2014"), db.getEntryByCitationKey("1").get().getField(StandardField.YEAR)); } /** * Test for #669 */ @Test void correctlyParseEncodingWithoutNewline() throws IOException { ParserResult result = OpenDatabase.loadDatabase(bibEncodingWithoutNewline, importFormatPreferences, fileMonitor); assertEquals(StandardCharsets.US_ASCII, result.getMetaData().getEncoding().get()); BibDatabase db = result.getDatabase(); assertEquals(Optional.of("testPreamble"), db.getPreamble()); Collection<BibEntry> entries = db.getEntries(); assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); assertEquals(Optional.of("testArticle"), entry.getCitationKey()); } }
5,028
39.886179
121
java
null
jabref-main/src/test/java/org/jabref/logic/importer/ParserResultTest.java
package org.jabref.logic.importer; import java.util.List; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class ParserResultTest { @Test void isEmptyForNewParseResult() { ParserResult empty = new ParserResult(); assertTrue(empty.isEmpty()); } @Test void isNotEmptyForBibDatabaseWithOneEntry() { BibEntry bibEntry = new BibEntry(); BibDatabase bibDatabase = new BibDatabase(List.of(bibEntry)); ParserResult parserResult = new ParserResult(bibDatabase); assertFalse(parserResult.isEmpty()); } }
764
25.37931
69
java
null
jabref-main/src/test/java/org/jabref/logic/importer/QueryParserTest.java
package org.jabref.logic.importer; import org.jabref.logic.importer.fetcher.ComplexSearchQuery; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class QueryParserTest { QueryParser parser = new QueryParser(); @Test public void convertAuthorField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("author:\"Igor Steinmacher\"").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().author("\"Igor Steinmacher\"").build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertDefaultField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("\"default value\"").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().defaultFieldPhrase("\"default value\"").build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertExplicitDefaultField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("default:\"default value\"").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().defaultFieldPhrase("\"default value\"").build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertJournalField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("journal:Nature").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().journal("\"Nature\"").build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertAlphabeticallyFirstJournalField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("journal:Nature journal:\"Complex Networks\"").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().journal("\"Complex Networks\"").build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertYearField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("year:2015").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().singleYear(2015).build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertNumericallyFirstYearField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("year:2015 year:2014").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().singleYear(2014).build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertYearRangeField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("year-range:2012-2015").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().fromYearAndToYear(2012, 2015).build(); assertEquals(expectedQuery, searchQuery); } @Test public void convertMultipleValuesWithTheSameField() { ComplexSearchQuery searchQuery = parser.parseQueryStringIntoComplexQuery("author:\"Igor Steinmacher\" author:\"Christoph Treude\"").get(); ComplexSearchQuery expectedQuery = ComplexSearchQuery.builder().author("\"Igor Steinmacher\"").author("\"Christoph Treude\"").build(); assertEquals(expectedQuery, searchQuery); } }
3,369
43.933333
146
java
null
jabref-main/src/test/java/org/jabref/logic/importer/WebFetchersTest.java
package org.jabref.logic.importer; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.jabref.logic.importer.fetcher.AbstractIsbnFetcher; import org.jabref.logic.importer.fetcher.GoogleScholar; import org.jabref.logic.importer.fetcher.GrobidCitationFetcher; import org.jabref.logic.importer.fetcher.JstorFetcher; import org.jabref.logic.importer.fetcher.MrDLibFetcher; import org.jabref.logic.importer.fetcher.isbntobibtex.DoiToBibtexConverterComIsbnFetcher; import org.jabref.logic.importer.fetcher.isbntobibtex.EbookDeIsbnFetcher; import org.jabref.logic.importer.fetcher.isbntobibtex.OpenLibraryIsbnFetcher; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.FilePreferences; import io.github.classgraph.ClassGraph; import io.github.classgraph.ClassInfoList; import io.github.classgraph.ScanResult; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; 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; class WebFetchersTest { private static final Logger LOGGER = LoggerFactory.getLogger(WebFetchersTest.class); private static final Set<String> IGNORED_INACCESSIBLE_FETCHERS = Set.of("ArXivFetcher$ArXiv"); private ImportFormatPreferences importFormatPreferences; private ImporterPreferences importerPreferences; private final ClassGraph classGraph = new ClassGraph().enableAllInfo().acceptPackages("org.jabref"); @BeforeEach void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); importerPreferences = mock(ImporterPreferences.class); } private Set<Class<?>> getIgnoredInaccessibleClasses() { return IGNORED_INACCESSIBLE_FETCHERS.stream() .map(className -> "org.jabref.logic.importer.fetcher." + className) .map(classPath -> { try { return Class.forName(classPath); } catch (ClassNotFoundException e) { LOGGER.error("Some of the ignored classes were not found", e); return null; } }).filter(Objects::nonNull).collect(Collectors.toSet()); } @Test void getIdBasedFetchersReturnsAllFetcherDerivingFromIdBasedFetcher() { Set<IdBasedFetcher> idFetchers = WebFetchers.getIdBasedFetchers(importFormatPreferences, importerPreferences); try (ScanResult scanResult = classGraph.scan()) { ClassInfoList controlClasses = scanResult.getClassesImplementing(IdBasedFetcher.class.getCanonicalName()); Set<Class<?>> expected = new HashSet<>(controlClasses.loadClasses()); // Some classes implement IdBasedFetcher, but are only accessible to other fetcher, so ignore them expected.removeAll(getIgnoredInaccessibleClasses()); expected.remove(AbstractIsbnFetcher.class); expected.remove(IdBasedParserFetcher.class); // Remove special ISBN fetcher since we don't want to expose them to the user expected.remove(OpenLibraryIsbnFetcher.class); expected.remove(EbookDeIsbnFetcher.class); expected.remove(DoiToBibtexConverterComIsbnFetcher.class); // Remove the following, because they don't work at the moment expected.remove(JstorFetcher.class); expected.remove(GoogleScholar.class); assertEquals(expected, getClasses(idFetchers)); } } @Test void getEntryBasedFetchersReturnsAllFetcherDerivingFromEntryBasedFetcher() { Set<EntryBasedFetcher> idFetchers = WebFetchers.getEntryBasedFetchers( mock(ImporterPreferences.class), importFormatPreferences, mock(FilePreferences.class), mock(BibDatabaseContext.class)); try (ScanResult scanResult = classGraph.scan()) { ClassInfoList controlClasses = scanResult.getClassesImplementing(EntryBasedFetcher.class.getCanonicalName()); Set<Class<?>> expected = new HashSet<>(controlClasses.loadClasses()); expected.remove(EntryBasedParserFetcher.class); expected.remove(MrDLibFetcher.class); assertEquals(expected, getClasses(idFetchers)); } } @Test void getSearchBasedFetchersReturnsAllFetcherDerivingFromSearchBasedFetcher() { Set<SearchBasedFetcher> searchBasedFetchers = WebFetchers.getSearchBasedFetchers(importFormatPreferences, importerPreferences); try (ScanResult scanResult = classGraph.scan()) { ClassInfoList controlClasses = scanResult.getClassesImplementing(SearchBasedFetcher.class.getCanonicalName()); Set<Class<?>> expected = new HashSet<>(controlClasses.loadClasses()); // Some classes implement SearchBasedFetcher, but are only accessible to other fetcher, so ignore them expected.removeAll(getIgnoredInaccessibleClasses()); // Remove interfaces expected.remove(SearchBasedParserFetcher.class); // Remove the following, because they don't work atm expected.remove(JstorFetcher.class); expected.remove(GoogleScholar.class); expected.remove(PagedSearchBasedParserFetcher.class); expected.remove(PagedSearchBasedFetcher.class); // Remove GROBID, because we don't want to show this to the user expected.remove(GrobidCitationFetcher.class); assertEquals(expected, getClasses(searchBasedFetchers)); } } @Test void getFullTextFetchersReturnsAllFetcherDerivingFromFullTextFetcher() { Set<FulltextFetcher> fullTextFetchers = WebFetchers.getFullTextFetchers(importFormatPreferences, importerPreferences); try (ScanResult scanResult = classGraph.scan()) { ClassInfoList controlClasses = scanResult.getClassesImplementing(FulltextFetcher.class.getCanonicalName()); Set<Class<?>> expected = new HashSet<>(controlClasses.loadClasses()); // Some classes implement FulltextFetcher, but are only accessible to other fetcher, so ignore them expected.removeAll(getIgnoredInaccessibleClasses()); // Remove the following, because they don't work atm expected.remove(JstorFetcher.class); expected.remove(GoogleScholar.class); assertEquals(expected, getClasses(fullTextFetchers)); } } @Test void getIdFetchersReturnsAllFetcherDerivingFromIdFetcher() { Set<IdFetcher<?>> idFetchers = WebFetchers.getIdFetchers(importFormatPreferences); try (ScanResult scanResult = classGraph.scan()) { ClassInfoList controlClasses = scanResult.getClassesImplementing(IdFetcher.class.getCanonicalName()); Set<Class<?>> expected = new HashSet<>(controlClasses.loadClasses()); // Some classes implement IdFetcher, but are only accessible to other fetcher, so ignore them expected.removeAll(getIgnoredInaccessibleClasses()); expected.remove(IdParserFetcher.class); // Remove the following, because they don't work at the moment expected.remove(GoogleScholar.class); assertEquals(expected, getClasses(idFetchers)); } } private Set<? extends Class<?>> getClasses(Collection<?> objects) { return objects.stream().map(Object::getClass).collect(Collectors.toSet()); } }
7,768
43.649425
135
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/ACMPortalFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.fileformat.ACMPortalParser; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.apache.lucene.queryparser.flexible.core.QueryNodeParseException; import org.apache.lucene.queryparser.flexible.core.parser.SyntaxParser; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.jabref.logic.importer.fetcher.transformers.AbstractQueryTransformer.NO_EXPLICIT_FIELD; import static org.junit.jupiter.api.Assertions.assertEquals; @FetcherTest class ACMPortalFetcherTest { ACMPortalFetcher fetcher; @BeforeEach void setUp() { fetcher = new ACMPortalFetcher(); } @Test void searchByQueryFindsEntry() throws Exception { BibEntry searchEntry = new BibEntry(StandardEntryType.Conference) .withField(StandardField.AUTHOR, "Tobias Olsson and Morgan Ericsson and Anna Wingkvist") .withField(StandardField.YEAR, "2017") .withField(StandardField.MONTH, "9") .withField(StandardField.DAY, "11") .withField(StandardField.SERIES, "ECSA '17") .withField(StandardField.BOOKTITLE, "Proceedings of the 11th European Conference on Software Architecture: Companion Proceedings") .withField(StandardField.DOI, "10.1145/3129790.3129810") .withField(StandardField.LOCATION, "Canterbury, United Kingdom") .withField(StandardField.ISBN, "9781450352178") .withField(StandardField.KEYWORDS, "conformance checking, repository data mining, software architecture") .withField(StandardField.PUBLISHER, "Association for Computing Machinery") .withField(StandardField.ADDRESS, "New York, NY, USA") .withField(StandardField.TITLE, "The relationship of code churn and architectural violations in the open source software JabRef") .withField(StandardField.URL, "https://doi.org/10.1145/3129790.3129810") .withField(StandardField.PAGETOTAL, "7") .withField(StandardField.PAGES, "152–158"); List<BibEntry> fetchedEntries = fetcher.performSearch("The relationship of code churn and architectural violations in the open source software JabRef"); // we clear the abstract due to copyright reasons (JabRef's code should not contain copyrighted abstracts) for (BibEntry bibEntry : fetchedEntries) { bibEntry.clearField(StandardField.ABSTRACT); } assertEquals(Optional.of(searchEntry), fetchedEntries.stream().findFirst()); } @Test void testGetURLForQuery() throws FetcherException, MalformedURLException, URISyntaxException, QueryNodeParseException { String testQuery = "test query url"; SyntaxParser parser = new StandardSyntaxParser(); URL url = fetcher.getURLForQuery(parser.parse(testQuery, NO_EXPLICIT_FIELD)); String expected = "https://dl.acm.org/action/doSearch?AllField=test+query+url"; assertEquals(expected, url.toString()); } @Test void testGetParser() { ACMPortalParser expected = new ACMPortalParser(); assertEquals(expected.getClass(), fetcher.getParser().getClass()); } }
3,857
49.103896
160
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/ACSTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.support.DisabledOnCIServer; 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 ACSTest { private ACS finder; private BibEntry entry; @BeforeEach void setUp() { finder = new ACS(); entry = new BibEntry(); } @Test @DisabledOnCIServer("CI server is unreliable") void findByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1021/bk-2006-STYG.ch014"); assertEquals( Optional.of(new URL("https://pubs.acs.org/doi/pdf/10.1021/bk-2006-STYG.ch014")), finder.findFullText(entry) ); } @Test @DisabledOnCIServer("CI server is unreliable") void notFoundByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1021/bk-2006-WWW.ch014"); assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void entityWithoutDoi() throws IOException { assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void trustLevel() { assertEquals(TrustLevel.PUBLISHER, finder.getTrustLevel()); } }
1,488
25.122807
96
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/AbstractIsbnFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.model.entry.BibEntry; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @FetcherTest public abstract class AbstractIsbnFetcherTest { protected AbstractIsbnFetcher fetcher; protected BibEntry bibEntryEffectiveJava; public abstract void testName(); public abstract void authorsAreCorrectlyFormatted() throws Exception; public abstract void searchByIdSuccessfulWithShortISBN() throws FetcherException; @Test public void searchByIdSuccessfulWithLongISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("978-0321356680"); assertEquals(Optional.of(bibEntryEffectiveJava), fetchedEntry); } @Test public void searchByIdReturnsEmptyWithEmptyISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById(""); assertEquals(Optional.empty(), fetchedEntry); } @Test public void searchByIdThrowsExceptionForShortInvalidISBN() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("123456789")); } @Test public void searchByIdThrowsExceptionForLongInvalidISB() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("012345678910")); } @Test public void searchByIdThrowsExceptionForInvalidISBN() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("jabref-4-ever")); } }
1,725
31.566038
95
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/ApsFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.net.URL; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; 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 ApsFetcherTest { private ApsFetcher finder; @BeforeEach void setUp() { finder = new ApsFetcher(); } @Test void findFullTextFromDoi() throws Exception { BibEntry entry = new BibEntry().withField(StandardField.DOI, "10.1103/PhysRevLett.116.061102"); assertEquals(Optional.of(new URL("https://journals.aps.org/prl/pdf/10.1103/PhysRevLett.116.061102")), finder.findFullText(entry)); } @Test void findFullTextFromLowercaseDoi() throws Exception { BibEntry entry = new BibEntry().withField(StandardField.DOI, "10.1103/physrevlett.124.029002"); assertEquals(Optional.of(new URL("https://journals.aps.org/prl/pdf/10.1103/PhysRevLett.124.029002")), finder.findFullText(entry)); } @Test void notFindFullTextForUnauthorized() throws Exception { BibEntry entry = new BibEntry().withField(StandardField.DOI, "10.1103/PhysRevLett.89.127401"); assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void notFindFullTextForUnknownEntry() throws Exception { BibEntry entry = new BibEntry().withField(StandardField.DOI, "10.1016/j.aasri.2014.0559.002"); assertEquals(Optional.empty(), finder.findFullText(entry)); } }
1,648
32.653061
138
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/ArXivFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.StringJoiner; import java.util.stream.Collectors; import javafx.collections.FXCollections; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportCleanup; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.PagedSearchBasedFetcher; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.identifier.ArXivIdentifier; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest class ArXivFetcherTest implements SearchBasedFetcherCapabilityTest, PagedSearchFetcherTest { private static ImportFormatPreferences importFormatPreferences; private ArXivFetcher fetcher; private BibEntry entry; private BibEntry sliceTheoremPaper; private BibEntry mainOriginalPaper; private BibEntry mainResultPaper; private BibEntry completePaper; @BeforeAll static void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); // Used during DOI fetch process when(importFormatPreferences.fieldPreferences().getNonWrappableFields()).thenReturn( FXCollections.observableArrayList(List.of( StandardField.PDF, StandardField.PS, StandardField.URL, StandardField.DOI, StandardField.FILE, StandardField.ISBN, StandardField.ISSN))); } @BeforeEach void eachSetUp() { fetcher = new ArXivFetcher(importFormatPreferences); entry = new BibEntry(); // A BibEntry with information only from ArXiv API mainOriginalPaper = new BibEntry(StandardEntryType.Article) // ArXiv-original fields .withField(StandardField.AUTHOR, "Joeran Beel and Andrew Collins and Akiko Aizawa") .withField(StandardField.TITLE, "The Architecture of Mr. DLib's Scientific Recommender-System API") .withField(StandardField.DATE, "2018-11-26") .withField(StandardField.ABSTRACT, "Recommender systems in academia are not widely available. This may be in part due to the difficulty and cost of developing and maintaining recommender systems. Many operators of academic products such as digital libraries and reference managers avoid this effort, although a recommender system could provide significant benefits to their users. In this paper, we introduce Mr. DLib's \"Recommendations as-a-Service\" (RaaS) API that allows operators of academic products to easily integrate a scientific recommender system into their products. Mr. DLib generates recommendations for research articles but in the future, recommendations may include call for papers, grants, etc. Operators of academic products can request recommendations from Mr. DLib and display these recommendations to their users. Mr. DLib can be integrated in just a few hours or days; creating an equivalent recommender system from scratch would require several months for an academic operator. Mr. DLib has been used by GESIS Sowiport and by the reference manager JabRef. Mr. DLib is open source and its goal is to facilitate the application of, and research on, scientific recommender systems. In this paper, we present the motivation for Mr. DLib, the architecture and details about the effectiveness. Mr. DLib has delivered 94m recommendations over a span of two years with an average click-through rate of 0.12%.") .withField(StandardField.EPRINT, "1811.10364") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1811.10364v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "cs.IR") .withField(StandardField.KEYWORDS, "cs.IR, cs.AI, cs.DL, cs.LG"); mainResultPaper = new BibEntry(StandardEntryType.Article) // ArXiv-original fields // .withField(StandardField.AUTHOR, "Joeran Beel and Andrew Collins and Akiko Aizawa") .withField(StandardField.TITLE, "The Architecture of Mr. DLib's Scientific Recommender-System API") .withField(StandardField.DATE, "2018-11-26") .withField(StandardField.ABSTRACT, "Recommender systems in academia are not widely available. This may be in part due to the difficulty and cost of developing and maintaining recommender systems. Many operators of academic products such as digital libraries and reference managers avoid this effort, although a recommender system could provide significant benefits to their users. In this paper, we introduce Mr. DLib's \"Recommendations as-a-Service\" (RaaS) API that allows operators of academic products to easily integrate a scientific recommender system into their products. Mr. DLib generates recommendations for research articles but in the future, recommendations may include call for papers, grants, etc. Operators of academic products can request recommendations from Mr. DLib and display these recommendations to their users. Mr. DLib can be integrated in just a few hours or days; creating an equivalent recommender system from scratch would require several months for an academic operator. Mr. DLib has been used by GESIS Sowiport and by the reference manager JabRef. Mr. DLib is open source and its goal is to facilitate the application of, and research on, scientific recommender systems. In this paper, we present the motivation for Mr. DLib, the architecture and details about the effectiveness. Mr. DLib has delivered 94m recommendations over a span of two years with an average click-through rate of 0.12%.") .withField(StandardField.EPRINT, "1811.10364") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1811.10364v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "cs.IR") // .withField(StandardField.KEYWORDS, "cs.IR, cs.AI, cs.DL, cs.LG") // Unavailable info: // StandardField.JOURNALTITLE // INFO NOT APPLICABLE TO THIS ENTRY // ArXiv-issue DOI fields .withField(new UnknownField("copyright"), "arXiv.org perpetual, non-exclusive license") .withField((InternalField.KEY_FIELD), "https://doi.org/10.48550/arxiv.1811.10364") .withField(StandardField.YEAR, "2018") .withField(StandardField.KEYWORDS, "Information Retrieval (cs.IR), Artificial Intelligence (cs.AI), Digital Libraries (cs.DL), Machine Learning (cs.LG), FOS: Computer and information sciences") .withField(StandardField.AUTHOR, "Beel, Joeran and Collins, Andrew and Aizawa, Akiko") .withField(StandardField.PUBLISHER, "arXiv") .withField(StandardField.DOI, "10.48550/ARXIV.1811.10364"); // Example of a robust result, with information from both ArXiv-assigned and user-assigned DOIs // FixMe: Test this BibEntry completePaper = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Büscher, Tobias and Diez, Angel L. and Gompper, Gerhard and Elgeti, Jens") .withField(StandardField.TITLE, "Instability and fingering of interfaces in growing tissue") .withField(StandardField.DATE, "2020-03-10") .withField(StandardField.YEAR, "2020") .withField(StandardField.MONTH, "aug") .withField(StandardField.NUMBER, "8") .withField(StandardField.VOLUME, "22") .withField(StandardField.PAGES, "083005") .withField(StandardField.PUBLISHER, "{IOP} Publishing") .withField(StandardField.JOURNAL, "New Journal of Physics") .withField(StandardField.ABSTRACT, "Interfaces in tissues are ubiquitous, both between tissue and environment as well as between populations of different cell types. The propagation of an interface can be driven mechanically. % e.g. by a difference in the respective homeostatic stress of the different cell types. Computer simulations of growing tissues are employed to study the stability of the interface between two tissues on a substrate. From a mechanical perspective, the dynamics and stability of this system is controlled mainly by four parameters of the respective tissues: (i) the homeostatic stress (ii) cell motility (iii) tissue viscosity and (iv) substrate friction. For propagation driven by a difference in homeostatic stress, the interface is stable for tissue-specific substrate friction even for very large differences of homeostatic stress; however, it becomes unstable above a critical stress difference when the tissue with the larger homeostatic stress has a higher viscosity. A small difference in directed bulk motility between the two tissues suffices to result in propagation with a stable interface, even for otherwise identical tissues. Larger differences in motility force, however, result in a finite-wavelength instability of the interface. Interestingly, the instability is apparently bound by nonlinear effects and the amplitude of the interface undulations only grows to a finite value in time.") .withField(StandardField.DOI, "10.1088/1367-2630/ab9e88") .withField(StandardField.EPRINT, "2003.04601") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/2003.04601v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "q-bio.TO") .withField(StandardField.KEYWORDS, "Tissues and Organs (q-bio.TO), FOS: Biological sciences") .withField(InternalField.KEY_FIELD, "B_scher_2020") .withField(new UnknownField("copyright"), "arXiv.org perpetual, non-exclusive license"); sliceTheoremPaper = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Diez, Tobias") .withField(StandardField.TITLE, "Slice theorem for Fréchet group actions and covariant symplectic field theory") .withField(StandardField.DATE, "2014-05-09") .withField(StandardField.YEAR, "2014") .withField(StandardField.PUBLISHER, "arXiv") .withField(StandardField.ABSTRACT, "A general slice theorem for the action of a Fr\\'echet Lie group on a Fr\\'echet manifolds is established. The Nash-Moser theorem provides the fundamental tool to generalize the result of Palais to this infinite-dimensional setting. The presented slice theorem is illustrated by its application to gauge theories: the action of the gauge transformation group admits smooth slices at every point and thus the gauge orbit space is stratified by Fr\\'echet manifolds. Furthermore, a covariant and symplectic formulation of classical field theory is proposed and extensively discussed. At the root of this novel framework is the incorporation of field degrees of freedom F and spacetime M into the product manifold F * M. The induced bigrading of differential forms is used in order to carry over the usual symplectic theory to this new setting. The examples of the Klein-Gordon field and general Yang-Mills theory illustrate that the presented approach conveniently handles the occurring symmetries.") .withField(StandardField.DOI, "10.48550/ARXIV.1405.2249") .withField(StandardField.EPRINT, "1405.2249") .withField(StandardField.EPRINTCLASS, "math-ph") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1405.2249v1:PDF") .withField(StandardField.KEYWORDS, "Mathematical Physics (math-ph), Differential Geometry (math.DG), Symplectic Geometry (math.SG), FOS: Physical sciences, FOS: Mathematics, 58B99, 58Z05, 58B25, 22E65, 58D19, 53D20, 53D42") .withField(InternalField.KEY_FIELD, "https://doi.org/10.48550/arxiv.1405.2249") .withField(new UnknownField("copyright"), "arXiv.org perpetual, non-exclusive license"); } @Override public SearchBasedFetcher getFetcher() { return fetcher; } public List<String> getInputTestAuthors() { return Arrays.stream(mainOriginalPaper.getField(StandardField.AUTHOR).get() .split("and")).map(String::trim).collect(Collectors.toList()); } @Override public List<String> getTestAuthors() { return Arrays.stream(mainResultPaper.getField(StandardField.AUTHOR).get() .split("and")).map(String::trim).collect(Collectors.toList()); } @Override public String getTestJournal() { return "Journal of Geometry and Physics (2013)"; } @Override public PagedSearchBasedFetcher getPagedFetcher() { return fetcher; } @Test @Override public void supportsAuthorSearch() throws FetcherException { StringJoiner queryBuilder = new StringJoiner("\" AND author:\"", "author:\"", "\""); getInputTestAuthors().forEach(queryBuilder::add); List<BibEntry> result = getFetcher().performSearch(queryBuilder.toString()); new ImportCleanup(BibDatabaseMode.BIBTEX).doPostCleanup(result); assertFalse(result.isEmpty()); result.forEach(bibEntry -> { String author = bibEntry.getField(StandardField.AUTHOR).orElse(""); // The co-authors differ, thus we check for the author present at all papers getTestAuthors().forEach(expectedAuthor -> Assertions.assertTrue(author.contains(expectedAuthor.replace("\"", "")))); }); } @Test public void noSupportsAuthorSearchWithLastFirstName() throws FetcherException { StringJoiner queryBuilder = new StringJoiner("\" AND author:\"", "author:\"", "\""); getTestAuthors().forEach(queryBuilder::add); List<BibEntry> result = getFetcher().performSearch(queryBuilder.toString()); new ImportCleanup(BibDatabaseMode.BIBTEX).doPostCleanup(result); assertTrue(result.isEmpty()); } @Test void findFullTextForEmptyEntryResultsEmptyOptional() throws IOException { assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test void findFullTextRejectsNullParameter() { assertThrows(NullPointerException.class, () -> fetcher.findFullText(null)); } @Test void findFullTextByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1529/biophysj.104.047340"); entry.setField(StandardField.TITLE, "Pause Point Spectra in DNA Constant-Force Unzipping"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/cond-mat/0406246v1")), fetcher.findFullText(entry)); } @Test void findFullTextByEprint() throws IOException { entry.setField(StandardField.EPRINT, "1603.06570"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/1603.06570v1")), fetcher.findFullText(entry)); } @Test void findFullTextByEprintWithPrefix() throws IOException { entry.setField(StandardField.EPRINT, "arXiv:1603.06570"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/1603.06570v1")), fetcher.findFullText(entry)); } @Test void findFullTextByEprintWithUnknownDOI() throws IOException { entry.setField(StandardField.DOI, "10.1529/unknown"); entry.setField(StandardField.EPRINT, "1603.06570"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/1603.06570v1")), fetcher.findFullText(entry)); } @Test void findFullTextByTitle() throws IOException { entry.setField(StandardField.TITLE, "Pause Point Spectra in DNA Constant-Force Unzipping"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/cond-mat/0406246v1")), fetcher.findFullText(entry)); } @Test void findFullTextByTitleWithCurlyBracket() throws IOException { entry.setField(StandardField.TITLE, "Machine versus {Human} {Attention} in {Deep} {Reinforcement} {Learning} {Tasks}"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/2010.15942v3")), fetcher.findFullText(entry)); } @Test void findFullTextByTitleWithColonAndJournalWithoutEprint() throws IOException { entry.setField(StandardField.TITLE, "Bayes-TrEx: a Bayesian Sampling Approach to Model Transparency by Example"); entry.setField(StandardField.JOURNAL, "arXiv:2002.10248v4 [cs]"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/2002.10248v4")), fetcher.findFullText(entry)); } @Test void findFullTextByTitleWithColonAndUrlWithoutEprint() throws IOException { entry.setField(StandardField.TITLE, "Bayes-TrEx: a Bayesian Sampling Approach to Model Transparency by Example"); entry.setField(StandardField.URL, "http://arxiv.org/abs/2002.10248v4"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/2002.10248v4")), fetcher.findFullText(entry)); } @Test void findFullTextByTitleAndPartOfAuthor() throws IOException { entry.setField(StandardField.TITLE, "Pause Point Spectra in DNA Constant-Force Unzipping"); entry.setField(StandardField.AUTHOR, "Weeks and Lucks"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/cond-mat/0406246v1")), fetcher.findFullText(entry)); } @Test void findFullTextByTitleWithCurlyBracketAndPartOfAuthor() throws IOException { entry.setField(StandardField.TITLE, "Machine versus {Human} {Attention} in {Deep} {Reinforcement} {Learning} {Tasks}"); entry.setField(StandardField.AUTHOR, "Zhang, Ruohan and Guo"); assertEquals(Optional.of(new URL("http://arxiv.org/pdf/2010.15942v3")), fetcher.findFullText(entry)); } @Test void notFindFullTextByUnknownDOI() throws IOException { entry.setField(StandardField.DOI, "10.1529/unknown"); assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test void notFindFullTextByUnknownId() throws IOException { entry.setField(StandardField.EPRINT, "1234.12345"); assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test void findFullTextByDOINotAvailableInCatalog() throws IOException { entry.setField(StandardField.DOI, "10.1016/0370-2693(77)90015-6"); entry.setField(StandardField.TITLE, "Superspace formulation of supergravity"); assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test void findFullTextEntityWithoutDoi() throws IOException { assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test void findFullTextTrustLevel() { assertEquals(TrustLevel.PREPRINT, fetcher.getTrustLevel()); } @Test void searchEntryByPartOfTitle() throws Exception { assertEquals(Collections.singletonList(mainResultPaper), fetcher.performSearch("title:\"the architecture of mr. dLib's\"")); } @Test void searchEntryByPartOfTitleWithAcuteAccent() throws Exception { assertEquals(Collections.singletonList(sliceTheoremPaper), fetcher.performSearch("title:\"slice theorem for Fréchet\"")); } @Test void searchEntryByOldId() throws Exception { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "{H1 Collaboration}") .withField(StandardField.TITLE, "Multi-Electron Production at High Transverse Momenta in ep Collisions at HERA") .withField(StandardField.NUMBER, "1") .withField(StandardField.VOLUME, "31") .withField(StandardField.PAGES, "17--29") .withField(StandardField.DATE, "2003-07-07") .withField(StandardField.YEAR, "2003") .withField(StandardField.MONTH, "oct") .withField(StandardField.ABSTRACT, "Multi-electron production is studied at high electron transverse momentum in positron- and electron-proton collisions using the H1 detector at HERA. The data correspond to an integrated luminosity of 115 pb-1. Di-electron and tri-electron event yields are measured. Cross sections are derived in a restricted phase space region dominated by photon-photon collisions. In general good agreement is found with the Standard Model predictions. However, for electron pair invariant masses above 100 GeV, three di-electron events and three tri-electron events are observed, compared to Standard Model expectations of 0.30 \\pm 0.04 and 0.23 \\pm 0.04, respectively.") .withField(StandardField.PUBLISHER, "Springer Science and Business Media {LLC}") .withField(StandardField.EPRINT, "hep-ex/0307015") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/hep-ex/0307015v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "hep-ex") .withField(StandardField.KEYWORDS, "High Energy Physics - Experiment (hep-ex), FOS: Physical sciences") .withField(StandardField.DOI, "10.1140/epjc/s2003-01326-x") .withField(StandardField.JOURNAL, "Eur.Phys.J.C31:17-29,2003") .withField(InternalField.KEY_FIELD, "2003") .withField(new UnknownField("copyright"), "Assumed arXiv.org perpetual, non-exclusive license to distribute this article for submissions made before January 2004"); assertEquals(Optional.of(expected), fetcher.performSearchById("hep-ex/0307015")); } @Test void searchEntryByIdWith4DigitsAndVersion() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), fetcher.performSearchById("1405.2249v1")); } @Test void searchEntryByIdWith4Digits() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), fetcher.performSearchById("1405.2249")); } @Test void searchEntryByIdWith4DigitsAndPrefix() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), fetcher.performSearchById("arXiv:1405.2249")); } @Test void searchEntryByIdWith4DigitsAndPrefixAndNotTrimmed() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), fetcher.performSearchById("arXiv : 1405. 2249")); } @Test void searchEntryByIdWith5Digits() throws Exception { assertEquals(Optional.of( "An Optimal Convergence Theorem for Mean Curvature Flow of Arbitrary Codimension in Hyperbolic Spaces"), fetcher.performSearchById("1503.06747").flatMap(entry -> entry.getField(StandardField.TITLE))); } @Test void searchWithMalformedIdReturnsEmpty() throws Exception { assertEquals(Optional.empty(), fetcher.performSearchById("123412345")); } @Test void searchIdentifierForSlicePaper() throws Exception { sliceTheoremPaper.clearField(StandardField.EPRINT); assertEquals(ArXivIdentifier.parse("1405.2249"), fetcher.findIdentifier(sliceTheoremPaper)); } @Test void searchEmptyId() throws Exception { assertEquals(Optional.empty(), fetcher.performSearchById("")); } @Test void searchWithHttpUrl() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), fetcher.performSearchById("http://arxiv.org/abs/1405.2249")); } @Test void searchWithHttpsUrl() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), fetcher.performSearchById("https://arxiv.org/abs/1405.2249")); } @Test void searchWithHttpsUrlNotTrimmed() throws Exception { assertEquals(Optional.of(sliceTheoremPaper), fetcher.performSearchById("https : // arxiv . org / abs / 1405 . 2249 ")); } @Disabled("Is not supported by the current API") @Test @Override public void supportsYearSearch() throws Exception { } @Disabled("Is not supported by the current API") @Test @Override public void supportsYearRangeSearch() throws Exception { } /** * A phrase is a sequence of terms wrapped in quotes. * Only documents that contain exactly this sequence are returned. */ @Test public void supportsPhraseSearch() throws Exception { List<BibEntry> resultWithPhraseSearch = fetcher.performSearch("title:\"Taxonomy of Distributed\""); List<BibEntry> resultWithOutPhraseSearch = fetcher.performSearch("title:Taxonomy AND title:of AND title:Distributed"); // Phrase search result has to be subset of the default search result assertTrue(resultWithOutPhraseSearch.containsAll(resultWithPhraseSearch)); } /** * A phrase is a sequence of terms wrapped in quotes. * Only documents that contain exactly this sequence are returned. */ @Test public void supportsPhraseSearchAndMatchesExact() throws Exception { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Rafrastara, Fauzi Adi and Deyu, Qi") .withField(StandardField.TITLE, "A Survey and Taxonomy of Distributed Data Mining Research Studies: A Systematic Literature Review") .withField(StandardField.DATE, "2020-09-14") .withField(StandardField.YEAR, "2020") .withField(StandardField.PUBLISHER, "arXiv") .withField(StandardField.ABSTRACT, "Context: Data Mining (DM) method has been evolving year by year and as of today there is also the enhancement of DM technique that can be run several times faster than the traditional one, called Distributed Data Mining (DDM). It is not a new field in data processing actually, but in the recent years many researchers have been paying more attention on this area. Problems: The number of publication regarding DDM in high reputation journals and conferences has increased significantly. It makes difficult for researchers to gain a comprehensive view of DDM that require further research. Solution: We conducted a systematic literature review to map the previous research in DDM field. Our objective is to provide the motivation for new research by identifying the gap in DDM field as well as the hot area itself. Result: Our analysis came up with some conclusions by answering 7 research questions proposed in this literature review. In addition, the taxonomy of DDM research area is presented in this paper. Finally, this systematic literature review provides the statistic of development of DDM since 2000 to 2015, in which this will help the future researchers to have a comprehensive overview of current situation of DDM.") .withField(StandardField.EPRINT, "2009.10618") .withField(StandardField.DOI, "10.48550/ARXIV.2009.10618") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/2009.10618v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "cs.DC") .withField(StandardField.KEYWORDS, "Distributed / Parallel / Cluster Computing (cs.DC), Machine Learning (cs.LG), FOS: Computer and information sciences") .withField(InternalField.KEY_FIELD, "https://doi.org/10.48550/arxiv.2009.10618") .withField(new UnknownField("copyright"), "arXiv.org perpetual, non-exclusive license"); List<BibEntry> resultWithPhraseSearch = fetcher.performSearch("title:\"Taxonomy of Distributed\""); // There is only a single paper found by searching that contains the exact sequence "Taxonomy of Distributed" in the title. assertEquals(Collections.singletonList(expected), resultWithPhraseSearch); } @Test public void supportsBooleanANDSearch() throws Exception { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Büscher, Tobias and Diez, Angel L. and Gompper, Gerhard and Elgeti, Jens") .withField(StandardField.TITLE, "Instability and fingering of interfaces in growing tissue") .withField(StandardField.DATE, "2020-03-10") .withField(StandardField.YEAR, "2020") .withField(StandardField.MONTH, "aug") .withField(StandardField.NUMBER, "8") .withField(StandardField.VOLUME, "22") .withField(StandardField.PAGES, "083005") .withField(StandardField.PUBLISHER, "{IOP} Publishing") .withField(StandardField.JOURNAL, "New Journal of Physics") .withField(StandardField.ABSTRACT, "Interfaces in tissues are ubiquitous, both between tissue and environment as well as between populations of different cell types. The propagation of an interface can be driven mechanically. % e.g. by a difference in the respective homeostatic stress of the different cell types. Computer simulations of growing tissues are employed to study the stability of the interface between two tissues on a substrate. From a mechanical perspective, the dynamics and stability of this system is controlled mainly by four parameters of the respective tissues: (i) the homeostatic stress (ii) cell motility (iii) tissue viscosity and (iv) substrate friction. For propagation driven by a difference in homeostatic stress, the interface is stable for tissue-specific substrate friction even for very large differences of homeostatic stress; however, it becomes unstable above a critical stress difference when the tissue with the larger homeostatic stress has a higher viscosity. A small difference in directed bulk motility between the two tissues suffices to result in propagation with a stable interface, even for otherwise identical tissues. Larger differences in motility force, however, result in a finite-wavelength instability of the interface. Interestingly, the instability is apparently bound by nonlinear effects and the amplitude of the interface undulations only grows to a finite value in time.") .withField(StandardField.DOI, "10.1088/1367-2630/ab9e88") .withField(StandardField.EPRINT, "2003.04601") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/2003.04601v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "q-bio.TO") .withField(StandardField.KEYWORDS, "Tissues and Organs (q-bio.TO), FOS: Biological sciences") .withField(InternalField.KEY_FIELD, "B_scher_2020") .withField(new UnknownField("copyright"), "arXiv.org perpetual, non-exclusive license"); List<BibEntry> result = fetcher.performSearch("author:\"Tobias Büscher\" AND title:\"Instability and fingering of interfaces\""); // There is only one paper authored by Tobias Büscher with that phrase in the title assertEquals(Collections.singletonList(expected), result); } @Test public void retrievePureArxivEntryWhenAllDOIFetchingFails() throws FetcherException { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Hai Zheng and Po-Yi Ho and Meiling Jiang and Bin Tang and Weirong Liu and Dengjin Li and Xuefeng Yu and Nancy E. Kleckner and Ariel Amir and Chenli Liu") .withField(StandardField.TITLE, "Interrogating the Escherichia coli cell cycle by cell dimension perturbations") .withField(StandardField.DATE, "2017-01-03") .withField(StandardField.JOURNAL, "PNAS December 27, 2016 vol. 113 no. 52 15000-15005") .withField(StandardField.ABSTRACT, "Bacteria tightly regulate and coordinate the various events in their cell cycles to duplicate themselves accurately and to control their cell sizes. Growth of Escherichia coli, in particular, follows a relation known as Schaechter 's growth law. This law says that the average cell volume scales exponentially with growth rate, with a scaling exponent equal to the time from initiation of a round of DNA replication to the cell division at which the corresponding sister chromosomes segregate. Here, we sought to test the robustness of the growth law to systematic perturbations in cell dimensions achieved by varying the expression levels of mreB and ftsZ. We found that decreasing the mreB level resulted in increased cell width, with little change in cell length, whereas decreasing the ftsZ level resulted in increased cell length. Furthermore, the time from replication termination to cell division increased with the perturbed dimension in both cases. Moreover, the growth law remained valid over a range of growth conditions and dimension perturbations. The growth law can be quantitatively interpreted as a consequence of a tight coupling of cell division to replication initiation. Thus, its robustness to perturbations in cell dimensions strongly supports models in which the timing of replication initiation governs that of cell division, and cell volume is the key phenomenological variable governing the timing of replication initiation. These conclusions are discussed in the context of our recently proposed adder-per-origin model, in which cells add a constant volume per origin between initiations and divide a constant time after initiation.") .withField(StandardField.DOI, "10.1073/pnas.1617932114") .withField(StandardField.EPRINT, "1701.00587") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1701.00587v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "q-bio.CB") .withField(StandardField.KEYWORDS, "q-bio.CB"); DoiFetcher modifiedDoiFetcher = Mockito.spy(new DoiFetcher(importFormatPreferences)); when(modifiedDoiFetcher.performSearchById("10.1073/pnas.1617932114")).thenThrow(new FetcherException("Could not fetch user-assigned DOI")); when(modifiedDoiFetcher.performSearchById("10.48550/arXiv.1701.00587")).thenThrow(new FetcherException("Could not fetch ArXiv-assigned DOI")); ArXivFetcher modifiedArXivFetcher = Mockito.spy(new ArXivFetcher(importFormatPreferences, modifiedDoiFetcher)); assertEquals(Optional.of(expected), modifiedArXivFetcher.performSearchById("1701.00587")); } @Test public void canReplicateArXivOnlySearchByPassingNullParameter() throws FetcherException { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Hai Zheng and Po-Yi Ho and Meiling Jiang and Bin Tang and Weirong Liu and Dengjin Li and Xuefeng Yu and Nancy E. Kleckner and Ariel Amir and Chenli Liu") .withField(StandardField.TITLE, "Interrogating the Escherichia coli cell cycle by cell dimension perturbations") .withField(StandardField.DATE, "2017-01-03") .withField(StandardField.JOURNAL, "PNAS December 27, 2016 vol. 113 no. 52 15000-15005") .withField(StandardField.ABSTRACT, "Bacteria tightly regulate and coordinate the various events in their cell cycles to duplicate themselves accurately and to control their cell sizes. Growth of Escherichia coli, in particular, follows a relation known as Schaechter 's growth law. This law says that the average cell volume scales exponentially with growth rate, with a scaling exponent equal to the time from initiation of a round of DNA replication to the cell division at which the corresponding sister chromosomes segregate. Here, we sought to test the robustness of the growth law to systematic perturbations in cell dimensions achieved by varying the expression levels of mreB and ftsZ. We found that decreasing the mreB level resulted in increased cell width, with little change in cell length, whereas decreasing the ftsZ level resulted in increased cell length. Furthermore, the time from replication termination to cell division increased with the perturbed dimension in both cases. Moreover, the growth law remained valid over a range of growth conditions and dimension perturbations. The growth law can be quantitatively interpreted as a consequence of a tight coupling of cell division to replication initiation. Thus, its robustness to perturbations in cell dimensions strongly supports models in which the timing of replication initiation governs that of cell division, and cell volume is the key phenomenological variable governing the timing of replication initiation. These conclusions are discussed in the context of our recently proposed adder-per-origin model, in which cells add a constant volume per origin between initiations and divide a constant time after initiation.") .withField(StandardField.DOI, "10.1073/pnas.1617932114") .withField(StandardField.EPRINT, "1701.00587") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1701.00587v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "q-bio.CB") .withField(StandardField.KEYWORDS, "q-bio.CB"); ArXivFetcher modifiedArXivFetcher = new ArXivFetcher(importFormatPreferences, null); assertEquals(Optional.of(expected), modifiedArXivFetcher.performSearchById("1701.00587")); } @Test public void retrievePartialResultWhenCannotGetInformationFromUserAssignedDOI() throws FetcherException { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Zheng, Hai and Ho, Po-Yi and Jiang, Meiling and Tang, Bin and Liu, Weirong and Li, Dengjin and Yu, Xuefeng and Kleckner, Nancy E. and Amir, Ariel and Liu, Chenli") .withField(StandardField.TITLE, "Interrogating the Escherichia coli cell cycle by cell dimension perturbations") .withField(StandardField.DATE, "2017-01-03") .withField(StandardField.JOURNAL, "PNAS December 27, 2016 vol. 113 no. 52 15000-15005") .withField(StandardField.ABSTRACT, "Bacteria tightly regulate and coordinate the various events in their cell cycles to duplicate themselves accurately and to control their cell sizes. Growth of Escherichia coli, in particular, follows a relation known as Schaechter 's growth law. This law says that the average cell volume scales exponentially with growth rate, with a scaling exponent equal to the time from initiation of a round of DNA replication to the cell division at which the corresponding sister chromosomes segregate. Here, we sought to test the robustness of the growth law to systematic perturbations in cell dimensions achieved by varying the expression levels of mreB and ftsZ. We found that decreasing the mreB level resulted in increased cell width, with little change in cell length, whereas decreasing the ftsZ level resulted in increased cell length. Furthermore, the time from replication termination to cell division increased with the perturbed dimension in both cases. Moreover, the growth law remained valid over a range of growth conditions and dimension perturbations. The growth law can be quantitatively interpreted as a consequence of a tight coupling of cell division to replication initiation. Thus, its robustness to perturbations in cell dimensions strongly supports models in which the timing of replication initiation governs that of cell division, and cell volume is the key phenomenological variable governing the timing of replication initiation. These conclusions are discussed in the context of our recently proposed adder-per-origin model, in which cells add a constant volume per origin between initiations and divide a constant time after initiation.") .withField(StandardField.DOI, "10.1073/pnas.1617932114") .withField(StandardField.EPRINT, "1701.00587") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1701.00587v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "q-bio.CB") .withField(StandardField.KEYWORDS, "Cell Behavior (q-bio.CB), FOS: Biological sciences") .withField(new UnknownField("copyright"), "arXiv.org perpetual, non-exclusive license") .withField(InternalField.KEY_FIELD, "https://doi.org/10.48550/arxiv.1701.00587") .withField(StandardField.YEAR, "2017") .withField(StandardField.PUBLISHER, "arXiv"); DoiFetcher modifiedDoiFetcher = Mockito.spy(new DoiFetcher(importFormatPreferences)); when(modifiedDoiFetcher.performSearchById("10.1073/pnas.1617932114")).thenThrow(new FetcherException("Could not fetch user-assigned DOI")); ArXivFetcher modifiedArXivFetcher = Mockito.spy(new ArXivFetcher(importFormatPreferences, modifiedDoiFetcher)); assertEquals(Optional.of(expected), modifiedArXivFetcher.performSearchById("1701.00587")); } @Test public void retrievePartialResultWhenCannotGetInformationFromArXivAssignedDOI() throws FetcherException { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Hai Zheng and Po-Yi Ho and Meiling Jiang and Bin Tang and Weirong Liu and Dengjin Li and Xuefeng Yu and Nancy E. Kleckner and Ariel Amir and Chenli Liu") .withField(StandardField.TITLE, "Interrogating the Escherichia coli cell cycle by cell dimension perturbations") .withField(StandardField.DATE, "2017-01-03") .withField(StandardField.JOURNAL, "PNAS December 27, 2016 vol. 113 no. 52 15000-15005") .withField(StandardField.ABSTRACT, "Bacteria tightly regulate and coordinate the various events in their cell cycles to duplicate themselves accurately and to control their cell sizes. Growth of Escherichia coli, in particular, follows a relation known as Schaechter 's growth law. This law says that the average cell volume scales exponentially with growth rate, with a scaling exponent equal to the time from initiation of a round of DNA replication to the cell division at which the corresponding sister chromosomes segregate. Here, we sought to test the robustness of the growth law to systematic perturbations in cell dimensions achieved by varying the expression levels of mreB and ftsZ. We found that decreasing the mreB level resulted in increased cell width, with little change in cell length, whereas decreasing the ftsZ level resulted in increased cell length. Furthermore, the time from replication termination to cell division increased with the perturbed dimension in both cases. Moreover, the growth law remained valid over a range of growth conditions and dimension perturbations. The growth law can be quantitatively interpreted as a consequence of a tight coupling of cell division to replication initiation. Thus, its robustness to perturbations in cell dimensions strongly supports models in which the timing of replication initiation governs that of cell division, and cell volume is the key phenomenological variable governing the timing of replication initiation. These conclusions are discussed in the context of our recently proposed adder-per-origin model, in which cells add a constant volume per origin between initiations and divide a constant time after initiation.") .withField(StandardField.DOI, "10.1073/pnas.1617932114") .withField(StandardField.EPRINT, "1701.00587") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1701.00587v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "q-bio.CB") .withField(StandardField.KEYWORDS, "q-bio.CB") .withField(StandardField.MONTH, "dec") .withField(StandardField.YEAR, "2016") .withField(StandardField.VOLUME, "113") .withField(InternalField.KEY_FIELD, "Zheng_2016") .withField(StandardField.PUBLISHER, "Proceedings of the National Academy of Sciences") .withField(StandardField.PAGES, "15000--15005") .withField(StandardField.NUMBER, "52"); DoiFetcher modifiedDoiFetcher = Mockito.spy(new DoiFetcher(importFormatPreferences)); when(modifiedDoiFetcher.performSearchById("10.48550/arXiv.1701.00587")).thenThrow(new FetcherException("Could not fetch ArXiv-assigned DOI")); ArXivFetcher modifiedArXivFetcher = Mockito.spy(new ArXivFetcher(importFormatPreferences, modifiedDoiFetcher)); assertEquals(Optional.of(expected), modifiedArXivFetcher.performSearchById("1701.00587")); } }
46,209
76.533557
1,713
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/AstrophysicsDataSystemTest.java
package org.jabref.logic.importer.fetcher; import java.util.List; import java.util.Optional; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.PagedSearchBasedFetcher; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.paging.Page; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest public class AstrophysicsDataSystemTest implements PagedSearchFetcherTest { private AstrophysicsDataSystem fetcher; private BibEntry diezSliceTheoremEntry; private BibEntry famaeyMcGaughEntry; private BibEntry sunWelchEntry; private BibEntry xiongSunEntry; private BibEntry ingersollPollardEntry; private BibEntry luceyPaulEntry; @BeforeEach public void setUp() throws Exception { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); ImporterPreferences importerPreferences = mock(ImporterPreferences.class); when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); fetcher = new AstrophysicsDataSystem(importFormatPreferences, importerPreferences); diezSliceTheoremEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("2018arXiv181204698D") .withField(StandardField.AUTHOR, "Diez, Tobias and Rudolph, Gerd") .withField(StandardField.TITLE, "Slice theorem and orbit type stratification in infinite dimensions") .withField(StandardField.YEAR, "2018") .withField(StandardField.ARCHIVEPREFIX, "arXiv") .withField(StandardField.DOI, "10.48550/arXiv.1812.04698") .withField(StandardField.EPRINT, "1812.04698") .withField(StandardField.JOURNAL, "arXiv e-prints") .withField(StandardField.KEYWORDS, "Mathematics - Differential Geometry, Mathematical Physics, 58B25, (58D19, 58B20, 22E99, 58A35)") .withField(StandardField.MONTH, "#dec#") .withField(StandardField.PAGES, "arXiv:1812.04698") .withField(StandardField.EID, "arXiv:1812.04698") .withField(StandardField.PRIMARYCLASS, "math.DG") .withField(StandardField.URL, "https://ui.adsabs.harvard.edu/abs/2018arXiv181204698D") .withField(StandardField.ABSTRACT, "We establish a general slice theorem for the action of a locally convex Lie group on a locally convex manifold, which generalizes the classical slice theorem of Palais to infinite dimensions. We discuss two important settings under which the assumptions of this theorem are fulfilled. First, using Gl{\\\"o}ckner's inverse function theorem, we show that the linear action of a compact Lie group on a Fr{\\'e}chet space admits a slice. Second, using the Nash--Moser theorem, we establish a slice theorem for the tame action of a tame Fr{\\'e}chet Lie group on a tame Fr{\\'e}chet manifold. For this purpose, we develop the concept of a graded Riemannian metric, which allows the construction of a path-length metric compatible with the manifold topology and of a local addition. Finally, generalizing a classical result in finite dimensions, we prove that the existence of a slice implies that the decomposition of the manifold into orbit types of the group action is a stratification."); famaeyMcGaughEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("2012LRR....15...10F") .withField(StandardField.AUTHOR, "Famaey, Beno{\\^\\i}t and McGaugh, Stacy S.") .withField(StandardField.TITLE, "Modified Newtonian Dynamics (MOND): Observational Phenomenology and Relativistic Extensions") .withField(StandardField.JOURNAL, "Living Reviews in Relativity") .withField(StandardField.YEAR, "2012") .withField(StandardField.VOLUME, "15") .withField(StandardField.MONTH, "#sep#") .withField(StandardField.NUMBER, "1") .withField(StandardField.ARCHIVEPREFIX, "arXiv") .withField(StandardField.DOI, "10.12942/lrr-2012-10") .withField(StandardField.PRIMARYCLASS, "astro-ph.CO") .withField(StandardField.EID, "10") .withField(StandardField.EPRINT, "1112.3960") .withField(StandardField.PAGES, "10") .withField(StandardField.KEYWORDS, "astronomical observations, Newtonian limit, equations of motion, extragalactic astronomy, cosmology, theories of gravity, fundamental physics, astrophysics, Astrophysics - Cosmology and Nongalactic Astrophysics, Astrophysics - Astrophysics of Galaxies, General Relativity and Quantum Cosmology, High Energy Physics - Phenomenology, High Energy Physics - Theory") .withField(StandardField.URL, "https://ui.adsabs.harvard.edu/abs/2012LRR....15...10F"); sunWelchEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("2012NatMa..11...44S") .withField(StandardField.AUTHOR, "Sun, Yanming and Welch, Gregory C. and Leong, Wei Lin and Takacs, Christopher J. and Bazan, Guillermo C. and Heeger, Alan J.") .withField(StandardField.DOI, "10.1038/nmat3160") .withField(StandardField.JOURNAL, "Nature Materials") .withField(StandardField.MONTH, "#jan#") .withField(StandardField.NUMBER, "1") .withField(StandardField.PAGES, "44-48") .withField(StandardField.TITLE, "Solution-processed small-molecule solar cells with 6.7\\% efficiency") .withField(StandardField.VOLUME, "11") .withField(StandardField.YEAR, "2012") .withField(StandardField.URL, "https://ui.adsabs.harvard.edu/abs/2012NatMa..11...44S"); xiongSunEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("2007ITGRS..45..879X") .withField(StandardField.AUTHOR, "Xiong, Xiaoxiong and Sun, Junqiang and Barnes, William and Salomonson, Vincent and Esposito, Joseph and Erives, Hector and Guenther, Bruce") .withField(StandardField.DOI, "10.1109/TGRS.2006.890567") .withField(StandardField.JOURNAL, "IEEE Transactions on Geoscience and Remote Sensing") .withField(StandardField.MONTH, "#apr#") .withField(StandardField.NUMBER, "4") .withField(StandardField.PAGES, "879-889") .withField(StandardField.TITLE, "Multiyear On-Orbit Calibration and Performance of Terra MODIS Reflective Solar Bands") .withField(StandardField.VOLUME, "45") .withField(StandardField.YEAR, "2007") .withField(StandardField.URL, "https://ui.adsabs.harvard.edu/abs/2007ITGRS..45..879X"); ingersollPollardEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("1982Icar...52...62I") .withField(StandardField.ABSTRACT, "If Jupiter's and Saturn's fluid interiors were inviscid and adiabatic, any steady zonal motion would take the form of differentially rotating cylinders concentric about the planetary axis of rotation. B. A. Smith et al. [ Science215, 504-537 (1982)] showed that Saturn's observed zonal wind profile extends a significant distance below cloud base. Further extension into the interior occurs if the values of the eddy viscosity and superadiabaticity are small. We estimate these values using a scaling analysis of deep convection in the presence of differential rotation. The differential rotation inhibits the convection and reduces the effective eddy viscosity. Viscous dissipation of zonal mean kinetic energy is then within the bounds set by the internal heat source. The differential rotation increases the superadiabaticity, but not so much as to eliminate the cylindrical structure of the flow. Very large departures from adiabaticity, necessary for decoupling the atmosphere and interior, do not occur. Using our scaling analysis we develop the anelastic equations that describe motions in Jupiter's and Saturn's interiors. A simple problem is solved, that of an adiabatic fluid with a steady zonal wind varying as a function of cylindrical radius. Low zonal wavenumber perturbations are two dimensional (independent of the axial coordinate) and obey a modified barotropic stability equation. The parameter analogous to {\\ensuremath{\\beta}} is negative and is three to four times larger than the {\\ensuremath{\\beta}} for thin atmospheres. Jupiter's and Saturn's observed zonal wind profiles are close to marginal stability according to this deep sphere criterion, but are several times supercritical according to the thin atmosphere criterion.") .withField(StandardField.AUTHOR, "Ingersoll, A.~P. and Pollard, D.") .withField(StandardField.DOI, "10.1016/0019-1035(82)90169-5") .withField(StandardField.JOURNAL, "\\icarus") .withField(StandardField.KEYWORDS, "Atmospheric Circulation, Barotropic Flow, Convective Flow, Flow Stability, Jupiter Atmosphere, Rotating Fluids, Saturn Atmosphere, Adiabatic Flow, Anelasticity, Compressible Fluids, Planetary Rotation, Rotating Cylinders, Scaling Laws, Wind Profiles, PLANETS, JUPITER, SATURN, MOTION, INTERIORS, ATMOSPHERE, ANALYSIS, SCALE, BAROTROPY, CHARACTERISTICS, STRUCTURE, WINDS, VISCOSITY, DATA, CONVECTION, ROTATION, EDDY EFFECTS, ENERGY, ADIABATICITY, DIAGRAMS, REVIEW, LATITUDE, ZONES, VELOCITY, MATHEMATICAL MODELS, HEAT FLOW, EQUATIONS OF MOTION, FLUIDS, DYNAMICS, TEMPERATURE, GRADIENTS, Lunar and Planetary Exploration; Planets, Earth Science, Earth Science") .withField(StandardField.MONTH, "#oct#") .withField(StandardField.NUMBER, "1") .withField(StandardField.PAGES, "62-80") .withField(StandardField.TITLE, "Motion in the interiors and atmospheres of Jupiter and Saturn: scale analysis, anelastic equations, barotropic stability criterion") .withField(StandardField.VOLUME, "52") .withField(StandardField.YEAR, "1982") .withField(StandardField.URL, "https://ui.adsabs.harvard.edu/abs/1982Icar...52...62I"); luceyPaulEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("2000JGR...10520297L") .withField(StandardField.AUTHOR, "Lucey, Paul G. and Blewett, David T. and Jolliff, Bradley L.") .withField(StandardField.DOI, "10.1029/1999JE001117") .withField(StandardField.JOURNAL, "\\jgr") .withField(StandardField.KEYWORDS, "Planetology: Solid Surface Planets: Composition, Planetology: Solid Surface Planets: Remote sensing, Planetology: Solid Surface Planets: Surface materials and properties, Planetology: Solar System Objects: Moon (1221)") .withField(StandardField.PAGES, "20297-20306") .withField(StandardField.TITLE, "Lunar iron and titanium abundance algorithms based on final processing of Clementine ultraviolet-visible images") .withField(StandardField.VOLUME, "105") .withField(StandardField.YEAR, "2000") .withField(StandardField.URL, "https://ui.adsabs.harvard.edu/abs/2000JGR...10520297L") .withField(StandardField.MONTH, "#jan#") .withField(StandardField.NUMBER, "E8") .withField(StandardField.ABSTRACT, "The Clementine mission to the Moon returned global imaging data collected by the ultraviolet visible (UVVIS) camera. This data set is now in a final state of calibration, and a five-band multispectral digital image model (DIM) of the lunar surface will soon be available to the science community. We have used observations of the lunar sample-return sites and stations extracted from the final DIM in conjunction with compositional information for returned lunar soils to revise our previously published algorithms for the spectral determination of the FeO and TiO$_{2}$ content of the lunar surface. The algorithms successfully normalize the effects of space weathering so that composition may be determined without regard to a surface's state of maturity. These algorithms permit anyone with access to the standard archived DIM to construct high spatial resolution maps of FeO and TiO$_{2}$ abundance. Such maps will be of great utility in a variety of lunar geologic studies."); } @Test public void testGetName() { assertEquals("SAO/NASA ADS", fetcher.getName()); } @Test public void searchByQueryFindsEntry() throws Exception { List<BibEntry> fetchedEntries = fetcher.performSearch("Diez slice theorem Lie"); assertFalse(fetchedEntries.isEmpty()); assertTrue(fetchedEntries.contains(diezSliceTheoremEntry)); } @Test public void searchByEntryFindsEntry() throws Exception { BibEntry searchEntry = new BibEntry() .withField(StandardField.TITLE, "slice theorem") .withField(StandardField.AUTHOR, "Diez"); List<BibEntry> fetchedEntries = fetcher.performSearch(searchEntry); // The list contains more than one element, thus we need to check in two steps and cannot use assertEquals(List.of(diezSliceTheoremEntry, fetchedEntries)) assertFalse(fetchedEntries.isEmpty()); assertTrue(fetchedEntries.contains(diezSliceTheoremEntry)); } @Test public void testPerformSearchByFamaeyMcGaughEntry() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.12942/lrr-2012-10"); fetchedEntry.ifPresent(entry -> entry.clearField(StandardField.ABSTRACT)); // Remove abstract due to copyright assertEquals(Optional.of(famaeyMcGaughEntry), fetchedEntry); } @Test public void testPerformSearchByIdEmptyDOI() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById(""); assertEquals(Optional.empty(), fetchedEntry); } @Test public void testPerformSearchByIdInvalidDoi() throws Exception { assertEquals(Optional.empty(), fetcher.performSearchById("this.doi.will.fail")); } @Test public void testPerformSearchBySunWelchEntry() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.1038/nmat3160"); fetchedEntry.ifPresent(entry -> entry.clearField(StandardField.ABSTRACT)); // Remove abstract due to copyright assertEquals(Optional.of(sunWelchEntry), fetchedEntry); } @Test public void testPerformSearchByXiongSunEntry() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.1109/TGRS.2006.890567"); assertEquals(Optional.of(xiongSunEntry), fetchedEntry); } @Test public void testPerformSearchByIngersollPollardEntry() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.1016/0019-1035(82)90169-5"); assertEquals(Optional.of(ingersollPollardEntry), fetchedEntry); } @Test public void testPerformSearchByLuceyPaulEntry() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("2000JGR...10520297L"); assertEquals(Optional.of(luceyPaulEntry), fetchedEntry); } @Test public void performSearchByQueryPaged_searchLimitsSize() throws Exception { Page<BibEntry> page = fetcher.performSearchPaged("author:\"A\"", 0); assertEquals(fetcher.getPageSize(), page.getSize(), "fetcher return wrong page size"); } @Test public void performSearchByQueryPaged_invalidAuthorsReturnEmptyPages() throws Exception { Page<BibEntry> page = fetcher.performSearchPaged("author:\"ThisAuthorWillNotBeFound\"", 0); Page<BibEntry> page5 = fetcher.performSearchPaged("author:\"ThisAuthorWillNotBeFound\"", 5); assertEquals(0, page.getSize(), "fetcher doesnt return empty pages for invalid author"); assertEquals(0, page5.getSize(), "fetcher doesnt return empty pages for invalid author"); } @Override public PagedSearchBasedFetcher getPagedFetcher() { return fetcher; } }
17,354
75.792035
2,040
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/BiodiversityLibraryTest.java
package org.jabref.logic.importer.fetcher; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.util.BuildInfo; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import kong.unirest.json.JSONObject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest public class BiodiversityLibraryTest { private final String BASE_URL = "https://www.biodiversitylibrary.org/api3?"; private final String RESPONSE_FORMAT = "&format=json"; private final BuildInfo buildInfo = new BuildInfo(); private BiodiversityLibrary fetcher; @BeforeEach void setUp() { ImporterPreferences importerPreferences = mock(ImporterPreferences.class); when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); fetcher = new BiodiversityLibrary(importerPreferences); } @Test public void testGetName() { assertEquals("Biodiversity Heritage", fetcher.getName()); assertNotEquals("Biodiversity Heritage Library", fetcher.getName()); assertNotEquals("Biodiversity Library", fetcher.getName()); } @Test public void biodiversityHeritageApiKeyIsNotEmpty() { BuildInfo buildInfo = new BuildInfo(); assertNotNull(buildInfo.biodiversityHeritageApiKey); } @Test public void baseURLConstruction() throws MalformedURLException, URISyntaxException { String expected = fetcher .getTestUrl() .concat(buildInfo.biodiversityHeritageApiKey) .concat(RESPONSE_FORMAT); assertEquals(expected, fetcher.getBaseURL().toString()); } @ParameterizedTest @ValueSource(strings = {"1234", "331", "121"}) public void getPartMetadaUrl(String id) throws MalformedURLException, URISyntaxException { String expected = fetcher .getTestUrl() .concat(buildInfo.biodiversityHeritageApiKey) .concat(RESPONSE_FORMAT) .concat("&op=GetPartMetadata&pages=f&names=f") .concat("&id="); assertEquals(expected.concat(id), fetcher.getPartMetadataURL(id).toString()); } @ParameterizedTest @ValueSource(strings = {"1234", "4321", "331"}) public void getItemMetadaUrl(String id) throws MalformedURLException, URISyntaxException { String expected = fetcher .getTestUrl() .concat(buildInfo.biodiversityHeritageApiKey) .concat(RESPONSE_FORMAT) .concat("&op=GetItemMetadata&pages=f&ocr=f&ocr=f") .concat("&id="); assertEquals(expected.concat(id), fetcher.getItemMetadataURL(id).toString()); } @Test public void testPerformSearch() throws FetcherException { BibEntry expected = new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Ingersoll, Ernest, ") .withField(StandardField.EDITOR, "University of Illinois Urbana-Champaign Alternates") .withField(StandardField.LANGUAGE, "English") .withField(StandardField.PUBLISHER, "University Library, University of Illinois Urbana Champaign") .withField(StandardField.LOCATION, "Chicago") .withField(StandardField.TITLE, "Dogs") .withField(StandardField.URL, "https://www.biodiversitylibrary.org/item/219826") .withField(StandardField.YEAR, "1879"); // fetcher returns more than entry, by default up to 200, but we only want to check one here assertEquals(List.of(expected), fetcher.performSearch("dogs").subList(0, 1)); } @Test public void jsonResultToBibEntry() { JSONObject input = new JSONObject("{\n\"BHLType\": \"Part\",\n\"FoundIn\": \"Metadata\",\n\"Volume\": \"3\",\n\"Authors\": [\n{\n\"Name\": \"Dimmock, George,\"\n}\n],\n\"PartUrl\": \"https://www.biodiversitylibrary.org/part/181199\",\n\"PartID\": \"181199\",\n\"Genre\": \"Article\",\n\"Title\": \"The Cocoons of Cionus Scrophulariae\",\n\"ContainerTitle\": \"Psyche.\",\n\"Date\": \"1882\",\n\"PageRange\": \"411--413\"\n}"); BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.TITLE, "The Cocoons of Cionus Scrophulariae") .withField(StandardField.AUTHOR, "Dimmock, George, ") .withField(StandardField.PAGES, "411--413") .withField(StandardField.DATE, "1882") .withField(StandardField.JOURNALTITLE, "Psyche.") .withField(StandardField.VOLUME, "3"); assertEquals(expected, fetcher.jsonResultToBibEntry(input)); input = new JSONObject(""" { "BHLType": "Item", "FoundIn": "Metadata", "ItemID": "174333", "TitleID": "96205", "ItemUrl": "https://www.biodiversitylibrary.org/item/174333", "TitleUrl": "https://www.biodiversitylibrary.org/bibliography/96205", "MaterialType": "Published material", "PublisherPlace": "Salisbury", "PublisherName": "Frederick A. Blake,", "PublicationDate": "1861", "Authors": [ { "Name": "George, George" } ], "Genre": "Book", "Title": "Potatoes : the poor man's own crop : illustrated with plates, showing the decay and disease of the potatoe [sic] : with hints to improve the land and life of the poor man : published to aid the Industrial Marlborough Exhibition" }"""); expected = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Potatoes : the poor man's own crop : illustrated with plates, showing the decay and disease of the potatoe [sic] : with hints to improve the land and life of the poor man : published to aid the Industrial Marlborough Exhibition") .withField(StandardField.AUTHOR, "George, George ") .withField(StandardField.YEAR, "1861") .withField(StandardField.LOCATION, "Salisbury") .withField(StandardField.PUBLISHER, "Frederick A. Blake,"); assertEquals(expected, fetcher.jsonResultToBibEntry(input)); input = new JSONObject(""" { "BHLType": "Item", "FoundIn": "Metadata", "ItemID": "200116", "TitleID": "115108", "ItemUrl": "https://www.biodiversitylibrary.org/item/200116", "TitleUrl": "https://www.biodiversitylibrary.org/bibliography/115108", "MaterialType": "Published material", "PublisherPlace": "Washington", "PublisherName": "Government Prining Office,", "PublicationDate": "1911", "Authors": [ { "Name": "Whitaker, George M. (George Mason)" } ], "Genre": "Book", "Title": "The extra cost of producing clean milk." }"""); expected = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "The extra cost of producing clean milk.") .withField(StandardField.AUTHOR, "Whitaker, George M. (George Mason) ") .withField(StandardField.YEAR, "1911") .withField(StandardField.LOCATION, "Washington") .withField(StandardField.PUBLISHER, "Government Prining Office,"); assertEquals(expected, fetcher.jsonResultToBibEntry(input)); } }
8,850
48.446927
434
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/BvbFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.net.URL; import java.util.Collections; import java.util.List; import org.jabref.logic.importer.FetcherException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.jabref.logic.importer.fetcher.transformers.AbstractQueryTransformer.NO_EXPLICIT_FIELD; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @FetcherTest public class BvbFetcherTest { BvbFetcher fetcher = new BvbFetcher(); BibEntry bibEntryISBN0134685997; BibEntry bibEntryISBN9783960886402; @Test void testPerformTest() throws Exception { String searchquery = "effective java author:bloch"; List<BibEntry> result = fetcher.performSearch(searchquery); assertTrue(result.size() > 0); // System.out.println("Query:\n"); // System.out.println(fetcher.getURLForQuery(new StandardSyntaxParser().parse(searchquery, NO_EXPLICIT_FIELD))); // System.out.println("Test result:\n"); // result.forEach(entry -> System.out.println(entry.toString())); } @BeforeEach public void setUp() { fetcher = new BvbFetcher(); bibEntryISBN9783960886402 = new BibEntry(StandardEntryType.Misc) .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.YEAR, "2018") .withField(StandardField.SUBTITLE, "best practices für die Java-Plattform") .withField(StandardField.AUTHOR, "Bloch, Joshua") .withField(StandardField.TITLEADDON, "Joshua Bloch") .withField(StandardField.EDITION, "3. Auflage, Übersetzung der englischsprachigen 3. Originalausgabe 2018") .withField(StandardField.FILE, "ParsedFileField{description='', link='http://search.ebscohost.com/login.aspx?direct=true&scope=site&db=nlebk&db=nlabk&AN=1906353', fileType='PDF'}") .withField(StandardField.ISBN, "9783960886402") .withField(StandardField.KEYWORDS, "Klassen, Interfaces, Generics, Enums, Annotationen, Lambdas, Streams, Module, parallel, Parallele Programmierung, Serialisierung, funktional, funktionale Programmierung, Java EE, Jakarta EE") .withField(StandardField.LOCATION, "Heidelberg") .withField(StandardField.PUBLISHER, "{dpunkt.verlag} and {Dpunkt. Verlag (Heidelberg)}"); bibEntryISBN0134685997 = new BibEntry(StandardEntryType.Misc) .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.YEAR, "2018") .withField(StandardField.AUTHOR, "Bloch, Joshua") .withField(StandardField.TITLEADDON, "Joshua Bloch") .withField(StandardField.EDITION, "Third edition") .withField(StandardField.ISBN, "0134685997") .withField(StandardField.LOCATION, "Boston") .withField(StandardField.PUBLISHER, "{Addison-Wesley}"); } @Test public void testGetName() { assertEquals("Bibliotheksverbund Bayern (Experimental)", fetcher.getName()); } @Test public void simpleSearchQueryURLCorrect() throws Exception { String query = "java jdk"; QueryNode luceneQuery = new StandardSyntaxParser().parse(query, NO_EXPLICIT_FIELD); URL url = fetcher.getURLForQuery(luceneQuery); assertEquals("http://bvbr.bib-bvb.de:5661/bvb01sru?version=1.1&recordSchema=marcxml&operation=searchRetrieve&query=java+jdk&maximumRecords=30", url.toString()); } @Test public void complexSearchQueryURLCorrect() throws Exception { String query = "title:jdk"; QueryNode luceneQuery = new StandardSyntaxParser().parse(query, NO_EXPLICIT_FIELD); URL url = fetcher.getURLForQuery(luceneQuery); assertEquals("http://bvbr.bib-bvb.de:5661/bvb01sru?version=1.1&recordSchema=marcxml&operation=searchRetrieve&query=jdk&maximumRecords=30", url.toString()); } @Test public void testPerformSearchMatchingMultipleEntries() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch("effective java bloch"); assertEquals(bibEntryISBN9783960886402, searchResult.get(0)); assertEquals(bibEntryISBN0134685997, searchResult.get(1)); } @Test public void testPerformSearchEmpty() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch(""); assertEquals(Collections.emptyList(), searchResult); } }
4,929
46.864078
243
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/CiteSeerTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @FetcherTest class CiteSeerTest { private CiteSeer fetcher = new CiteSeer(); @Test void searchByQueryFindsEntryRigorousDerivation() throws Exception { String title = "RIGOROUS DERIVATION FROM LANDAU-DE GENNES THEORY TO ERICKSEN-LESLIE THEORY"; BibEntry expected = new BibEntry(StandardEntryType.Misc) .withField(StandardField.DOI, "68b3fde1aa6354a34061f8811e2050e1b512af26") .withField(StandardField.AUTHOR, "Wang, Wei and Zhang, Pingwen and Zhang, Zhifei") .withField(StandardField.TITLE, title) .withField(StandardField.ABSTRACT, "ar") .withField(StandardField.YEAR, "0") .withField(StandardField.URL, "http://arxiv.org/pdf/1307.0986.pdf"); List<BibEntry> fetchedEntries = fetcher.performSearch("title:\"Rigorous Derivation from Landau-de Gennes Theory to Ericksen-leslie Theory\" AND pageSize:1"); assertEquals(Collections.singletonList(expected), fetchedEntries); } @Test void searchByQueryFindsEntryCopingTheoryAndResearch() throws Exception { BibEntry expected = new BibEntry(StandardEntryType.Misc) .withField(StandardField.DOI, "c16e0888b17cb2c689e5dfa4e2be4fdffb23869e") .withField(StandardField.AUTHOR, "Lazarus, Richard S.") .withField(StandardField.TITLE, "Coping theory and research: Past, present, and future") .withField(StandardField.ABSTRACT, "In this essay in honor of Donald Oken, I emphasize coping as a key concept for theory and research on adaptation and health. My focus will be the contrasts between two approaches to coping, one that emphasizes") .withField(StandardField.YEAR, "1993") .withField(StandardField.VENUE, "Psychosomatic Medicine") .withField(StandardField.URL, "http://intl.psychosomaticmedicine.org/content/55/3/234.full.pdf"); List<BibEntry> fetchedEntries = fetcher.performSearch("title:\"Coping Theory and Research: Past Present and Future\" AND pageSize:1"); assertEquals(Collections.singletonList(expected), fetchedEntries); } /* * CiteSeer seems to only apply year ranges effectively when we search for entries * with associated pdfs, year values do not accurately reflect realistic values * */ @Disabled @Test void searchWithSortingByYear() throws FetcherException { Optional<String> expected = Optional.of("1552"); List<BibEntry> fetchedEntries = fetcher.performSearch("title:Theory AND year:1552 AND sortBy:Year"); for (BibEntry actual: fetchedEntries) { if (actual.hasField(StandardField.YEAR)) { assertEquals(expected, actual.getField(StandardField.YEAR)); } } } @Test void searchWithSortingByYearAndYearRange() throws FetcherException { List<BibEntry> fetchedEntries = fetcher.performSearch("title:Theory AND year-range:2002-2012 AND sortBy:Year"); Iterator<BibEntry> fetchedEntriesIter = fetchedEntries.iterator(); BibEntry recentEntry = fetchedEntriesIter.next(); while (fetchedEntriesIter.hasNext()) { BibEntry laterEntry = fetchedEntriesIter.next(); if (recentEntry.hasField(StandardField.YEAR) && laterEntry.hasField(StandardField.YEAR)) { Integer recentYear = Integer.parseInt(recentEntry.getField(StandardField.YEAR).orElse("0")); Integer laterYear = Integer.parseInt(laterEntry.getField(StandardField.YEAR).orElse("0")); assertFalse(recentYear < laterYear); } recentEntry = laterEntry; } } @Test void findByIdAsDOI() throws FetcherException, IOException { BibEntry entry = new BibEntry(StandardEntryType.Misc) .withField(StandardField.DOI, "c16e0888b17cb2c689e5dfa4e2be4fdffb23869e"); Optional<URL> expected = Optional.of(new URL("https://citeseerx.ist.psu.edu/document?repid=rep1&type=pdf&doi=c16e0888b17cb2c689e5dfa4e2be4fdffb23869e")); assertEquals(expected, fetcher.findFullText(entry)); } @Test void findBySourceURL() throws FetcherException, IOException { BibEntry entry = new BibEntry(StandardEntryType.Misc) .withField(StandardField.DOI, "") .withField(StandardField.URL, "http://intl.psychosomaticmedicine.org/content/55/3/234.full.pdf"); Optional<URL> expected = Optional.of(new URL("http://intl.psychosomaticmedicine.org/content/55/3/234.full.pdf")); assertEquals(expected, fetcher.findFullText(entry)); } @Test void notFoundByIdOrURL() throws FetcherException, IOException { assertEquals(Optional.empty(), fetcher.findFullText(new BibEntry())); } }
5,461
48.207207
263
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/CollectionOfComputerScienceBibliographiesFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fetcher.transformers.AbstractQueryTransformer; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.apache.lucene.queryparser.flexible.core.QueryNodeParseException; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; 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; @FetcherTest class CollectionOfComputerScienceBibliographiesFetcherTest { private CollectionOfComputerScienceBibliographiesFetcher fetcher; @BeforeEach public void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); fetcher = new CollectionOfComputerScienceBibliographiesFetcher(importFormatPreferences); } @Test public void getNameReturnsCorrectName() { assertEquals("Collection of Computer Science Bibliographies", fetcher.getName()); } @Test public void getUrlForQueryReturnsCorrectUrl() throws MalformedURLException, URISyntaxException, FetcherException, QueryNodeParseException { String query = "java jdk"; URL url = fetcher.getURLForQuery(new StandardSyntaxParser().parse(query, AbstractQueryTransformer.NO_EXPLICIT_FIELD)); assertEquals("http://liinwww.ira.uka.de/bibliography/rss?query=java+jdk&sort=score", url.toString()); } @Test public void performSearchReturnsMatchingMultipleEntries() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch("jabref"); BibEntry secondBibEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("oai:DiVA.org:lnu-68408") .withField(StandardField.ISBN, "978-1-4503-5217-8") .withField(StandardField.DOI, "10.1145/3129790.3129810") .withField(new UnknownField("ISI"), "000505046100032") .withField(new UnknownField("Scopus"), "2-s2.0-85037741580") .withField(new UnknownField("subject"), "Software Architecture; Code Churn; Open Source; Architecrual Erosion; Technical Debt; Software Engineering; Programvaruteknik") .withField(new UnknownField("relation"), "ACM International Conference Proceeding Series; ECSA '17~Proceedings of the 11th European Conference on Software Architecture : Companion Proceedings, p. 152-158") .withField(StandardField.ABSTRACT, "The open source application JabRef has existed since" + " 2003. In 2015, the developers decided to make an" + " architectural refactoring as continued development was" + " deemed too demanding. The developers also introduced" + " Static Architecture Conformance Checking (SACC) to" + " prevent violations to the intended architecture." + " Measurements mined from source code repositories such" + " as code churn and code ownership has been linked to" + " several problems, for example fault proneness, security" + " vulnerabilities, code smells, and degraded" + " maintainability. The root cause of such problems can be" + " architectural. To determine the impact of the" + " refactoring of JabRef, we measure the code churn and" + " code ownership before and after the refactoring and" + " find that large files with violations had a" + " significantly higher code churn than large files" + " without violations before the refactoring. After the" + " refactoring, the files that had violations show a more" + " normal code churn. We find no such effect on code" + " ownership. We conclude that files that contain" + " violations detectable by SACC methods are connected to" + " higher than normal code churn.") .withField(StandardField.TYPE, "info:eu-repo/semantics/conferenceObject") .withField(new UnknownField("description"), "Information and Software Qualtiy") .withField(StandardField.PAGES, "152--158") .withField(new UnknownField("bibsource"), "OAI-PMH server at www.diva-portal.org") .withField(new UnknownField("rights"), "info:eu-repo/semantics/openAccess") .withField(StandardField.URL, "http://urn.kb.se/resolve?urn=urn:nbn:se:lnu:diva-68408") .withField(new UnknownField("oai"), "oai:DiVA.org:lnu-68408") .withField(StandardField.TITLE, "The relationship of code churn and architectural violations in the open source software JabRef") .withField(StandardField.PUBLISHER, "Linn{\\'e}universitetet, Institutionen f{\\\"o}r datavetenskap (DV); Linn{\\'e}universitetet, Institutionen f{\\\"o}r datavetenskap (DV); Linn{\\'e}universitetet, Institutionen f{\\\"o}r datavetenskap (DV); New York, NY, USA") .withField(StandardField.LANGUAGE, "eng") .withField(StandardField.AUTHOR, "Tobias Olsson and Morgan Ericsson and Anna Wingkvist") .withField(StandardField.YEAR, "2017"); // Checking a subset, because the query "jabref" is generic and returns a changing result set assertEquals(Set.of(secondBibEntry), searchResult.stream().filter(bibEntry -> { String citeKey = bibEntry.getCitationKey().get(); return citeKey.equals(secondBibEntry.getCitationKey().get()); }).collect(Collectors.toSet())); } @Test public void performSearchReturnsEmptyListForEmptySearch() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch(""); assertEquals(Collections.emptyList(), searchResult); } }
6,833
59.477876
279
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/CollectionOfComputerScienceBibliographiesParserTest.java
package org.jabref.logic.importer.fetcher; import java.io.InputStream; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.jabref.logic.bibtex.BibEntryAssert; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Disabled; 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; import static org.mockito.Mockito.when; @FetcherTest public class CollectionOfComputerScienceBibliographiesParserTest { @Test public void parseEntriesReturnsEmptyListIfXmlHasNoResults() throws Exception { parseXmlAndCheckResults("collection_of_computer_science_bibliographies_empty_result.xml", Collections.emptyList()); } @Disabled("Parse/fetcher remote side does not return anything valid for the link") @Test public void parseEntriesReturnsOneBibEntryInListIfXmlHasSingleResult() throws Exception { parseXmlAndCheckResults("collection_of_computer_science_bibliographies_single_result.xml", Collections.singletonList("collection_of_computer_science_bibliographies_single_result.bib")); } @Test public void parseEntriesReturnsMultipleBibEntriesInListIfXmlHasMultipleResults() throws Exception { parseXmlAndCheckResults("collection_of_computer_science_bibliographies_multiple_results.xml", Arrays.asList("collection_of_computer_science_bibliographies_multiple_results_first_result.bib", "collection_of_computer_science_bibliographies_multiple_results_second_result.bib")); } private void parseXmlAndCheckResults(String xmlName, List<String> resourceNames) throws Exception { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); InputStream is = CollectionOfComputerScienceBibliographiesParserTest.class.getResourceAsStream(xmlName); CollectionOfComputerScienceBibliographiesParser parser = new CollectionOfComputerScienceBibliographiesParser(importFormatPreferences); List<BibEntry> entries = parser.parseEntries(is); assertEquals(resourceNames.size(), entries.size()); assertNotNull(entries); for (int i = 0; i < resourceNames.size(); i++) { BibEntryAssert.assertEquals(CollectionOfComputerScienceBibliographiesParserTest.class, resourceNames.get(i), entries.get(i)); } } }
2,702
49.055556
284
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/CompositeIdFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.importer.CompositeIdFetcher; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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 org.junit.jupiter.params.provider.ValueSource; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests the CompositeIdFetcher, for which Fetchers implementing the * IdBasedFetcher interface are a prerequisite. Excluding TitleFetcher. */ @FetcherTest class CompositeIdFetcherTest { private CompositeIdFetcher compositeIdFetcher; public static Stream<Arguments> performSearchByIdReturnsCorrectEntryForIdentifier() { return Stream.of( Arguments.arguments( "performSearchByIdReturnsCorrectEntryForArXivId", new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Cunningham, Emily C. and Sanderson, Robyn E. and Johnston, Kathryn V. and Panithanpaisal, Nondh and Ness, Melissa K. and Wetzel, Andrew and Loebman, Sarah R. and Escala, Ivanna and Horta, Danny and Faucher-Giguère, Claude-André") .withField(StandardField.TITLE, "Reading the CARDs: the Imprint of Accretion History in the Chemical Abundances of the Milky Way's Stellar Halo") .withField(StandardField.DATE, "2021-10-06") .withField(StandardField.YEAR, "2021") .withField(StandardField.MONTH, "aug") .withField(StandardField.NUMBER, "2") .withField(StandardField.VOLUME, "934") .withField(StandardField.PUBLISHER, "American Astronomical Society") .withField(StandardField.JOURNAL, "The Astrophysical Journal") .withField(StandardField.PAGES, "172") .withField(StandardField.ABSTRACT, "In the era of large-scale spectroscopic surveys in the Local Group (LG), we can explore using chemical abundances of halo stars to study the star formation and chemical enrichment histories of the dwarf galaxy progenitors of the Milky Way (MW) and M31 stellar halos. In this paper, we investigate using the Chemical Abundance Ratio Distributions (CARDs) of seven stellar halos from the Latte suite of FIRE-2 simulations. We attempt to infer galaxies' assembly histories by modelling the CARDs of the stellar halos of the Latte galaxies as a linear combination of template CARDs from disrupted dwarfs, with different stellar masses $M_{\\star}$ and quenching times $t_{100}$. We present a method for constructing these templates using present-day dwarf galaxies. For four of the seven Latte halos studied in this work, we recover the mass spectrum of accreted dwarfs to a precision of $<10\\%$. For the fraction of mass accreted as a function of $t_{100}$, we find residuals of $20-30\\%$ for five of the seven simulations. We discuss the failure modes of this method, which arise from the diversity of star formation and chemical enrichment histories dwarf galaxies can take. These failure cases can be robustly identified by the high model residuals. Though the CARDs modeling method does not successfully infer the assembly histories in these cases, the CARDs of these disrupted dwarfs contain signatures of their unusual formation histories. Our results are promising for using CARDs to learn more about the histories of the progenitors of the MW and M31 stellar halos.") .withField(StandardField.DOI, "10.3847/1538-4357/ac78ea") .withField(StandardField.EPRINT, "2110.02957") .withField(StandardField.DOI, "10.3847/1538-4357/ac78ea") .withField(StandardField.FILE, ":http\\://arxiv.org/pdf/2110.02957v1:PDF") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.EPRINTCLASS, "astro-ph.GA") .withField(StandardField.KEYWORDS, "Astrophysics of Galaxies (astro-ph.GA), FOS: Physical sciences") .withField(InternalField.KEY_FIELD, "Cunningham_2022") .withField(new UnknownField("copyright"), "Creative Commons Attribution 4.0 International"), "arXiv:2110.02957" ), /* disabled, because Iacr does not work Arguments.arguments( "performSearchByIdReturnsCorrectEntryForIacrEprintId", new BibEntry(StandardEntryType.Misc) .withField(StandardField.ABSTRACT, "The decentralized cryptocurrency Bitcoin has experienced great success but also encountered many challenges. One of the challenges has been the long confirmation time. Another challenge is the lack of incentives at certain steps of the protocol, raising concerns for transaction withholding, selfish mining, etc. To address these challenges, we propose Solida, a decentralized blockchain protocol based on reconfigurable Byzantine consensus augmented by proof-of-work. Solida improves on Bitcoin in confirmation time, and provides safety and liveness assuming the adversary control less than (roughly) one-third of the total mining power.\n") .withField(StandardField.AUTHOR, "Ittai Abraham and Dahlia Malkhi and Kartik Nayak and Ling Ren and Alexander Spiegelman") .withField(StandardField.DATE, "2017-11-18") .withField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Report 2017/1118") .withField(StandardField.NOTE, "\\url{https://ia.cr/2017/1118}") .withField(StandardField.TITLE, "Solida: A Blockchain Protocol Based on Reconfigurable Byzantine Consensus") .withField(StandardField.URL, "https://eprint.iacr.org/2017/1118/20171124:064527") .withField(StandardField.VERSION, "20171124:064527") .withField(StandardField.YEAR, "2017") .withCitationKey("cryptoeprint:2017:1118"), "2017/1118" ), */ Arguments.arguments( "performSearchByIdReturnsCorrectEntryForIsbnId", new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.PUBLISHER, "Addison-Wesley Professional") .withField(StandardField.YEAR, "2017") .withField(StandardField.AUTHOR, "Bloch, Joshua") .withField(StandardField.PAGES, "416") .withField(StandardField.ISBN, "9780134685991"), "9780134685991" ), Arguments.arguments( "performSearchByIdReturnsCorrectEntryForDoiId", new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Java{\\textregistered} For Dummies{\\textregistered}") .withField(StandardField.PUBLISHER, "Wiley") .withField(StandardField.YEAR, "2011") .withField(StandardField.AUTHOR, "Barry Burd") .withField(StandardField.MONTH, "jul") .withField(StandardField.DOI, "10.1002/9781118257517") .withCitationKey("Burd_2011"), "10.1002/9781118257517" ) ); } @BeforeEach void setUp() throws Exception { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); // Needed for ArXiv Fetcher keyword processing when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); compositeIdFetcher = new CompositeIdFetcher(importFormatPreferences); } @ParameterizedTest @ValueSource(strings = "arZiv:2110.02957") void performSearchByIdReturnsEmptyForInvalidId(String groundInvalidArXivId) throws FetcherException { assertEquals(Optional.empty(), compositeIdFetcher.performSearchById(groundInvalidArXivId)); } @ParameterizedTest(name = "{index} {0}") @MethodSource void performSearchByIdReturnsCorrectEntryForIdentifier(String name, BibEntry bibEntry, String identifier) throws FetcherException { assertEquals(Optional.of(bibEntry), compositeIdFetcher.performSearchById(identifier)); } }
9,682
76.464
1,642
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/CompositeSearchBasedFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import javafx.collections.FXCollections; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportCleanup; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest @DisabledOnCIServer("Produces to many requests on CI") public class CompositeSearchBasedFetcherTest { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeSearchBasedFetcherTest.class); @Test public void createCompositeFetcherWithNullSet() { Assertions.assertThrows(IllegalArgumentException.class, () -> new CompositeSearchBasedFetcher(null, 0)); } @Test public void performSearchWithoutFetchers() throws Exception { Set<SearchBasedFetcher> empty = new HashSet<>(); CompositeSearchBasedFetcher fetcher = new CompositeSearchBasedFetcher(empty, Integer.MAX_VALUE); List<BibEntry> result = fetcher.performSearch("quantum"); Assertions.assertEquals(result, Collections.emptyList()); } @ParameterizedTest(name = "Perform Search on empty query.") @MethodSource("performSearchParameters") public void performSearchOnEmptyQuery(Set<SearchBasedFetcher> fetchers) throws Exception { CompositeSearchBasedFetcher compositeFetcher = new CompositeSearchBasedFetcher(fetchers, Integer.MAX_VALUE); List<BibEntry> queryResult = compositeFetcher.performSearch(""); Assertions.assertEquals(queryResult, Collections.emptyList()); } @ParameterizedTest(name = "Perform search on query \"quantum\". Using the CompositeFetcher of the following " + "Fetchers: {arguments}") @MethodSource("performSearchParameters") public void performSearchOnNonEmptyQuery(Set<SearchBasedFetcher> fetchers) throws Exception { CompositeSearchBasedFetcher compositeFetcher = new CompositeSearchBasedFetcher(fetchers, Integer.MAX_VALUE); ImportCleanup cleanup = new ImportCleanup(BibDatabaseMode.BIBTEX); List<BibEntry> compositeResult = compositeFetcher.performSearch("quantum"); for (SearchBasedFetcher fetcher : fetchers) { try { List<BibEntry> fetcherResult = fetcher.performSearch("quantum"); fetcherResult.forEach(cleanup::doPostCleanup); Assertions.assertTrue(compositeResult.containsAll(fetcherResult)); } catch (FetcherException e) { /* We catch the Fetcher exception here, since the failing fetcher also fails in the CompositeFetcher * and just leads to no additional results in the returned list. Therefore, the test should not fail * due to the fetcher exception */ LOGGER.debug("Fetcher {} failed ", fetcher.getName(), e); } } } /** * This method provides other methods with different sized sets of search-based fetchers wrapped in arguments. * * @return A stream of Arguments wrapping set of fetchers. */ static Stream<Arguments> performSearchParameters() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); ImporterPreferences importerPreferences = mock(ImporterPreferences.class); when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); List<Set<SearchBasedFetcher>> fetcherParameters = new ArrayList<>(); List<SearchBasedFetcher> list = List.of( new ArXivFetcher(importFormatPreferences), new INSPIREFetcher(importFormatPreferences), new GvkFetcher(), new AstrophysicsDataSystem(importFormatPreferences, importerPreferences), new MathSciNet(importFormatPreferences), new ZbMATH(importFormatPreferences), new GoogleScholar(importFormatPreferences), new DBLPFetcher(importFormatPreferences), new SpringerFetcher(importerPreferences), new CrossRef(), new CiteSeer(), new DOAJFetcher(importFormatPreferences), new IEEE(importFormatPreferences, importerPreferences)); /* Disabled due to an issue regarding comparison: Title fields of the entries that otherwise are equivalent differ * due to different JAXBElements. */ // new MedlineFetcher() // Create different sized sets of fetchers to use in the composite fetcher. // Selected 1173 to have differencing sets for (int i = 1; i < Math.pow(2, list.size()); i += 1173) { Set<SearchBasedFetcher> fetchers = new HashSet<>(); // Only shift i at maximum to its MSB to the right for (int j = 0; Math.pow(2, j) <= i; j++) { // Add fetcher j to the list if the j-th bit of i is 1 if (((i >> j) % 2) == 1) { fetchers.add(list.get(j)); } } fetcherParameters.add(fetchers); } return fetcherParameters.stream().map(Arguments::of); } }
6,023
42.970803
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/CrossRefTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.Locale; import java.util.Optional; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; 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; import static org.junit.jupiter.api.Assertions.assertThrows; @FetcherTest public class CrossRefTest { private CrossRef fetcher; private BibEntry barrosEntry; @BeforeEach public void setUp() throws Exception { fetcher = new CrossRef(); barrosEntry = new BibEntry(); barrosEntry.setField(StandardField.TITLE, "Service Interaction Patterns"); barrosEntry.setField(StandardField.AUTHOR, "Alistair Barros and Marlon Dumas and Arthur H. M. ter Hofstede"); barrosEntry.setField(StandardField.YEAR, "2005"); barrosEntry.setField(StandardField.DOI, "10.1007/11538394_20"); barrosEntry.setField(StandardField.ISSN, "0302-9743"); barrosEntry.setField(StandardField.PAGES, "302-318"); } @Test public void findExactData() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Service Interaction Patterns"); entry.setField(StandardField.AUTHOR, "Barros, Alistair and Dumas, Marlon and Arthur H.M. ter Hofstede"); entry.setField(StandardField.YEAR, "2005"); assertEquals("10.1007/11538394_20", fetcher.findIdentifier(entry).get().getDOI().toLowerCase(Locale.ENGLISH)); } @Test public void findMissingAuthor() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Towards Application Portability in Platform as a Service"); entry.setField(StandardField.AUTHOR, "Stefan Kolb"); assertEquals("10.1109/sose.2014.26", fetcher.findIdentifier(entry).get().getDOI().toLowerCase(Locale.ENGLISH)); } @Test public void findTitleOnly() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Towards Application Portability in Platform as a Service"); assertEquals("10.1109/sose.2014.26", fetcher.findIdentifier(entry).get().getDOI().toLowerCase(Locale.ENGLISH)); } @Test public void notFindIncompleteTitle() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Towards Application Portability"); entry.setField(StandardField.AUTHOR, "Stefan Kolb and Guido Wirtz"); assertEquals(Optional.empty(), fetcher.findIdentifier(entry)); } @Test public void acceptTitleUnderThreshold() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Towards Application Portability in Platform as a Service----"); entry.setField(StandardField.AUTHOR, "Stefan Kolb and Guido Wirtz"); assertEquals("10.1109/sose.2014.26", fetcher.findIdentifier(entry).get().getDOI().toLowerCase(Locale.ENGLISH)); } @Test public void notAcceptTitleOverThreshold() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Towards Application Portability in Platform as a Service-----"); entry.setField(StandardField.AUTHOR, "Stefan Kolb and Guido Wirtz"); assertEquals(Optional.empty(), fetcher.findIdentifier(entry)); } @Test public void findWrongAuthor() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Towards Application Portability in Platform as a Service"); entry.setField(StandardField.AUTHOR, "Stefan Kolb and Simon Harrer"); assertEquals("10.1109/sose.2014.26", fetcher.findIdentifier(entry).get().getDOI().toLowerCase(Locale.ENGLISH)); } @Test public void findWithSubtitle() throws Exception { BibEntry entry = new BibEntry(); // CrossRef entry will only include { "title": "A break in the clouds", "subtitle": "towards a cloud definition" } entry.setField(StandardField.TITLE, "A break in the clouds: towards a cloud definition"); assertEquals("10.1145/1496091.1496100", fetcher.findIdentifier(entry).get().getDOI().toLowerCase(Locale.ENGLISH)); } @Test public void findByDOI() throws Exception { assertEquals(Optional.of(barrosEntry), fetcher.performSearchById("10.1007/11538394_20")); } @Test public void findByAuthors() throws Exception { assertEquals(Optional.of(barrosEntry), fetcher.performSearch("\"Barros, Alistair\" AND \"Dumas, Marlon\" AND \"Arthur H.M. ter Hofstede\"").stream().findFirst()); } @Test public void findByEntry() throws Exception { BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, "Service Interaction Patterns"); entry.setField(StandardField.AUTHOR, "Barros, Alistair and Dumas, Marlon and Arthur H.M. ter Hofstede"); entry.setField(StandardField.YEAR, "2005"); assertEquals(Optional.of(barrosEntry), fetcher.performSearch(entry).stream().findFirst()); } @Test public void performSearchByIdFindsPaperWithoutTitle() throws Exception { BibEntry entry = new BibEntry(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Dominik Wujastyk"); entry.setField(StandardField.DOI, "10.1023/a:1003473214310"); entry.setField(StandardField.ISSN, "0019-7246"); entry.setField(StandardField.PAGES, "172-176"); entry.setField(StandardField.VOLUME, "42"); entry.setField(StandardField.YEAR, "1999"); assertEquals(Optional.of(entry), fetcher.performSearchById("10.1023/a:1003473214310")); } @Test public void performSearchByEmptyId() throws Exception { assertEquals(Optional.empty(), fetcher.performSearchById("")); } @Test public void performSearchByEmptyQuery() throws Exception { assertEquals(Collections.emptyList(), fetcher.performSearch("")); } /** * reveal fetching error on crossref performSearchById */ @Test public void testPerformSearchValidReturnNothingDOI() throws FetcherException { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("10.1392/BC1.0")); } }
6,600
42.143791
170
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/DBLPFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest public class DBLPFetcherTest { private DBLPFetcher dblpFetcher; private BibEntry entry; @BeforeEach public void setUp() { dblpFetcher = new DBLPFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setCitationKey("DBLP:journals/stt/GeigerHL16"); entry.setField(StandardField.TITLE, "Process Engine Benchmarking with Betsy in the Context of {ISO/IEC} Quality Standards"); entry.setField(StandardField.AUTHOR, "Matthias Geiger and Simon Harrer and J{\\\"{o}}rg Lenhard"); entry.setField(StandardField.JOURNAL, "Softwaretechnik-Trends"); entry.setField(StandardField.VOLUME, "36"); entry.setField(StandardField.NUMBER, "2"); entry.setField(StandardField.YEAR, "2016"); entry.setField(StandardField.URL, "http://pi.informatik.uni-siegen.de/stt/36_2/03_Technische_Beitraege/ZEUS2016/beitrag_2.pdf"); entry.setField(new UnknownField("biburl"), "https://dblp.org/rec/journals/stt/GeigerHL16.bib"); entry.setField(new UnknownField("bibsource"), "dblp computer science bibliography, https://dblp.org"); } @Test public void findSingleEntry() throws FetcherException { // In Lucene curly brackets are used for range queries, therefore they have to be escaped using "". See https://lucene.apache.org/core/5_4_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html String query = "Process Engine Benchmarking with Betsy in the Context of \"{ISO/IEC}\" Quality Standards"; List<BibEntry> result = dblpFetcher.performSearch(query); assertEquals(Collections.singletonList(entry), result); } @Test public void findSingleEntryUsingComplexOperators() throws FetcherException { String query = "geiger harrer betsy$ softw.trends"; // -wirtz Negative operators do no longer work, see issue https://github.com/JabRef/jabref/issues/2890 List<BibEntry> result = dblpFetcher.performSearch(query); assertEquals(Collections.singletonList(entry), result); } @Test public void findNothing() throws Exception { assertEquals(Collections.emptyList(), dblpFetcher.performSearch("")); } }
3,003
42.536232
219
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/DOABFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.List; import java.util.stream.Stream; import org.jabref.logic.importer.FetcherException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest @DisabledOnCIServer("Disable on CI Server to not hit the API call limit") public class DOABFetcherTest { private final DOABFetcher fetcher = new DOABFetcher(); @Test public void testGetName() { assertEquals("DOAB", fetcher.getName()); } public static Stream<Arguments> testPerformSearch() { return Stream.of( Arguments.of( new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "David Pol") .withField(StandardField.TITLE, "I Open Fire") .withField(StandardField.DOI, "10.21983/P3.0086.1.00") .withField(StandardField.PAGES, "56") .withField(StandardField.DATE, "2014") .withField(StandardField.URL, "http://library.oapen.org/handle/20.500.12657/25535") .withField(StandardField.URI, "https://directory.doabooks.org/handle/20.500.12854/34739") .withField(StandardField.LANGUAGE, "English") .withField(StandardField.KEYWORDS, "poetry, love, warfare") .withField(StandardField.PUBLISHER, "punctum books"), "i open fire" ), Arguments.of( new BibEntry(StandardEntryType.Book) .withField(StandardField.ISBN, "9789085551201") .withField(StandardField.AUTHOR, "Ronald Snijder") .withField(StandardField.TITLE, "The deliverance of open access books") .withField(StandardField.SUBTITLE, "Examining usage and dissemination") .withField(StandardField.DOI, "10.26530/OAPEN_1004809") .withField(StandardField.PAGES, "234") .withField(StandardField.DATE, "2019") .withField(StandardField.URL, "http://library.oapen.org/handle/20.500.12657/25287") .withField(StandardField.URI, "https://directory.doabooks.org/handle/20.500.12854/26303") .withField(StandardField.LANGUAGE, "English") .withField(StandardField.KEYWORDS, "Open Access, Monographs, OAPEN Library, " + "Directory of Open Access Books") .withField(StandardField.PUBLISHER, "Amsterdam University Press"), "the deliverance of open access books" ), Arguments.of( new BibEntry(StandardEntryType.Book) .withField(StandardField.EDITOR, "Andrew Perrin and Loren T. Stuckenbruck") .withField(StandardField.TITLE, "Four Kingdom Motifs before and beyond the Book of Daniel") .withField(StandardField.DOI, "10.1163/9789004443280") .withField(StandardField.PAGES, "354") .withField(StandardField.DATE, "2020") .withField(StandardField.URL, "https://library.oapen.org/handle/20.500.12657/48312") .withField(StandardField.URI, "https://directory.doabooks.org/handle/20.500.12854/68086") .withField(StandardField.LANGUAGE, "English") .withField(StandardField.KEYWORDS, "Religion") .withField(StandardField.PUBLISHER, "Brill"), "Four Kingdom Motifs before and beyond the Book of Daniel" ), Arguments.of( new BibEntry(StandardEntryType.Book) .withField(StandardField.EDITOR, "Felipe Gonzalez Toro and Antonios Tsourdos") .withField(StandardField.TITLE, "UAV Sensors for Environmental Monitoring") .withField(StandardField.DOI, "10.3390/books978-3-03842-754-4") .withField(StandardField.PAGES, "670") .withField(StandardField.DATE, "2018") .withField(StandardField.URI, "https://directory.doabooks.org/handle/20.500.12854/39793") .withField(StandardField.LANGUAGE, "English") .withField(StandardField.KEYWORDS, "UAV sensors, Environmental Monitoring, drones, unmanned aerial vehicles") .withField(StandardField.PUBLISHER, "MDPI - Multidisciplinary Digital Publishing Institute"), "UAV Sensors for Environmental Monitoring" ), Arguments.of( new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Carl Marnewick and Wikus Erasmus and Joseph Nazeer") .withField(StandardField.TITLE, "The symbiosis between information system project complexity and information system project success") .withField(StandardField.DOI, "10.4102/aosis.2017.itpsc45") .withField(StandardField.PAGES, "184") .withField(StandardField.DATE, "2017") .withField(StandardField.URL, "http://library.oapen.org/handle/20.500.12657/30652") .withField(StandardField.URI, "https://directory.doabooks.org/handle/20.500.12854/38792") .withField(StandardField.LANGUAGE, "English") .withField(StandardField.KEYWORDS, "agile, structural equation modelling, information technology, success, models, strategic alignment, complexity, waterfall, project management, quantitative, Agile software development, Change management, Deliverable, Exploratory factor analysis, South Africa") .withField(StandardField.PUBLISHER, "AOSIS"), "The symbiosis between information system project complexity and information system project success" ) ); } @ParameterizedTest @MethodSource public void testPerformSearch(BibEntry expected, String query) throws FetcherException { List<BibEntry> entries = fetcher.performSearch(query); // We must not contain abstracts in our code base; thus we remove the abstracts from the fetched results entries.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); assertEquals(List.of(expected), entries); } }
7,580
64.353448
328
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/DOAJFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import kong.unirest.json.JSONObject; import org.apache.http.client.utils.URIBuilder; 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; @FetcherTest class DOAJFetcherTest { DOAJFetcher fetcher; @BeforeEach void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); fetcher = new DOAJFetcher(importFormatPreferences); } @Test void searchByQueryFindsEntry() throws Exception { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Nísea de A. Corrêa and Maria P. Foss and Paula R. B. Diniz") .withField(StandardField.DOI, "10.11606/issn.2176-7262.v49i6p533-548") .withField(StandardField.ISSN, "2176-7262") .withField(StandardField.JOURNAL, "Medicina") .withField(StandardField.PUBLISHER, "Universidade de São Paulo") .withField(StandardField.TITLE, "Structural and functional changes related to memory deficit in non-demential elderly individuals") .withField(StandardField.URL, "http://www.revistas.usp.br/rmrp/article/view/127443") .withField(StandardField.VOLUME, "49") .withField(StandardField.NUMBER, "6") .withField(StandardField.YEAR, "2016") .withField(StandardField.MONTH, "December") .withField(StandardField.KEYWORDS, "Central Nervous System. Structural Changes. Functional Changes. Memory deficits. Aging. Normal Aging. Magnetic Resonance Imaging") .withField(StandardField.ABSTRACT, "Objective: Based on Magnetic Resonance Imaging (MRI), verify the structural and functional changes related to memory deficits in non-demented elderly individuals in comparison with young adults. Methodology: Proceeded a systematic review based on Preferred Reporting Items for Systematic Review and Meta-Analysis (PRISMA) fluxogram. The search was done on PubMed, Scopus and EBSCO databases using JabRef 2.10, and Web of Science. It was included in the analysis quasi-experimental, cross-sectional, cohort and case-control studies published between 2005 and 2014 in national and international indexed periodicals that had as sample: non-demented individuals older than 60 years old, who were submitted to MRI investigation of their for any brain structural and functional changes associated with memory deficits, identified in neuropsychologicals tests. Results: About the imaging technique, we reviewed studies that used structural MRIs (two articles), functional MRIs (six articles), both techniques (four articles). In the 12 studies, 38 distinct neuropsychological tests were used, an average of five different tests for each study (variation of 1-12). The most used tests were WAIS Digit Span Backwards (seven articles), Trail Making Test A and B (four articles) and Wechsler Memory Scale (four articles). Conclusion: The review showed that in normal aging the parahippocampal white substance, the hippocampus volume and entorhinal cortex slightly shrink, causing verbal memory reduction, possibly due to fiber demyelination; reduced connections between temporal and frontal lobes contributing to an impairement of episodic, working memory and verbal fluency; reduction suppression of irrelevant information, affecting the register of information; changes on frontal and parietal areas, compromising recognition memory; modifications in activity and connectivity of the default mode network; reorganization of cognitive functions and also a slower response, probably due to reduction of pre-frontal cortex activation"); List<BibEntry> fetchedEntries = fetcher.performSearch("JabRef MRI"); assertEquals(Collections.singletonList(expected), fetchedEntries); } @Test void testBibJSONConverter() { String jsonString = "{\"title\":\"Design of Finite Word Length Linear-Phase FIR Filters in the Logarithmic Number System Domain\",\"journal\":{\"publisher\":\"Hindawi Publishing Corporation\",\"language\":[\"English\"],\"title\":\"VLSI Design\",\"country\":\"US\",\"volume\":\"2014\"},\"author\":[{\"name\":\"Syed Asad Alam\"},{\"name\":\"Oscar Gustafsson\"}],\"link\":[{\"url\":\"http://dx.doi.org/10.1155/2014/217495\",\"type\":\"fulltext\"}],\"year\":\"2014\",\"identifier\":[{\"type\":\"pissn\",\"id\":\"1065-514X\"},{\"type\":\"eissn\",\"id\":\"1563-5171\"},{\"type\":\"doi\",\"id\":\"10.1155/2014/217495\"}],\"created_date\":\"2014-05-09T19:38:31Z\"}"; JSONObject jsonObject = new JSONObject(jsonString); BibEntry bibEntry = DOAJFetcher.parseBibJSONtoBibtex(jsonObject, ','); assertEquals(StandardEntryType.Article, bibEntry.getType()); assertEquals(Optional.of("VLSI Design"), bibEntry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("10.1155/2014/217495"), bibEntry.getField(StandardField.DOI)); assertEquals(Optional.of("Syed Asad Alam and Oscar Gustafsson"), bibEntry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Design of Finite Word Length Linear-Phase FIR Filters in the Logarithmic Number System Domain"), bibEntry.getField(StandardField.TITLE)); assertEquals(Optional.of("2014"), bibEntry.getField(StandardField.YEAR)); } @Test public void searchByEmptyQuery() throws Exception { assertEquals(Collections.emptyList(), fetcher.performSearch("")); } @Test void appendSingleWord() throws Exception { URIBuilder builder = new URIBuilder("http://example.com/test"); DOAJFetcher.addPath(builder, "/example"); assertEquals("http://example.com/test/example", builder.build().toASCIIString()); } @Test void appendSingleWordWithSlash() throws Exception { URIBuilder builder = new URIBuilder("http://example.com/test"); DOAJFetcher.addPath(builder, "/example"); assertEquals("http://example.com/test/example", builder.build().toASCIIString()); } @Test void appendSlash() throws Exception { URIBuilder builder = new URIBuilder("http://example.com/test"); DOAJFetcher.addPath(builder, "/"); assertEquals("http://example.com/test", builder.build().toASCIIString()); } @Test void appendTwoWords() throws Exception { URIBuilder builder = new URIBuilder("http://example.com/test"); DOAJFetcher.addPath(builder, "example two"); assertEquals("http://example.com/test/example%20two", builder.build().toASCIIString()); } }
7,154
68.466019
2,068
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @FetcherTest public class DiVATest { private DiVA fetcher; @BeforeEach public void setUp() { fetcher = new DiVA(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test public void testGetName() { assertEquals("DiVA", fetcher.getName()); } @Test public void testPerformSearchById() throws Exception { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setCitationKey("Gustafsson260746"); entry.setField(StandardField.AUTHOR, "Gustafsson, Oscar"); entry.setField(StandardField.INSTITUTION, "Linköping University, The Institute of Technology"); entry.setField(StandardField.JOURNAL, "IEEE transactions on circuits and systems. 2, Analog and digital signal processing (Print)"); entry.setField(StandardField.NUMBER, "11"); entry.setField(StandardField.PAGES, "974--978"); entry.setField(StandardField.TITLE, "Lower bounds for constant multiplication problems"); entry.setField(StandardField.VOLUME, "54"); entry.setField(StandardField.YEAR, "2007"); entry.setField(StandardField.ABSTRACT, "Lower bounds for problems related to realizing multiplication by constants with shifts, adders, and subtracters are presented. These lower bounds are straightforwardly calculated and have applications in proving the optimality of solutions obtained by heuristics. "); entry.setField(StandardField.DOI, "10.1109/TCSII.2007.903212"); assertEquals(Optional.of(entry), fetcher.performSearchById("diva2:260746")); } @Test public void testValidIdentifier() { assertTrue(fetcher.isValidId("diva2:260746")); } @Test public void testInvalidIdentifier() { assertFalse(fetcher.isValidId("banana")); } @Test public void testEmptyId() throws Exception { assertEquals(Optional.empty(), fetcher.performSearchById("")); } }
2,647
36.828571
315
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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.assertThrows; import static org.mockito.Mockito.mock; @FetcherTest public class DoiFetcherTest { private final DoiFetcher fetcher = new DoiFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); private final BibEntry bibEntryBurd2011 = new BibEntry(StandardEntryType.Book) .withCitationKey("Burd_2011") .withField(StandardField.TITLE, "Java{\\textregistered} For Dummies{\\textregistered}") .withField(StandardField.PUBLISHER, "Wiley") .withField(StandardField.YEAR, "2011") .withField(StandardField.AUTHOR, "Barry Burd") .withField(StandardField.MONTH, "jul") .withField(StandardField.DOI, "10.1002/9781118257517"); private final BibEntry bibEntryDecker2007 = new BibEntry(StandardEntryType.InProceedings) .withCitationKey("Decker_2007") .withField(StandardField.AUTHOR, "Gero Decker and Oliver Kopp and Frank Leymann and Mathias Weske") .withField(StandardField.BOOKTITLE, "{IEEE} International Conference on Web Services ({ICWS} 2007)") .withField(StandardField.MONTH, "jul") .withField(StandardField.PUBLISHER, "{IEEE}") .withField(StandardField.TITLE, "{BPEL}4Chor: Extending {BPEL} for Modeling Choreographies") .withField(StandardField.YEAR, "2007") .withField(StandardField.DOI, "10.1109/icws.2007.59"); private final BibEntry bibEntryIannarelli2019 = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "" + "Iannarelli Riccardo and " + "Novello Anna and " + "Stricker Damien and " + "Cisternino Marco and " + "Gallizio Federico and " + "Telib Haysam and " + "Meyer Thierry ") .withField(StandardField.PUBLISHER, "AIDIC: Italian Association of Chemical Engineering") .withField(StandardField.TITLE, "Safety in research institutions: how to better communicate the risks using numerical simulations") .withField(StandardField.YEAR, "2019") .withField(StandardField.DOI, "10.3303/CET1977146") .withField(StandardField.JOURNAL, "Chemical Engineering Transactions") .withField(StandardField.PAGES, "871-876") .withField(StandardField.VOLUME, "77"); private final BibEntry bibEntryStenzel2020 = new BibEntry(StandardEntryType.Article) .withCitationKey("Stenzel_2020") .withField(StandardField.AUTHOR, "L. Stenzel and A. L. C. Hayward and U. Schollwöck and F. Heidrich-Meisner") .withField(StandardField.JOURNAL, "Physical Review A") .withField(StandardField.TITLE, "Topological phases in the Fermi-Hofstadter-Hubbard model on hybrid-space ladders") .withField(StandardField.YEAR, "2020") .withField(StandardField.MONTH, "aug") .withField(StandardField.VOLUME, "102") .withField(StandardField.DOI, "10.1103/physreva.102.023315") .withField(StandardField.PUBLISHER, "American Physical Society ({APS})") .withField(StandardField.PAGES, "023315") .withField(StandardField.NUMBER, "2"); @Test public void testGetName() { assertEquals("DOI", fetcher.getName()); } @Test public void testPerformSearchBurd2011() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.1002/9781118257517"); assertEquals(Optional.of(bibEntryBurd2011), fetchedEntry); } @Test public void testPerformSearchDecker2007() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.1109/ICWS.2007.59"); assertEquals(Optional.of(bibEntryDecker2007), fetchedEntry); } @Test public void testPerformSearchIannarelli2019() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.3303/CET1977146"); assertEquals(Optional.of(bibEntryIannarelli2019), fetchedEntry); } @Test public void testPerformSearchEmptyDOI() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("")); } @Test public void testPerformSearchInvalidDOI() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("10.1002/9781118257517F")); } @Test public void testPerformSearchInvalidDOIClientResultsinFetcherClientException() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("10.1002/9781118257517F")); } @Test public void testPerformSearchInvalidDOIClientResultsinFetcherClientException2() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("10.1002/9781517F")); } @Test public void testPerformSearchNonTrimmedDOI() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("http s://doi.org/ 10.1109 /ICWS .2007.59 "); assertEquals(Optional.of(bibEntryDecker2007), fetchedEntry); } @Test public void testAPSJournalCopiesArticleIdToPageField() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("10.1103/physreva.102.023315"); assertEquals(Optional.of(bibEntryStenzel2020), fetchedEntry); } }
6,055
47.063492
143
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/DoiResolutionTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Optional; import org.jabref.logic.preferences.DOIPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest class DoiResolutionTest { private DoiResolution finder; private BibEntry entry; @BeforeEach void setup() { DOIPreferences doiPreferences = mock(DOIPreferences.class); when(doiPreferences.isUseCustom()).thenReturn(false); finder = new DoiResolution(doiPreferences); entry = new BibEntry(); } @Test void linkWithPdfInTitleTag() throws IOException { entry.setField(StandardField.DOI, "10.1051/0004-6361/201527330"); assertEquals( Optional.of(new URL("https://www.aanda.org/articles/aa/pdf/2016/01/aa27330-15.pdf")), finder.findFullText(entry) ); } @Disabled("Cannot fetch due to Cloudflare protection") @Test void linkWithPdfStringLeadsToFulltext() throws IOException { entry.setField(StandardField.DOI, "10.1002/acr2.11101"); assertEquals(Optional.of(new URL("https://onlinelibrary.wiley.com/doi/pdf/10.1002/acr2.11101")), finder.findFullText(entry)); } @Test void citationMetaTagLeadsToFulltext() throws IOException { entry.setField(StandardField.DOI, "10.1007/978-3-319-89963-3_28"); assertEquals(Optional.of(new URL("https://link.springer.com/content/pdf/10.1007/978-3-319-89963-3_28.pdf")), finder.findFullText(entry)); } @Test void notReturnAnythingWhenMultipleLinksAreFound() throws IOException { entry.setField(StandardField.DOI, "10.1109/JXCDC.2019.2911135"); assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void returnAnythingWhenBehindSpringerPayWall() throws IOException { // Springer returns an HTML page instead of an empty page, // even if the user does not have access // We cannot easily handle this case, because other publisher return the wrong media type. entry.setField(StandardField.DOI, "10.1007/978-3-319-62594-2_12"); assertEquals(Optional.of(new URL("https://link.springer.com/content/pdf/10.1007/978-3-319-62594-2_12.pdf")), finder.findFullText(entry)); } @Test void notFoundByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1186/unknown-doi"); assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void entityWithoutDoi() throws IOException { assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void trustLevel() { assertEquals(TrustLevel.SOURCE, finder.getTrustLevel()); } }
3,092
34.551724
145
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/FulltextFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import java.util.Set; import org.jabref.logic.importer.FulltextFetcher; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.WebFetchers; import org.jabref.model.entry.BibEntry; 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.assertThrows; import static org.mockito.Mockito.mock; class FulltextFetcherTest { @SuppressWarnings("unused") private static Set<FulltextFetcher> fetcherProvider() { return WebFetchers.getFullTextFetchers(mock(ImportFormatPreferences.class), mock(ImporterPreferences.class)); } @ParameterizedTest @MethodSource("fetcherProvider") void findFullTextRejectsNullParameter(FulltextFetcher fetcher) { assertThrows(NullPointerException.class, () -> fetcher.findFullText(null)); } @ParameterizedTest @MethodSource("fetcherProvider") void findFullTextWithEmptyEntryFindsNothing(FulltextFetcher fetcher) throws Exception { assertEquals(Optional.empty(), fetcher.findFullText(new BibEntry())); } }
1,317
33.684211
117
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/GoogleScholarTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.PagedSearchBasedFetcher; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest @DisabledOnCIServer("CI server is blocked by Google") class GoogleScholarTest implements SearchBasedFetcherCapabilityTest, PagedSearchFetcherTest { private GoogleScholar finder; private BibEntry entry; @BeforeEach void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); finder = new GoogleScholar(importFormatPreferences); entry = new BibEntry(); } @Test void linkFound() throws IOException, FetcherException { entry.setField(StandardField.TITLE, "Towards Application Portability in Platform as a Service"); assertEquals( Optional.of(new URL("https://www.uni-bamberg.de/fileadmin/uni/fakultaeten/wiai_lehrstuehle/praktische_informatik/Dateien/Publikationen/sose14-towards-application-portability-in-paas.pdf")), finder.findFullText(entry) ); } @Test void noLinkFound() throws IOException, FetcherException { entry.setField(StandardField.TITLE, "Curriculum programme of career-oriented java specialty guided by principles of software engineering"); assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void findSingleEntry() throws FetcherException { entry.setType(StandardEntryType.InProceedings); entry.setCitationKey("geiger2013detecting"); entry.setField(StandardField.TITLE, "Detecting Interoperability and Correctness Issues in BPMN 2.0 Process Models."); entry.setField(StandardField.AUTHOR, "Geiger, Matthias and Wirtz, Guido"); entry.setField(StandardField.BOOKTITLE, "ZEUS"); entry.setField(StandardField.YEAR, "2013"); entry.setField(StandardField.PAGES, "41--44"); List<BibEntry> foundEntries = finder.performSearch("Detecting Interoperability and Correctness Issues in BPMN 2.0 Process Models"); assertEquals(Collections.singletonList(entry), foundEntries); } @Test void findManyEntries() throws FetcherException { List<BibEntry> foundEntries = finder.performSearch("random test string"); assertEquals(20, foundEntries.size()); } @Override public SearchBasedFetcher getFetcher() { return finder; } @Override public PagedSearchBasedFetcher getPagedFetcher() { return finder; } @Override public List<String> getTestAuthors() { return List.of("Mittermeier", "Myers"); } @Override public String getTestJournal() { return "Nature"; } }
3,436
33.717172
205
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/GrobidCitationFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.util.GrobidService; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest public class GrobidCitationFetcherTest { static ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); static GrobidPreferences grobidPreferences = new GrobidPreferences( true, false, "http://grobid.jabref.org:8070"); static GrobidCitationFetcher grobidCitationFetcher = new GrobidCitationFetcher(grobidPreferences, importFormatPreferences); static String example1 = "Derwing, T. M., Rossiter, M. J., & Munro, M. J. (2002). Teaching native speakers to listen to foreign-accented speech. Journal of Multilingual and Multicultural Development, 23(4), 245-259."; static BibEntry example1AsBibEntry = new BibEntry(StandardEntryType.Article).withCitationKey("-1") .withField(StandardField.AUTHOR, "Derwing, Tracey and Rossiter, Marian and Munro, Murray") .withField(StandardField.TITLE, "Teaching Native Speakers to Listen to Foreign-accented Speech") .withField(StandardField.JOURNAL, "Journal of Multilingual and Multicultural Development") .withField(StandardField.DOI, "10.1080/01434630208666468") .withField(StandardField.DATE, "2002-09") .withField(StandardField.MONTH, "9") .withField(StandardField.YEAR, "2002") .withField(StandardField.PAGES, "245-259") .withField(StandardField.VOLUME, "23") .withField(StandardField.PUBLISHER, "Informa UK Limited") .withField(StandardField.NUMBER, "4"); static String example2 = "Thomas, H. K. (2004). Training strategies for improving listeners' comprehension of foreign-accented speech (Doctoral dissertation). University of Colorado, Boulder."; static BibEntry example2AsBibEntry = new BibEntry(BibEntry.DEFAULT_TYPE).withCitationKey("-1") .withField(StandardField.AUTHOR, "Thomas, H") .withField(StandardField.TITLE, "Training strategies for improving listeners' comprehension of foreign-accented speech (Doctoral dissertation)") .withField(StandardField.DATE, "2004") .withField(StandardField.YEAR, "2004") .withField(StandardField.ADDRESS, "Boulder"); static String example3 = "Turk, J., Graham, P., & Verhulst, F. (2007). Child and adolescent psychiatry : A developmental approach. Oxford, England: Oxford University Press."; static BibEntry example3AsBibEntry = new BibEntry(BibEntry.DEFAULT_TYPE).withCitationKey("-1") .withField(StandardField.AUTHOR, "Turk, Jeremy and Graham, Philip and Verhulst, Frank") .withField(StandardField.TITLE, "Child and Adolescent Psychiatry") .withField(StandardField.PUBLISHER, "Oxford University Press") .withField(StandardField.DATE, "2007-02") .withField(StandardField.YEAR, "2007") .withField(StandardField.MONTH, "2") .withField(StandardField.DOI, "10.1093/med/9780199216697.001.0001") .withField(StandardField.ADDRESS, "Oxford, England"); static String example4 = "Carr, I., & Kidner, R. (2003). Statutes and conventions on international trade law (4th ed.). London, England: Cavendish."; static BibEntry example4AsBibEntry = new BibEntry(StandardEntryType.InBook).withCitationKey("-1") .withField(StandardField.AUTHOR, "Carr, I and Kidner, R") .withField(StandardField.BOOKTITLE, "Statutes and conventions on international trade law") .withField(StandardField.PUBLISHER, "Cavendish") .withField(StandardField.DATE, "2003") .withField(StandardField.YEAR, "2003") .withField(StandardField.ADDRESS, "London, England"); public static Stream<Arguments> provideExamplesForCorrectResultTest() { return Stream.of( Arguments.of("example1", example1AsBibEntry, example1), Arguments.of("example2", example2AsBibEntry, example2), Arguments.of("example3", example3AsBibEntry, example3), Arguments.of("example4", example4AsBibEntry, example4) ); } public static Stream<Arguments> provideInvalidInput() { return Stream.of( Arguments.of("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx________________________________"), Arguments.of("¦@#¦@#¦@#¦@#¦@#¦@#¦@°#¦@¦°¦@°") ); } @ParameterizedTest(name = "{0}") @MethodSource("provideExamplesForCorrectResultTest") public void grobidPerformSearchCorrectResultTest(String testName, BibEntry expectedBibEntry, String searchQuery) throws FetcherException { List<BibEntry> entries = grobidCitationFetcher.performSearch(searchQuery); assertEquals(List.of(expectedBibEntry), entries); } @Test public void grobidPerformSearchCorrectlySplitsStringTest() throws FetcherException { List<BibEntry> entries = grobidCitationFetcher.performSearch(example1 + "\n\n" + example2 + "\r\n\r\n" + example3 + "\r\r" + example4); assertEquals(List.of(example1AsBibEntry, example2AsBibEntry, example3AsBibEntry, example4AsBibEntry), entries); } @Test public void grobidPerformSearchWithEmptyStringsTest() throws FetcherException { List<BibEntry> entries = grobidCitationFetcher.performSearch(" \n "); assertEquals(Collections.emptyList(), entries); } @ParameterizedTest @MethodSource("provideInvalidInput") public void grobidPerformSearchWithInvalidDataTest(String invalidInput) throws FetcherException { List<BibEntry> entries = grobidCitationFetcher.performSearch(invalidInput); assertEquals(Collections.emptyList(), entries); } @Test public void performSearchThrowsExceptionInCaseOfConnectionIssues() throws IOException, ParseException { GrobidService grobidServiceMock = mock(GrobidService.class); when(grobidServiceMock.processCitation(anyString(), any(), any())).thenThrow(new SocketTimeoutException("Timeout")); grobidCitationFetcher = new GrobidCitationFetcher(importFormatPreferences, grobidServiceMock); assertThrows(FetcherException.class, () -> grobidCitationFetcher.performSearch("any text"), "performSearch should throw an FetcherException, when there are underlying IOException."); } }
9,454
69.037037
221
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/GvkFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.net.URL; import java.util.Collections; import java.util.List; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.fetcher.transformers.AbstractQueryTransformer; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; 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.assertTrue; @FetcherTest public class GvkFetcherTest { private GvkFetcher fetcher; private BibEntry bibEntryPPN591166003; private BibEntry bibEntryPPN66391437X; @BeforeEach public void setUp() { fetcher = new GvkFetcher(); bibEntryPPN591166003 = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.PUBLISHER, "Addison-Wesley") .withField(StandardField.YEAR, "2008") .withField(StandardField.AUTHOR, "Joshua Bloch") .withField(StandardField.SERIES, "The @Java series") .withField(StandardField.ADDRESS, "Upper Saddle River, NJ [u.a.]") .withField(StandardField.EDITION, "2. ed., 5. print.") .withField(StandardField.NOTE, "Literaturverz. S. 321 - 325") .withField(StandardField.ISBN, "9780321356680") .withField(StandardField.PAGETOTAL, "XXI, 346") .withField(new UnknownField("ppn_gvk"), "591166003") .withField(StandardField.SUBTITLE, "[revised and updated for JAVA SE 6]"); bibEntryPPN66391437X = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Effective unit testing") .withField(StandardField.PUBLISHER, "Manning") .withField(StandardField.YEAR, "2013") .withField(StandardField.AUTHOR, "Lasse Koskela") .withField(StandardField.ADDRESS, "Shelter Island, NY") .withField(StandardField.ISBN, "9781935182573") .withField(StandardField.PAGETOTAL, "XXIV, 223") .withField(new UnknownField("ppn_gvk"), "66391437X") .withField(StandardField.SUBTITLE, "A guide for Java developers"); } @Test public void testGetName() { assertEquals("GVK", fetcher.getName()); } @Test public void simpleSearchQueryURLCorrect() throws Exception { String query = "java jdk"; QueryNode luceneQuery = new StandardSyntaxParser().parse(query, AbstractQueryTransformer.NO_EXPLICIT_FIELD); URL url = fetcher.getURLForQuery(luceneQuery); assertEquals("http://sru.gbv.de/gvk?version=1.1&operation=searchRetrieve&query=pica.all%3Djava+and+pica.all%3Djdk&maximumRecords=50&recordSchema=picaxml&sortKeys=Year%2C%2C1", url.toString()); } @Test public void complexSearchQueryURLCorrect() throws Exception { String query = "kon:java tit:jdk"; QueryNode luceneQuery = new StandardSyntaxParser().parse(query, AbstractQueryTransformer.NO_EXPLICIT_FIELD); URL url = fetcher.getURLForQuery(luceneQuery); assertEquals("http://sru.gbv.de/gvk?version=1.1&operation=searchRetrieve&query=pica.kon%3Djava+and+pica.tit%3Djdk&maximumRecords=50&recordSchema=picaxml&sortKeys=Year%2C%2C1", url.toString()); } @Test public void testPerformSearchMatchingMultipleEntries() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch("title:\"effective java\""); assertTrue(searchResult.contains(bibEntryPPN591166003)); assertTrue(searchResult.contains(bibEntryPPN66391437X)); } @Test public void testPerformSearch591166003() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch("ppn:591166003"); assertEquals(Collections.singletonList(bibEntryPPN591166003), searchResult); } @Test public void testPerformSearch66391437X() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch("ppn:66391437X"); assertEquals(Collections.singletonList(bibEntryPPN66391437X), searchResult); } @Test public void testPerformSearchEmpty() throws FetcherException { List<BibEntry> searchResult = fetcher.performSearch(""); assertEquals(Collections.emptyList(), searchResult); } }
4,809
44.377358
200
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/IEEETest.java
package org.jabref.logic.importer.fetcher; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Optional; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.PagedSearchBasedFetcher; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest class IEEETest implements SearchBasedFetcherCapabilityTest, PagedSearchFetcherTest { private final BibEntry IGOR_NEWCOMERS = new BibEntry(StandardEntryType.InProceedings) .withField(StandardField.AUTHOR, "Igor Steinmacher and Tayana Uchoa Conte and Christoph Treude and Marco Aurélio Gerosa") .withField(StandardField.DATE, "14-22 May 2016") .withField(StandardField.YEAR, "2016") .withField(StandardField.EVENTDATE, "14-22 May 2016") .withField(StandardField.EVENTTITLEADDON, "Austin, TX, USA") .withField(StandardField.LOCATION, "Austin, TX, USA") .withField(StandardField.DOI, "10.1145/2884781.2884806") .withField(StandardField.JOURNALTITLE, "2016 IEEE/ACM 38th International Conference on Software Engineering (ICSE)") .withField(StandardField.PAGES, "273--284") .withField(StandardField.ISBN, "978-1-5090-2071-3") .withField(StandardField.ISSN, "1558-1225") .withField(StandardField.PUBLISHER, "IEEE") .withField(StandardField.KEYWORDS, "Portals, Documentation, Computer bugs, Joining processes, Industries, Open source software, Newcomers, Newbies, Novices, Beginners, Open Source Software, Barriers, Obstacles, Onboarding, Joining Process") .withField(StandardField.TITLE, "Overcoming Open Source Project Entry Barriers with a Portal for Newcomers") .withField(StandardField.FILE, ":https\\://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7886910:PDF"); private IEEE fetcher; private BibEntry entry; @BeforeEach void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); ImporterPreferences importerPreferences = mock(ImporterPreferences.class); when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); fetcher = new IEEE(importFormatPreferences, importerPreferences); entry = new BibEntry(); } @Test void findByDOI() throws Exception { entry.setField(StandardField.DOI, "10.1109/ACCESS.2016.2535486"); assertEquals(Optional.of(new URL("https://ieeexplore.ieee.org/ielx7/6287639/7419931/07421926.pdf?tp=&arnumber=7421926&isnumber=7419931&ref=")), fetcher.findFullText(entry)); } @Test void findByDocumentUrl() throws Exception { entry.setField(StandardField.URL, "https://ieeexplore.ieee.org/document/7421926/"); assertEquals(Optional.of(new URL("https://ieeexplore.ieee.org/ielx7/6287639/7419931/07421926.pdf?tp=&arnumber=7421926&isnumber=7419931&ref=")), fetcher.findFullText(entry)); } @Test void findByURL() throws Exception { entry.setField(StandardField.URL, "https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7421926&ref="); assertEquals(Optional.of(new URL("https://ieeexplore.ieee.org/ielx7/6287639/7419931/07421926.pdf?tp=&arnumber=7421926&isnumber=7419931&ref=")), fetcher.findFullText(entry)); } @Test void findByOldURL() throws Exception { entry.setField(StandardField.URL, "https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7421926"); assertEquals(Optional.of(new URL("https://ieeexplore.ieee.org/ielx7/6287639/7419931/07421926.pdf?tp=&arnumber=7421926&isnumber=7419931&ref=")), fetcher.findFullText(entry)); } @Test void findByDOIButNotURL() throws Exception { entry.setField(StandardField.DOI, "10.1109/ACCESS.2016.2535486"); entry.setField(StandardField.URL, "http://dx.doi.org/10.1109/ACCESS.2016.2535486"); assertEquals(Optional.of(new URL("https://ieeexplore.ieee.org/ielx7/6287639/7419931/07421926.pdf?tp=&arnumber=7421926&isnumber=7419931&ref=")), fetcher.findFullText(entry)); } @Test void notFoundByURL() throws Exception { entry.setField(StandardField.URL, "http://dx.doi.org/10.1109/ACCESS.2016.2535486"); assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test void notFoundByDOI() throws Exception { entry.setField(StandardField.DOI, "10.1021/bk-2006-WWW.ch014"); assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test void searchResultHasNoKeywordTerms() throws Exception { BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Shatakshi Sharma and Bhim Singh and Sukumar Mishra") .withField(StandardField.DATE, "April 2020") .withField(StandardField.YEAR, "2020") .withField(StandardField.DOI, "10.1109/TII.2019.2935531") .withField(StandardField.FILE, ":https\\://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912:PDF") .withField(StandardField.ISSUE, "4") .withField(StandardField.ISSN, "1941-0050") .withField(StandardField.JOURNALTITLE, "IEEE Transactions on Industrial Informatics") .withField(StandardField.PAGES, "2346--2356") .withField(StandardField.PUBLISHER, "IEEE") .withField(StandardField.TITLE, "Economic Operation and Quality Control in PV-BES-DG-Based Autonomous System") .withField(StandardField.VOLUME, "16") .withField(StandardField.KEYWORDS, "Batteries, Generators, Economics, Power quality, State of charge, Harmonic analysis, Control systems, Battery, diesel generator (DG), distributed generation, power quality, photovoltaic (PV), voltage source converter (VSC)"); List<BibEntry> fetchedEntries = fetcher.performSearch("article_number:8801912"); // article number fetchedEntries.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); // Remove abstract due to copyright); assertEquals(Collections.singletonList(expected), fetchedEntries); } @Test void searchByPlainQueryFindsEntry() throws Exception { List<BibEntry> fetchedEntries = fetcher.performSearch("Overcoming Open Source Project Entry Barriers with a Portal for Newcomers"); // Abstract should not be included in JabRef tests fetchedEntries.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); assertEquals(Collections.singletonList(IGOR_NEWCOMERS), fetchedEntries); } @Test void searchByQuotedQueryFindsEntry() throws Exception { List<BibEntry> fetchedEntries = fetcher.performSearch("\"Overcoming Open Source Project Entry Barriers with a Portal for Newcomers\""); // Abstract should not be included in JabRef tests fetchedEntries.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); assertEquals(Collections.singletonList(IGOR_NEWCOMERS), fetchedEntries); } @Override public SearchBasedFetcher getFetcher() { return fetcher; } @Override public List<String> getTestAuthors() { return List.of("Igor Steinmacher", "Tayana Uchoa Conte", "Christoph Treude", "Marco Aurélio Gerosa"); } @Override public String getTestJournal() { return "IET Renewable Power Generation"; } @Override public PagedSearchBasedFetcher getPagedFetcher() { return fetcher; } }
8,314
48.494048
277
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/INSPIREFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest class INSPIREFetcherTest { private INSPIREFetcher fetcher; @BeforeEach void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); fetcher = new INSPIREFetcher(importFormatPreferences); } @Test void searchByQueryFindsEntry() throws Exception { BibEntry master = new BibEntry(StandardEntryType.MastersThesis) .withCitationKey("Diez:2013fdp") .withField(StandardField.AUTHOR, "Diez, Tobias") .withField(StandardField.TITLE, "Slice theorem for Fréchet group actions and covariant symplectic field theory") .withField(StandardField.SCHOOL, "Leipzig U.") .withField(StandardField.YEAR, "2013") .withField(StandardField.EPRINT, "1405.2249") .withField(StandardField.ARCHIVEPREFIX, "arXiv") .withField(StandardField.PRIMARYCLASS, "math-ph"); List<BibEntry> fetchedEntries = fetcher.performSearch("Fréchet group actions field"); assertEquals(Collections.singletonList(master), fetchedEntries); } @Test public void searchByIdentifierFindsEntry() throws Exception { BibEntry article = new BibEntry(StandardEntryType.Article) .withCitationKey("Melnikov:1998pr") .withField(StandardField.AUTHOR, "Melnikov, Kirill and Yelkhovsky, Alexander") .withField(StandardField.TITLE, "Top quark production at threshold with O(alpha-s**2) accuracy") .withField(StandardField.DOI, "10.1016/S0550-3213(98)00348-4") .withField(StandardField.JOURNAL, "Nucl. Phys. B") .withField(StandardField.PAGES, "59--72") .withField(StandardField.VOLUME, "528") .withField(StandardField.YEAR, "1998") .withField(StandardField.EPRINT, "hep-ph/9802379") .withField(StandardField.ARCHIVEPREFIX, "arXiv") .withField(new UnknownField("reportnumber"), "BUDKER-INP-1998-7, TTP-98-10"); List<BibEntry> fetchedEntries = fetcher.performSearch("\"hep-ph/9802379\""); assertEquals(Collections.singletonList(article), fetchedEntries); } @Test public void searchByExistingEntry() throws Exception { BibEntry article = new BibEntry(StandardEntryType.Article) .withCitationKey("Melnikov:1998pr") .withField(StandardField.AUTHOR, "Melnikov, Kirill and Yelkhovsky, Alexander") .withField(StandardField.TITLE, "Top quark production at threshold with O(alpha-s**2) accuracy") .withField(StandardField.DOI, "10.1016/S0550-3213(98)00348-4") .withField(StandardField.JOURNAL, "Nucl. Phys. B") .withField(StandardField.PAGES, "59--72") .withField(StandardField.VOLUME, "528") .withField(StandardField.YEAR, "1998") .withField(StandardField.EPRINT, "hep-ph/9802379") .withField(StandardField.ARCHIVEPREFIX, "arXiv") .withField(new UnknownField("reportnumber"), "BUDKER-INP-1998-7, TTP-98-10"); List<BibEntry> fetchedEntries = fetcher.performSearch(article); assertEquals(Collections.singletonList(article), fetchedEntries); } }
3,982
47.573171
128
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/IacrEprintFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; 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.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @FetcherTest @DisabledOnCIServer("eprint.iacr.org blocks with 500 when there are too many calls from the same IP address.") public class IacrEprintFetcherTest { private IacrEprintFetcher fetcher; private BibEntry abram2017; private BibEntry abram2017noVersion; private BibEntry beierle2016; private BibEntry delgado2017; @BeforeEach public void setUp() { fetcher = new IacrEprintFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); abram2017 = new BibEntry(StandardEntryType.Misc) .withCitationKey("cryptoeprint:2017/1118") .withField(StandardField.ABSTRACT, "dummy") .withField(StandardField.AUTHOR, "Ittai Abraham and Dahlia Malkhi and Kartik Nayak and Ling Ren and Alexander Spiegelman") .withField(StandardField.DATE, "2017-11-24") .withField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Paper 2017/1118") .withField(StandardField.NOTE, "\\url{https://eprint.iacr.org/2017/1118}") .withField(StandardField.TITLE, "Solida: A Blockchain Protocol Based on Reconfigurable Byzantine Consensus") .withField(StandardField.URL, "https://eprint.iacr.org/2017/1118/20171124:064527") .withField(StandardField.VERSION, "20171124:064527") .withField(StandardField.YEAR, "2017"); abram2017noVersion = new BibEntry(StandardEntryType.Misc) .withCitationKey("cryptoeprint:2017/1118") .withField(StandardField.ABSTRACT, "dummy") .withField(StandardField.AUTHOR, "Ittai Abraham and Dahlia Malkhi and Kartik Nayak and Ling Ren and Alexander Spiegelman") .withField(StandardField.DATE, "2017-11-24") .withField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Paper 2017/1118") .withField(StandardField.NOTE, "\\url{https://eprint.iacr.org/2017/1118}") .withField(StandardField.TITLE, "Solida: A Blockchain Protocol Based on Reconfigurable Byzantine Consensus") .withField(StandardField.URL, "https://eprint.iacr.org/2017/1118") .withField(StandardField.YEAR, "2017"); beierle2016 = new BibEntry(StandardEntryType.Misc) .withCitationKey("cryptoeprint:2016/119") .withField(StandardField.ABSTRACT, "dummy") .withField(StandardField.AUTHOR, "Christof Beierle and Thorsten Kranz and Gregor Leander") .withField(StandardField.DATE, "2017-02-17") .withField(StandardField.DOI, "10.1007/978-3-662-53018-4_23") .withField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Paper 2016/119") .withField(StandardField.NOTE, "\\url{https://eprint.iacr.org/2016/119}") .withField(StandardField.TITLE, "Lightweight Multiplication in GF(2^n) with Applications to MDS Matrices") .withField(StandardField.URL, "https://eprint.iacr.org/2016/119/20170217:150415") .withField(StandardField.VERSION, "20170217:150415") .withField(StandardField.YEAR, "2016"); delgado2017 = new BibEntry(StandardEntryType.Misc) .withCitationKey("cryptoeprint:2017/1095") .withField(StandardField.ABSTRACT, "dummy") .withField(StandardField.AUTHOR, "Sergi Delgado-Segura and Cristina Pérez-Solà and Guillermo Navarro-Arribas and Jordi Herrera-Joancomartí") .withField(StandardField.DATE, "2018-01-19") .withField(StandardField.HOWPUBLISHED, "Cryptology ePrint Archive, Paper 2017/1095") .withField(StandardField.NOTE, "\\url{https://eprint.iacr.org/2017/1095}") .withField(StandardField.TITLE, "Analysis of the Bitcoin UTXO set") .withField(StandardField.URL, "https://eprint.iacr.org/2017/1095/20180119:113352") .withField(StandardField.VERSION, "20180119:113352") .withField(StandardField.YEAR, "2017"); } @Test public void searchByIdWithValidId1() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("Report 2017/1118 "); assertFalse(fetchedEntry.get().getField(StandardField.ABSTRACT).get().isEmpty()); fetchedEntry.get().setField(StandardField.ABSTRACT, "dummy"); assertEquals(Optional.of(abram2017), fetchedEntry); } @Test public void searchByIdWithValidId2() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("iacr ePrint 2016/119"); assertFalse(fetchedEntry.get().getField(StandardField.ABSTRACT).get().isEmpty()); fetchedEntry.get().setField(StandardField.ABSTRACT, "dummy"); assertEquals(Optional.of(beierle2016), fetchedEntry); } @Test public void searchByIdWithValidIdAndNonAsciiChars() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("some random 2017/1095 stuff around the id"); assertFalse(fetchedEntry.get().getField(StandardField.ABSTRACT).get().isEmpty()); fetchedEntry.get().setField(StandardField.ABSTRACT, "dummy"); assertEquals(Optional.of(delgado2017), fetchedEntry); } @Test public void searchByIdWithEmptyIdFails() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("")); } @Test public void searchByIdWithInvalidReportNumberFails() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("2016/1")); } @Test public void searchByIdWithInvalidYearFails() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("16/115")); } @Test public void searchByIdWithInvalidIdFails() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("asdf")); } @Test public void searchForNonexistentIdFails() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("2016/6425")); } @Test public void testGetName() { assertEquals(IacrEprintFetcher.NAME, fetcher.getName()); } @Test public void searchByIdForWithdrawnPaperFails() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("1998/016")); } @Test public void searchByIdWithOldHtmlFormatAndCheckDate() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("1997/006"); assertEquals(Optional.of("1997-05-04"), fetchedEntry.get().getField(StandardField.DATE)); } @DisplayName("Get all entries with old HTML format (except withdrawn ones)") @ParameterizedTest(name = "Fetch for id: {0}") @MethodSource("allNonWithdrawnIdsWithOldHtmlFormat") @Disabled("Takes a lot of time - should only be called manually") public void searchByIdWithOldHtmlFormatWithoutDateCheck(String id) throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById(id); assertTrue(fetchedEntry.isPresent(), "Expected to get an entry for id " + id); assertNotEquals(Optional.empty(), fetchedEntry.get().getField(StandardField.DATE), "Expected non empty date field, entry is\n" + fetchedEntry.toString()); assertTrue(fetchedEntry.get().getField(StandardField.DATE).get().length() == 10, "Expected yyyy-MM-dd date format, entry is\n" + fetchedEntry.toString()); assertNotEquals(Optional.empty(), fetchedEntry.get().getField(StandardField.ABSTRACT), "Expected non empty abstract field, entry is\n" + fetchedEntry.toString()); } /** * Helper method for allNonWithdrawnIdsWithOldHtmlFormat. * * @param year The year of the generated IDs (e.g. 1996) * @param maxId The maximum ID to generate in the given year (e.g. 112) * @return A list of IDs in the from yyyy/iii (e.g. [1996/001, 1996/002, ..., 1996/112] */ private static List<String> getIdsFor(int year, int maxId) { List<String> result = new ArrayList<>(); for (int i = 1; i <= maxId; i++) { result.add(String.format("%04d/%03d", year, i)); } return result; } // Parameter provider (method name is passed as a string) @SuppressWarnings("unused") private static Stream<String> allNonWithdrawnIdsWithOldHtmlFormat() { Collection<String> withdrawnIds = Arrays.asList("1998/016", "1999/006"); List<String> ids = new ArrayList<>(); ids.addAll(getIdsFor(1996, 16)); ids.addAll(getIdsFor(1997, 15)); ids.addAll(getIdsFor(1998, 26)); ids.addAll(getIdsFor(1999, 24)); ids.removeAll(withdrawnIds); return ids.stream(); } @Test public void getFulltextWithVersion() throws FetcherException, IOException { Optional<URL> pdfUrl = fetcher.findFullText(abram2017); assertEquals(Optional.of("https://eprint.iacr.org/archive/2017/1118/1511505927.pdf"), pdfUrl.map(URL::toString)); } @Test public void getFulltextWithoutVersion() throws FetcherException, IOException { Optional<URL> pdfUrl = fetcher.findFullText(abram2017noVersion); assertEquals(Optional.of("https://eprint.iacr.org/2017/1118.pdf"), pdfUrl.map(URL::toString)); } @Test public void getFulltextWithoutUrl() throws FetcherException, IOException { BibEntry abram2017WithoutUrl = abram2017; abram2017WithoutUrl.clearField(StandardField.URL); Optional<URL> pdfUrl = fetcher.findFullText(abram2017WithoutUrl); assertEquals(Optional.empty(), pdfUrl); } @Test public void getFulltextWithNonIACRUrl() throws IOException { BibEntry abram2017WithNonIACRUrl = abram2017; abram2017WithNonIACRUrl.setField(StandardField.URL, "https://example.com"); assertThrows(FetcherException.class, () -> fetcher.findFullText(abram2017WithNonIACRUrl)); } }
11,256
47.943478
170
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/JstorFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.net.URL; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; @FetcherTest @DisabledOnCIServer("CI server is blocked by JSTOR") public class JstorFetcherTest implements SearchBasedFetcherCapabilityTest { private final JstorFetcher fetcher = new JstorFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); private final BibEntry bibEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("10.2307/90002164") .withField(StandardField.AUTHOR, "Yang Yanxia") .withField(StandardField.TITLE, "Test Anxiety Analysis of Chinese College Students in Computer-based Spoken English Test") .withField(StandardField.ISSN, "11763647, 14364522") .withField(StandardField.JOURNAL, "Journal of Educational Technology & Society") .withField(StandardField.ABSTRACT, "ABSTRACT Test anxiety was a commonly known or assumed factor that could greatly influence performance of test takers. With the employment of designed questionnaires and computer-based spoken English test, this paper explored test anxiety manifestation of Chinese college students from both macro and micro aspects, and found out that the major anxiety in computer-based spoken English test was spoken English test anxiety, which consisted of test anxiety and communication apprehension. Regard to proximal test anxiety, the causes listed in proper order as low spoken English abilities, lack of speaking techniques, anxiety from the evaluative process and inadaptability with computer-based spoken English test format. As to distal anxiety causes, attitude toward learning spoken English and self-evaluation of speaking abilities were significantly negatively correlated with test anxiety. Besides, as test anxiety significantly associated often with test performance, a look at pedagogical implications has been discussed in this paper.") .withField(StandardField.PUBLISHER, "International Forum of Educational Technology & Society") .withField(StandardField.NUMBER, "2") .withField(StandardField.PAGES, "63--73") .withField(StandardField.VOLUME, "20") .withField(StandardField.URL, "http://www.jstor.org/stable/90002164") .withField(StandardField.YEAR, "2017"); private final BibEntry doiEntry = new BibEntry(StandardEntryType.Article) .withCitationKey("10.1086/501484") .withField(StandardField.AUTHOR, "Johnmarshall Reeve") .withField(StandardField.TITLE, "Teachers as Facilitators: What Autonomy‐Supportive Teachers Do and Why Their Students Benefit") .withField(StandardField.ISSN, "00135984, 15548279") .withField(StandardField.JOURNAL, "The Elementary School Journal") .withField(StandardField.ABSTRACT, "Abstract Students are sometimes proactive and engaged in classroom learning activities, but they are also sometimes only reactive and passive. Recognizing this, in this article I argue that students’ classroom engagement depends, in part, on the supportive quality of the classroom climate in which they learn. According to the dialectical framework within self‐determination theory, students possess inner motivational resources that classroom conditions can support or frustrate. When teachers find ways to nurture these inner resources, they adopt an autonomy‐supportive motivating style. After articulating what autonomy‐supportive teachers say and do during instruction, I discuss 3 points: teachers can learn how to be more autonomy supportive toward students; teachers most engage students when they offer high levels of both autonomy support and structure; and an autonomy‐supportive motivating style is an important element to a high‐quality teacher‐student relationship.") .withField(StandardField.PUBLISHER, "The University of Chicago Press") .withField(StandardField.NUMBER, "3") .withField(StandardField.PAGES, "225--236") .withField(StandardField.VOLUME, "106") .withField(StandardField.URL, "http://www.jstor.org/stable/10.1086/501484") .withField(StandardField.YEAR, "2006"); @Test void searchByTitle() throws Exception { List<BibEntry> entries = fetcher.performSearch("title: \"Test Anxiety Analysis of Chinese College Students in Computer-based Spoken English Test\""); assertEquals(Collections.singletonList(bibEntry), entries); } @Test void searchById() throws Exception { Optional<BibEntry> actual = fetcher.performSearchById("90002164"); // The URL date is always the current date in the US. No need to properly check it. actual.ifPresent(entry -> entry.clearField(StandardField.URLDATE)); assertEquals(Optional.of(bibEntry), actual); } @Test void searchByUrlUsingId() throws Exception { doiEntry.setField(StandardField.URLDATE, LocalDate.now().format(DateTimeFormatter.ISO_DATE)); assertEquals(Optional.of(doiEntry), fetcher.performSearchById("https://www.jstor.org/stable/10.1086/501484?seq=1")); } @Test void fetchPDF() throws Exception { Optional<URL> url = fetcher.findFullText(bibEntry); assertEquals(Optional.of(new URL("https://www.jstor.org/stable/pdf/90002164.pdf")), url); } @Override public SearchBasedFetcher getFetcher() { return fetcher; } @Override public List<String> getTestAuthors() { return List.of("Haman", "Medlin"); } @Override public String getTestJournal() { // Does not provide articles and journals return "Test"; } @Disabled("jstor does not support search only based on year") @Override public void supportsYearRangeSearch() throws Exception { } @Disabled("jstor does not provide articles with journals") @Override public void supportsJournalSearch() throws Exception { } @Disabled("jstor does not support search only based on year") @Override public void supportsYearSearch() throws Exception { } }
6,810
57.715517
1,087
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/LibraryOfCongressTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.preferences.BibEntryPreferences; 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; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest public class LibraryOfCongressTest { private LibraryOfCongress fetcher; @BeforeEach public void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class); when(importFormatPreferences.bibEntryPreferences()).thenReturn(mock(BibEntryPreferences.class)); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); fetcher = new LibraryOfCongress(importFormatPreferences); } @Test public void performSearchById() throws Exception { BibEntry expected = new BibEntry() .withField(StandardField.ADDRESS, "mau, Burlington, MA") .withField(StandardField.AUTHOR, "West, Matthew") .withField(StandardField.DATE, "2011") .withField(StandardField.ISBN, "0123751063 (pbk.)") .withField(new UnknownField("issuance"), "monographic") .withField(StandardField.KEYWORDS, "Database design, Data structures (Computer science)") .withField(StandardField.LANGUAGE, "eng") .withField(new UnknownField("lccn"), "2010045158") .withField(StandardField.NOTE, "Matthew West., Includes index.") .withField(new UnknownField("oclc"), "ocn665135773") .withField(new UnknownField("source"), "aacr") .withField(StandardField.TITLE, "Developing high quality data models") .withField(StandardField.YEAR, "2011"); assertEquals(Optional.of(expected), fetcher.performSearchById("2010045158")); } @Test public void performSearchByEmptyId() throws Exception { assertEquals(Optional.empty(), fetcher.performSearchById("")); } @Test public void performSearchByInvalidId() { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("xxx")); } }
2,642
39.661538
105
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/MathSciNetTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest class MathSciNetTest { MathSciNet fetcher; private BibEntry ratiuEntry; @BeforeEach void setUp() throws Exception { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); fetcher = new MathSciNet(importFormatPreferences); ratiuEntry = new BibEntry(); ratiuEntry.setType(StandardEntryType.Article); ratiuEntry.setCitationKey("MR3537908"); ratiuEntry.setField(StandardField.AUTHOR, "Chechkin, Gregory A. and Ratiu, Tudor S. and Romanov, Maxim S. and Samokhin, Vyacheslav N."); ratiuEntry.setField(StandardField.TITLE, "Existence and uniqueness theorems for the two-dimensional {E}ricksen-{L}eslie system"); ratiuEntry.setField(StandardField.JOURNAL, "Journal of Mathematical Fluid Mechanics"); ratiuEntry.setField(StandardField.VOLUME, "18"); ratiuEntry.setField(StandardField.YEAR, "2016"); ratiuEntry.setField(StandardField.NUMBER, "3"); ratiuEntry.setField(StandardField.PAGES, "571--589"); ratiuEntry.setField(StandardField.ISSN, "1422-6928"); ratiuEntry.setField(StandardField.KEYWORDS, "76A15 (35A01 35A02 35K61 82D30)"); ratiuEntry.setField(StandardField.MR_NUMBER, "3537908"); ratiuEntry.setField(StandardField.DOI, "10.1007/s00021-016-0250-0"); } @Test void searchByEntryFindsEntry() throws Exception { BibEntry searchEntry = new BibEntry(); searchEntry.setField(StandardField.TITLE, "existence"); searchEntry.setField(StandardField.AUTHOR, "Ratiu"); searchEntry.setField(StandardField.JOURNAL, "fluid"); List<BibEntry> fetchedEntries = fetcher.performSearch(searchEntry); assertEquals(Collections.singletonList(ratiuEntry), fetchedEntries); } @Test @DisabledOnCIServer("CI server has no subscription to MathSciNet and thus gets 401 response") void searchByIdInEntryFindsEntry() throws Exception { BibEntry searchEntry = new BibEntry(); searchEntry.setField(StandardField.MR_NUMBER, "3537908"); List<BibEntry> fetchedEntries = fetcher.performSearch(searchEntry); assertEquals(Collections.singletonList(ratiuEntry), fetchedEntries); } @Test @DisabledOnCIServer("CI server has no subscription to MathSciNet and thus gets 401 response") void searchByQueryFindsEntry() throws Exception { List<BibEntry> fetchedEntries = fetcher.performSearch("Existence and uniqueness theorems Two-Dimensional Ericksen Leslie System"); assertFalse(fetchedEntries.isEmpty()); assertEquals(ratiuEntry, fetchedEntries.get(1)); } @Test @DisabledOnCIServer("CI server has no subscription to MathSciNet and thus gets 401 response") void searchByIdFindsEntry() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("3537908"); assertEquals(Optional.of(ratiuEntry), fetchedEntry); } }
3,831
42.545455
144
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/MedlineFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.FetcherClientException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @FetcherTest public class MedlineFetcherTest { private MedlineFetcher fetcher; private BibEntry entryWijedasa; private BibEntry entryEndharti; private BibEntry bibEntryIchikawa; private BibEntry bibEntrySari; @BeforeEach public void setUp() throws InterruptedException { // pause between runs to avoid 403 and 429 at Medline Thread.sleep(1000); fetcher = new MedlineFetcher(); entryWijedasa = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Wijedasa, Lahiru S. and Jauhiainen, Jyrki and Könönen, Mari and Lampela, Maija and Vasander, Harri and Leblanc, Marie-Claire and Evers, Stephanie and Smith, Thomas E. L. and Yule, Catherine M. and Varkkey, Helena and Lupascu, Massimo and Parish, Faizal and Singleton, Ian and Clements, Gopalasamy R. and Aziz, Sheema Abdul and Harrison, Mark E. and Cheyne, Susan and Anshari, Gusti Z. and Meijaard, Erik and Goldstein, Jenny E. and Waldron, Susan and Hergoualc'h, Kristell and Dommain, Rene and Frolking, Steve and Evans, Christopher D. and Posa, Mary Rose C. and Glaser, Paul H. and Suryadiputra, Nyoman and Lubis, Reza and Santika, Truly and Padfield, Rory and Kurnianto, Sofyan and Hadisiswoyo, Panut and Lim, Teck Wyn and Page, Susan E. and Gauci, Vincent and Van Der Meer, Peter J. and Buckland, Helen and Garnier, Fabien and Samuel, Marshall K. and Choo, Liza Nuriati Lim Kim and O'Reilly, Patrick and Warren, Matthew and Suksuwan, Surin and Sumarga, Elham and Jain, Anuj and Laurance, William F. and Couwenberg, John and Joosten, Hans and Vernimmen, Ronald and Hooijer, Aljosja and Malins, Chris and Cochrane, Mark A. and Perumal, Balu and Siegert, Florian and Peh, Kelvin S.-H. and Comeau, Louis-Pierre and Verchot, Louis and Harvey, Charles F. and Cobb, Alex and Jaafar, Zeehan and Wösten, Henk and Manuri, Solichin and Müller, Moritz and Giesen, Wim and Phelps, Jacob and Yong, Ding Li and Silvius, Marcel and Wedeux, Béatrice M. M. and Hoyt, Alison and Osaki, Mitsuru and Hirano, Takashi and Takahashi, Hidenori and Kohyama, Takashi S. and Haraguchi, Akira and Nugroho, Nunung P. and Coomes, David A. and Quoi, Le Phat and Dohong, Alue and Gunawan, Haris and Gaveau, David L. A. and Langner, Andreas and Lim, Felix K. S. and Edwards, David P. and Giam, Xingli and Van Der Werf, Guido and Carmenta, Rachel and Verwer, Caspar C. and Gibson, Luke and Gandois, Laure and Graham, Laura Linda Bozena and Regalino, Jhanson and Wich, Serge A. and Rieley, Jack and Kettridge, Nicholas and Brown, Chloe and Pirard, Romain and Moore, Sam and Capilla, B. Ripoll and Ballhorn, Uwe and Ho, Hua Chew and Hoscilo, Agata and Lohberger, Sandra and Evans, Theodore A. and Yulianti, Nina and Blackham, Grace and Onrizal and Husson, Simon and Murdiyarso, Daniel and Pangala, Sunita and Cole, Lydia E. S. and Tacconi, Luca and Segah, Hendrik and Tonoto, Prayoto and Lee, Janice S. H. and Schmilewski, Gerald and Wulffraat, Stephan and Putra, Erianto Indra and Cattau, Megan E. and Clymo, R. S. and Morrison, Ross and Mujahid, Aazani and Miettinen, Jukka and Liew, Soo Chin and Valpola, Samu and Wilson, David and D'Arcy, Laura and Gerding, Michiel and Sundari, Siti and Thornton, Sara A. and Kalisz, Barbara and Chapman, Stephen J. and Su, Ahmad Suhaizi Mat and Basuki, Imam and Itoh, Masayuki and Traeholt, Carl and Sloan, Sean and Sayok, Alexander K. and Andersen, Roxane") .withField(new UnknownField("country"), "England") .withField(StandardField.DOI, "10.1111/gcb.13516") .withField(StandardField.ISSN, "1365-2486") .withField(new UnknownField("issn-linking"), "1354-1013") .withField(StandardField.ISSUE, "3") .withField(StandardField.JOURNAL, "Global change biology") .withField(StandardField.MONTH, "#mar#") .withField(new UnknownField("nlm-id"), "9888746") .withField(StandardField.OWNER, "NLM") .withField(StandardField.PAGES, "977--982") .withField(StandardField.PMID, "27670948") .withField(new UnknownField("pubmodel"), "Print-Electronic") .withField(StandardField.PUBSTATE, "ppublish") .withField(new UnknownField("revised"), "2019-11-20") .withField(StandardField.TITLE, "Denial of long-term issues with agriculture on tropical peatlands will have devastating consequences.") .withField(StandardField.VOLUME, "23") .withField(StandardField.YEAR, "2017"); entryEndharti = new BibEntry(StandardEntryType.Article) .withField(StandardField.TITLE, "Dendrophthoe pentandra (L.) Miq extract effectively inhibits inflammation, proliferation and induces p53 expression on colitis-associated colon cancer.") .withField(StandardField.AUTHOR, "Endharti, Agustina Tri and Wulandari, Adisti and Listyana, Anik and Norahmawati, Eviana and Permana, Sofy") .withField(new UnknownField("country"), "England") .withField(StandardField.DOI, "10.1186/s12906-016-1345-0") .withField(new UnknownField("pii"), "374") .withField(new UnknownField("pmc"), "PMC5037598") .withField(StandardField.ISSN, "1472-6882") .withField(new UnknownField("issn-linking"), "1472-6882") .withField(StandardField.ISSUE, "1") .withField(StandardField.JOURNAL, "BMC complementary and alternative medicine") .withField(StandardField.KEYWORDS, "CAC; Dendrophtoe pentandra; IL-22; MPO; Proliferation; p53") .withField(new UnknownField("nlm-id"), "101088661") .withField(StandardField.OWNER, "NLM") .withField(StandardField.PAGES, "374") .withField(StandardField.MONTH, "#sep#") .withField(StandardField.PMID, "27670445") .withField(new UnknownField("pubmodel"), "Electronic") .withField(StandardField.PUBSTATE, "epublish") .withField(new UnknownField("revised"), "2022-04-08") .withField(StandardField.VOLUME, "16") .withField(StandardField.YEAR, "2016"); bibEntryIchikawa = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Ichikawa-Seki, Madoka and Guswanto, Azirwan and Allamanda, Puttik and Mariamah, Euis Siti and Wibowo, Putut Eko and Igarashi, Ikuo and Nishikawa, Yoshifumi") .withField(new UnknownField("chemicals"), "Antibodies, Protozoan, Antigens, Protozoan, GRA7 protein, Toxoplasma gondii, Protozoan Proteins") .withField(new UnknownField("citation-subset"), "IM") .withField(new UnknownField("completed"), "2016-07-26") .withField(new UnknownField("country"), "Netherlands") .withField(StandardField.DOI, "10.1016/j.parint.2015.07.004") .withField(StandardField.ISSN, "1873-0329") .withField(StandardField.PUBSTATE, "ppublish") .withField(new UnknownField("revised"), "2015-09-26") .withField(new UnknownField("issn-linking"), "1383-5769") .withField(StandardField.ISSUE, "6") .withField(StandardField.JOURNAL, "Parasitology international") .withField(StandardField.KEYWORDS, "Animals; Antibodies, Protozoan, blood; Antigens, Protozoan, immunology; Cattle, parasitology; Cattle Diseases, epidemiology, parasitology; Enzyme-Linked Immunosorbent Assay, veterinary; Geography; Humans; Indonesia, epidemiology; Livestock, immunology, parasitology; Meat, parasitology; Protozoan Proteins, immunology; Seroepidemiologic Studies; Swine, parasitology; Swine Diseases, epidemiology, parasitology; Toxoplasma, immunology; Toxoplasmosis, Animal, epidemiology, immunology, parasitology; Cattle; ELISA; Indonesia; Pig; TgGRA7; Toxoplasma gondii") .withField(StandardField.MONTH, "#dec#") .withField(new UnknownField("nlm-id"), "9708549") .withField(StandardField.OWNER, "NLM") .withField(StandardField.PAGES, "484--486") .withField(new UnknownField("pii"), "S1383-5769(15)00124-5") .withField(StandardField.PMID, "26197440") .withField(new UnknownField("pubmodel"), "Print-Electronic") .withField(StandardField.TITLE, "Seroprevalence of antibody to TgGRA7 antigen of Toxoplasma gondii in livestock animals from Western Java, Indonesia.") .withField(StandardField.VOLUME, "64") .withField(StandardField.YEAR, "2015"); bibEntrySari = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Sari, Yulia and Haryati, Sri and Raharjo, Irvan and Prasetyo, Afiono Agung") .withField(new UnknownField("chemicals"), "Antibodies, Protozoan, Antibodies, Viral, HTLV-I Antibodies, HTLV-II Antibodies, Hepatitis Antibodies, Hepatitis B Antibodies, Hepatitis C Antibodies, Immunoglobulin G, Immunoglobulin M") .withField(new UnknownField("citation-subset"), "IM") .withField(new UnknownField("completed"), "2016-04-21") .withField(new UnknownField("country"), "Thailand") .withField(StandardField.ISSN, "0125-1562") .withField(new UnknownField("issn-linking"), "0125-1562") .withField(StandardField.ISSUE, "6") .withField(StandardField.JOURNAL, "The Southeast Asian journal of tropical medicine and public health") .withField(StandardField.KEYWORDS, "Antibodies, Protozoan; Antibodies, Viral, immunology; Coinfection, epidemiology, immunology; Female; HIV Infections, epidemiology; HTLV-I Antibodies, immunology; HTLV-I Infections, epidemiology, immunology; HTLV-II Antibodies, immunology; HTLV-II Infections, epidemiology, immunology; Hepatitis Antibodies, immunology; Hepatitis B Antibodies, immunology; Hepatitis C Antibodies, immunology; Hepatitis Delta Virus, immunology; Hepatitis, Viral, Human, epidemiology, immunology; Humans; Immunoglobulin G, immunology; Immunoglobulin M, immunology; Indonesia, epidemiology; Male; Prisoners; Seroepidemiologic Studies; Toxoplasma, immunology; Toxoplasmosis, epidemiology, immunology") .withField(StandardField.MONTH, "#nov#") .withField(StandardField.PUBSTATE, "ppublish") .withField(new UnknownField("revised"), "2018-12-02") .withField(new UnknownField("nlm-id"), "0266303") .withField(StandardField.OWNER, "NLM") .withField(StandardField.PAGES, "977--985") .withField(StandardField.PMID, "26867355") .withField(new UnknownField("pubmodel"), "Print") .withField(StandardField.TITLE, "TOXOPLASMA AND VIRAL ANTIBODIES AMONG HIV PATIENTS AND INMATES IN CENTRAL JAVA, INDONESIA.") .withField(StandardField.VOLUME, "46") .withField(StandardField.YEAR, "2015"); } @Test public void testGetName() { assertEquals("Medline/PubMed", fetcher.getName()); } @Test public void testSearchByIDWijedasa() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("27670948"); assertTrue(fetchedEntry.isPresent()); fetchedEntry.get().clearField(StandardField.ABSTRACT); // Remove abstract due to copyright assertEquals(Optional.of(entryWijedasa), fetchedEntry); } @Test public void testSearchByIDEndharti() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("27670445"); assertTrue(fetchedEntry.isPresent()); fetchedEntry.get().clearField(StandardField.ABSTRACT); // Remove abstract due to copyright assertEquals(Optional.of(entryEndharti), fetchedEntry); } @Test public void testSearchByIDIchikawa() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("26197440"); assertTrue(fetchedEntry.isPresent()); fetchedEntry.get().clearField(StandardField.ABSTRACT); // Remove abstract due to copyright assertEquals(Optional.of(bibEntryIchikawa), fetchedEntry); } @Test public void testSearchByIDSari() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("26867355"); assertTrue(fetchedEntry.isPresent()); fetchedEntry.get().clearField(StandardField.ABSTRACT); // Remove abstract due to copyright assertEquals(Optional.of(bibEntrySari), fetchedEntry); } @Test public void testMultipleEntries() throws Exception { List<BibEntry> entryList = fetcher.performSearch("java"); entryList.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); // Remove abstract due to copyright); assertEquals(50, entryList.size()); } @Test public void testWithLuceneQueryAuthorDate() throws Exception { List<BibEntry> entryList = fetcher.performSearch("author:vigmond AND year:2021"); entryList.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); // Remove abstract due to copyright); assertEquals(18, entryList.size()); } @Test public void testWithLuceneQueryAuthorDateRange() throws Exception { List<BibEntry> entryList = fetcher.performSearch("author:vigmond AND year-range:2020-2021"); entryList.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); // Remove abstract due to copyright); assertEquals(28, entryList.size()); } @Test public void testInvalidSearchTerm() throws Exception { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("this.is.a.invalid.search.term.for.the.medline.fetcher")); } @Test public void testEmptyEntryList() throws Exception { List<BibEntry> entryList = fetcher.performSearch("java is fantastic and awesome "); assertEquals(Collections.emptyList(), entryList); } @Test public void testEmptyInput() throws Exception { assertEquals(Collections.emptyList(), fetcher.performSearch("")); } }
15,018
71.555556
2,914
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/MedraTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherException; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @FetcherTest public class MedraTest { private final Medra fetcher = new Medra(); private static Stream<Arguments> getDoiBibEntryPairs() { return Stream.of( Arguments.of("10.2143/TVF.80.3.3285690", Optional.of( new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "SPILEERS, Steven ") .withField(StandardField.PUBLISHER, "Peeters online journals") .withField(StandardField.TITLE, "Algemene kroniek") .withField(StandardField.YEAR, "2018") .withField(StandardField.DOI, "10.2143/TVF.80.3.3285690") .withField(StandardField.ISSN, "2031-8952, 2031-8952") .withField(StandardField.JOURNAL, "Tijdschrift voor Filosofie") .withField(StandardField.PAGES, "625-629") )), Arguments.of("10.3303/CET1977146", Optional.of( new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "" + "Iannarelli Riccardo and " + "Novello Anna and " + "Stricker Damien and " + "Cisternino Marco and " + "Gallizio Federico and " + "Telib Haysam and " + "Meyer Thierry ") .withField(StandardField.PUBLISHER, "AIDIC: Italian Association of Chemical Engineering") .withField(StandardField.TITLE, "Safety in research institutions: how to better communicate the risks using numerical simulations") .withField(StandardField.YEAR, "2019") .withField(StandardField.DOI, "10.3303/CET1977146") .withField(StandardField.JOURNAL, "Chemical Engineering Transactions") .withField(StandardField.PAGES, "871-876") .withField(StandardField.VOLUME, "77"))), Arguments.of("10.1400/115378", Optional.of( new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Paola Cisternino") .withField(StandardField.PUBLISHER, "Edizioni Otto Novecento") .withField(StandardField.TITLE, "Diagramma semantico dei lemmi : casa, parola, silenzio e attesa in È fatto giorno e Margherite e rosolacci di Rocco Scotellaro") .withField(StandardField.ISSN, "03912639") .withField(StandardField.YEAR, "1999") .withField(StandardField.DOI, "10.1400/115378") .withField(StandardField.JOURNAL, "Otto/Novecento : rivista quadrimestrale di critica e storia letteraria") )) ); } @Test public void testGetName() { assertEquals("mEDRA", fetcher.getName()); } @Test public void testPerformSearchEmptyDOI() throws FetcherException { assertEquals(Optional.empty(), fetcher.performSearchById("")); } @Test public void testPerformNonExistent() throws FetcherException { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("10.1016/j.bjoms.2007.08.004")); } @ParameterizedTest @MethodSource("getDoiBibEntryPairs") public void testDoiBibEntryPairs(String identifier, Optional<BibEntry> expected) throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById(identifier); assertEquals(expected, fetchedEntry); } }
5,209
53.270833
201
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/MrDLibFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.List; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.util.Version; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.MrDlibPreferences; 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; import static org.junit.jupiter.api.Assertions.assertFalse; @FetcherTest public class MrDLibFetcherTest { private MrDLibFetcher fetcher; @BeforeEach public void setUp() { MrDlibPreferences mrDlibPreferences = new MrDlibPreferences( true, false, false, false); fetcher = new MrDLibFetcher("", Version.parse(""), mrDlibPreferences); } @Test public void testPerformSearch() throws FetcherException { BibEntry bibEntry = new BibEntry(); bibEntry.setField(StandardField.TITLE, "lernen"); List<BibEntry> bibEntrys = fetcher.performSearch(bibEntry); assertFalse(bibEntrys.isEmpty()); } @Test public void testPerformSearchForHornecker2006() throws FetcherException { BibEntry bibEntry = new BibEntry(); bibEntry.setCitationKey("Hornecker:2006:GGT:1124772.1124838"); bibEntry.setField(StandardField.ADDRESS, "New York, NY, USA"); bibEntry.setField(StandardField.AUTHOR, "Hornecker, Eva and Buur, Jacob"); bibEntry.setField(StandardField.BOOKTITLE, "Proceedings of the SIGCHI Conference on Human Factors in Computing Systems"); bibEntry.setField(StandardField.DOI, "10.1145/1124772.1124838"); bibEntry.setField(StandardField.ISBN, "1-59593-372-7"); bibEntry.setField(StandardField.KEYWORDS, "CSCW,analysis,collaboration,design,framework,social interaction,tangible interaction,tangible interface"); bibEntry.setField(StandardField.PAGES, "437--446"); bibEntry.setField(StandardField.PUBLISHER, "ACM"); bibEntry.setField(StandardField.SERIES, "CHI '06"); bibEntry.setField(StandardField.TITLE, "{Getting a Grip on Tangible Interaction: A Framework on Physical Space and Social Interaction}"); bibEntry.setField(StandardField.URL, "http://doi.acm.org/10.1145/1124772.1124838"); bibEntry.setField(StandardField.YEAR, "2006"); List<BibEntry> bibEntrys = fetcher.performSearch(bibEntry); assertFalse(bibEntrys.isEmpty()); } @Test public void testGetName() { assertEquals("MDL_FETCHER", fetcher.getName()); } }
2,688
39.134328
157
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/OpenAccessDoiTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Optional; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; 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 OpenAccessDoiTest { private OpenAccessDoi finder; private BibEntry entry; @BeforeEach void setUp() { finder = new OpenAccessDoi(); entry = new BibEntry(); } @Test void findByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1038/nature12373"); assertEquals(Optional.of(new URL("https://dash.harvard.edu/bitstream/1/12285462/1/Nanometer-Scale%20Thermometry.pdf")), finder.findFullText(entry)); } @Test void notFoundByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1186/unknown-doi"); assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void entryWithoutDoi() throws IOException { assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void trustLevel() { assertEquals(TrustLevel.META_SEARCH, finder.getTrustLevel()); } }
1,341
25.84
156
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/PagedSearchFetcherTest.java
package org.jabref.logic.importer.fetcher; import org.jabref.logic.importer.PagedSearchBasedFetcher; import org.jabref.model.entry.BibEntry; import org.jabref.model.paging.Page; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; /** * This interface provides general test methods for paged fetchers */ public interface PagedSearchFetcherTest { /** * Ensure that different page return different entries */ @Test default void pageSearchReturnsUniqueResultsPerPage() throws Exception { String query = "Software"; Page<BibEntry> firstPage = getPagedFetcher().performSearchPaged(query, 0); Page<BibEntry> secondPage = getPagedFetcher().performSearchPaged(query, 1); for (BibEntry entry : firstPage.getContent()) { assertFalse(secondPage.getContent().contains(entry)); } } PagedSearchBasedFetcher getPagedFetcher(); }
947
28.625
83
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/PicaXmlParserTest.java
package org.jabref.logic.importer.fetcher; import java.io.InputStream; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.bibtex.BibEntryAssert; import org.jabref.logic.importer.fileformat.PicaXmlParser; 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.junit.jupiter.api.Assertions.assertNotNull; @FetcherTest public class PicaXmlParserTest { private void doTest(String xmlName, int expectedSize, List<String> resourceNames) throws Exception { try (InputStream is = PicaXmlParserTest.class.getResourceAsStream(xmlName)) { PicaXmlParser parser = new PicaXmlParser(); List<BibEntry> entries = parser.parseEntries(is); assertNotNull(entries); assertEquals(expectedSize, entries.size()); int i = 0; for (String resourceName : resourceNames) { BibEntryAssert.assertEquals(PicaXmlParserTest.class, resourceName, entries.get(i)); i++; } } } @Test public void emptyResult() throws Exception { doTest("gvk_empty_result_because_of_bad_query.xml", 0, Collections.emptyList()); } @Test public void resultFor797485368() throws Exception { doTest("gvk_result_for_797485368.xml", 1, Collections.singletonList("gvk_result_for_797485368.bib")); } @Test public void testGMP() throws Exception { doTest("gvk_gmp.xml", 2, Arrays.asList("gvk_gmp.1.bib", "gvk_gmp.2.bib")); } @Test public void subTitleTest() throws Exception { try (InputStream is = PicaXmlParserTest.class.getResourceAsStream("gvk_artificial_subtitle_test.xml")) { PicaXmlParser parser = new PicaXmlParser(); List<BibEntry> entries = parser.parseEntries(is); assertNotNull(entries); assertEquals(5, entries.size()); assertEquals(Optional.empty(), entries.get(0).getField(StandardField.SUBTITLE)); assertEquals(Optional.of("C"), entries.get(1).getField(StandardField.SUBTITLE)); assertEquals(Optional.of("Word"), entries.get(2).getField(StandardField.SUBTITLE)); assertEquals(Optional.of("Word1 word2"), entries.get(3).getField(StandardField.SUBTITLE)); assertEquals(Optional.of("Word1 word2"), entries.get(4).getField(StandardField.SUBTITLE)); } } }
2,627
37.647059
112
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/ResearchGateTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.jabref.logic.importer.fetcher.transformers.AbstractQueryTransformer.NO_EXPLICIT_FIELD; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @FetcherTest @DisabledOnCIServer("Blocked by Cloudflare") public class ResearchGateTest { private static final String URL_PDF = "https://www.researchgate.net/profile/Abdurrazzak-Gehani/publication/4207355_Paranoid_a_global_secure_file_access_control_system/links/5457747d0cf2cf516480995e/Paranoid-a-global-secure-file-access-control-system.pdf"; private final String URL_PAGE = "https://www.researchgate.net/publication/4207355_Paranoid_a_global_secure_file_access_control_system"; private ResearchGate fetcher; private BibEntry entry; @BeforeEach public void setUp() { fetcher = new ResearchGate(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); entry = new BibEntry(StandardEntryType.InProceedings); entry.setField(StandardField.DOI, "10.1109/CSAC.2005.42"); entry.setField(StandardField.TITLE, "Paranoid: a global secure file access control system"); } @Test @DisabledOnCIServer("CI server is unreliable") void fullTextFoundByDOI() throws IOException, FetcherException { assertEquals(Optional.of(new URL(URL_PDF)), fetcher.findFullText(entry)); } @Test @DisabledOnCIServer("CI server is unreliable") void fullTextNotFoundByDOI() throws IOException, FetcherException { BibEntry entry2 = new BibEntry().withField(StandardField.DOI, "10.1021/bk-2006-WWW.ch014"); assertEquals(Optional.empty(), fetcher.findFullText(entry2)); } @Test void getDocumentByTitle() throws IOException, NullPointerException { Optional<String> source = fetcher.getURLByString(entry.getTitle().get()); assertTrue(source.isPresent() && source.get().startsWith(URL_PAGE)); } @Test void getDocumentByDOI() throws IOException, NullPointerException { Optional<String> source = fetcher.getURLByDoi(entry.getDOI().get()); assertEquals(URL_PAGE, source.orElse("")); } @Test void trustLevel() { assertEquals(TrustLevel.META_SEARCH, fetcher.getTrustLevel()); } @Test void performSearchWithString() throws Exception { BibEntry master = new BibEntry(StandardEntryType.PhdThesis) .withCitationKey("phdthesis") .withField(StandardField.AUTHOR, "Diez, Tobias") .withField(StandardField.TITLE, "Slice theorem for Fréchet group actions and covariant symplectic field theory") .withField(StandardField.MONTH, "10") .withField(StandardField.YEAR, "2013"); List<BibEntry> fetchedEntries = fetcher.performSearch("Slice theorem for Fréchet group actions and covariant symplectic"); assertEquals(Optional.of(master), fetchedEntries.stream().findFirst()); } @Test void performSearchWithLuceneQuery() throws Exception { BibEntry master = new BibEntry(StandardEntryType.Article) .withCitationKey("article") .withField(StandardField.TITLE, "Wine Microbiology and Predictive Microbiology: " + "A Short Overview on Application, and Perspectives") .withField(StandardField.DOI, "10.3390/microorganisms10020421") .withField(StandardField.JOURNAL, "Microorganisms") .withField(StandardField.MONTH, "02") .withField(StandardField.PAGES, "421") .withField(StandardField.VOLUME, "10") .withField(StandardField.YEAR, "2022") .withField(StandardField.AUTHOR, "Petruzzi, Leonardo and Campaniello, Daniela and Corbo," + " Maria and Speranza, Barbara and Altieri, Clelia and Sinigaglia, Milena and Bevilacqua, Antonio"); QueryNode queryNode = new StandardSyntaxParser().parse("Wine Microbiology and Predictive " + "Microbiology: A Short Overview on Application, and Perspectives", NO_EXPLICIT_FIELD); assertEquals(Optional.of(master), fetcher.performSearch(queryNode).stream().findFirst()); } @Test void performSearchWithBibEntry() throws FetcherException { BibEntry entryZaffar = new BibEntry(StandardEntryType.InProceedings) .withCitationKey("inproceedings") .withField(StandardField.ISBN, "0-7695-2461-3") .withField(StandardField.TITLE, "Looking Back at the Bell-La Padula Model") .withField(StandardField.MONTH, "01") .withField(StandardField.PAGES, "15 pp. - 351") .withField(StandardField.DOI, "10.1109/CSAC.2005.37") .withField(StandardField.VOLUME, "2005") .withField(StandardField.YEAR, "2006") .withField(StandardField.JOURNAL, "Proceedings - Annual Computer Security Applications Conference, ACSAC") .withField(StandardField.AUTHOR, "Bell, D.E."); assertEquals(Optional.of(entryZaffar), fetcher.performSearch(entryZaffar).stream().findFirst()); } @Test @DisabledOnCIServer("CI server is unreliable") void performSearchWithTitleWithCurlyBraces() throws FetcherException { BibEntry entryInput = new BibEntry(StandardEntryType.Misc) .withField(StandardField.TITLE, "Communicating {COVID}-19 against the backdrop of conspiracy ideologies: {HOW} {PUBLIC} {FIGURES} {DISCUSS} {THE} {MATTER} {ON} {FACEBOOK} {AND} {TELEGRAM}"); Optional<BibEntry> expected = Optional.of(new BibEntry(new UnknownEntryType("unknown")) .withCitationKey("unknown") .withField(StandardField.TITLE, "Communicating COVID-19 against the backdrop of conspiracy ideologies: HOW PUBLIC FIGURES DISCUSS THE MATTER ON FACEBOOK AND TELEGRAM") .withField(StandardField.MONTH, "05") .withField(StandardField.YEAR, "2021") .withField(StandardField.AUTHOR, "Hohlfeld, Ralf and Bauerfeind, Franziska and Braglia, Ilenia and Butt, Aqib and Dietz, Anna-Lena and Drexel, Denise and Fedlmeier, Julia and Fischer, Lana and Gandl, Vanessa and Glaser, Felia and Haberzettel, Eva and Helling, Teresa and Käsbauer, Isabel and Kast, Matthias and Krieger, Anja and Lächner, Anja and Malkanova, Adriana and Raab, Marie-Kristin and Rech, Anastasia and Weymar, Pia") .withField(StandardField.DOI, "10.13140/RG.2.2.36822.78406")); Optional<BibEntry> actual = fetcher.performSearch(entryInput) .stream().findFirst(); assertEquals(expected, actual); } }
7,596
52.5
443
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/RfcFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; 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; @FetcherTest public class RfcFetcherTest { private RfcFetcher fetcher = new RfcFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); private BibEntry bibEntry = new BibEntry(StandardEntryType.Misc) .withCitationKey("rfc1945") .withField(StandardField.SERIES, "Request for Comments") .withField(StandardField.NUMBER, "1945") .withField(StandardField.HOWPUBLISHED, "RFC 1945") .withField(StandardField.PUBLISHER, "RFC Editor") .withField(StandardField.DOI, "10.17487/RFC1945") .withField(StandardField.URL, "https://www.rfc-editor.org/info/rfc1945") .withField(StandardField.AUTHOR, "Henrik Nielsen and Roy T. Fielding and Tim Berners-Lee") .withField(StandardField.TITLE, "{Hypertext Transfer Protocol -- HTTP/1.0}") .withField(StandardField.PAGETOTAL, "60") .withField(StandardField.YEAR, "1996") .withField(StandardField.MONTH, "#may#") .withField(StandardField.ABSTRACT, "The Hypertext Transfer Protocol (HTTP) is an application-level protocol with the lightness and speed necessary for distributed, collaborative, hypermedia information systems. This memo provides information for the Internet community. This memo does not specify an Internet standard of any kind."); @Test public void getNameReturnsEqualIdName() { assertEquals("RFC", fetcher.getName()); } @Test public void performSearchByIdFindsEntryWithDraftIdentifier() throws Exception { BibEntry bibDraftEntry = new BibEntry(StandardEntryType.TechReport) .withField(InternalField.KEY_FIELD, "fielding-http-spec-01") .withField(StandardField.AUTHOR, "Henrik Nielsen and Roy T. Fielding and Tim Berners-Lee") .withField(StandardField.DAY, "20") .withField(StandardField.INSTITUTION, "Internet Engineering Task Force") .withField(StandardField.MONTH, "#dec#") .withField(StandardField.NOTE, "Work in Progress") .withField(StandardField.NUMBER, "draft-fielding-http-spec-01") .withField(StandardField.PAGETOTAL, "41") .withField(StandardField.PUBLISHER, "Internet Engineering Task Force") .withField(StandardField.TITLE, "{Hypertext Transfer Protocol -- HTTP/1.0}") .withField(StandardField.TYPE, "Internet-Draft") .withField(StandardField.URL, "https://datatracker.ietf.org/doc/draft-fielding-http-spec/01/") .withField(StandardField.YEAR, "1994") .withField(StandardField.ABSTRACT, "The Hypertext Transfer Protocol (HTTP) is an application-level protocol with the lightness and speed necessary for distributed, collaborative, hypermedia information systems. It is a generic, stateless, object-oriented protocol which can be used for many tasks, such as name servers and distributed object management systems, through extension of its request methods (commands). A feature of HTTP is the typing and negotiation of data representation, allowing systems to be built independently of the data being transferred. HTTP has been in use by the World-Wide Web global information initiative since 1990. This specification reflects preferred usage of the protocol referred to as 'HTTP/1.0', and is compatible with the most commonly used HTTP server and client programs implemented prior to November 1994."); bibDraftEntry.setCommentsBeforeEntry("%% You should probably cite draft-ietf-http-v10-spec instead of this I-D.\n"); assertEquals(Optional.of(bibDraftEntry), fetcher.performSearchById("draft-fielding-http-spec")); } @ParameterizedTest @CsvSource({"rfc1945", "RFC1945", "1945"}) public void performSearchByIdFindsEntry(String identifier) throws Exception { assertEquals(Optional.of(bibEntry), fetcher.performSearchById(identifier)); } @Test public void performSearchByIdFindsNothingWithoutIdentifier() throws Exception { assertEquals(Optional.empty(), fetcher.performSearchById("")); } @ParameterizedTest @CsvSource({ // syntactically valid identifier "draft-test-draft-spec", "RFC9999", // invalid identifier "banana"}) public void performSearchByIdFindsNothingWithValidDraftIdentifier(String identifier) throws Exception { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById(identifier)); } }
5,337
58.311111
865
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/ScienceDirectTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Optional; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.support.DisabledOnCIServer; 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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest class ScienceDirectTest { private final ImporterPreferences importerPreferences = mock(ImporterPreferences.class); private ScienceDirect finder; private BibEntry entry; @BeforeEach void setUp() { when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); finder = new ScienceDirect(importerPreferences); entry = new BibEntry(); } @Test @DisabledOnCIServer("CI server is blocked") void findByDoiOldPage() throws IOException { entry.setField(StandardField.DOI, "10.1016/j.jrmge.2015.08.004"); assertEquals( Optional.of(new URL("https://www.sciencedirect.com/science/article/pii/S1674775515001079/pdfft?md5=2b19b19a387cffbae237ca6a987279df&pid=1-s2.0-S1674775515001079-main.pdf")), finder.findFullText(entry) ); } @Test @DisabledOnCIServer("CI server is blocked") void findByDoiNewPage() throws IOException { entry.setField(StandardField.DOI, "10.1016/j.aasri.2014.09.002"); assertEquals( Optional.of(new URL("https://www.sciencedirect.com/science/article/pii/S2212671614001024/pdf?md5=4e2e9a369b4d5b3db5100aba599bef8b&pid=1-s2.0-S2212671614001024-main.pdf")), finder.findFullText(entry) ); } @Test @DisabledOnCIServer("CI server is blocked") void findByDoiWorksForBoneArticle() throws IOException { // The DOI is an example by a user taken from https://github.com/JabRef/jabref/issues/5860 entry.setField(StandardField.DOI, "https://doi.org/10.1016/j.bone.2020.115226"); assertEquals( Optional.of(new URL("https://www.sciencedirect.com/science/article/pii/S8756328220300065/pdfft?md5=0ad75ff155637dec358e5c9fb8b90afd&pid=1-s2.0-S8756328220300065-main.pdf")), finder.findFullText(entry) ); } @Test @DisabledOnCIServer("CI server is blocked") void notFoundByDoi() throws IOException { entry.setField(StandardField.DOI, "10.1016/j.aasri.2014.0559.002"); assertEquals(Optional.empty(), finder.findFullText(entry)); } }
2,792
34.807692
189
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/SearchBasedFetcherCapabilityTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.StringJoiner; import java.util.stream.Collectors; import org.jabref.logic.importer.ImportCleanup; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.Assertions; 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; /** * Defines the set of capability tests that each tests a given search capability, e.g. author based search. * The idea is to code the capabilities of a fetcher into Java code. * This way, a) the capabilities of a fetcher are checked automatically (because they can change from time-to-time by the provider) * and b) the queries sent to the fetchers can be debugged directly without a route through to some fetcher code. */ interface SearchBasedFetcherCapabilityTest { /** * Test whether the library API supports author field search. */ @Test default void supportsAuthorSearch() throws Exception { StringJoiner queryBuilder = new StringJoiner("\" AND author:\"", "author:\"", "\""); getTestAuthors().forEach(queryBuilder::add); List<BibEntry> result = getFetcher().performSearch(queryBuilder.toString()); new ImportCleanup(BibDatabaseMode.BIBTEX).doPostCleanup(result); assertFalse(result.isEmpty()); result.forEach(bibEntry -> { String author = bibEntry.getField(StandardField.AUTHOR).orElse(""); // The co-authors differ, thus we check for the author present at all papers getTestAuthors().forEach(expectedAuthor -> Assertions.assertTrue(author.contains(expectedAuthor.replace("\"", "")))); }); } /** * Test whether the library API supports year field search. */ @Test default void supportsYearSearch() throws Exception { List<BibEntry> result = getFetcher().performSearch("year:" + getTestYear()); new ImportCleanup(BibDatabaseMode.BIBTEX).doPostCleanup(result); List<String> differentYearsInResult = result.stream() .map(bibEntry -> bibEntry.getField(StandardField.YEAR)) .filter(Optional::isPresent) .map(Optional::get) .distinct() .collect(Collectors.toList()); assertEquals(Collections.singletonList(getTestYear().toString()), differentYearsInResult); } /** * Test whether the library API supports year range search. */ @Test default void supportsYearRangeSearch() throws Exception { List<String> yearsInYearRange = List.of("2018", "2019", "2020"); List<BibEntry> result = getFetcher().performSearch("year-range:2018-2020"); new ImportCleanup(BibDatabaseMode.BIBTEX).doPostCleanup(result); List<String> differentYearsInResult = result.stream() .map(bibEntry -> bibEntry.getField(StandardField.YEAR)) .filter(Optional::isPresent) .map(Optional::get) .distinct() .collect(Collectors.toList()); assertFalse(result.isEmpty()); assertTrue(yearsInYearRange.containsAll(differentYearsInResult)); } /** * Test whether the library API supports journal based search. * * WARNING: the error while merging information from user-assigned DOI (more specifically, "10.1016/j.geomphys.2012.09.009") * is related to a failed read by the Bibtex Parser (title is formatted in a weird way) */ @Test default void supportsJournalSearch() throws Exception { List<BibEntry> result = getFetcher().performSearch("journal:\"" + getTestJournal() + "\""); new ImportCleanup(BibDatabaseMode.BIBTEX).doPostCleanup(result); assertFalse(result.isEmpty()); result.forEach(bibEntry -> { assertTrue(bibEntry.hasField(StandardField.JOURNAL)); String journal = bibEntry.getField(StandardField.JOURNAL).orElse(""); assertTrue(journal.contains(getTestJournal().replace("\"", ""))); }); } SearchBasedFetcher getFetcher(); List<String> getTestAuthors(); String getTestJournal(); default Integer getTestYear() { return 2016; } }
4,922
41.808696
131
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/SemanticScholarTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.PagedSearchBasedFetcher; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.support.DisabledOnCIServer; import org.jabref.testutils.category.FetcherTest; import org.apache.lucene.queryparser.flexible.core.QueryNodeParseException; import org.apache.lucene.queryparser.flexible.core.parser.SyntaxParser; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @FetcherTest public class SemanticScholarTest implements PagedSearchFetcherTest { private static final String DOI = "10.23919/IFIPNetworking52078.2021.9472772"; private final BibEntry IGOR_NEWCOMERS = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Igor Steinmacher and T. Conte and Christoph Treude and M. Gerosa") .withField(StandardField.YEAR, "2016") .withField(StandardField.DOI, "10.1145/2884781.2884806") .withField(StandardField.TITLE, "Overcoming Open Source Project Entry Barriers with a Portal for Newcomers") .withField(StandardField.URL, "https://www.semanticscholar.org/paper/4bea2b4029a895bf898701329409e5a784fc2090") .withField(StandardField.VENUE, "International Conference on Software Engineering"); private SemanticScholar fetcher; private BibEntry entry; @BeforeEach void setUp() { fetcher = new SemanticScholar(); entry = new BibEntry(); } @Test void getDocument() throws IOException, FetcherException { String source = fetcher.getURLBySource( String.format("https://api.semanticscholar.org/v1/paper/%s", DOI)); assertEquals("https://www.semanticscholar.org/paper/7f7b38604a2c167f6d5fb1c5dffcbb127d0525c0", source); } @Test @DisabledOnCIServer("CI server is unreliable") void fullTextFindByDOI() throws IOException, FetcherException { entry.withField(StandardField.DOI, "10.1038/nrn3241"); assertEquals( Optional.of(new URL("https://europepmc.org/articles/pmc4907333?pdf=render")), fetcher.findFullText(entry) ); } @Test @DisabledOnCIServer("CI server is unreliable") void fullTextFindByDOIAlternate() throws IOException, FetcherException { assertEquals( Optional.of(new URL("https://pdfs.semanticscholar.org/7f6e/61c254bc2df38a784c1228f56c13317caded.pdf")), fetcher.findFullText(new BibEntry() .withField(StandardField.DOI, "10.3390/healthcare9020206"))); } @Test @DisabledOnCIServer("CI server is unreliable") void fullTextSearchOnEmptyEntry() throws IOException, FetcherException { assertEquals(Optional.empty(), fetcher.findFullText(new BibEntry())); } @Test @DisabledOnCIServer("CI server is unreliable") void fullTextNotFoundByDOI() throws IOException, FetcherException { entry = new BibEntry().withField(StandardField.DOI, DOI); entry.setField(StandardField.DOI, "10.1021/bk-2006-WWW.ch014"); assertEquals(Optional.empty(), fetcher.findFullText(entry)); } @Test @DisabledOnCIServer("CI server is unreliable") void fullTextFindByArXiv() throws IOException, FetcherException { entry = new BibEntry().withField(StandardField.EPRINT, "1407.3561") .withField(StandardField.ARCHIVEPREFIX, "arXiv"); assertEquals( Optional.of(new URL("https://arxiv.org/pdf/1407.3561.pdf")), fetcher.findFullText(entry) ); } @Test void fullTextEntityWithoutDoi() throws IOException, FetcherException { assertEquals(Optional.empty(), fetcher.findFullText(new BibEntry())); } @Test void trustLevel() { assertEquals(TrustLevel.META_SEARCH, fetcher.getTrustLevel()); } @Override public PagedSearchBasedFetcher getPagedFetcher() { return fetcher; } @Test void getURLForQueryWithLucene() throws QueryNodeParseException, MalformedURLException, FetcherException, URISyntaxException { String query = "Software engineering"; SyntaxParser parser = new StandardSyntaxParser(); URL url = fetcher.getURLForQuery(parser.parse(query, "default"), 0); assertEquals("https://api.semanticscholar.org/graph/v1/paper/search?query=Software+engineering&offset=0&limit=20&fields=paperId%2CexternalIds%2Curl%2Ctitle%2Cabstract%2Cvenue%2Cyear%2Cauthors", url.toString()); } @Test void searchByQueryFindsEntry() throws Exception { BibEntry master = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Tobias Diez") .withField(StandardField.TITLE, "Slice theorem for Fréchet group actions and covariant symplectic field theory") .withField(StandardField.YEAR, "2014") .withField(StandardField.EPRINT, "1405.2249") .withField(StandardField.EPRINTTYPE, "arXiv") .withField(StandardField.URL, "https://www.semanticscholar.org/paper/4986c1060236e7190b63f934df7806fbf2056cec"); List<BibEntry> fetchedEntries = fetcher.performSearch("Slice theorem for Fréchet group actions and covariant symplectic"); // Abstract should not be included in JabRef tests fetchedEntries.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); assertEquals(Collections.singletonList(master), fetchedEntries); } @Test void searchByPlainQueryFindsEntry() throws Exception { List<BibEntry> fetchedEntries = fetcher.performSearch("Overcoming Open Source Project Entry Barriers with a Portal for Newcomers"); // Abstract should not be included in JabRef tests fetchedEntries.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); assertEquals(Collections.singletonList(IGOR_NEWCOMERS), fetchedEntries); } @Test void searchByQuotedQueryFindsEntry() throws Exception { List<BibEntry> fetchedEntries = fetcher.performSearch("\"Overcoming Open Source Project Entry Barriers with a Portal for Newcomers\""); // Abstract should not be included in JabRef tests fetchedEntries.forEach(entry -> entry.clearField(StandardField.ABSTRACT)); assertEquals(Collections.singletonList(IGOR_NEWCOMERS), fetchedEntries); } @Test public void performSearchByEmptyQuery() throws Exception { assertEquals(Collections.emptyList(), fetcher.performSearch("")); } @Test public void findByEntry() throws Exception { BibEntry barrosEntry = new BibEntry(StandardEntryType.Article) .withField(StandardField.TITLE, "Formalising BPMN Service Interaction Patterns") .withField(StandardField.AUTHOR, "Chiara Muzi and Luise Pufahl and Lorenzo Rossi and M. Weske and F. Tiezzi") .withField(StandardField.YEAR, "2018") .withField(StandardField.DOI, "10.1007/978-3-030-02302-7_1") .withField(StandardField.URL, "https://www.semanticscholar.org/paper/3bb026fd67db7d8e0e25de3189d6b7031b12783e") .withField(StandardField.VENUE, "The Practice of Enterprise Modeling"); entry.withField(StandardField.TITLE, "Formalising BPMN Service Interaction Patterns"); BibEntry actual = fetcher.performSearch(entry).get(0); // Abstract should not be included in JabRef tests actual.clearField(StandardField.ABSTRACT); assertEquals(barrosEntry, actual); } @Test @Override @DisabledOnCIServer("Unstable on CI") public void pageSearchReturnsUniqueResultsPerPage() throws Exception { // Implementation is done in the interface } }
8,290
43.575269
218
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/SpringerFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import java.util.Optional; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.PagedSearchBasedFetcher; import org.jabref.logic.importer.SearchBasedFetcher; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import kong.unirest.json.JSONObject; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest class SpringerFetcherTest implements SearchBasedFetcherCapabilityTest, PagedSearchFetcherTest { ImporterPreferences importerPreferences = mock(ImporterPreferences.class); SpringerFetcher fetcher; @BeforeEach void setUp() { when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); fetcher = new SpringerFetcher(importerPreferences); } @Test void searchByQueryFindsEntry() throws Exception { BibEntry firstArticle = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Steinmacher, Igor and Balali, Sogol and Trinkenreich, Bianca and Guizani, Mariam and Izquierdo-Cortazar, Daniel and Cuevas Zambrano, Griselda G. and Gerosa, Marco Aurelio and Sarma, Anita") .withField(StandardField.DATE, "2021-09-09") .withField(StandardField.DOI, "10.1186/s13174-021-00140-z") .withField(StandardField.ISSN, "1867-4828") .withField(StandardField.JOURNAL, "Journal of Internet Services and Applications") .withField(StandardField.MONTH, "#sep#") .withField(StandardField.PAGES, "1--33") .withField(StandardField.NUMBER, "1") .withField(StandardField.VOLUME, "12") .withField(StandardField.PUBLISHER, "Springer") .withField(StandardField.TITLE, "Being a Mentor in open source projects") .withField(StandardField.YEAR, "2021") .withField(StandardField.FILE, ":https\\://www.biomedcentral.com/openurl/pdf?id=doi\\:10.1186/s13174-021-00140-z:PDF") .withField(StandardField.ABSTRACT, "Mentoring is a well-known way to help newcomers to Open Source Software (OSS) projects overcome initial contribution barriers. Through mentoring, newcomers learn to acquire essential technical, social, and organizational skills. Despite the importance of OSS mentors, they are understudied in the literature. Understanding who OSS project mentors are, the challenges they face, and the strategies they use can help OSS projects better support mentors’ work. In this paper, we employ a two-stage study to comprehensively investigate mentors in OSS. First, we identify the characteristics of mentors in the Apache Software Foundation, a large OSS community, using an online survey. We found that less experienced volunteer contributors are less likely to take on the mentorship role. Second, through interviews with OSS mentors (n=18), we identify the challenges that mentors face and how they mitigate them. In total, we identified 25 general mentorship challenges and 7 sub-categories of challenges regarding task recommendation. We also identified 13 strategies to overcome the challenges related to task recommendation. Our results provide insights for OSS communities, formal mentorship programs, and tool builders who design automated support for task assignment and internship."); BibEntry secondArticle = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Steinmacher, Igor and Gerosa, Marco and Conte, Tayana U. and Redmiles, David F.") .withField(StandardField.DATE, "2019-04-15") .withField(StandardField.DOI, "10.1007/s10606-018-9335-z") .withField(StandardField.ISSN, "0925-9724") .withField(StandardField.JOURNAL, "Computer Supported Cooperative Work (CSCW)") .withField(StandardField.MONTH, "#apr#") .withField(StandardField.PAGES, "247--290") .withField(StandardField.NUMBER, "1-2") .withField(StandardField.VOLUME, "28") .withField(StandardField.PUBLISHER, "Springer") .withField(StandardField.TITLE, "Overcoming Social Barriers When Contributing to Open Source Software Projects") .withField(StandardField.YEAR, "2019") .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/s10606-018-9335-z:PDF") .withField(StandardField.ABSTRACT, "An influx of newcomers is critical to the survival, long-term success, and continuity of many Open Source Software (OSS) community-based projects. However, newcomers face many barriers when making their first contribution, leading in many cases to dropouts. Due to the collaborative nature of community-based OSS projects, newcomers may be susceptible to social barriers, such as communication breakdowns and reception issues. In this article, we report a two-phase study aimed at better understanding social barriers faced by newcomers. In the first phase, we qualitatively analyzed the literature and data collected from practitioners to identify barriers that hinder newcomers’ first contribution. We designed a model composed of 58 barriers, including 13 social barriers. In the second phase, based on the barriers model, we developed FLOSScoach, a portal to support newcomers making their first contribution. We evaluated the portal in a diary-based study and found that the portal guided the newcomers and reduced the need for communication. Our results provide insights for communities that want to support newcomers and lay a foundation for building better onboarding tools. The contributions of this paper include identifying and gathering empirical evidence of social barriers faced by newcomers; understanding how social barriers can be reduced or avoided by using a portal that organizes proper information for newcomers (FLOSScoach); presenting guidelines for communities and newcomers on how to reduce or avoid social barriers; and identifying new streams of research."); BibEntry thirdArticle = new BibEntry(StandardEntryType.InCollection) .withField(StandardField.AUTHOR, "Serrano Alves, Luiz Philipe and Wiese, Igor Scaliante and Chaves, Ana Paula and Steinmacher, Igor") .withField(StandardField.BOOKTITLE, "Chatbot Research and Design") .withField(StandardField.DATE, "2022-01-01") .withField(StandardField.DOI, "10.1007/978-3-030-94890-0_6") .withField(StandardField.ISBN, "978-3-030-94889-4") .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/978-3-030-94890-0_6:PDF") .withField(StandardField.MONTH, "#jan#") .withField(StandardField.PUBLISHER, "Springer") .withField(StandardField.YEAR, "2022") .withField(StandardField.TITLE, "How to Find My Task? Chatbot to Assist Newcomers in Choosing Tasks in OSS Projects") .withField(StandardField.ABSTRACT, "Open Source Software (OSS) is making a meteoric rise in the software industry since several big companies have entered this market. Unfortunately, newcomers enter these projects and usually lose interest in contributing because of several factors. This paper aims to reduce the problems users face when they walk their first steps into OSS projects: finding the appropriate task. This paper presents a chatbot that filters tasks to help newcomers choose a task that fits their skills. We performed a quantitative and a qualitative study comparing the chatbot with the current GitHub issue tracker interface, which uses labels to categorize and identify tasks. The results show that users perceived the chatbot as easier to use than the GitHub issue tracker. Additionally, users tend to interpret the use of chatbots as situational, helping mainly newcomers and inexperienced contributors."); BibEntry fourthArticle = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Calefato, Fabio and Gerosa, Marco Aurélio and Iaffaldano, Giuseppe and Lanubile, Filippo and Steinmacher, Igor") .withField(StandardField.DATE, "2022-03-19") .withField(StandardField.DOI, "10.1007/s10664-021-10012-6") .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/s10664-021-10012-6:PDF") .withField(StandardField.ISSN, "1382-3256") .withField(StandardField.JOURNAL, "Empirical Software Engineering") .withField(StandardField.MONTH, "#mar#") .withField(StandardField.NUMBER, "3") .withField(StandardField.PAGES, "1--41") .withField(StandardField.PUBLISHER, "Springer") .withField(StandardField.TITLE, "Will you come back to contribute? Investigating the inactivity of OSS core developers in GitHub") .withField(StandardField.VOLUME, "27") .withField(StandardField.YEAR, "2022") .withField(StandardField.ABSTRACT, "Several Open-Source Software (OSS) projects depend on the continuity of their development communities to remain sustainable. Understanding how developers become inactive or why they take breaks can help communities prevent abandonment and incentivize developers to come back. In this paper, we propose a novel method to identify developers’ inactive periods by analyzing the individual rhythm of contributions to the projects. Using this method, we quantitatively analyze the inactivity of core developers in 18 OSS organizations hosted on GitHub. We also survey core developers to receive their feedback about the identified breaks and transitions. Our results show that our method was effective for identifying developers’ breaks. About 94% of the surveyed core developers agreed with our state model of inactivity; 71% and 79% of them acknowledged their breaks and state transition, respectively. We also show that all core developers take breaks (at least once) and about a half of them (~45%) have completely disengaged from a project for at least one year. We also analyzed the probability of transitions to/from inactivity and found that developers who pause their activity have a ~35 to ~55% chance to return to an active state; yet, if the break lasts for a year or longer, then the probability of resuming activities drops to ~21–26%, with a ~54% chance of complete disengagement. These results may support the creation of policies and mechanisms to make OSS community managers aware of breaks and potential project abandonment."); List<BibEntry> fetchedEntries = fetcher.performSearch("JabRef Social Barriers Steinmacher"); assertEquals(List.of(fourthArticle, thirdArticle, firstArticle, secondArticle), fetchedEntries); } @Test void testSpringerJSONToBibtex() { String jsonString = """ {\r "identifier":"doi:10.1007/BF01201962",\r "title":"Book reviews",\r "publicationName":"World Journal of Microbiology & Biotechnology",\r "issn":"1573-0972",\r "isbn":"",\r "doi":"10.1007/BF01201962",\r "publisher":"Springer",\r "publicationDate":"1992-09-01",\r "volume":"8",\r "number":"5",\r "startingPage":"550",\r "url":"http://dx.doi.org/10.1007/BF01201962","copyright":"©1992 Rapid Communications of Oxford Ltd."\r }"""; JSONObject jsonObject = new JSONObject(jsonString); BibEntry bibEntry = SpringerFetcher.parseSpringerJSONtoBibtex(jsonObject); assertEquals(Optional.of("1992"), bibEntry.getField(StandardField.YEAR)); assertEquals(Optional.of("5"), bibEntry.getField(StandardField.NUMBER)); assertEquals(Optional.of("#sep#"), bibEntry.getField(StandardField.MONTH)); assertEquals(Optional.of("10.1007/BF01201962"), bibEntry.getField(StandardField.DOI)); assertEquals(Optional.of("8"), bibEntry.getField(StandardField.VOLUME)); assertEquals(Optional.of("Springer"), bibEntry.getField(StandardField.PUBLISHER)); assertEquals(Optional.of("1992-09-01"), bibEntry.getField(StandardField.DATE)); } @Test void searchByEmptyQueryFindsNothing() throws Exception { assertEquals(Collections.emptyList(), fetcher.performSearch("")); } @Test @Disabled("Year search is currently broken, because the API returns mutliple years.") @Override public void supportsYearSearch() { } @Test @Disabled("Year range search is not natively supported by the API, but can be emulated by multiple single year searches.") @Override public void supportsYearRangeSearch() { } @Test public void supportsPhraseSearch() throws Exception { // Normal search should match due to Redmiles, Elissa M., phrase search on the other hand should not find it. BibEntry expected = new BibEntry(StandardEntryType.InCollection) .withField(StandardField.AUTHOR, "Booth, Kayla M. and Dosono, Bryan and Redmiles, Elissa M. and Morales, Miraida and Depew, Michael and Farzan, Rosta and Herman, Everett and Trahan, Keith and Tananis, Cindy") .withField(StandardField.DATE, "2018-01-01") .withField(StandardField.DOI, "10.1007/978-3-319-78105-1_75") .withField(StandardField.ISBN, "978-3-319-78104-4") .withField(StandardField.MONTH, "#jan#") .withField(StandardField.PUBLISHER, "Springer") .withField(StandardField.BOOKTITLE, "Transforming Digital Worlds") .withField(StandardField.TITLE, "Diversifying the Next Generation of Information Scientists: Six Years of Implementation and Outcomes for a Year-Long REU Program") .withField(StandardField.YEAR, "2018") .withField(StandardField.FILE, ":http\\://link.springer.com/openurl/pdf?id=doi\\:10.1007/978-3-319-78105-1_75:PDF") .withField(StandardField.ABSTRACT, "The iSchool Inclusion Institute (i3) is a Research Experience for Undergraduates (REU) program in the US designed to address underrepresentation in the information sciences. i3 is a year-long, cohort-based program that prepares undergraduate students for graduate school in information science and is rooted in a research and leadership development curriculum. Using data from six years of i3 cohorts, we present in this paper a qualitative and quantitative evaluation of the program in terms of student learning, research production, and graduate school enrollment. We find that students who participate in i3 report significant learning gains in information-science- and graduate-school-related areas and that 52% of i3 participants enroll in graduate school, over 2 $$\\times $$ × the national average. Based on these and additional results, we distill recommendations for future implementations of similar programs to address underrepresentation in information science."); List<BibEntry> resultPhrase = fetcher.performSearch("author:\"Redmiles David\""); List<BibEntry> result = fetcher.performSearch("author:Redmiles David"); // Phrase search should be a subset of the normal search result. Assertions.assertTrue(result.containsAll(resultPhrase)); result.removeAll(resultPhrase); Assertions.assertEquals(Collections.singletonList(expected), result); } @Test public void supportsBooleanANDSearch() throws Exception { List<BibEntry> resultJustByAuthor = fetcher.performSearch("author:\"Redmiles, David\""); List<BibEntry> result = fetcher.performSearch("author:\"Redmiles, David\" AND journal:\"Computer Supported Cooperative Work\""); Assertions.assertTrue(resultJustByAuthor.containsAll(result)); List<BibEntry> allEntriesFromCSCW = result.stream() .filter(bibEntry -> "Computer Supported Cooperative Work (CSCW)" .equals(bibEntry.getField(StandardField.JOURNAL) .orElse(""))) .toList(); allEntriesFromCSCW.stream() .map(bibEntry -> bibEntry.getField(StandardField.AUTHOR)) .filter(Optional::isPresent) .map(Optional::get).forEach(authorField -> assertTrue(authorField.contains("Redmiles"))); } @Override public SearchBasedFetcher getFetcher() { return fetcher; } @Override public List<String> getTestAuthors() { return List.of("Steinmacher, Igor", "Gerosa, Marco", "Conte, Tayana U."); } @Override public String getTestJournal() { return "Clinical Research in Cardiology"; } @Override public PagedSearchBasedFetcher getPagedFetcher() { return fetcher; } }
17,820
81.888372
1,637
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/SpringerLinkTest.java
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Optional; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.support.DisabledOnCIServer; 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; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest public class SpringerLinkTest { private final ImporterPreferences importerPreferences = mock(ImporterPreferences.class); private SpringerLink finder; private BibEntry entry; @BeforeEach public void setUp() { when(importerPreferences.getApiKeys()).thenReturn(FXCollections.emptyObservableSet()); finder = new SpringerLink(importerPreferences); entry = new BibEntry(); } @Test public void rejectNullParameter() { assertThrows(NullPointerException.class, () -> finder.findFullText(null)); } @Test public void doiNotPresent() throws IOException { assertEquals(Optional.empty(), finder.findFullText(entry)); } @DisabledOnCIServer("Disable on CI Server to not hit the API call limit") @Test public void findByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1186/s13677-015-0042-8"); assertEquals( Optional.of(new URL("http://link.springer.com/content/pdf/10.1186/s13677-015-0042-8.pdf")), finder.findFullText(entry)); } @DisabledOnCIServer("Disable on CI Server to not hit the API call limit") @Test public void notFoundByDOI() throws IOException { entry.setField(StandardField.DOI, "10.1186/unknown-doi"); assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void entityWithoutDoi() throws IOException { assertEquals(Optional.empty(), finder.findFullText(entry)); } @Test void trustLevel() { assertEquals(TrustLevel.PUBLISHER, finder.getTrustLevel()); } }
2,314
30.283784
107
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest public class TitleFetcherTest { private TitleFetcher fetcher; private BibEntry bibEntryBischof2009; @BeforeEach public void setUp() { fetcher = new TitleFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); bibEntryBischof2009 = new BibEntry(); bibEntryBischof2009.setType(StandardEntryType.InProceedings); bibEntryBischof2009.setCitationKey("Bischof_2009"); bibEntryBischof2009.setField(StandardField.AUTHOR, "Marc Bischof and Oliver Kopp and Tammo van Lessen and Frank Leymann"); bibEntryBischof2009.setField(StandardField.BOOKTITLE, "2009 35th Euromicro Conference on Software Engineering and Advanced Applications"); bibEntryBischof2009.setField(StandardField.PUBLISHER, "{IEEE}"); bibEntryBischof2009.setField(StandardField.TITLE, "{BPELscript}: A Simplified Script Syntax for {WS}-{BPEL} 2.0"); bibEntryBischof2009.setField(StandardField.YEAR, "2009"); bibEntryBischof2009.setField(StandardField.MONTH, "aug"); bibEntryBischof2009.setField(StandardField.DOI, "10.1109/seaa.2009.21"); } @Test public void testGetName() { assertEquals("Title", fetcher.getName()); } @Test public void testPerformSearchKopp2007() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("BPELscript: A simplified script syntax for WS-BPEL 2.0"); assertEquals(Optional.of(bibEntryBischof2009), fetchedEntry); } @Test public void testPerformSearchEmptyTitle() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById(""); assertEquals(Optional.empty(), fetchedEntry); } @Test public void testPerformSearchInvalidTitle() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("An unknown title where noi DOI can be determined"); assertEquals(Optional.empty(), fetchedEntry); } }
2,588
39.453125
146
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/ZbMATHTest.java
package org.jabref.logic.importer.fetcher; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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; @FetcherTest class ZbMATHTest { private ZbMATH fetcher; private BibEntry donaldsonEntry; @BeforeEach void setUp() throws Exception { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); fetcher = new ZbMATH(importFormatPreferences); donaldsonEntry = new BibEntry(); donaldsonEntry.setType(StandardEntryType.Article); donaldsonEntry.setCitationKey("zbMATH03800580"); donaldsonEntry.setField(StandardField.AUTHOR, "Donaldson, S. K."); donaldsonEntry.setField(StandardField.JOURNAL, "Journal of Differential Geometry"); donaldsonEntry.setField(StandardField.DOI, "10.4310/jdg/1214437665"); donaldsonEntry.setField(StandardField.ISSN, "0022-040X"); donaldsonEntry.setField(StandardField.LANGUAGE, "English"); donaldsonEntry.setField(StandardField.KEYWORDS, "57N13,57R10,53C05,58J99,57R65"); donaldsonEntry.setField(StandardField.PAGES, "279--315"); donaldsonEntry.setField(StandardField.TITLE, "An application of gauge theory to four dimensional topology"); donaldsonEntry.setField(StandardField.VOLUME, "18"); donaldsonEntry.setField(StandardField.YEAR, "1983"); donaldsonEntry.setField(StandardField.ZBL_NUMBER, "0507.57010"); donaldsonEntry.setField(new UnknownField("zbmath"), "3800580"); } @Test void searchByQueryFindsEntry() throws Exception { List<BibEntry> fetchedEntries = fetcher.performSearch("an:0507.57010"); assertEquals(Collections.singletonList(donaldsonEntry), fetchedEntries); } @Test void searchByIdFindsEntry() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("0507.57010"); assertEquals(Optional.of(donaldsonEntry), fetchedEntry); } @Test void searchByEntryFindsEntry() throws Exception { BibEntry searchEntry = new BibEntry(); searchEntry.setField(StandardField.TITLE, "An application of gauge theory to four dimensional topology"); searchEntry.setField(StandardField.AUTHOR, "S. K. {Donaldson}"); List<BibEntry> fetchedEntries = fetcher.performSearch(searchEntry); assertEquals(Collections.singletonList(donaldsonEntry), fetchedEntries); } @Test void searchByNoneEntryFindsNothing() throws Exception { BibEntry searchEntry = new BibEntry(); searchEntry.setField(StandardField.TITLE, "t"); searchEntry.setField(StandardField.AUTHOR, "a"); List<BibEntry> fetchedEntries = fetcher.performSearch(searchEntry); assertEquals(Collections.emptyList(), fetchedEntries); } @Test void searchByIdInEntryFindsEntry() throws Exception { BibEntry searchEntry = new BibEntry(); searchEntry.setField(StandardField.ZBL_NUMBER, "0507.57010"); List<BibEntry> fetchedEntries = fetcher.performSearch(searchEntry); assertEquals(Collections.singletonList(donaldsonEntry), fetchedEntries); } }
3,828
40.619565
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/DoiToBibtexConverterComIsbnFetcherTest.java
package org.jabref.logic.importer.fetcher.isbntobibtex; import java.util.Optional; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fetcher.AbstractIsbnFetcherTest; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; 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.assertThrows; import static org.mockito.Mockito.mock; @Disabled("Page https://doi-to-bibtex-converter.herokuapp.com is down") @FetcherTest public class DoiToBibtexConverterComIsbnFetcherTest extends AbstractIsbnFetcherTest { @BeforeEach public void setUp() { bibEntryEffectiveJava = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Effective Java(TM) Programming Language Guide (2nd Edition) (The Java Series)") .withField(StandardField.PUBLISHER, "Prentice Hall PTR") .withField(StandardField.YEAR, "2007") .withField(StandardField.AUTHOR, "Bloch, Joshua") .withField(StandardField.ISBN, "9780321356680") .withField(StandardField.PAGES, "256"); fetcher = new DoiToBibtexConverterComIsbnFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test @Override public void testName() { assertEquals("ISBN (doi-to-bibtex-converter.herokuapp.com)", fetcher.getName()); } @Test @Disabled @Override public void searchByIdSuccessfulWithShortISBN() { throw new UnsupportedOperationException(); } @Test @Disabled @Override public void searchByIdSuccessfulWithLongISBN() { throw new UnsupportedOperationException(); } @Test @Override public void authorsAreCorrectlyFormatted() throws Exception { BibEntry bibEntry = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Repository") .withField(StandardField.ISBN, "9783110702125") .withField(StandardField.AUTHOR, "Hans-Joachim Habermann and Frank Leymann") .withField(StandardField.PAGES, "294") .withField(StandardField.YEAR, "2020") .withField(StandardField.DAY, "12") .withField(StandardField.MONTH, "10"); Optional<BibEntry> fetchedEntry = fetcher.performSearchById("9783110702125"); assertEquals(Optional.of(bibEntry), fetchedEntry); } @Test public void testIsbnNeitherAvailable() { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("9785646216541")); } @Test public void searchByIdFailedWithLongISBN() { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("9780321356680")); } @Test public void searchByIdFailedWithShortISBN() throws FetcherException { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("0321356683")); } }
3,392
36.7
128
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/EbookDeIsbnFetcherTest.java
package org.jabref.logic.importer.fetcher.isbntobibtex; import java.util.Optional; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fetcher.AbstractIsbnFetcherTest; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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.assertThrows; import static org.mockito.Mockito.mock; @FetcherTest public class EbookDeIsbnFetcherTest extends AbstractIsbnFetcherTest { @BeforeEach public void setUp() { bibEntryEffectiveJava = new BibEntry(StandardEntryType.Book) .withCitationKey("9780134685991") .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.PUBLISHER, "Addison Wesley") .withField(StandardField.YEAR, "2018") .withField(StandardField.AUTHOR, "Bloch, Joshua") .withField(StandardField.DATE, "2018-01-15") .withField(new UnknownField("ean"), "9780134685991") .withField(StandardField.ISBN, "0134685997") .withField(StandardField.URL, "https://www.ebook.de/de/product/28983211/joshua_bloch_effective_java.html"); fetcher = new EbookDeIsbnFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test @Override public void testName() { assertEquals("ISBN (ebook.de)", fetcher.getName()); } @Test @Override public void searchByIdSuccessfulWithShortISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("0134685997"); assertEquals(Optional.of(bibEntryEffectiveJava), fetchedEntry); } @Test @Override public void searchByIdSuccessfulWithLongISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("9780134685991"); assertEquals(Optional.of(bibEntryEffectiveJava), fetchedEntry); } @Test @Override public void authorsAreCorrectlyFormatted() throws Exception { BibEntry bibEntry = new BibEntry(StandardEntryType.Book) .withCitationKey("9783662585856") .withField(StandardField.TITLE, "Fundamentals of Business Process Management") .withField(StandardField.PUBLISHER, "Springer Berlin Heidelberg") .withField(StandardField.YEAR, "2019") .withField(StandardField.AUTHOR, "Dumas, Marlon and Rosa, Marcello La and Mendling, Jan and Reijers, Hajo A.") .withField(StandardField.DATE, "2019-02-01") .withField(StandardField.PAGETOTAL, "560") .withField(new UnknownField("ean"), "9783662585856") .withField(StandardField.ISBN, "3662585855") .withField(StandardField.URL, "https://www.ebook.de/de/product/35805105/marlon_dumas_marcello_la_rosa_jan_mendling_hajo_a_reijers_fundamentals_of_business_process_management.html"); Optional<BibEntry> fetchedEntry = fetcher.performSearchById("3662585855"); assertEquals(Optional.of(bibEntry), fetchedEntry); } /** * This test searches for a valid ISBN. See https://www.amazon.de/dp/3728128155/?tag=jabref-21 However, this ISBN is * not available on ebook.de. */ @Test public void searchForValidButNotFoundISBN() throws Exception { assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("3728128155")); } }
3,931
42.688889
197
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/IsbnFetcherTest.java
package org.jabref.logic.importer.fetcher.isbntobibtex; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; 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.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; @FetcherTest class IsbnFetcherTest { private IsbnFetcher fetcher; private BibEntry bibEntry; @BeforeEach void setUp() { fetcher = new IsbnFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); bibEntry = new BibEntry(StandardEntryType.Book) .withField(StandardField.AUTHOR, "Bloch, Joshua") .withField(StandardField.TITLE, "Effective Java") .withField(StandardField.PUBLISHER, "Addison-Wesley Professional") .withField(StandardField.YEAR, "2017") .withField(StandardField.PAGES, "416") .withField(StandardField.ISBN, "9780134685991"); } @Test void testName() { assertEquals("ISBN", fetcher.getName()); } @Test void searchByIdSuccessfulWithShortISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("0134685997"); assertEquals(Optional.of(bibEntry), fetchedEntry); } @Test void searchByIdSuccessfulWithLongISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("9780134685991"); assertEquals(Optional.of(bibEntry), fetchedEntry); } @Test void searchByIdReturnsEmptyWithEmptyISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById(""); assertEquals(Optional.empty(), fetchedEntry); } @Test void searchByIdThrowsExceptionForShortInvalidISBN() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("123456789")); } @Test void searchByIdThrowsExceptionForLongInvalidISB() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("012345678910")); } @Test void searchByIdThrowsExceptionForInvalidISBN() { assertThrows(FetcherException.class, () -> fetcher.performSearchById("jabref-4-ever")); } @Test void searchByEntryWithISBNSuccessful() throws FetcherException { BibEntry input = new BibEntry().withField(StandardField.ISBN, "0134685997"); List<BibEntry> fetchedEntry = fetcher.performSearch(input); assertEquals(Collections.singletonList(bibEntry), fetchedEntry); } /** * This test searches for a valid ISBN. See https://www.amazon.de/dp/3728128155/?tag=jabref-21 However, this ISBN is * not available on ebook.de. The fetcher should something as it falls back to OttoBib */ @Test void searchForIsbnAvailableAtOttoBibButNonOnEbookDe() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("3728128155"); assertNotEquals(Optional.empty(), fetchedEntry); } }
3,519
34.918367
120
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/isbntobibtex/OpenLibraryIsbnFetcherTest.java
package org.jabref.logic.importer.fetcher.isbntobibtex; import java.util.Optional; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fetcher.AbstractIsbnFetcherTest; 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.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; public class OpenLibraryIsbnFetcherTest extends AbstractIsbnFetcherTest { @BeforeEach public void setUp() { bibEntryEffectiveJava = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Effective Java(TM) Programming Language Guide (2nd Edition) (The Java Series)") .withField(StandardField.PUBLISHER, "Prentice Hall PTR") .withField(StandardField.YEAR, "2007") .withField(StandardField.AUTHOR, "Bloch, Joshua") .withField(StandardField.ISBN, "9780321356680") .withField(StandardField.PAGES, "256"); fetcher = new OpenLibraryIsbnFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test @Override public void testName() { assertEquals("OpenLibrary", fetcher.getName()); } @Test @Override public void searchByIdSuccessfulWithShortISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("0321356683"); assertEquals(Optional.of(bibEntryEffectiveJava), fetchedEntry); } @Test @Override public void searchByIdSuccessfulWithLongISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("9780321356680"); assertEquals(Optional.of(bibEntryEffectiveJava), fetchedEntry); } @Test @Override public void authorsAreCorrectlyFormatted() throws Exception { BibEntry bibEntry = new BibEntry(StandardEntryType.Book) .withField(StandardField.TITLE, "Repository Eine Einführung") .withField(StandardField.SUBTITLE, "Eine Einführung") .withField(StandardField.PUBLISHER, "de Gruyter GmbH, Walter") .withField(StandardField.AUTHOR, "Habermann, Hans-Joachim and Leymann, Frank") .withField(StandardField.ISBN, "9783110702125") .withField(StandardField.YEAR, "2020"); Optional<BibEntry> fetchedEntry = fetcher.performSearchById("9783110702125"); assertEquals(Optional.of(bibEntry), fetchedEntry); } /** * Checks whether the given ISBN is <emph>NOT</emph> available at any ISBN fetcher */ @Test public void testIsbnNeitherAvailableOnEbookDeNorOrViaOpenLibrary() throws Exception { // In this test, the ISBN needs to be a valid (syntax+checksum) ISBN number // However, the ISBN number must not be assigned to a real book assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("9785646216541")); } }
3,344
40.8125
128
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/ArXivQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; class ArXivQueryTransformerTest extends YearRangeByFilteringQueryTransformerTest<ArXivQueryTransformer> { @Override public ArXivQueryTransformer getTransformer() { return new ArXivQueryTransformer(); } @Override public String getAuthorPrefix() { return "au:"; } @Override public String getUnFieldedPrefix() { return "all:"; } @Override public String getJournalPrefix() { return "jr:"; } @Override public String getTitlePrefix() { return "ti:"; } @Override public void convertYearField() throws Exception { ArXivQueryTransformer transformer = getTransformer(); String queryString = "2018"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> query = transformer.transformLuceneQuery(luceneQuery); assertEquals(Optional.of("2018"), query); assertEquals(2018, transformer.getStartYear()); assertEquals(2018, transformer.getEndYear()); } }
1,390
27.979167
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/CiteSeerQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.importer.FetcherException; import org.jabref.model.strings.StringUtil; import kong.unirest.json.JSONObject; import org.apache.lucene.queryparser.flexible.core.QueryNodeParseException; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; 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 CiteSeerQueryTransformerTest extends InfixTransformerTest<CiteSeerQueryTransformer> { @Override protected CiteSeerQueryTransformer getTransformer() { return new CiteSeerQueryTransformer(); } @Override public void convertYearField() throws Exception { String queryString = "year:2023"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); CiteSeerQueryTransformer transformer = getTransformer(); transformer.transformLuceneQuery(luceneQuery); Optional<Integer> start = Optional.of(transformer.getJSONPayload().getInt("yearStart")); Optional<Integer> end = Optional.of(transformer.getJSONPayload().getInt("yearEnd")); assertEquals(Optional.of(2023), start); assertEquals(Optional.of(2023), end); } @Override public void convertYearRangeField() throws Exception { String queryString = "year-range:2019-2023"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); CiteSeerQueryTransformer transformer = getTransformer(); transformer.transformLuceneQuery(luceneQuery); Optional<Integer> start = Optional.of(transformer.getJSONPayload().getInt("yearStart")); Optional<Integer> end = Optional.of(transformer.getJSONPayload().getInt("yearEnd")); assertEquals(Optional.of(2019), start); assertEquals(Optional.of(2023), end); } @Test public void convertPageField() throws Exception { String queryString = "page:2"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); CiteSeerQueryTransformer transformer = getTransformer(); transformer.transformLuceneQuery(luceneQuery); Optional<Integer> page = Optional.of(transformer.getJSONPayload().getInt("page")); assertEquals(Optional.of(2), page); } @Test public void convertPageSizeField() throws Exception { String queryString = "pageSize:20"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); CiteSeerQueryTransformer transformer = getTransformer(); transformer.transformLuceneQuery(luceneQuery); Optional<Integer> pageSize = Optional.of(transformer.getJSONPayload().getInt("pageSize")); assertEquals(Optional.of(20), pageSize); } @Test public void convertSortByField() throws Exception { String queryString = "sortBy:relevance"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); CiteSeerQueryTransformer transformer = getTransformer(); transformer.transformLuceneQuery(luceneQuery); Optional<String> sortBy = Optional.of(transformer.getJSONPayload().get("sortBy").toString()); assertEquals(Optional.of("relevance"), sortBy); } @Test public void convertMultipleAuthors() throws Exception { String queryString = "author:\"Wang Wei\" author:\"Zhang Pingwen\" author:\"Zhang Zhifei\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); CiteSeerQueryTransformer transformer = getTransformer(); transformer.transformLuceneQuery(luceneQuery); List<String> authorsActual = transformer.getJSONPayload().getJSONArray("author").toList(); List<String> authorsExpected = List.of("Wang Wei", "Zhang Pingwen", "Zhang Zhifei"); assertEquals(authorsExpected, authorsActual); } private static Stream<Arguments> getJSONWithYearVariations() throws FetcherException { String baseString = "title:Ericksen-Leslie page:1 pageSize:20 must_have_pdf:false sortBy:relevance"; List<String> withYearAndYearRange = List.of( StringUtil.join(new String[]{baseString, "year:2020"}, " ", 0, 2), StringUtil.join(new String[]{baseString, "year-range:2019-2023"}, " ", 0, 2) ); JSONObject expectedJson = new JSONObject(); expectedJson.put("queryString", "Ericksen-Leslie"); expectedJson.put("page", 1); expectedJson.put("pageSize", 20); expectedJson.put("must_have_pdf", "false"); expectedJson.put("sortBy", "relevance"); List<JSONObject> actualJSONObjects = new ArrayList<>(); withYearAndYearRange.forEach(requestStr -> { QueryNode luceneQuery = null; try { luceneQuery = new StandardSyntaxParser().parse(requestStr, AbstractQueryTransformer.NO_EXPLICIT_FIELD); } catch (QueryNodeParseException e) { throw new RuntimeException(e); } CiteSeerQueryTransformer transformer = new CiteSeerQueryTransformer(); transformer.transformLuceneQuery(luceneQuery); actualJSONObjects.add(transformer.getJSONPayload()); }); Iterator<JSONObject> jsonObjectIterator = actualJSONObjects.iterator(); return Stream.of( Arguments.of(expectedJson, 2020, 2020, jsonObjectIterator.next()), Arguments.of(expectedJson, 2019, 2023, jsonObjectIterator.next()) ); } @ParameterizedTest @MethodSource("getJSONWithYearVariations") public void compareJSONRequestsWithYearVariations(JSONObject expected, Integer yearStart, Integer yearEnd, JSONObject actual) throws Exception { expected.put("yearStart", yearStart); expected.put("yearEnd", yearEnd); assertEquals(expected, actual); expected.remove("yearStart"); expected.remove("yearEnd"); } }
6,609
44.586207
148
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/CollectionOfComputerScienceBibliographiesQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; class CollectionOfComputerScienceBibliographiesQueryTransformerTest extends InfixTransformerTest<CollectionOfComputerScienceBibliographiesQueryTransformer> { @Override public CollectionOfComputerScienceBibliographiesQueryTransformer getTransformer() { return new CollectionOfComputerScienceBibliographiesQueryTransformer(); } @Override public String getAuthorPrefix() { return "au:"; } @Override public String getUnFieldedPrefix() { return ""; } @Override public String getJournalPrefix() { return ""; } @Override public String getTitlePrefix() { return "ti:"; } @Override public void convertYearField() throws Exception { String queryString = "2018"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> query = getTransformer().transformLuceneQuery(luceneQuery); assertEquals(Optional.of("year:2018"), query); } @Override public void convertYearRangeField() throws Exception { String queryString = "year-range:2018-2021"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> query = getTransformer().transformLuceneQuery(luceneQuery); assertEquals(Optional.of("year:2018 OR year:2019 OR year:2020 OR year:2021"), query); } }
1,780
32.603774
157
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/DBLPQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; class DBLPQueryTransformerTest extends InfixTransformerTest<DBLPQueryTransformer> { @Override public DBLPQueryTransformer getTransformer() { return new DBLPQueryTransformer(); } @Override public String getAuthorPrefix() { return ""; } @Override public String getUnFieldedPrefix() { return ""; } @Override public String getJournalPrefix() { return ""; } @Override public String getTitlePrefix() { return ""; } @Override public void convertYearField() throws Exception { String queryString = "year:2015"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("2015"); assertEquals(expected, searchQuery); } @Override public void convertYearRangeField() throws Exception { String queryString = "year-range:2012-2015"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("2012|2013|2014|2015"); assertEquals(expected, searchQuery); } }
1,713
30.163636
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/DefaultQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; class DefaultQueryTransformerTest extends YearAndYearRangeByFilteringQueryTransformerTest<DefaultQueryTransformer> { @Override protected DefaultQueryTransformer getTransformer() { return new DefaultQueryTransformer(); } @Override public String getAuthorPrefix() { return ""; } @Override public String getUnFieldedPrefix() { return ""; } @Override public String getJournalPrefix() { return ""; } @Override public String getTitlePrefix() { return ""; } }
615
19.533333
116
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/GVKQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import org.junit.jupiter.api.Disabled; import static org.junit.jupiter.api.Assertions.assertEquals; class GVKQueryTransformerTest extends InfixTransformerTest<GVKQueryTransformer> { @Override public GVKQueryTransformer getTransformer() { return new GVKQueryTransformer(); } @Override public String getAuthorPrefix() { return "pica.per="; } @Override public String getUnFieldedPrefix() { return "pica.all="; } @Override public String getJournalPrefix() { return "pica.zti="; } @Override public String getTitlePrefix() { return "pica.tit="; } @Override public void convertYearField() throws Exception { String queryString = "year:2018"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> query = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("ver:2018"); assertEquals(expected, query); } @Disabled("Not supported by GVK") @Override public void convertYearRangeField() throws Exception { } }
1,431
26.018868
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/IEEEQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import java.util.stream.Stream; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; 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 IEEEQueryTransformerTest extends InfixTransformerTest<IEEEQueryTransformer> { @Override public IEEEQueryTransformer getTransformer() { return new IEEEQueryTransformer(); } @Override public String getAuthorPrefix() { return "author:"; } @Override public String getUnFieldedPrefix() { return ""; } @Override public String getJournalPrefix() { return "publication_title:"; } @Override public String getTitlePrefix() { return "article_title:"; } @Override public void convertJournalFieldPrefix() throws Exception { IEEEQueryTransformer transformer = getTransformer(); String queryString = "journal:Nature"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); transformer.transformLuceneQuery(luceneQuery); assertEquals("\"Nature\"", transformer.getJournal().get()); } @Override public void convertYearField() throws Exception { // IEEE does not support year range // Thus, a generic test does not work IEEEQueryTransformer transformer = getTransformer(); String queryString = "year:2021"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); transformer.transformLuceneQuery(luceneQuery); assertEquals(2021, transformer.getStartYear()); assertEquals(2021, transformer.getEndYear()); } @Override public void convertYearRangeField() throws Exception { IEEEQueryTransformer transformer = getTransformer(); String queryString = "year-range:2018-2021"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); transformer.transformLuceneQuery(luceneQuery); assertEquals(2018, transformer.getStartYear()); assertEquals(2021, transformer.getEndYear()); } private static Stream<Arguments> getTitleTestData() { return Stream.of( Arguments.of("Overcoming AND Open AND Source AND Project AND Entry AND Barriers AND Portal AND Newcomers", "Overcoming Open Source Project Entry Barriers with a Portal for Newcomers"), Arguments.of("Overcoming AND Open AND Source AND Project AND Entry AND Barriers", "Overcoming Open Source Project Entry Barriers"), Arguments.of(null, "and") ); } @ParameterizedTest @MethodSource("getTitleTestData") public void testStopWordRemoval(String expected, String queryString) throws Exception { QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> result = getTransformer().transformLuceneQuery(luceneQuery); assertEquals(Optional.ofNullable(expected), result); } }
3,451
35.336842
200
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/InfixTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Interface for all transformers that use infix notation for their logical binary operators */ public abstract class InfixTransformerTest<T extends AbstractQueryTransformer> { protected abstract T getTransformer(); /* All prefixes have to include the used separator * Example in the case of ':': <code>"author:"</code> */ protected String getAuthorPrefix() { return ""; } protected String getUnFieldedPrefix() { return ""; } protected String getJournalPrefix() { return ""; } protected String getTitlePrefix() { return ""; } @Test public void convertAuthorFieldPrefix() throws Exception { String queryString = "author:\"Igor Steinmacher\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(getAuthorPrefix() + "\"Igor Steinmacher\""); assertEquals(expected, searchQuery); } @Test public void convertUnFieldedTermPrefix() throws Exception { String queryString = "\"default value\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(getUnFieldedPrefix() + queryString); assertEquals(expected, searchQuery); } @Test public void convertExplicitUnFieldedTermPrefix() throws Exception { String queryString = "default:\"default value\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(getUnFieldedPrefix() + "\"default value\""); assertEquals(expected, searchQuery); } @Test public void convertJournalFieldPrefix() throws Exception { String queryString = "journal:Nature"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(getJournalPrefix() + "Nature"); assertEquals(expected, searchQuery); } @Test public abstract void convertYearField() throws Exception; @Test public abstract void convertYearRangeField() throws Exception; @Test public void convertMultipleValuesWithTheSameFieldPrefix() throws Exception { String queryString = "author:\"Igor Steinmacher\" author:\"Christoph Treude\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(getAuthorPrefix() + "\"Igor Steinmacher\"" + getTransformer().getLogicalAndOperator() + getAuthorPrefix() + "\"Christoph Treude\""); assertEquals(expected, searchQuery); } @Test public void groupedOperationsPrefix() throws Exception { String queryString = "(author:\"Igor Steinmacher\" OR author:\"Christoph Treude\" AND author:\"Christoph Freunde\") AND title:test"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("(" + getAuthorPrefix() + "\"Igor Steinmacher\"" + getTransformer().getLogicalOrOperator() + "(" + getAuthorPrefix() + "\"Christoph Treude\"" + getTransformer().getLogicalAndOperator() + getAuthorPrefix() + "\"Christoph Freunde\"))" + getTransformer().getLogicalAndOperator() + getTitlePrefix() + "test"); assertEquals(expected, searchQuery); } @Test public void notOperatorPrefix() throws Exception { String queryString = "!(author:\"Igor Steinmacher\" OR author:\"Christoph Treude\")"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(getTransformer().getLogicalNotOperator() + "(" + getAuthorPrefix() + "\"Igor Steinmacher\"" + getTransformer().getLogicalOrOperator() + getAuthorPrefix() + "\"Christoph Treude\")"); assertEquals(expected, searchQuery); } }
5,156
47.196262
353
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/JstorQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; class JstorQueryTransformerTest extends InfixTransformerTest<JstorQueryTransformer> { @Override public JstorQueryTransformer getTransformer() { return new JstorQueryTransformer(); } @Override public String getAuthorPrefix() { return "au:"; } @Override public String getUnFieldedPrefix() { return ""; } @Override public String getJournalPrefix() { return "pt:"; } @Override public String getTitlePrefix() { return "ti:"; } @Override public void convertYearField() throws Exception { String queryString = "year:2018"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> query = getTransformer().transformLuceneQuery(luceneQuery); assertEquals(Optional.of("sd:2018 AND ed:2018"), query); } @Override public void convertYearRangeField() throws Exception { String queryString = "year-range:2018-2021"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> query = getTransformer().transformLuceneQuery(luceneQuery); assertEquals(Optional.of("sd:2018 AND ed:2021"), query); } }
1,625
29.679245
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/ScholarQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; class ScholarQueryTransformerTest extends YearAndYearRangeByFilteringQueryTransformerTest<ScholarQueryTransformer> { @Override public ScholarQueryTransformer getTransformer() { return new ScholarQueryTransformer(); } @Override public String getAuthorPrefix() { return "author:"; } @Override public String getUnFieldedPrefix() { return ""; } @Override public String getJournalPrefix() { return "source:"; } @Override public String getTitlePrefix() { return "allintitle:"; } }
637
20.266667
116
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/SpringerQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; class SpringerQueryTransformerTest extends InfixTransformerTest<SpringerQueryTransformer> { @Override public String getAuthorPrefix() { return "name:"; } @Override public SpringerQueryTransformer getTransformer() { return new SpringerQueryTransformer(); } @Override public String getUnFieldedPrefix() { return ""; } @Override public String getJournalPrefix() { return "journal:"; } @Override public String getTitlePrefix() { return "title:"; } @Override public void convertYearField() throws Exception { String queryString = "year:2015"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("date:2015*"); assertEquals(expected, searchQuery); } @Override public void convertYearRangeField() throws Exception { String queryString = "year-range:2012-2015"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("date:2012* OR date:2013* OR date:2014* OR date:2015*"); assertEquals(expected, searchQuery); } }
1,789
30.403509
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/SuffixTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Interface for all transformers that use suffix notation for their logical binary operators */ public abstract class SuffixTransformerTest<T extends AbstractQueryTransformer> { protected abstract T getTransformer(); protected abstract String getAuthorSuffix(); protected abstract String getUnFieldedSuffix(); protected abstract String getJournalSuffix(); protected abstract String getTitleSuffix(); @Test public void convertAuthorFieldSuffix() throws Exception { String queryString = "author:\"Igor Steinmacher\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("\"Igor Steinmacher\"" + getAuthorSuffix()); assertEquals(expected, searchQuery); } @Test public void convertUnFieldedTermSuffix() throws Exception { String queryString = "\"default value\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(queryString + getUnFieldedSuffix()); assertEquals(expected, searchQuery); } @Test public void convertExplicitUnFieldedTermSuffix() throws Exception { String queryString = "default:\"default value\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("\"default value\"" + getUnFieldedSuffix()); assertEquals(expected, searchQuery); } @Test public void convertJournalFieldSuffix() throws Exception { String queryString = "journal:Nature"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("Nature" + getJournalSuffix()); assertEquals(expected, searchQuery); } @Test public abstract void convertYearField() throws Exception; @Test public abstract void convertYearRangeField() throws Exception; @Test public void convertMultipleValuesWithTheSameSuffix() throws Exception { String queryString = "author:\"Igor Steinmacher\" author:\"Christoph Treude\""; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("\"Igor Steinmacher\"" + getAuthorSuffix() + getTransformer().getLogicalAndOperator() + "\"Christoph Treude\"" + getAuthorSuffix()); assertEquals(expected, searchQuery); } @Test public void groupedOperationsSuffix() throws Exception { String queryString = "(author:\"Igor Steinmacher\" OR author:\"Christoph Treude\" AND author:\"Christoph Freunde\") AND title:test"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("(" + "\"Igor Steinmacher\"" + getAuthorSuffix() + getTransformer().getLogicalOrOperator() + "(" + "\"Christoph Treude\"" + getAuthorSuffix() + getTransformer().getLogicalAndOperator() + "\"Christoph Freunde\"" + getAuthorSuffix() + "))" + getTransformer().getLogicalAndOperator() + "test" + getTitleSuffix()); assertEquals(expected, searchQuery); } @Test public void notOperatorSufix() throws Exception { String queryString = "!(author:\"Igor Steinmacher\" OR author:\"Christoph Treude\")"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of(getTransformer().getLogicalNotOperator() + "(" + "\"Igor Steinmacher\"" + getAuthorSuffix() + getTransformer().getLogicalOrOperator() + "\"Christoph Treude\")" + getAuthorSuffix()); assertEquals(expected, searchQuery); } }
4,967
51.294737
358
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/YearAndYearRangeByFilteringQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; public abstract class YearAndYearRangeByFilteringQueryTransformerTest<T extends YearAndYearRangeByFilteringQueryTransformer> extends YearRangeByFilteringQueryTransformerTest<T> { @Override public void convertYearField() throws Exception { YearAndYearRangeByFilteringQueryTransformer transformer = getTransformer(); String queryString = "year:2021"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> query = transformer.transformLuceneQuery(luceneQuery); assertEquals(Optional.of(""), query); assertEquals(2021, transformer.getStartYear()); assertEquals(2021, transformer.getEndYear()); } }
1,040
46.318182
178
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/YearRangeByFilteringQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; public abstract class YearRangeByFilteringQueryTransformerTest<T extends YearRangeByFilteringQueryTransformer> extends InfixTransformerTest<T> { @Override public void convertYearRangeField() throws Exception { YearRangeByFilteringQueryTransformer transformer = getTransformer(); String queryString = "year-range:2018-2021"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> result = transformer.transformLuceneQuery(luceneQuery); // The API does not support querying for a year range // The implementation of the fetcher filters the results manually // The implementations returns an empty query assertEquals(Optional.of(""), result); // The implementation sets the start year and end year values according to the query assertEquals(2018, transformer.getStartYear()); assertEquals(2021, transformer.getEndYear()); } }
1,305
41.129032
144
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fetcher/transformers/ZbMathQueryTransformerTest.java
package org.jabref.logic.importer.fetcher.transformers; import java.util.Optional; import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode; import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser; import static org.junit.jupiter.api.Assertions.assertEquals; class ZbMathQueryTransformerTest extends InfixTransformerTest<ZbMathQueryTransformer> { @Override public ZbMathQueryTransformer getTransformer() { return new ZbMathQueryTransformer(); } @Override public String getAuthorPrefix() { return "au:"; } @Override public String getUnFieldedPrefix() { return "any:"; } @Override public String getJournalPrefix() { return "so:"; } @Override public String getTitlePrefix() { return "ti:"; } @Override public void convertYearField() throws Exception { String queryString = "year:2015"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("py:2015"); assertEquals(expected, searchQuery); } @Override public void convertYearRangeField() throws Exception { String queryString = "year-range:2012-2015"; QueryNode luceneQuery = new StandardSyntaxParser().parse(queryString, AbstractQueryTransformer.NO_EXPLICIT_FIELD); Optional<String> searchQuery = getTransformer().transformLuceneQuery(luceneQuery); Optional<String> expected = Optional.of("py:2012-2015"); assertEquals(expected, searchQuery); } }
1,730
30.472727
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/ACMPortalParserTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.CookieHandler; import java.net.CookieManager; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.List; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ParseException; import org.jabref.logic.net.URLDownload; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import com.microsoft.applicationinsights.core.dependencies.http.client.utils.URIBuilder; 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; @FetcherTest public class ACMPortalParserTest { ACMPortalParser parser; List<BibEntry> searchEntryList; URL searchUrl; String searchQuery = "The relationship of code churn and architectural violations in the open source software JabRef"; String jsonStr = "{\"id\":\"10.1145/3129790.3129810\",\"type\":\"PAPER_CONFERENCE\",\"author\":[{\"family\":\"Olsson\",\"given\":\"Tobias\"},{\"family\":\"Ericsson\",\"given\":\"Morgan\"},{\"family\":\"Wingkvist\",\"given\":\"Anna\"}],\"accessed\":{\"date-parts\":[[2021,5,12]]},\"issued\":{\"date-parts\":[[2017,9,11]]},\"original-date\":{\"date-parts\":[[2017,9,11]]},\"abstract\":\"The open source application JabRef has existed since 2003. In 2015, the developers decided to make an architectural refactoring as continued development was deemed too demanding. The developers also introduced Static Architecture Conformance Checking (SACC) to prevent violations to the intended architecture. Measurements mined from source code repositories such as code churn and code ownership has been linked to several problems, for example fault proneness, security vulnerabilities, code smells, and degraded maintainability. The root cause of such problems can be architectural. To determine the impact of the refactoring of JabRef, we measure the code churn and code ownership before and after the refactoring and find that large files with violations had a significantly higher code churn than large files without violations before the refactoring. After the refactoring, the files that had violations show a more normal code churn. We find no such effect on code ownership. We conclude that files that contain violations detectable by SACC methods are connected to higher than normal code churn.\",\"call-number\":\"10.1145/3129790.3129810\",\"collection-title\":\"ECSA '17\",\"container-title\":\"Proceedings of the 11th European Conference on Software Architecture: Companion Proceedings\",\"DOI\":\"10.1145/3129790.3129810\",\"event-place\":\"Canterbury, United Kingdom\",\"ISBN\":\"9781450352178\",\"keyword\":\"software architecture, conformance checking, repository data mining\",\"number-of-pages\":\"7\",\"page\":\"152–158\",\"publisher\":\"Association for Computing Machinery\",\"publisher-place\":\"New York, NY, USA\",\"title\":\"The relationship of code churn and architectural violations in the open source software JabRef\",\"URL\":\"https://doi.org/10.1145/3129790.3129810\"}"; @BeforeEach void setUp() throws URISyntaxException, MalformedURLException { parser = new ACMPortalParser(); searchUrl = new URIBuilder("https://dl.acm.org/action/doSearch") .addParameter("AllField", searchQuery).build().toURL(); searchEntryList = List.of( new BibEntry(StandardEntryType.Conference) .withField(StandardField.AUTHOR, "Tobias Olsson and Morgan Ericsson and Anna Wingkvist") .withField(StandardField.YEAR, "2017") .withField(StandardField.MONTH, "9") .withField(StandardField.DAY, "11") .withField(StandardField.SERIES, "ECSA '17") .withField(StandardField.BOOKTITLE, "Proceedings of the 11th European Conference on Software Architecture: Companion Proceedings") .withField(StandardField.DOI, "10.1145/3129790.3129810") .withField(StandardField.LOCATION, "Canterbury, United Kingdom") .withField(StandardField.ISBN, "9781450352178") .withField(StandardField.KEYWORDS, "conformance checking, repository data mining, software architecture") .withField(StandardField.PUBLISHER, "Association for Computing Machinery") .withField(StandardField.ADDRESS, "New York, NY, USA") .withField(StandardField.TITLE, "The relationship of code churn and architectural violations in the open source software JabRef") .withField(StandardField.URL, "https://doi.org/10.1145/3129790.3129810") .withField(StandardField.PAGETOTAL, "7") .withField(StandardField.PAGES, "152–158"), new BibEntry(StandardEntryType.Book) .withField(StandardField.YEAR, "2016") .withField(StandardField.MONTH, "10") .withField(StandardField.TITLE, "Proceedings of the 2016 24th ACM SIGSOFT International Symposium on Foundations of Software Engineering") .withField(StandardField.LOCATION, "Seattle, WA, USA") .withField(StandardField.ISBN, "9781450342186") .withField(StandardField.PUBLISHER, "Association for Computing Machinery") .withField(StandardField.ADDRESS, "New York, NY, USA") ); } @Test void testParseEntries() throws IOException, ParseException { CookieHandler.setDefault(new CookieManager()); List<BibEntry> bibEntries = parser.parseEntries(new URLDownload(searchUrl).asInputStream()); for (BibEntry bibEntry : bibEntries) { bibEntry.clearField(StandardField.ABSTRACT); } assertEquals(searchEntryList.get(0), bibEntries.get(0)); } @Test void testParseDoiSearchPage() throws ParseException, IOException { String testDoi = "10.1145/3129790.3129810"; CookieHandler.setDefault(new CookieManager()); List<String> doiList = parser.parseDoiSearchPage(new URLDownload(searchUrl).asInputStream()); assertFalse(doiList.isEmpty()); assertEquals(testDoi, doiList.get(0)); } @Test void testGetBibEntriesFromDoiList() throws FetcherException { List<String> testDoiList = List.of("10.1145/3129790.3129810", "10.1145/2950290"); List<BibEntry> bibEntries = parser.getBibEntriesFromDoiList(testDoiList); for (BibEntry bibEntry : bibEntries) { bibEntry.clearField(StandardField.ABSTRACT); } assertEquals(searchEntryList, bibEntries); } @Test void testGetUrlFromDoiList() throws MalformedURLException, URISyntaxException { String target = "https://dl.acm.org/action/exportCiteProcCitation?targetFile=custom-bibtex&format=bibTex&dois=10.1145%2F3129790.3129810%2C10.1145%2F2950290"; List<String> doiList = List.of("10.1145/3129790.3129810", "10.1145/2950290"); URL url = parser.getUrlFromDoiList(doiList); assertEquals(target, url.toString()); } @Test void testParseBibEntry() { BibEntry bibEntry = parser.parseBibEntry(jsonStr); bibEntry.clearField(StandardField.ABSTRACT); assertEquals(searchEntryList.get(0), bibEntry); } @Test void testNoEntryFound() throws URISyntaxException, IOException, ParseException { CookieHandler.setDefault(new CookieManager()); URL url = new URIBuilder("https://dl.acm.org/action/doSearch?AllField=10.1145/3129790.31298").build().toURL(); List<BibEntry> bibEntries = parser.parseEntries(new URLDownload(url).asInputStream()); assertEquals(Collections.emptyList(), bibEntries); } }
8,188
65.577236
2,191
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; public class BiblioscapeImporterFilesTest { private static final String FILE_ENDING = ".txt"; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("BiblioscapeImporterTest") && name.endsWith(FILE_ENDING) && !name.contains("Corrupt"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(new BiblioscapeImporter(), fileName); } @ParameterizedTest @MethodSource("fileNames") public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new BiblioscapeImporter(), fileName, FILE_ENDING); } }
1,111
33.75
95
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTest.java
package org.jabref.logic.importer.fileformat; import java.nio.file.Path; import java.util.Collections; import org.jabref.logic.util.StandardFileType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class BiblioscapeImporterTest { private BiblioscapeImporter importer; @BeforeEach public void setUp() throws Exception { importer = new BiblioscapeImporter(); } @Test public void testGetFormatName() { assertEquals("Biblioscape", importer.getName()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.TXT, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Imports a Biblioscape Tag File.\n" + "Several Biblioscape field types are ignored. Others are only included in the BibTeX field \"comment\".", importer.getDescription()); } @Test public void testGetCLIID() { assertEquals("biblioscape", importer.getId()); } @Test public void testImportEntriesAbortion() throws Throwable { Path file = Path.of(BiblioscapeImporter.class.getResource("BiblioscapeImporterTestCorrupt.txt").toURI()); assertEquals(Collections.emptyList(), importer.importDatabase(file).getDatabase().getEntries()); } }
1,409
27.2
149
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/BiblioscapeImporterTypesTest.java
package org.jabref.logic.importer.fileformat; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class BiblioscapeImporterTypesTest { private static Stream<Arguments> types() { return Stream.of( Arguments.of("journal", StandardEntryType.Article), Arguments.of("book section", StandardEntryType.InBook), Arguments.of("book", StandardEntryType.Book), Arguments.of("conference", StandardEntryType.InProceedings), Arguments.of("proceedings", StandardEntryType.InProceedings), Arguments.of("report", StandardEntryType.TechReport), Arguments.of("master thesis", StandardEntryType.MastersThesis), Arguments.of("thesis", StandardEntryType.PhdThesis), Arguments.of("master", StandardEntryType.Misc) ); } @ParameterizedTest @MethodSource("types") void importConvertsToCorrectBibType(String biblioscapeType, EntryType bibtexType) throws IOException { String bsInput = "--AU-- Baklouti, F.\n" + "--YP-- 1999\n" + "--KW-- Cells; Rna; Isoforms\n" + "--TI-- Blood\n" + "--RT-- " + biblioscapeType + "\n" + "------"; List<BibEntry> bibEntries = new BiblioscapeImporter().importDatabase(new BufferedReader(new StringReader(bsInput))) .getDatabase().getEntries(); BibEntry entry = new BibEntry(); entry.setField(StandardField.AUTHOR, "Baklouti, F."); entry.setField(StandardField.KEYWORDS, "Cells; Rna; Isoforms"); entry.setField(StandardField.TITLE, "Blood"); entry.setField(StandardField.YEAR, "1999"); entry.setType(bibtexType); Assertions.assertEquals(Collections.singletonList(entry), bibEntries); } }
2,345
41.654545
123
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.util.DummyFileUpdateMonitor; import org.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.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; /** * This class tests the BibtexImporter. * <p> * Tests for writing can be found at {@link org.jabref.logic.exporter.BibtexDatabaseWriterTest}. * Tests for parsing single entry BibTeX can be found at {@link BibtexParserTest} */ public class BibtexImporterTest { private BibtexImporter importer; @BeforeEach public void setUp() { importer = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); } @Test public void testIsRecognizedFormat() throws IOException, URISyntaxException { Path file = Path.of(BibtexImporterTest.class.getResource("BibtexImporter.examples.bib").toURI()); assertTrue(importer.isRecognizedFormat(file)); } @Test public void testImportEntries() throws IOException, URISyntaxException { Path file = Path.of(BibtexImporterTest.class.getResource("BibtexImporter.examples.bib").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(4, bibEntries.size()); for (BibEntry entry : bibEntries) { if ("aksin".equals(entry.getCitationKey().get())) { assertEquals( Optional.of( "Aks{\\i}n, {\\\"O}zge and T{\\\"u}rkmen, Hayati and Artok, Levent and {\\c{C}}etinkaya, " + "Bekir and Ni, Chaoying and B{\\\"u}y{\\\"u}kg{\\\"u}ng{\\\"o}r, Orhan and {\\\"O}zkal, Erhan"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("aksin"), entry.getCitationKey()); assertEquals(Optional.of("2006"), entry.getField(StandardField.DATE)); assertEquals(Optional.of("Effect of immobilization on catalytic characteristics"), entry.getField(new UnknownField("indextitle"))); assertEquals(Optional.of("#jomch#"), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("13"), entry.getField(StandardField.NUMBER)); assertEquals(Optional.of("3027-3036"), entry.getField(StandardField.PAGES)); assertEquals(Optional .of("Effect of immobilization on catalytic characteristics of saturated {Pd-N}-heterocyclic " + "carbenes in {Mizoroki-Heck} reactions"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("691"), entry.getField(StandardField.VOLUME)); } else if ("stdmodel".equals(entry.getCitationKey().get())) { assertEquals(Optional .of("A \\texttt{set} with three members discussing the standard model of particle physics. " + "The \\texttt{crossref} field in the \\texttt{@set} entry and the \\texttt{entryset} field in " + "each set member entry is needed only when using BibTeX as the backend"), entry.getField(StandardField.ANNOTATION)); assertEquals(Optional.of("stdmodel"), entry.getCitationKey()); assertEquals(Optional.of("glashow,weinberg,salam"), entry.getField(StandardField.ENTRYSET)); } else if ("set".equals(entry.getCitationKey().get())) { assertEquals(Optional .of("A \\texttt{set} with three members. The \\texttt{crossref} field in the \\texttt{@set} " + "entry and the \\texttt{entryset} field in each set member entry is needed only when using " + "BibTeX as the backend"), entry.getField(StandardField.ANNOTATION)); assertEquals(Optional.of("set"), entry.getCitationKey()); assertEquals(Optional.of("herrmann,aksin,yoon"), entry.getField(StandardField.ENTRYSET)); } else if ("Preissel2016".equals(entry.getCitationKey().get())) { assertEquals(Optional.of("Heidelberg"), entry.getField(StandardField.ADDRESS)); assertEquals(Optional.of("Preißel, René"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Preissel2016"), entry.getCitationKey()); assertEquals(Optional.of("3., aktualisierte und erweiterte Auflage"), entry.getField(StandardField.EDITION)); assertEquals(Optional.of("978-3-86490-311-3"), entry.getField(StandardField.ISBN)); assertEquals(Optional.of("Versionsverwaltung"), entry.getField(StandardField.KEYWORDS)); assertEquals(Optional.of("XX, 327 Seiten"), entry.getField(StandardField.PAGES)); assertEquals(Optional.of("dpunkt.verlag"), entry.getField(StandardField.PUBLISHER)); assertEquals(Optional.of("Git: dezentrale Versionsverwaltung im Team : Grundlagen und Workflows"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("http://d-nb.info/107601965X"), entry.getField(StandardField.URL)); assertEquals(Optional.of("2016"), entry.getField(StandardField.YEAR)); } } } @Test public void testGetFormatName() { assertEquals("BibTeX", importer.getName()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.BIBTEX_DB, importer.getFileType()); } @Test public void testGetDescription() { assertEquals( "This importer enables `--importToOpen someEntry.bib`", importer.getDescription()); } @Test public void testRecognizesDatabaseID() throws Exception { Path file = Path.of(BibtexImporterTest.class.getResource("AutosavedSharedDatabase.bib").toURI()); String sharedDatabaseID = importer.importDatabase(file).getDatabase().getSharedDatabaseID().get(); assertEquals("13ceoc8dm42f5g1iitao3dj2ap", sharedDatabaseID); } static Stream<Arguments> testParsingOfEncodedFileWithHeader() { return Stream.of( Arguments.of(StandardCharsets.US_ASCII, "encoding-us-ascii-with-header.bib"), Arguments.of(StandardCharsets.UTF_8, "encoding-utf-8-with-header.bib"), Arguments.of(Charset.forName("Windows-1252"), "encoding-windows-1252-with-header.bib"), Arguments.of(StandardCharsets.UTF_16BE, "encoding-utf-16BE-with-header.bib"), Arguments.of(StandardCharsets.UTF_16BE, "encoding-utf-16BE-without-header.bib") ); } @ParameterizedTest @MethodSource public void testParsingOfEncodedFileWithHeader(Charset charset, String fileName) throws Exception { ParserResult parserResult = importer.importDatabase( Path.of(BibtexImporterTest.class.getResource(fileName).toURI())); assertEquals(Optional.of(charset), parserResult.getMetaData().getEncoding()); } @ParameterizedTest @CsvSource({"encoding-windows-1252-with-header.bib", "encoding-windows-1252-without-header.bib"}) public void testParsingOfWindows1252EncodedFileReadsDegreeCharacterCorrectly(String filename) throws Exception { ParserResult parserResult = importer.importDatabase( Path.of(BibtexImporterTest.class.getResource(filename).toURI())); assertEquals( List.of(new BibEntry(StandardEntryType.Article).withField(StandardField.ABSTRACT, "25° C")), parserResult.getDatabase().getEntries()); } @ParameterizedTest @CsvSource({"encoding-utf-8-with-header.bib", "encoding-utf-8-without-header.bib", "encoding-utf-16BE-with-header.bib", "encoding-utf-16BE-without-header.bib"}) public void testParsingFilesReadsUmlautCharacterCorrectly(String filename) throws Exception { ParserResult parserResult = importer.importDatabase( Path.of(BibtexImporterTest.class.getResource(filename).toURI())); assertEquals( List.of(new BibEntry(StandardEntryType.Article).withField(StandardField.TITLE, "Ü ist ein Umlaut")), parserResult.getDatabase().getEntries()); } private static Stream<Arguments> encodingExplicitlySuppliedCorrectlyDetermined() { return Stream.of( Arguments.of("encoding-utf-8-with-header.bib", true), Arguments.of("encoding-utf-8-without-header.bib", false), Arguments.of("encoding-utf-16BE-with-header.bib", true), Arguments.of("encoding-utf-16BE-without-header.bib", false) ); } @ParameterizedTest @MethodSource public void encodingExplicitlySuppliedCorrectlyDetermined(String filename, boolean encodingExplicitlySupplied) throws Exception { ParserResult parserResult = importer.importDatabase( Path.of(BibtexImporterTest.class.getResource(filename).toURI())); assertEquals(encodingExplicitlySupplied, parserResult.getMetaData().getEncodingExplicitlySupplied()); } @Test public void wrongEncodingSupplied() throws Exception { ParserResult parserResult = importer.importDatabase( Path.of(BibtexImporterTest.class.getResource("encoding-windows-1252-but-utf-8-declared--decoding-fails.bib").toURI())); // The test file contains "Test{NBSP}I. Last" where the character "{NBSP}" is encoded using Windows-1252 instead of UTF-8 assertEquals( List.of(new BibEntry(StandardEntryType.Article).withField(StandardField.AUTHOR, "Test�I. Last")), parserResult.getDatabase().getEntries()); } @Test public void encodingNotSupplied() throws Exception { ParserResult parserResult = importer.importDatabase( Path.of(BibtexImporterTest.class.getResource("encoding-utf-8-without-header.bib").toURI())); assertFalse(parserResult.getMetaData().getEncodingExplicitlySupplied()); } }
11,316
52.382075
147
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.io.StringReader; import java.net.InetAddress; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Optional; import javafx.collections.FXCollections; import org.jabref.logic.citationkeypattern.AbstractCitationKeyPattern; 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.exporter.SaveConfiguration; 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.NormalizeMonthFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import org.jabref.logic.formatter.casechanger.LowerCaseFormatter; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.util.OS; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibtexString; import org.jabref.model.entry.Date; import org.jabref.model.entry.Month; import org.jabref.model.entry.field.BibField; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldPriority; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; 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.groups.RegexKeywordGroup; import org.jabref.model.groups.TexGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.SaveOrder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests for reading whole bib files can be found at {@link org.jabref.logic.importer.fileformat.BibtexImporterTest} * <p> * Tests cannot be executed concurrently, because Localization is used at {@link BibtexParser#parseAndAddEntry(String)} */ class BibtexParserTest { private ImportFormatPreferences importFormatPreferences; private BibtexParser parser; @BeforeEach void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); parser = new BibtexParser(importFormatPreferences); } @Test void parseWithNullThrowsNullPointerException() throws Exception { Executable toBeTested = () -> parser.parse(null); assertThrows(NullPointerException.class, toBeTested); } @Test void fromStringRecognizesEntry() throws ParseException { List<BibEntry> result = parser .parseEntries("@article{test,author={Ed von Test}}"); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result); } @Test void fromStringReturnsEmptyListFromEmptyString() throws ParseException { Collection<BibEntry> parsed = parser.parseEntries(""); assertEquals(Collections.emptyList(), parsed); } @Test void fromStringReturnsEmptyListIfNoEntryRecognized() throws ParseException { Collection<BibEntry> parsed = parser .parseEntries("@@article@@{{{{{{}"); assertEquals(Collections.emptyList(), parsed); } @Test void singleFromStringRecognizesEntry() throws ParseException { Optional<BibEntry> parsed = BibtexParser.singleFromString( """ @article{canh05, author = {Crowston, K. and Annabi, H.}, title = {Title A}} """, importFormatPreferences); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("canh05") .withField(StandardField.AUTHOR, "Crowston, K. and Annabi, H.") .withField(StandardField.TITLE, "Title A"); assertEquals(Optional.of(expected), parsed); } @Test void singleFromStringRecognizesEntryInMultiple() throws ParseException { Optional<BibEntry> parsed = BibtexParser.singleFromString(""" @article{canh05, author = {Crowston, K. and Annabi, H.}, title = {Title A}} @inProceedings{foo, author={Norton Bar}}""", importFormatPreferences); assertTrue(parsed.get().getCitationKey().equals(Optional.of("canh05")) || parsed.get().getCitationKey().equals(Optional.of("foo"))); } @Test void singleFromStringReturnsEmptyFromEmptyString() throws ParseException { Optional<BibEntry> parsed = BibtexParser.singleFromString("", importFormatPreferences); assertEquals(Optional.empty(), parsed); } @Test void singleFromStringReturnsEmptyIfNoEntryRecognized() throws ParseException { Optional<BibEntry> parsed = BibtexParser.singleFromString("@@article@@{{{{{{}", importFormatPreferences); assertEquals(Optional.empty(), parsed); } @Test void parseRecognizesEntry() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={Ed von Test}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesFieldValuesInQuotationMarks() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author=\"Ed von Test\"}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryOnlyWithKey() throws IOException { ParserResult result = parser.parse(new StringReader("@article{test}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWithWhitespaceAtBeginning() throws IOException { ParserResult result = parser .parse(new StringReader(" @article{test,author={Ed von Test}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withUserComments(" ") .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWithWhitespace() throws IOException { ParserResult result = parser .parse(new StringReader("@article { test,author={Ed von Test}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWithNewlines() throws IOException { ParserResult result = parser .parse(new StringReader("@article\n{\ntest,author={Ed von Test}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWithUnknownType() throws IOException { ParserResult result = parser .parse(new StringReader("@unknown{test,author={Ed von Test}}")); BibEntry expected = new BibEntry(new UnknownEntryType("unknown")) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWithVeryLongType() throws IOException { ParserResult result = parser.parse( new StringReader("@thisIsALongStringToTestMaybeItIsToLongWhoKnowsNOTme{test,author={Ed von Test}}")); BibEntry expected = new BibEntry(new UnknownEntryType("thisisalongstringtotestmaybeitistolongwhoknowsnotme")) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryInParenthesis() throws IOException { ParserResult result = parser .parse(new StringReader("@article(test,author={Ed von Test})")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWithBigNumbers() throws IOException { ParserResult result = parser.parse(new StringReader(""" @article{canh05,isbn = 1234567890123456789, isbn2 = {1234567890123456789}, small = 1234, }""")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("canh05") .withField(StandardField.ISBN, "1234567890123456789") .withField(new UnknownField("isbn2"), "1234567890123456789") .withField(new UnknownField("small"), "1234"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesCitationKeyWithSpecialCharacters() throws IOException { ParserResult result = parser .parse(new StringReader("@article{te_st:with-special(characters),author={Ed von Test}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("te_st:with-special(characters)") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWhereLastFieldIsFinishedWithComma() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={Ed von Test},}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryWithAtInField() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={Ed von T@st}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(InternalField.KEY_FIELD, "test") .withField(StandardField.AUTHOR, "Ed von T@st"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesEntryPrecedingComment() throws IOException { String comment = "@Comment{@article{myarticle,}" + OS.NEWLINE + "@inproceedings{blabla, title={the proceedings of bl@bl@}; }" + OS.NEWLINE + "}" + OS.NEWLINE; String entryWithComment = comment + "@article{test,author={Ed von T@st}}"; BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(InternalField.KEY_FIELD, "test") .withField(StandardField.AUTHOR, "Ed von T@st"); expected.setCommentsBeforeEntry(comment); ParserResult result = parser.parse(new StringReader(entryWithComment)); List<BibEntry> parsed = result.getDatabase().getEntries(); assertEquals(List.of(expected), parsed); assertEquals(expected.getUserComments(), parsed.get(0).getUserComments()); } @Test void parseRecognizesMultipleEntries() throws IOException { ParserResult result = parser.parse( new StringReader(""" @article{canh05, author = {Crowston, K. and Annabi, H.}, title = {Title A}} @inProceedings{foo, author={Norton Bar}}""")); List<BibEntry> expected = List.of( new BibEntry(StandardEntryType.Article) .withCitationKey("canh05") .withField(StandardField.AUTHOR, "Crowston, K. and Annabi, H.") .withField(StandardField.TITLE, "Title A"), new BibEntry(StandardEntryType.InProceedings) .withCitationKey("foo") .withField(StandardField.AUTHOR, "Norton Bar")); assertEquals(expected, result.getDatabase().getEntries()); } @Test void parseSetsParsedSerialization() throws IOException { String firstEntry = "@article{canh05," + " author = {Crowston, K. and Annabi, H.}," + OS.NEWLINE + " title = {Title A}}" + OS.NEWLINE; String secondEntry = "@inProceedings{foo," + " author={Norton Bar}}"; List<BibEntry> parsedEntries = parser.parse(new StringReader(firstEntry + secondEntry)) .getDatabase().getEntries(); assertEquals(firstEntry, parsedEntries.get(0).getParsedSerialization()); assertEquals(secondEntry, parsedEntries.get(1).getParsedSerialization()); } @Test void parseRecognizesMultipleEntriesOnSameLine() throws IOException { ParserResult result = parser .parse(new StringReader("@article{canh05}" + "@inProceedings{foo}")); List<BibEntry> expected = List.of( new BibEntry(StandardEntryType.Article) .withCitationKey("canh05"), new BibEntry(StandardEntryType.InProceedings) .withCitationKey("foo")); assertEquals(expected, result.getDatabase().getEntries()); } @Test void parseCombinesMultipleAuthorFields() throws IOException { ParserResult result = parser.parse( new StringReader("@article{test,author={Ed von Test},author={Second Author},author={Third Author}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test and Second Author and Third Author"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseCombinesMultipleEditorFields() throws IOException { ParserResult result = parser.parse( new StringReader("@article{test,editor={Ed von Test},editor={Second Author},editor={Third Author}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.EDITOR, "Ed von Test and Second Author and Third Author"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseCombinesMultipleKeywordsFields() throws IOException { ParserResult result = parser.parse( new StringReader("@article{test,Keywords={Test},Keywords={Second Keyword},Keywords={Third Keyword}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.KEYWORDS, "Test, Second Keyword, Third Keyword"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesHeaderButIgnoresEncoding() throws IOException { ParserResult result = parser.parse(new StringReader(""" This file was created with JabRef 2.1 beta 2. Encoding: Cp1252 @INPROCEEDINGS{CroAnnHow05, author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}, title = {Effective work practices for floss development: A model and propositions}, booktitle = {Hawaii International Conference On System Sciences (HICSS)}, year = {2005}, owner = {oezbek}, timestamp = {2006.05.29}, url = {http://james.howison.name/publications.html} }))""")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(Optional.empty(), result.getMetaData().getEncoding()); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.InProceedings, entry.getType()); assertEquals(8, entry.getFields().size()); assertEquals(Optional.of("CroAnnHow05"), entry.getCitationKey()); assertEquals(Optional.of("Crowston, K. and Annabi, H. and Howison, J. and Masango, C."), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Effective work practices for floss development: A model and propositions"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("Hawaii International Conference On System Sciences (HICSS)"), entry.getField(StandardField.BOOKTITLE)); assertEquals(Optional.of("2005"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("oezbek"), entry.getField(StandardField.OWNER)); assertEquals(Optional.of("2006.05.29"), entry.getField(StandardField.TIMESTAMP)); assertEquals(Optional.of("http://james.howison.name/publications.html"), entry.getField(StandardField.URL)); } @Test void parseRecognizesFormatedEntry() throws IOException { ParserResult result = parser.parse( new StringReader(""" @INPROCEEDINGS{CroAnnHow05, author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}, title = {Effective work practices for floss development: A model and propositions}, booktitle = {Hawaii International Conference On System Sciences (HICSS)}, year = {2005}, owner = {oezbek}, timestamp = {2006.05.29}, url = {http://james.howison.name/publications.html} }))""")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.InProceedings, entry.getType()); assertEquals(8, entry.getFields().size()); assertEquals(Optional.of("CroAnnHow05"), entry.getCitationKey()); assertEquals(Optional.of("Crowston, K. and Annabi, H. and Howison, J. and Masango, C."), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Effective work practices for floss development: A model and propositions"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("Hawaii International Conference On System Sciences (HICSS)"), entry.getField(StandardField.BOOKTITLE)); assertEquals(Optional.of("2005"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("oezbek"), entry.getField(StandardField.OWNER)); assertEquals(Optional.of("2006.05.29"), entry.getField(StandardField.TIMESTAMP)); assertEquals(Optional.of("http://james.howison.name/publications.html"), entry.getField(StandardField.URL)); } @Test void parseRecognizesNumbersWithoutBracketsOrQuotationMarks() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,year = 2005}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.YEAR, "2005"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesUppercaseFields() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,AUTHOR={Ed von Test}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesAbsoluteFile() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,file = {D:\\Documents\\literature\\Tansel-PRL2006.pdf}}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.FILE, "D:\\Documents\\literature\\Tansel-PRL2006.pdf"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseRecognizesFinalSlashAsSlash() throws Exception { ParserResult result = parser .parse(new StringReader(""" @misc{, test = {wired\\}, } """)); assertEquals( List.of(new BibEntry() .withField(new UnknownField("test"), "wired\\")), result.getDatabase().getEntries() ); } /** * JabRef's heuristics is not able to parse this special case. */ @Test void parseFailsWithFinalSlashAsSlashWhenSingleLine() throws Exception { ParserResult parserResult = parser.parse(new StringReader("@misc{, test = {wired\\}}")); // In case JabRef was more relaxed, `assertFalse` would be provided here. assertTrue(parserResult.hasWarnings()); } @Test void parseRecognizesDateFieldWithConcatenation() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,date = {1-4~} # nov}")); BibEntry expected = new BibEntry(StandardEntryType.Article) .withCitationKey("test") .withField(StandardField.DATE, "1-4~#nov#"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseReturnsEmptyListIfNoEntryRecognized() throws IOException { ParserResult result = parser.parse( new StringReader(""" author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.}, title = {Effective work practices for floss development: A model and propositions}, booktitle = {Hawaii International Conference On System Sciences (HICSS)}, year = {2005}, owner = {oezbek}, timestamp = {2006.05.29}, url = {http://james.howison.name/publications.html} }))""")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); assertEquals(0, parsed.size()); } @Test void parseReturnsEmptyListIfNoEntryExistent() throws IOException { ParserResult result = parser .parse(new StringReader(""" This was created with JabRef 2.1 beta 2. Encoding: Cp1252 """)); assertEquals(List.of(), result.getDatabase().getEntries()); } @Test void parseNotWarnsAboutEntryWithoutCitationKey() throws IOException { ParserResult result = parser .parse(new StringReader("@article{,author={Ed von Test}}")); assertFalse(result.hasWarnings()); BibEntry expected = new BibEntry(StandardEntryType.Article) .withField(StandardField.AUTHOR, "Ed von Test"); assertEquals(List.of(expected), result.getDatabase().getEntries()); } @Test void parseIgnoresAndWarnsAboutEntryWithUnmatchedOpenBracket() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={author missing bracket}")); assertTrue(result.hasWarnings()); assertEquals(List.of(), result.getDatabase().getEntries()); } @Test void parseAddsEscapedOpenBracketToFieldValue() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,review={escaped \\{ bracket}}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(Optional.of("escaped \\{ bracket"), entry.getField(StandardField.REVIEW)); assertFalse(result.hasWarnings()); } @Test void parseAddsEscapedClosingBracketToFieldValue() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,review={escaped \\} bracket}}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(Optional.of("escaped \\} bracket"), entry.getField(StandardField.REVIEW)); assertFalse(result.hasWarnings()); } @Test void parseIgnoresAndWarnsAboutEntryWithUnmatchedOpenBracketInQuotationMarks() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author=\"author {missing bracket\"}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); assertEquals(0, parsed.size()); assertTrue(result.hasWarnings()); } @Test void parseIgnoresArbitraryContentAfterEntry() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={author bracket }}}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); assertEquals(1, parsed.size(), "Size should be one, but was " + parsed.size()); assertEquals("}", result.getDatabase().getEpilog(), "Epilog should be preserved"); } @Test void parseWarnsAboutUnmatchedContentInEntryWithoutComma() throws IOException { ParserResult result = parser.parse(new StringReader("@article{test,author={author bracket } too much}")); List<BibEntry> entries = result.getDatabase().getEntries(); assertEquals(Optional.of("author bracket #too##much#"), entries.get(0).getField(StandardField.AUTHOR)); } @Test void parseWarnsAboutUnmatchedContentInEntry() throws IOException { ParserResult result = parser.parse(new StringReader("@article{test,author={author bracket }, too much}")); List<BibEntry> entries = result.getDatabase().getEntries(); assertTrue(result.hasWarnings(), "There should be warnings"); assertEquals(0, entries.size(), "Size should be zero, but was " + entries.size()); } @Test void parseAcceptsEntryWithAtSymbolInBrackets() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={author @ good}}")); List<BibEntry> entries = result.getDatabase().getEntries(); assertEquals(1, entries.size()); assertEquals(Optional.of("author @ good"), entries.get(0).getField(StandardField.AUTHOR)); } @Test void parseRecognizesEntryWithAtSymbolInQuotationMarks() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author=\"author @ good\"}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(2, entry.getFields().size()); assertEquals(Optional.of("author @ good"), entry.getField(StandardField.AUTHOR)); } @Test void parseRecognizesFieldsWithBracketsEnclosedInQuotationMarks() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author=\"Test {Ed {von} Test}\"}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(2, entry.getFields().size()); assertEquals(Optional.of("Test {Ed {von} Test}"), entry.getField(StandardField.AUTHOR)); } @Test void parseRecognizesFieldsWithEscapedQuotationMarks() throws IOException { // Quotes in fields of the form key = "value" have to be escaped by putting them into braces ParserResult result = parser .parse(new StringReader("@article{test,author=\"Test {\" Test}\"}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(2, entry.getFields().size()); assertEquals(Optional.of("Test {\" Test}"), entry.getField(StandardField.AUTHOR)); } @Test void parseIgnoresAndWarnsAboutEntryWithFieldsThatAreNotSeperatedByComma() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={Ed von Test} year=2005}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); assertEquals(0, parsed.size()); assertTrue(result.hasWarnings()); } @Test void parseIgnoresAndWarnsAboutCorruptedEntryButRecognizeOthers() throws IOException { ParserResult result = parser.parse( new StringReader( "@article{test,author={author missing bracket}" + "@article{test,author={Ed von Test}}")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(2, entry.getFields().size()); assertEquals(Optional.of("Ed von Test"), entry.getField(StandardField.AUTHOR)); assertTrue(result.hasWarnings()); } @Test void parseRecognizesMonthFieldsWithFollowingComma() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={Ed von Test},month={8,}},")); Collection<BibEntry> parsed = result.getDatabase().getEntries(); BibEntry entry = parsed.iterator().next(); assertEquals(1, parsed.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(3, entry.getFields().size()); assertEquals(Optional.of("Ed von Test"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("8,"), entry.getField(StandardField.MONTH)); } @Test void parseRecognizesPreamble() throws IOException { ParserResult result = parser .parse(new StringReader("@preamble{some text and \\latex}")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test void parseRecognizesUppercasePreamble() throws IOException { ParserResult result = parser .parse(new StringReader("@PREAMBLE{some text and \\latex}")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test void parseRecognizesPreambleWithWhitespace() throws IOException { ParserResult result = parser .parse(new StringReader("@preamble {some text and \\latex}")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test void parseRecognizesPreambleInParenthesis() throws IOException { ParserResult result = parser .parse(new StringReader("@preamble(some text and \\latex)")); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test void parseRecognizesPreambleWithConcatenation() throws IOException { ParserResult result = parser .parse(new StringReader("@preamble{\"some text\" # \"and \\latex\"}")); assertEquals(Optional.of("\"some text\" # \"and \\latex\""), result.getDatabase().getPreamble()); } @Test void parseRecognizesString() throws IOException { ParserResult result = parser .parse(new StringReader("@string{bourdieu = {Bourdieu, Pierre}}")); BibtexString string = result.getDatabase().getStringValues().iterator().next(); assertEquals(1, result.getDatabase().getStringCount()); assertEquals("bourdieu", string.getName()); assertEquals("Bourdieu, Pierre", string.getContent()); } @Test void parseSavesOneNewlineAfterStringInParsedSerialization() throws IOException { String string = "@string{bourdieu = {Bourdieu, Pierre}}" + OS.NEWLINE; ParserResult result = parser .parse(new StringReader(string + OS.NEWLINE + OS.NEWLINE)); BibtexString parsedString = result.getDatabase().getStringValues().iterator().next(); assertEquals(1, result.getDatabase().getStringCount()); assertEquals(string, parsedString.getParsedSerialization()); } @Test void parseRecognizesStringWithWhitespace() throws IOException { ParserResult result = parser .parse(new StringReader("@string {bourdieu = {Bourdieu, Pierre}}")); BibtexString parsedString = result.getDatabase().getStringValues().iterator().next(); assertEquals(1, result.getDatabase().getStringCount()); assertEquals("bourdieu", parsedString.getName()); assertEquals("Bourdieu, Pierre", parsedString.getContent()); } @Test void parseRecognizesStringInParenthesis() throws IOException { ParserResult result = parser .parse(new StringReader("@string(bourdieu = {Bourdieu, Pierre})")); BibtexString parsedString = result.getDatabase().getStringValues().iterator().next(); assertEquals(1, result.getDatabase().getStringCount()); assertEquals("bourdieu", parsedString.getName()); assertEquals("Bourdieu, Pierre", parsedString.getContent()); } @Test void parseRecognizesMultipleStrings() throws IOException { ParserResult result = parser .parse(new StringReader("@string{bourdieu = {Bourdieu, Pierre}}" + "@string{adieu = {Adieu, Pierre}}")); Iterator<BibtexString> iterator = result.getDatabase().getStringValues().iterator(); BibtexString first = iterator.next(); BibtexString second = iterator.next(); // Sort them because we can't be sure about the order if ("adieu".equals(first.getName())) { BibtexString tmp = first; first = second; second = tmp; } assertEquals(2, result.getDatabase().getStringCount()); assertEquals("bourdieu", first.getName()); assertEquals("Bourdieu, Pierre", first.getContent()); assertEquals("adieu", second.getName()); assertEquals("Adieu, Pierre", second.getContent()); } @Test void parseRecognizesStringAndEntry() throws IOException { ParserResult result = parser.parse( new StringReader("" + "@string{bourdieu = {Bourdieu, Pierre}}" + "@book{bourdieu-2002-questions-sociologie, " + " Address = {Paris}," + " Author = bourdieu," + " Isbn = 2707318256," + " Publisher = {Minuit}," + " Title = {Questions de sociologie}," + " Year = 2002" + "}")); BibtexString parsedString = result.getDatabase().getStringValues().iterator().next(); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, result.getDatabase().getStringCount()); assertEquals("bourdieu", parsedString.getName()); assertEquals("Bourdieu, Pierre", parsedString.getContent()); assertEquals(1, parsedEntries.size()); assertEquals(StandardEntryType.Book, parsedEntry.getType()); assertEquals(Optional.of("bourdieu-2002-questions-sociologie"), parsedEntry.getCitationKey()); assertEquals(Optional.of("Paris"), parsedEntry.getField(StandardField.ADDRESS)); assertEquals(Optional.of("#bourdieu#"), parsedEntry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("2707318256"), parsedEntry.getField(StandardField.ISBN)); assertEquals(Optional.of("Minuit"), parsedEntry.getField(StandardField.PUBLISHER)); assertEquals(Optional.of("Questions de sociologie"), parsedEntry.getField(StandardField.TITLE)); assertEquals(Optional.of("2002"), parsedEntry.getField(StandardField.YEAR)); } @Test void parseWarnsAboutStringsWithSameNameAndOnlyKeepsOne() throws IOException { ParserResult result = parser .parse(new StringReader("@string{bourdieu = {Bourdieu, Pierre}}" + "@string{bourdieu = {Other}}")); assertTrue(result.hasWarnings()); assertEquals(1, result.getDatabase().getStringCount()); } @Test void parseIgnoresComments() throws IOException { ParserResult result = parser .parse(new StringReader("@comment{some text and \\latex}")); assertEquals(0, result.getDatabase().getEntries().size()); } @Test void parseIgnoresUpercaseComments() throws IOException { ParserResult result = parser .parse(new StringReader("@COMMENT{some text and \\latex}")); assertEquals(0, result.getDatabase().getEntries().size()); } @Test void parseIgnoresCommentsBeforeEntry() throws IOException { ParserResult result = parser .parse(new StringReader("@comment{some text and \\latex}" + "@article{test,author={Ed von Test}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(StandardEntryType.Article, parsedEntry.getType()); assertEquals(Optional.of("test"), parsedEntry.getCitationKey()); assertEquals(2, parsedEntry.getFields().size()); assertEquals(Optional.of("Ed von Test"), parsedEntry.getField(StandardField.AUTHOR)); } @Test void parseIgnoresCommentsAfterEntry() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={Ed von Test}}" + "@comment{some text and \\latex}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(StandardEntryType.Article, parsedEntry.getType()); assertEquals(Optional.of("test"), parsedEntry.getCitationKey()); assertEquals(2, parsedEntry.getFields().size()); assertEquals(Optional.of("Ed von Test"), parsedEntry.getField(StandardField.AUTHOR)); } @Test void parseIgnoresText() throws IOException { ParserResult result = parser .parse(new StringReader("comment{some text and \\latex")); assertEquals(0, result.getDatabase().getEntries().size()); } @Test void parseIgnoresTextBeforeEntry() throws IOException { ParserResult result = parser .parse(new StringReader("comment{some text and \\latex" + "@article{test,author={Ed von Test}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(StandardEntryType.Article, parsedEntry.getType()); assertEquals(Optional.of("test"), parsedEntry.getCitationKey()); assertEquals(2, parsedEntry.getFields().size()); assertEquals(Optional.of("Ed von Test"), parsedEntry.getField(StandardField.AUTHOR)); } @Test void parseIgnoresTextAfterEntry() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author={Ed von Test}}" + "comment{some text and \\latex")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(StandardEntryType.Article, parsedEntry.getType()); assertEquals(Optional.of("test"), parsedEntry.getCitationKey()); assertEquals(2, parsedEntry.getFields().size()); assertEquals(Optional.of("Ed von Test"), parsedEntry.getField(StandardField.AUTHOR)); } @Test void parseConvertsNewlineToSpace() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,a = {a\nb}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("a"))); } @Test void parseConvertsMultipleNewlinesToSpace() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,a = {a\n\nb}," + "b = {a\n \nb}," + "c = {a \n \n b}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("a"))); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("b"))); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("c"))); } @Test void parseConvertsTabToSpace() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,a = {a\tb}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("a"))); } @Test void parseConvertsMultipleTabsToSpace() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,a = {a\t\tb}," + "b = {a\t \tb}," + "c = {a \t \t b}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("a"))); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("b"))); assertEquals(Optional.of("a b"), parsedEntry.getField(new UnknownField("c"))); } @Test void parsePreservesMultipleSpacesInNonWrappableField() throws IOException { when(importFormatPreferences.fieldPreferences().getNonWrappableFields()).thenReturn( FXCollections.observableArrayList(List.of(StandardField.FILE))); BibtexParser parser = new BibtexParser(importFormatPreferences); ParserResult result = parser .parse(new StringReader("@article{canh05,file = {ups sala}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(Optional.of("ups sala"), parsedEntry.getField(StandardField.FILE)); } @Test void parsePreservesTabsInAbstractField() throws IOException { ParserResult result = parser.parse(new StringReader("@article{canh05,abstract = {ups \tsala}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(Optional.of("ups \tsala"), parsedEntry.getField(StandardField.ABSTRACT)); } @Test void parsePreservesNewlineInAbstractField() throws IOException { ParserResult result = parser.parse(new StringReader("@article{canh05,abstract = {ups \nsala}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(Optional.of("ups \nsala"), parsedEntry.getField(StandardField.ABSTRACT)); } @Test void parseHandlesAccentsCorrectly() throws IOException { ParserResult result = parser .parse(new StringReader("@article{test,author = {H'{e}lne Fiaux}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertFalse(result.hasWarnings()); assertEquals(1, parsedEntries.size()); assertEquals(StandardEntryType.Article, parsedEntry.getType()); assertEquals(Optional.of("test"), parsedEntry.getCitationKey()); assertEquals(Optional.of("H'{e}lne Fiaux"), parsedEntry.getField(StandardField.AUTHOR)); } /** * Test for <a href="https://github.com/JabRef/jabref/issues/669">#669</a> */ @Test void parsePreambleAndEntryWithoutNewLine() throws IOException { ParserResult result = parser .parse(new StringReader("@preamble{some text and \\latex}@article{test,author = {H'{e}lne Fiaux}}")); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertFalse(result.hasWarnings()); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); assertEquals(1, parsedEntries.size()); assertEquals(StandardEntryType.Article, parsedEntry.getType()); assertEquals(Optional.of("test"), parsedEntry.getCitationKey()); assertEquals(Optional.of("H'{e}lne Fiaux"), parsedEntry.getField(StandardField.AUTHOR)); } @Test void parseFileHeaderAndPreambleWithoutNewLine() throws IOException { ParserResult result = parser .parse(new StringReader("\\% Encoding: US-ASCII@preamble{some text and \\latex}")); assertFalse(result.hasWarnings()); assertEquals(Optional.of("some text and \\latex"), result.getDatabase().getPreamble()); } @Test void parseSavesEntryInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; ParserResult result = parser.parse(new StringReader(testEntry)); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(testEntry, parsedEntry.getParsedSerialization()); } @Test void parseSavesOneNewlineAfterEntryInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; ParserResult result = parser .parse(new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE)); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(testEntry + OS.NEWLINE, parsedEntry.getParsedSerialization()); } @Test void parseSavesAllButOneNewlinesBeforeEntryInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; ParserResult result = parser .parse(new StringReader(OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntry)); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); // The first newline is removed, because JabRef interprets that always as block separator assertEquals(OS.NEWLINE + OS.NEWLINE + testEntry, parsedEntry.getParsedSerialization()); } @Test void parseRemovesEncodingLineAndSeparatorInParsedSerialization() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; ParserResult result = parser.parse( new StringReader(SaveConfiguration.ENCODING_PREFIX + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntry)); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); // First two newlines are removed because of removal of "Encoding" // Third newline removed because of block functionality assertEquals(testEntry, parsedEntry.getParsedSerialization()); } @Test void parseSavesNewlinesBetweenEntriesInParsedSerialization() throws IOException { String testEntryOne = "@article{test1,author={Ed von Test}}"; String testEntryTwo = "@article{test2,author={Ed von Test}}"; ParserResult result = parser .parse(new StringReader(testEntryOne + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + testEntryTwo)); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); Iterator<BibEntry> iterator = parsedEntries.iterator(); BibEntry first = iterator.next(); BibEntry second = iterator.next(); // Sort them because we can't be sure about the order if (first.getCitationKey().equals(Optional.of("test2"))) { BibEntry tmp = first; first = second; second = tmp; } assertEquals(2, parsedEntries.size()); assertEquals(testEntryOne + OS.NEWLINE, first.getParsedSerialization()); // one newline is removed, because it is written by JabRef's block functionality assertEquals(OS.NEWLINE + testEntryTwo, second.getParsedSerialization()); } @Test void parseIgnoresWhitespaceInEpilogue() throws IOException { ParserResult result = parser.parse(new StringReader(" " + OS.NEWLINE)); assertEquals("", result.getDatabase().getEpilog()); } @Test void parseIgnoresWhitespaceInEpilogueAfterEntry() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; ParserResult result = parser .parse(new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + " " + OS.NEWLINE)); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(testEntry + OS.NEWLINE, parsedEntry.getParsedSerialization()); assertEquals("", result.getDatabase().getEpilog()); } @Test void parseTrimsWhitespaceInEpilogueAfterEntry() throws IOException { String testEntry = "@article{test,author={Ed von Test}}"; ParserResult result = parser .parse(new StringReader(testEntry + OS.NEWLINE + OS.NEWLINE + OS.NEWLINE + " epilogue " + OS.NEWLINE)); Collection<BibEntry> parsedEntries = result.getDatabase().getEntries(); BibEntry parsedEntry = parsedEntries.iterator().next(); assertEquals(1, parsedEntries.size()); assertEquals(testEntry + OS.NEWLINE, parsedEntry.getParsedSerialization()); assertEquals("epilogue", result.getDatabase().getEpilog()); } @Test void parseRecognizesSaveActionsAfterEntry() throws IOException { ParserResult parserResult = parser.parse( new StringReader(""" @InProceedings{6055279, Title = {Educational session 1}, Booktitle = {Custom Integrated Circuits Conference (CICC), 2011 IEEE}, Year = {2011}, Month = {Sept}, Pages = {1-7}, Abstract = {Start of the above-titled section of the conference proceedings record.}, DOI = {10.1109/CICC.2011.6055279}, ISSN = {0886-5930} } @comment{jabref-meta: saveActions:enabled;title[lower_case]}""")); FieldFormatterCleanups saveActions = parserResult.getMetaData().getSaveActions().get(); assertTrue(saveActions.isEnabled()); assertEquals(List.of(new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter())), saveActions.getConfiguredActions()); } @Test void parserKeepsSaveActions() throws IOException { ParserResult parserResult = parser.parse( new StringReader(""" @InProceedings{6055279, Title = {Educational session 1}, Booktitle = {Custom Integrated Circuits Conference (CICC), 2011 IEEE}, Year = {2011}, Month = {Sept}, Pages = {1-7}, Abstract = {Start of the above-titled section of the conference proceedings record.}, DOI = {10.1109/CICC.2011.6055279}, ISSN = {0886-5930} } @Comment{jabref-meta: saveActions:enabled; 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] ;} """)); FieldFormatterCleanups saveActions = parserResult.getMetaData().getSaveActions().get(); assertTrue(saveActions.isEnabled()); 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, saveActions.getConfiguredActions()); } @Test void parseRecognizesCRLFLineBreak() throws IOException { ParserResult result = parser.parse( new StringReader("@InProceedings{6055279,\r\n" + " Title = {Educational session 1},\r\n" + " Booktitle = {Custom Integrated Circuits Conference (CICC), 2011 IEEE},\r\n" + " Year = {2011},\r\n" + " Month = {Sept},\r\n" + " Pages = {1-7},\r\n" + " Abstract = {Start of the above-titled section of the conference proceedings record.},\r\n" + " DOI = {10.1109/CICC.2011.6055279},\r\n" + " ISSN = {0886-5930}\r\n" + "}\r\n")); assertEquals("\r\n", result.getDatabase().getNewLineSeparator()); } @Test void parseRecognizesLFLineBreak() throws IOException { ParserResult result = parser.parse( new StringReader("@InProceedings{6055279,\n" + " Title = {Educational session 1},\n" + " Booktitle = {Custom Integrated Circuits Conference (CICC), 2011 IEEE},\n" + " Year = {2011},\n" + " Month = {Sept},\n" + " Pages = {1-7},\n" + " Abstract = {Start of the above-titled section of the conference proceedings record.},\n" + " DOI = {10.1109/CICC.2011.6055279},\n" + " ISSN = {0886-5930}\n" + "}\n")); assertEquals("\n", result.getDatabase().getNewLineSeparator()); } @Test void integrationTestSaveActions() throws IOException { ParserResult parserResult = parser .parse(new StringReader("@comment{jabref-meta: saveActions:enabled;title[lower_case]}")); FieldFormatterCleanups saveActions = parserResult.getMetaData().getSaveActions().get(); assertTrue(saveActions.isEnabled()); assertEquals(List.of(new FieldFormatterCleanup(StandardField.TITLE, new LowerCaseFormatter())), saveActions.getConfiguredActions()); } @Test void integrationTestBibEntryType() throws IOException { ParserResult result = parser.parse( new StringReader("@comment{jabref-entrytype: Lecturenotes: req[author;title] opt[language;url]}")); BibEntryType expectedEntryType = new BibEntryType( new UnknownEntryType("lecturenotes"), Arrays.asList( new BibField(StandardField.AUTHOR, FieldPriority.IMPORTANT), new BibField(StandardField.TITLE, FieldPriority.IMPORTANT), new BibField(StandardField.LANGUAGE, FieldPriority.IMPORTANT), new BibField(StandardField.URL, FieldPriority.IMPORTANT)), Arrays.asList( new OrFields(StandardField.AUTHOR), new OrFields(StandardField.TITLE) )); assertEquals(Collections.singleton(expectedEntryType), result.getEntryTypes()); } @Test void integrationTestSaveOrderConfig() throws IOException { ParserResult result = parser.parse( new StringReader( "@Comment{jabref-meta: saveOrderConfig:specified;author;false;year;true;abstract;false;}")); Optional<SaveOrder> saveOrderConfig = result.getMetaData().getSaveOrderConfig(); assertEquals(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))), saveOrderConfig.get()); } @Test void integrationTestCustomKeyPattern() throws IOException { ParserResult result = parser .parse(new StringReader("@comment{jabref-meta: keypattern_article:articleTest;}" + OS.NEWLINE + "@comment{jabref-meta: keypatterndefault:test;}")); GlobalCitationKeyPattern pattern = mock(GlobalCitationKeyPattern.class); AbstractCitationKeyPattern bibtexKeyPattern = result.getMetaData().getCiteKeyPattern(pattern); AbstractCitationKeyPattern expectedPattern = new DatabaseCitationKeyPattern(pattern); expectedPattern.setDefaultValue("test"); expectedPattern.addCitationKeyPattern(StandardEntryType.Article, "articleTest"); assertEquals(expectedPattern, bibtexKeyPattern); } @Test void integrationTestBiblatexMode() throws IOException { ParserResult result = parser .parse(new StringReader("@comment{jabref-meta: databaseType:biblatex;}")); Optional<BibDatabaseMode> mode = result.getMetaData().getMode(); assertEquals(BibDatabaseMode.BIBLATEX, mode.get()); } @Test void integrationTestGroupTree() throws IOException, ParseException { ParserResult result = parser.parse(new StringReader(""" @comment{jabref-meta: groupsversion:3;} @comment{jabref-meta: groupstree: 0 AllEntriesGroup:; 1 KeywordGroup:Fréchet\\;0\\;keywords\\;FrechetSpace\\;0\\;1\\;; 1 KeywordGroup:Invariant theory\\;0\\;keywords\\;GIT\\;0\\;0\\;; 1 ExplicitGroup:TestGroup\\;0\\;Key1\\;Key2\\;;}""")); GroupTreeNode root = result.getMetaData().getGroups().get(); assertEquals(new AllEntriesGroup("All entries"), root.getGroup()); assertEquals(3, root.getNumberOfChildren()); assertEquals( new RegexKeywordGroup("Fréchet", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, "FrechetSpace", false), root.getChildren().get(0).getGroup()); assertEquals( new WordKeywordGroup("Invariant theory", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, "GIT", false, ',', false), root.getChildren().get(1).getGroup()); assertEquals(Arrays.asList("Key1", "Key2"), ((ExplicitGroup) root.getChildren().get(2).getGroup()).getLegacyEntryKeys()); } /** * Checks that a TexGroup finally gets the required data, after parsing the library. */ @Test void integrationTestTexGroup() throws Exception { ParserResult result = parser.parse(new StringReader( "@comment{jabref-meta: grouping:" + OS.NEWLINE + "0 AllEntriesGroup:;" + OS.NEWLINE + "1 TexGroup:cited entries\\;0\\;paper.aux\\;1\\;0x8a8a8aff\\;\\;\\;;" + "}" + OS.NEWLINE + "@Comment{jabref-meta: databaseType:biblatex;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory:src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectory-" + System.getProperty("user.name") + "-" + InetAddress.getLocalHost().getHostName() + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE + "@Comment{jabref-meta: fileDirectoryLatex-" + System.getProperty("user.name") + "-" + InetAddress.getLocalHost().getHostName() + ":src/test/resources/org/jabref/model/groups;}" + OS.NEWLINE )); GroupTreeNode root = result.getMetaData().getGroups().get(); assertEquals(((TexGroup) root.getChildren().get(0).getGroup()).getFilePath(), Path.of("src/test/resources/org/jabref/model/groups/paper.aux")); } @Test void integrationTestProtectedFlag() throws IOException { ParserResult result = parser .parse(new StringReader("@comment{jabref-meta: protectedFlag:true;}")); assertTrue(result.getMetaData().isProtected()); } @Test void integrationTestContentSelectors() throws IOException { ParserResult result = parser.parse( new StringReader("@Comment{jabref-meta: selector_pubstate:approved;captured;received;status;}")); List<String> values = new ArrayList<>(4); values.add("approved"); values.add("captured"); values.add("received"); values.add("status"); assertEquals(values, result.getMetaData().getContentSelectors().getSelectorValuesForField(StandardField.PUBSTATE)); } @Test void parseReallyUnknownType() throws Exception { String bibtexEntry = """ @ReallyUnknownType{test, Comment = {testentry} }"""; Collection<BibEntry> entries = parser.parseEntries(bibtexEntry); BibEntry expectedEntry = new BibEntry(); expectedEntry.setType(new UnknownEntryType("Reallyunknowntype")); expectedEntry.setCitationKey("test"); expectedEntry.setField(StandardField.COMMENT, "testentry"); assertEquals(List.of(expectedEntry), entries); } @Test void parseOtherTypeTest() throws Exception { String bibtexEntry = """ @Other{test, Comment = {testentry} }"""; Collection<BibEntry> entries = parser.parseEntries(bibtexEntry); BibEntry expectedEntry = new BibEntry(); expectedEntry.setType(new UnknownEntryType("Other")); expectedEntry.setCitationKey("test"); expectedEntry.setField(StandardField.COMMENT, "testentry"); assertEquals(List.of(expectedEntry), entries); } @Test void parseRecognizesDatabaseID() throws Exception { String expectedDatabaseID = "q1w2e3r4t5z6"; StringBuilder sharedDatabaseFileContent = new StringBuilder() .append("\\% DBID: ").append(expectedDatabaseID) .append(OS.NEWLINE) .append("@Article{a}"); ParserResult parserResult = parser.parse(new StringReader(sharedDatabaseFileContent.toString())); String actualDatabaseID = parserResult.getDatabase().getSharedDatabaseID().get(); assertEquals(expectedDatabaseID, actualDatabaseID); } @Test void parseDoesNotRecognizeDatabaseIDasUserComment() throws Exception { StringBuilder sharedDatabaseFileContent = new StringBuilder() .append("\\% Encoding: UTF-8").append(OS.NEWLINE) .append("\\% DBID: q1w2e3r4t5z6").append(OS.NEWLINE) .append("@Article{a}"); ParserResult parserResult = parser.parse(new StringReader(sharedDatabaseFileContent.toString())); List<BibEntry> entries = parserResult.getDatabase().getEntries(); assertEquals(1, entries.size()); assertEquals("", entries.get(0).getUserComments()); } @Test void integrationTestFileDirectories() throws IOException { ParserResult result = parser.parse( new StringReader("@comment{jabref-meta: fileDirectory:\\\\Literature\\\\;}" + "@comment{jabref-meta: fileDirectory-defaultOwner-user:D:\\\\Documents;}" + "@comment{jabref-meta: fileDirectoryLatex-defaultOwner-user:D:\\\\Latex;}")); assertEquals("\\Literature\\", result.getMetaData().getDefaultFileDirectory().get()); assertEquals("D:\\Documents", result.getMetaData().getUserFileDirectory("defaultOwner-user").get()); assertEquals("D:\\Latex", result.getMetaData().getLatexFileDirectory("defaultOwner-user").get().toString()); } @ParameterizedTest @CsvSource({ // single backslash kept "C:\\temp\\test", "\\\\servername\\path\\to\\file", "//servername/path/to/file", "."}) void fileDirectoriesUnmodified(String directory) throws IOException { ParserResult result = parser.parse( new StringReader("@comment{jabref-meta: fileDirectory:" + directory + "}")); assertEquals(directory, result.getMetaData().getDefaultFileDirectory().get()); } @ParameterizedTest @CsvSource({ "C:\\temp\\test, C:\\\\temp\\\\test", "\\\\servername\\path\\to\\file, \\\\\\\\servername\\\\path\\\\to\\\\file"}) void fileDirectoryWithDoubleEscapeIsRead(String expected, String provided) throws IOException { ParserResult result = parser.parse( new StringReader("@comment{jabref-meta: fileDirectory: " + provided + "}")); assertEquals(expected, result.getMetaData().getDefaultFileDirectory().get()); } @Test void parseReturnsEntriesInSameOrder() throws IOException { List<BibEntry> expected = new ArrayList<>(); BibEntry first = new BibEntry(); first.setType(StandardEntryType.Article); first.setCitationKey("a"); expected.add(first); BibEntry second = new BibEntry(); second.setType(StandardEntryType.Article); second.setCitationKey("b"); expected.add(second); BibEntry third = new BibEntry(); third.setType(StandardEntryType.InProceedings); third.setCitationKey("c"); expected.add(third); ParserResult result = parser .parse(new StringReader(""" @article{a} @article{b} @inProceedings{c}""")); assertEquals(expected, result.getDatabase().getEntries()); } @Test void parsePrecedingComment() throws IOException { String bibtexEntry = """ % Some random comment that should stay here @Article{test, Author = {Foo Bar}, Journal = {International Journal of Something}, Note = {some note}, Number = {1} }"""; // read in bibtex string ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); assertEquals(1, entries.size()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(5, entry.getFields().size()); assertTrue(entry.getFields().contains(StandardField.AUTHOR)); assertEquals(Optional.of("Foo Bar"), entry.getField(StandardField.AUTHOR)); assertEquals(bibtexEntry, entry.getParsedSerialization()); } @Test void parseCommentAndEntryInOneLine() throws IOException { String bibtexEntry = """ Some random comment that should stay here @Article{test, Author = {Foo Bar}, Journal = {International Journal of Something}, Note = {some note}, Number = {1} }"""; // read in bibtex string ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); assertEquals(1, entries.size()); assertEquals(Optional.of("test"), entry.getCitationKey()); assertEquals(5, entry.getFields().size()); assertTrue(entry.getFields().contains(StandardField.AUTHOR)); assertEquals(Optional.of("Foo Bar"), entry.getField(StandardField.AUTHOR)); assertEquals(bibtexEntry, entry.getParsedSerialization()); } @Test void preserveEncodingPrefixInsideEntry() throws ParseException { BibEntry expected = new BibEntry(); expected.setType(StandardEntryType.Article); expected.setCitationKey("test"); expected.setField(StandardField.AUTHOR, SaveConfiguration.ENCODING_PREFIX); List<BibEntry> parsed = parser .parseEntries("@article{test,author={" + SaveConfiguration.ENCODING_PREFIX + "}}"); assertEquals(List.of(expected), parsed); } @Test void parseBracketedComment() throws IOException { String commentText = "@Comment{someComment}"; ParserResult result = parser.parse(new StringReader(commentText)); assertEquals(commentText, result.getDatabase().getEpilog()); } @Test void parseRegularCommentBeforeEntry() throws IOException { String bibtexEntry = """ @Comment{someComment} @Article{test, Author = {Foo Bar}, Journal = {International Journal of Something}, Note = {some note}, Number = {1} }"""; ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); assertEquals(bibtexEntry, entry.getParsedSerialization()); } @Test void parseCommentWithoutBrackets() throws IOException { String commentText = "@Comment someComment"; ParserResult result = parser.parse(new StringReader(commentText)); assertEquals(commentText, result.getDatabase().getEpilog()); } @Test void parseCommentWithoutBracketsBeforeEntry() throws IOException { String bibtexEntry = """ @Comment someComment @Article{test, Author = {Foo Bar}, Journal = {International Journal of Something}, Note = {some note}, Number = {1} }"""; ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); assertEquals(bibtexEntry, entry.getParsedSerialization()); } @Test void parseCommentContainingEntries() throws IOException { String bibtexEntry = """ @Comment{@article{myarticle,} @inproceedings{blabla, title={the proceedings of blabla}; } } @Article{test, Author = {Foo Bar}, Journal = {International Journal of Something}, Note = {some note}, Number = {1} }"""; ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); assertEquals(bibtexEntry, entry.getParsedSerialization()); } @Test void parseCommentContainingEntriesAndAtSymbols() throws IOException { String bibtexEntry = """ @Comment{@article{myarticle,} @inproceedings{blabla, title={the proceedings of bl@bl@}; } } @Article{test, Author = {Foo@Bar}, Journal = {International Journal of Something}, Note = {some note}, Number = {1} }"""; ParserResult result = parser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); BibEntry entry = entries.iterator().next(); assertEquals(bibtexEntry, entry.getParsedSerialization()); } @Test void parseEmptyPreambleLeadsToEmpty() throws IOException { ParserResult result = parser.parse(new StringReader("@preamble{}")); assertFalse(result.hasWarnings()); assertEquals(Optional.empty(), result.getDatabase().getPreamble()); } @Test void parseEmptyFileLeadsToPreamble() throws IOException { ParserResult result = parser.parse(new StringReader("")); assertFalse(result.hasWarnings()); assertEquals(Optional.empty(), result.getDatabase().getPreamble()); } @Test void parseYearWithMonthString() throws Exception { Optional<BibEntry> result = parser.parseSingleEntry("@ARTICLE{HipKro03, year = {2003}, month = feb }"); assertEquals(new Date(2003, 2), result.get().getPublicationDate().get()); } @Test void parseYearWithIllFormattedMonthString() throws Exception { Optional<BibEntry> result = parser.parseSingleEntry("@ARTICLE{HipKro03, year = {2003}, month = #FEB# }"); assertEquals(new Date(2003, 2), result.get().getPublicationDate().get()); } @Test void parseYearWithMonthNumber() throws Exception { Optional<BibEntry> result = parser.parseSingleEntry("@ARTICLE{HipKro03, year = {2003}, month = 2 }"); assertEquals(new Date(2003, 2), result.get().getPublicationDate().get()); } @Test void parseYear() throws Exception { Optional<BibEntry> result = parser.parseSingleEntry("@ARTICLE{HipKro03, year = {2003} }"); assertEquals(new Date(2003), result.get().getPublicationDate().get()); } @Test void parseEntryUsingStringConstantsForTwoAuthorsWithEtAsStringConstant() throws ParseException { // source of the example: https://docs.jabref.org/fields/strings Collection<BibEntry> parsed = parser .parseEntries("@String { kopp = \"Kopp, Oliver\" }" + "@String { kubovy = \"Kubovy, Jan\" }" + "@String { et = \" and \" }" + "@Misc{m1, author = kopp # et # kubovy }"); BibEntry expectedEntry = new BibEntry(StandardEntryType.Misc) .withCitationKey("m1") .withField(StandardField.AUTHOR, "#kopp##et##kubovy#"); assertEquals(List.of(expectedEntry), parsed); } @Test void parseStringConstantsForTwoAuthorsHasCorrectBibTeXEntry() throws ParseException { // source of the example: https://docs.jabref.org/fields/strings Collection<BibEntry> parsed = parser .parseEntries("@String { kopp = \"Kopp, Oliver\" }" + "@String { kubovy = \"Kubovy, Jan\" }" + "@String { et = \" and \" }" + "@Misc{m2, author = kopp # \" and \" # kubovy }"); BibEntry expectedEntry = new BibEntry(StandardEntryType.Misc) .withCitationKey("m2") .withField(StandardField.AUTHOR, "#kopp# and #kubovy#"); assertEquals(List.of(expectedEntry), parsed); } @Test void parseStringConstantsForTwoAuthors() throws ParseException { // source of the example: https://docs.jabref.org/fields/strings Collection<BibEntry> parsed = parser .parseEntries("@String { kopp = \"Kopp, Oliver\" }" + "@String { kubovy = \"Kubovy, Jan\" }" + "@String { et = \" and \" }" + "@Misc{m2, author = kopp # \" and \" # kubovy }"); assertEquals("#kopp# and #kubovy#", parsed.iterator().next().getField(StandardField.AUTHOR).get()); } @Test void textAprilIsParsedAsMonthApril() throws ParseException { Optional<BibEntry> result = parser.parseSingleEntry("@Misc{m, month = \"apr\" }"); assertEquals(Month.APRIL, result.get().getMonth().get()); } @Test void textAprilIsDisplayedAsConstant() throws ParseException { Optional<BibEntry> result = parser.parseSingleEntry("@Misc{m, month = \"apr\" }"); assertEquals("apr", result.get().getField(StandardField.MONTH).get()); } @Test void bibTeXConstantAprilIsParsedAsMonthApril() throws ParseException { Optional<BibEntry> result = parser.parseSingleEntry("@Misc{m, month = apr }"); assertEquals(Month.APRIL, result.get().getMonth().get()); } @Test void bibTeXConstantAprilIsDisplayedAsConstant() throws ParseException { Optional<BibEntry> result = parser.parseSingleEntry("@Misc{m, month = apr }"); assertEquals("#apr#", result.get().getField(StandardField.MONTH).get()); } @Test void bibTeXConstantAprilIsParsedAsStringMonthAprilWhenReadingTheField() throws ParseException { Optional<BibEntry> result = parser.parseSingleEntry("@Misc{m, month = apr }"); assertEquals(Optional.of("#apr#"), result.get().getField(StandardField.MONTH)); } @Test void parseDuplicateKeywordsWithOnlyOneEntry() throws ParseException { Optional<BibEntry> result = parser.parseSingleEntry("@Article{,\n" + "Keywords={asdf,asdf,asdf},\n" + "}\n" + ""); BibEntry expectedEntry = new BibEntry(StandardEntryType.Article) .withField(StandardField.KEYWORDS, "asdf,asdf,asdf"); assertEquals(Optional.of(expectedEntry), result); } @Test void parseDuplicateKeywordsWithTwoEntries() throws Exception { BibEntry expectedEntryFirst = new BibEntry(StandardEntryType.Article) .withField(StandardField.KEYWORDS, "bbb") .withCitationKey("Test2017"); BibEntry expectedEntrySecond = new BibEntry(StandardEntryType.Article) .withField(StandardField.KEYWORDS, "asdf,asdf,asdf"); String entries = """ @Article{Test2017, keywords = {bbb}, } @Article{, keywords = {asdf,asdf,asdf}, }, """; ParserResult result = parser.parse(new StringReader(entries)); assertEquals(List.of(expectedEntryFirst, expectedEntrySecond), result.getDatabase().getEntries()); } }
84,831
44.4376
155
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/CffImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.BiblatexSoftwareField; 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; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class CffImporterTest { private CffImporter importer; @BeforeEach public void setUp() { importer = new CffImporter(); } @Test public void testGetFormatName() { assertEquals("CFF", importer.getName()); } @Test public void testGetCLIId() { assertEquals("cff", importer.getId()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.CFF, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Importer for the CFF format. Is only used to cite software, one entry per file.", importer.getDescription()); } @Test public void testIsRecognizedFormat() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestValid.cff").toURI()); assertTrue(importer.isRecognizedFormat(file)); } @Test public void testIsRecognizedFormatReject() throws IOException, URISyntaxException { List<String> list = Arrays.asList("CffImporterTestInvalid1.cff", "CffImporterTestInvalid2.cff"); for (String string : list) { Path file = Path.of(CffImporterTest.class.getResource(string).toURI()); assertFalse(importer.isRecognizedFormat(file)); } } @Test public void testImportEntriesBasic() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestValid.cff").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); BibEntry expected = getPopulatedEntry().withField(StandardField.AUTHOR, "Joe van Smith"); assertEquals(entry, expected); } @Test public void testImportEntriesMultipleAuthors() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestValidMultAuthors.cff").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); BibEntry expected = getPopulatedEntry(); assertEquals(entry, expected); } @Test public void testImportEntriesSwhIdSelect1() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestValidSwhIdSelect1.cff").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); BibEntry expected = getPopulatedEntry().withField(BiblatexSoftwareField.SWHID, "swh:1:rel:22ece559cc7cc2364edc5e5593d63ae8bd229f9f"); assertEquals(entry, expected); } @Test public void testImportEntriesSwhIdSelect2() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestValidSwhIdSelect2.cff").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); BibEntry expected = getPopulatedEntry().withField(BiblatexSoftwareField.SWHID, "swh:1:cnt:94a9ed024d3859793618152ea559a168bbcbb5e2"); assertEquals(entry, expected); } @Test public void testImportEntriesDataset() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestDataset.cff").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); BibEntry expected = getPopulatedEntry(); expected.setType(StandardEntryType.Dataset); assertEquals(entry, expected); } @Test public void testImportEntriesDoiSelect() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestDoiSelect.cff").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); BibEntry expected = getPopulatedEntry(); assertEquals(entry, expected); } @Test public void testImportEntriesUnknownFields() throws IOException, URISyntaxException { Path file = Path.of(CffImporterTest.class.getResource("CffImporterTestUnknownFields.cff").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); BibEntry expected = getPopulatedEntry().withField(new UnknownField("commit"), "10ad"); assertEquals(entry, expected); } public BibEntry getPopulatedEntry() { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Software); entry.setField(StandardField.AUTHOR, "Joe van Smith and Bob Jones, Jr."); entry.setField(StandardField.TITLE, "Test"); entry.setField(StandardField.URL, "www.google.com"); entry.setField(BiblatexSoftwareField.REPOSITORY, "www.github.com"); entry.setField(StandardField.DOI, "10.0000/TEST"); entry.setField(StandardField.DATE, "2000-07-02"); entry.setField(StandardField.COMMENT, "Test entry."); entry.setField(StandardField.ABSTRACT, "Test abstract."); entry.setField(BiblatexSoftwareField.LICENSE, "MIT"); entry.setField(StandardField.VERSION, "1.0"); return entry; } }
6,296
37.163636
141
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/CitaviXmlImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; public class CitaviXmlImporterFilesTest { private static final String FILE_ENDING = ".ctv6bak"; private final CitaviXmlImporter citaviXmlImporter = new CitaviXmlImporter(); private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("CitaviXmlImporterTest") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> invalidFileNames() throws IOException { Predicate<String> fileName = name -> !name.startsWith("CitaviXmlImporterTest"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @ParameterizedTest @MethodSource("fileNames") void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(citaviXmlImporter, fileName); } @ParameterizedTest @MethodSource("invalidFileNames") void testIsNotRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsNotRecognizedFormat(citaviXmlImporter, fileName); } @ParameterizedTest @MethodSource("fileNames") void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(citaviXmlImporter, fileName, FILE_ENDING); } }
1,577
35.697674
116
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/CitaviXmlImporterTest.java
package org.jabref.logic.importer.fileformat; 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; class CitaviXmlImporterTest { CitaviXmlImporter citaviXmlImporter = new CitaviXmlImporter(); public static Stream<Arguments> cleanUpText() { return Stream.of( Arguments.of("no action", "no action"), Arguments.of("\\{action\\}", "{action}"), Arguments.of("\\}", "}")); } @ParameterizedTest @MethodSource void cleanUpText(String expected, String input) { assertEquals(expected, citaviXmlImporter.cleanUpText(input)); } }
815
28.142857
69
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; public class CopacImporterFilesTest { private static final String FILE_ENDING = ".txt"; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("CopacImporterTest") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> nonCopacfileNames() throws IOException { Predicate<String> fileName = name -> !name.startsWith("CopacImporterTest"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(new CopacImporter(), fileName); } @ParameterizedTest @MethodSource("nonCopacfileNames") public void testIsNotRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsNotRecognizedFormat(new CopacImporter(), fileName); } @ParameterizedTest @MethodSource("fileNames") public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new CopacImporter(), fileName, FILE_ENDING); } }
1,525
34.488372
89
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/CopacImporterTest.java
package org.jabref.logic.importer.fileformat; import java.nio.file.Path; import java.util.Collections; import java.util.List; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class CopacImporterTest { private CopacImporter importer; @BeforeEach public void setUp() throws Exception { importer = new CopacImporter(); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.TXT, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Importer for COPAC format.", importer.getDescription()); } @Test public void testImportEmptyEntries() throws Exception { Path path = Path.of(CopacImporterTest.class.getResource("Empty.txt").toURI()); List<BibEntry> entries = importer.importDatabase(path).getDatabase().getEntries(); assertEquals(Collections.emptyList(), entries); } }
1,103
25.926829
90
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/CustomImporterTest.java
package org.jabref.logic.importer.fileformat; import java.nio.file.Path; import java.util.Arrays; import org.jabref.logic.importer.Importer; 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.assertTrue; public class CustomImporterTest { private CustomImporter importer; @BeforeEach public void setUp() throws Exception { importer = asCustomImporter(new CopacImporter()); } @Test public void testGetName() { assertEquals("Copac", importer.getName()); } @Test public void testGetId() { assertEquals("cpc", importer.getId()); } @Test public void testGetClassName() { assertEquals("org.jabref.logic.importer.fileformat.CopacImporter", importer.getClassName()); } @Test public void testGetBasePath() { assertEquals(Path.of("src/main/java/org/jabref/logic/importer/fileformat/CopacImporter.java"), importer.getBasePath()); } @Test public void testGetAsStringList() { assertEquals(Arrays.asList("src/main/java/org/jabref/logic/importer/fileformat/CopacImporter.java", "org.jabref.logic.importer.fileformat.CopacImporter"), importer.getAsStringList()); } @Test public void equalsWithSameReference() { assertEquals(importer, importer); } @Test public void equalsIsBasedOnName() { // noinspection AssertEqualsBetweenInconvertibleTypes assertEquals(new CopacImporter(), importer); } @Test public void testCompareToSmaller() throws Exception { CustomImporter ovidImporter = asCustomImporter(new OvidImporter()); assertTrue(importer.compareTo(ovidImporter) < 0); } @Test public void testCompareToEven() throws Exception { assertEquals(0, importer.compareTo(asCustomImporter(new CopacImporter()))); } @Test public void testToString() { assertEquals("Copac", importer.toString()); } @Test public void testClassicConstructor() throws Exception { CustomImporter customImporter = new CustomImporter( "src/main/java/org/jabref/logic/importer/fileformat/CopacImporter.java", "org.jabref.logic.importer.fileformat.CopacImporter"); assertEquals(importer, customImporter); } private CustomImporter asCustomImporter(Importer importer) throws Exception { return new CustomImporter( "src/main/java/org/jabref/logic/importer/fileformat/" + importer.getName() + "Importer.java", importer.getClass().getName()); } }
2,722
28.27957
109
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.StandardFileType; 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.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; public class EndnoteImporterTest { private EndnoteImporter importer; @BeforeEach public void setUp() { importer = new EndnoteImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test public void testGetFormatName() { assertEquals("Refer/Endnote", importer.getName()); } @Test public void testGetCLIId() { assertEquals("refer", importer.getId()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.ENDNOTE, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Importer for the Refer/Endnote format." + " Modified to use article number for pages if pages are missing.", importer.getDescription()); } @Test public void testIsRecognizedFormat() throws IOException, URISyntaxException { List<String> list = Arrays.asList("Endnote.pattern.A.enw", "Endnote.pattern.E.enw", "Endnote.book.example.enw"); for (String string : list) { Path file = Path.of(EndnoteImporterTest.class.getResource(string).toURI()); assertTrue(importer.isRecognizedFormat(file)); } } @Test public void testIsRecognizedFormatReject() throws IOException, URISyntaxException { List<String> list = Arrays.asList("IEEEImport1.txt", "IsiImporterTest1.isi", "IsiImporterTestInspec.isi", "IsiImporterTestWOS.isi", "IsiImporterTestMedline.isi", "RisImporterTest1.ris", "Endnote.pattern.no_enw", "empty.pdf", "annotated.pdf"); for (String string : list) { Path file = Path.of(EndnoteImporterTest.class.getResource(string).toURI()); assertFalse(importer.isRecognizedFormat(file)); } } @Test public void testImportEntries0() throws IOException, URISyntaxException { Path file = Path.of(EndnoteImporterTest.class.getResource("Endnote.entries.enw").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(5, bibEntries.size()); BibEntry first = bibEntries.get(0); assertEquals(StandardEntryType.Misc, first.getType()); assertEquals(Optional.of("testA0 and testA1"), first.getField(StandardField.AUTHOR)); assertEquals(Optional.of("testE0 and testE1"), first.getField(StandardField.EDITOR)); assertEquals(Optional.of("testT"), first.getField(StandardField.TITLE)); BibEntry second = bibEntries.get(1); assertEquals(StandardEntryType.Misc, second.getType()); assertEquals(Optional.of("testC"), second.getField(StandardField.ADDRESS)); assertEquals(Optional.of("testB2"), second.getField(StandardField.BOOKTITLE)); assertEquals(Optional.of("test8"), second.getField(StandardField.DATE)); assertEquals(Optional.of("test7"), second.getField(StandardField.EDITION)); assertEquals(Optional.of("testJ"), second.getField(StandardField.JOURNAL)); assertEquals(Optional.of("testD"), second.getField(StandardField.YEAR)); BibEntry third = bibEntries.get(2); assertEquals(StandardEntryType.Article, third.getType()); assertEquals(Optional.of("testB0"), third.getField(StandardField.JOURNAL)); BibEntry fourth = bibEntries.get(3); assertEquals(StandardEntryType.Book, fourth.getType()); assertEquals(Optional.of("testI0"), fourth.getField(StandardField.PUBLISHER)); assertEquals(Optional.of("testB1"), fourth.getField(StandardField.SERIES)); BibEntry fifth = bibEntries.get(4); assertEquals(StandardEntryType.MastersThesis, fifth.getType()); assertEquals(Optional.of("testX"), fifth.getField(StandardField.ABSTRACT)); assertEquals(Optional.of("testF"), fifth.getCitationKey()); assertEquals(Optional.of("testR"), fifth.getField(StandardField.DOI)); assertEquals(Optional.of("testK"), fifth.getField(StandardField.KEYWORDS)); assertEquals(Optional.of("testO1"), fifth.getField(StandardField.NOTE)); assertEquals(Optional.of("testN"), fifth.getField(StandardField.NUMBER)); assertEquals(Optional.of("testP"), fifth.getField(StandardField.PAGES)); assertEquals(Optional.of("testI1"), fifth.getField(StandardField.SCHOOL)); assertEquals(Optional.of("testU"), fifth.getField(StandardField.URL)); assertEquals(Optional.of("testV"), fifth.getField(StandardField.VOLUME)); } @Test public void testImportEntries1() throws IOException { String medlineString = "%O Artn\\\\s testO\n%A testA,\n%E testE0, testE1"; List<BibEntry> bibEntries = importer.importDatabase(new BufferedReader(new StringReader(medlineString))).getDatabase() .getEntries(); BibEntry entry = bibEntries.get(0); assertEquals(1, bibEntries.size()); assertEquals(StandardEntryType.Misc, entry.getType()); assertEquals(Optional.of("testA"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("testE0, testE1"), entry.getField(StandardField.EDITOR)); assertEquals(Optional.of("testO"), entry.getField(StandardField.PAGES)); } @Test public void testImportEntriesBookExample() throws IOException, URISyntaxException { Path file = Path.of(EndnoteImporterTest.class.getResource("Endnote.book.example.enw").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = bibEntries.get(0); assertEquals(1, bibEntries.size()); assertEquals(StandardEntryType.Book, entry.getType()); assertEquals(Optional.of("Heidelberg"), entry.getField(StandardField.ADDRESS)); assertEquals(Optional.of("Preißel, René and Stachmann, Bjørn"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("3., aktualisierte und erweiterte Auflage"), entry.getField(StandardField.EDITION)); assertEquals(Optional.of("Versionsverwaltung"), entry.getField(StandardField.KEYWORDS)); assertEquals(Optional.of("XX, 327"), entry.getField(StandardField.PAGES)); assertEquals(Optional.of("dpunkt.verlag"), entry.getField(StandardField.PUBLISHER)); assertEquals(Optional.of("Git : dezentrale Versionsverwaltung im Team : Grundlagen und Workflows"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("http://d-nb.info/107601965X"), entry.getField(StandardField.URL)); assertEquals(Optional.of("2016"), entry.getField(StandardField.YEAR)); } }
7,509
45.9375
126
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/EndnoteXmlImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.importer.ImportFormatPreferences; 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.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class EndnoteXmlImporterFilesTest { private static final String FILE_ENDING = ".xml"; private ImportFormatPreferences importFormatPreferences; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("EndnoteXmlImporterTest") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> invalidFileNames() throws IOException { Predicate<String> fileName = name -> !name.startsWith("EndnoteXmlImporterTest"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @BeforeEach void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(';'); } @ParameterizedTest @MethodSource("fileNames") void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(new EndnoteXmlImporter(importFormatPreferences), fileName); } @ParameterizedTest @MethodSource("invalidFileNames") void testIsNotRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsNotRecognizedFormat(new EndnoteXmlImporter(importFormatPreferences), fileName); } @ParameterizedTest @MethodSource("fileNames") void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new EndnoteXmlImporter(importFormatPreferences), fileName, FILE_ENDING); } }
2,095
36.428571
117
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/ImporterTestEngine.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.bibtex.BibEntryAssert; import org.jabref.logic.importer.ImportException; import org.jabref.logic.importer.Importer; import org.jabref.logic.importer.ParserResult; import org.jabref.model.entry.BibEntry; import org.junit.jupiter.api.Assertions; import static org.junit.jupiter.api.Assertions.assertEquals; public class ImporterTestEngine { private static final String TEST_RESOURCES = "src/test/resources/org/jabref/logic/importer/fileformat"; /** * @param fileNamePredicate A predicate that describes the files which contain tests * @return A collection with the names of files in the test folder * @throws IOException if there is a problem when trying to read the files in the file system */ public static Collection<String> getTestFiles(Predicate<String> fileNamePredicate) throws IOException { try (Stream<Path> stream = Files.list(Path.of(TEST_RESOURCES))) { return stream .map(path -> path.getFileName().toString()) .filter(fileNamePredicate) .collect(Collectors.toList()); } } public static void testIsRecognizedFormat(Importer importer, String fileName) throws IOException { Assertions.assertTrue(importer.isRecognizedFormat(getPath(fileName))); } public static void testIsNotRecognizedFormat(Importer importer, String fileName) throws IOException { Assertions.assertFalse(importer.isRecognizedFormat(getPath(fileName))); } public static void testImportEntries(Importer importer, String fileName, String fileType) throws IOException, ImportException { ParserResult parserResult = importer.importDatabase(getPath(fileName)); if (parserResult.isInvalid()) { throw new ImportException(parserResult.getErrorMessage()); } List<BibEntry> entries = parserResult.getDatabase() .getEntries(); BibEntryAssert.assertEquals(ImporterTestEngine.class, fileName.replaceAll(fileType, ".bib"), entries); } private static Path getPath(String fileName) throws IOException { try { return Path.of(ImporterTestEngine.class.getResource(fileName).toURI()); } catch (URISyntaxException e) { throw new IOException(e); } } public static void testImportMalformedFiles(Importer importer, String fileName) throws IOException { List<BibEntry> entries = importer.importDatabase(getPath(fileName)).getDatabase() .getEntries(); assertEquals(entries, new ArrayList<BibEntry>()); } }
3,023
39.864865
131
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/InspecImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.bibtex.BibEntryAssert; import org.jabref.logic.util.StandardFileType; 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.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class InspecImporterTest { private static final String FILE_ENDING = ".txt"; private InspecImporter importer; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("InspecImportTest") && !name.contains("False") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> nonInspecfileNames() throws IOException { Predicate<String> fileName = name -> !name.startsWith("InspecImportTest"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @BeforeEach public void setUp() throws Exception { this.importer = new InspecImporter(); } @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormatAccept(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(importer, fileName); } @ParameterizedTest @MethodSource("nonInspecfileNames") public void testIsRecognizedFormatReject(String fileName) throws IOException { ImporterTestEngine.testIsNotRecognizedFormat(importer, fileName); } @Test public void testCompleteBibtexEntryOnJournalPaperImport() throws IOException, URISyntaxException { BibEntry expectedEntry = new BibEntry(StandardEntryType.Article); expectedEntry.setField(StandardField.TITLE, "The SIS project : software reuse with a natural language approach"); expectedEntry.setField(StandardField.AUTHOR, "Prechelt, Lutz"); expectedEntry.setField(StandardField.YEAR, "1992"); expectedEntry.setField(StandardField.ABSTRACT, "Abstrakt"); expectedEntry.setField(StandardField.KEYWORDS, "key"); expectedEntry.setField(StandardField.JOURNAL, "10000"); expectedEntry.setField(StandardField.PAGES, "20"); expectedEntry.setField(StandardField.VOLUME, "19"); BibEntryAssert.assertEquals(Collections.singletonList(expectedEntry), InspecImporterTest.class.getResource("InspecImportTest2.txt"), importer); } @Test public void importConferencePaperGivesInproceedings() throws IOException { String testInput = "Record.*INSPEC.*\n" + "\n" + "RT ~ Conference-Paper\n" + "AU ~ Prechelt, Lutz"; BibEntry expectedEntry = new BibEntry(StandardEntryType.InProceedings); expectedEntry.setField(StandardField.AUTHOR, "Prechelt, Lutz"); try (BufferedReader reader = new BufferedReader(new StringReader(testInput))) { List<BibEntry> entries = importer.importDatabase(reader).getDatabase().getEntries(); assertEquals(Collections.singletonList(expectedEntry), entries); } } @Test public void importMiscGivesMisc() throws IOException { String testInput = "Record.*INSPEC.*\n" + "\n" + "AU ~ Prechelt, Lutz \n" + "RT ~ Misc"; BibEntry expectedEntry = new BibEntry(StandardEntryType.Misc); expectedEntry.setField(StandardField.AUTHOR, "Prechelt, Lutz"); try (BufferedReader reader = new BufferedReader(new StringReader(testInput))) { List<BibEntry> entries = importer.importDatabase(reader).getDatabase().getEntries(); assertEquals(1, entries.size()); BibEntry entry = entries.get(0); assertEquals(expectedEntry, entry); } } @Test public void testGetFormatName() { assertEquals("INSPEC", importer.getName()); } @Test public void testGetCLIId() { assertEquals("inspec", importer.getId()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.TXT, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("INSPEC format importer.", importer.getDescription()); } }
4,776
36.614173
121
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/IsiImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Month; import org.jabref.model.entry.field.Field; 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.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; public class IsiImporterTest { private static final String FILE_ENDING = ".isi"; private final IsiImporter importer = new IsiImporter(); private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("IsiImporterTest") && !name.contains("Empty") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> invalidFileNames() throws IOException { Predicate<String> fileName = name -> !name.startsWith("IsiImporterTest"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @Test public void testParseMonthException() { IsiImporter.parseMonth("20l06 06-07"); } @Test public void testGetFormatName() { assertEquals("ISI", importer.getName()); } @Test public void testGetCLIId() { assertEquals("isi", importer.getId()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.ISI, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Importer for the ISI Web of Science, INSPEC and Medline format.", importer.getDescription()); } @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormatAccepted(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(importer, fileName); } @ParameterizedTest @MethodSource("invalidFileNames") public void testIsRecognizedFormatRejected(String fileName) throws IOException { ImporterTestEngine.testIsNotRecognizedFormat(importer, fileName); } @Test public void testProcessSubSup() { HashMap<Field, String> subs = new HashMap<>(); subs.put(StandardField.TITLE, "/sub 3/"); IsiImporter.processSubSup(subs); assertEquals("$_3$", subs.get(StandardField.TITLE)); subs.put(StandardField.TITLE, "/sub 3 /"); IsiImporter.processSubSup(subs); assertEquals("$_3$", subs.get(StandardField.TITLE)); subs.put(StandardField.TITLE, "/sub 31/"); IsiImporter.processSubSup(subs); assertEquals("$_{31}$", subs.get(StandardField.TITLE)); subs.put(StandardField.ABSTRACT, "/sub 3/"); IsiImporter.processSubSup(subs); assertEquals("$_3$", subs.get(StandardField.ABSTRACT)); subs.put(StandardField.REVIEW, "/sub 31/"); IsiImporter.processSubSup(subs); assertEquals("$_{31}$", subs.get(StandardField.REVIEW)); subs.put(StandardField.TITLE, "/sup 3/"); IsiImporter.processSubSup(subs); assertEquals("$^3$", subs.get(StandardField.TITLE)); subs.put(StandardField.TITLE, "/sup 31/"); IsiImporter.processSubSup(subs); assertEquals("$^{31}$", subs.get(StandardField.TITLE)); subs.put(StandardField.ABSTRACT, "/sup 3/"); IsiImporter.processSubSup(subs); assertEquals("$^3$", subs.get(StandardField.ABSTRACT)); subs.put(StandardField.REVIEW, "/sup 31/"); IsiImporter.processSubSup(subs); assertEquals("$^{31}$", subs.get(StandardField.REVIEW)); subs.put(StandardField.TITLE, "/sub $Hello/"); IsiImporter.processSubSup(subs); assertEquals("$_{\\$Hello}$", subs.get(StandardField.TITLE)); } @Test public void testImportEntries1() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IsiImporterTest1.isi").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = entries.get(0); assertEquals(1, entries.size()); assertEquals(Optional.of("Optical properties of MgO doped LiNbO$_3$ single crystals"), entry.getField(StandardField.TITLE)); assertEquals( Optional.of( "James Brown and James Marc Brown and Brown, J. M. and Brown, J. and Brown, J. M. and Brown, J."), entry.getField(StandardField.AUTHOR)); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("Optical Materials"), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("2006"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("28"), entry.getField(StandardField.VOLUME)); assertEquals(Optional.of("5"), entry.getField(StandardField.NUMBER)); assertEquals(Optional.of("467--72"), entry.getField(StandardField.PAGES)); } @Test public void testImportEntries2() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IsiImporterTest2.isi").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = entries.get(0); assertEquals(3, entries.size()); assertEquals(Optional.of("Optical properties of MgO doped LiNbO$_3$ single crystals"), entry.getField(StandardField.TITLE)); assertEquals(StandardEntryType.Misc, entry.getType()); assertEquals(Optional.of("Optical Materials"), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("2006"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("28"), entry.getField(StandardField.VOLUME)); assertEquals(Optional.of("5"), entry.getField(StandardField.NUMBER)); assertEquals(Optional.of("467-72"), entry.getField(StandardField.PAGES)); } @Test public void testImportEntriesINSPEC() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IsiImporterTestInspec.isi").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry first = entries.get(0); BibEntry second = entries.get(1); if (first.getField(StandardField.TITLE).equals( Optional.of("Optical and photoelectric spectroscopy of photorefractive Sn$_2$P$_2$S$_6$ crystals"))) { BibEntry tmp = first; first = second; second = tmp; } assertEquals(2, entries.size()); assertEquals( Optional.of( "Second harmonic generation of continuous wave ultraviolet light and production of beta -BaB$_2$O$_4$ optical waveguides"), first.getField(StandardField.TITLE)); assertEquals(StandardEntryType.Article, first.getType()); assertEquals(Optional.of("Degl'Innocenti, R. and Guarino, A. and Poberaj, G. and Gunter, P."), first.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Applied Physics Letters"), first.getField(StandardField.JOURNAL)); assertEquals(Optional.of("2006"), first.getField(StandardField.YEAR)); assertEquals(Optional.of(Month.JULY), first.getMonth()); assertEquals(Optional.of("89"), first.getField(StandardField.VOLUME)); assertEquals(Optional.of("4"), first.getField(StandardField.NUMBER)); assertEquals(Optional.of("Lorem ipsum abstract"), first.getField(StandardField.ABSTRACT)); assertEquals(Optional.of("Aip"), first.getField(StandardField.PUBLISHER)); assertEquals( Optional.of("Optical and photoelectric spectroscopy of photorefractive Sn$_2$P$_2$S$_6$ crystals"), second.getField(StandardField.TITLE)); assertEquals(StandardEntryType.Article, second.getType()); } @Test public void testImportEntriesWOS() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IsiImporterTestWOS.isi").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry first = entries.get(0); BibEntry second = entries.get(1); assertEquals(2, entries.size()); assertEquals(Optional.of("Optical and photoelectric spectroscopy of photorefractive Sn2P2S6 crystals"), first.getField(StandardField.TITLE)); assertEquals(Optional.of("Optical waveguides in Sn2P2S6 by low fluence MeV He+ ion implantation"), second.getField(StandardField.TITLE)); assertEquals(Optional.of("Journal of Physics-Condensed Matter"), first.getField(StandardField.JOURNAL)); } @Test public void testIsiAuthorsConvert() { assertEquals( "James Brown and James Marc Brown and Brown, J. M. and Brown, J. and Brown, J. M. and Brown, J.", IsiImporter.isiAuthorsConvert( "James Brown and James Marc Brown and Brown, J.M. and Brown, J. and Brown, J.M. and Brown, J.")); assertEquals( "Joffe, Hadine and Hall, Janet E. and Gruber, Staci and Sarmiento, Ingrid A. and Cohen, Lee S. and Yurgelun-Todd, Deborah and Martin, Kathryn A.", IsiImporter.isiAuthorsConvert( "Joffe, Hadine; Hall, Janet E; Gruber, Staci; Sarmiento, Ingrid A; Cohen, Lee S; Yurgelun-Todd, Deborah; Martin, Kathryn A")); } @Test public void testMonthConvert() { assertEquals("#jun#", IsiImporter.parseMonth("06")); assertEquals("#jun#", IsiImporter.parseMonth("JUN")); assertEquals("#jun#", IsiImporter.parseMonth("jUn")); assertEquals("#may#", IsiImporter.parseMonth("MAY-JUN")); assertEquals("#jun#", IsiImporter.parseMonth("2006 06")); assertEquals("#jun#", IsiImporter.parseMonth("2006 06-07")); assertEquals("#jul#", IsiImporter.parseMonth("2006 07 03")); assertEquals("#may#", IsiImporter.parseMonth("2006 May-Jun")); } @Test public void testIsiAuthorConvert() { assertEquals("James Brown", IsiImporter.isiAuthorConvert("James Brown")); assertEquals("James Marc Brown", IsiImporter.isiAuthorConvert("James Marc Brown")); assertEquals("Brown, J. M.", IsiImporter.isiAuthorConvert("Brown, J.M.")); assertEquals("Brown, J.", IsiImporter.isiAuthorConvert("Brown, J.")); assertEquals("Brown, J. M.", IsiImporter.isiAuthorConvert("Brown, JM")); assertEquals("Brown, J.", IsiImporter.isiAuthorConvert("Brown, J")); assertEquals("Brown, James", IsiImporter.isiAuthorConvert("Brown, James")); assertEquals("Hall, Janet E.", IsiImporter.isiAuthorConvert("Hall, Janet E")); assertEquals("", IsiImporter.isiAuthorConvert("")); } @Test public void testImportIEEEExport() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IEEEImport1.txt").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = entries.get(0); assertEquals(1, entries.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("Geoscience and Remote Sensing Letters, IEEE"), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("Improving Urban Road Extraction in High-Resolution " + "Images Exploiting Directional Filtering, Perceptual " + "Grouping, and Simple Topological Concepts"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("4"), entry.getField(StandardField.VOLUME)); assertEquals(Optional.of("3"), entry.getField(StandardField.NUMBER)); assertEquals(Optional.of("1545-598X"), entry.getField(new UnknownField("SN"))); assertEquals(Optional.of("387--391"), entry.getField(StandardField.PAGES)); assertEquals(Optional.of("Gamba, P. and Dell'Acqua, F. and Lisini, G."), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("2006"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("Perceptual grouping, street extraction, urban remote sensing"), entry.getField(StandardField.KEYWORDS)); assertEquals(Optional.of("Lorem ipsum abstract"), entry.getField(StandardField.ABSTRACT)); } @Test public void testIEEEImport() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IEEEImport1.txt").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry entry = entries.get(0); assertEquals(1, entries.size()); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("Geoscience and Remote Sensing Letters, IEEE"), entry.getField(StandardField.JOURNAL)); assertEquals( Optional.of( "Improving Urban Road Extraction in High-Resolution Images Exploiting Directional Filtering, Perceptual Grouping, and Simple Topological Concepts"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("4"), entry.getField(StandardField.VOLUME)); assertEquals(Optional.of("3"), entry.getField(StandardField.NUMBER)); assertEquals(Optional.of("1545-598X"), entry.getField(new UnknownField("SN"))); assertEquals(Optional.of("387--391"), entry.getField(StandardField.PAGES)); assertEquals(Optional.of("Gamba, P. and Dell'Acqua, F. and Lisini, G."), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("2006"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("Perceptual grouping, street extraction, urban remote sensing"), entry.getField(StandardField.KEYWORDS)); assertEquals(Optional.of("Lorem ipsum abstract"), entry.getField(StandardField.ABSTRACT)); } @Test public void testImportEntriesMedline() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IsiImporterTestMedline.isi").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntry first = entries.get(0); BibEntry second = entries.get(1); assertEquals(2, entries.size()); assertEquals( Optional.of("Effects of modafinil on cognitive performance and alertness during sleep deprivation."), first.getField(StandardField.TITLE)); assertEquals(Optional.of("Wesensten, Nancy J."), first.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Curr Pharm Des"), first.getField(StandardField.JOURNAL)); assertEquals(Optional.of("2006"), first.getField(StandardField.YEAR)); assertEquals(Optional.empty(), first.getField(StandardField.MONTH)); assertEquals(Optional.of("12"), first.getField(StandardField.VOLUME)); assertEquals(Optional.of("20"), first.getField(StandardField.NUMBER)); assertEquals(Optional.of("2457--71"), first.getField(StandardField.PAGES)); assertEquals(StandardEntryType.Article, first.getType()); assertEquals( Optional.of( "Estrogen therapy selectively enhances prefrontal cognitive processes: a randomized, double-blind, placebo-controlled study with functional magnetic resonance imaging in perimenopausal and recently postmenopausal women."), second.getField(StandardField.TITLE)); assertEquals( Optional.of( "Joffe, Hadine and Hall, Janet E. and Gruber, Staci and Sarmiento, Ingrid A. and Cohen, Lee S. and Yurgelun-Todd, Deborah and Martin, Kathryn A."), second.getField(StandardField.AUTHOR)); assertEquals(Optional.of("2006"), second.getField(StandardField.YEAR)); assertEquals(Optional.of(Month.MAY), second.getMonth()); assertEquals(Optional.of("13"), second.getField(StandardField.VOLUME)); assertEquals(Optional.of("3"), second.getField(StandardField.NUMBER)); assertEquals(Optional.of("411--22"), second.getField(StandardField.PAGES)); assertEquals(StandardEntryType.Article, second.getType()); } @Test public void testImportEntriesEmpty() throws IOException, URISyntaxException { Path file = Path.of(IsiImporterTest.class.getResource("IsiImporterTestEmpty.isi").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(1, entries.size()); } }
17,337
48.679083
246
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; public class MedlineImporterFilesTest { private static final String FILE_ENDING = ".xml"; private static final String MALFORMED_KEY_WORD = "Malformed"; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("MedlineImporterTest") && name.endsWith(FILE_ENDING) && !name.contains(MALFORMED_KEY_WORD); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> invalidFileNames() throws IOException { Predicate<String> fileName = name -> !name.startsWith("MedlineImporterTest"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(new MedlineImporter(), fileName); } @ParameterizedTest @MethodSource("invalidFileNames") public void testIsNotRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsNotRecognizedFormat(new MedlineImporter(), fileName); } @ParameterizedTest @MethodSource("fileNames") public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new MedlineImporter(), fileName, FILE_ENDING); } private static Stream<String> malformedFileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("MedlineImporterTest" + MALFORMED_KEY_WORD) && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } @ParameterizedTest @MethodSource("malformedFileNames") public void testImportMalfomedFiles(String fileName) throws IOException { ImporterTestEngine.testImportMalformedFiles(new MedlineImporter(), fileName); } }
2,176
37.192982
113
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/MedlineImporterTest.java
package org.jabref.logic.importer.fileformat; import org.jabref.logic.util.StandardFileType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Articles in the medline format can be downloaded from http://www.ncbi.nlm.nih.gov/pubmed/. 1. Search for a term and * make sure you have selected the PubMed database 2. Select the results you want to export by checking their checkboxes * 3. Press on the 'Send to' drop down menu on top of the search results 4. Select 'File' as Destination and 'XML' as * Format 5. Press 'Create File' to download your search results in a medline xml file */ public class MedlineImporterTest { private MedlineImporter importer; @BeforeEach public void setUp() throws Exception { this.importer = new MedlineImporter(); } @Test public void testGetFormatName() { assertEquals("Medline/PubMed", importer.getName()); } @Test public void testGetCLIId() { assertEquals("medline", importer.getId()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.MEDLINE, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Importer for the Medline format.", importer.getDescription()); } }
1,361
29.266667
120
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/MedlinePlainImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.bibtex.BibEntryAssert; import org.jabref.logic.util.StandardFileType; 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.function.Executable; 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.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class MedlinePlainImporterTest { private static final String FILE_ENDING = ".txt"; private MedlinePlainImporter importer; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("MedlinePlainImporterTest") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private BufferedReader readerForString(String string) { return new BufferedReader(new StringReader(string)); } @BeforeEach void setUp() { importer = new MedlinePlainImporter(); } @Test void testsGetExtensions() { assertEquals(StandardFileType.MEDLINE_PLAIN, importer.getFileType()); } @Test void testGetDescription() { assertEquals("Importer for the MedlinePlain format.", importer.getDescription()); } @ParameterizedTest @MethodSource("fileNames") void testIsRecognizedFormat(String fileName) throws Exception { ImporterTestEngine.testIsRecognizedFormat(importer, fileName); } @Test void doesNotRecognizeEmptyFiles() throws IOException { assertFalse(importer.isRecognizedFormat(readerForString(""))); } @Test void testImportMultipleEntriesInSingleFile() throws IOException, URISyntaxException { Path inputFile = Path.of(MedlinePlainImporter.class.getResource("MedlinePlainImporterTestMultipleEntries.txt").toURI()); List<BibEntry> entries = importer.importDatabase(inputFile).getDatabase() .getEntries(); BibEntry testEntry = entries.get(0); assertEquals(7, entries.size()); assertEquals(StandardEntryType.Article, testEntry.getType()); assertEquals(Optional.empty(), testEntry.getField(StandardField.MONTH)); assertEquals(Optional.of("Long, Vicky and Marland, Hilary"), testEntry.getField(StandardField.AUTHOR)); assertEquals( Optional.of( "From danger and motherhood to health and beauty: health advice for the factory girl in early twentieth-century Britain."), testEntry.getField(StandardField.TITLE)); testEntry = entries.get(1); assertEquals(StandardEntryType.Conference, testEntry.getType()); assertEquals(Optional.of("06"), testEntry.getField(StandardField.MONTH)); assertEquals(Optional.empty(), testEntry.getField(StandardField.AUTHOR)); assertEquals(Optional.empty(), testEntry.getField(StandardField.TITLE)); testEntry = entries.get(2); assertEquals(StandardEntryType.Book, testEntry.getType()); assertEquals( Optional.of( "This is a Testtitle: This title should be appended: This title should also be appended. Another append to the Title? LastTitle"), testEntry.getField(StandardField.TITLE)); testEntry = entries.get(3); assertEquals(StandardEntryType.TechReport, testEntry.getType()); assertTrue(testEntry.getField(StandardField.DOI).isPresent()); testEntry = entries.get(4); assertEquals(StandardEntryType.InProceedings, testEntry.getType()); assertEquals(Optional.of("Inproceedings book title"), testEntry.getField(StandardField.BOOKTITLE)); BibEntry expectedEntry5 = new BibEntry(StandardEntryType.Proceedings); expectedEntry5.setField(StandardField.KEYWORDS, "Female"); assertEquals(expectedEntry5, entries.get(5)); BibEntry expectedEntry6 = new BibEntry(); expectedEntry6.setType(StandardEntryType.Misc); expectedEntry6.setField(StandardField.KEYWORDS, "Female"); assertEquals(expectedEntry6, entries.get(6)); } @Test void testEmptyFileImport() throws IOException { List<BibEntry> emptyEntries = importer.importDatabase(readerForString("")).getDatabase().getEntries(); assertEquals(Collections.emptyList(), emptyEntries); } @Test void testImportSingleEntriesInSingleFiles() throws IOException, URISyntaxException { List<String> testFiles = Arrays.asList("MedlinePlainImporterTestCompleteEntry", "MedlinePlainImporterTestMultiAbstract", "MedlinePlainImporterTestMultiTitle", "MedlinePlainImporterTestDOI", "MedlinePlainImporterTestInproceeding"); for (String testFile : testFiles) { String medlineFile = testFile + ".txt"; String bibtexFile = testFile + ".bib"; assertImportOfMedlineFileEqualsBibtexFile(medlineFile, bibtexFile); } } private void assertImportOfMedlineFileEqualsBibtexFile(String medlineFile, String bibtexFile) throws IOException, URISyntaxException { Path file = Path.of(MedlinePlainImporter.class.getResource(medlineFile).toURI()); try (InputStream nis = MedlinePlainImporter.class.getResourceAsStream(bibtexFile)) { List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); assertNotNull(entries); assertEquals(1, entries.size()); BibEntryAssert.assertEquals(nis, entries.get(0)); } } @Test void testMultiLineComments() throws IOException { try (BufferedReader reader = readerForString("PMID-22664220" + "\n" + "CON - Comment1" + "\n" + "CIN - Comment2" + "\n" + "EIN - Comment3" + "\n" + "EFR - Comment4" + "\n" + "CRI - Comment5" + "\n" + "CRF - Comment6" + "\n" + "PRIN- Comment7" + "\n" + "PROF- Comment8" + "\n" + "RPI - Comment9" + "\n" + "RPF - Comment10" + "\n" + "RIN - Comment11" + "\n" + "ROF - Comment12" + "\n" + "UIN - Comment13" + "\n" + "UOF - Comment14" + "\n" + "SPIN- Comment15" + "\n" + "ORI - Comment16")) { List<BibEntry> actualEntries = importer.importDatabase(reader).getDatabase().getEntries(); BibEntry expectedEntry = new BibEntry(); expectedEntry.setField(StandardField.COMMENT, "Comment1" + "\n" + "Comment2" + "\n" + "Comment3" + "\n" + "Comment4" + "\n" + "Comment5" + "\n" + "Comment6" + "\n" + "Comment7" + "\n" + "Comment8" + "\n" + "Comment9" + "\n" + "Comment10" + "\n" + "Comment11" + "\n" + "Comment12" + "\n" + "Comment13" + "\n" + "Comment14" + "\n" + "Comment15" + "\n" + "Comment16"); assertEquals(Collections.singletonList(expectedEntry), actualEntries); } } @Test void testKeyWords() throws IOException { try (BufferedReader reader = readerForString("PMID-22664795" + "\n" + "MH - Female" + "\n" + "OT - Male")) { List<BibEntry> actualEntries = importer.importDatabase(reader).getDatabase().getEntries(); BibEntry expectedEntry = new BibEntry(); expectedEntry.setField(StandardField.KEYWORDS, "Female, Male"); assertEquals(Collections.singletonList(expectedEntry), actualEntries); } } @Test void testWithNbibFile() throws IOException, URISyntaxException { Path file = Path.of(MedlinePlainImporter.class.getResource("NbibImporterTest.nbib").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntryAssert.assertEquals(MedlinePlainImporter.class, "NbibImporterTest.bib", entries); } @Test void testWithMultipleEntries() throws IOException, URISyntaxException { Path file = Path.of(MedlinePlainImporter.class.getResource("MedlinePlainImporterStringOutOfBounds.txt").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); BibEntryAssert.assertEquals(MedlinePlainImporter.class, "MedlinePlainImporterStringOutOfBounds.bib", entries); } @Test void testInvalidFormat() throws URISyntaxException, IOException { Path file = Path.of(MedlinePlainImporter.class.getResource("MedlinePlainImporterTestInvalidFormat.xml").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), entries); } @Test void testNullReader() throws IOException { Executable fail = () -> { try (BufferedReader reader = null) { importer.importDatabase(reader); } }; assertThrows(NullPointerException.class, fail); } @Test void testAllArticleTypes() throws IOException { try (BufferedReader reader = readerForString("PMID-22664795" + "\n" + "MH - Female\n" + "PT - journal article" + "\n" + "PT - classical article" + "\n" + "PT - corrected and republished article" + "\n" + "PT - introductory journal article" + "\n" + "PT - newspaper article")) { List<BibEntry> actualEntries = importer.importDatabase(reader).getDatabase().getEntries(); BibEntry expectedEntry = new BibEntry(); expectedEntry.setType(StandardEntryType.Article); expectedEntry.setField(StandardField.KEYWORDS, "Female"); assertEquals(Collections.singletonList(expectedEntry), actualEntries); } } @Test void testGetFormatName() { assertEquals("Medline/PubMed Plain", importer.getName()); } @Test void testGetCLIId() { assertEquals("medlineplain", importer.getId()); } }
10,703
42.16129
154
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.importer.ImportFormatPreferences; 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.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ModsImporterFilesTest { private static final String FILE_ENDING = ".xml"; private ImportFormatPreferences importFormatPreferences; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("MODS") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } @BeforeEach void setUp() { importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); } @ParameterizedTest @MethodSource("fileNames") void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(new ModsImporter(importFormatPreferences), fileName); } @ParameterizedTest @MethodSource("fileNames") void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new ModsImporter(importFormatPreferences), fileName, FILE_ENDING); } }
1,561
33.711111
111
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/MrDLibImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.List; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; public class MrDLibImporterTest { private MrDLibImporter importer; private BufferedReader input; @BeforeEach public void setUp() { importer = new MrDLibImporter(); String testInput = "{\"label\": {\"label-description\": \"The following articles are similar to the document have currently selected.\", \"label-language\": \"en\", \"label-text\": \"Related Articles\"}, \"recommendation_set_id\": \"1\", \"recommendations\": { \"74021358\": { \"abstract\": \"abstract\", \"authors\":\"Sajovic, Marija\", \"published_year\": \"2006\", \"item_id_original\": \"12088644\", \"keywords\": [ \"visoko\\u0161olski program Geodezija - smer Prostorska informatika\" ], \"language_provided\": \"sl\", \"recommendation_id\": \"1\", \"title\": \"The protection of rural lands with the spatial development strategy on the case of Hrastnik commune\", \"url\": \"http://drugg.fgg.uni-lj.si/701/1/GEV_0199_Sajovic.pdf\" }, \"82005804\": { \"abstract\": \"abstract\", \"year_published\": null, \"item_id_original\": \"30145702\", \"language_provided\": null, \"recommendation_id\": \"2\", \"title\": \"Engagement of the volunteers in the solution to the accidents in the South-Moravia region\" }, \"82149599\": { \"abstract\": \"abstract\", \"year_published\": null, \"item_id_original\": \"97690763\", \"language_provided\": null, \"recommendation_id\": \"3\", \"title\": \"\\\"The only Father's word\\\". The relationship of the Father and the Son in the documents of saint John of the Cross\", \"url\": \"http://www.nusl.cz/ntk/nusl-285711\" }, \"84863921\": { \"abstract\": \"abstract\", \"authors\":\"Kaffa, Elena\", \"year_published\": null, \"item_id_original\": \"19397104\", \"keywords\": [ \"BX\", \"D111\" ], \"language_provided\": \"en\", \"recommendation_id\": \"4\", \"title\": \"Greek Church of Cyprus, the Morea and Constantinople during the Frankish Era (1196-1303)\" }, \"88950992\": { \"abstract\": \"abstract\", \"authors\":\"Yasui, Kono\", \"year_published\": null, \"item_id_original\": \"38763657\", \"language_provided\": null, \"recommendation_id\": \"5\", \"title\": \"A Phylogenetic Consideration on the Vascular Plants, Cotyledonary Node Including Hypocotyl Being Taken as the Ancestral Form : A Preliminary Note\" } }}"; input = new BufferedReader(new StringReader(testInput)); } @Test public void testGetDescription() { assertEquals("Takes valid JSON documents from the Mr. DLib API and parses them into a BibEntry", importer.getDescription()); } @Test public void testGetName() { assertEquals("MrDLibImporter", importer.getName()); } @Test public void testGetFileExtention() { assertEquals(StandardFileType.JSON, importer.getFileType()); } @Test public void testImportDatabaseIsYearSetCorrectly() throws IOException { ParserResult parserResult = importer.importDatabase(input); List<BibEntry> resultList = parserResult.getDatabase().getEntries(); assertEquals("2006", resultList.get(0).getLatexFreeField(StandardField.YEAR).get()); } @Test public void testImportDatabaseIsTitleSetCorrectly() throws IOException { ParserResult parserResult = importer.importDatabase(input); List<BibEntry> resultList = parserResult.getDatabase().getEntries(); assertEquals("The protection of rural lands with the spatial development strategy on the case of Hrastnik commune", resultList.get(0).getLatexFreeField(StandardField.TITLE).get()); } @Test public void testImportDatabaseMin() throws IOException { ParserResult parserResult = importer.importDatabase(input); List<BibEntry> resultList = parserResult.getDatabase().getEntries(); assertSame(5, resultList.size()); } }
4,921
64.626667
2,627
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; public class MsBibImporterFilesTest { private static final String FILE_ENDING = ".xml"; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("MsBib") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> invalidFileNames() throws IOException { Predicate<String> fileName = name -> !name.contains("MsBib"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(new MsBibImporter(), fileName); } @ParameterizedTest @MethodSource("invalidFileNames") public void testIsNotRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsNotRecognizedFormat(new MsBibImporter(), fileName); } @ParameterizedTest @MethodSource("fileNames") public void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new MsBibImporter(), fileName, FILE_ENDING); } }
1,497
33.837209
89
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/MsBibImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; public class MsBibImporterTest { @Test public void testsGetExtensions() { MsBibImporter importer = new MsBibImporter(); assertEquals(StandardFileType.XML, importer.getFileType()); } @Test public void testGetDescription() { MsBibImporter importer = new MsBibImporter(); assertEquals("Importer for the MS Office 2007 XML bibliography format.", importer.getDescription()); } @Test public final void testIsNotRecognizedFormat() throws Exception { MsBibImporter testImporter = new MsBibImporter(); List<String> notAccepted = Arrays.asList("CopacImporterTest1.txt", "IsiImporterTest1.isi", "IsiImporterTestInspec.isi", "emptyFile.xml", "IsiImporterTestWOS.isi"); for (String s : notAccepted) { Path file = Path.of(MsBibImporter.class.getResource(s).toURI()); assertFalse(testImporter.isRecognizedFormat(file)); } } @Test public final void testImportEntriesEmpty() throws IOException, URISyntaxException { MsBibImporter testImporter = new MsBibImporter(); Path file = Path.of(MsBibImporter.class.getResource("EmptyMsBib_Test.xml").toURI()); List<BibEntry> entries = testImporter.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), entries); } @Test public final void testImportEntriesNotRecognizedFormat() throws IOException, URISyntaxException { MsBibImporter testImporter = new MsBibImporter(); Path file = Path.of(MsBibImporter.class.getResource("CopacImporterTest1.txt").toURI()); List<BibEntry> entries = testImporter.importDatabase(file).getDatabase().getEntries(); assertEquals(0, entries.size()); } @Test public final void testGetFormatName() { MsBibImporter testImporter = new MsBibImporter(); assertEquals("MSBib", testImporter.getName()); } @Test public final void testGetCommandLineId() { MsBibImporter testImporter = new MsBibImporter(); assertEquals("msbib", testImporter.getId()); } }
2,582
35.380282
108
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/OvidImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.bibtex.BibEntryAssert; import org.jabref.logic.util.StandardFileType; 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 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.assertNotNull; public class OvidImporterTest { private static final String FILE_ENDING = ".txt"; private OvidImporter importer; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("OvidImporterTest") && !name.contains("Invalid") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } private static Stream<String> invalidFileNames() throws IOException { Predicate<String> fileName = name -> !name.contains("OvidImporterTest"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @BeforeEach public void setUp() { importer = new OvidImporter(); } @Test public void testGetFormatName() { assertEquals("Ovid", importer.getName()); } @Test public void testGetCLIId() { assertEquals("ovid", importer.getId()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.TXT, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Imports an Ovid file.", importer.getDescription()); } @ParameterizedTest @MethodSource("fileNames") public void testIsRecognizedFormatAccept(String fileName) throws IOException, URISyntaxException { ImporterTestEngine.testIsRecognizedFormat(importer, fileName); } @ParameterizedTest @MethodSource("invalidFileNames") public void testIsRecognizedFormatRejected(String fileName) throws IOException, URISyntaxException { ImporterTestEngine.testIsNotRecognizedFormat(importer, fileName); } @Test public void testImportEmpty() throws IOException, URISyntaxException { Path file = Path.of(OvidImporter.class.getResource("Empty.txt").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), entries); } @Test public void testImportEntries1() throws IOException, URISyntaxException { Path file = Path.of(OvidImporter.class.getResource("OvidImporterTest1.txt").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(5, entries.size()); BibEntry entry = entries.get(0); assertEquals(StandardEntryType.Misc, entry.getType()); assertEquals(Optional.of("Mustermann and Musterfrau"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Short abstract"), entry.getField(StandardField.ABSTRACT)); assertEquals(Optional.of("Musterbuch"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("Einleitung"), entry.getField(new UnknownField("chaptertitle"))); entry = entries.get(1); assertEquals(StandardEntryType.InProceedings, entry.getType()); assertEquals(Optional.of("Max"), entry.getField(StandardField.EDITOR)); assertEquals(Optional.of("Max the Editor"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("Very Long Title"), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("28"), entry.getField(StandardField.VOLUME)); assertEquals(Optional.of("2"), entry.getField(StandardField.ISSUE)); assertEquals(Optional.of("2015"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("103--106"), entry.getField(StandardField.PAGES)); entry = entries.get(2); assertEquals(StandardEntryType.InCollection, entry.getType()); assertEquals(Optional.of("Max"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Test"), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("Very Long Title"), entry.getField(StandardField.JOURNAL)); assertEquals(Optional.of("28"), entry.getField(StandardField.VOLUME)); assertEquals(Optional.of("2"), entry.getField(StandardField.ISSUE)); assertEquals(Optional.of("April"), entry.getField(StandardField.MONTH)); assertEquals(Optional.of("2015"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("103--106"), entry.getField(StandardField.PAGES)); entry = entries.get(3); assertEquals(StandardEntryType.Book, entry.getType()); assertEquals(Optional.of("Max"), entry.getField(StandardField.AUTHOR)); assertEquals(Optional.of("2015"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("Editor"), entry.getField(StandardField.EDITOR)); assertEquals(Optional.of("Very Long Title"), entry.getField(StandardField.BOOKTITLE)); assertEquals(Optional.of("103--106"), entry.getField(StandardField.PAGES)); assertEquals(Optional.of("Address"), entry.getField(StandardField.ADDRESS)); assertEquals(Optional.of("Publisher"), entry.getField(StandardField.PUBLISHER)); entry = entries.get(4); assertEquals(StandardEntryType.Article, entry.getType()); assertEquals(Optional.of("2014"), entry.getField(StandardField.YEAR)); assertEquals(Optional.of("58"), entry.getField(StandardField.PAGES)); assertEquals(Optional.of("Test"), entry.getField(StandardField.ADDRESS)); assertEquals(Optional.empty(), entry.getField(StandardField.TITLE)); assertEquals(Optional.of("TestPublisher"), entry.getField(StandardField.PUBLISHER)); } @Test public void testImportEntries2() throws IOException, URISyntaxException { Path file = Path.of(OvidImporter.class.getResource("OvidImporterTest2Invalid.txt").toURI()); List<BibEntry> entries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), entries); } @Test public void testImportSingleEntries() throws IOException, URISyntaxException { for (int n = 3; n <= 7; n++) { Path file = Path.of(OvidImporter.class.getResource("OvidImporterTest" + n + ".txt").toURI()); try (InputStream nis = OvidImporter.class.getResourceAsStream("OvidImporterTestBib" + n + ".bib")) { List<BibEntry> entries = importer.importDatabase(file).getDatabase() .getEntries(); assertNotNull(entries); assertEquals(1, entries.size()); BibEntryAssert.assertEquals(nis, entries.get(0)); } } } }
7,408
44.176829
112
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterFilesTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.importer.ImportFormatPreferences; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.mockito.Mockito.mock; class PdfContentImporterFilesTest { private static final String FILE_ENDING = ".pdf"; private static Stream<String> fileNames() throws IOException { Predicate<String> fileName = name -> name.startsWith("LNCS-minimal") && name.endsWith(FILE_ENDING); return ImporterTestEngine.getTestFiles(fileName).stream(); } @ParameterizedTest @MethodSource("fileNames") void testIsRecognizedFormat(String fileName) throws IOException { ImporterTestEngine.testIsRecognizedFormat(new PdfContentImporter(mock(ImportFormatPreferences.class)), fileName); } @ParameterizedTest @MethodSource("fileNames") @Disabled("bib file does not contain linked file") void testImportEntries(String fileName) throws Exception { ImporterTestEngine.testImportEntries(new PdfContentImporter(mock(ImportFormatPreferences.class)), fileName, FILE_ENDING); } }
1,311
33.526316
129
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java
package org.jabref.logic.importer.fileformat; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; 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.mockito.Mockito.mock; class PdfContentImporterTest { private PdfContentImporter importer; @BeforeEach void setUp() { importer = new PdfContentImporter(mock(ImportFormatPreferences.class)); } @Test void testsGetExtensions() { assertEquals(StandardFileType.PDF, importer.getFileType()); } @Test void testGetDescription() { assertEquals("PdfContentImporter parses data of the first page of the PDF and creates a BibTeX entry. Currently, Springer and IEEE formats are supported.", importer.getDescription()); } @Test void doesNotHandleEncryptedPdfs() throws Exception { Path file = Path.of(PdfContentImporter.class.getResource("/pdfs/encrypted.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), result); } @Test void importTwiceWorksAsExpected() throws Exception { Path file = Path.of(PdfContentImporter.class.getResource("/pdfs/minimal.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); BibEntry expected = new BibEntry(StandardEntryType.InProceedings); expected.setField(StandardField.AUTHOR, "1 "); expected.setField(StandardField.TITLE, "Hello World"); expected.setFiles(Collections.singletonList(new LinkedFile("", file.toAbsolutePath(), "PDF"))); List<BibEntry> resultSecondImport = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.singletonList(expected), result); assertEquals(Collections.singletonList(expected), resultSecondImport); } @Test void testParsingEditorWithoutPagesorSeriesInformation() { BibEntry entry = new BibEntry(StandardEntryType.InProceedings); entry.setField(StandardField.AUTHOR, "Anke Lüdeling and Merja Kytö (Eds.)"); entry.setField(StandardField.EDITOR, "Anke Lüdeling and Merja Kytö"); entry.setField(StandardField.PUBLISHER, "Springer"); entry.setField(StandardField.TITLE, "Corpus Linguistics – An International Handbook – Lüdeling, Anke, Kytö, Merja (Eds.)"); String firstPageContents = "Corpus Linguistics – An International Handbook – Lüdeling, Anke,\n" + "Kytö, Merja (Eds.)\n" + "\n" + "Anke Lüdeling, Merja Kytö (Eds.)\n" + "\n" + "VOLUME 2\n" + "\n" + "This handbook provides an up-to-date survey of the field of corpus linguistics, a Handbücher zur Sprach- und\n" + "field whose methodology has revolutionized much of the empirical work done in Kommunikationswissenschaft / Handbooks\n" + "\n" + "of Linguistics and Communication Science\n" + "most fields of linguistic study over the past decade. (HSK) 29/2\n" + "\n" + "vii, 578 pages\n" + "Corpus linguistics investigates human language by starting out from large\n"; assertEquals(Optional.of(entry), importer.getEntryFromPDFContent(firstPageContents, "\n")); } @Test void testParsingWithoutActualDOINumber() { BibEntry entry = new BibEntry(StandardEntryType.InProceedings); entry.withField(StandardField.AUTHOR, "Link to record in KAR and http://kar.kent.ac.uk/51043/ and Document Version and UNSPECIFIED and Master of Research (MRes) thesis and University of Kent") .withField(StandardField.TITLE, "Kent Academic Repository Full text document (pdf) Citation for published version Smith, Lucy Anna (2014) Mortality in the Ornamental Fish Retail Sector: an Analysis of Stock Losses and Stakeholder Opinions. DOI") .withField(StandardField.YEAR, "5104"); String firstPageContents = "Kent Academic Repository Full text document (pdf)\n" + "Citation for published version\n" + "Smith, Lucy Anna (2014) Mortality in the Ornamental Fish Retail Sector: an Analysis of Stock\n" + "Losses and Stakeholder Opinions.\n" + "DOI\n\n\n" + "Link to record in KAR\n" + "http://kar.kent.ac.uk/51043/\n" + "Document Version\n" + "UNSPECIFIED\n" + "Master of Research (MRes) thesis, University of Kent,."; assertEquals(Optional.of(entry), importer.getEntryFromPDFContent(firstPageContents, "\n")); } }
5,613
49.576577
258
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/PdfEmbeddedBibFileImporterTest.java
package org.jabref.logic.importer.fileformat; import java.nio.file.Path; import java.util.Collections; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.StandardFileType; 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.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class PdfEmbeddedBibFileImporterTest { private PdfEmbeddedBibFileImporter importer; @BeforeEach void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.fieldPreferences().getNonWrappableFields()).thenReturn(FXCollections.emptyObservableList()); importer = new PdfEmbeddedBibFileImporter(importFormatPreferences); } @Test void testsGetExtensions() { assertEquals(StandardFileType.PDF, importer.getFileType()); } @Test void testGetDescription() { assertEquals("PdfEmbeddedBibFileImporter imports an embedded Bib-File from the PDF.", importer.getDescription()); } @Test void doesNotHandleEncryptedPdfs() throws Exception { Path file = Path.of(PdfEmbeddedBibFileImporter.class.getResource("/pdfs/encrypted.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), result); } @Test void importWorksAsExpected() throws Exception { Path file = Path.of(PdfEmbeddedBibFileImporterTest.class.getResource("mixedMetadata.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); BibEntry expected = new BibEntry(StandardEntryType.Misc); expected.setCitationKey("jabreftext2021"); expected.setField(StandardField.AUTHOR, "Someone embedded"); expected.setField(StandardField.TITLE, "I like beds"); expected.setField(StandardField.DOI, "10.1002/9781118257517"); expected.setField(StandardField.COMMENT, "From embedded bib"); assertEquals(Collections.singletonList(expected), result); } }
2,492
36.208955
129
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/PdfGrobidImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fetcher.GrobidPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @FetcherTest public class PdfGrobidImporterTest { private PdfGrobidImporter importer; @BeforeEach public void setUp() { GrobidPreferences grobidPreferences = mock(GrobidPreferences.class, Answers.RETURNS_DEEP_STUBS); when(grobidPreferences.isGrobidEnabled()).thenReturn(true); when(grobidPreferences.getGrobidURL()).thenReturn("http://grobid.jabref.org:8070"); ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(','); when(importFormatPreferences.grobidPreferences()).thenReturn(grobidPreferences); importer = new PdfGrobidImporter(importFormatPreferences); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.PDF, importer.getFileType()); } @Test public void testImportEntries() throws URISyntaxException { Path file = Path.of(PdfGrobidImporterTest.class.getResource("LNCS-minimal.pdf").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(1, bibEntries.size()); BibEntry be0 = bibEntries.get(0); assertEquals(Optional.of("Lastname, Firstname"), be0.getField(StandardField.AUTHOR)); assertEquals(Optional.of("Paper Title"), be0.getField(StandardField.TITLE)); } @Test public void testIsRecognizedFormat() throws IOException, URISyntaxException { Path file = Path.of(PdfGrobidImporterTest.class.getResource("annotated.pdf").toURI()); assertTrue(importer.isRecognizedFormat(file)); } @Test public void testIsRecognizedFormatReject() throws IOException, URISyntaxException { Path file = Path.of(PdfGrobidImporterTest.class.getResource("BibtexImporter.examples.bib").toURI()); assertFalse(importer.isRecognizedFormat(file)); } @Test public void testGetCommandLineId() { assertEquals("grobidPdf", importer.getId()); } }
2,943
36.74359
122
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/PdfMergeMetadataImporterTest.java
package org.jabref.logic.importer.fileformat; import java.nio.file.Path; import java.util.Collections; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fetcher.GrobidPreferences; import org.jabref.logic.util.StandardFileType; 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.entry.types.StandardEntryType; import org.jabref.testutils.category.FetcherTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; 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; @FetcherTest class PdfMergeMetadataImporterTest { private PdfMergeMetadataImporter importer; @BeforeEach void setUp() { GrobidPreferences grobidPreferences = mock(GrobidPreferences.class, Answers.RETURNS_DEEP_STUBS); when(grobidPreferences.isGrobidEnabled()).thenReturn(true); when(grobidPreferences.getGrobidURL()).thenReturn("http://grobid.jabref.org:8070"); ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.fieldPreferences().getNonWrappableFields()).thenReturn(FXCollections.emptyObservableList()); when(importFormatPreferences.grobidPreferences()).thenReturn(grobidPreferences); importer = new PdfMergeMetadataImporter(importFormatPreferences); } @Test void testsGetExtensions() { assertEquals(StandardFileType.PDF, importer.getFileType()); } @Test void testGetDescription() { assertEquals("PdfMergeMetadataImporter imports metadata from a PDF using multiple strategies and merging the result.", importer.getDescription()); } @Test void doesNotHandleEncryptedPdfs() throws Exception { Path file = Path.of(PdfMergeMetadataImporter.class.getResource("/pdfs/encrypted.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), result); } @Test @Disabled("Switch from ottobib to OpenLibraryFetcher changed the results") void importWorksAsExpected() throws Exception { Path file = Path.of(PdfMergeMetadataImporterTest.class.getResource("mixedMetadata.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); // From DOI (contained in embedded bib file) BibEntry expected = new BibEntry(StandardEntryType.Book); expected.setCitationKey("9780134685991"); expected.setField(StandardField.AUTHOR, "Bloch, Joshua"); expected.setField(StandardField.TITLE, "Effective Java"); expected.setField(StandardField.PUBLISHER, "Addison Wesley"); expected.setField(StandardField.YEAR, "2018"); expected.setField(StandardField.MONTH, "jul"); expected.setField(StandardField.DOI, "10.1002/9781118257517"); // From ISBN (contained on first page verbatim bib entry) expected.setField(StandardField.DATE, "2018-01-31"); expected.setField(new UnknownField("ean"), "9780134685991"); expected.setField(StandardField.ISBN, "0134685997"); expected.setField(StandardField.URL, "https://www.ebook.de/de/product/28983211/joshua_bloch_effective_java.html"); // From embedded bib file expected.setField(StandardField.COMMENT, "From embedded bib"); // From first page verbatim bib entry expected.setField(StandardField.JOURNAL, "Some Journal"); expected.setField(StandardField.VOLUME, "1"); // From merge expected.setFiles(List.of(new LinkedFile("", file.toAbsolutePath(), StandardFileType.PDF.getName()))); assertEquals(Collections.singletonList(expected), result); } }
4,153
40.959596
129
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/PdfVerbatimBibTextImporterTest.java
package org.jabref.logic.importer.fileformat; import java.nio.file.Path; import java.util.Collections; import java.util.List; import javafx.collections.FXCollections; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.StandardFileType; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; 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.mockito.Answers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class PdfVerbatimBibTextImporterTest { private PdfVerbatimBibTextImporter importer; @BeforeEach void setUp() { ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); when(importFormatPreferences.fieldPreferences().getNonWrappableFields()).thenReturn(FXCollections.emptyObservableList()); importer = new PdfVerbatimBibTextImporter(importFormatPreferences); } @Test void testsGetExtensions() { assertEquals(StandardFileType.PDF, importer.getFileType()); } @Test void testGetDescription() { assertEquals("PdfVerbatimBibTextImporter imports a verbatim BibTeX entry from the first page of the PDF.", importer.getDescription()); } @Test void doesNotHandleEncryptedPdfs() throws Exception { Path file = Path.of(PdfVerbatimBibTextImporter.class.getResource("/pdfs/encrypted.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.emptyList(), result); } @Test void importTwiceWorksAsExpected() throws Exception { Path file = Path.of(PdfVerbatimBibTextImporterTest.class.getResource("mixedMetadata.pdf").toURI()); List<BibEntry> result = importer.importDatabase(file).getDatabase().getEntries(); BibEntry expected = new BibEntry(StandardEntryType.Article); expected.setCitationKey("jabreftest2021"); expected.setField(StandardField.AUTHOR, "Me, myself and I"); expected.setField(StandardField.TITLE, "Something"); expected.setField(StandardField.VOLUME, "1"); expected.setField(StandardField.JOURNAL, "Some Journal"); expected.setField(StandardField.YEAR, "2021"); expected.setField(StandardField.ISBN, "0134685997"); expected.setFiles(Collections.singletonList(new LinkedFile("", file.toAbsolutePath(), "PDF"))); List<BibEntry> resultSecondImport = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(Collections.singletonList(expected), result); assertEquals(Collections.singletonList(expected), resultSecondImport); } }
2,940
39.287671
129
java
null
jabref-main/src/test/java/org/jabref/logic/importer/fileformat/PdfXmpImporterTest.java
package org.jabref.logic.importer.fileformat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.util.StandardFileType; import org.jabref.logic.xmp.XmpPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import 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.assertTrue; import static org.mockito.Mockito.mock; public class PdfXmpImporterTest { private PdfXmpImporter importer; private static Stream<String> invalidFileNames() throws IOException { Predicate<String> fileName = name -> !name.contains("annotated.pdf"); return ImporterTestEngine.getTestFiles(fileName).stream(); } @BeforeEach public void setUp() { importer = new PdfXmpImporter(mock(XmpPreferences.class)); } @Test public void testGetFormatName() { assertEquals("XMP-annotated PDF", importer.getName()); } @Test public void testsGetExtensions() { assertEquals(StandardFileType.PDF, importer.getFileType()); } @Test public void testGetDescription() { assertEquals("Wraps the XMPUtility function to be used as an Importer.", importer.getDescription()); } @Disabled("XMP reader prints warnings to the logger when parsing does not work") @Test public void importEncryptedFileReturnsError() throws URISyntaxException { Path file = Path.of(PdfXmpImporterTest.class.getResource("/pdfs/encrypted.pdf").toURI()); ParserResult result = importer.importDatabase(file); assertTrue(result.hasWarnings()); } @Test public void testImportEntries() throws URISyntaxException { Path file = Path.of(PdfXmpImporterTest.class.getResource("annotated.pdf").toURI()); List<BibEntry> bibEntries = importer.importDatabase(file).getDatabase().getEntries(); assertEquals(1, bibEntries.size()); BibEntry be0 = bibEntries.get(0); assertEquals(Optional.of("how to annotate a pdf"), be0.getField(StandardField.ABSTRACT)); assertEquals(Optional.of("Chris"), be0.getField(StandardField.AUTHOR)); assertEquals(Optional.of("pdf, annotation"), be0.getField(StandardField.KEYWORDS)); assertEquals(Optional.of("The best Pdf ever"), be0.getField(StandardField.TITLE)); } @Test public void testIsRecognizedFormat() throws IOException, URISyntaxException { Path file = Path.of(PdfXmpImporterTest.class.getResource("annotated.pdf").toURI()); assertTrue(importer.isRecognizedFormat(file)); } @ParameterizedTest @MethodSource("invalidFileNames") public void testIsRecognizedFormatReject(String fileName) throws IOException, URISyntaxException { ImporterTestEngine.testIsNotRecognizedFormat(importer, fileName); } @Test public void testGetCommandLineId() { assertEquals("xmp", importer.getId()); } }
3,387
34.663158
108
java