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/fileformat/RISImporterFilesTest.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;
class RISImporterFilesTest {
private static final String FILE_ENDING = ".ris";
private static Stream<String> fileNames() throws IOException {
Predicate<String> fileName = name -> name.startsWith("RisImporterTest") && name.endsWith(FILE_ENDING);
return ImporterTestEngine.getTestFiles(fileName).stream();
}
@ParameterizedTest
@MethodSource("fileNames")
void testIsRecognizedFormat(String fileName) throws IOException {
ImporterTestEngine.testIsRecognizedFormat(new RisImporter(), fileName);
}
@ParameterizedTest
@MethodSource("fileNames")
void testImportEntries(String fileName) throws Exception {
ImporterTestEngine.testImportEntries(new RisImporter(), fileName, FILE_ENDING);
}
}
| 1,013 | 31.709677 | 110 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/fileformat/RISImporterTest.java | package org.jabref.logic.importer.fileformat;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
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;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class RISImporterTest {
private RisImporter importer;
@BeforeEach
public void setUp() {
importer = new RisImporter();
}
@Test
public void testGetFormatName() {
assertEquals("RIS", importer.getName());
}
@Test
public void testGetCLIId() {
assertEquals("ris", importer.getId());
}
@Test
public void testsGetExtensions() {
assertEquals(StandardFileType.RIS, importer.getFileType());
}
@Test
public void testGetDescription() {
assertEquals("Imports a Biblioscape Tag File.", importer.getDescription());
}
@Test
public void testIfNotRecognizedFormat() throws IOException, URISyntaxException {
Path file = Path.of(RISImporterTest.class.getResource("RisImporterCorrupted.ris").toURI());
assertFalse(importer.isRecognizedFormat(file));
}
}
| 1,264 | 24.3 | 99 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/fileformat/RepecNepImporterTest.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.jabref.logic.util.StandardFileType;
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 org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RepecNepImporterTest {
private static final String FILE_ENDING = ".txt";
private RepecNepImporter testImporter;
@BeforeEach
public void setUp() {
ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(',');
testImporter = new RepecNepImporter(importFormatPreferences);
}
private static Stream<String> fileNames() throws IOException {
Predicate<String> fileName = name -> name.startsWith("RepecNepImporter")
&& name.endsWith(FILE_ENDING);
return ImporterTestEngine.getTestFiles(fileName).stream();
}
private static Stream<String> invalidFileNames() throws IOException {
Predicate<String> fileName = name -> !name.contains("RepecNepImporter");
return ImporterTestEngine.getTestFiles(fileName).stream();
}
@ParameterizedTest
@MethodSource("fileNames")
public void testIsRecognizedFormat(String fileName) throws IOException {
ImporterTestEngine.testIsRecognizedFormat(testImporter, fileName);
}
@ParameterizedTest
@MethodSource("invalidFileNames")
public void testIsNotRecognizedFormat(String fileName) throws IOException {
ImporterTestEngine.testIsNotRecognizedFormat(testImporter, fileName);
}
@ParameterizedTest
@MethodSource("fileNames")
public void testImportEntries(String fileName) throws Exception {
ImporterTestEngine.testImportEntries(testImporter, fileName, FILE_ENDING);
}
@Test
public final void testGetFormatName() {
assertEquals("REPEC New Economic Papers (NEP)", testImporter.getName());
}
@Test
public final void testGetCliId() {
assertEquals("repecnep", testImporter.getId());
}
@Test
public void testGetExtension() {
assertEquals(StandardFileType.TXT, testImporter.getFileType());
}
@Test
public final void testGetDescription() {
assertEquals("Imports a New Economics Papers-Message from the REPEC-NEP Service.",
testImporter.getDescription());
}
}
| 2,815 | 32.52381 | 122 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/fileformat/SilverPlatterImporterTest.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.Importer;
import org.jabref.logic.util.StandardFileType;
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;
class SilverPlatterImporterTest {
private static final String FILE_ENDING = ".txt";
private Importer testImporter;
@BeforeEach
void setUp() throws Exception {
testImporter = new SilverPlatterImporter();
}
private static Stream<String> fileNames() throws IOException {
Predicate<String> fileName = name -> name.startsWith("SilverPlatterImporterTest") && name.endsWith(FILE_ENDING);
return ImporterTestEngine.getTestFiles(fileName).stream();
}
private static Stream<String> invalidFileNames() throws IOException {
Predicate<String> fileName = name -> !name.startsWith("SilverPlatterImporterTest");
return ImporterTestEngine.getTestFiles(fileName).stream();
}
@ParameterizedTest
@MethodSource("fileNames")
void testIsRecognizedFormat(String fileName) throws IOException {
ImporterTestEngine.testIsRecognizedFormat(testImporter, fileName);
}
@ParameterizedTest
@MethodSource("invalidFileNames")
void testIsNotRecognizedFormat(String fileName) throws IOException {
ImporterTestEngine.testIsNotRecognizedFormat(testImporter, fileName);
}
@ParameterizedTest
@MethodSource("fileNames")
void testImportEntries(String fileName) throws Exception {
ImporterTestEngine.testImportEntries(testImporter, fileName, FILE_ENDING);
}
@Test
void testsGetExtensions() {
assertEquals(StandardFileType.SILVER_PLATTER, testImporter.getFileType());
}
@Test
void testGetDescription() {
assertEquals("Imports a SilverPlatter exported file.", testImporter.getDescription());
}
}
| 2,129 | 31.272727 | 120 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/FileFieldParserTest.java | package org.jabref.logic.importer.util;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.jabref.model.entry.LinkedFile;
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 FileFieldParserTest {
private static Stream<Arguments> testData() {
return Stream.of(
Arguments.of(
new LinkedFile("arXiv Fulltext PDF", "https://arxiv.org/pdf/1109.0517.pdf", "application/pdf"),
List.of("arXiv Fulltext PDF", "https://arxiv.org/pdf/1109.0517.pdf", "application/pdf")
),
Arguments.of(
new LinkedFile("arXiv Fulltext PDF", "https/://arxiv.org/pdf/1109.0517.pdf", "application/pdf"),
List.of("arXiv Fulltext PDF", "https\\://arxiv.org/pdf/1109.0517.pdf", "application/pdf")
)
);
}
@ParameterizedTest
@MethodSource("testData")
public void check(LinkedFile expected, List<String> input) {
// we need to convert the unmodifiable list to a modifiable because of the side effect of "convert"
assertEquals(expected, FileFieldParser.convert(new ArrayList<>(input)));
}
private static Stream<Arguments> stringsToParseTest() throws Exception {
return Stream.of(
// null string
Arguments.of(
Collections.emptyList(),
null
),
// empty string
Arguments.of(
Collections.emptyList(),
""
),
// correct input
Arguments.of(
Collections.singletonList(new LinkedFile("Desc", Path.of("File.PDF"), "PDF")),
"Desc:File.PDF:PDF"
),
// Mendeley input
Arguments.of(
Collections.singletonList(new LinkedFile("", Path.of("C:/Users/XXXXXX/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Brown - 2017 - Physical test methods for elastomers.pdf"), "pdf")),
":C$\\backslash$:/Users/XXXXXX/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Brown - 2017 - Physical test methods for elastomers.pdf:pdf"
),
// parseCorrectOnlineInput
Arguments.of(
Collections.singletonList(new LinkedFile(new URL("http://arxiv.org/pdf/2010.08497v1"), "PDF")),
":http\\://arxiv.org/pdf/2010.08497v1:PDF"
),
// parseFaultyOnlineInput
Arguments.of(
Collections.singletonList(new LinkedFile("", "htt://arxiv.org/pdf/2010.08497v1", "PDF")),
":htt\\://arxiv.org/pdf/2010.08497v1:PDF"
),
// parseFaultyArxivOnlineInput
Arguments.of(
Collections.singletonList(new LinkedFile("arXiv Fulltext PDF", "https://arxiv.org/pdf/1109.0517.pdf", "application/pdf")),
"arXiv Fulltext PDF:https\\://arxiv.org/pdf/1109.0517.pdf:application/pdf"
),
// ignoreMissingDescription
Arguments.of(
Collections.singletonList(new LinkedFile("", Path.of("wei2005ahp.pdf"), "PDF")),
":wei2005ahp.pdf:PDF"
),
// interpretLinkAsOnlyMandatoryField: single
Arguments.of(
Collections.singletonList(new LinkedFile("", Path.of("wei2005ahp.pdf"), "")),
"wei2005ahp.pdf"
),
// interpretLinkAsOnlyMandatoryField: multiple
Arguments.of(
List.of(
new LinkedFile("", Path.of("wei2005ahp.pdf"), ""),
new LinkedFile("", Path.of("other.pdf"), "")
),
"wei2005ahp.pdf;other.pdf"
),
// escapedCharactersInDescription
Arguments.of(
Collections.singletonList(new LinkedFile("test:;", Path.of("wei2005ahp.pdf"), "PDF")),
"test\\:\\;:wei2005ahp.pdf:PDF"
),
// handleXmlCharacters
Arguments.of(
Collections.singletonList(new LinkedFile("test,st:;", Path.of("wei2005ahp.pdf"), "PDF")),
"test,\\;st\\:\\;:wei2005ahp.pdf:PDF"
),
// handleEscapedFilePath
Arguments.of(
Collections.singletonList(new LinkedFile("desc", Path.of("C:\\test.pdf"), "PDF")),
"desc:C\\:\\\\test.pdf:PDF"
),
// handleNonEscapedFilePath
Arguments.of(
Collections.singletonList(new LinkedFile("desc", Path.of("C:\\test.pdf"), "PDF")),
"desc:C:\\test.pdf:PDF"
),
// Source: https://github.com/JabRef/jabref/issues/8991#issuecomment-1214131042
Arguments.of(
Collections.singletonList(new LinkedFile("Boyd2012.pdf", Path.of("C:\\Users\\Literature_database\\Boyd2012.pdf"), "PDF")),
"Boyd2012.pdf:C\\:\\\\Users\\\\Literature_database\\\\Boyd2012.pdf:PDF"
),
// subsetOfFieldsResultsInFileLink: description only
Arguments.of(
Collections.singletonList(new LinkedFile("", Path.of("file.pdf"), "")),
"file.pdf::"
),
// subsetOfFieldsResultsInFileLink: file only
Arguments.of(
Collections.singletonList(new LinkedFile("", Path.of("file.pdf"), "")),
":file.pdf"
),
// subsetOfFieldsResultsInFileLink: type only
Arguments.of(
Collections.singletonList(new LinkedFile("", Path.of("file.pdf"), "")),
"::file.pdf"
),
// tooManySeparators
Arguments.of(
Collections.singletonList(new LinkedFile("desc", Path.of("file.pdf"), "PDF")),
"desc:file.pdf:PDF:asdf"
),
// www inside filename
Arguments.of(
Collections.singletonList(new LinkedFile("", Path.of("/home/www.google.de.pdf"), "")),
":/home/www.google.de.pdf"
),
// url
Arguments.of(
Collections.singletonList(new LinkedFile(new URL("https://books.google.de/"), "")),
"https://books.google.de/"
),
// url with www
Arguments.of(
Collections.singletonList(new LinkedFile(new URL("https://www.google.de/"), "")),
"https://www.google.de/"
),
// url as file
Arguments.of(
Collections.singletonList(new LinkedFile("", new URL("http://ceur-ws.org/Vol-438"), "URL")),
":http\\://ceur-ws.org/Vol-438:URL"
),
// url as file with desc
Arguments.of(
Collections.singletonList(new LinkedFile("desc", new URL("http://ceur-ws.org/Vol-438"), "URL")),
"desc:http\\://ceur-ws.org/Vol-438:URL"
)
);
}
@ParameterizedTest
@MethodSource
public void stringsToParseTest(List<LinkedFile> expected, String input) {
assertEquals(expected, FileFieldParser.parse(input));
}
}
| 8,266 | 41.178571 | 217 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/GrobidServiceTest.java | package org.jabref.logic.importer.util;
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.ParseException;
import org.jabref.logic.importer.fetcher.GrobidPreferences;
import org.jabref.logic.importer.fileformat.PdfGrobidImporterTest;
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.BeforeAll;
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.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
public class GrobidServiceTest {
private static GrobidService grobidService;
private static ImportFormatPreferences importFormatPreferences;
@BeforeAll
public static void setup() {
importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(',');
GrobidPreferences grobidPreferences = new GrobidPreferences(
true,
false,
"http://grobid.jabref.org:8070");
grobidService = new GrobidService(grobidPreferences);
}
@Test
public void processValidCitationTest() throws IOException, ParseException {
BibEntry exampleBibEntry = 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.YEAR, "2002")
.withField(StandardField.MONTH, "9")
.withField(StandardField.PAGES, "245-259")
.withField(StandardField.VOLUME, "23")
.withField(StandardField.PUBLISHER, "Informa UK Limited")
.withField(StandardField.NUMBER, "4");
Optional<BibEntry> response = grobidService.processCitation("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.", importFormatPreferences, GrobidService.ConsolidateCitations.WITH_METADATA);
assertTrue(response.isPresent());
assertEquals(exampleBibEntry, response.get());
}
@Test
public void processEmptyStringTest() throws IOException, ParseException {
Optional<BibEntry> response = grobidService.processCitation(" ", importFormatPreferences, GrobidService.ConsolidateCitations.WITH_METADATA);
assertNotNull(response);
assertEquals(Optional.empty(), response);
}
@Test
public void processInvalidCitationTest() {
assertThrows(IOException.class, () -> grobidService.processCitation(
"iiiiiiiiiiiiiiiiiiiiiiii",
importFormatPreferences,
GrobidService.ConsolidateCitations.WITH_METADATA));
}
@Test
public void failsWhenGrobidDisabled() {
GrobidPreferences importSettingsWithGrobidDisabled = new GrobidPreferences(
false,
false,
"http://grobid.jabref.org:8070");
assertThrows(UnsupportedOperationException.class, () -> new GrobidService(importSettingsWithGrobidDisabled));
}
@Test
public void processPdfTest() throws IOException, ParseException, URISyntaxException {
Path file = Path.of(PdfGrobidImporterTest.class.getResource("LNCS-minimal.pdf").toURI());
List<BibEntry> response = grobidService.processPDF(file, importFormatPreferences);
assertEquals(1, response.size());
BibEntry be0 = response.get(0);
assertEquals(Optional.of("Lastname, Firstname"), be0.getField(StandardField.AUTHOR));
assertEquals(Optional.of("Paper Title"), be0.getField(StandardField.TITLE));
assertEquals(Optional.of("2014-10-05"), be0.getField(StandardField.DATE));
}
}
| 5,536 | 52.757282 | 180 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/GroupsParserTest.java | package org.jabref.logic.importer.util;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import javafx.scene.paint.Color;
import org.jabref.logic.auxparser.DefaultAuxParser;
import org.jabref.logic.importer.ParseException;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.AutomaticGroup;
import org.jabref.model.groups.AutomaticKeywordGroup;
import org.jabref.model.groups.AutomaticPersonsGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.groups.SearchGroup;
import org.jabref.model.groups.TexGroup;
import org.jabref.model.metadata.MetaData;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.model.util.FileUpdateMonitor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class GroupsParserTest {
private FileUpdateMonitor fileMonitor;
private MetaData metaData;
@BeforeEach
void setUp() throws Exception {
fileMonitor = new DummyFileUpdateMonitor();
metaData = new MetaData();
}
@Test
// For https://github.com/JabRef/jabref/issues/1681
void fromStringParsesExplicitGroupWithEscapedCharacterInName() throws Exception {
ExplicitGroup expected = new ExplicitGroup("B{\\\"{o}}hmer", GroupHierarchyType.INDEPENDENT, ',');
AbstractGroup parsed = GroupsParser.fromString("ExplicitGroup:B{\\\\\"{o}}hmer;0;", ',', fileMonitor, metaData);
assertEquals(expected, parsed);
}
@Test
void keywordDelimiterThatNeedsToBeEscaped() throws Exception {
AutomaticGroup expected = new AutomaticKeywordGroup("group1", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ';', '>');
AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;\\;;>;1;;;;;", ';', fileMonitor, metaData);
assertEquals(expected, parsed);
}
@Test
void hierarchicalDelimiterThatNeedsToBeEscaped() throws Exception {
AutomaticGroup expected = new AutomaticKeywordGroup("group1", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ',', ';');
AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:group1;0;keywords;,;\\;;1;;;;;", ';', fileMonitor, metaData);
assertEquals(expected, parsed);
}
@Test
void fromStringThrowsParseExceptionForNotEscapedGroupName() throws Exception {
assertThrows(ParseException.class, () -> GroupsParser.fromString("ExplicitGroup:slit\\\\;0\\;mertsch_slit2_2007\\;;", ',', fileMonitor, metaData));
}
@Test
void testImportSubGroups() throws Exception {
List<String> orderedData = Arrays.asList("0 AllEntriesGroup:", "1 ExplicitGroup:1;0;",
"2 ExplicitGroup:2;0;", "0 ExplicitGroup:3;0;");
// Create group hierarchy:
// Level 0 Name: All entries
// Level 1 Name: 1
// Level 2 Name: 2
// Level 1 Name: 3
GroupTreeNode rootNode = new GroupTreeNode(
new ExplicitGroup("All entries", GroupHierarchyType.INDEPENDENT, ','));
AbstractGroup firstSubGrpLvl1 = new ExplicitGroup("1", GroupHierarchyType.INDEPENDENT, ',');
rootNode.addSubgroup(firstSubGrpLvl1);
AbstractGroup subLvl2 = new ExplicitGroup("2", GroupHierarchyType.INDEPENDENT, ',');
rootNode.getFirstChild().ifPresent(c -> c.addSubgroup(subLvl2));
AbstractGroup thirdSubGrpLvl1 = new ExplicitGroup("3", GroupHierarchyType.INDEPENDENT, ',');
rootNode.addSubgroup(thirdSubGrpLvl1);
GroupTreeNode parsedNode = GroupsParser.importGroups(orderedData, ',', fileMonitor, metaData);
assertEquals(rootNode.getChildren(), parsedNode.getChildren());
}
@Test
void fromStringParsesExplicitGroupWithIconAndDescription() throws Exception {
ExplicitGroup expected = new ExplicitGroup("myExplicitGroup", GroupHierarchyType.INDEPENDENT, ',');
expected.setIconName("test icon");
expected.setExpanded(true);
expected.setColor(Color.ALICEBLUE);
expected.setDescription("test description");
AbstractGroup parsed = GroupsParser.fromString("StaticGroup:myExplicitGroup;0;1;0xf0f8ffff;test icon;test description;", ',', fileMonitor, metaData);
assertEquals(expected, parsed);
}
@Test
void fromStringParsesAutomaticKeywordGroup() throws Exception {
AutomaticGroup expected = new AutomaticKeywordGroup("myAutomaticGroup", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ',', '>');
AbstractGroup parsed = GroupsParser.fromString("AutomaticKeywordGroup:myAutomaticGroup;0;keywords;,;>;1;;;;", ',', fileMonitor, metaData);
assertEquals(expected, parsed);
}
@Test
void fromStringParsesAutomaticPersonGroup() throws Exception {
AutomaticPersonsGroup expected = new AutomaticPersonsGroup("myAutomaticGroup", GroupHierarchyType.INDEPENDENT, StandardField.AUTHOR);
AbstractGroup parsed = GroupsParser.fromString("AutomaticPersonsGroup:myAutomaticGroup;0;author;1;;;;", ',', fileMonitor, metaData);
assertEquals(expected, parsed);
}
@Test
void fromStringParsesTexGroup() throws Exception {
TexGroup expected = TexGroup.create("myTexGroup", GroupHierarchyType.INDEPENDENT, Path.of("path", "To", "File"), new DefaultAuxParser(new BibDatabase()), metaData);
AbstractGroup parsed = GroupsParser.fromString("TexGroup:myTexGroup;0;path/To/File;1;;;;", ',', fileMonitor, metaData);
assertEquals(expected, parsed);
}
@Test
void fromStringUnknownGroupThrowsException() throws Exception {
assertThrows(ParseException.class, () -> GroupsParser.fromString("0 UnknownGroup:myUnknownGroup;0;;1;;;;", ',', fileMonitor, metaData));
}
@Test
void fromStringParsesSearchGroup() throws Exception {
SearchGroup expected = new SearchGroup("Data", GroupHierarchyType.INCLUDING, "project=data|number|quant*", EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
AbstractGroup parsed = GroupsParser.fromString("SearchGroup:Data;2;project=data|number|quant*;0;1;1;;;;;", ',', fileMonitor, metaData);
assertEquals(expected, parsed);
}
}
| 6,586 | 44.743056 | 172 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/JsonReaderTest.java | package org.jabref.logic.importer.util;
import java.io.ByteArrayInputStream;
import org.jabref.logic.importer.ParseException;
import kong.unirest.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class JsonReaderTest {
@Test
void nullStreamThrowsNullPointerException() {
Assertions.assertThrows(NullPointerException.class, () -> {
JsonReader.toJsonObject(null);
});
}
@Test
void invalidJsonThrowsParserException() {
Assertions.assertThrows(ParseException.class, () -> {
JsonReader.toJsonObject(new ByteArrayInputStream("invalid JSON".getBytes()));
});
}
@Test
void emptyStringResultsInEmptyObject() throws Exception {
JSONObject result = JsonReader.toJsonObject(new ByteArrayInputStream("".getBytes()));
assertEquals("{}", result.toString());
}
@Test
void arrayThrowsParserException() {
// Reason: We expect a JSON object, not a JSON array
Assertions.assertThrows(ParseException.class, () -> {
JsonReader.toJsonObject(new ByteArrayInputStream("[]".getBytes()));
});
}
@Test
void exampleJsonResultsInSameJson() throws Exception {
String input = "{\"name\":\"test\"}";
JSONObject result = JsonReader.toJsonObject(new ByteArrayInputStream(input.getBytes()));
assertEquals(input, result.toString());
}
}
| 1,506 | 29.14 | 96 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/MathMLParserTest.java | package org.jabref.logic.importer.util;
import java.io.StringReader;
import java.util.stream.Stream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.junit.jupiter.api.BeforeAll;
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 MathMLParserTest {
private static XMLInputFactory xmlInputFactory;
@BeforeAll
public static void setUp() {
xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
}
@ParameterizedTest
@MethodSource("tests")
void parserConvertsMathMLIntoLatex(String expected, String input) throws XMLStreamException {
XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(new StringReader(input));
assertEquals(expected, MathMLParser.parse(reader));
}
private static Stream<Arguments> tests() {
return Stream.of(
Arguments.of("$\\begin{pmatrix}0 & 1 & 0\\\\ 0 & 0 & 1\\\\ 1 & 0 & 0\\end{pmatrix}$",
"""
<math xmlns="http://www.w3.org/1998/Math/MathML">
<matrix>
<matrixrow>
<cn> 0 </cn> <cn> 1 </cn> <cn> 0 </cn>
</matrixrow>
<matrixrow>
<cn> 0 </cn> <cn> 0 </cn> <cn> 1 </cn>
</matrixrow>
<matrixrow>
<cn> 1 </cn> <cn> 0 </cn> <cn> 0 </cn>
</matrixrow>
</matrix>
</math>
"""),
Arguments.of("${\\eta }_{p}^{2}$",
"""
<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML">
<mml:mrow>
<mml:msubsup>
<mml:mi>η</mml:mi>
<mml:mi>p</mml:mi>
<mml:mn>2</mml:mn>
</mml:msubsup>
</mml:mrow>
</mml:math>
"""),
Arguments.of("<Unsupported MathML expression>",
"""
<mml:math xmlns=http://www.w3.org/1998/Math/MathML>
<mml:mrow>
<mml:msubsup>
<mml:mi>η</abc>
</mml:msubsup>
</mml:mrow>
</mml:math>
"""),
Arguments.of("$\\underset{a}{\\overset{b}{\\int }}\\left(5x+2\\mathrm{sin}\\left(x\\right)\\right)\\mathrm{dx}$",
"""
<math xmlns="http://www.w3.org/1998/Math/MathML">
<munderover>
<mo>∫</mo>
<mi>a</mi>
<mi>b</mi>
</munderover>
<mfenced separators=''>
<mn>5</mn>
<mi>x</mi>
<mo>+</mo>
<mn>2</mn>
<mi>sin</mi>
<mfenced separators=''>
<mi>x</mi>
</mfenced>
</mfenced>
<mi>dx</mi>
</math>
"""),
Arguments.of("$\\stackrel{\\to }{v}=\\left({v}_{1},{v}_{2},{v}_{3}\\right)$",
"""
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mover>
<mi>v</mi>
<mo>→</mo>
</mover>
<mo>=</mo>
<mfenced>
<msub>
<mi>v</mi>
<mn>1</mn>
</msub>
<msub>
<mi>v</mi>
<mn>2</mn>
</msub>
<msub>
<mi>v</mi>
<mn>3</mn>
</msub>
</mfenced>
</math>
""")
);
}
}
| 5,663 | 45.809917 | 129 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/MetaDataParserTest.java | package org.jabref.logic.importer.util;
import java.util.Optional;
import java.util.stream.Stream;
import org.jabref.logic.exporter.MetaDataSerializerTest;
import org.jabref.model.entry.BibEntryTypeBuilder;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.UnknownEntryType;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MetaDataParserTest {
@ParameterizedTest
@CsvSource({
"C:\\temp\\test, C:\\temp\\test",
"\\\\servername\\path\\to\\file, \\\\\\\\servername\\\\path\\\\to\\\\file",
"\\\\servername\\path\\to\\file, \\\\servername\\path\\to\\file",
"//servername/path/to/file, //servername/path/to/file",
".\\pdfs, .\\pdfs,",
".\\pdfs, .\\\\pdfs,",
"., .",
})
void parseDirectory(String expected, String input) {
assertEquals(expected, MetaDataParser.parseDirectory(input));
}
/**
* In case of any change, copy the content to {@link MetaDataSerializerTest#serializeCustomizedEntryType()}
*/
public static Stream<Arguments> parseCustomizedEntryType() {
return Stream.of(
Arguments.of(
new BibEntryTypeBuilder()
.withType(new UnknownEntryType("test"))
.withRequiredFields(UnknownField.fromDisplayName("Test1"), UnknownField.fromDisplayName("Test2")),
"jabref-entrytype: test: req[Test1;Test2] opt[]"
),
Arguments.of(
new BibEntryTypeBuilder()
.withType(new UnknownEntryType("test"))
.withRequiredFields(UnknownField.fromDisplayName("tEST"), UnknownField.fromDisplayName("tEsT2")),
"jabref-entrytype: test: req[tEST;tEsT2] opt[]"
)
);
}
@ParameterizedTest
@MethodSource
void parseCustomizedEntryType(BibEntryTypeBuilder expected, String source) {
assertEquals(Optional.of(expected.build()), MetaDataParser.parseCustomEntryType(source));
}
}
| 2,479 | 40.333333 | 130 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/ShortDOIServiceTest.java | package org.jabref.logic.importer.util;
import org.jabref.model.entry.identifier.DOI;
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
class ShortDOIServiceTest {
private final DOI doi = new DOI("10.1109/ACCESS.2013.2260813");
private final DOI notExistingDoi = new DOI("10.1109/ACCESS.2013.226081400");
private ShortDOIService sut;
@BeforeEach
void setUp() {
sut = new ShortDOIService();
}
@Test
void getShortDOI() throws ShortDOIServiceException {
DOI shortDoi = sut.getShortDOI(doi);
assertEquals("10/gf4gqc", shortDoi.getDOI());
}
@Test
void shouldThrowExceptionWhenDOIWasNotFound() throws ShortDOIServiceException {
assertThrows(ShortDOIServiceException.class, () -> sut.getShortDOI(notExistingDoi));
}
}
| 1,012 | 26.378378 | 92 | java |
null | jabref-main/src/test/java/org/jabref/logic/importer/util/StaxParserTest.java | package org.jabref.logic.importer.util;
import java.io.StringReader;
import java.util.stream.Stream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.junit.jupiter.api.BeforeAll;
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 StaxParserTest {
private static XMLInputFactory xmlInputFactory;
@BeforeAll
public static void setUp() {
xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
}
@ParameterizedTest
@MethodSource("tests")
void getsCompleteXMLContent(String expected, String input) throws XMLStreamException {
XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(new StringReader(input));
assertEquals(expected, StaxParser.getXMLContent(reader));
}
private static Stream<Arguments> tests() {
return Stream.of(
Arguments.of("<ForeName attr=\"1\">Alan</ForeName>",
"""
<ForeName attr="1">Alan</ForeName>
"""),
Arguments.of("<ForeName attr=\"1\">Alan</ForeName>",
"""
<ForeName attr="1">Alan</ForeName>
<LastName attr="2">Grant</LastName>
"""),
Arguments.of("<ForeName attr=\"1\">Alan<ForeName attr=\"5\">MiddleName</ForeName></ForeName>",
"""
<ForeName attr="1">
Alan
<ForeName attr="5">MiddleName</ForeName>
</ForeName>
<LastName attr="2">Grant</LastName>
"""),
Arguments.of("<PubDate><Year>2020</Year><Month>Jul</Month><Day>24</Day></PubDate>",
"""
<PubDate>
<Year>2020</Year>
<Month>Jul</Month>
<Day>24</Day>
</PubDate>
"""),
Arguments.of("<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\"><mml:mrow><mml:msubsup><mml:mi>η</mml:mi><mml:mi>p</mml:mi><mml:mn>2</mml:mn></mml:msubsup></mml:mrow></mml:math>",
"""
<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML">
<mml:mrow>
<mml:msubsup>
<mml:mi>η</mml:mi>
<mml:mi>p</mml:mi>
<mml:mn>2</mml:mn>
</mml:msubsup>
</mml:mrow>
</mml:math>
"""),
Arguments.of("<Journal><ISSN IssnType=\"Electronic\">1613-4516</ISSN><JournalIssue CitedMedium=\"Internet\"><Volume>17</Volume><Issue>2-3</Issue><PubDate><Year>2020</Year><Month>Jul</Month><Day>24</Day></PubDate></JournalIssue><Title>Journal of integrative bioinformatics</Title><ISOAbbreviation>J Integr Bioinform</ISOAbbreviation></Journal>",
"""
<Journal>
<ISSN IssnType="Electronic">1613-4516</ISSN>
<JournalIssue CitedMedium="Internet">
<Volume>17</Volume>
<Issue>2-3</Issue>
<PubDate>
<Year>2020</Year>
<Month>Jul</Month>
<Day>24</Day>
</PubDate>
</JournalIssue>
<Title>Journal of integrative bioinformatics</Title>
<ISOAbbreviation>J Integr Bioinform</ISOAbbreviation>
</Journal>
""")
);
}
}
| 4,595 | 48.956522 | 360 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/ASCIICharacterCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ASCIICharacterCheckerTest {
private final ASCIICharacterChecker checker = new ASCIICharacterChecker();
private final BibEntry entry = new BibEntry();
@Test
void fieldAcceptsAsciiCharacters() {
entry.setField(StandardField.TITLE, "Only ascii characters!'@12");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void fieldDoesNotAcceptUmlauts() {
entry.setField(StandardField.MONTH, "Umlauts are nöt ällowed");
assertEquals(List.of(new IntegrityMessage("Non-ASCII encoded character found", entry, StandardField.MONTH)), checker.check(entry));
}
@Test
void fieldDoesNotAcceptUnicode() {
entry.setField(StandardField.AUTHOR, "Some unicode ⊕");
assertEquals(List.of(new IntegrityMessage("Non-ASCII encoded character found", entry, StandardField.AUTHOR)), checker.check(entry));
}
@Test
void fieldAcceptsOnlyAsciiCharacters() {
String field = "";
for (int i = 32; i <= 127; i++) {
field += Character.toString(i);
}
entry.setField(StandardField.TITLE, field);
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void fieldDoesNotAcceptNonAsciiCharacters() {
String field = Character.toString(31) + Character.toString(128);
entry.setField(StandardField.TITLE, field);
assertEquals(List.of(new IntegrityMessage("Non-ASCII encoded character found", entry, StandardField.TITLE)), checker.check(entry));
}
}
| 1,824 | 33.433962 | 140 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/AbbreviationCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import org.jabref.logic.journals.Abbreviation;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.journals.JournalAbbreviationRepository;
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 static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class AbbreviationCheckerTest {
private JournalAbbreviationRepository abbreviationRepository;
private AbbreviationChecker checker;
private BibEntry entry;
@BeforeEach
void setUp() {
abbreviationRepository = JournalAbbreviationLoader.loadBuiltInRepository();
abbreviationRepository.addCustomAbbreviation(new Abbreviation("Test Journal", "T. J."));
entry = new BibEntry(StandardEntryType.InProceedings);
checker = new AbbreviationChecker(abbreviationRepository);
}
@Test
void checkEntryComplainsAboutAbbreviatedJournalName() {
entry.setField(StandardField.BOOKTITLE, "T. J.");
assertNotEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void checkEntryDoesNotComplainAboutJournalNameThatHasSameAbbreviation() {
entry.setField(StandardField.BOOKTITLE, "Journal");
abbreviationRepository.addCustomAbbreviation(new Abbreviation("Journal", "Journal"));
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void checkEntryDoesNotComplainAboutJournalNameThatHasΝοAbbreviation() {
entry.setField(StandardField.BOOKTITLE, "IEEE Software");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void checkEntryDoesNotComplainAboutJournalNameThatHasΝοInput() {
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void checkEntryWorksForLaTeXField() {
entry.setField(StandardField.BOOKTITLE, "Reducing Complexity and Power of Digital Multibit Error-Feedback $\\Delta$$\\Sigma$ Modulators");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void checkEntryWorksForLaTeXFieldStilContainingIllegalChars() {
entry.setField(StandardField.BOOKTITLE, "Proceedings of the 5\\({}^{\\mbox{th}}\\) Central-European Workshop on Services and their Composition, Rostock, Germany, February 21-22, 2013");
assertEquals(Collections.emptyList(), checker.check(entry));
}
}
| 2,643 | 37.882353 | 193 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/AmpersandCheckerTest.java | package org.jabref.logic.integrity;
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.Field;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AmpersandCheckerTest {
private final AmpersandChecker checker = new AmpersandChecker();
private final BibEntry entry = new BibEntry();
@ParameterizedTest
@MethodSource("provideAcceptedInputs")
void acceptsAllowedInputs(List<IntegrityMessage> expected, Field field, String value) {
entry.setField(field, value);
assertEquals(expected, checker.check(entry));
}
private static Stream<Arguments> provideAcceptedInputs() {
return Stream.of(
Arguments.of(Collections.emptyList(), StandardField.TITLE, "No ampersand at all"),
Arguments.of(Collections.emptyList(), StandardField.FOREWORD, "Properly escaped \\&"),
Arguments.of(Collections.emptyList(), StandardField.AUTHOR, "\\& Multiple properly escaped \\&"),
Arguments.of(Collections.emptyList(), StandardField.BOOKTITLE, "\\\\\\& With multiple backslashes"),
Arguments.of(Collections.emptyList(), StandardField.COMMENT, "\\\\\\& With multiple backslashes multiple times \\\\\\\\\\&"),
Arguments.of(Collections.emptyList(), StandardField.NOTE, "In the \\& middle of \\\\\\& something")
);
}
@ParameterizedTest
@MethodSource("provideUnacceptedInputs")
void rejectsDisallowedInputs(String expectedMessage, Field field, String value) {
entry.setField(field, value);
assertEquals(List.of(new IntegrityMessage(expectedMessage, entry, field)), checker.check(entry));
}
private static Stream<Arguments> provideUnacceptedInputs() {
return Stream.of(
Arguments.of("Found 1 unescaped '&'", StandardField.SUBTITLE, "A single &"),
Arguments.of("Found 2 unescaped '&'", StandardField.ABSTRACT, "Multiple \\\\& not properly & escaped"),
Arguments.of("Found 1 unescaped '&'", StandardField.AUTHOR, "To many backslashes \\\\&"),
Arguments.of("Found 2 unescaped '&'", StandardField.LABEL, "\\\\\\\\& Multiple times \\\\& multiple backslashes")
);
}
@Test
void entryWithEscapedAndUnescapedAmpersand() {
entry.setField(StandardField.TITLE, "Jack \\& Jill & more");
assertEquals(List.of(new IntegrityMessage("Found 1 unescaped '&'", entry, StandardField.TITLE)), checker.check(entry));
}
@Test
void entryWithMultipleEscapedAndUnescapedAmpersands() {
entry.setField(StandardField.AFTERWORD, "May the force be with you & live long \\\\& prosper \\& to infinity \\\\\\& beyond & assemble \\\\\\\\& excelsior!");
assertEquals(List.of(new IntegrityMessage("Found 4 unescaped '&'", entry, StandardField.AFTERWORD)), checker.check(entry));
}
}
| 3,232 | 45.855072 | 166 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/BibStringCheckerTest.java | package org.jabref.logic.integrity;
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.Field;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BibStringCheckerTest {
private final BibStringChecker checker = new BibStringChecker();
private final BibEntry entry = new BibEntry();
@ParameterizedTest
@MethodSource("provideAcceptedInputs")
void acceptsAllowedInputs(List<IntegrityMessage> expected, Field field, String value) {
entry.setField(field, value);
assertEquals(expected, checker.check(entry));
}
private static Stream<Arguments> provideAcceptedInputs() {
return Stream.of(
Arguments.of(Collections.emptyList(), StandardField.TITLE, "Not a single hash mark"),
Arguments.of(Collections.emptyList(), StandardField.MONTH, "#jan#"),
Arguments.of(Collections.emptyList(), StandardField.AUTHOR, "#einstein# and #newton#")
);
}
@Test
void monthDoesNotAcceptOddNumberOfHashMarks() {
entry.setField(StandardField.MONTH, "#jan");
assertEquals(List.of(new IntegrityMessage("odd number of unescaped '#'", entry, StandardField.MONTH)), checker.check(entry));
}
@Test
void authorDoesNotAcceptOddNumberOfHashMarks() {
entry.setField(StandardField.AUTHOR, "#einstein# #amp; #newton#");
assertEquals(List.of(new IntegrityMessage("odd number of unescaped '#'", entry, StandardField.AUTHOR)), checker.check(entry));
}
}
| 1,863 | 36.28 | 134 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/BooktitleCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class BooktitleCheckerTest {
private final BooktitleChecker checker = new BooktitleChecker();
@Test
void booktitleAcceptsIfItDoesNotEndWithConferenceOn() {
assertEquals(Optional.empty(), checker.checkValue("2014 Fourth International Conference on Digital Information and Communication Technology and it's Applications (DICTAP)"));
}
@Test
void booktitleDoesNotAcceptsIfItEndsWithConferenceOn() {
assertNotEquals(Optional.empty(), checker.checkValue("Digital Information and Communication Technology and it's Applications (DICTAP), 2014 Fourth International Conference on"));
}
@Test
void booktitleIsBlank() {
assertEquals(Optional.empty(), checker.checkValue(" "));
}
}
| 972 | 32.551724 | 186 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/BracesCorrectorTest.java | package org.jabref.logic.integrity;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class BracesCorrectorTest {
@Test
public void inputIsNull() {
assertNull(BracesCorrector.apply(null));
}
@Test
public void inputIsEmpty() {
assertEquals("", BracesCorrector.apply(""));
}
@Test
public void inputWithoutBraces() {
assertEquals("banana", BracesCorrector.apply("banana"));
}
@Test
public void inputAlreadyCorrect() {
assertEquals("{banana}", BracesCorrector.apply("{banana}"));
}
@Test
public void inputMissingClosing() {
assertEquals("{banana}", BracesCorrector.apply("{banana"));
}
@Test
public void inputMissingOpening() {
assertEquals("{banana}", BracesCorrector.apply("banana}"));
}
@Test
public void inputWithMaskedBraces() {
assertEquals("\\\\\\{banana", BracesCorrector.apply("\\\\\\{banana"));
}
@Test
public void inputWithMixedBraces() {
assertEquals("{b{anana\\\\\\}}}", BracesCorrector.apply("{b{anana\\\\\\}"));
}
}
| 1,210 | 23.22 | 84 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/BracketCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class BracketCheckerTest {
private final BracketChecker checker = new BracketChecker();
@Test
void fieldAcceptsNoBrackets() {
assertEquals(Optional.empty(), checker.checkValue("x"));
}
@Test
void fieldAcceptsEvenNumberOfBrackets() {
assertEquals(Optional.empty(), checker.checkValue("{x}"));
}
@Test
void fieldAcceptsExpectedBracket() {
assertEquals(Optional.empty(), checker.checkValue("{x}x{}x{{}}"));
}
@Test
void fieldDoesNotAcceptOddNumberOfBrackets() {
assertNotEquals(Optional.empty(), checker.checkValue("{x}x{}}x{{}}"));
}
@Test
void fieldDoesNotAcceptUnexpectedClosingBracket() {
assertNotEquals(Optional.empty(), checker.checkValue("}"));
}
@Test
void fieldDoesNotAcceptUnexpectedOpeningBracket() {
assertNotEquals(Optional.empty(), checker.checkValue("{"));
}
@Test
void fieldAcceptsFirstCharacterNotABracket() {
assertEquals(Optional.empty(), checker.checkValue("test{x}"));
}
@Test
void fieldAcceptsLastCharacterNotABracket() {
assertEquals(Optional.empty(), checker.checkValue("{x}test"));
}
@Test
void fieldAcceptsFirstAndLastCharacterNotABracket() {
assertEquals(Optional.empty(), checker.checkValue("test{x}test"));
}
@Test
void fieldAcceptsEmptyInput() {
assertEquals(Optional.empty(), checker.checkValue(""));
}
}
| 1,683 | 25.3125 | 78 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/CitationKeyCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CitationKeyCheckerTest {
private final CitationKeyChecker checker = new CitationKeyChecker();
@Test
void bibTexAcceptsKeyFromAuthorAndYear() {
BibEntry entry = new BibEntry().withField(InternalField.KEY_FIELD, "Knuth2014")
.withField(StandardField.AUTHOR, "Knuth")
.withField(StandardField.YEAR, "2014");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void acceptsKeyFromAuthorAndTitle() {
BibEntry entry = new BibEntry().withField(InternalField.KEY_FIELD, "BrownTheTitle")
.withField(StandardField.AUTHOR, "Brown")
.withField(StandardField.TITLE, "The Title");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void acceptsKeyFromTitleAndYear() {
BibEntry entry = new BibEntry().withField(InternalField.KEY_FIELD, "TheTitle2021")
.withField(StandardField.TITLE, "The Title")
.withField(StandardField.YEAR, "2021");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void emptyCitationKey() {
BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Brown")
.withField(StandardField.TITLE, "The Title")
.withField(StandardField.YEAR, "2021");
List<IntegrityMessage> expected = Collections.singletonList(new IntegrityMessage(Localization.lang("empty citation key") + ": " + entry.getAuthorTitleYear(100), entry, InternalField.KEY_FIELD));
assertEquals(expected, checker.check(entry));
}
}
| 2,184 | 41.019231 | 202 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/CitationKeyDeviationCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.citationkeypattern.AbstractCitationKeyPattern;
import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences;
import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.metadata.MetaData;
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;
public class CitationKeyDeviationCheckerTest {
private final BibDatabaseContext bibDatabaseContext = mock(BibDatabaseContext.class);
private final BibDatabase bibDatabase = mock(BibDatabase.class);
private final MetaData metaData = mock(MetaData.class);
private final AbstractCitationKeyPattern abstractCitationKeyPattern = mock(AbstractCitationKeyPattern.class);
private final GlobalCitationKeyPattern globalCitationKeyPattern = mock(GlobalCitationKeyPattern.class);
private final CitationKeyPatternPreferences citationKeyPatternPreferences = mock(CitationKeyPatternPreferences.class);
private final CitationKeyDeviationChecker checker = new CitationKeyDeviationChecker(bibDatabaseContext, citationKeyPatternPreferences);
@BeforeEach
void setUp() {
when(bibDatabaseContext.getMetaData()).thenReturn(metaData);
when(citationKeyPatternPreferences.getKeyPattern()).thenReturn(globalCitationKeyPattern);
when(metaData.getCiteKeyPattern(citationKeyPatternPreferences.getKeyPattern())).thenReturn(abstractCitationKeyPattern);
when(bibDatabaseContext.getDatabase()).thenReturn(bibDatabase);
}
@Test
void citationKeyDeviatesFromGeneratedKey() {
BibEntry entry = new BibEntry().withField(InternalField.KEY_FIELD, "Knuth2014")
.withField(StandardField.AUTHOR, "Knuth")
.withField(StandardField.YEAR, "2014");
List<IntegrityMessage> expected = Collections.singletonList(new IntegrityMessage(
Localization.lang("Citation key deviates from generated key"), entry, InternalField.KEY_FIELD));
assertEquals(expected, checker.check(entry));
}
}
| 2,586 | 48.75 | 139 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/CitationKeyDuplicationCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CitationKeyDuplicationCheckerTest {
@Test
void emptyCitationKey() {
BibEntry entry = new BibEntry().withField(InternalField.KEY_FIELD, "")
.withField(StandardField.AUTHOR, "Knuth")
.withField(StandardField.YEAR, "2014");
BibDatabase bibDatabase = new BibDatabase(List.of(entry));
CitationKeyDuplicationChecker checker = new CitationKeyDuplicationChecker(bibDatabase);
List<IntegrityMessage> expected = Collections.emptyList();
assertEquals(expected, checker.check(entry));
}
@Test
void hasDuplicateCitationKey() {
BibEntry entry = new BibEntry().withField(InternalField.KEY_FIELD, "Knuth2014")
.withField(StandardField.AUTHOR, "Knuth")
.withField(StandardField.YEAR, "2014");
BibEntry entry2 = new BibEntry().withField(InternalField.KEY_FIELD, "Knuth2014")
.withField(StandardField.AUTHOR, "Knuth")
.withField(StandardField.YEAR, "2014");
BibDatabase bibDatabase = new BibDatabase(List.of(entry, entry2));
CitationKeyDuplicationChecker checker = new CitationKeyDuplicationChecker(bibDatabase);
List<IntegrityMessage> expected = Collections.singletonList(
new IntegrityMessage(Localization.lang("Duplicate citation key"), entry, StandardField.KEY));
assertEquals(expected, checker.check(entry));
}
}
| 2,001 | 42.521739 | 109 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/DateCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
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;
class DateCheckerTest {
private final DateChecker checker = new DateChecker();
@Test
void acceptsEmptyInput() {
assertEquals(Optional.empty(), checker.checkValue(""));
}
@ParameterizedTest
@ValueSource(strings = {"2018-04-21", "2018-04", "21-04-2018", "04-2018", "04/18", "04/2018", "April 21, 2018", "April, 2018", "21.04.2018", "2018.04.21", "2018"})
void acceptsValidDates(String s) {
assertEquals(Optional.empty(), checker.checkValue(s));
}
@ParameterizedTest
@ValueSource(strings = {"2018-04-21TZ", "2018-Apr-21", "2018-Apr-Twentyone", "2018-Apr-Twentyfirst", "2018_04_21", "2018 04 21", "2018~04~21"})
void complainsAboutInvalidInput(String s) {
assertEquals(Optional.of("incorrect format"), checker.checkValue(s));
}
}
| 1,070 | 32.46875 | 167 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/DoiDuplicationCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DoiDuplicationCheckerTest {
private final DoiDuplicationChecker checker = new DoiDuplicationChecker();
private String doiA = "10.1023/A:1022883727209";
private String doiB = "10.1177/1461444811422887";
private String doiC = "10.1145/2568225.2568315";
private BibEntry doiA_entry1 = new BibEntry().withField(StandardField.DOI, doiA);
private BibEntry doiA_entry2 = new BibEntry().withField(StandardField.DOI, doiA);
private BibEntry doiB_entry1 = new BibEntry().withField(StandardField.DOI, doiB);
private BibEntry doiB_entry2 = new BibEntry().withField(StandardField.DOI, doiB);
private BibEntry doiC_entry1 = new BibEntry().withField(StandardField.DOI, doiC);
@Test
public void testOnePairDuplicateDOI() {
List<BibEntry> entries = List.of(doiA_entry1, doiA_entry2, doiC_entry1);
BibDatabase database = new BibDatabase(entries);
List<IntegrityMessage> results = List.of(new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiA_entry1, StandardField.DOI),
new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiA_entry2, StandardField.DOI));
assertEquals(results, checker.check(database));
}
@Test
public void testMultiPairsDuplicateDOI() {
List<BibEntry> entries = List.of(doiA_entry1, doiA_entry2, doiB_entry1, doiB_entry2, doiC_entry1);
BibDatabase database = new BibDatabase(entries);
List<IntegrityMessage> results = List.of(new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiA_entry1, StandardField.DOI),
new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiA_entry2, StandardField.DOI),
new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiB_entry1, StandardField.DOI),
new IntegrityMessage(Localization.lang("Same DOI used in multiple entries"), doiB_entry2, StandardField.DOI));
assertEquals(results, checker.check(database));
}
@Test
public void testNoDuplicateDOI() {
List<BibEntry> entries = List.of(doiA_entry1, doiB_entry1, doiC_entry1);
BibDatabase database = new BibDatabase(entries);
assertEquals(Collections.emptyList(), checker.check(database));
}
}
| 2,704 | 49.092593 | 158 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/DoiValidityCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
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;
class DoiValidityCheckerTest {
private final DoiValidityChecker checker = new DoiValidityChecker();
@Test
void doiAcceptsValidInput() {
assertEquals(Optional.empty(), checker.checkValue("10.1023/A:1022883727209"));
}
@Test
void doiAcceptsEmptyInput() {
assertEquals(Optional.empty(), checker.checkValue(""));
}
@Test
void doiAcceptsValidInputWithNotOnlyNumbers() {
assertEquals(Optional.empty(), checker.checkValue("10.17487/rfc1436"));
}
@Test
void doiAcceptsValidInputNoMatterTheLengthOfTheDOIName() {
assertEquals(Optional.empty(), checker.checkValue("10.1002/(SICI)1097-4571(199205)43:4<284::AID-ASI3>3.0.CO;2-0"));
}
@Test
void doiDoesNotAcceptInvalidInput() {
assertNotEquals(Optional.empty(), checker.checkValue("asdf"));
}
@ParameterizedTest
@ValueSource(strings = {"11.1000/182", "01.1000/182", "100.1000/182", "110.1000/182", "a10.1000/182", "10a.1000/182"})
void doiDoesNotAcceptInputWithTypoInFirstPart(String s) {
assertNotEquals(Optional.empty(), checker.checkValue(s));
}
@ParameterizedTest
@ValueSource(strings = {"10.a1000/182", "10.1000a/182", "10.10a00/182"})
void doiDoesNotAcceptInputWithTypoInSecondPart(String s) {
assertNotEquals(Optional.empty(), checker.checkValue(s));
}
}
| 1,692 | 30.943396 | 123 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/EditionCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class EditionCheckerTest {
@Test
void isFirstCharacterANumber() {
assertTrue(createSimpleEditionChecker(new BibDatabaseContext(), false).isFirstCharDigit("0HelloWorld"));
}
@Test
void isFirstCharacterANumberFalseForEmptyString() {
assertFalse(createSimpleEditionChecker(new BibDatabaseContext(), false).isFirstCharDigit(""));
}
@Test
void isFirstCharacterNotANumber() {
assertFalse(createSimpleEditionChecker(new BibDatabaseContext(), false).isFirstCharDigit("HelloWorld"));
}
@Test
void editionCheckerDoesNotComplainIfAllowIntegerEditionIsEnabled() {
assertEquals(Optional.empty(), createSimpleEditionChecker(new BibDatabaseContext(), true).checkValue("2"));
}
@Test
void bibTexAcceptsOrdinalNumberInWordsWithCapitalFirstLetter() {
assertEquals(Optional.empty(), createBibtexEditionChecker(true).checkValue("Second"));
}
@Test
void bibTexDoesNotAcceptOrdinalNumberInWordsWithNonCapitalFirstLetter() {
assertNotEquals(Optional.empty(), createBibtexEditionChecker(true).checkValue("second"));
}
@Test
void bibTexAcceptsIntegerInputInEdition() {
assertEquals(Optional.empty(), createBibtexEditionChecker(true).checkValue("2"));
}
@Test
void bibTexAcceptsOrdinalNumberInNumbers() {
assertEquals(Optional.empty(), createBibtexEditionChecker(true).checkValue("2nd"));
}
@Test
void bibTexEmptyValueAsInput() {
assertEquals(Optional.empty(), createBibtexEditionChecker(false).checkValue(""));
}
@Test
void bibTexNullValueAsInput() {
assertEquals(Optional.empty(), createBibtexEditionChecker(false).checkValue(null));
}
@Test
void bibTexDoesNotAcceptIntegerOnly() {
assertEquals(Optional.of(Localization.lang("no integer as values for edition allowed")), createBibtexEditionChecker(false).checkValue("3"));
}
@Test
void bibTexAcceptsFirstEditionAlsoIfIntegerEditionDisallowed() {
assertEquals(Optional.of(Localization.lang("edition of book reported as just 1")), createBibtexEditionChecker(false).checkValue("1"));
}
@Test
void bibLaTexAcceptsEditionWithCapitalFirstLetter() {
assertEquals(Optional.empty(), createBiblatexEditionChecker(true).checkValue("Edition 2000"));
}
@Test
void bibLaTexAcceptsIntegerInputInEdition() {
assertEquals(Optional.empty(), createBiblatexEditionChecker(true).checkValue("2"));
}
@Test
void bibLaTexAcceptsEditionAsLiteralString() {
assertEquals(Optional.empty(), createBiblatexEditionChecker(true).checkValue("Third, revised and expanded edition"));
}
@Test
void bibLaTexDoesNotAcceptOrdinalNumberInNumbers() {
assertNotEquals(Optional.empty(), createBiblatexEditionChecker(true).checkValue("2nd"));
}
private EditionChecker createBibtexEditionChecker(Boolean allowIntegerEdition) {
BibDatabaseContext bibtex = new BibDatabaseContext();
bibtex.setMode(BibDatabaseMode.BIBTEX);
return new EditionChecker(bibtex, allowIntegerEdition);
}
private EditionChecker createBiblatexEditionChecker(Boolean allowIntegerEdition) {
BibDatabaseContext biblatex = new BibDatabaseContext();
biblatex.setMode(BibDatabaseMode.BIBLATEX);
return new EditionChecker(biblatex, allowIntegerEdition);
}
private EditionChecker createSimpleEditionChecker(BibDatabaseContext bibDatabaseContextEdition, boolean allowIntegerEdition) {
return new EditionChecker(bibDatabaseContextEdition, allowIntegerEdition);
}
}
| 4,127 | 35.530973 | 148 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/EntryLinkCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.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.assertThrows;
class EntryLinkCheckerTest {
private BibDatabase database;
private EntryLinkChecker checker;
private BibEntry entry;
@BeforeEach
void setUp() {
database = new BibDatabase();
checker = new EntryLinkChecker(database);
entry = new BibEntry();
database.insertEntry(entry);
}
@Test
void testEntryLinkChecker() {
assertThrows(NullPointerException.class, () -> new EntryLinkChecker(null));
}
@Test
void testCheckNoFields() {
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void testCheckNonRelatedFieldsOnly() {
entry.setField(StandardField.YEAR, "2016");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void testCheckNonExistingCrossref() {
entry.setField(StandardField.CROSSREF, "banana");
List<IntegrityMessage> message = checker.check(entry);
assertFalse(message.isEmpty(), message.toString());
}
@Test
void testCheckExistingCrossref() {
entry.setField(StandardField.CROSSREF, "banana");
BibEntry entry2 = new BibEntry();
entry2.setCitationKey("banana");
database.insertEntry(entry2);
List<IntegrityMessage> message = checker.check(entry);
assertEquals(Collections.emptyList(), message);
}
@Test
void testCheckExistingRelated() {
entry.setField(StandardField.RELATED, "banana,pineapple");
BibEntry entry2 = new BibEntry();
entry2.setCitationKey("banana");
database.insertEntry(entry2);
BibEntry entry3 = new BibEntry();
entry3.setCitationKey("pineapple");
database.insertEntry(entry3);
List<IntegrityMessage> message = checker.check(entry);
assertEquals(Collections.emptyList(), message);
}
@Test
void testCheckNonExistingRelated() {
BibEntry entry1 = new BibEntry();
entry1.setField(StandardField.RELATED, "banana,pineapple,strawberry");
database.insertEntry(entry1);
BibEntry entry2 = new BibEntry();
entry2.setCitationKey("banana");
database.insertEntry(entry2);
BibEntry entry3 = new BibEntry();
entry3.setCitationKey("pineapple");
database.insertEntry(entry3);
List<IntegrityMessage> message = checker.check(entry1);
assertFalse(message.isEmpty(), message.toString());
}
}
| 2,928 | 28 | 83 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/HTMLCharacterCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class HTMLCharacterCheckerTest {
private final HTMLCharacterChecker checker = new HTMLCharacterChecker();
private final BibEntry entry = new BibEntry();
@Test
void testSettingNullThrowsNPE() {
assertThrows(
NullPointerException.class,
() -> entry.setField(StandardField.AUTHOR, null)
);
}
@Test
void titleAcceptsNonHTMLEncodedCharacters() {
entry.setField(StandardField.TITLE, "Not a single {HTML} character");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void monthAcceptsNonHTMLEncodedCharacters() {
entry.setField(StandardField.MONTH, "#jan#");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void authorAcceptsNonHTMLEncodedCharacters() {
entry.setField(StandardField.AUTHOR, "A. Einstein and I. Newton");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void urlAcceptsNonHTMLEncodedCharacters() {
entry.setField(StandardField.URL, "http://www.thinkmind.org/index.php?view=article&articleid=cloud_computing_2013_1_20_20130");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void authorDoesNotAcceptHTMLEncodedCharacters() {
entry.setField(StandardField.AUTHOR, "Lenhard, Jãrg");
assertEquals(List.of(new IntegrityMessage("HTML encoded character found", entry, StandardField.AUTHOR)), checker.check(entry));
}
@Test
void journalDoesNotAcceptHTMLEncodedCharacters() {
entry.setField(StandardField.JOURNAL, "Ärling Ström for – ‱");
assertEquals(List.of(new IntegrityMessage("HTML encoded character found", entry, StandardField.JOURNAL)), checker.check(entry));
}
}
| 2,178 | 33.587302 | 139 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/HowPublishedCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
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.assertNotEquals;
public class HowPublishedCheckerTest {
private HowPublishedChecker checker;
private HowPublishedChecker checkerBiblatex;
@BeforeEach
public void setUp() {
BibDatabaseContext databaseContext = new BibDatabaseContext();
BibDatabaseContext databaseBiblatex = new BibDatabaseContext();
databaseContext.setMode(BibDatabaseMode.BIBTEX);
checker = new HowPublishedChecker(databaseContext);
databaseBiblatex.setMode(BibDatabaseMode.BIBLATEX);
checkerBiblatex = new HowPublishedChecker(databaseBiblatex);
}
@Test
void bibTexAcceptsStringWithCapitalFirstLetter() {
assertEquals(Optional.empty(), checker.checkValue("Lorem ipsum"));
}
@Test
void bibTexDoesNotCareAboutSpecialCharacters() {
assertEquals(Optional.empty(), checker.checkValue("Lorem ipsum? 10"));
}
@Test
void bibTexDoesNotAcceptStringWithLowercaseFirstLetter() {
assertNotEquals(Optional.empty(), checker.checkValue("lorem ipsum"));
}
@Test
void bibTexAcceptsUrl() {
assertEquals(Optional.empty(), checker.checkValue("\\url{someurl}"));
}
@Test
void bibLaTexAcceptsStringWithCapitalFirstLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("Lorem ipsum"));
}
@Test
void bibLaTexAcceptsStringWithLowercaseFirstLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("lorem ipsum"));
}
}
| 1,837 | 30.152542 | 82 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/ISBNCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import java.util.stream.Stream;
import org.jabref.logic.l10n.Localization;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class ISBNCheckerTest {
private final ISBNChecker checker = new ISBNChecker();
@Test
void isbnAcceptsValidInput() {
assertEquals(Optional.empty(), checker.checkValue("0-201-53082-1"));
}
@Test
void isbnAcceptsNumbersAndCharacters() {
assertEquals(Optional.empty(), checker.checkValue("0-9752298-0-X"));
}
@Test
void isbnDoesNotAcceptRandomInput() {
assertNotEquals(Optional.empty(), checker.checkValue("Some other stuff"));
}
@Test
void isbnDoesNotAcceptInvalidInput() {
assertNotEquals(Optional.empty(), checker.checkValue("0-201-53082-2"));
}
@ParameterizedTest
@MethodSource("provideBoundaryArgumentsForISBN13")
public void checkISBNValue(Optional optValue, String id) {
assertEquals(optValue, checker.checkValue(id));
}
private static Stream<Arguments> provideBoundaryArgumentsForISBN13() {
return Stream.of(
Arguments.of(Optional.empty(), "978-0-306-40615-7"),
Arguments.of(Optional.of(Localization.lang("incorrect control digit")), "978-0-306-40615-2"),
Arguments.of(Optional.of(Localization.lang("incorrect format")), "978_0_306_40615_7")
);
}
}
| 1,708 | 30.648148 | 109 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/ISSNCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import java.util.stream.Stream;
import org.jabref.logic.l10n.Localization;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class ISSNCheckerTest {
private final ISSNChecker checker = new ISSNChecker();
@Test
void issnAcceptsValidInput() {
assertEquals(Optional.empty(), checker.checkValue("0020-7217"));
}
@Test
void issnAcceptsNumbersAndCharacters() {
assertEquals(Optional.empty(), checker.checkValue("2434-561x"));
}
@Test
void issnDoesNotAcceptRandomInput() {
assertNotEquals(Optional.empty(), checker.checkValue("Some other stuff"));
}
@Test
void issnDoesNotAcceptInvalidInput() {
assertNotEquals(Optional.empty(), checker.checkValue("0020-7218"));
}
@Test
void emptyIssnValue() {
assertEquals(Optional.empty(), checker.checkValue(""));
}
@ParameterizedTest
@MethodSource("provideIncorrectFormatArguments")
public void issnWithWrongFormat(String wrongISSN) {
assertEquals(Optional.of(Localization.lang("incorrect format")), checker.checkValue(wrongISSN));
}
private static Stream<Arguments> provideIncorrectFormatArguments() {
return Stream.of(
Arguments.of("020-721"),
Arguments.of("0020-72109"),
Arguments.of("0020~72109")
);
}
}
| 1,690 | 27.661017 | 104 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java | package org.jabref.logic.integrity;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
import org.jabref.logic.citationkeypattern.CitationKeyGenerator;
import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences;
import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.IEEETranEntryType;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.metadata.MetaData;
import org.jabref.preferences.FilePreferences;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* This class tests the Integrity Checker as a whole.
* Aspects are: selected fields, issues arising in a complete BibTeX entry, ... When testing a checker works with a certain input,
* this test has to go to a test belonging to the respective checker. See PersonNamesCheckerTest for an example test.
*/
class IntegrityCheckTest {
@Test
void bibTexAcceptsStandardEntryType() {
assertCorrect(withMode(createContext(StandardField.TITLE, "sometitle", StandardEntryType.Article), BibDatabaseMode.BIBTEX));
}
@Test
void bibTexDoesNotAcceptIEEETranEntryType() {
assertWrong(withMode(createContext(StandardField.TITLE, "sometitle", IEEETranEntryType.Patent), BibDatabaseMode.BIBTEX));
}
@Test
void bibLaTexAcceptsIEEETranEntryType() {
assertCorrect((withMode(createContext(StandardField.TITLE, "sometitle", IEEETranEntryType.Patent), BibDatabaseMode.BIBLATEX)));
}
@Test
void bibLaTexAcceptsStandardEntryType() {
assertCorrect(withMode(createContext(StandardField.TITLE, "sometitle", StandardEntryType.Article), BibDatabaseMode.BIBLATEX));
}
@ParameterizedTest
@MethodSource("provideCorrectFormat")
void authorNameChecksCorrectFormat(String input) {
for (Field field : FieldFactory.getPersonNameFields()) {
assertCorrect(withMode(createContext(field, input), BibDatabaseMode.BIBLATEX));
}
}
@ParameterizedTest
@MethodSource("provideIncorrectFormat")
void authorNameChecksIncorrectFormat(String input) {
for (Field field : FieldFactory.getPersonNameFields()) {
assertWrong(withMode(createContext(field, input), BibDatabaseMode.BIBLATEX));
}
}
private static Stream<String> provideCorrectFormat() {
return Stream.of("", "Knuth", "Donald E. Knuth and Kurt Cobain and A. Einstein");
}
private static Stream<String> provideIncorrectFormat() {
return Stream.of(" Knuth, Donald E. ",
"Knuth, Donald E. and Kurt Cobain and A. Einstein",
", and Kurt Cobain and A. Einstein", "Donald E. Knuth and Kurt Cobain and ,",
"and Kurt Cobain and A. Einstein", "Donald E. Knuth and Kurt Cobain and");
}
@Test
void testFileChecks() {
MetaData metaData = mock(MetaData.class);
Mockito.when(metaData.getDefaultFileDirectory()).thenReturn(Optional.of("."));
Mockito.when(metaData.getUserFileDirectory(any(String.class))).thenReturn(Optional.empty());
// FIXME: must be set as checkBibtexDatabase only activates title checker based on database mode
Mockito.when(metaData.getMode()).thenReturn(Optional.of(BibDatabaseMode.BIBTEX));
assertCorrect(createContext(StandardField.FILE, ":build.gradle:gradle", metaData));
assertCorrect(createContext(StandardField.FILE, "description:build.gradle:gradle", metaData));
assertWrong(createContext(StandardField.FILE, ":asflakjfwofja:PDF", metaData));
}
@Test
void fileCheckFindsFilesRelativeToBibFile(@TempDir Path testFolder) throws IOException {
Path bibFile = testFolder.resolve("lit.bib");
Files.createFile(bibFile);
Path pdfFile = testFolder.resolve("file.pdf");
Files.createFile(pdfFile);
BibDatabaseContext databaseContext = createContext(StandardField.FILE, ":file.pdf:PDF");
databaseContext.setDatabasePath(bibFile);
assertCorrect(databaseContext);
}
@Test
void testEntryIsUnchangedAfterChecks() {
BibEntry entry = new BibEntry();
// populate with all known fields
for (Field field : FieldFactory.getCommonFields()) {
entry.setField(field, UUID.randomUUID().toString());
}
// add a random field
entry.setField(StandardField.EPRINT, UUID.randomUUID().toString());
// duplicate entry
BibEntry clonedEntry = (BibEntry) entry.clone();
BibDatabase bibDatabase = new BibDatabase();
bibDatabase.insertEntry(entry);
BibDatabaseContext context = new BibDatabaseContext(bibDatabase);
new IntegrityCheck(context,
mock(FilePreferences.class),
createCitationKeyPatternPreferences(),
JournalAbbreviationLoader.loadBuiltInRepository(), false)
.check();
assertEquals(clonedEntry, entry);
}
private BibDatabaseContext createContext(Field field, String value, EntryType type) {
BibEntry entry = new BibEntry(type)
.withField(field, value);
BibDatabase bibDatabase = new BibDatabase();
bibDatabase.insertEntry(entry);
return new BibDatabaseContext(bibDatabase);
}
private BibDatabaseContext createContext(Field field, String value, MetaData metaData) {
BibEntry entry = new BibEntry()
.withField(field, value);
BibDatabase bibDatabase = new BibDatabase();
bibDatabase.insertEntry(entry);
return new BibDatabaseContext(bibDatabase, metaData);
}
private BibDatabaseContext createContext(Field field, String value) {
MetaData metaData = new MetaData();
metaData.setMode(BibDatabaseMode.BIBTEX);
return createContext(field, value, metaData);
}
private void assertWrong(BibDatabaseContext context) {
List<IntegrityMessage> messages = new IntegrityCheck(context,
mock(FilePreferences.class),
createCitationKeyPatternPreferences(),
JournalAbbreviationLoader.loadBuiltInRepository(), false)
.check();
assertNotEquals(Collections.emptyList(), messages);
}
private void assertCorrect(BibDatabaseContext context) {
FilePreferences filePreferencesMock = mock(FilePreferences.class);
when(filePreferencesMock.shouldStoreFilesRelativeToBibFile()).thenReturn(true);
List<IntegrityMessage> messages = new IntegrityCheck(context,
filePreferencesMock,
createCitationKeyPatternPreferences(),
JournalAbbreviationLoader.loadBuiltInRepository(), false
).check();
assertEquals(Collections.emptyList(), messages);
}
private CitationKeyPatternPreferences createCitationKeyPatternPreferences() {
return new CitationKeyPatternPreferences(
false,
false,
false,
CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_B,
"",
"",
CitationKeyGenerator.DEFAULT_UNWANTED_CHARACTERS,
GlobalCitationKeyPattern.fromPattern("[auth][year]"),
"",
',');
}
private BibDatabaseContext withMode(BibDatabaseContext context, BibDatabaseMode mode) {
context.setMode(mode);
return context;
}
}
| 8,458 | 39.473684 | 135 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/JournalInAbbreviationListCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.journals.Abbreviation;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class JournalInAbbreviationListCheckerTest {
private JournalInAbbreviationListChecker checker;
private JournalInAbbreviationListChecker checkerb;
private JournalAbbreviationRepository abbreviationRepository;
private BibEntry entry;
@BeforeEach
void setUp() {
abbreviationRepository = JournalAbbreviationLoader.loadBuiltInRepository();
abbreviationRepository.addCustomAbbreviation(new Abbreviation("IEEE Software", "IEEE SW"));
checker = new JournalInAbbreviationListChecker(StandardField.JOURNAL, abbreviationRepository);
checkerb = new JournalInAbbreviationListChecker(StandardField.JOURNALTITLE, abbreviationRepository);
entry = new BibEntry();
}
@Test
void journalAcceptsNameInTheList() {
entry.setField(StandardField.JOURNAL, "IEEE Software");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void journalDoesNotAcceptNameNotInList() {
entry.setField(StandardField.JOURNAL, "IEEE Whocares");
assertEquals(List.of(new IntegrityMessage("journal not found in abbreviation list", entry, StandardField.JOURNAL)), checker.check(entry));
}
@Test
void journalTitleDoesNotAcceptRandomInputInTitle() {
entry.setField(StandardField.JOURNALTITLE, "A journal");
assertEquals(List.of(new IntegrityMessage("journal not found in abbreviation list", entry, StandardField.JOURNALTITLE)), checkerb.check(entry));
}
@Test
void journalDoesNotAcceptRandomInputInTitle() {
entry.setField(StandardField.JOURNAL, "A journal");
assertEquals(List.of(new IntegrityMessage("journal not found in abbreviation list", entry, StandardField.JOURNAL)), checker.check(entry));
}
}
| 2,255 | 38.578947 | 152 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/MonthCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
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.assertNotEquals;
public class MonthCheckerTest {
private MonthChecker checker;
private MonthChecker checkerBiblatex;
@BeforeEach
public void setUp() {
BibDatabaseContext databaseContext = new BibDatabaseContext();
BibDatabaseContext databaseBiblatex = new BibDatabaseContext();
databaseContext.setMode(BibDatabaseMode.BIBTEX);
checker = new MonthChecker(databaseContext);
databaseBiblatex.setMode(BibDatabaseMode.BIBLATEX);
checkerBiblatex = new MonthChecker(databaseBiblatex);
}
@Test
void bibTexAcceptsThreeLetterAbbreviationsWithHashMarks() {
assertEquals(Optional.empty(), checker.checkValue("#mar#"));
}
@Test
void bibTexDoesNotAcceptWhateverThreeLetterAbbreviations() {
assertNotEquals(Optional.empty(), checker.checkValue("#bla#"));
}
@Test
void bibTexDoesNotAcceptThreeLetterAbbreviationsWithNoHashMarks() {
assertNotEquals(Optional.empty(), checker.checkValue("Dec"));
}
@Test
void bibTexDoesNotAcceptFullInput() {
assertNotEquals(Optional.empty(), checker.checkValue("December"));
}
@Test
void bibTexDoesNotAcceptRandomString() {
assertNotEquals(Optional.empty(), checker.checkValue("Lorem"));
}
@Test
void bibTexDoesNotAcceptInteger() {
assertNotEquals(Optional.empty(), checker.checkValue("10"));
}
@Test
void bibLaTexAcceptsThreeLetterAbbreviationsWithHashMarks() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("#jan#"));
}
@Test
void bibLaTexDoesNotAcceptThreeLetterAbbreviationsWithNoHashMarks() {
assertNotEquals(Optional.empty(), checkerBiblatex.checkValue("jan"));
}
@Test
void bibLaTexDoesNotAcceptFullInput() {
assertNotEquals(Optional.empty(), checkerBiblatex.checkValue("January"));
}
@Test
void bibLaTexDoesNotAcceptRandomString() {
assertNotEquals(Optional.empty(), checkerBiblatex.checkValue("Lorem"));
}
@Test
void bibLaTexAcceptsInteger() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("10"));
}
}
| 2,507 | 28.857143 | 81 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/NoBibTexFieldCheckerTest.java | package org.jabref.logic.integrity;
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.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
class NoBibTexFieldCheckerTest {
private final NoBibtexFieldChecker checker = new NoBibtexFieldChecker();
private static Stream<Field> nonBiblatexOnlyFields() {
return Stream.of(
// arbitrary field
new UnknownField("fieldNameNotDefinedInThebiblatexManual"),
StandardField.ABSTRACT,
StandardField.COMMENT,
StandardField.DOI,
StandardField.URL,
// these fields are not recognized as biblatex only fields
StandardField.ADDRESS,
StandardField.INSTITUTION,
StandardField.JOURNAL,
StandardField.KEYWORDS,
StandardField.REVIEW
);
}
@ParameterizedTest()
@MethodSource("nonBiblatexOnlyFields")
void nonBiblatexOnlyField(Field field) {
BibEntry entry = new BibEntry().withField(field, "test");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@ParameterizedTest(name = "field={0}")
@CsvSource({
"AFTERWORD",
"JOURNALTITLE",
"LOCATION"
})
void biblatexOnlyField(StandardField field) {
BibEntry entry = new BibEntry().withField(field, "test");
IntegrityMessage message = new IntegrityMessage("biblatex field only", entry, field);
List<IntegrityMessage> messages = checker.check(entry);
assertEquals(Collections.singletonList(message), messages);
}
}
| 2,026 | 32.783333 | 93 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/NoteCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
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.assertNotEquals;
public class NoteCheckerTest {
private NoteChecker checker;
private NoteChecker checkerBiblatex;
@BeforeEach
void setUp() {
BibDatabaseContext database = new BibDatabaseContext();
BibDatabaseContext databaseBiblatex = new BibDatabaseContext();
database.setMode(BibDatabaseMode.BIBTEX);
checker = new NoteChecker(database);
databaseBiblatex.setMode(BibDatabaseMode.BIBLATEX);
checkerBiblatex = new NoteChecker(databaseBiblatex);
}
@Test
void bibTexAcceptsNoteWithFirstCapitalLetter() {
assertEquals(Optional.empty(), checker.checkValue("Lorem ipsum"));
}
@Test
void bibTexAcceptsNoteWithFirstCapitalLetterAndDoesNotCareAboutTheRest() {
assertEquals(Optional.empty(), checker.checkValue("Lorem ipsum? 10"));
}
@Test
void bibTexDoesNotAcceptFirstLowercaseLetter() {
assertNotEquals(Optional.empty(), checker.checkValue("lorem ipsum"));
}
@Test
void bibLaTexAcceptsNoteWithFirstCapitalLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("Lorem ipsum"));
}
@Test
void bibTexAcceptsUrl() {
assertEquals(Optional.empty(), checker.checkValue("\\url{someurl}"));
}
@Test
void bibLaTexAcceptsFirstLowercaseLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("lorem ipsum"));
}
}
| 1,771 | 29.033898 | 82 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/PagesCheckerBiblatexTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import java.util.stream.Stream;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.junit.jupiter.api.BeforeEach;
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.assertNotEquals;
public class PagesCheckerBiblatexTest {
private PagesChecker checker;
@BeforeEach
void setUp() {
BibDatabaseContext database = new BibDatabaseContext();
database.setMode(BibDatabaseMode.BIBLATEX);
checker = new PagesChecker(database);
}
public static Stream<String> bibtexAccepts() {
return Stream.of("",
// single dash
"1-2",
// double dash
"1--2",
// one page number
"12",
// Multiple numbers
"1,2,3",
// bibTexAcceptsNoSimpleRangeOfNumbers
"43+",
// bibTexAcceptsMorePageNumbersWithRangeOfNumbers
"7+,41--43,73"
);
}
@ParameterizedTest
@MethodSource
void bibtexAccepts(String source) {
assertEquals(Optional.empty(), checker.checkValue(source));
}
public static Stream<String> bibtexRejects() {
return Stream.of(
// hex numbers forbidden
"777e23",
// bibTexDoesNotAcceptMorePageNumbersWithoutComma
"1 2",
// bibTexDoesNotAcceptBrackets
"{1}-{2}"
);
}
@ParameterizedTest
@MethodSource
void bibtexRejects(String source) {
assertNotEquals(Optional.empty(), checker.checkValue(source));
}
}
| 1,911 | 27.537313 | 70 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/PagesCheckerBibtexTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import java.util.stream.Stream;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.junit.jupiter.api.BeforeEach;
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.assertNotEquals;
public class PagesCheckerBibtexTest {
private PagesChecker checker;
@BeforeEach
void setUp() {
BibDatabaseContext database = new BibDatabaseContext();
database.setMode(BibDatabaseMode.BIBTEX);
checker = new PagesChecker(database);
}
public static Stream<String> bibtexAccepts() {
return Stream.of("",
// double dash
"1--2",
// one page number
"12",
// Multiple numbers
"1,2,3",
// bibTexAcceptsNoSimpleRangeOfNumbers
"43+",
// bibTexAcceptsMorePageNumbersWithRangeOfNumbers
"7+,41--43,73"
);
}
@ParameterizedTest
@MethodSource
void bibtexAccepts(String source) {
assertEquals(Optional.empty(), checker.checkValue(source));
}
public static Stream<String> bibtexRejects() {
return Stream.of(
// hex numbers forbidden
"777e23",
// bibTexDoesNotAcceptRangeOfNumbersWithSingleDash
"1-2",
// bibTexDoesNotAcceptMorePageNumbersWithoutComma
"1 2",
// bibTexDoesNotAcceptBrackets
"{1}-{2}"
);
}
@ParameterizedTest
@MethodSource
void bibtexRejects(String source) {
assertNotEquals(Optional.empty(), checker.checkValue(source));
}
}
| 1,943 | 28.014925 | 70 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/PersonNamesCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import java.util.stream.Stream;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
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.assertNotEquals;
public class PersonNamesCheckerTest {
private PersonNamesChecker checker;
private PersonNamesChecker checkerb;
@BeforeEach
public void setUp() throws Exception {
BibDatabaseContext databaseContext = new BibDatabaseContext();
databaseContext.setMode(BibDatabaseMode.BIBTEX);
checker = new PersonNamesChecker(databaseContext);
BibDatabaseContext database = new BibDatabaseContext();
database.setMode(BibDatabaseMode.BIBLATEX);
checkerb = new PersonNamesChecker(database);
}
@ParameterizedTest
@MethodSource("provideValidNames")
public void validNames(String name) {
assertEquals(Optional.empty(), checker.checkValue(name));
}
private static Stream<String> provideValidNames() {
return Stream.of(
"Kolb, Stefan", // single [Name, Firstname]
"Kolb, Stefan and Harrer, Simon", // multiple [Name, Firstname]
"Stefan Kolb", // single [Firstname Name]
"Stefan Kolb and Simon Harrer", // multiple [Firstname Name]
"M. J. Gotay", // second name in front
"{JabRef}", // corporate name in brackets
"{JabRef} and Stefan Kolb", // mixed corporate name with name
"{JabRef} and Kolb, Stefan",
"hugo Para{\\~n}os" // tilde in name
);
}
@Test
public void complainAboutPersonStringWithTwoManyCommas() {
assertEquals(Optional.of("Names are not in the standard BibTeX format."),
checker.checkValue("Test1, Test2, Test3, Test4, Test5, Test6"));
}
@ParameterizedTest
@MethodSource("provideCorrectFormats")
public void authorNameInCorrectFormatsShouldNotComplain(String input) {
assertEquals(Optional.empty(), checkerb.checkValue(input));
}
@ParameterizedTest
@MethodSource("provideIncorrectFormats")
public void authorNameInIncorrectFormatsShouldComplain(String input) {
assertNotEquals(Optional.empty(), checkerb.checkValue(input));
}
private static Stream<String> provideCorrectFormats() {
return Stream.of(
"",
"Knuth",
"Donald E. Knuth and Kurt Cobain and A. Einstein");
}
private static Stream<String> provideIncorrectFormats() {
return Stream.of(
" Knuth, Donald E. ",
"Knuth, Donald E. and Kurt Cobain and A. Einstein",
", and Kurt Cobain and A. Einstein",
"Donald E. Knuth and Kurt Cobain and ,",
"and Kurt Cobain and A. Einstein",
"Donald E. Knuth and Kurt Cobain and");
}
}
| 3,321 | 35.911111 | 85 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/TitleCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
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.assertNotEquals;
public class TitleCheckerTest {
private TitleChecker checker;
private TitleChecker checkerBiblatex;
@BeforeEach
public void setUp() {
BibDatabaseContext databaseContext = new BibDatabaseContext();
BibDatabaseContext databaseBiblatex = new BibDatabaseContext();
databaseContext.setMode(BibDatabaseMode.BIBTEX);
checker = new TitleChecker(databaseContext);
databaseBiblatex.setMode(BibDatabaseMode.BIBLATEX);
checkerBiblatex = new TitleChecker(databaseBiblatex);
}
@Test
public void firstLetterAsOnlyCapitalLetterInSubTitle2() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1: This is a sub title 2"));
}
@Test
public void noCapitalLetterInSubTitle2() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1: this is a sub title 2"));
}
@Test
public void twoCapitalLettersInSubTitle2() {
assertNotEquals(Optional.empty(), checker.checkValue("This is a sub title 1: This is A sub title 2"));
}
@Test
public void middleLetterAsOnlyCapitalLetterInSubTitle2() {
assertNotEquals(Optional.empty(), checker.checkValue("This is a sub title 1: this is A sub title 2"));
}
@Test
public void twoCapitalLettersInSubTitle2WithCurlyBrackets() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1: This is {A} sub title 2"));
}
@Test
public void middleLetterAsOnlyCapitalLetterInSubTitle2WithCurlyBrackets() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1: this is {A} sub title 2"));
}
@Test
public void firstLetterAsOnlyCapitalLetterInSubTitle2AfterContinuousDelimiters() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1...This is a sub title 2"));
}
@Test
public void middleLetterAsOnlyCapitalLetterInSubTitle2AfterContinuousDelimiters() {
assertNotEquals(Optional.empty(), checker.checkValue("This is a sub title 1... this is a sub Title 2"));
}
@Test
public void firstLetterAsOnlyCapitalLetterInEverySubTitleWithContinuousDelimiters() {
assertEquals(Optional.empty(), checker.checkValue("This is; A sub title 1.... This is a sub title 2"));
}
@Test
public void firstLetterAsOnlyCapitalLetterInEverySubTitleWithRandomDelimiters() {
assertEquals(Optional.empty(), checker.checkValue("This!is!!A!Title??"));
}
@Test
public void moreThanOneCapitalLetterInSubTitleWithoutCurlyBrackets() {
assertNotEquals(Optional.empty(), checker.checkValue("This!is!!A!TitlE??"));
}
@Test
void bibTexAcceptsTitleWithOnlyFirstCapitalLetter() {
assertEquals(Optional.empty(), checker.checkValue("This is a title"));
}
@Test
void bibTexDoesNotAcceptCapitalLettersInsideTitle() {
assertNotEquals(Optional.empty(), checker.checkValue("This is a Title"));
}
@Test
void bibTexRemovesCapitalLetterInsideTitle() {
assertEquals(Optional.empty(), checker.checkValue("This is a {T}itle"));
}
@Test
void bibTexRemovesEverythingInBracketsAndAcceptsNoTitleInput() {
assertEquals(Optional.empty(), checker.checkValue("{This is a Title}"));
}
@Test
void bibTexRemovesEverythingInBrackets() {
assertEquals(Optional.empty(), checker.checkValue("This is a {Title}"));
}
@Test
void bibTexAcceptsTitleWithLowercaseFirstLetter() {
assertEquals(Optional.empty(), checker.checkValue("{C}urrent {C}hronicle"));
}
@Test
void bibTexAcceptsSubTitlesWithOnlyFirstCapitalLetter() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1: This is a sub title 2"));
}
@Test
void bibTexAcceptsSubTitleWithLowercaseFirstLetter() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1: this is a sub title 2"));
}
@Test
void bibTexDoesNotAcceptCapitalLettersInsideSubTitle() {
assertNotEquals(Optional.empty(), checker.checkValue("This is a sub title 1: This is A sub title 2"));
}
@Test
void bibTexRemovesCapitalLetterInsideSubTitle() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1: this is {A} sub title 2"));
}
@Test
void bibTexSplitsSubTitlesBasedOnDots() {
assertEquals(Optional.empty(), checker.checkValue("This is a sub title 1...This is a sub title 2"));
}
@Test
void bibTexSplitsSubTitleBasedOnSpecialCharacters() {
assertEquals(Optional.empty(), checker.checkValue("This is; A sub title 1.... This is a sub title 2"));
}
@Test
void bibTexAcceptsCapitalLetterAfterSpecialCharacter() {
assertEquals(Optional.empty(), checker.checkValue("This!is!!A!Title??"));
}
@Test
void bibTexAcceptsCapitalLetterOnlyAfterSpecialCharacter() {
assertNotEquals(Optional.empty(), checker.checkValue("This!is!!A!TitlE??"));
}
@Test
void bibLaTexAcceptsTitleWithOnlyFirstCapitalLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a title"));
}
@Test
void bibLaTexAcceptsCapitalLettersInsideTitle() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a Title"));
}
@Test
void bibLaTexRemovesCapitalLetterInsideTitle() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a {T}itle"));
}
@Test
void bibLaTexRemovesEverythingInBracketsAndAcceptsNoTitleInput() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("{This is a Title}"));
}
@Test
void bibLaTexRemovesEverythingInBrackets() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a {Title}"));
}
@Test
void bibLaTexAcceptsTitleWithLowercaseFirstLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("{C}urrent {C}hronicle"));
}
@Test
void bibLaTexAcceptsSubTitlesWithOnlyFirstCapitalLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a sub title 1: This is a sub title 2"));
}
@Test
void bibLaTexAcceptsSubTitleWithLowercaseFirstLetter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a sub title 1: this is a sub title 2"));
}
@Test
void bibLaTexAcceptsCapitalLettersInsideSubTitle() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a sub title 1: This is A sub title 2"));
}
@Test
void bibLaTexRemovesCapitalLetterInsideSubTitle() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a sub title 1: this is {A} sub title 2"));
}
@Test
void bibLaTexSplitsSubTitlesBasedOnDots() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is a sub title 1...This is a sub title 2"));
}
@Test
void bibLaTexSplitsSubTitleBasedOnSpecialCharacters() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This is; A sub title 1.... This is a sub title 2"));
}
@Test
void bibLaTexAcceptsCapitalLetterAfterSpecialCharacter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This!is!!A!Title??"));
}
@Test
void bibLaTexAcceptsCapitalLetterNotOnlyAfterSpecialCharacter() {
assertEquals(Optional.empty(), checkerBiblatex.checkValue("This!is!!A!TitlE??"));
}
}
| 7,882 | 34.191964 | 119 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/TypeCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Collections;
import java.util.List;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TypeCheckerTest {
private final TypeChecker checker = new TypeChecker();
private BibEntry entry;
@Test
void inProceedingsHasPagesNumbers() {
entry = new BibEntry(StandardEntryType.InProceedings);
entry.setField(StandardField.PAGES, "11--15");
assertEquals(Collections.emptyList(), checker.check(entry));
}
@Test
void proceedingsDoesNotHavePageNumbers() {
entry = new BibEntry(StandardEntryType.Proceedings);
entry.setField(StandardField.PAGES, "11--15");
assertEquals(List.of(new IntegrityMessage("wrong entry type as proceedings has page numbers", entry, StandardField.PAGES)), checker.check(entry));
}
}
| 1,038 | 30.484848 | 154 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/UTF8CheckerTest.java | package org.jabref.logic.integrity;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class UTF8CheckerTest {
private static final Charset GBK = Charset.forName("GBK");
private final BibEntry entry = new BibEntry();
/**
* fieldAcceptsUTF8 to check UTF8Checker's result set
* when the entry is encoded in UTF-8 (should be empty)
*/
@Test
void fieldAcceptsUTF8() {
UTF8Checker checker = new UTF8Checker(StandardCharsets.UTF_8);
entry.setField(StandardField.TITLE, "Only ascii characters!'@12");
assertEquals(Collections.emptyList(), checker.check(entry));
}
/**
* fieldDoesNotAcceptUmlauts to check UTF8Checker's result set
* when the entry is encoded in Non-Utf-8 charset and the Library
* environment is Non UTF-8.
* Finally, we need to reset the environment charset.
*
* @throws UnsupportedEncodingException initial a String in charset GBK
* Demo: new String(StringDemo.getBytes(), "GBK");
*/
@Test
void fieldDoesNotAcceptUmlauts() throws UnsupportedEncodingException {
UTF8Checker checker = new UTF8Checker(Charset.forName("GBK"));
String NonUTF8 = new String("你好,这条语句使用GBK字符集".getBytes(StandardCharsets.UTF_8), GBK);
entry.setField(StandardField.MONTH, NonUTF8);
assertEquals(List.of(new IntegrityMessage("Non-UTF-8 encoded field found", entry, StandardField.MONTH)), checker.check(entry));
}
/**
* To check the UTF8Checker.UTF8EncodingChecker
* in NonUTF8 char array (should return false)
*
* @throws UnsupportedEncodingException initial a String in charset GBK
* Demo: new String(StringDemo.getBytes(), "GBK");
*/
@Test
void NonUTF8EncodingCheckerTest() throws UnsupportedEncodingException {
String NonUTF8 = new String("你好,这条语句使用GBK字符集".getBytes(StandardCharsets.UTF_8), GBK);
assertFalse(UTF8Checker.UTF8EncodingChecker(NonUTF8.getBytes(GBK)));
}
/**
* To check the UTF8Checker.UTF8EncodingChecker
* in UTF-8 char array (should return true)
*/
@Test
void UTF8EncodingCheckerTest() {
String UTF8Demo = new String("你好,这条语句使用GBK字符集".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
assertTrue(UTF8Checker.UTF8EncodingChecker(UTF8Demo.getBytes(StandardCharsets.UTF_8)));
}
}
| 2,802 | 36.878378 | 135 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/UrlCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class UrlCheckerTest {
private final UrlChecker checker = new UrlChecker();
@Test
void urlFieldAcceptsHttpAddress() {
assertEquals(Optional.empty(), checker.checkValue("http://www.google.com"));
}
@Test
void urlFieldAcceptsFullLocalPath() {
assertEquals(Optional.empty(), checker.checkValue("file://c:/asdf/asdf"));
}
@Test
void urlFieldAcceptsFullPathHttpAddress() {
assertEquals(Optional.empty(), checker.checkValue("http://scikit-learn.org/stable/modules/ensemble.html#random-forests"));
}
@Test
void urlFieldDoesNotAcceptHttpAddressWithoutTheHttp() {
assertNotEquals(Optional.empty(), checker.checkValue("www.google.com"));
}
@Test
void urlFieldDoesNotAcceptPartialHttpAddress() {
assertNotEquals(Optional.empty(), checker.checkValue("google.com"));
}
@Test
void urlFieldDoesNotAcceptPartialLocalPath() {
assertNotEquals(Optional.empty(), checker.checkValue("c:/asdf/asdf"));
}
}
| 1,249 | 27.409091 | 130 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/ValidCitationKeyCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import java.util.stream.Stream;
import org.jabref.logic.l10n.Localization;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ValidCitationKeyCheckerTest {
private final ValidCitationKeyChecker checker = new ValidCitationKeyChecker();
@ParameterizedTest
@MethodSource("provideCitationKeys")
void citationKeyValidity(Optional optionalArgument, String citationKey) {
assertEquals(optionalArgument, checker.checkValue(citationKey));
}
private static Stream<Arguments> provideCitationKeys() {
return Stream.of(
Arguments.of(Optional.of(Localization.lang("empty citation key")), ""),
Arguments.of(Optional.empty(), "Seaver2019"),
Arguments.of(Optional.of(Localization.lang("Invalid citation key")), "Seaver_2019}")
);
}
}
| 1,069 | 32.4375 | 100 | java |
null | jabref-main/src/test/java/org/jabref/logic/integrity/YearCheckerTest.java | package org.jabref.logic.integrity;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class YearCheckerTest {
private final YearChecker checker = new YearChecker();
@Test
void yearFieldAccepts21stCenturyDate() {
assertEquals(Optional.empty(), checker.checkValue("2014"));
}
@Test
void yearFieldAccepts20thCenturyDate() {
assertEquals(Optional.empty(), checker.checkValue("1986"));
}
@Test
void yearFieldAcceptsApproximateDate() {
assertEquals(Optional.empty(), checker.checkValue("around 1986"));
}
@Test
void yearFieldAcceptsApproximateDateWithParenthesis() {
assertEquals(Optional.empty(), checker.checkValue("(around 1986)"));
}
@Test
void yearFieldRemovesCommaFromYear() {
assertEquals(Optional.empty(), checker.checkValue("1986,"));
}
@Test
void yearFieldRemovesBraceAndPercentageFromYear() {
assertEquals(Optional.empty(), checker.checkValue("1986}%"));
}
@Test
void yearFieldRemovesSpecialCharactersFromYear() {
assertEquals(Optional.empty(), checker.checkValue("1986(){},.;!?<>%&$"));
}
@Test
void yearFieldDoesNotAcceptStringAsInput() {
assertNotEquals(Optional.empty(), checker.checkValue("abc"));
}
@Test
void yearFieldDoesNotAcceptDoubleDigitNumber() {
assertNotEquals(Optional.empty(), checker.checkValue("86"));
}
@Test
void yearFieldDoesNotAcceptTripleDigitNumber() {
assertNotEquals(Optional.empty(), checker.checkValue("204"));
}
@Test
void yearFieldDoesNotRemoveStringInYear() {
assertNotEquals(Optional.empty(), checker.checkValue("1986a"));
}
@Test
void yearFieldDoesNotRemoveStringInParenthesis() {
assertNotEquals(Optional.empty(), checker.checkValue("(1986a)"));
}
@Test
void yearFieldDoesNotRemoveStringBeforeComma() {
assertNotEquals(Optional.empty(), checker.checkValue("1986a,"));
}
@Test
void yearFieldDoesNotRemoveStringInsideBraceAndPercentage() {
assertNotEquals(Optional.empty(), checker.checkValue("1986}a%"));
}
@Test
void yearFieldDoesNotRemoveStringBeforeSpecialCharacters() {
assertNotEquals(Optional.empty(), checker.checkValue("1986a(){},.;!?<>%&$"));
}
@Test
void testEmptyValue() {
assertEquals(Optional.empty(), checker.checkValue(""));
}
}
| 2,572 | 26.37234 | 85 | java |
null | jabref-main/src/test/java/org/jabref/logic/journals/AbbreviationTest.java | package org.jabref.logic.journals;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class AbbreviationTest {
@Test
void testAbbreviationsWithTrailingSpaces() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.");
assertEquals("Long Name", abbreviation.getName());
assertEquals("L. N.", abbreviation.getAbbreviation());
assertEquals("L N", abbreviation.getDotlessAbbreviation());
assertEquals("L. N.", abbreviation.getShortestUniqueAbbreviation());
}
@Test
void testAbbreviationsWithTrailingSpacesWithShortestUniqueAbbreviation() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.", "LN");
assertEquals("Long Name", abbreviation.getName());
assertEquals("L. N.", abbreviation.getAbbreviation());
assertEquals("L N", abbreviation.getDotlessAbbreviation());
assertEquals("LN", abbreviation.getShortestUniqueAbbreviation());
}
@Test
void testAbbreviationsWithSemicolons() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.;LN;M");
assertEquals("Long Name", abbreviation.getName());
assertEquals("L. N.;LN;M", abbreviation.getAbbreviation());
assertEquals("L N ;LN;M", abbreviation.getDotlessAbbreviation());
assertEquals("L. N.;LN;M", abbreviation.getShortestUniqueAbbreviation());
}
@Test
void testAbbreviationsWithSemicolonsWithShortestUniqueAbbreviation() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.;LN;M", "LNLNM");
assertEquals("Long Name", abbreviation.getName());
assertEquals("L. N.;LN;M", abbreviation.getAbbreviation());
assertEquals("L N ;LN;M", abbreviation.getDotlessAbbreviation());
assertEquals("LNLNM", abbreviation.getShortestUniqueAbbreviation());
}
@Test
void testGetNextElement() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.");
assertEquals("L. N.", abbreviation.getNext("Long Name"));
assertEquals("L N", abbreviation.getNext("L. N."));
assertEquals("Long Name", abbreviation.getNext("L N"));
}
@Test
void testGetNextElementWithShortestUniqueAbbreviation() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.", "LN");
assertEquals("L. N.", abbreviation.getNext("Long Name"));
assertEquals("L N", abbreviation.getNext("L. N."));
assertEquals("LN", abbreviation.getNext("L N"));
assertEquals("Long Name", abbreviation.getNext("LN"));
}
@Test
void testGetNextElementWithTrailingSpaces() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.");
assertEquals("L. N.", abbreviation.getNext("Long Name"));
assertEquals("L N", abbreviation.getNext("L. N."));
assertEquals("Long Name", abbreviation.getNext("L N"));
}
@Test
void testGetNextElementWithTrailingSpacesWithShortestUniqueAbbreviation() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L. N.", "LN");
assertEquals("L. N.", abbreviation.getNext("Long Name"));
assertEquals("L N", abbreviation.getNext("L. N."));
assertEquals("LN", abbreviation.getNext("L N"));
assertEquals("Long Name", abbreviation.getNext("LN"));
}
@Test
void testDefaultAndMedlineAbbreviationsAreSame() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L N");
assertEquals(abbreviation.getAbbreviation(), abbreviation.getDotlessAbbreviation());
}
@Test
void testDefaultAndMedlineAbbreviationsAreSameWithShortestUniqueAbbreviation() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L N", "LN");
assertEquals(abbreviation.getAbbreviation(), abbreviation.getDotlessAbbreviation());
}
@Test
void testDefaultAndShortestUniqueAbbreviationsAreSame() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L N");
assertEquals(abbreviation.getAbbreviation(), abbreviation.getShortestUniqueAbbreviation());
}
@Test
void testEquals() {
Abbreviation abbreviation = new Abbreviation("Long Name", "L N", "LN");
Abbreviation otherAbbreviation = new Abbreviation("Long Name", "L N", "LN");
assertEquals(abbreviation, otherAbbreviation);
assertNotEquals(abbreviation, "String");
}
@Test
void equalAbbrevationsWithFourComponentsAreAlsoCompareZero() {
Abbreviation abbreviation1 = new Abbreviation("Long Name", "L. N.", "LN");
Abbreviation abbreviation2 = new Abbreviation("Long Name", "L. N.", "LN");
assertEquals(0, abbreviation1.compareTo(abbreviation2));
}
}
| 4,834 | 38.958678 | 99 | java |
null | jabref-main/src/test/java/org/jabref/logic/journals/AbbreviationWriterTest.java | package org.jabref.logic.journals;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Execution(ExecutionMode.CONCURRENT)
class AbbreviationWriterTest {
@Test
void shortestUniqueAbbreviationWrittenIfItDiffers(@TempDir Path tempDir) throws Exception {
Abbreviation abbreviation = new Abbreviation("Full", "Abbr", "A");
Path csvFile = tempDir.resolve("test.csv");
AbbreviationWriter.writeOrCreate(
csvFile,
List.of(abbreviation));
assertEquals(List.of("Full;Abbr;A"), Files.readAllLines(csvFile));
}
@Test
void doNotWriteShortestUniqueAbbreviationWrittenIfItDiffers(@TempDir Path tempDir) throws Exception {
Abbreviation abbreviation = new Abbreviation("Full", "Abbr");
Path csvFile = tempDir.resolve("test.csv");
AbbreviationWriter.writeOrCreate(
csvFile,
List.of(abbreviation));
assertEquals(List.of("Full;Abbr"), Files.readAllLines(csvFile));
}
}
| 1,273 | 33.432432 | 105 | java |
null | jabref-main/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java | package org.jabref.logic.journals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AbbreviationsTest {
private JournalAbbreviationRepository repository;
@BeforeEach
void setUp() {
repository = JournalAbbreviationLoader.loadBuiltInRepository();
}
@Test
void getNextAbbreviationAbbreviatesJournalTitle() {
assertEquals("2D Mater.", repository.getNextAbbreviation("2D Materials").get());
}
@Test
void getNextAbbreviationConvertsAbbreviationToDotlessAbbreviation() {
assertEquals("2D Mater", repository.getNextAbbreviation("2D Mater.").get());
}
}
| 710 | 25.333333 | 88 | java |
null | jabref-main/src/test/java/org/jabref/logic/journals/JournalAbbreviationRepositoryTest.java | package org.jabref.logic.journals;
import java.util.Set;
import javax.swing.undo.CompoundEdit;
import org.jabref.architecture.AllowedToUseSwing;
import org.jabref.gui.journals.AbbreviationType;
import org.jabref.gui.journals.UndoableAbbreviator;
import org.jabref.gui.journals.UndoableUnabbreviator;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.AMSField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@AllowedToUseSwing("UndoableUnabbreviator and UndoableAbbreviator requires Swing Compound Edit in order test the abbreviation and unabbreviation of journal titles")
class JournalAbbreviationRepositoryTest {
private JournalAbbreviationRepository repository;
private final BibDatabase bibDatabase = new BibDatabase();
private UndoableUnabbreviator undoableUnabbreviator;
@BeforeEach
void setUp() {
repository = JournalAbbreviationLoader.loadBuiltInRepository();
undoableUnabbreviator = new UndoableUnabbreviator(repository);
}
@Test
void empty() {
assertTrue(repository.getCustomAbbreviations().isEmpty());
}
@Test
void oneElement() {
repository.addCustomAbbreviation(new Abbreviation("Long Name", "L. N."));
assertEquals(1, repository.getCustomAbbreviations().size());
assertEquals("L. N.", repository.getDefaultAbbreviation("Long Name").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getDefaultAbbreviation("?").orElse("UNKNOWN"));
assertEquals("L N", repository.getDotless("Long Name").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getDotless("?").orElse("UNKNOWN"));
assertEquals("L. N.", repository.getShortestUniqueAbbreviation("Long Name").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getShortestUniqueAbbreviation("?").orElse("UNKNOWN"));
assertEquals("L. N.", repository.getNextAbbreviation("Long Name").orElse("WRONG"));
assertEquals("L N", repository.getNextAbbreviation("L. N.").orElse("WRONG"));
assertEquals("Long Name", repository.getNextAbbreviation("L N").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getNextAbbreviation("?").orElse("UNKNOWN"));
assertTrue(repository.isKnownName("Long Name"));
assertTrue(repository.isKnownName("L. N."));
assertTrue(repository.isKnownName("L N"));
assertFalse(repository.isKnownName("?"));
}
@Test
void oneElementWithShortestUniqueAbbreviation() {
repository.addCustomAbbreviation(new Abbreviation("Long Name", "L. N.", "LN"));
assertEquals(1, repository.getCustomAbbreviations().size());
assertEquals("L. N.", repository.getDefaultAbbreviation("Long Name").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getDefaultAbbreviation("?").orElse("UNKNOWN"));
assertEquals("L N", repository.getDotless("Long Name").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getDotless("?").orElse("UNKNOWN"));
assertEquals("LN", repository.getShortestUniqueAbbreviation("Long Name").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getShortestUniqueAbbreviation("?").orElse("UNKNOWN"));
assertEquals("L. N.", repository.getNextAbbreviation("Long Name").orElse("WRONG"));
assertEquals("L N", repository.getNextAbbreviation("L. N.").orElse("WRONG"));
assertEquals("LN", repository.getNextAbbreviation("L N").orElse("WRONG"));
assertEquals("Long Name", repository.getNextAbbreviation("LN").orElse("WRONG"));
assertEquals("UNKNOWN", repository.getNextAbbreviation("?").orElse("UNKNOWN"));
assertTrue(repository.isKnownName("Long Name"));
assertTrue(repository.isKnownName("L. N."));
assertTrue(repository.isKnownName("L N"));
assertTrue(repository.isKnownName("LN"));
assertFalse(repository.isKnownName("?"));
}
@Test
void testDuplicates() {
repository.addCustomAbbreviation(new Abbreviation("Long Name", "L. N."));
repository.addCustomAbbreviation(new Abbreviation("Long Name", "L. N."));
assertEquals(1, repository.getCustomAbbreviations().size());
}
@Test
void testDuplicatesWithShortestUniqueAbbreviation() {
repository.addCustomAbbreviation(new Abbreviation("Long Name", "L. N.", "LN"));
repository.addCustomAbbreviation(new Abbreviation("Long Name", "L. N.", "LN"));
assertEquals(1, repository.getCustomAbbreviations().size());
}
@Test
void testDuplicatesIsoOnly() {
repository.addCustomAbbreviation(new Abbreviation("Old Long Name", "L. N."));
repository.addCustomAbbreviation(new Abbreviation("New Long Name", "L. N."));
assertEquals(2, repository.getCustomAbbreviations().size());
}
@Test
void testDuplicatesIsoOnlyWithShortestUniqueAbbreviation() {
repository.addCustomAbbreviation(new Abbreviation("Old Long Name", "L. N.", "LN"));
repository.addCustomAbbreviation(new Abbreviation("New Long Name", "L. N.", "LN"));
assertEquals(2, repository.getCustomAbbreviations().size());
}
@Test
void testDuplicateKeys() {
Abbreviation abbreviationOne = new Abbreviation("Long Name", "L. N.");
repository.addCustomAbbreviation(abbreviationOne);
assertEquals(Set.of(abbreviationOne), repository.getCustomAbbreviations());
assertEquals("L. N.", repository.getDefaultAbbreviation("Long Name").orElse("WRONG"));
Abbreviation abbreviationTwo = new Abbreviation("Long Name", "LA. N.");
repository.addCustomAbbreviation(abbreviationTwo);
assertEquals(Set.of(abbreviationOne, abbreviationTwo), repository.getCustomAbbreviations());
// Both abbreviations are kept in the repository
// "L. N." is smaller than "LA. N.", therefore "L. N." is returned
assertEquals("L. N.", repository.getDefaultAbbreviation("Long Name").orElse("WRONG"));
}
@Test
void testDuplicateKeysWithShortestUniqueAbbreviation() {
Abbreviation abbreviationOne = new Abbreviation("Long Name", "L. N.", "LN");
repository.addCustomAbbreviation(abbreviationOne);
assertEquals(Set.of(abbreviationOne), repository.getCustomAbbreviations());
assertEquals("L. N.", repository.getDefaultAbbreviation("Long Name").orElse("WRONG"));
assertEquals("LN", repository.getShortestUniqueAbbreviation("Long Name").orElse("WRONG"));
Abbreviation abbreviationTwo = new Abbreviation("Long Name", "LA. N.", "LAN");
repository.addCustomAbbreviation(abbreviationTwo);
assertEquals(Set.of(abbreviationOne, abbreviationTwo), repository.getCustomAbbreviations());
// Both abbreviations are kept in the repository
// "L. N." is smaller than "LA. N.", therefore "L. N." is returned
assertEquals("L. N.", repository.getDefaultAbbreviation("Long Name").orElse("WRONG"));
assertEquals("LN", repository.getShortestUniqueAbbreviation("Long Name").orElse("WRONG"));
}
@Test
void getFromFullName() {
assertEquals(new Abbreviation("American Journal of Public Health", "Am. J. Public Health"), repository.get("American Journal of Public Health").get());
}
@Test
void getFromAbbreviatedName() {
assertEquals(new Abbreviation("American Journal of Public Health", "Am. J. Public Health"), repository.get("Am. J. Public Health").get());
}
@Test
void testAbbreviationsWithEscapedAmpersand() {
assertEquals(new Abbreviation("ACS Applied Materials & Interfaces", "ACS Appl. Mater. Interfaces"), repository.get("ACS Applied Materials & Interfaces").get());
assertEquals(new Abbreviation("ACS Applied Materials & Interfaces", "ACS Appl. Mater. Interfaces"), repository.get("ACS Applied Materials \\& Interfaces").get());
assertEquals(new Abbreviation("Antioxidants & Redox Signaling", "Antioxid. Redox Signaling"), repository.get("Antioxidants & Redox Signaling").get());
assertEquals(new Abbreviation("Antioxidants & Redox Signaling", "Antioxid. Redox Signaling"), repository.get("Antioxidants \\& Redox Signaling").get());
repository.addCustomAbbreviation(new Abbreviation("Long & Name", "L. N.", "LN"));
assertEquals(new Abbreviation("Long & Name", "L. N.", "LN"), repository.get("Long & Name").get());
assertEquals(new Abbreviation("Long & Name", "L. N.", "LN"), repository.get("Long \\& Name").get());
}
@Test
void testJournalAbbreviationWithEscapedAmpersand() {
UndoableAbbreviator undoableAbbreviator = new UndoableAbbreviator(repository, AbbreviationType.DEFAULT, false);
BibEntry entryWithEscapedAmpersandInJournal = new BibEntry(StandardEntryType.Article);
entryWithEscapedAmpersandInJournal.setField(StandardField.JOURNAL, "ACS Applied Materials \\& Interfaces");
undoableAbbreviator.abbreviate(bibDatabase, entryWithEscapedAmpersandInJournal, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, entryWithEscapedAmpersandInJournal);
}
@Test
void testJournalUnabbreviate() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article);
abbreviatedJournalEntry.setField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
@Test
void testJournalAbbreviateWithoutEscapedAmpersand() {
UndoableAbbreviator undoableAbbreviator = new UndoableAbbreviator(repository, AbbreviationType.DEFAULT, false);
BibEntry entryWithoutEscapedAmpersandInJournal = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces");
undoableAbbreviator.abbreviate(bibDatabase, entryWithoutEscapedAmpersandInJournal, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, entryWithoutEscapedAmpersandInJournal);
}
@Test
void testJournalAbbreviateWithEmptyFJournal() {
UndoableAbbreviator undoableAbbreviator = new UndoableAbbreviator(repository, AbbreviationType.DEFAULT, true);
BibEntry entryWithoutEscapedAmpersandInJournal = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces")
.withField(AMSField.FJOURNAL, " ");
undoableAbbreviator.abbreviate(bibDatabase, entryWithoutEscapedAmpersandInJournal, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces")
.withField(AMSField.FJOURNAL, "ACS Applied Materials & Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, entryWithoutEscapedAmpersandInJournal);
}
@Test
void testUnabbreviateWithJournalExistsAndFJournalNot() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
@Test
void testUnabbreviateWithJournalExistsAndFJournalExists() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Appl. Mater. Interfaces")
.withField(AMSField.FJOURNAL, "ACS Applied Materials & Interfaces");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
@Test
void testJournalDotlessAbbreviation() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Appl Mater Interfaces");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
@Test
void testJournalDotlessAbbreviationWithCurlyBraces() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "{ACS Appl Mater Interfaces}");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "ACS Applied Materials & Interfaces");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
/**
* Tests <a href="https://github.com/JabRef/jabref/issues/9475">Issue 9475</a>
*/
@Test
void testTitleEmbeddedWithCurlyBracesHavingNoChangesKeepsBraces() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.InCollection)
.withField(StandardField.JOURNAL, "{The Visualization Handbook}");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.InCollection)
.withField(StandardField.JOURNAL, "{The Visualization Handbook}");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
/**
* Tests <a href="https://github.com/JabRef/jabref/issues/9503">Issue 9503</a>
*/
@Test
void testTitleWithNestedCurlyBracesHavingNoChangesKeepsBraces() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.InProceedings)
.withField(StandardField.BOOKTITLE, "2015 {IEEE} International Conference on Digital Signal Processing, {DSP} 2015, Singapore, July 21-24, 2015");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.InProceedings)
.withField(StandardField.BOOKTITLE, "2015 {IEEE} International Conference on Digital Signal Processing, {DSP} 2015, Singapore, July 21-24, 2015");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
@Test
void testDotlessForPhysRevB() {
BibEntry abbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "Phys Rev B");
undoableUnabbreviator.unabbreviate(bibDatabase, abbreviatedJournalEntry, StandardField.JOURNAL, new CompoundEdit());
BibEntry expectedAbbreviatedJournalEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.JOURNAL, "Physical Review B");
assertEquals(expectedAbbreviatedJournalEntry, abbreviatedJournalEntry);
}
}
| 16,739 | 51.641509 | 170 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/EncodingsTest.java | package org.jabref.logic.l10n;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class EncodingsTest {
@Test
public void charsetsShouldNotBeNull() {
assertNotNull(Encodings.ENCODINGS);
}
@Test
public void displayNamesShouldNotBeNull() {
assertNotNull(Encodings.ENCODINGS_DISPLAYNAMES);
}
@Test
public void charsetsShouldNotBeEmpty() {
assertNotEquals(0, Encodings.ENCODINGS.length);
}
@Test
public void displayNamesShouldNotBeEmpty() {
assertNotEquals(0, Encodings.ENCODINGS_DISPLAYNAMES.length);
}
}
| 705 | 23.344828 | 68 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/JavaLocalizationEntryParser.java | package org.jabref.logic.l10n;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class JavaLocalizationEntryParser {
private static final String INFINITE_WHITESPACE = "\\s*";
private static final String DOT = "\\.";
private static final Pattern LOCALIZATION_START_PATTERN = Pattern.compile("Localization" + INFINITE_WHITESPACE + DOT + INFINITE_WHITESPACE + "lang" + INFINITE_WHITESPACE + "\\(");
private static final Pattern LOCALIZATION_MENU_START_PATTERN = Pattern.compile("Localization" + INFINITE_WHITESPACE + DOT + INFINITE_WHITESPACE + "menuTitle" + INFINITE_WHITESPACE + "\\(");
private static final Pattern ESCAPED_QUOTATION_SYMBOL = Pattern.compile("\\\\\"");
private static final String QUOTATION_PLACEHOLDER = "QUOTATIONPLACEHOLDER";
private static final Pattern QUOTATION_SYMBOL_PATTERN = Pattern.compile(QUOTATION_PLACEHOLDER);
public static List<String> getLanguageKeysInString(String content, LocalizationBundleForTest type) {
List<String> parameters = getLocalizationParameter(content, type);
List<String> result = new ArrayList<>();
for (String param : parameters) {
String languageKey = getContentWithinQuotes(param);
if (languageKey.contains("\\\n") || languageKey.contains("\\\\n")) {
// see also https://stackoverflow.com/a/10285687/873282
// '\n' (newline character) in the language key is stored as text "\n" in the .properties file. This is OK.
throw new RuntimeException("\"" + languageKey + "\" contains an escaped new line character. The newline character has to be written with a single backslash, not with a double one: \\n is correct, \\\\n is wrong.");
}
// Java escape chars which are not used in property file keys
// The call to `getPropertiesKey` escapes them
String languagePropertyKey = LocalizationKey.fromEscapedJavaString(languageKey).getKey();
if (languagePropertyKey.endsWith(" ")) {
throw new RuntimeException("\"" + languageKey + "\" ends with a space. As this is a localization key, this is illegal!");
}
if (!languagePropertyKey.trim().isEmpty()) {
result.add(languagePropertyKey);
}
}
return result;
}
private static String getContentWithinQuotes(String param) {
// protect \" in string
String contentWithProtectedEscapedQuote = ESCAPED_QUOTATION_SYMBOL.matcher(param).replaceAll(QUOTATION_PLACEHOLDER);
// extract text between "..."
StringBuilder stringBuilder = new StringBuilder();
int quotations = 0;
for (char currentCharacter : contentWithProtectedEscapedQuote.toCharArray()) {
if ((currentCharacter == '"') && (quotations > 0)) {
quotations--;
} else if (currentCharacter == '"') {
quotations++;
} else if (quotations != 0) {
stringBuilder.append(currentCharacter);
} else if (currentCharacter == ',') {
break;
}
}
// re-introduce \" (escaped quotes) into string
String languageKey = QUOTATION_SYMBOL_PATTERN.matcher(stringBuilder.toString()).replaceAll("\\\"");
return languageKey;
}
public static List<String> getLocalizationParameter(String content, LocalizationBundleForTest type) {
List<String> result = new ArrayList<>();
Matcher matcher;
if (type == LocalizationBundleForTest.LANG) {
matcher = LOCALIZATION_START_PATTERN.matcher(content);
} else {
matcher = LOCALIZATION_MENU_START_PATTERN.matcher(content);
}
while (matcher.find()) {
// find contents between the brackets, covering multi-line strings as well
int index = matcher.end();
int brackets = 1;
StringBuilder buffer = new StringBuilder();
while (brackets != 0) {
char c = content.charAt(index);
if (c == '(') {
brackets++;
} else if (c == ')') {
brackets--;
}
// skip closing brackets
if (brackets != 0) {
buffer.append(c);
}
index++;
}
// trim newlines and whitespace
result.add(buffer.toString().trim());
}
return result;
}
}
| 4,601 | 41.611111 | 230 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/JavaLocalizationEntryParserTest.java | package org.jabref.logic.l10n;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class JavaLocalizationEntryParserTest {
public static Stream<Arguments> singleLineChecks() {
return Stream.of(
Arguments.of("Localization.lang(\"one per line\")", "one per line"),
// '\c' is an escaped character, thus "\cite" is wrong as lookup text. It has to be "\\cite" in the .properties file
Arguments.of("Localization.lang(\"Copy \\\\cite{citation key}\")", "Copy \\\\cite{citation key}"),
// " is kept unescaped
Arguments.of("Localization.lang(\"\\\"Hey\\\"\")", "\"Hey\""),
// \n is a "real" newline character in the simulated read read Java source code
Arguments.of("Localization.lang(\"multi \" + \n\"line\")", "multi line"),
Arguments.of("Localization.lang(\n \"A string\")", "A string"),
Arguments.of("Localization.lang(\"one per line with var\", var)", "one per line with var"),
Arguments.of("Localization.lang(\"Search %0\", \"Springer\")", "Search %0"),
Arguments.of("Localization.lang(\"Reset preferences (key1,key2,... or 'all')\")", "Reset preferences (key1,key2,... or 'all')"),
Arguments.of("Localization.lang(\"Multiple entries selected. Do you want to change the type of all these to '%0'?\")",
"Multiple entries selected. Do you want to change the type of all these to '%0'?"),
Arguments.of("Localization.lang(\"Run fetcher, e.g. \\\"--fetch=Medline:cancer\\\"\");",
"Run fetcher, e.g. \"--fetch=Medline:cancer\""),
// \n is allowed. See // see also https://stackoverflow.com/a/10285687/873282
// It appears as "\n" literally in the source code
// It appears as "\n" as key of the localization, too
// To mirror that, we have to write \\n here
Arguments.of("Localization.lang(\"First line\\nSecond line\")", "First line\\nSecond line")
);
}
public static Stream<Arguments> multiLineChecks() {
return Stream.of(
Arguments.of("Localization.lang(\"two per line\") Localization.lang(\"two per line\")", Arrays.asList("two per line", "two per line"))
);
}
public static Stream<Arguments> singleLineParameterChecks() {
return Stream.of(
Arguments.of("Localization.lang(\"one per line\")", "\"one per line\""),
Arguments.of("Localization.lang(\"one per line\" + var)", "\"one per line\" + var"),
Arguments.of("Localization.lang(var + \"one per line\")", "var + \"one per line\""),
Arguments.of("Localization.lang(\"Search %0\", \"Springer\")", "\"Search %0\", \"Springer\"")
);
}
public static Stream<String> causesRuntimeExceptions() {
return Stream.of(
"Localization.lang(\"Ends with a space \")",
// "\\n" in the *.java source file
"Localization.lang(\"Escaped newline\\\\nthere\")"
);
}
@ParameterizedTest
@MethodSource("singleLineChecks")
public void testLocalizationKeyParsing(String code, String expectedLanguageKeys) {
testLocalizationKeyParsing(code, List.of(expectedLanguageKeys));
}
@ParameterizedTest
@MethodSource("multiLineChecks")
public void testLocalizationKeyParsing(String code, List<String> expectedLanguageKeys) {
List<String> languageKeysInString = JavaLocalizationEntryParser.getLanguageKeysInString(code, LocalizationBundleForTest.LANG);
assertEquals(expectedLanguageKeys, languageKeysInString);
}
@ParameterizedTest
@MethodSource("singleLineParameterChecks")
public void testLocalizationParameterParsing(String code, String expectedParameter) {
List<String> languageKeysInString = JavaLocalizationEntryParser.getLocalizationParameter(code, LocalizationBundleForTest.LANG);
assertEquals(List.of(expectedParameter), languageKeysInString);
}
@ParameterizedTest
@MethodSource("causesRuntimeExceptions")
public void throwsRuntimeException(String code) {
assertThrows(RuntimeException.class, () -> JavaLocalizationEntryParser.getLanguageKeysInString(code, LocalizationBundleForTest.LANG));
}
}
| 4,726 | 49.287234 | 150 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LanguageTest.java | package org.jabref.logic.l10n;
import java.util.Locale;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class LanguageTest {
@Test
void convertKnownLanguageOnly() {
assertEquals(Optional.of(Locale.of("en")), Language.convertToSupportedLocale(Language.ENGLISH));
}
@Test
void convertKnownLanguageAndCountryCorrect() {
// Language and country code have to be separated see: https://stackoverflow.com/a/3318598
assertEquals(Optional.of(Locale.of("pt", "BR")), Language.convertToSupportedLocale(Language.BRAZILIAN_PORTUGUESE));
}
@Test
void convertToKnownLocaleNull() {
assertThrows(NullPointerException.class, () -> Language.convertToSupportedLocale(null));
}
}
| 870 | 29.034483 | 123 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LocalizationBundleForTest.java | package org.jabref.logic.l10n;
enum LocalizationBundleForTest {
LANG, MENU
}
| 82 | 12.833333 | 32 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LocalizationConsistencyTest.java | package org.jabref.logic.l10n;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.testfx.framework.junit5.ApplicationExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
// Need to run on JavaFX thread since we are parsing FXML files
@ExtendWith(ApplicationExtension.class)
class LocalizationConsistencyTest {
@Test
void allFilesMustBeInLanguages() throws IOException {
String bundle = "JabRef";
// e.g., "<bundle>_en.properties", where <bundle> is [JabRef, Menu]
Pattern propertiesFile = Pattern.compile(String.format("%s_.{2,}.properties", bundle));
Set<String> localizationFiles = new HashSet<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Path.of("src/main/resources/l10n"))) {
for (Path fullPath : directoryStream) {
String fileName = fullPath.getFileName().toString();
if (propertiesFile.matcher(fileName).matches()) {
localizationFiles.add(fileName.substring(bundle.length() + 1, fileName.length() - ".properties".length()));
}
}
}
Set<String> knownLanguages = Stream.of(Language.values())
.map(Language::getId)
.collect(Collectors.toSet());
assertEquals(knownLanguages, localizationFiles, "There are some localization files that are not present in org.jabref.logic.l10n.Language or vice versa!");
}
@Test
void ensureNoDuplicates() {
String bundle = "JabRef";
for (Language lang : Language.values()) {
String propertyFilePath = String.format("/l10n/%s_%s.properties", bundle, lang.getId());
// read in
DuplicationDetectionProperties properties = new DuplicationDetectionProperties();
try (InputStream is = LocalizationConsistencyTest.class.getResourceAsStream(propertyFilePath);
InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
properties.load(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
List<String> duplicates = properties.getDuplicates();
assertEquals(Collections.emptyList(), duplicates, "Duplicate keys inside bundle " + bundle + "_" + lang.getId());
}
}
@Test
void keyValueShouldBeEqualForEnglishPropertiesMessages() {
Properties englishKeys = LocalizationParser.getProperties(String.format("/l10n/%s_%s.properties", "JabRef", "en"));
for (Map.Entry<Object, Object> entry : englishKeys.entrySet()) {
String expectedKeyEqualsKey = String.format("%s=%s", entry.getKey(), entry.getKey().toString().replace("\n", "\\n"));
String actualKeyEqualsValue = String.format("%s=%s", entry.getKey(), entry.getValue().toString().replace("\n", "\\n"));
assertEquals(expectedKeyEqualsKey, actualKeyEqualsValue);
}
}
@Test
void languageKeysShouldNotContainUnderscoresForSpaces() throws IOException {
final List<LocalizationEntry> quotedEntries = LocalizationParser
.findLocalizationParametersStringsInJavaFiles(LocalizationBundleForTest.LANG)
.stream()
.filter(key -> key.getKey().contains("\\_"))
.collect(Collectors.toList());
assertEquals(Collections.emptyList(), quotedEntries,
"Language keys must not use underscores for spaces! Use \"This is a message\" instead of \"This_is_a_message\".\n" +
"Please correct the following entries:\n" +
quotedEntries
.stream()
.map(key -> String.format("\n%s (%s)\n", key.getKey(), key.getPath()))
.collect(Collectors.toList()));
}
@Test
void languageKeysShouldNotContainHtmlBrAndHtmlP() throws IOException {
final List<LocalizationEntry> entriesWithHtml = LocalizationParser
.findLocalizationParametersStringsInJavaFiles(LocalizationBundleForTest.LANG)
.stream()
.filter(key -> key.getKey().contains("<br>") || key.getKey().contains("<p>"))
.collect(Collectors.toList());
assertEquals(Collections.emptyList(), entriesWithHtml,
"Language keys must not contain HTML <br> or <p>. Use \\n for a line break.\n" +
"Please correct the following entries:\n" +
entriesWithHtml
.stream()
.map(key -> String.format("\n%s (%s)\n", key.getKey(), key.getPath()))
.collect(Collectors.toList()));
}
@Test
void findMissingLocalizationKeys() throws IOException {
List<LocalizationEntry> missingKeys = LocalizationParser.findMissingKeys(LocalizationBundleForTest.LANG)
.stream()
.collect(Collectors.toList());
assertEquals(Collections.emptyList(), missingKeys,
missingKeys.stream()
.map(key -> LocalizationKey.fromKey(key.getKey()))
.map(key -> String.format("%s=%s",
key.getEscapedPropertiesKey(),
key.getValueForEnglishPropertiesFile()))
.collect(Collectors.joining("\n",
"\n\nDETECTED LANGUAGE KEYS WHICH ARE NOT IN THE ENGLISH LANGUAGE FILE\n" +
"PASTE THESE INTO THE ENGLISH LANGUAGE FILE\n\n",
"\n\n")));
}
@Test
void findObsoleteLocalizationKeys() throws IOException {
Set<String> obsoleteKeys = LocalizationParser.findObsolete(LocalizationBundleForTest.LANG);
assertEquals(Collections.emptySet(), obsoleteKeys,
obsoleteKeys.stream().collect(Collectors.joining("\n",
"Obsolete keys found in language properties file: \n\n",
"\n\n1. CHECK IF THE KEY IS REALLY NOT USED ANYMORE\n" +
"2. REMOVE THESE FROM THE ENGLISH LANGUAGE FILE\n"))
);
}
@Test
void localizationParameterMustIncludeAString() throws IOException {
// Must start or end with "
// Localization.lang("test"), Localization.lang("test" + var), Localization.lang(var + "test")
// TODO: Localization.lang(var1 + "test" + var2) not covered
// Localization.lang("Problem downloading from %1", address)
Set<LocalizationEntry> keys = LocalizationParser.findLocalizationParametersStringsInJavaFiles(LocalizationBundleForTest.LANG);
for (LocalizationEntry e : keys) {
assertTrue(e.getKey().startsWith("\"") || e.getKey().endsWith("\""), "Illegal localization parameter found. Must include a String with potential concatenation or replacement parameters. Illegal parameter: Localization.lang(" + e.getKey());
}
keys = LocalizationParser.findLocalizationParametersStringsInJavaFiles(LocalizationBundleForTest.MENU);
for (LocalizationEntry e : keys) {
assertTrue(e.getKey().startsWith("\"") || e.getKey().endsWith("\""), "Illegal localization parameter found. Must include a String with potential concatenation or replacement parameters. Illegal parameter: Localization.lang(" + e.getKey());
}
}
private static Language[] installedLanguages() {
return Language.values();
}
@ParameterizedTest
@MethodSource("installedLanguages")
void resourceBundleExists(Language language) {
Path messagesPropertyFile = Path.of("src/main/resources").resolve(Localization.RESOURCE_PREFIX + "_" + language.getId() + ".properties");
assertTrue(Files.exists(messagesPropertyFile));
}
@ParameterizedTest
@MethodSource("installedLanguages")
void languageCanBeLoaded(Language language) {
Locale oldLocale = Locale.getDefault();
try {
Locale locale = Language.convertToSupportedLocale(language).get();
Locale.setDefault(locale);
ResourceBundle messages = ResourceBundle.getBundle(Localization.RESOURCE_PREFIX, locale);
assertNotNull(messages);
} finally {
Locale.setDefault(oldLocale);
}
}
private static class DuplicationDetectionProperties extends Properties {
private static final long serialVersionUID = 1L;
private final List<String> duplicates = new ArrayList<>();
DuplicationDetectionProperties() {
super();
}
/**
* Overriding the HashTable put() so we can check for duplicates
*/
@Override
public synchronized Object put(Object key, Object value) {
// Have we seen this key before?
if (containsKey(key)) {
duplicates.add(String.valueOf(key));
}
return super.put(key, value);
}
List<String> getDuplicates() {
return duplicates;
}
}
}
| 10,200 | 45.579909 | 251 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LocalizationEntry.java | package org.jabref.logic.l10n;
import java.nio.file.Path;
import java.util.Objects;
/**
* Representation of a localization key required for testing
*/
class LocalizationEntry implements Comparable<LocalizationEntry> {
private final Path path;
private final String key;
private final LocalizationBundleForTest bundle;
LocalizationEntry(Path path, String key, LocalizationBundleForTest bundle) {
this.path = path;
this.key = key;
this.bundle = bundle;
}
public Path getPath() {
return path;
}
public String getKey() {
return key;
}
public String getId() {
return String.format("%s___%s", bundle, key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
LocalizationEntry that = (LocalizationEntry) o;
if (!Objects.equals(key, that.key)) {
return false;
}
return bundle == that.bundle;
}
@Override
public int hashCode() {
return Objects.hash(key, bundle);
}
public LocalizationBundleForTest getBundle() {
return bundle;
}
@Override
public String toString() {
return String.format("%s (%s %s)", key, path, bundle);
}
@Override
public int compareTo(LocalizationEntry o) {
return getId().compareTo(o.getId());
}
}
| 1,498 | 20.724638 | 80 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LocalizationKeyParamsTest.java | package org.jabref.logic.l10n;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class LocalizationKeyParamsTest {
@ParameterizedTest
@MethodSource("provideTestData")
public void testReplacePlaceholders(String expected, LocalizationKeyParams input) {
assertEquals(expected, input.replacePlaceholders());
}
private static Stream<Arguments> provideTestData() {
return Stream.of(
Arguments.of("biblatex mode", new LocalizationKeyParams("biblatex mode")),
Arguments.of("biblatex mode", new LocalizationKeyParams("%0 mode", "biblatex")),
Arguments.of("C:\\bla mode", new LocalizationKeyParams("%0 mode", "C:\\bla")),
Arguments.of("What \n : %e %c a b", new LocalizationKeyParams("What \n : %e %c %0 %1", "a", "b")),
Arguments.of("What \n : %e %c_a b", new LocalizationKeyParams("What \n : %e %c_%0 %1", "a", "b"))
);
}
@Test
public void testTooManyParams() {
assertThrows(IllegalStateException.class, () -> new LocalizationKeyParams("", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"));
}
}
| 1,482 | 40.194444 | 172 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LocalizationKeyTest.java | package org.jabref.logic.l10n;
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 LocalizationKeyTest {
private static Stream<Arguments> propertiesKeyTestCases() {
return Stream.of(
// underscore is preserved
Arguments.of("test_with_underscore", "test_with_underscore"),
// Java code: Copy \\cite{citation key}
// String representation: "Copy \\\\cite{citation key}"
// In other words: The property is "Copy\ \\cite{citation\\ key}", because the "\" before "cite" is a backslash, not an escape for the c. That property is "Copy\ \\cite{citation\ key}" in Java code, because of the escaping of the backslash.
Arguments.of("Copy\\ \\\\cite{citation\\ key}", "Copy \\\\cite{citation key}"),
// Java code: Newline follows\n
// String representation: "Newline follows\\n"
Arguments.of("Newline\\ follows\\n", "Newline follows\\n"),
// Java code: First line\nSecond line
// String representation: "First line\\nSecond line"
// In other words: "First line\nSecond line" is the wrong test case, because the source code contains "First line\nSecond line", which is rendered as Java String as "First line\\nSecond line"
Arguments.of("First\\ line\\nSecond\\ line", "First line\\nSecond line")
);
}
@ParameterizedTest
@MethodSource("propertiesKeyTestCases")
public void getPropertiesKeyReturnsCorrectValue(String expected, String input) {
assertEquals(expected, LocalizationKey.fromEscapedJavaString(input).getEscapedPropertiesKey());
}
}
| 1,899 | 46.5 | 256 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LocalizationParser.java | package org.jabref.logic.l10n;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.fxml.FXMLLoader;
import com.airhacks.afterburner.views.ViewLoader;
import org.mockito.Answers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class LocalizationParser {
public static SortedSet<LocalizationEntry> findMissingKeys(LocalizationBundleForTest type) throws IOException {
Set<LocalizationEntry> entries = findLocalizationEntriesInFiles(type);
Set<String> keysInJavaFiles = entries.stream()
.map(LocalizationEntry::getKey)
.collect(Collectors.toSet());
Set<String> englishKeys;
if (type == LocalizationBundleForTest.LANG) {
englishKeys = getKeysInPropertiesFile("/l10n/JabRef_en.properties");
} else {
englishKeys = getKeysInPropertiesFile("/l10n/Menu_en.properties");
}
List<String> missingKeys = new ArrayList<>(keysInJavaFiles);
missingKeys.removeAll(englishKeys);
return entries.stream()
.filter(e -> missingKeys.contains(e.getKey()))
.collect(Collectors.toCollection(TreeSet::new));
}
public static SortedSet<String> findObsolete(LocalizationBundleForTest type) throws IOException {
Set<String> englishKeys;
if (type == LocalizationBundleForTest.LANG) {
englishKeys = getKeysInPropertiesFile("/l10n/JabRef_en.properties");
} else {
englishKeys = getKeysInPropertiesFile("/l10n/Menu_en.properties");
}
Set<String> keysInSourceFiles = findLocalizationEntriesInFiles(type)
.stream().map(LocalizationEntry::getKey).collect(Collectors.toSet());
englishKeys.removeAll(keysInSourceFiles);
return new TreeSet<>(englishKeys);
}
private static Set<LocalizationEntry> findLocalizationEntriesInFiles(LocalizationBundleForTest type) throws IOException {
if (type == LocalizationBundleForTest.MENU) {
return findLocalizationEntriesInJavaFiles(type);
} else {
Set<LocalizationEntry> entriesInFiles = new HashSet<>();
entriesInFiles.addAll(findLocalizationEntriesInJavaFiles(type));
entriesInFiles.addAll(findLocalizationEntriesInFxmlFiles(type));
return entriesInFiles;
}
}
public static Set<LocalizationEntry> findLocalizationParametersStringsInJavaFiles(LocalizationBundleForTest type)
throws IOException {
try (Stream<Path> pathStream = Files.walk(Path.of("src/main"))) {
return pathStream
.filter(LocalizationParser::isJavaFile)
.flatMap(path -> getLocalizationParametersInJavaFile(path, type).stream())
.collect(Collectors.toSet());
} catch (UncheckedIOException ioe) {
throw new IOException(ioe);
}
}
private static Set<LocalizationEntry> findLocalizationEntriesInJavaFiles(LocalizationBundleForTest type)
throws IOException {
try (Stream<Path> pathStream = Files.walk(Path.of("src/main"))) {
return pathStream
.filter(LocalizationParser::isJavaFile)
.flatMap(path -> getLanguageKeysInJavaFile(path, type).stream())
.collect(Collectors.toSet());
} catch (UncheckedIOException ioe) {
throw new IOException(ioe);
}
}
private static Set<LocalizationEntry> findLocalizationEntriesInFxmlFiles(LocalizationBundleForTest type)
throws IOException {
try (Stream<Path> pathStream = Files.walk(Path.of("src/main"))) {
return pathStream
.filter(LocalizationParser::isFxmlFile)
.flatMap(path -> getLanguageKeysInFxmlFile(path, type).stream())
.collect(Collectors.toSet());
} catch (UncheckedIOException ioe) {
throw new IOException(ioe);
}
}
/**
* Returns the trimmed key set of the given property file. Each key is already unescaped.
*/
public static SortedSet<String> getKeysInPropertiesFile(String path) {
Properties properties = getProperties(path);
return properties.keySet().stream()
.map(Object::toString)
.map(String::trim)
.map(key -> key
// escape keys to make them comparable
.replace("\\", "\\\\")
.replace("\n", "\\n")
)
.collect(Collectors.toCollection(TreeSet::new));
}
public static Properties getProperties(String path) {
Properties properties = new Properties();
try (InputStream is = LocalizationConsistencyTest.class.getResourceAsStream(path);
InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
properties.load(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
return properties;
}
private static boolean isJavaFile(Path path) {
return path.toString().endsWith(".java");
}
private static boolean isFxmlFile(Path path) {
return path.toString().endsWith(".fxml");
}
private static List<LocalizationEntry> getLanguageKeysInJavaFile(Path path, LocalizationBundleForTest type) {
List<String> lines;
try {
lines = Files.readAllLines(path, StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
String content = String.join("\n", lines);
return JavaLocalizationEntryParser.getLanguageKeysInString(content, type).stream()
.map(key -> new LocalizationEntry(path, key, type))
.collect(Collectors.toList());
}
private static List<LocalizationEntry> getLocalizationParametersInJavaFile(Path path, LocalizationBundleForTest type) {
List<String> lines;
try {
lines = Files.readAllLines(path, StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
String content = String.join("\n", lines);
return JavaLocalizationEntryParser.getLocalizationParameter(content, type).stream()
.map(key -> new LocalizationEntry(path, key, type))
.collect(Collectors.toList());
}
/**
* Loads the fxml file and returns all used language resources.
*/
private static List<LocalizationEntry> getLanguageKeysInFxmlFile(Path path, LocalizationBundleForTest type) {
List<String> result = new ArrayList<>();
// Afterburner ViewLoader forces a controller factory, but we do not need any controller
MockedStatic<ViewLoader> viewLoader = Mockito.mockStatic(ViewLoader.class, Answers.RETURNS_DEEP_STUBS);
// Record which keys are requested; we pretend that we have all keys
ResourceBundle registerUsageResourceBundle = new ResourceBundle() {
@Override
protected Object handleGetObject(String key) {
result.add(key);
return "test";
}
@Override
public Enumeration<String> getKeys() {
return null;
}
@Override
public boolean containsKey(String key) {
return true;
}
};
try {
FXMLLoader loader = new FXMLLoader(path.toUri().toURL(), registerUsageResourceBundle);
// We don't want to initialize controller
loader.setControllerFactory(Mockito::mock);
// We need to load in "static mode" because otherwise fxml files with fx:root doesn't work
setStaticLoad(loader);
loader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
} finally {
viewLoader.close();
}
return result.stream()
.map(key -> new LocalizationEntry(path, key, type))
.collect(Collectors.toList());
}
private static void setStaticLoad(FXMLLoader loader) {
// Somebody decided to make "setStaticLoad" package-private, so let's use reflection
//
// Issues in JFX:
// - https://bugs.openjdk.java.net/browse/JDK-8159005 "SceneBuilder needs public access to FXMLLoader setStaticLoad" --> call for "request from community users with use cases"
// - https://bugs.openjdk.java.net/browse/JDK-8127532 "FXMLLoader#setStaticLoad is deprecated"
try {
Method method = FXMLLoader.class.getDeclaredMethod("setStaticLoad", boolean.class);
method.setAccessible(true);
method.invoke(loader, true);
} catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
| 9,927 | 41.067797 | 185 | java |
null | jabref-main/src/test/java/org/jabref/logic/l10n/LocalizationTest.java | package org.jabref.logic.l10n;
import java.util.Locale;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class LocalizationTest {
private Locale locale;
@BeforeEach
void storeDefaultLocale() {
locale = Locale.getDefault();
}
@AfterEach
void restoreDefaultLocale() {
Locale.setDefault(locale);
Localization.setLanguage(Language.ENGLISH);
}
@Test
void testSetKnownLanguage() {
Locale.setDefault(Locale.CHINA);
Localization.setLanguage(Language.ENGLISH);
assertEquals("en", Locale.getDefault().toString());
}
@Test
void testKnownTranslationWithGroups() {
Localization.setLanguage(Language.ENGLISH);
assertEquals("Groups", Localization.lang("Groups"));
}
@Test
void testKnownEnglishTranslationOfUndo() {
Localization.setLanguage(Language.ENGLISH);
assertEquals("Undo", Localization.lang("Undo"));
}
@Test
void testKnownGermanTranslation() {
Localization.setLanguage(Language.GERMAN);
assertEquals("Zeige Einstellungen", Localization.lang("Show preferences"));
}
@Test
void newLineIsAvailableAndKeptUnescaped() {
Localization.setLanguage(Language.ENGLISH);
assertEquals("Hint: To search specific fields only, enter for example:\n<tt>author=smith and title=electrical</tt>", Localization.lang("Hint: To search specific fields only, enter for example:\n<tt>author=smith and title=electrical</tt>"));
}
@Test
void testKnownTranslationWithCountryModifier() {
Localization.setLanguage(Language.BRAZILIAN_PORTUGUESE);
assertEquals("Grupos", Localization.lang("Groups"));
}
@Test
void testUnknownTranslation() {
Localization.setLanguage(Language.ENGLISH);
assertEquals("WHATEVER", Localization.lang("WHATEVER"));
}
@Test
void testUnsetLanguageTranslation() {
assertEquals("Groups", Localization.lang("Groups"));
}
}
| 2,123 | 27.702703 | 248 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java | package org.jabref.logic.layout;
import java.io.IOException;
import java.io.StringReader;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
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;
/**
* The test class LayoutEntryTest test the net.sf.jabref.export.layout.LayoutEntry. Indirectly the
* net.sf.jabref.export.layout.Layout is tested too.
* <p/>
* The LayoutEntry creates a human readable String assigned with HTML formatters. To test the Highlighting Feature, an
* instance of LayoutEntry will be instantiated via Layout and LayoutHelper. With these instance the doLayout() Method
* is called several times for each test case. To simulate a search, a BibEntry will be created, which will be used by
* LayoutEntry.
*
* There are five test cases: - The shown result text has no words which should be highlighted. - There is one word
* which will be highlighted ignoring case sensitivity. - There are two words which will be highlighted ignoring case
* sensitivity. - There is one word which will be highlighted case sensitivity. - There are more words which will be
* highlighted case sensitivity.
*/
public class LayoutEntryTest {
private BibEntry mBTE;
@BeforeEach
public void setUp() {
mBTE = new BibEntry();
mBTE.setField(StandardField.ABSTRACT, "In this paper, we initiate a formal study of security on Android: Google's new open-source platform for mobile devices. Tags: Paper android google Open-Source Devices");
// Specifically, we present a core typed language to describe Android applications, and to reason about their data-flow security properties. Our operational semantics and type system provide some necessary foundations to help both users and developers of Android applications deal with their security concerns.
mBTE.setField(StandardField.KEYWORDS, "android, mobile devices, security");
mBTE.setField(new UnknownField("posted-at"), "2010-08-11 15:00:49");
mBTE.setField(StandardField.LOCATION, "Dublin, Ireland");
mBTE.setCitationKey("chaudhuri-plas09");
mBTE.setField(StandardField.PAGES, "1--7");
mBTE.setField(StandardField.BOOKTITLE, "PLAS '09: Proceedings of the ACM SIGPLAN Fourth Workshop on Programming Languages and Analysis for Security");
mBTE.setField(new UnknownField("citeulike-article-id"), "7615801");
mBTE.setField(new UnknownField("citeulike-linkout-1"), "http://dx.doi.org/10.1145/1554339.1554341");
mBTE.setField(StandardField.URL, "http://dx.doi.org/10.1145/1554339.1554341");
mBTE.setField(StandardField.PUBLISHER, "ACM");
mBTE.setField(StandardField.TIMESTAMP, "2010.11.11");
mBTE.setField(StandardField.AUTHOR, "Chaudhuri, Avik");
mBTE.setField(StandardField.TITLE, "Language-based security on Android");
mBTE.setField(StandardField.ADDRESS, "New York, NY, USA");
mBTE.setField(SpecialField.PRIORITY, "2");
mBTE.setField(StandardField.ISBN, "978-1-60558-645-8");
mBTE.setField(StandardField.OWNER, "Arne");
mBTE.setField(StandardField.YEAR, "2009");
mBTE.setField(new UnknownField("citeulike-linkout-0"), "http://portal.acm.org/citation.cfm?id=1554339.1554341");
mBTE.setField(StandardField.DOI, "10.1145/1554339.1554341");
}
public String layout(String layoutFile, BibEntry entry) throws IOException {
StringReader sr = new StringReader(layoutFile.replace("__NEWLINE__", "\n"));
Layout layout = new LayoutHelper(sr, mock(LayoutFormatterPreferences.class), mock(JournalAbbreviationRepository.class)).getLayoutFromText();
return layout.doLayout(entry, null);
}
@Test
public void testParseMethodCalls() {
assertEquals(1, LayoutEntry.parseMethodsCalls("bla").size());
assertEquals("bla", (LayoutEntry.parseMethodsCalls("bla").get(0)).get(0));
assertEquals(1, LayoutEntry.parseMethodsCalls("bla,").size());
assertEquals("bla", (LayoutEntry.parseMethodsCalls("bla,").get(0)).get(0));
assertEquals(1, LayoutEntry.parseMethodsCalls("_bla.bla.blub,").size());
assertEquals("_bla.bla.blub", (LayoutEntry.parseMethodsCalls("_bla.bla.blub,").get(0)).get(0));
assertEquals(2, LayoutEntry.parseMethodsCalls("bla,foo").size());
assertEquals("bla", (LayoutEntry.parseMethodsCalls("bla,foo").get(0)).get(0));
assertEquals("foo", (LayoutEntry.parseMethodsCalls("bla,foo").get(1)).get(0));
assertEquals(2, LayoutEntry.parseMethodsCalls("bla(\"test\"),foo(\"fark\")").size());
assertEquals("bla", (LayoutEntry.parseMethodsCalls("bla(\"test\"),foo(\"fark\")").get(0)).get(0));
assertEquals("foo", (LayoutEntry.parseMethodsCalls("bla(\"test\"),foo(\"fark\")").get(1)).get(0));
assertEquals("test", (LayoutEntry.parseMethodsCalls("bla(\"test\"),foo(\"fark\")").get(0)).get(1));
assertEquals("fark", (LayoutEntry.parseMethodsCalls("bla(\"test\"),foo(\"fark\")").get(1)).get(1));
assertEquals(2, LayoutEntry.parseMethodsCalls("bla(test),foo(fark)").size());
assertEquals("bla", (LayoutEntry.parseMethodsCalls("bla(test),foo(fark)").get(0)).get(0));
assertEquals("foo", (LayoutEntry.parseMethodsCalls("bla(test),foo(fark)").get(1)).get(0));
assertEquals("test", (LayoutEntry.parseMethodsCalls("bla(test),foo(fark)").get(0)).get(1));
assertEquals("fark", (LayoutEntry.parseMethodsCalls("bla(test),foo(fark)").get(1)).get(1));
}
}
| 5,811 | 57.707071 | 319 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/LayoutHelperTest.java | package org.jabref.logic.layout;
import java.io.IOException;
import java.io.StringReader;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
class LayoutHelperTest {
private final LayoutFormatterPreferences layoutFormatterPreferences = mock(LayoutFormatterPreferences.class);
private final JournalAbbreviationRepository abbreviationRepository = mock(JournalAbbreviationRepository.class);
@Test
public void backslashDoesNotTriggerException() {
StringReader stringReader = new StringReader("\\");
LayoutHelper layoutHelper = new LayoutHelper(stringReader, layoutFormatterPreferences, abbreviationRepository);
assertThrows(IOException.class, layoutHelper::getLayoutFromText);
}
@Test
public void unbalancedBeginEndIsParsed() throws Exception {
StringReader stringReader = new StringReader("\\begin{doi}, DOI: \\doi");
LayoutHelper layoutHelper = new LayoutHelper(stringReader, layoutFormatterPreferences, abbreviationRepository);
Layout layout = layoutHelper.getLayoutFromText();
assertNotNull(layout);
}
@Test
public void minimalExampleWithDoiGetsParsed() throws Exception {
StringReader stringReader = new StringReader("\\begin{doi}, DOI: \\doi\\end{doi}");
LayoutHelper layoutHelper = new LayoutHelper(stringReader, layoutFormatterPreferences, abbreviationRepository);
Layout layout = layoutHelper.getLayoutFromText();
assertNotNull(layout);
}
}
| 1,698 | 39.452381 | 119 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/LayoutTest.java | package org.jabref.logic.layout;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.layout.format.NameFormatterPreferences;
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.jabref.model.entry.types.UnknownEntryType;
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 LayoutTest {
private LayoutFormatterPreferences layoutFormatterPreferences;
private JournalAbbreviationRepository abbreviationRepository;
@BeforeEach
void setUp() {
layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS);
abbreviationRepository = mock(JournalAbbreviationRepository.class);
}
private String layout(String layout, List<Path> fileDirForDatabase, BibEntry entry) throws IOException {
StringReader layoutStringReader = new StringReader(layout.replace("__NEWLINE__", "\n"));
return new LayoutHelper(layoutStringReader, fileDirForDatabase, layoutFormatterPreferences, abbreviationRepository)
.getLayoutFromText()
.doLayout(entry, null);
}
private String layout(String layout, BibEntry entry) throws IOException {
return layout(layout, Collections.emptyList(), entry);
}
@Test
void entryTypeForUnknown() throws IOException {
BibEntry entry = new BibEntry(new UnknownEntryType("unknown")).withField(StandardField.AUTHOR, "test");
assertEquals("Unknown", layout("\\bibtextype", entry));
}
@Test
void entryTypeForArticle() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article).withField(StandardField.AUTHOR, "test");
assertEquals("Article", layout("\\bibtextype", entry));
}
@Test
void entryTypeForMisc() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Misc).withField(StandardField.AUTHOR, "test");
assertEquals("Misc", layout("\\bibtextype", entry));
}
@Test
void HTMLChar() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article).withField(StandardField.AUTHOR, "This\nis\na\ntext");
String actual = layout("\\begin{author}\\format[HTMLChars]{\\author}\\end{author}", entry);
assertEquals("This<br>is<br>a<br>text", actual);
}
@Test
void HTMLCharWithDoubleLineBreak() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article).withField(StandardField.AUTHOR, "This\nis\na\n\ntext");
String layoutText = layout("\\begin{author}\\format[HTMLChars]{\\author}\\end{author} ", entry);
assertEquals("This<br>is<br>a<p>text ", layoutText);
}
@Test
void nameFormatter() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article).withField(StandardField.AUTHOR, "Joe Doe and Jane, Moon");
String layoutText = layout("\\begin{author}\\format[NameFormatter]{\\author}\\end{author}", entry);
assertEquals("Joe Doe, Moon Jane", layoutText);
}
@Test
void HTMLCharsWithDotlessIAndTiled() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.ABSTRACT, "\\~{n} \\~n \\'i \\i \\i");
String layoutText = layout(
"<font face=\"arial\">\\begin{abstract}<BR><BR><b>Abstract: </b> \\format[HTMLChars]{\\abstract}\\end{abstract}</font>",
entry);
assertEquals(
"<font face=\"arial\"><BR><BR><b>Abstract: </b> ñ ñ í ı ı</font>",
layoutText);
}
@Test
void beginConditionals() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Misc)
.withField(StandardField.AUTHOR, "Author");
// || (OR)
String layoutText = layout("\\begin{editor||author}\\format[HTMLChars]{\\author}\\end{editor||author}", entry);
assertEquals("Author", layoutText);
// && (AND)
layoutText = layout("\\begin{editor&&author}\\format[HTMLChars]{\\author}\\end{editor&&author}", entry);
assertEquals("", layoutText);
// ! (NOT)
layoutText = layout("\\begin{!year}\\format[HTMLChars]{(no year)}\\end{!year}", entry);
assertEquals("(no year)", layoutText);
// combined (!a&&b)
layoutText = layout(
"\\begin{!editor&&author}\\format[HTMLChars]{\\author}\\end{!editor&&author}" +
"\\begin{editor&&!author}\\format[HTMLChars]{\\editor} (eds.)\\end{editor&&!author}", entry);
assertEquals("Author", layoutText);
}
/**
* Test for http://discourse.jabref.org/t/the-wrapfilelinks-formatter/172 (the example in the help files)
*/
@Test
void wrapFileLinksExpandFile() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article);
entry.addFile(new LinkedFile("Test file", Path.of("encrypted.pdf"), "PDF"));
String layoutText = layout(
"\\begin{file}\\format[WrapFileLinks(\\i. \\d (\\p))]{\\file}\\end{file}",
Collections.singletonList(Path.of("src/test/resources/pdfs/")),
entry);
assertEquals(
"1. Test file (" + new File("src/test/resources/pdfs/encrypted.pdf").getCanonicalPath() + ")",
layoutText);
}
@Test
void expandCommandIfTerminatedByMinus() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article).withField(StandardField.EDITION, "2");
String layoutText = layout("\\edition-th ed.-", entry);
assertEquals("2-th ed.-", layoutText);
}
@Test
void customNameFormatter() throws IOException {
when(layoutFormatterPreferences.getNameFormatterPreferences()).thenReturn(
new NameFormatterPreferences(Collections.singletonList("DCA"), Collections.singletonList("1@*@{ll}@@2@1..1@{ff}{ll}@2..2@ and {ff}{l}@@*@*@more")));
BibEntry entry = new BibEntry(StandardEntryType.Article).withField(StandardField.AUTHOR, "Joe Doe and Mary Jane");
String layoutText = layout("\\begin{author}\\format[DCA]{\\author}\\end{author}", entry);
assertEquals("JoeDoe and MaryJ", layoutText);
}
}
| 6,772 | 37.265537 | 164 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorAbbreviatorTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Is the save as the AuthorLastFirstAbbreviator.
*/
public class AuthorAbbreviatorTest {
@Test
public void testFormat() {
LayoutFormatter a = new AuthorLastFirstAbbreviator();
LayoutFormatter b = new AuthorAbbreviator();
assertEquals(b.format(""), a.format(""));
assertEquals(b.format("Someone, Van Something"), a.format("Someone, Van Something"));
assertEquals(b.format("Smith, John"), a.format("Smith, John"));
assertEquals(b.format("von Neumann, John and Smith, John and Black Brown, Peter"), a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
}
}
| 844 | 31.5 | 93 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorAndToSemicolonReplacerTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
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 AuthorAndToSemicolonReplacerTest {
private static Stream<Arguments> data() {
return Stream.of(
Arguments.of("", ""),
Arguments.of("Someone, Van Something", "Someone, Van Something"),
Arguments.of("John Smith and Black Brown, Peter", "John Smith; Black Brown, Peter"),
Arguments.of("von Neumann, John and Smith, John and Black Brown, Peter", "von Neumann, John; Smith, John; Black Brown, Peter"),
Arguments.of("John von Neumann and John Smith and Peter Black Brown", "John von Neumann; John Smith; Peter Black Brown"));
}
@ParameterizedTest
@MethodSource("data")
void testFormat(String input, String expected) {
LayoutFormatter a = new AuthorAndToSemicolonReplacer();
assertEquals(expected, a.format(input));
}
}
| 1,193 | 36.3125 | 143 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorAndsCommaReplacerTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorAndsCommaReplacerTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorAndsCommaReplacer#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorAndsCommaReplacer();
// Empty case
assertEquals("", a.format(""));
// Single Names don't change
assertEquals("Someone, Van Something", a.format("Someone, Van Something"));
// Two names just an &
assertEquals("John von Neumann & Peter Black Brown",
a.format("John von Neumann and Peter Black Brown"));
// Three names put a comma:
assertEquals("von Neumann, John, Smith, John & Black Brown, Peter",
a.format("von Neumann, John and Smith, John and Black Brown, Peter"));
}
}
| 1,015 | 29.787879 | 111 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorAndsReplacerTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorAndsReplacerTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorAndsReplacer#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorAndsReplacer();
// Empty case
assertEquals("", a.format(""));
// Single Names don't change
assertEquals("Someone, Van Something", a.format("Someone, Van Something"));
// Two names just an &
assertEquals("John Smith & Black Brown, Peter", a
.format("John Smith and Black Brown, Peter"));
// Three names put a comma:
assertEquals("von Neumann, John; Smith, John & Black Brown, Peter", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("John von Neumann; John Smith & Peter Black Brown", a
.format("John von Neumann and John Smith and Peter Black Brown"));
}
}
| 1,151 | 31 | 106 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastCommasTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorFirstAbbrLastCommasTest {
@Test
public void testFormat() {
LayoutFormatter a = new AuthorFirstAbbrLastCommas();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("V. S. Someone", a.format("Someone, Van Something"));
// Two names
assertEquals("J. von Neumann and P. Black Brown", a
.format("John von Neumann and Black Brown, Peter"));
// Three names
assertEquals("J. von Neumann, J. Smith and P. Black Brown", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("J. von Neumann, J. Smith and P. Black Brown", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 993 | 29.121212 | 85 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorFirstAbbrLastOxfordCommasTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorFirstAbbrLastOxfordCommasTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorFirstAbbrLastOxfordCommas#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorFirstAbbrLastOxfordCommas();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("V. S. Someone", a.format("Someone, Van Something"));
// Two names
assertEquals("J. von Neumann and P. Black Brown", a
.format("John von Neumann and Black Brown, Peter"));
// Three names
assertEquals("J. von Neumann, J. Smith, and P. Black Brown", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("J. von Neumann, J. Smith, and P. Black Brown", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 1,143 | 30.777778 | 119 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstCommasTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorFirstFirstCommasTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorFirstFirstCommas#format(java.lang.String)}.
*/
@Test
public void testFormat() {
assertEquals("John von Neumann, John Smith and Peter Black Brown, Jr",
new AuthorFirstFirstCommas()
.format("von Neumann,,John and John Smith and Black Brown, Jr, Peter"));
}
}
| 579 | 29.526316 | 110 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorFirstFirstTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorFirstFirstTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorFirstFirst#format(java.lang.String)}.
*/
@Test
public void testFormat() {
assertEquals("John von Neumann and John Smith and Peter Black Brown, Jr",
new AuthorFirstFirst()
.format("von Neumann,,John and John Smith and Black Brown, Jr, Peter"));
}
}
| 564 | 28.736842 | 104 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastCommasTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorFirstLastCommasTest {
LayoutFormatter authorFLCFormatter = new AuthorFirstLastCommas();
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorFirstLastCommas#format(java.lang.String)}.
*/
@ParameterizedTest
@MethodSource("formatTests")
void paramLayoutFormatTest(String expectedString, String inputString) {
assertEquals(expectedString, authorFLCFormatter.format(inputString));
}
private static Stream<Arguments> formatTests() {
return Stream.of(
Arguments.of("", ""),
Arguments.of("Van Something Someone", "Someone, Van Something"),
Arguments.of("John von Neumann and Peter Black Brown", "John von Neumann and Peter Black Brown"),
Arguments.of("John von Neumann, John Smith and Peter Black Brown", "von Neumann, John and Smith, John and Black Brown, Peter"),
Arguments.of("John von Neumann, John Smith and Peter Black Brown", "John von Neumann and John Smith and Black Brown, Peter"),
Arguments.of("John von Neumann and Peter Black Brown", "John von Neumann and Peter Black Brown"),
Arguments.of("John von Neumann and Peter Black Brown", "John von Neumann and Peter Black Brown")
);
}
}
| 1,644 | 42.289474 | 143 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorFirstLastOxfordCommasTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorFirstLastOxfordCommasTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorFirstLastOxfordCommas#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorFirstLastOxfordCommas();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("Van Something Someone", a.format("Someone, Van Something"));
// Two names
assertEquals("John von Neumann and Peter Black Brown", a
.format("John von Neumann and Peter Black Brown"));
// Three names
assertEquals("John von Neumann, John Smith, and Peter Black Brown", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("John von Neumann, John Smith, and Peter Black Brown", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 1,157 | 31.166667 | 115 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFAbbrTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorLF_FFAbbrTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorLF_FFAbbr#format(java.lang.String)}.
*/
@Test
public void testFormat() {
assertEquals("von Neumann, J. and J. Smith and P. Black Brown, Jr",
new AuthorLF_FFAbbr()
.format("von Neumann,,John and John Smith and Black Brown, Jr, Peter"));
}
}
| 555 | 28.263158 | 103 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLF_FFTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorLF_FFTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorLF_FF#format(java.lang.String)}.
*/
@Test
public void testFormat() {
assertEquals("von Neumann, John and John Smith and Peter Black Brown, Jr",
new AuthorLF_FF()
.format("von Neumann,,John and John Smith and Black Brown, Jr, Peter"));
}
}
| 550 | 28 | 99 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrCommasTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorLastFirstAbbrCommasTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorLastFirstAbbrCommas#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorLastFirstAbbrCommas();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("Someone, V. S.", a.format("Van Something Someone"));
// Two names
assertEquals("von Neumann, J. and Black Brown, P.", a
.format("John von Neumann and Black Brown, Peter"));
// Three names
assertEquals("von Neumann, J., Smith, J. and Black Brown, P.", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("von Neumann, J., Smith, J. and Black Brown, P.", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 1,131 | 30.444444 | 113 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbrOxfordCommasTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorLastFirstAbbrOxfordCommasTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorLastFirstAbbrOxfordCommas#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorLastFirstAbbrOxfordCommas();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("Someone, V. S.", a.format("Van Something Someone"));
// Two names
assertEquals("von Neumann, J. and Black Brown, P.", a
.format("John von Neumann and Black Brown, Peter"));
// Three names
assertEquals("von Neumann, J., Smith, J., and Black Brown, P.", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("von Neumann, J., Smith, J., and Black Brown, P.", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 1,151 | 31 | 119 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test case that verifies the functionalities of the formater AuthorLastFirstAbbreviator.
*/
class AuthorLastFirstAbbreviatorTest {
/**
* Verifies the Abbreviation of one single author with a simple name.
* <p/>
* Ex: Lastname, Name
*/
@Test
void testOneAuthorSimpleName() {
assertEquals("Lastname, N.", abbreviate("Lastname, Name"));
}
/**
* Verifies the Abbreviation of one single author with a common name.
* <p/>
* Ex: Lastname, Name Middlename
*/
@Test
void testOneAuthorCommonName() {
assertEquals("Lastname, N. M.", abbreviate("Lastname, Name Middlename"));
}
/**
* Verifies the Abbreviation of two single with a common name.
* <p/>
* Ex: Lastname, Name Middlename
*/
@Test
void testTwoAuthorsCommonName() {
String result = abbreviate("Lastname, Name Middlename and Sobrenome, Nome Nomedomeio");
String expectedResult = "Lastname, N. M. and Sobrenome, N. N.";
assertEquals(expectedResult, result);
}
@Test
void testJrAuthor() {
assertEquals("Other, Jr., A. N.", abbreviate("Other, Jr., Anthony N."));
}
@Test
void testFormat() {
assertEquals("", abbreviate(""));
assertEquals("Someone, V. S.", abbreviate("Someone, Van Something"));
assertEquals("Smith, J.", abbreviate("Smith, John"));
assertEquals("von Neumann, J. and Smith, J. and Black Brown, P.",
abbreviate("von Neumann, John and Smith, John and Black Brown, Peter"));
}
private String abbreviate(String name) {
return new AuthorLastFirstAbbreviator().format(name);
}
}
| 1,831 | 28.079365 | 95 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstCommasTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorLastFirstCommasTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorLastFirstCommas#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorLastFirstCommas();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("Someone, Van Something", a.format("Van Something Someone"));
// Two names
assertEquals("von Neumann, John and Black Brown, Peter", a
.format("John von Neumann and Black Brown, Peter"));
// Three names
assertEquals("von Neumann, John, Smith, John and Black Brown, Peter", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("von Neumann, John, Smith, John and Black Brown, Peter", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 1,146 | 30.861111 | 109 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstOxfordCommasTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorLastFirstOxfordCommasTest {
/**
* Test method for {@link org.jabref.logic.layout.format.AuthorLastFirstOxfordCommas#format(java.lang.String)}.
*/
@Test
public void testFormat() {
LayoutFormatter a = new AuthorLastFirstOxfordCommas();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("Someone, Van Something", a.format("Van Something Someone"));
// Two names
assertEquals("von Neumann, John and Black Brown, Peter", a
.format("John von Neumann and Black Brown, Peter"));
// Three names
assertEquals("von Neumann, John, Smith, John, and Black Brown, Peter", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("von Neumann, John, Smith, John, and Black Brown, Peter", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 1,166 | 31.416667 | 115 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorLastFirstTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorLastFirstTest {
@Test
public void testFormat() {
LayoutFormatter a = new AuthorLastFirst();
// Empty case
assertEquals("", a.format(""));
// Single Names
assertEquals("Someone, Van Something", a.format("Van Something Someone"));
// Two names
assertEquals("von Neumann, John and Black Brown, Peter", a
.format("John von Neumann and Black Brown, Peter"));
// Three names
assertEquals("von Neumann, John and Smith, John and Black Brown, Peter", a
.format("von Neumann, John and Smith, John and Black Brown, Peter"));
assertEquals("von Neumann, John and Smith, John and Black Brown, Peter", a
.format("John von Neumann and John Smith and Black Brown, Peter"));
}
}
| 1,014 | 29.757576 | 85 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorNatBibTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorNatBibTest {
LayoutFormatter authorNatBibFormatter = new AuthorNatBib();
@ParameterizedTest
@MethodSource("formatTests")
void paramLayoutFormatTest(String expectedString, String inputString) {
assertEquals(expectedString, authorNatBibFormatter.format(inputString));
}
private static Stream<Arguments> formatTests() {
return Stream.of(
// Test method for {@link org.jabref.logic.layout.format.AuthorNatBib#format(java.lang.String)}.
Arguments.of("von Neumann et al.", "von Neumann,,John and John Smith and Black Brown, Jr, Peter"),
// Test method for {@link org.jabref.logic.layout.format.AuthorLF_FF#format(java.lang.String)}.
Arguments.of("von Neumann and Smith", "von Neumann,,John and John Smith"),
Arguments.of("von Neumann", "von Neumann, John")
);
}
}
| 1,257 | 36 | 114 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorOrgSciTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorOrgSciTest {
LayoutFormatter authorOrgNatFormatter = new AuthorOrgSci();
LayoutFormatter authorOrgNatFormatterComposite = new CompositeFormat(new AuthorOrgSci(), new NoSpaceBetweenAbbreviations());
@ParameterizedTest
@MethodSource("formatTests")
void paramLayoutFormatTest(String expectedString, String inputString) {
assertEquals(expectedString, authorOrgNatFormatter.format(inputString));
}
@ParameterizedTest
@MethodSource("formatTestsComposite")
void paramLayoutFormatTestComposite(String expectedString, String inputString) {
assertEquals(expectedString, authorOrgNatFormatterComposite.format(inputString));
}
private static Stream<Arguments> formatTests() {
return Stream.of(
Arguments.of("Flynn, J., S. Gartska", "John Flynn and Sabine Gartska"),
Arguments.of("Garvin, D. A.", "David A. Garvin"),
Arguments.of("Makridakis, S., S. C. Wheelwright, V. E. McGee", "Sa Makridakis and Sa Ca Wheelwright and Va Ea McGee")
);
}
private static Stream<Arguments> formatTestsComposite() {
return Stream.of(
Arguments.of("Flynn, J., S. Gartska", "John Flynn and Sabine Gartska"),
Arguments.of("Garvin, D.A.", "David A. Garvin"),
Arguments.of("Makridakis, S., S.C. Wheelwright, V.E. McGee", "Sa Makridakis and Sa Ca Wheelwright and Va Ea McGee")
);
}
}
| 1,815 | 38.478261 | 133 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/AuthorsTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.ParamLayoutFormatter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AuthorsTest {
private ParamLayoutFormatter authorsLayoutFormatter = new Authors();
@Test
public void testStandardUsage() {
assertEquals("B. C. Bruce, C. Manson and J. Jumper",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper"));
}
@Test
public void testStandardUsageOne() {
authorsLayoutFormatter.setArgument("fullname, LastFirst, Comma, Comma");
assertEquals("Bruce, Bob Croydon, Jumper, Jolly", authorsLayoutFormatter.format("Bob Croydon Bruce and Jolly Jumper"));
}
@Test
public void testStandardUsageTwo() {
authorsLayoutFormatter.setArgument("initials");
assertEquals("B. C. Bruce and J. Jumper", authorsLayoutFormatter.format("Bob Croydon Bruce and Jolly Jumper"));
}
@Test
public void testStandardUsageThree() {
authorsLayoutFormatter.setArgument("fullname, LastFirst, Comma");
assertEquals("Bruce, Bob Croydon, Manson, Charles and Jumper, Jolly",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper"));
}
@Test
public void testStandardUsageFour() {
authorsLayoutFormatter.setArgument("fullname, LastFirst, Comma, 2");
assertEquals("Bruce, Bob Croydon et al.",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper"));
}
@Test
public void testStandardUsageFive() {
authorsLayoutFormatter.setArgument("fullname, LastFirst, Comma, 3");
assertEquals("Bruce, Bob Croydon et al.",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles"));
}
@Test
public void testStandardUsageSix() {
authorsLayoutFormatter.setArgument("fullname, LastFirst, Comma, 3, 2");
assertEquals("Bruce, Bob Croydon, Manson, Charles et al.",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles"));
}
@Test
public void testSpecialEtAl() {
authorsLayoutFormatter.setArgument("fullname, LastFirst, Comma, 3, etal= and a few more");
assertEquals("Bruce, Bob Croydon and a few more",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles"));
}
@Test
public void testStandardUsageNull() {
assertEquals("", authorsLayoutFormatter.format(null));
}
@Test
public void testStandardOxford() {
authorsLayoutFormatter.setArgument("Oxford");
assertEquals("B. C. Bruce, C. Manson, and J. Jumper",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper"));
}
@Test
public void testStandardOxfordFullName() {
authorsLayoutFormatter.setArgument("FullName,Oxford");
assertEquals("Bob Croydon Bruce, Charles Manson, and Jolly Jumper",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles Manson and Jolly Jumper"));
}
@Test
public void testStandardCommaFullName() {
authorsLayoutFormatter.setArgument("FullName,Comma,Comma");
assertEquals("Bob Croydon Bruce, Charles Manson, Jolly Jumper",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles Manson and Jolly Jumper"));
}
@Test
public void testStandardAmpFullName() {
authorsLayoutFormatter.setArgument("FullName,Amp");
assertEquals("Bob Croydon Bruce, Charles Manson & Jolly Jumper",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles Manson and Jolly Jumper"));
}
@Test
public void testLastName() {
authorsLayoutFormatter.setArgument("LastName");
assertEquals("Bruce, von Manson and Jumper",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles von Manson and Jolly Jumper"));
}
@Test
public void testMiddleInitial() {
authorsLayoutFormatter.setArgument("MiddleInitial");
assertEquals("Bob C. Bruce, Charles K. von Manson and Jolly Jumper",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles Kermit von Manson and Jumper, Jolly"));
}
@Test
public void testNoPeriod() {
authorsLayoutFormatter.setArgument("NoPeriod");
assertEquals("B C Bruce, C K von Manson and J Jumper",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles Kermit von Manson and Jumper, Jolly"));
}
@Test
public void testEtAl() {
authorsLayoutFormatter.setArgument("2,1");
assertEquals("B. C. Bruce et al.",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles Kermit von Manson and Jumper, Jolly"));
}
@Test
public void testEtAlNotEnoughAuthors() {
authorsLayoutFormatter.setArgument("2,1");
assertEquals("B. C. Bruce and C. K. von Manson",
authorsLayoutFormatter.format("Bruce, Bob Croydon and Charles Kermit von Manson"));
}
@Test
public void testEmptyEtAl() {
authorsLayoutFormatter.setArgument("fullname, LastFirst, Comma, 3, etal=");
assertEquals("Bruce, Bob Croydon",
authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles"));
}
@ParameterizedTest(name = "arg={0}, formattedStr={1}")
@CsvSource({
"FirstFirst, 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // FirstFirst
"LastFirst, 'Bruce, B. C., Manson, C., Jumper, J. and Chuckles, C.'", // LastFirst
"LastFirstFirstFirst, 'Bruce, B. C., C. Manson, J. Jumper and C. Chuckles'" // LastFirstFirstFirst
})
public void testAuthorOrder(String arg, String expectedResult) {
authorsLayoutFormatter.setArgument(arg);
String formattedStr = authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles");
assertEquals(expectedResult, formattedStr);
}
@ParameterizedTest(name = "arg={0}, formattedStr={1}")
@CsvSource({
"FullName, 'Bob Croydon Bruce, Charles Manson, Jolly Jumper and Chuck Chuckles'", // FullName
"Initials, 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // Initials
"FirstInitial, 'B. Bruce, C. Manson, J. Jumper and C. Chuckles'", // FirstInitial
"MiddleInitial, 'Bob C. Bruce, Charles Manson, Jolly Jumper and Chuck Chuckles'", // MiddleInitial
"LastName, 'Bruce, Manson, Jumper and Chuckles'", // LastName
"InitialsNoSpace, 'B.C. Bruce, C. Manson, J. Jumper and C. Chuckles'" // InitialsNoSpace
})
public void testAuthorABRV(String arg, String expectedResult) {
authorsLayoutFormatter.setArgument(arg);
String formattedStr = authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles");
assertEquals(expectedResult, formattedStr);
}
@ParameterizedTest(name = "arg={0}, formattedStr={1}")
@CsvSource({
"FullPunc, 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // FullPunc
"NoPunc, 'B C Bruce, C Manson, J Jumper and C Chuckles'", // NoPunc
"NoComma, 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // NoComma
"NoPeriod, 'B C Bruce, C Manson, J Jumper and C Chuckles'" // NoPeriod
})
public void testAuthorPUNC(String arg, String expectedResult) {
authorsLayoutFormatter.setArgument(arg);
String formattedStr = authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles");
assertEquals(expectedResult, formattedStr);
}
@ParameterizedTest(name = "arg={0}, formattedStr={1}")
@CsvSource({
"Comma, 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // Comma
"And, 'B. C. Bruce and C. Manson and J. Jumper and C. Chuckles'", // And
"Colon, 'B. C. Bruce: C. Manson: J. Jumper and C. Chuckles'", // Colon
"Semicolon, 'B. C. Bruce; C. Manson; J. Jumper and C. Chuckles'", // Semicolon
"Oxford, 'B. C. Bruce, C. Manson, J. Jumper, and C. Chuckles'", // Oxford
"Amp, 'B. C. Bruce, C. Manson, J. Jumper & C. Chuckles'", // Amp
"Sep, 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // Sep
"LastSep, 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // LastSep
"Sep=|, 'B. C. Bruce|C. Manson|J. Jumper and C. Chuckles'", // Custom Sep
"LastSep=|, 'B. C. Bruce, C. Manson, J. Jumper|C. Chuckles'", // Custom LastSep
"'Comma, And', 'B. C. Bruce, C. Manson, J. Jumper and C. Chuckles'", // Comma And
"'Comma, Colon', 'B. C. Bruce, C. Manson, J. Jumper: C. Chuckles'", // Comma Colon
"'Comma, Semicolon', 'B. C. Bruce, C. Manson, J. Jumper; C. Chuckles'", // Comma Semicolon
})
public void testAuthorSEPARATORS(String arg, String expectedResult) {
authorsLayoutFormatter.setArgument(arg);
String formattedStr = authorsLayoutFormatter.format("Bob Croydon Bruce and Charles Manson and Jolly Jumper and Chuck Chuckles");
assertEquals(expectedResult, formattedStr);
}
}
| 9,661 | 46.131707 | 136 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/CompositeFormatTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CompositeFormatTest {
@Test
public void testEmptyComposite() {
LayoutFormatter f = new CompositeFormat();
assertEquals("No Change", f.format("No Change"));
}
@Test
public void testArrayComposite() {
LayoutFormatter f = new CompositeFormat(new LayoutFormatter[]{fieldText -> fieldText + fieldText,
fieldText -> "A" + fieldText, fieldText -> "B" + fieldText});
assertEquals("BAff", f.format("f"));
}
@Test
public void testDoubleComposite() {
LayoutFormatter f = new CompositeFormat(new AuthorOrgSci(), new NoSpaceBetweenAbbreviations());
LayoutFormatter first = new AuthorOrgSci();
LayoutFormatter second = new NoSpaceBetweenAbbreviations();
assertEquals(second.format(first.format("John Flynn and Sabine Gartska")),
f.format("John Flynn and Sabine Gartska"));
assertEquals(second.format(first.format("Sa Makridakis and Sa Ca Wheelwright and Va Ea McGee")),
f.format("Sa Makridakis and Sa Ca Wheelwright and Va Ea McGee"));
}
}
| 1,288 | 33.837838 | 105 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/DOICheckTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DOICheckTest {
private LayoutFormatter layoutFormatter = new DOICheck();
@ParameterizedTest
@MethodSource("provideDOI")
void formatDOI(String formattedDOI, String originalDOI) {
assertEquals(formattedDOI, layoutFormatter.format(originalDOI));
}
private static Stream<Arguments> provideDOI() {
return Stream.of(
Arguments.of("", ""),
Arguments.of(null, null),
Arguments.of("https://doi.org/10.1000/ISBN1-900512-44-0", "10.1000/ISBN1-900512-44-0"),
Arguments.of("https://doi.org/10.1000/ISBN1-900512-44-0", "http://dx.doi.org/10.1000/ISBN1-900512-44-0"),
Arguments.of("https://doi.org/10.1000/ISBN1-900512-44-0", "http://doi.acm.org/10.1000/ISBN1-900512-44-0"),
Arguments.of("https://doi.org/10.1145/354401.354407", "http://doi.acm.org/10.1145/354401.354407"),
Arguments.of("https://doi.org/10.1145/354401.354407", "10.1145/354401.354407"),
Arguments.of("https://doi.org/10.1145/354401.354407", "/10.1145/354401.354407"),
Arguments.of("10", "10"),
Arguments.of("1", "1")
);
}
}
| 1,549 | 38.74359 | 122 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/DOIStripTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DOIStripTest {
LayoutFormatter layoutFormatter = new DOIStrip();
@ParameterizedTest
@MethodSource("provideDOI")
public void testFormatDOIStrip(String formattedDOI, String originalDOI) {
assertEquals(formattedDOI, layoutFormatter.format(originalDOI));
}
private static Stream<Arguments> provideDOI() {
return Stream.of(
Arguments.of("", ""),
Arguments.of(null, null),
Arguments.of("10.1000/ISBN1-900512-44-0", "10.1000/ISBN1-900512-44-0"),
Arguments.of("10.1000/ISBN1-900512-44-0", "http://dx.doi.org/10.1000/ISBN1-900512-44-0"),
Arguments.of("10.1000/ISBN1-900512-44-0", "http://doi.acm.org/10.1000/ISBN1-900512-44-0"),
Arguments.of("10.1145/354401.354407", "http://doi.acm.org/10.1145/354401.354407"),
Arguments.of("10", "10"),
Arguments.of("1", "1")
);
}
}
| 1,243 | 33.555556 | 102 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/DateFormatterTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.ParamLayoutFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateFormatterTest {
private ParamLayoutFormatter formatter;
@BeforeEach
public void setUp() {
formatter = new DateFormatter();
}
@Test
public void testDefaultFormat() {
assertEquals("2016-07-15", formatter.format("2016-07-15"));
}
@Test
public void testRequestedFormat() {
formatter.setArgument("MM/yyyy");
assertEquals("07/2016", formatter.format("2016-07-15"));
}
@ParameterizedTest(name = "formatArg={0}, input={1}, formattedStr={2}")
@CsvSource({
"MM/dd/yyyy, 2016-07-15, 07/15/2016", // MM/dd/yyyy
"dd MMMM yyyy, 2016-07-15, 15 July 2016", // dd MMMM yyyy
"MM-dd-yyyy, 2016-07-15, 07-15-2016", // MM-dd-yyyy
"yyyy.MM.dd, 2016-07-15, 2016.07.15", // yyyy.MM.dd
"yyyy/MM, 2016-07-15, 2016/07", // yyyy/MM
})
public void testOtherFormats(String formatArg, String input, String expectedResult) {
formatter.setArgument(formatArg);
String formattedStr = formatter.format(input);
assertEquals(expectedResult, formattedStr);
}
}
| 1,457 | 30.695652 | 89 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/DefaultTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.ParamLayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DefaultTest {
ParamLayoutFormatter paramLayoutFormatter = new Default();
@ParameterizedTest
@MethodSource("formatTests")
void paramLayoutFormatTest(String expectedString, String inputString, String formatterArgument) {
if (!formatterArgument.isEmpty()) {
paramLayoutFormatter.setArgument(formatterArgument);
}
assertEquals(expectedString, paramLayoutFormatter.format(inputString));
}
private static Stream<Arguments> formatTests() {
return Stream.of(
Arguments.of("Bob Bruce", "Bob Bruce", "DEFAULT TEXT"),
Arguments.of("DEFAULT TEXT", null, "DEFAULT TEXT"),
Arguments.of("DEFAULT TEXT", "", "DEFAULT TEXT"),
Arguments.of("Bob Bruce and Jolly Jumper", "Bob Bruce and Jolly Jumper", ""),
Arguments.of("", null, ""),
Arguments.of("", "", "")
);
}
}
| 1,288 | 33.837838 | 101 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/EntryTypeFormatterTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EntryTypeFormatterTest {
private EntryTypeFormatter formatter = new EntryTypeFormatter();
@ParameterizedTest
@MethodSource("formatTests")
void testCorrectFormat(String expectedString, String inputString) {
assertEquals(expectedString, formatter.format(inputString));
}
private static Stream<Arguments> formatTests() {
return Stream.of(
Arguments.of("Article", "article"),
Arguments.of("Banana", "banana"),
Arguments.of("InBook", "inbook"),
Arguments.of("Aarticle", "aarticle")
);
}
}
| 911 | 29.4 | 71 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java | package org.jabref.logic.layout.format;
import java.util.Collections;
import java.util.stream.Stream;
import org.jabref.logic.layout.ParamLayoutFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FileLinkTest {
private ParamLayoutFormatter fileLinkLayoutFormatter;
@BeforeEach
public void setUp() throws Exception {
fileLinkLayoutFormatter = new FileLink(Collections.emptyList(), "");
}
@ParameterizedTest
@MethodSource("provideFileLinks")
void formatFileLinks(String formattedFileLink, String originalFileLink, String desiredDocType) {
if (!desiredDocType.isEmpty()) {
fileLinkLayoutFormatter.setArgument(desiredDocType);
}
assertEquals(formattedFileLink, fileLinkLayoutFormatter.format(originalFileLink));
}
private static Stream<Arguments> provideFileLinks() {
return Stream.of(
Arguments.of("", "", ""),
Arguments.of("", null, ""),
Arguments.of("test.pdf", "test.pdf", ""),
Arguments.of("test.pdf", "paper:test.pdf:PDF", ""),
Arguments.of("test.pdf", "paper:test.pdf:PDF;presentation:pres.ppt:PPT", ""),
Arguments.of("pres.ppt", "paper:test.pdf:PDF;presentation:pres.ppt:PPT", "ppt"),
Arguments.of("", "paper:test.pdf:PDF;presentation:pres.ppt:PPT", "doc")
);
}
}
| 1,621 | 35.044444 | 100 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/FirstPageTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FirstPageTest {
private LayoutFormatter firstPageLayoutFormatter = new FirstPage();
@ParameterizedTest
@MethodSource("providePages")
void formatPages(String formattedFirstPage, String originalPages) {
assertEquals(formattedFirstPage, firstPageLayoutFormatter.format(originalPages));
}
private static Stream<Arguments> providePages() {
return Stream.of(
Arguments.of("", ""),
Arguments.of("", null),
Arguments.of("345", "345"),
Arguments.of("345", "345-350"),
Arguments.of("345", "345--350")
);
}
}
| 990 | 29.030303 | 89 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HTMLCharsTest {
private LayoutFormatter layout;
@BeforeEach
public void setUp() {
layout = new HTMLChars();
}
@Test
public void testBasicFormat() {
assertEquals("", layout.format(""));
assertEquals("hallo", layout.format("hallo"));
assertEquals("Réflexions sur le timing de la quantité",
layout.format("Réflexions sur le timing de la quantité"));
assertEquals("%%%", layout.format("\\%\\%\\%"));
assertEquals("People remember 10%, 20%…Oh Really?", layout.format("{{People remember 10\\%, 20\\%…Oh Really?}}"));
assertEquals("hállo", layout.format("h\\'allo"));
assertEquals("ı ı", layout.format("\\i \\i"));
assertEquals("ı", layout.format("\\i"));
assertEquals("ı", layout.format("\\{i}"));
assertEquals("ıı", layout.format("\\i\\i"));
assertEquals("ä", layout.format("{\\\"{a}}"));
assertEquals("ä", layout.format("{\\\"a}"));
assertEquals("ä", layout.format("\\\"a"));
assertEquals("Ç", layout.format("{\\c{C}}"));
assertEquals("&Oogon;ı", layout.format("\\k{O}\\i"));
assertEquals("ñ ñ í ı ı", layout.format("\\~{n} \\~n \\'i \\i \\i"));
}
@Test
public void testLaTeXHighlighting() {
assertEquals("<em>hallo</em>", layout.format("\\emph{hallo}"));
assertEquals("<em>hallo</em>", layout.format("{\\emph hallo}"));
assertEquals("<em>hallo</em>", layout.format("{\\em hallo}"));
assertEquals("<i>hallo</i>", layout.format("\\textit{hallo}"));
assertEquals("<i>hallo</i>", layout.format("{\\textit hallo}"));
assertEquals("<i>hallo</i>", layout.format("{\\it hallo}"));
assertEquals("<b>hallo</b>", layout.format("\\textbf{hallo}"));
assertEquals("<b>hallo</b>", layout.format("{\\textbf hallo}"));
assertEquals("<b>hallo</b>", layout.format("{\\bf hallo}"));
assertEquals("<sup>hallo</sup>", layout.format("\\textsuperscript{hallo}"));
assertEquals("<sub>hallo</sub>", layout.format("\\textsubscript{hallo}"));
assertEquals("<u>hallo</u>", layout.format("\\underline{hallo}"));
assertEquals("<s>hallo</s>", layout.format("\\sout{hallo}"));
assertEquals("<tt>hallo</tt>", layout.format("\\texttt{hallo}"));
}
@Test
public void testEquations() {
assertEquals("$", layout.format("\\$"));
assertEquals("σ", layout.format("$\\sigma$"));
assertEquals("A 32 mA ΣΔ-modulator",
layout.format("A 32~{mA} {$\\Sigma\\Delta$}-modulator"));
}
@Test
public void testNewLine() {
assertEquals("a<br>b", layout.format("a\nb"));
assertEquals("a<p>b", layout.format("a\n\nb"));
}
/*
* Is missing a lot of test cases for the individual chars...
*/
@Test
public void testQuoteSingle() {
assertEquals("'", layout.format("{\\textquotesingle}"));
}
@Test
public void unknownCommandIsKept() {
assertEquals("aaaa", layout.format("\\aaaa"));
}
@Test
public void unknownCommandKeepsArgument() {
assertEquals("bbbb", layout.format("\\aaaa{bbbb}"));
}
@Test
public void unknownCommandWithEmptyArgumentIsKept() {
assertEquals("aaaa", layout.format("\\aaaa{}"));
}
}
| 3,716 | 33.416667 | 122 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/HTMLParagraphsTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HTMLParagraphsTest {
LayoutFormatter htmlFormatter = new HTMLParagraphs();
@ParameterizedTest
@MethodSource("htmlFormatTests")
void testCorrectFormat(String expectedString, String inputString) {
assertEquals(expectedString, htmlFormatter.format(inputString));
}
private static Stream<Arguments> htmlFormatTests() {
return Stream.of(
Arguments.of("", ""),
Arguments.of("<p>\nHello\n</p>", "Hello"),
Arguments.of("<p>\nHello\nWorld\n</p>", "Hello\nWorld"),
Arguments.of("<p>\nHello World\n</p>\n<p>\nWhat a lovely day\n</p>", "Hello World\n \nWhat a lovely day\n"),
Arguments.of("<p>\nHello World\n</p>\n<p>\nCould not be any better\n</p>\n<p>\nWhat a lovely day\n</p>", "Hello World\n \n\nCould not be any better\n\nWhat a lovely day\n")
);
}
}
| 1,238 | 36.545455 | 188 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/IfPluralTest.java | package org.jabref.logic.layout.format;
import org.jabref.logic.layout.ParamLayoutFormatter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IfPluralTest {
@Test
public void testStandardUsageOneEditor() {
ParamLayoutFormatter a = new IfPlural();
a.setArgument("Eds.,Ed.");
assertEquals("Ed.", a.format("Bob Bruce"));
}
@Test
public void testStandardUsageTwoEditors() {
ParamLayoutFormatter a = new IfPlural();
a.setArgument("Eds.,Ed.");
assertEquals("Eds.", a.format("Bob Bruce and Jolly Jumper"));
}
@Test
public void testFormatNull() {
ParamLayoutFormatter a = new IfPlural();
a.setArgument("Eds.,Ed.");
assertEquals("", a.format(null));
}
@Test
public void testFormatEmpty() {
ParamLayoutFormatter a = new IfPlural();
a.setArgument("Eds.,Ed.");
assertEquals("", a.format(""));
}
@Test
public void testNoArgumentSet() {
ParamLayoutFormatter a = new IfPlural();
assertEquals("", a.format("Bob Bruce and Jolly Jumper"));
}
@Test
public void testNoProperArgument() {
ParamLayoutFormatter a = new IfPlural();
a.setArgument("Eds.");
assertEquals("", a.format("Bob Bruce and Jolly Jumper"));
}
}
| 1,371 | 25.384615 | 69 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/LastPageTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LastPageTest {
private LayoutFormatter lastPageLayoutFormatter = new LastPage();
@ParameterizedTest
@MethodSource("provideArguments")
void formatLastPage(String formattedText, String originalText) {
assertEquals(formattedText, lastPageLayoutFormatter.format(originalText));
}
private static Stream<Arguments> provideArguments() {
return Stream.of(
Arguments.of("", ""),
Arguments.of("", null),
Arguments.of("345", "345"),
Arguments.of("350", "345-350"),
Arguments.of("350", "345--350"),
Arguments.of("", "--")
);
}
}
| 1,025 | 29.176471 | 82 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/LatexToUnicodeFormatterTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class LatexToUnicodeFormatterTest {
final LatexToUnicodeFormatter formatter = new LatexToUnicodeFormatter();
@Test
void testPlainFormat() {
assertEquals("aaa", formatter.format("aaa"));
}
@Test
void testFormatUmlaut() {
assertEquals("ä", formatter.format("{\\\"{a}}"));
assertEquals("Ä", formatter.format("{\\\"{A}}"));
}
@Test
void preserveUnknownCommand() {
assertEquals("\\mbox{-}", formatter.format("\\mbox{-}"));
}
@Test
void testFormatTextit() {
// See #1464
assertEquals("\uD835\uDC61\uD835\uDC52\uD835\uDC65\uD835\uDC61", formatter.format("\\textit{text}"));
}
@Test
void testEscapedDollarSign() {
assertEquals("$", formatter.format("\\$"));
}
@Test
void testEquationsSingleSymbol() {
assertEquals("σ", formatter.format("$\\sigma$"));
}
@Test
void testEquationsMoreComplicatedFormatting() {
assertEquals("A 32 mA ΣΔ-modulator", formatter.format("A 32~{mA} {$\\Sigma\\Delta$}-modulator"));
}
@Test
void formatExample() {
assertEquals("Mönch", formatter.format(formatter.getExampleInput()));
}
@Test
void testChi() {
// See #1464
assertEquals("χ", formatter.format("$\\chi$"));
}
@Test
void testSWithCaron() {
// Bug #1264
assertEquals("Š", formatter.format("{\\v{S}}"));
}
@Test
void testIWithDiaresis() {
assertEquals("ï", formatter.format("\\\"{i}"));
}
@Test
void testIWithDiaresisAndEscapedI() {
// this might look strange in the test, but is actually a correct translation and renders identically to the above example in the UI
assertEquals("ı̈", formatter.format("\\\"{\\i}"));
}
@Test
void testIWithDiaresisAndUnnecessaryBraces() {
assertEquals("ï", formatter.format("{\\\"{i}}"));
}
@Test
void testUpperCaseIWithDiaresis() {
assertEquals("Ï", formatter.format("\\\"{I}"));
}
@Test
void testPolishName() {
assertEquals("Łęski", formatter.format("\\L\\k{e}ski"));
}
@Test
void testDoubleCombiningAccents() {
assertEquals("ώ", formatter.format("$\\acute{\\omega}$"));
}
@Test
void testCombiningAccentsCase1() {
assertEquals("ḩ", formatter.format("{\\c{h}}"));
}
@Disabled("This is not a standard LaTeX command. It is debatable why we should convert this.")
@Test
void testCombiningAccentsCase2() {
assertEquals("a͍", formatter.format("\\spreadlips{a}"));
}
@Test
void keepUnknownCommandWithoutArgument() {
assertEquals("\\aaaa", formatter.format("\\aaaa"));
}
@Test
void keepUnknownCommandWithArgument() {
assertEquals("\\aaaa{bbbb}", formatter.format("\\aaaa{bbbb}"));
}
@Test
void keepUnknownCommandWithEmptyArgument() {
assertEquals("\\aaaa{}", formatter.format("\\aaaa{}"));
}
@Test
void testTildeN() {
assertEquals("Montaña", formatter.format("Monta\\~{n}a"));
}
@Test
void testAcuteNLongVersion() {
assertEquals("Maliński", formatter.format("Mali\\'{n}ski"));
assertEquals("MaliŃski", formatter.format("Mali\\'{N}ski"));
}
@Test
void testAcuteNShortVersion() {
assertEquals("Maliński", formatter.format("Mali\\'nski"));
assertEquals("MaliŃski", formatter.format("Mali\\'Nski"));
}
@Test
void testApostrophN() {
assertEquals("Mali'nski", formatter.format("Mali'nski"));
assertEquals("Mali'Nski", formatter.format("Mali'Nski"));
}
@Test
void testApostrophO() {
assertEquals("L'oscillation", formatter.format("L'oscillation"));
}
@Test
void testApostrophC() {
assertEquals("O'Connor", formatter.format("O'Connor"));
}
@Test
void testPreservationOfSingleUnderscore() {
assertEquals("Lorem ipsum_lorem ipsum", formatter.format("Lorem ipsum_lorem ipsum"));
}
@Test
void testConversionOfUnderscoreWithBraces() {
assertEquals("Lorem ipsum_(lorem ipsum)", formatter.format("Lorem ipsum_{lorem ipsum}"));
}
@Test
void testConversionOfOrdinal1st() {
assertEquals("1ˢᵗ", formatter.format("1\\textsuperscript{st}"));
}
@Test
void testConversionOfOrdinal2nd() {
assertEquals("2ⁿᵈ", formatter.format("2\\textsuperscript{nd}"));
}
@Test
void testConversionOfOrdinal3rd() {
assertEquals("3ʳᵈ", formatter.format("3\\textsuperscript{rd}"));
}
@Test
void testConversionOfOrdinal4th() {
assertEquals("4ᵗʰ", formatter.format("4\\textsuperscript{th}"));
}
@Test
void testConversionOfOrdinal9th() {
assertEquals("9ᵗʰ", formatter.format("9\\textsuperscript{th}"));
}
}
| 5,027 | 25.324607 | 140 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/MarkdownFormatterTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
class MarkdownFormatterTest {
private MarkdownFormatter markdownFormatter;
@BeforeEach
void setUp() {
markdownFormatter = new MarkdownFormatter();
}
@Test
void formatWhenFormattingPlainTextThenReturnsTextWrappedInParagraph() {
assertEquals("<p>Hello World</p>", markdownFormatter.format("Hello World"));
}
@Test
void formatWhenFormattingComplexMarkupThenReturnsOnlyOneLine() {
assertFalse(markdownFormatter.format("Markup\n\n* list item one\n* list item 2\n\n rest").contains("\n"));
}
@Test
void formatWhenFormattingEmptyStringThenReturnsEmptyString() {
assertEquals("", markdownFormatter.format(""));
}
@Test
void formatWhenFormattingNullThenThrowsException() {
Exception exception = assertThrows(NullPointerException.class, () -> markdownFormatter.format(null));
assertEquals("Field Text should not be null, when handed to formatter", exception.getMessage());
}
}
| 1,286 | 31.175 | 114 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/NameFormatterTest.java | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class NameFormatterTest {
@Test
public void testFormatStringStringBibtexEntry() {
NameFormatter l = new NameFormatter();
assertEquals("Doe", l.format("Joe Doe", "1@*@{ll}"));
assertEquals("moremoremoremore", l.format("Joe Doe and Mary Jane and Bruce Bar and Arthur Kay",
"1@*@{ll}@@2@1..1@{ff}{ll}@2..2@ and {ff}{last}@@*@*@more"));
assertEquals("Doe", l.format("Joe Doe", "1@*@{ll}@@2@1..1@{ff}{ll}@2..2@ and {ff}{last}@@*@*@more"));
assertEquals("JoeDoe and MaryJ",
l.format("Joe Doe and Mary Jane", "1@*@{ll}@@2@1..1@{ff}{ll}@2..2@ and {ff}{l}@@*@*@more"));
assertEquals("Doe, Joe and Jane, M. and Kamp, J.~A.",
l.format("Joe Doe and Mary Jane and John Arthur van Kamp",
"1@*@{ll}, {ff}@@*@1@{ll}, {ff}@2..-1@ and {ll}, {f}."));
assertEquals("Doe Joe and Jane, M. and Kamp, J.~A.",
l.format("Joe Doe and Mary Jane and John Arthur van Kamp",
"1@*@{ll}, {ff}@@*@1@{ll} {ff}@2..-1@ and {ll}, {f}."));
}
@Test
public void testFormat() {
NameFormatter a = new NameFormatter();
// Empty case
assertEquals("", a.format(""));
String formatString = "1@1@{vv }{ll}{ ff}@@2@1@{vv }{ll}{ ff}@2@ and {vv }{ll}{, ff}@@*@1@{vv }{ll}{ ff}@2..-2@, {vv }{ll}{, ff}@-1@ and {vv }{ll}{, ff}";
// Single Names
assertEquals("Vandekamp Mary~Ann", a.format("Mary Ann Vandekamp", formatString));
// Two names
assertEquals("von Neumann John and Black~Brown, Peter",
a.format("John von Neumann and Black Brown, Peter", formatString));
// Three names
assertEquals("von Neumann John, Smith, John and Black~Brown, Peter",
a.format("von Neumann, John and Smith, John and Black Brown, Peter", formatString));
assertEquals("von Neumann John, Smith, John and Black~Brown, Peter",
a.format("John von Neumann and John Smith and Black Brown, Peter", formatString));
// Four names
assertEquals("von Neumann John, Smith, John, Vandekamp, Mary~Ann and Black~Brown, Peter", a.format(
"von Neumann, John and Smith, John and Vandekamp, Mary Ann and Black Brown, Peter", formatString));
}
}
| 2,471 | 40.2 | 162 | java |
null | jabref-main/src/test/java/org/jabref/logic/layout/format/NoSpaceBetweenAbbreviationsTest.java | package org.jabref.logic.layout.format;
import java.util.stream.Stream;
import org.jabref.logic.layout.LayoutFormatter;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class NoSpaceBetweenAbbreviationsTest {
private LayoutFormatter nsbaLayoutFormatter = new NoSpaceBetweenAbbreviations();
@ParameterizedTest
@MethodSource("provideAbbreviations")
void formatAbbreviations(String formattedAbbreviation, String originalAbbreviation) {
assertEquals(formattedAbbreviation, nsbaLayoutFormatter.format(originalAbbreviation));
}
private static Stream<Arguments> provideAbbreviations() {
return Stream.of(
Arguments.of("", ""),
Arguments.of("John Meier", "John Meier"),
Arguments.of("J.F. Kennedy", "J. F. Kennedy"),
Arguments.of("J.R.R. Tolkien", "J. R. R. Tolkien"),
Arguments.of("J.R.R. Tolkien and J.F. Kennedy", "J. R. R. Tolkien and J. F. Kennedy")
);
}
}
| 1,171 | 34.515152 | 101 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.