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/main/java/org/jabref/preferences/WorkspacePreferences.java | package org.jabref.preferences;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import org.jabref.gui.theme.Theme;
import org.jabref.logic.l10n.Language;
public class WorkspacePreferences {
private final ObjectProperty<Language> language;
private final BooleanProperty shouldOverrideDefaultFontSize;
private final IntegerProperty mainFontSize;
private final IntegerProperty defaultFontSize;
private final ObjectProperty<Theme> theme;
private final BooleanProperty shouldOpenLastEdited;
private final BooleanProperty showAdvancedHints;
private final BooleanProperty warnAboutDuplicatesInInspection;
private final BooleanProperty confirmDelete;
public WorkspacePreferences(Language language,
boolean shouldOverrideDefaultFontSize,
int mainFontSize,
int defaultFontSize,
Theme theme,
boolean shouldOpenLastEdited,
boolean showAdvancedHints,
boolean warnAboutDuplicatesInInspection,
boolean confirmDelete) {
this.language = new SimpleObjectProperty<>(language);
this.shouldOverrideDefaultFontSize = new SimpleBooleanProperty(shouldOverrideDefaultFontSize);
this.mainFontSize = new SimpleIntegerProperty(mainFontSize);
this.defaultFontSize = new SimpleIntegerProperty(defaultFontSize);
this.theme = new SimpleObjectProperty<>(theme);
this.shouldOpenLastEdited = new SimpleBooleanProperty(shouldOpenLastEdited);
this.showAdvancedHints = new SimpleBooleanProperty(showAdvancedHints);
this.warnAboutDuplicatesInInspection = new SimpleBooleanProperty(warnAboutDuplicatesInInspection);
this.confirmDelete = new SimpleBooleanProperty(confirmDelete);
}
public Language getLanguage() {
return language.get();
}
public ObjectProperty<Language> languageProperty() {
return language;
}
public void setLanguage(Language language) {
this.language.set(language);
}
public boolean shouldOverrideDefaultFontSize() {
return shouldOverrideDefaultFontSize.get();
}
public void setShouldOverrideDefaultFontSize(boolean newValue) {
shouldOverrideDefaultFontSize.set(newValue);
}
public BooleanProperty shouldOverrideDefaultFontSizeProperty() {
return shouldOverrideDefaultFontSize;
}
public int getMainFontSize() {
return mainFontSize.get();
}
public int getDefaultFontSize() {
return defaultFontSize.get();
}
public void setMainFontSize(int mainFontSize) {
this.mainFontSize.set(mainFontSize);
}
public IntegerProperty mainFontSizeProperty() {
return mainFontSize;
}
public Theme getTheme() {
return theme.get();
}
public void setTheme(Theme theme) {
this.theme.set(theme);
}
public ObjectProperty<Theme> themeProperty() {
return theme;
}
public boolean shouldOpenLastEdited() {
return shouldOpenLastEdited.get();
}
public BooleanProperty openLastEditedProperty() {
return shouldOpenLastEdited;
}
public void setOpenLastEdited(boolean shouldOpenLastEdited) {
this.shouldOpenLastEdited.set(shouldOpenLastEdited);
}
public boolean shouldShowAdvancedHints() {
return showAdvancedHints.get();
}
public BooleanProperty showAdvancedHintsProperty() {
return showAdvancedHints;
}
public void setShowAdvancedHints(boolean showAdvancedHints) {
this.showAdvancedHints.set(showAdvancedHints);
}
public boolean shouldWarnAboutDuplicatesInInspection() {
return warnAboutDuplicatesInInspection.get();
}
public BooleanProperty warnAboutDuplicatesInInspectionProperty() {
return warnAboutDuplicatesInInspection;
}
public void setWarnAboutDuplicatesInInspection(boolean warnAboutDuplicatesInInspection) {
this.warnAboutDuplicatesInInspection.set(warnAboutDuplicatesInInspection);
}
public boolean shouldConfirmDelete() {
return confirmDelete.get();
}
public BooleanProperty confirmDeleteProperty() {
return confirmDelete;
}
public void setConfirmDelete(boolean confirmDelete) {
this.confirmDelete.set(confirmDelete);
}
}
| 4,723 | 31.805556 | 106 | java |
null | jabref-main/src/test/java/org/jabref/IconsPropertiesTest.java | package org.jabref;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;
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 IconsPropertiesTest {
@Test
public void testExistenceOfIconImagesReferencedFromIconsProperties() throws IOException {
String folder = "src/main/resources/images/external";
String iconsProperties = "Icons.properties";
String iconsPropertiesPath = "src/main/resources/images/" + iconsProperties;
// load properties
Properties properties = new Properties();
try (Reader reader = Files.newBufferedReader(Path.of(iconsPropertiesPath))) {
properties.load(reader);
}
assertFalse(properties.entrySet().isEmpty(), "There must be loaded properties after loading " + iconsPropertiesPath);
// check that each key references an existing file
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String name = entry.getKey().toString();
String value = entry.getValue().toString();
assertTrue(Files.exists(Path.of(folder, value)), "Referenced image (" + name + " --> " + value + " does not exist in folder " + folder);
}
// check that each image in the folder is referenced by a key
List<String> imagesReferencedFromProperties = new ArrayList<>();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
imagesReferencedFromProperties.add(entry.getValue().toString());
}
try (Stream<Path> pathStream = Files.list(Path.of(folder))) {
List<String> fileNamesInFolder = pathStream.map(p -> p.getFileName().toString()).collect(Collectors.toList());
fileNamesInFolder.removeAll(imagesReferencedFromProperties);
assertEquals("[red.png]", fileNamesInFolder.toString(), "Images are in the folder that are unused");
}
}
}
| 2,294 | 39.982143 | 148 | java |
null | jabref-main/src/test/java/org/jabref/architecture/MainArchitectureTest.java | package org.jabref.architecture;
import java.nio.file.Paths;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchIgnore;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.library.GeneralCodingRules;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
/**
* This class checks JabRef's shipped classes for architecture quality
*/
@AnalyzeClasses(packages = "org.jabref")
class MainArchitectureTest {
public static final String CLASS_ORG_JABREF_GLOBALS = "org.jabref.gui.Globals";
private static final String PACKAGE_JAVAX_SWING = "javax.swing..";
private static final String PACKAGE_JAVA_AWT = "java.awt..";
private static final String PACKAGE_ORG_JABREF_GUI = "org.jabref.gui..";
private static final String PACKAGE_ORG_JABREF_LOGIC = "org.jabref.logic..";
private static final String PACKAGE_ORG_JABREF_MODEL = "org.jabref.model..";
private static final String PACKAGE_ORG_JABREF_CLI = "org.jabref.cli..";
@ArchTest
public static void doNotUseApacheCommonsLang3(JavaClasses classes) {
noClasses().that().areNotAnnotatedWith(ApacheCommonsLang3Allowed.class)
.should().accessClassesThat().resideInAPackage("org.apache.commons.lang3")
.check(classes);
}
@ArchTest
public static void doNotUseSwing(JavaClasses classes) {
// This checks for all Swing packages, but not the UndoManager
noClasses().that().areNotAnnotatedWith(AllowedToUseSwing.class)
.should().accessClassesThat()
.resideInAnyPackage("javax.swing",
"javax.swing.border..",
"javax.swing.colorchooser..",
"javax.swing.event..",
"javax.swing.filechooser..",
"javax.swing.plaf..",
"javax.swing.table..",
"javax.swing.text..",
"javax.swing.tree..")
.check(classes);
}
@ArchTest
public static void doNotUseAssertJ(JavaClasses classes) {
noClasses().should().accessClassesThat().resideInAPackage("org.assertj..")
.check(classes);
}
@ArchTest
public static void doNotUseJavaAWT(JavaClasses classes) {
noClasses().that().areNotAnnotatedWith(AllowedToUseAwt.class)
.should().accessClassesThat().resideInAPackage(PACKAGE_JAVA_AWT)
.check(classes);
}
@ArchTest
public static void doNotUsePaths(JavaClasses classes) {
noClasses().should()
.accessClassesThat()
.belongToAnyOf(Paths.class)
.because("Path.of(...) should be used instead")
.check(classes);
}
@ArchTest
@ArchIgnore
// Fails currently
public static void respectLayeredArchitecture(JavaClasses classes) {
layeredArchitecture().consideringOnlyDependenciesInLayers()
.layer("Gui").definedBy(PACKAGE_ORG_JABREF_GUI)
.layer("Logic").definedBy(PACKAGE_ORG_JABREF_LOGIC)
.layer("Model").definedBy(PACKAGE_ORG_JABREF_MODEL)
.layer("Cli").definedBy(PACKAGE_ORG_JABREF_CLI)
.layer("Migrations").definedBy("org.jabref.migrations..") // TODO: Move to logic
.layer("Preferences").definedBy("org.jabref.preferences..")
.layer("Styletester").definedBy("org.jabref.styletester..")
.whereLayer("Gui").mayOnlyBeAccessedByLayers("Preferences", "Cli") // TODO: Remove preferences here
.whereLayer("Logic").mayOnlyBeAccessedByLayers("Gui", "Cli", "Model", "Migrations", "Preferences")
.whereLayer("Model").mayOnlyBeAccessedByLayers("Gui", "Logic", "Migrations", "Cli", "Preferences")
.whereLayer("Cli").mayNotBeAccessedByAnyLayer()
.whereLayer("Migrations").mayOnlyBeAccessedByLayers("Logic")
.whereLayer("Preferences").mayOnlyBeAccessedByLayers("Gui", "Logic", "Migrations", "Styletester", "Cli") // TODO: Remove logic here
.check(classes);
}
@ArchTest
public static void doNotUseLogicInModel(JavaClasses classes) {
noClasses().that().resideInAPackage(PACKAGE_ORG_JABREF_MODEL)
.and().areNotAnnotatedWith(AllowedToUseLogic.class)
.should().dependOnClassesThat().resideInAPackage(PACKAGE_ORG_JABREF_LOGIC)
.check(classes);
}
@ArchTest
public static void restrictUsagesInModel(JavaClasses classes) {
// Until we switch to Lucene, we need to access Globals.stateManager().getActiveDatabase() from the search classes,
// because the PDFSearch needs to access the index of the corresponding database
noClasses().that().areNotAssignableFrom("org.jabref.model.search.rules.ContainBasedSearchRule")
.and().areNotAssignableFrom("org.jabref.model.search.rules.RegexBasedSearchRule")
.and().areNotAssignableFrom("org.jabref.model.search.rules.GrammarBasedSearchRule")
.and().resideInAPackage(PACKAGE_ORG_JABREF_MODEL)
.should().dependOnClassesThat().resideInAPackage(PACKAGE_JAVAX_SWING)
.orShould().dependOnClassesThat().haveFullyQualifiedName(CLASS_ORG_JABREF_GLOBALS)
.check(classes);
}
@ArchTest
public static void restrictUsagesInLogic(JavaClasses classes) {
noClasses().that().resideInAPackage(PACKAGE_ORG_JABREF_LOGIC)
.and().areNotAnnotatedWith(AllowedToUseSwing.class)
.should().dependOnClassesThat().resideInAPackage(PACKAGE_JAVAX_SWING)
.orShould().dependOnClassesThat().haveFullyQualifiedName(CLASS_ORG_JABREF_GLOBALS)
.check(classes);
}
@ArchTest
public static void restrictStandardStreams(JavaClasses classes) {
noClasses().that().resideOutsideOfPackages(PACKAGE_ORG_JABREF_CLI)
.and().resideOutsideOfPackages("org.jabref.gui.openoffice..") // Uses LibreOffice SDK
.and().areNotAnnotatedWith(AllowedToUseStandardStreams.class)
.should(GeneralCodingRules.ACCESS_STANDARD_STREAMS)
.because("logging framework should be used instead or the class be marked explicitly as @AllowedToUseStandardStreams")
.check(classes);
}
}
| 6,991 | 50.036496 | 160 | java |
null | jabref-main/src/test/java/org/jabref/architecture/TestArchitectureTest.java | package org.jabref.architecture;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static org.jabref.architecture.MainArchitectureTest.CLASS_ORG_JABREF_GLOBALS;
/**
* This class checks JabRef's test classes for architecture quality
*/
@AnalyzeClasses(packages = "org.jabref", importOptions = ImportOption.OnlyIncludeTests.class)
public class TestArchitectureTest {
private static final String CLASS_ORG_JABREF_PREFERENCES = "org.jabref.preferences.JabRefPreferences";
@ArchTest
public void testsAreIndependent(JavaClasses classes) {
noClasses().that().doNotHaveSimpleName("EntryEditorTest")
.and().doNotHaveSimpleName("LinkedFileViewModelTest")
.and().doNotHaveSimpleName("JabRefPreferencesTest")
.and().doNotHaveSimpleName("PreferencesMigrationsTest")
.and().doNotHaveSimpleName("SaveDatabaseActionTest")
.and().doNotHaveSimpleName("UpdateTimestampListenerTest")
.and().doNotHaveFullyQualifiedName("org.jabref.benchmarks.Benchmarks")
.and().doNotHaveFullyQualifiedName("org.jabref.testutils.interactive.styletester.StyleTesterMain")
.should().dependOnClassesThat().haveFullyQualifiedName(CLASS_ORG_JABREF_GLOBALS)
.orShould().dependOnClassesThat().haveFullyQualifiedName(CLASS_ORG_JABREF_PREFERENCES)
.check(classes);
}
@ArchTest
public void testNaming(JavaClasses classes) {
classes().that().areTopLevelClasses()
.and().doNotHaveFullyQualifiedName("org.jabref.benchmarks.Benchmarks")
.and().doNotHaveFullyQualifiedName("org.jabref.gui.autocompleter.AutoCompleterUtil")
.and().doNotHaveFullyQualifiedName("org.jabref.gui.search.TextFlowEqualityHelper")
.and().doNotHaveFullyQualifiedName("org.jabref.logic.bibtex.BibEntryAssert")
.and().doNotHaveFullyQualifiedName("org.jabref.logic.importer.fileformat.ImporterTestEngine")
.and().doNotHaveFullyQualifiedName("org.jabref.logic.l10n.JavaLocalizationEntryParser")
.and().doNotHaveFullyQualifiedName("org.jabref.logic.l10n.LocalizationEntry")
.and().doNotHaveFullyQualifiedName("org.jabref.logic.l10n.LocalizationParser")
.and().doNotHaveFullyQualifiedName("org.jabref.logic.openoffice.style.OOBibStyleTestHelper")
.and().doNotHaveFullyQualifiedName("org.jabref.logic.shared.TestManager")
.and().doNotHaveFullyQualifiedName("org.jabref.model.search.rules.MockSearchMatcher")
.and().doNotHaveFullyQualifiedName("org.jabref.model.TreeNodeTestData")
.and().doNotHaveFullyQualifiedName("org.jabref.performance.BibtexEntryGenerator")
.and().doNotHaveFullyQualifiedName("org.jabref.support.DisabledOnCIServer")
.and().doNotHaveFullyQualifiedName("org.jabref.support.CIServerCondition")
.and().doNotHaveFullyQualifiedName("org.jabref.testutils.interactive.styletester.StyleTesterMain")
.and().doNotHaveFullyQualifiedName("org.jabref.testutils.interactive.styletester.StyleTesterView")
.should().haveSimpleNameEndingWith("Test")
.check(classes);
}
}
| 3,667 | 61.169492 | 117 | java |
null | jabref-main/src/test/java/org/jabref/cli/ArgumentProcessorTest.java | package org.jabref.cli;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import javafx.collections.FXCollections;
import org.jabref.cli.ArgumentProcessor.Mode;
import org.jabref.logic.bibtex.BibEntryAssert;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ImporterPreferences;
import org.jabref.logic.importer.fileformat.BibtexImporter;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SearchPreferences;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ArgumentProcessorTest {
private ArgumentProcessor processor;
private BibtexImporter bibtexImporter;
private final PreferencesService preferencesService = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS);
private final ImporterPreferences importerPreferences = mock(ImporterPreferences.class, Answers.RETURNS_DEEP_STUBS);
private final ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
@BeforeEach()
void setup() {
when(importerPreferences.getCustomImporters()).thenReturn(FXCollections.emptyObservableSet());
when(preferencesService.getSearchPreferences()).thenReturn(
new SearchPreferences(null, EnumSet.noneOf(SearchRules.SearchFlags.class), false)
);
bibtexImporter = new BibtexImporter(importFormatPreferences, new DummyFileUpdateMonitor());
}
@Test
void testAuxImport(@TempDir Path tempDir) throws Exception {
String auxFile = Path.of(AuxCommandLineTest.class.getResource("paper.aux").toURI()).toAbsolutePath().toString();
String originBib = Path.of(AuxCommandLineTest.class.getResource("origin.bib").toURI()).toAbsolutePath().toString();
Path outputBib = tempDir.resolve("output.bisb").toAbsolutePath();
String outputBibFile = outputBib.toAbsolutePath().toString();
List<String> args = List.of("--nogui", "--debug", "--aux", auxFile + "," + outputBibFile, originBib);
processor = new ArgumentProcessor(
args.toArray(String[]::new),
Mode.INITIAL_START,
preferencesService,
mock(FileUpdateMonitor.class));
assertTrue(Files.exists(outputBib));
}
@Test
void testExportMatches(@TempDir Path tempDir) throws Exception {
Path originBib = Path.of(Objects.requireNonNull(ArgumentProcessorTest.class.getResource("origin.bib")).toURI());
String originBibFile = originBib.toAbsolutePath().toString();
Path expectedBib = Path.of(
Objects.requireNonNull(ArgumentProcessorTest.class.getResource("ArgumentProcessorTestExportMatches.bib"))
.toURI()
);
List<BibEntry> expectedEntries = bibtexImporter.importDatabase(expectedBib).getDatabase().getEntries();
Path outputBib = tempDir.resolve("output.bib").toAbsolutePath();
String outputBibFile = outputBib.toAbsolutePath().toString();
List<String> args = List.of("-n", "--debug", "--exportMatches", "Author=Einstein," + outputBibFile, originBibFile);
processor = new ArgumentProcessor(
args.toArray(String[]::new),
Mode.INITIAL_START,
preferencesService,
mock(FileUpdateMonitor.class));
assertTrue(Files.exists(outputBib));
BibEntryAssert.assertEquals(expectedEntries, outputBib, bibtexImporter);
}
}
| 3,989 | 40.5625 | 132 | java |
null | jabref-main/src/test/java/org/jabref/cli/AuxCommandLineTest.java | package org.jabref.cli;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.model.database.BibDatabase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
public class AuxCommandLineTest {
private ImportFormatPreferences importFormatPreferences;
@BeforeEach
public void setUp() throws Exception {
importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
}
@Test
public void test() throws URISyntaxException, IOException {
InputStream originalStream = AuxCommandLineTest.class.getResourceAsStream("origin.bib");
File auxFile = Path.of(AuxCommandLineTest.class.getResource("paper.aux").toURI()).toFile();
try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) {
ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader);
AuxCommandLine auxCommandLine = new AuxCommandLine(auxFile.getAbsolutePath(), result.getDatabase());
BibDatabase newDB = auxCommandLine.perform();
assertNotNull(newDB);
assertEquals(2, newDB.getEntries().size());
}
}
}
| 1,747 | 35.416667 | 112 | java |
null | jabref-main/src/test/java/org/jabref/cli/JabRefCLITest.java | package org.jabref.cli;
import java.util.Collections;
import java.util.List;
import javafx.util.Pair;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JabRefCLITest {
private final String bibtex = "@article{test, title=\"test title\"}";
@Test
void emptyCLILeftOversLongOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"});
assertEquals(Collections.emptyList(), cli.getLeftOver());
}
@Test
void guiIsDisabledLongOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"});
assertTrue(cli.isDisableGui());
}
@Test
void successfulParsingOfFileImportCLILongOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"});
assertEquals("some/file", cli.getFileImport());
}
@Test
void successfulParsingOfFileExportCLILongOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"--nogui", "--import=some/file", "--output=some/export/file"});
assertEquals("some/export/file", cli.getFileExport());
}
@Test
void emptyCLILeftOversShortOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"});
assertEquals(Collections.emptyList(), cli.getLeftOver());
}
@Test
void guiIsDisabledShortOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"});
assertTrue(cli.isDisableGui());
}
@Test
void successfulParsingOfFileImportShortOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"});
assertEquals("some/file", cli.getFileImport());
}
@Test
void successfulParsingOfFileExportShortOptions() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-i=some/file", "-o=some/export/file"});
assertEquals("some/export/file", cli.getFileExport());
}
@Test
void emptyPreferencesLeftOver() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-x=some/file"});
assertEquals(Collections.emptyList(), cli.getLeftOver());
}
@Test
void successfulExportOfPreferences() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-x=some/file"});
assertEquals("some/file", cli.getPreferencesExport());
}
@Test
void guiDisabledForPreferencesExport() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-n", "-x=some/file"});
assertTrue(cli.isDisableGui());
}
@Test
void emptyLeftOversCLIShortImportingBibtex() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-ib", bibtex});
assertEquals(Collections.emptyList(), cli.getLeftOver());
}
@Test
void recognizesImportBibtexShort() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-ib", bibtex});
assertTrue(cli.isBibtexImport());
}
@Test
void successfulParsingOfBibtexImportShort() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-ib", bibtex});
assertEquals(bibtex, cli.getBibtexImport());
}
@Test
void emptyLeftOversCLILongImportingBibtex() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-importBibtex", bibtex});
assertEquals(Collections.emptyList(), cli.getLeftOver());
}
@Test
void recognizesImportBibtexLong() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-importBibtex", bibtex});
assertTrue(cli.isBibtexImport());
}
@Test
void successfulParsingOfBibtexImportLong() throws Exception {
JabRefCLI cli = new JabRefCLI(new String[]{"-importBibtex", bibtex});
assertEquals(bibtex, cli.getBibtexImport());
}
@Test
void wrapStringList() {
List<String> given = List.of("html", "simplehtml", "docbook5", "docbook4", "din1505", "bibordf", "tablerefs", "listrefs",
"tablerefsabsbib", "harvard", "iso690rtf", "iso690txt", "endnote", "oocsv", "ris", "misq", "yaml", "bibtexml", "oocalc", "ods",
"MSBib", "mods", "xmp", "pdf", "bib");
String expected = """
Available export formats: html, simplehtml, docbook5, docbook4, din1505, bibordf, tablerefs,
listrefs, tablerefsabsbib, harvard, iso690rtf, iso690txt, endnote, oocsv, ris, misq, yaml, bibtexml,
oocalc, ods, MSBib, mods, xmp, pdf, bib""";
assertEquals(expected, "Available export formats: " + JabRefCLI.wrapStringList(given, 26));
}
@Test
void alignStringTable() {
List<Pair<String, String>> given = List.of(
new Pair<>("Apple", "Slice"),
new Pair<>("Bread", "Loaf"),
new Pair<>("Paper", "Sheet"),
new Pair<>("Country", "County"));
String expected = """
Apple : Slice
Bread : Loaf
Paper : Sheet
Country : County
""";
assertEquals(expected, JabRefCLI.alignStringTable(given));
}
}
| 5,530 | 32.11976 | 143 | java |
null | jabref-main/src/test/java/org/jabref/gui/UpdateTimestampListenerTest.java | package org.jabref.gui;
import java.util.Optional;
import org.jabref.logic.preferences.TimestampPreferences;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.preferences.PreferencesService;
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;
class UpdateTimestampListenerTest {
private BibDatabase database;
private BibEntry bibEntry;
private PreferencesService preferencesMock;
private TimestampPreferences timestampPreferencesMock;
private final String baseDate = "2000-1-1";
private final String newDate = "2000-1-2";
@BeforeEach
void setUp() {
database = new BibDatabase();
bibEntry = new BibEntry();
database.insertEntry(bibEntry);
preferencesMock = mock(PreferencesService.class);
timestampPreferencesMock = mock(TimestampPreferences.class);
when(preferencesMock.getTimestampPreferences()).thenReturn(timestampPreferencesMock);
}
@Test
void updateTimestampEnabled() {
final boolean includeTimestamp = true;
when(timestampPreferencesMock.now()).thenReturn(newDate);
when(timestampPreferencesMock.shouldAddModificationDate()).thenReturn(includeTimestamp);
bibEntry.setField(StandardField.MODIFICATIONDATE, baseDate);
assertEquals(Optional.of(baseDate), bibEntry.getField(StandardField.MODIFICATIONDATE), "Initial timestamp not set correctly");
database.registerListener(new UpdateTimestampListener(preferencesMock));
bibEntry.setField(new UnknownField("test"), "some value");
assertEquals(Optional.of(newDate), bibEntry.getField(StandardField.MODIFICATIONDATE), "Timestamp not set correctly after entry changed");
}
@Test
void updateTimestampDisabled() {
final boolean includeTimestamp = false;
when(timestampPreferencesMock.now()).thenReturn(newDate);
when(timestampPreferencesMock.shouldAddModificationDate()).thenReturn(includeTimestamp);
bibEntry.setField(StandardField.MODIFICATIONDATE, baseDate);
assertEquals(Optional.of(baseDate), bibEntry.getField(StandardField.MODIFICATIONDATE), "Initial timestamp not set correctly");
database.registerListener(new UpdateTimestampListener(preferencesMock));
bibEntry.setField(new UnknownField("test"), "some value");
assertEquals(Optional.of(baseDate), bibEntry.getField(StandardField.MODIFICATIONDATE), "New timestamp set after entry changed even though updates were disabled");
}
}
| 2,816 | 34.658228 | 170 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/AppendPersonNamesStrategyTest.java | package org.jabref.gui.autocompleter;
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 AppendPersonNamesStrategyTest {
@Test
void testWithoutParam() {
AppendPersonNamesStrategy strategy = new AppendPersonNamesStrategy();
assertEquals(" and ", strategy.getDelimiter());
}
@ParameterizedTest(name = "separationBySpace={0}, expectedResult={1}")
@CsvSource({
"TRUE, ' '",
"FALSE, ' and '",
})
void testWithParam(boolean separationBySpace, String expectedResult) {
AppendPersonNamesStrategy strategy = new AppendPersonNamesStrategy(separationBySpace);
assertEquals(expectedResult, strategy.getDelimiter());
}
}
| 862 | 30.962963 | 94 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/AutoCompleterUtil.java | package org.jabref.gui.autocompleter;
import org.controlsfx.control.textfield.AutoCompletionBinding;
public class AutoCompleterUtil {
public static AutoCompletionBinding.ISuggestionRequest getRequest(String text) {
return new AutoCompletionBinding.ISuggestionRequest() {
@Override
public boolean isCancelled() {
return false;
}
@Override
public String getUserText() {
return text;
}
};
}
}
| 521 | 25.1 | 84 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/BibEntrySuggestionProviderTest.java | package org.jabref.gui.autocompleter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.jabref.gui.autocompleter.AutoCompleterUtil.getRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class BibEntrySuggestionProviderTest {
private BibEntrySuggestionProvider autoCompleter;
private BibDatabase database;
@BeforeEach
void setUp() throws Exception {
database = new BibDatabase();
autoCompleter = new BibEntrySuggestionProvider(database);
}
@Test
void completeWithoutAddingAnythingReturnsNothing() {
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeAfterAddingEmptyEntryReturnsNothing() {
BibEntry entry = new BibEntry();
database.insertEntry(entry);
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeKeyReturnsKey() {
BibEntry entry = new BibEntry();
entry.setCitationKey("testKey");
database.insertEntry(entry);
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest("testKey"));
assertEquals(Collections.singletonList(entry), result);
}
@Test
void completeBeginningOfKeyReturnsKey() {
BibEntry entry = new BibEntry();
entry.setCitationKey("testKey");
database.insertEntry(entry);
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.singletonList(entry), result);
}
@Test
void completeLowercaseKeyReturnsKey() {
BibEntry entry = new BibEntry();
entry.setCitationKey("testKey");
database.insertEntry(entry);
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest("testkey"));
assertEquals(Collections.singletonList(entry), result);
}
@Test
void completeNullThrowsException() {
BibEntry entry = new BibEntry();
entry.setCitationKey("testKey");
database.insertEntry(entry);
assertThrows(NullPointerException.class, () -> autoCompleter.provideSuggestions(getRequest(null)));
}
@Test
void completeEmptyStringReturnsNothing() {
BibEntry entry = new BibEntry();
entry.setCitationKey("testKey");
database.insertEntry(entry);
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest(""));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeReturnsMultipleResults() {
BibEntry entryOne = new BibEntry();
entryOne.setCitationKey("testKeyOne");
database.insertEntry(entryOne);
BibEntry entryTwo = new BibEntry();
entryTwo.setCitationKey("testKeyTwo");
database.insertEntry(entryTwo);
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest("testKey"));
assertEquals(Arrays.asList(entryTwo, entryOne), result);
}
@Test
void completeShortKeyReturnsKey() {
BibEntry entry = new BibEntry();
entry.setCitationKey("key");
database.insertEntry(entry);
Collection<BibEntry> result = autoCompleter.provideSuggestions(getRequest("k"));
assertEquals(Collections.singletonList(entry), result);
}
}
| 3,731 | 31.452174 | 107 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/ContentSelectorSuggestionProviderTest.java | package org.jabref.gui.autocompleter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
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.jabref.gui.autocompleter.AutoCompleterUtil.getRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ContentSelectorSuggestionProviderTest {
private ContentSelectorSuggestionProvider autoCompleter;
@Test
void completeWithoutAddingAnythingReturnsNothing() {
SuggestionProvider<String> suggestionProvider = new EmptySuggestionProvider();
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Collections.emptyList());
Collection<String> expected = Collections.emptyList();
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(expected, result);
}
@Test
void completeKeywordReturnsKeyword() {
SuggestionProvider<String> suggestionProvider = new EmptySuggestionProvider();
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Collections.singletonList("test"));
Collection<String> expected = Collections.singletonList("test");
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(expected, result);
}
@Test
void completeBeginningOfKeywordReturnsKeyword() {
SuggestionProvider<String> suggestionProvider = new EmptySuggestionProvider();
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Collections.singletonList("test"));
Collection<String> expected = Collections.singletonList("test");
Collection<String> result = autoCompleter.provideSuggestions(getRequest("te"));
assertEquals(expected, result);
}
@Test
void completeKeywordReturnsKeywordFromDatabase() {
BibDatabase database = new BibDatabase();
BibEntry bibEntry = new BibEntry();
bibEntry.addKeyword("test", ',');
database.insertEntry(bibEntry);
SuggestionProvider<String> suggestionProvider = new WordSuggestionProvider(StandardField.KEYWORDS, database);
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Collections.emptyList());
Collection<String> expected = Collections.singletonList("test");
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(expected, result);
}
@Test
void completeUppercaseBeginningOfNameReturnsName() {
SuggestionProvider<String> suggestionProvider = new EmptySuggestionProvider();
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Collections.singletonList("test"));
Collection<String> expected = Collections.singletonList("test");
Collection<String> result = autoCompleter.provideSuggestions(getRequest("TE"));
assertEquals(expected, result);
}
@Test
void completeNullThrowsException() {
assertThrows(NullPointerException.class, () -> autoCompleter.provideSuggestions(getRequest(null)));
}
@Test
void completeEmptyStringReturnsNothing() {
SuggestionProvider<String> suggestionProvider = new EmptySuggestionProvider();
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Collections.singletonList("test"));
Collection<String> expected = Collections.emptyList();
Collection<String> result = autoCompleter.provideSuggestions(getRequest(""));
assertEquals(expected, result);
}
@Test
void completeReturnsMultipleResults() {
BibDatabase database = new BibDatabase();
BibEntry bibEntry = new BibEntry();
bibEntry.addKeyword("testa", ',');
database.insertEntry(bibEntry);
SuggestionProvider<String> suggestionProvider = new WordSuggestionProvider(StandardField.KEYWORDS, database);
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Collections.singletonList("testb"));
Collection<String> expected = Arrays.asList("testa", "testb");
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(expected, result);
}
@Test
void completeReturnsKeywordsInAlphabeticalOrder() {
BibDatabase database = new BibDatabase();
BibEntry bibEntry = new BibEntry();
bibEntry.addKeyword("testd", ',');
bibEntry.addKeyword("testc", ',');
database.insertEntry(bibEntry);
SuggestionProvider<String> suggestionProvider = new WordSuggestionProvider(StandardField.KEYWORDS, database);
autoCompleter = new ContentSelectorSuggestionProvider(suggestionProvider, Arrays.asList("testb", "testa"));
Collection<String> expected = Arrays.asList("testa", "testb", "testc", "testd");
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(expected, result);
}
}
| 5,240 | 39.315385 | 118 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/DefaultAutoCompleterTest.java | package org.jabref.gui.autocompleter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
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.jabref.gui.autocompleter.AutoCompleterUtil.getRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class DefaultAutoCompleterTest {
private WordSuggestionProvider autoCompleter;
private BibDatabase database;
@BeforeEach
void setUp() throws Exception {
database = new BibDatabase();
autoCompleter = new WordSuggestionProvider(StandardField.TITLE, database);
}
@Test
void initAutoCompleterWithNullFieldThrowsException() {
assertThrows(NullPointerException.class, () -> new WordSuggestionProvider(null, database));
}
@Test
void completeWithoutAddingAnythingReturnsNothing() {
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeAfterAddingEmptyEntryReturnsNothing() {
BibEntry entry = new BibEntry();
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeAfterAddingEntryWithoutFieldReturnsNothing() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "testAuthor");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeValueReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testValue");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("testValue"));
assertEquals(Arrays.asList("testValue"), result);
}
@Test
void completeBeginningOfValueReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testValue");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Arrays.asList("testValue"), result);
}
@Test
void completeLowercaseValueReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testValue");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("testvalue"));
assertEquals(Arrays.asList("testValue"), result);
}
@Test
void completeNullThrowsException() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testKey");
database.insertEntry(entry);
assertThrows(NullPointerException.class, () -> autoCompleter.provideSuggestions(getRequest(null)));
}
@Test
void completeEmptyStringReturnsNothing() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testKey");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest(""));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeReturnsMultipleResults() {
BibEntry entryOne = new BibEntry();
entryOne.setField(StandardField.TITLE, "testValueOne");
database.insertEntry(entryOne);
BibEntry entryTwo = new BibEntry();
entryTwo.setField(StandardField.TITLE, "testValueTwo");
database.insertEntry(entryTwo);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("testValue"));
assertEquals(Arrays.asList("testValueOne", "testValueTwo"), result);
}
@Test
void completeShortStringReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "val");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("va"));
assertEquals(Collections.singletonList("val"), result);
}
@Test
void completeBeginnigOfSecondWordReturnsWord() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "test value");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("val"));
assertEquals(Collections.singletonList("value"), result);
}
@Test
void completePartOfWordReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "test value");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("lue"));
assertEquals(Collections.singletonList("value"), result);
}
}
| 5,179 | 33.304636 | 107 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/FieldValueSuggestionProviderTest.java | package org.jabref.gui.autocompleter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javafx.collections.FXCollections;
import org.jabref.logic.journals.JournalAbbreviationRepository;
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.jabref.gui.autocompleter.AutoCompleterUtil.getRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class FieldValueSuggestionProviderTest {
private FieldValueSuggestionProvider autoCompleter;
private BibDatabase database;
@BeforeEach
void setUp() {
database = new BibDatabase();
autoCompleter = new FieldValueSuggestionProvider(StandardField.TITLE, database);
}
@Test
void initAutoCompleterWithNullFieldThrowsException() {
assertThrows(NullPointerException.class, () -> new FieldValueSuggestionProvider(null, new BibDatabase()));
}
@Test
void completeWithoutAddingAnythingReturnsNothing() {
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeAfterAddingEmptyEntryReturnsNothing() {
BibEntry entry = new BibEntry();
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeAfterAddingEntryWithoutFieldReturnsNothing() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "testAuthor");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeOnIgnoredFieldReturnsNothing() {
AutoCompletePreferences autoCompletePreferences = mock(AutoCompletePreferences.class);
JournalAbbreviationRepository journalAbbreviationRepository = mock(JournalAbbreviationRepository.class);
when(autoCompletePreferences.getCompleteFields()).thenReturn(FXCollections.observableSet(Set.of(StandardField.AUTHOR)));
SuggestionProviders suggestionProviders = new SuggestionProviders(database, journalAbbreviationRepository, autoCompletePreferences);
SuggestionProvider<String> autoCompleter = (SuggestionProvider<String>) suggestionProviders.getForField(StandardField.TITLE);
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testValue");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("testValue"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeValueReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testValue");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("testValue"));
assertEquals(List.of("testValue"), result);
}
@Test
void completeBeginnigOfValueReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testValue");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(List.of("testValue"), result);
}
@Test
void completeLowercaseValueReturnsValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testValue");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("testvalue"));
assertEquals(List.of("testValue"), result);
}
@Test
void completeNullThrowsException() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testKey");
database.insertEntry(entry);
assertThrows(NullPointerException.class, () -> autoCompleter.provideSuggestions(getRequest(null)));
}
@Test
void completeEmptyStringReturnsNothing() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testKey");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest(""));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeReturnsMultipleResults() {
BibEntry entryOne = new BibEntry();
entryOne.setField(StandardField.TITLE, "testValueOne");
database.insertEntry(entryOne);
BibEntry entryTwo = new BibEntry();
entryTwo.setField(StandardField.TITLE, "testValueTwo");
database.insertEntry(entryTwo);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("testValue"));
assertEquals(Arrays.asList("testValueOne", "testValueTwo"), result);
}
@Test
void completeShortStringReturnsFieldValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "val");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("va"));
assertEquals(Collections.singletonList("val"), result);
}
@Test
void completeBeginnigOfSecondWordReturnsWholeFieldValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "test value");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("val"));
assertEquals(Collections.singletonList("test value"), result);
}
@Test
void completePartOfWordReturnsWholeFieldValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "test value");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("lue"));
assertEquals(Collections.singletonList("test value"), result);
}
@Test
void completeReturnsWholeFieldValue() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "test value");
database.insertEntry(entry);
Collection<String> result = autoCompleter.provideSuggestions(getRequest("te"));
assertEquals(Collections.singletonList("test value"), result);
}
}
| 6,771 | 35.605405 | 140 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/PersonNameStringConverterTest.java | package org.jabref.gui.autocompleter;
import java.util.Collections;
import org.jabref.model.entry.Author;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PersonNameStringConverterTest {
/** The author. **/
private Author author;
@BeforeEach
void setUp() {
// set up auhtor's name
author = new Author("Joseph M.", "J. M.", "", "Reagle", "Jr.");
}
@ParameterizedTest(name = "autoCompFF={0}, autoCompLF={1}, autoCompleteFirstNameMode={2}, expectedResult={3}")
@CsvSource({
"TRUE, TRUE, ONLY_FULL, 'Reagle, Jr., Joseph M.'",
"TRUE, FALSE, ONLY_FULL, 'Joseph M. Reagle, Jr.'",
"FALSE, TRUE, ONLY_FULL, 'Reagle, Jr., Joseph M.'",
"FALSE, FALSE, ONLY_FULL, 'Reagle'",
"TRUE, TRUE, ONLY_ABBREVIATED, 'Reagle, Jr., J. M.'",
"TRUE, FALSE, ONLY_ABBREVIATED, 'J. M. Reagle, Jr.'",
"FALSE, TRUE, ONLY_ABBREVIATED, 'Reagle, Jr., J. M.'",
"FALSE, FALSE, ONLY_ABBREVIATED, 'Reagle'",
"TRUE, TRUE, BOTH, 'Reagle, Jr., J. M.'",
"TRUE, FALSE, BOTH, 'J. M. Reagle, Jr.'",
"FALSE, TRUE, BOTH, 'Reagle, Jr., J. M.'",
"FALSE, FALSE, BOTH, 'Reagle'"
})
void testToStringWithoutAutoCompletePreferences(boolean autoCompFF, boolean autoCompLF, AutoCompleteFirstNameMode autoCompleteFirstNameMode, String expectedResult) {
PersonNameStringConverter converter = new PersonNameStringConverter(autoCompFF, autoCompLF, autoCompleteFirstNameMode);
String formattedStr = converter.toString(author);
assertEquals(expectedResult, formattedStr);
}
@ParameterizedTest(name = "shouldAutoComplete={0}, firstNameMode={1}, nameFormat={2}, expectedResult={3}")
@CsvSource({
"TRUE, ONLY_FULL, LAST_FIRST, 'Reagle, Jr., Joseph M.'",
"TRUE, ONLY_ABBREVIATED, LAST_FIRST, 'Reagle, Jr., J. M.'",
"TRUE, BOTH, LAST_FIRST, 'Reagle, Jr., J. M.'",
"TRUE, ONLY_FULL, FIRST_LAST, 'Joseph M. Reagle, Jr.'",
"TRUE, ONLY_ABBREVIATED, FIRST_LAST, 'J. M. Reagle, Jr.'",
"TRUE, BOTH, FIRST_LAST, 'J. M. Reagle, Jr.'",
"TRUE, ONLY_FULL, BOTH, 'Reagle, Jr., Joseph M.'",
"TRUE, ONLY_ABBREVIATED, BOTH, 'Reagle, Jr., J. M.'",
"TRUE, BOTH, BOTH, 'Reagle, Jr., J. M.'"
})
void testToStringWithAutoCompletePreferences(boolean shouldAutoComplete,
AutoCompleteFirstNameMode firstNameMode,
AutoCompletePreferences.NameFormat nameFormat,
String expectedResult) {
AutoCompletePreferences preferences = new AutoCompletePreferences(
shouldAutoComplete,
firstNameMode,
nameFormat,
Collections.emptySet());
PersonNameStringConverter converter = new PersonNameStringConverter(preferences);
String formattedStr = converter.toString(author);
assertEquals(expectedResult, formattedStr);
}
}
| 3,290 | 42.88 | 169 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/PersonNameSuggestionProviderTest.java | package org.jabref.gui.autocompleter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.Author;
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.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.jabref.gui.autocompleter.AutoCompleterUtil.getRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PersonNameSuggestionProviderTest {
private final Author vassilisKostakos = new Author("Vassilis", "V.", "", "Kostakos", "");
private PersonNameSuggestionProvider autoCompleter;
private BibEntry entry;
private BibDatabase database;
@BeforeEach
void setUp() throws Exception {
database = new BibDatabase();
autoCompleter = new PersonNameSuggestionProvider(StandardField.AUTHOR, database);
entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "Vassilis Kostakos");
}
@Test
void initAutoCompleterWithNullFieldThrowsException() {
assertThrows(NullPointerException.class, () -> new PersonNameSuggestionProvider((Field) null, new BibDatabase()));
}
@Test
void completeWithoutAddingAnythingReturnsNothing() {
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeAfterAddingEmptyEntryReturnsNothing() {
BibEntry entry = new BibEntry();
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeAfterAddingEntryWithoutFieldReturnsNothing() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, "testTitle");
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("test"));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeNameReturnsName() {
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Kostakos"));
assertEquals(Collections.singletonList(vassilisKostakos), result);
}
@Test
void completeBeginningOfNameReturnsName() {
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Kosta"));
assertEquals(Collections.singletonList(vassilisKostakos), result);
}
@Test
void completeLowercaseBeginningOfNameReturnsName() {
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("kosta"));
assertEquals(Collections.singletonList(vassilisKostakos), result);
}
@Test
void completeNullThrowsException() {
assertThrows(NullPointerException.class, () -> autoCompleter.provideSuggestions(getRequest(null)));
}
@Test
void completeEmptyStringReturnsNothing() {
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest(""));
assertEquals(Collections.emptyList(), result);
}
@Test
void completeReturnsMultipleResults() {
database.insertEntry(entry);
BibEntry entryTwo = new BibEntry();
entryTwo.setField(StandardField.AUTHOR, "Kosta");
database.insertEntry(entryTwo);
Author authorTwo = new Author("", "", "", "Kosta", "");
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Ko"));
assertEquals(Arrays.asList(authorTwo, vassilisKostakos), result);
}
@Test
void completePartOfNameReturnsName() {
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("osta"));
assertEquals(Collections.singletonList(vassilisKostakos), result);
}
@Test
void completeBeginningOfFirstNameReturnsName() {
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Vas"));
assertEquals(Collections.singletonList(vassilisKostakos), result);
}
@Test
void completeBeginningOfFirstNameReturnsNameWithJr() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "Reagle, Jr., Joseph M.");
database.insertEntry(entry);
Author author = new Author("Joseph M.", "J. M.", "", "Reagle", "Jr.");
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Jos"));
assertEquals(Collections.singletonList(author), result);
}
@Test
void completeBeginningOfFirstNameReturnsNameWithVon() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "Eric von Hippel");
database.insertEntry(entry);
Author author = new Author("Eric", "E.", "von", "Hippel", "");
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Eric"));
assertEquals(Collections.singletonList(author), result);
}
@Test
void completeBeginningOfLastNameReturnsNameWithUmlauts() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "Honig Bär");
database.insertEntry(entry);
Author author = new Author("Honig", "H.", "", "Bär", "");
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Bä"));
assertEquals(Collections.singletonList(author), result);
}
@Test
void completeVonReturnsName() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "Eric von Hippel");
database.insertEntry(entry);
Author author = new Author("Eric", "E.", "von", "Hippel", "");
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("von"));
assertEquals(Collections.singletonList(author), result);
}
@Test
void completeBeginningOfFullNameReturnsName() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.AUTHOR, "Vassilis Kostakos");
database.insertEntry(entry);
Collection<Author> result = autoCompleter.provideSuggestions(getRequest("Kostakos, Va"));
assertEquals(Collections.singletonList(vassilisKostakos), result);
}
}
| 6,611 | 34.740541 | 122 | java |
null | jabref-main/src/test/java/org/jabref/gui/autocompleter/SuggestionProvidersTest.java | package org.jabref.gui.autocompleter;
import java.util.Set;
import java.util.stream.Stream;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.StandardField;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
class SuggestionProvidersTest {
private SuggestionProviders suggestionProviders;
@BeforeEach
public void initializeSuggestionProviders() {
BibDatabase database = new BibDatabase();
JournalAbbreviationRepository abbreviationRepository = mock(JournalAbbreviationRepository.class);
Set<Field> completeFields = Set.of(StandardField.AUTHOR, StandardField.XREF, StandardField.XDATA, StandardField.JOURNAL, StandardField.PUBLISHER, SpecialField.PRINTED);
AutoCompletePreferences autoCompletePreferences = new AutoCompletePreferences(
true,
AutoCompleteFirstNameMode.BOTH,
AutoCompletePreferences.NameFormat.BOTH,
completeFields);
this.suggestionProviders = new SuggestionProviders(database, abbreviationRepository, autoCompletePreferences);
}
private static Stream<Arguments> getTestPairs() {
return Stream.of(
// a person
Arguments.of(org.jabref.gui.autocompleter.PersonNameSuggestionProvider.class, StandardField.AUTHOR),
// a single entry field
Arguments.of(org.jabref.gui.autocompleter.BibEntrySuggestionProvider.class, StandardField.XREF),
// multi entry fieldg
Arguments.of(org.jabref.gui.autocompleter.JournalsSuggestionProvider.class, StandardField.JOURNAL),
// TODO: We should offer pre-configured publishers
Arguments.of(org.jabref.gui.autocompleter.JournalsSuggestionProvider.class, StandardField.PUBLISHER),
// TODO: Auto completion should be aware of possible values of special fields
Arguments.of(org.jabref.gui.autocompleter.WordSuggestionProvider.class, SpecialField.PRINTED)
);
}
@ParameterizedTest
@MethodSource("getTestPairs")
public void testAppropriateCompleterReturned(Class<SuggestionProvider<BibEntry>> expected, Field field) {
assertEquals(expected, suggestionProviders.getForField(field).getClass());
}
@Test
void emptySuggestionProviderReturnedForEmptySuggestionProviderList() {
SuggestionProviders empty = new SuggestionProviders();
assertEquals(EmptySuggestionProvider.class, empty.getForField(StandardField.AUTHOR).getClass());
}
}
| 3,046 | 42.528571 | 176 | java |
null | jabref-main/src/test/java/org/jabref/gui/commonfxcontrols/SaveOrderPanelViewModelTest.java | package org.jabref.gui.commonfxcontrols;
import java.util.List;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.metadata.SaveOrder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SaveOrderPanelViewModelTest {
SortCriterionViewModel sortCriterionKey = new SortCriterionViewModel(new SaveOrder.SortCriterion(StandardField.KEY, false));
SortCriterionViewModel sortCriterionAuthor = new SortCriterionViewModel(new SaveOrder.SortCriterion(StandardField.AUTHOR, false));
SortCriterionViewModel sortCriterionTitle = new SortCriterionViewModel(new SaveOrder.SortCriterion(StandardField.TITLE, true));
SaveOrderConfigPanelViewModel viewModel;
@BeforeEach
void setUp() {
viewModel = new SaveOrderConfigPanelViewModel();
viewModel.sortCriteriaProperty().addAll(List.of(sortCriterionKey, sortCriterionAuthor, sortCriterionTitle));
}
@Test
void addCriterion() {
viewModel.addCriterion();
assertEquals(4, viewModel.sortCriteriaProperty().size());
}
@Test
void removeCriterion() {
SortCriterionViewModel unknownCriterion = new SortCriterionViewModel(new SaveOrder.SortCriterion(StandardField.ABSTRACT, false));
viewModel.removeCriterion(unknownCriterion);
assertEquals(3, viewModel.sortCriteriaProperty().size());
viewModel.removeCriterion(sortCriterionAuthor);
assertEquals(2, viewModel.sortCriteriaProperty().size());
assertEquals(List.of(sortCriterionKey, sortCriterionTitle), viewModel.sortCriteriaProperty());
}
@Test
void moveCriterionUp() {
viewModel.moveCriterionUp(sortCriterionTitle);
assertEquals(List.of(sortCriterionKey, sortCriterionTitle, sortCriterionAuthor), viewModel.sortCriteriaProperty());
viewModel.moveCriterionUp(sortCriterionTitle);
assertEquals(List.of(sortCriterionTitle, sortCriterionKey, sortCriterionAuthor), viewModel.sortCriteriaProperty());
viewModel.moveCriterionUp(sortCriterionTitle);
assertEquals(List.of(sortCriterionTitle, sortCriterionKey, sortCriterionAuthor), viewModel.sortCriteriaProperty());
}
@Test
void moveCriterionDown() {
viewModel.moveCriterionDown(sortCriterionKey);
assertEquals(List.of(sortCriterionAuthor, sortCriterionKey, sortCriterionTitle), viewModel.sortCriteriaProperty());
viewModel.moveCriterionDown(sortCriterionKey);
assertEquals(List.of(sortCriterionAuthor, sortCriterionTitle, sortCriterionKey), viewModel.sortCriteriaProperty());
viewModel.moveCriterionDown(sortCriterionKey);
assertEquals(List.of(sortCriterionAuthor, sortCriterionTitle, sortCriterionKey), viewModel.sortCriteriaProperty());
}
}
| 2,842 | 40.808824 | 137 | java |
null | jabref-main/src/test/java/org/jabref/gui/documentviewer/PdfDocumentViewModelTest.java | package org.jabref.gui.documentviewer;
import java.io.IOException;
import java.nio.file.Path;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PdfDocumentViewModelTest {
@Test
void getPagesTest(@TempDir Path tempDir) throws IOException {
try (PDDocument mockPDF = new PDDocument()) {
Path pdfFile = tempDir.resolve("mockPDF.pdf");
mockPDF.addPage(new PDPage());
mockPDF.save(pdfFile.toAbsolutePath().toString());
PdfDocumentViewModel PDFviewModel = new PdfDocumentViewModel(mockPDF);
assertEquals(1, PDFviewModel.getPages().size());
}
}
}
| 771 | 25.62069 | 76 | java |
null | jabref-main/src/test/java/org/jabref/gui/edit/CopyMoreActionTest.java | package org.jabref.gui.edit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefDialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.StandardActions;
import org.jabref.logic.journals.JournalAbbreviationRepository;
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.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CopyMoreActionTest {
private final DialogService dialogService = spy(DialogService.class);
private final ClipBoardManager clipBoardManager = mock(ClipBoardManager.class);
private final PreferencesService preferencesService = mock(PreferencesService.class);
private final JournalAbbreviationRepository abbreviationRepository = mock(JournalAbbreviationRepository.class);
private final StateManager stateManager = mock(StateManager.class);
private final List<String> titles = new ArrayList<>();
private final List<String> keys = new ArrayList<>();
private final List<String> dois = new ArrayList<>();
private CopyMoreAction copyMoreAction;
private BibEntry entry;
@BeforeEach
public void setUp() {
String title = "A tale from the trenches";
entry = new BibEntry(StandardEntryType.Misc)
.withField(StandardField.AUTHOR, "Souti Chattopadhyay and Nicholas Nelson and Audrey Au and Natalia Morales and Christopher Sanchez and Rahul Pandita and Anita Sarma")
.withField(StandardField.TITLE, title)
.withField(StandardField.YEAR, "2020")
.withField(StandardField.DOI, "10.1145/3377811.3380330")
.withField(StandardField.SUBTITLE, "cognitive biases and software development")
.withCitationKey("abc");
titles.add(title);
keys.add("abc");
dois.add("10.1145/3377811.3380330");
}
@Test
public void testExecuteOnFail() {
when(stateManager.getActiveDatabase()).thenReturn(Optional.empty());
when(stateManager.getSelectedEntries()).thenReturn(FXCollections.emptyObservableList());
copyMoreAction = new CopyMoreAction(StandardActions.COPY_TITLE, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
verify(clipBoardManager, times(0)).setContent(any(String.class));
verify(dialogService, times(0)).notify(any(String.class));
}
@Test
public void testExecuteCopyTitleWithNoTitle() {
BibEntry entryWithNoTitle = (BibEntry) entry.clone();
entryWithNoTitle.clearField(StandardField.TITLE);
ObservableList<BibEntry> entriesWithNoTitles = FXCollections.observableArrayList(entryWithNoTitle);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithNoTitles));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(entriesWithNoTitles);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_TITLE, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
verify(clipBoardManager, times(0)).setContent(any(String.class));
verify(dialogService, times(1)).notify(Localization.lang("None of the selected entries have titles."));
}
@Test
public void testExecuteCopyTitleOnPartialSuccess() {
BibEntry entryWithNoTitle = (BibEntry) entry.clone();
entryWithNoTitle.clearField(StandardField.TITLE);
ObservableList<BibEntry> mixedEntries = FXCollections.observableArrayList(entryWithNoTitle, entry);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(mixedEntries));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(mixedEntries);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_TITLE, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
String copiedTitles = String.join("\n", titles);
verify(clipBoardManager, times(1)).setContent(copiedTitles);
verify(dialogService, times(1)).notify(Localization.lang("Warning: %0 out of %1 entries have undefined title.",
Integer.toString(mixedEntries.size() - titles.size()), Integer.toString(mixedEntries.size())));
}
@Test
public void testExecuteCopyTitleOnSuccess() {
ObservableList<BibEntry> entriesWithTitles = FXCollections.observableArrayList(entry);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithTitles));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(entriesWithTitles);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_TITLE, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
String copiedTitles = String.join("\n", titles);
verify(clipBoardManager, times(1)).setContent(copiedTitles);
verify(dialogService, times(1)).notify(Localization.lang("Copied '%0' to clipboard.",
JabRefDialogService.shortenDialogMessage(copiedTitles)));
}
@Test
public void testExecuteCopyKeyWithNoKey() {
BibEntry entryWithNoKey = (BibEntry) entry.clone();
entryWithNoKey.clearCiteKey();
ObservableList<BibEntry> entriesWithNoKeys = FXCollections.observableArrayList(entryWithNoKey);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithNoKeys));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(entriesWithNoKeys);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_KEY, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
verify(clipBoardManager, times(0)).setContent(any(String.class));
verify(dialogService, times(1)).notify(Localization.lang("None of the selected entries have citation keys."));
}
@Test
public void testExecuteCopyKeyOnPartialSuccess() {
BibEntry entryWithNoKey = (BibEntry) entry.clone();
entryWithNoKey.clearCiteKey();
ObservableList<BibEntry> mixedEntries = FXCollections.observableArrayList(entryWithNoKey, entry);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(mixedEntries));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(mixedEntries);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_KEY, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
String copiedKeys = String.join("\n", keys);
verify(clipBoardManager, times(1)).setContent(copiedKeys);
verify(dialogService, times(1)).notify(Localization.lang("Warning: %0 out of %1 entries have undefined citation key.",
Integer.toString(mixedEntries.size() - titles.size()), Integer.toString(mixedEntries.size())));
}
@Test
public void testExecuteCopyKeyOnSuccess() {
ObservableList<BibEntry> entriesWithKeys = FXCollections.observableArrayList(entry);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithKeys));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(entriesWithKeys);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_KEY, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
String copiedKeys = String.join("\n", keys);
verify(clipBoardManager, times(1)).setContent(copiedKeys);
verify(dialogService, times(1)).notify(Localization.lang("Copied '%0' to clipboard.",
JabRefDialogService.shortenDialogMessage(copiedKeys)));
}
@Test
public void testExecuteCopyDoiWithNoDoi() {
BibEntry entryWithNoDoi = (BibEntry) entry.clone();
entryWithNoDoi.clearField(StandardField.DOI);
ObservableList<BibEntry> entriesWithNoDois = FXCollections.observableArrayList(entryWithNoDoi);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithNoDois));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(entriesWithNoDois);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_DOI, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
verify(clipBoardManager, times(0)).setContent(any(String.class));
verify(dialogService, times(1)).notify(Localization.lang("None of the selected entries have DOIs."));
}
@Test
public void testExecuteCopyDoiOnPartialSuccess() {
BibEntry entryWithNoDoi = (BibEntry) entry.clone();
entryWithNoDoi.clearField(StandardField.DOI);
ObservableList<BibEntry> mixedEntries = FXCollections.observableArrayList(entryWithNoDoi, entry);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(mixedEntries));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(mixedEntries);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_DOI, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
String copiedDois = String.join("\n", dois);
verify(clipBoardManager, times(1)).setContent(copiedDois);
verify(dialogService, times(1)).notify(Localization.lang("Warning: %0 out of %1 entries have undefined DOIs.",
Integer.toString(mixedEntries.size() - titles.size()), Integer.toString(mixedEntries.size())));
}
@Test
public void testExecuteCopyDoiOnSuccess() {
ObservableList<BibEntry> entriesWithDois = FXCollections.observableArrayList(entry);
BibDatabaseContext databaseContext = new BibDatabaseContext(new BibDatabase(entriesWithDois));
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
when(stateManager.getSelectedEntries()).thenReturn(entriesWithDois);
copyMoreAction = new CopyMoreAction(StandardActions.COPY_DOI, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository);
copyMoreAction.execute();
String copiedDois = String.join("\n", dois);
verify(clipBoardManager, times(1)).setContent(copiedDois);
verify(dialogService, times(1)).notify(Localization.lang("Copied '%0' to clipboard.",
JabRefDialogService.shortenDialogMessage(copiedDois)));
}
}
| 12,136 | 53.183036 | 183 | java |
null | jabref-main/src/test/java/org/jabref/gui/edit/CopyOrMoveFieldContentTabViewModelTest.java | package org.jabref.gui.edit;
import java.util.List;
import java.util.Optional;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.copyormovecontent.CopyOrMoveFieldContentTabViewModel;
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.mockito.Mockito.mock;
public class CopyOrMoveFieldContentTabViewModelTest {
CopyOrMoveFieldContentTabViewModel copyOrMoveFieldContentTabViewModel;
BibEntry entryA;
BibEntry entryB;
BibDatabase bibDatabase;
StateManager stateManager = mock(StateManager.class);
@BeforeEach
void setup() {
entryA = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.YEAR, "2015")
.withField(StandardField.DATE, "2014");
entryB = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.DATE, "1998");
bibDatabase = new BibDatabase();
copyOrMoveFieldContentTabViewModel = newTwoFieldsViewModel(entryA, entryB);
}
@Test
void copyValueDoesNotCopyBlankValues() {
CopyOrMoveFieldContentTabViewModel copyOrMoveFieldContentTabViewModel = newTwoFieldsViewModel(entryA, entryB);
copyOrMoveFieldContentTabViewModel.fromFieldProperty().set(StandardField.YEAR);
copyOrMoveFieldContentTabViewModel.toFieldProperty().set(StandardField.DATE);
copyOrMoveFieldContentTabViewModel.overwriteFieldContentProperty().set(true);
copyOrMoveFieldContentTabViewModel.copyValue();
assertEquals(Optional.of("2015"), entryA.getField(StandardField.DATE), "YEAR field is not copied correctly to the DATE field");
assertEquals(Optional.of("2015"), entryA.getField(StandardField.YEAR), "YEAR field should not have changed");
assertEquals(Optional.of("1998"), entryB.getField(StandardField.DATE), "DATE field should not have changed because the YEAR field is blank e.g it doesn't exist");
}
@Test
void swapValuesShouldNotSwapFieldValuesIfOneOfTheValuesIsBlank() {
copyOrMoveFieldContentTabViewModel.fromFieldProperty().set(StandardField.YEAR);
copyOrMoveFieldContentTabViewModel.toFieldProperty().set(StandardField.DATE);
copyOrMoveFieldContentTabViewModel.overwriteFieldContentProperty().set(true);
copyOrMoveFieldContentTabViewModel.swapValues();
assertEquals(Optional.of("1998"), entryB.getField(StandardField.DATE));
assertEquals(Optional.empty(), entryB.getField(StandardField.YEAR));
}
@Test
void swapValuesShouldSwapFieldValuesIfBothValuesAreNotBlank() {
copyOrMoveFieldContentTabViewModel.fromFieldProperty().set(StandardField.YEAR);
copyOrMoveFieldContentTabViewModel.toFieldProperty().set(StandardField.DATE);
copyOrMoveFieldContentTabViewModel.overwriteFieldContentProperty().set(true);
copyOrMoveFieldContentTabViewModel.swapValues();
assertEquals(List.of(Optional.of("2014"), Optional.of("2015")),
List.of(entryA.getField(StandardField.YEAR), entryA.getField(StandardField.DATE)),
"YEAR and DATE values didn't swap");
}
@Test
void moveValueShouldNotMoveValueIfToFieldIsNotBlankAndOverwriteIsNotEnabled() {
copyOrMoveFieldContentTabViewModel.fromFieldProperty().set(StandardField.YEAR);
copyOrMoveFieldContentTabViewModel.toFieldProperty().set(StandardField.DATE);
copyOrMoveFieldContentTabViewModel.overwriteFieldContentProperty().set(false);
copyOrMoveFieldContentTabViewModel.moveValue();
assertEquals(Optional.of("2015"), entryA.getField(StandardField.YEAR));
assertEquals(Optional.of("2014"), entryA.getField(StandardField.DATE));
}
@Test
void moveValueShouldMoveValueIfOverwriteIsEnabled() {
copyOrMoveFieldContentTabViewModel.fromFieldProperty().set(StandardField.DATE);
copyOrMoveFieldContentTabViewModel.toFieldProperty().set(StandardField.YEAR);
copyOrMoveFieldContentTabViewModel.overwriteFieldContentProperty().set(true);
copyOrMoveFieldContentTabViewModel.moveValue();
assertEquals(Optional.of("1998"), entryB.getField(StandardField.YEAR));
assertEquals(Optional.empty(), entryB.getField(StandardField.DATE));
}
private CopyOrMoveFieldContentTabViewModel newTwoFieldsViewModel(BibEntry... selectedEntries) {
return new CopyOrMoveFieldContentTabViewModel(List.of(selectedEntries), bibDatabase, stateManager);
}
}
| 4,709 | 43.433962 | 170 | java |
null | jabref-main/src/test/java/org/jabref/gui/edit/EditFieldContentTabViewModelTest.java | package org.jabref.gui.edit;
import java.util.List;
import java.util.Optional;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.editfieldcontent.EditFieldContentViewModel;
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.assertNotEquals;
import static org.mockito.Mockito.mock;
public class EditFieldContentTabViewModelTest {
EditFieldContentViewModel editFieldContentViewModel;
BibEntry entryA;
BibEntry entryB;
BibDatabase bibDatabase;
StateManager stateManager = mock(StateManager.class);
@BeforeEach
void setup() {
entryA = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.YEAR, "2015")
.withField(StandardField.DATE, "2014");
entryB = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.DATE, "1998")
.withField(StandardField.YEAR, "");
bibDatabase = new BibDatabase();
editFieldContentViewModel = new EditFieldContentViewModel(bibDatabase, List.of(entryA, entryB), stateManager);
}
@Test
void clearSelectedFieldShouldClearFieldContentEvenWhenOverwriteFieldContentIsNotEnabled() {
editFieldContentViewModel.selectedFieldProperty().set(StandardField.YEAR);
editFieldContentViewModel.overwriteFieldContentProperty().set(false);
editFieldContentViewModel.clearSelectedField();
assertEquals(Optional.empty(), entryA.getField(StandardField.YEAR));
}
@Test
void clearSelectedFieldShouldDoNothingWhenFieldDoesntExistOrIsEmpty() {
editFieldContentViewModel.selectedFieldProperty().set(StandardField.FILE);
editFieldContentViewModel.clearSelectedField();
assertEquals(Optional.empty(), entryA.getField(StandardField.FILE));
}
@Test
void setFieldValueShouldNotDoAnythingIfOverwriteFieldContentIsNotEnabled() {
editFieldContentViewModel.overwriteFieldContentProperty().set(false);
editFieldContentViewModel.selectedFieldProperty().set(StandardField.YEAR);
editFieldContentViewModel.fieldValueProperty().set("2001");
editFieldContentViewModel.setFieldValue();
assertEquals(Optional.of("2015"), entryA.getField(StandardField.YEAR));
}
@Test
void setFieldValueShouldSetFieldValueIfOverwriteFieldContentIsEnabled() {
editFieldContentViewModel.overwriteFieldContentProperty().set(true);
editFieldContentViewModel.selectedFieldProperty().set(StandardField.YEAR);
editFieldContentViewModel.fieldValueProperty().set("2001");
editFieldContentViewModel.setFieldValue();
assertEquals(Optional.of("2001"), entryA.getField(StandardField.YEAR));
}
@Test
void setFieldValueShouldSetFieldValueIfFieldContentIsEmpty() {
editFieldContentViewModel.overwriteFieldContentProperty().set(false);
editFieldContentViewModel.selectedFieldProperty().set(StandardField.YEAR);
editFieldContentViewModel.fieldValueProperty().set("2001");
editFieldContentViewModel.setFieldValue();
assertEquals(Optional.of("2001"), entryB.getField(StandardField.YEAR));
}
@Test
void appendToFieldValueShouldDoNothingIfOverwriteFieldContentIsNotEnabled() {
editFieldContentViewModel.overwriteFieldContentProperty().set(false);
editFieldContentViewModel.selectedFieldProperty().set(StandardField.YEAR);
editFieldContentViewModel.fieldValueProperty().set("0");
editFieldContentViewModel.appendToFieldValue();
assertEquals(Optional.of("2015"), entryA.getField(StandardField.YEAR));
}
@Test
void appendToFieldValueShouldAppendFieldValueIfOverwriteFieldContentIsEnabled() {
editFieldContentViewModel.overwriteFieldContentProperty().set(true);
editFieldContentViewModel.selectedFieldProperty().set(StandardField.YEAR);
editFieldContentViewModel.fieldValueProperty().set("0");
editFieldContentViewModel.appendToFieldValue();
assertEquals(Optional.of("20150"), entryA.getField(StandardField.YEAR));
}
@Test
void getAllFieldsShouldNeverBeEmpty() {
assertNotEquals(0, editFieldContentViewModel.getAllFields().size());
}
@Test
void getSelectedFieldShouldHaveADefaultValue() {
assertNotEquals(null, editFieldContentViewModel.getSelectedField());
}
}
| 4,645 | 38.042017 | 118 | java |
null | jabref-main/src/test/java/org/jabref/gui/edit/ManageKeywordsViewModelTest.java | package org.jabref.gui.edit;
import java.util.Arrays;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.preferences.BibEntryPreferences;
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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ManageKeywordsViewModelTest {
private final BibEntryPreferences bibEntryPreferences = mock(BibEntryPreferences.class);
private ManageKeywordsViewModel keywordsViewModel;
@BeforeEach
void setUp() {
BibEntry entryOne = new BibEntry(StandardEntryType.Article)
.withField(StandardField.AUTHOR, "Prakhar Srivastava and Nishant Singh")
.withField(StandardField.YEAR, "2020")
.withField(StandardField.DOI, "10.1109/PARC49193.2020.236624")
.withField(StandardField.ISBN, "978-1-7281-6575-2")
.withField(StandardField.JOURNALTITLE, "2020 International Conference on Power Electronics & IoT Applications in Renewable Energy and its Control (PARC)")
.withField(StandardField.PAGES, "351--354")
.withField(StandardField.PUBLISHER, "IEEE")
.withField(StandardField.TITLE, "Automatized Medical Chatbot (Medibot)")
.withField(StandardField.KEYWORDS, "Human-machine interaction, Chatbot, Medical Chatbot, Natural Language Processing, Machine Learning, Bot");
BibEntry entryTwo = new BibEntry(StandardEntryType.Article)
.withField(StandardField.AUTHOR, "Mladjan Jovanovic and Marcos Baez and Fabio Casati")
.withField(StandardField.DATE, "November 2020")
.withField(StandardField.YEAR, "2020")
.withField(StandardField.DOI, "10.1109/MIC.2020.3037151")
.withField(StandardField.ISSN, "1941-0131")
.withField(StandardField.JOURNALTITLE, "IEEE Internet Computing")
.withField(StandardField.PAGES, "1--1")
.withField(StandardField.PUBLISHER, "IEEE")
.withField(StandardField.TITLE, "Chatbots as conversational healthcare services")
.withField(StandardField.KEYWORDS, "Chatbot, Medical services, Internet, Data collection, Medical diagnostic imaging, Automation, Vocabulary");
List<BibEntry> entries = List.of(entryOne, entryTwo);
when(bibEntryPreferences.getKeywordSeparator()).thenReturn(',');
keywordsViewModel = new ManageKeywordsViewModel(bibEntryPreferences, entries);
}
@Test
void keywordsFilledInCorrectly() {
ObservableList<String> addedKeywords = keywordsViewModel.getKeywords();
List<String> expectedKeywordsList = Arrays.asList("Human-machine interaction", "Chatbot", "Medical Chatbot",
"Natural Language Processing", "Machine Learning", "Bot", "Chatbot", "Medical services", "Internet",
"Data collection", "Medical diagnostic imaging", "Automation", "Vocabulary");
assertEquals(FXCollections.observableList(expectedKeywordsList), addedKeywords);
}
@Test
void removedKeywordNotIncludedInKeywordsList() {
ObservableList<String> modifiedKeywords = keywordsViewModel.getKeywords();
List<String> originalKeywordsList = Arrays.asList("Human-machine interaction", "Chatbot", "Medical Chatbot",
"Natural Language Processing", "Machine Learning", "Bot", "Chatbot", "Medical services", "Internet",
"Data collection", "Medical diagnostic imaging", "Automation", "Vocabulary");
assertEquals(FXCollections.observableList(originalKeywordsList), modifiedKeywords, "compared lists are not identical");
keywordsViewModel.removeKeyword("Human-machine interaction");
assertNotEquals(FXCollections.observableList(originalKeywordsList), modifiedKeywords, "compared lists are identical");
}
}
| 4,247 | 50.180723 | 170 | java |
null | jabref-main/src/test/java/org/jabref/gui/edit/RenameFieldViewModelTest.java | package org.jabref.gui.edit;
import java.util.List;
import java.util.Optional;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.renamefield.RenameFieldViewModel;
import org.jabref.model.database.BibDatabase;
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.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;
public class RenameFieldViewModelTest {
RenameFieldViewModel renameFieldViewModel;
BibEntry entryA;
BibEntry entryB;
BibDatabase bibDatabase;
StateManager stateManager = mock(StateManager.class);
@BeforeEach
void setup() {
entryA = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.YEAR, "2015")
.withField(StandardField.DATE, "2014")
.withField(StandardField.AUTHOR, "Doe");
entryB = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.DATE, "1998")
.withField(StandardField.YEAR, "")
.withField(StandardField.AUTHOR, "Eddie");
bibDatabase = new BibDatabase();
renameFieldViewModel = new RenameFieldViewModel(List.of(entryA, entryB), bibDatabase, stateManager);
}
@Test
void renameFieldShouldRenameFieldIfItExist() {
renameFieldViewModel.selectField(StandardField.DATE);
renameFieldViewModel.setNewFieldName("ETAD");
renameFieldViewModel.renameField();
assertEquals(Optional.of("2014"), entryA.getField(FieldFactory.parseField("ETAD")));
assertEquals(Optional.empty(), entryA.getField(StandardField.DATE));
assertEquals(Optional.of("1998"), entryB.getField(FieldFactory.parseField("ETAD")));
assertEquals(Optional.empty(), entryB.getField(StandardField.DATE));
}
@Test
void renameFieldShouldDoNothingIfFieldDoNotExist() {
Field toRenameField = new UnknownField("Some_field_that_doesnt_exist");
renameFieldViewModel.selectField(toRenameField);
renameFieldViewModel.setNewFieldName("new_field_name");
renameFieldViewModel.renameField();
assertEquals(Optional.empty(), entryA.getField(toRenameField));
assertEquals(Optional.empty(), entryA.getField(new UnknownField("new_field_name")));
assertEquals(Optional.empty(), entryB.getField(toRenameField));
assertEquals(Optional.empty(), entryB.getField(new UnknownField("new_field_name")));
}
@Test
void renameFieldShouldNotDoAnythingIfTheNewFieldNameIsEmpty() {
renameFieldViewModel.selectField(StandardField.AUTHOR);
renameFieldViewModel.setNewFieldName("");
renameFieldViewModel.renameField();
assertEquals(Optional.of("Doe"), entryA.getField(StandardField.AUTHOR));
assertEquals(Optional.empty(), entryA.getField(FieldFactory.parseField("")));
assertEquals(Optional.of("Eddie"), entryB.getField(StandardField.AUTHOR));
assertEquals(Optional.empty(), entryB.getField(FieldFactory.parseField("")));
}
@Test
void renameFieldShouldNotDoAnythingIfTheNewFieldNameHasWhitespaceCharacters() {
renameFieldViewModel.selectField(StandardField.AUTHOR);
renameFieldViewModel.setNewFieldName("Hello, World");
renameFieldViewModel.renameField();
assertEquals(Optional.of("Doe"), entryA.getField(StandardField.AUTHOR));
assertEquals(Optional.empty(), entryA.getField(FieldFactory.parseField("Hello, World")));
assertEquals(Optional.of("Eddie"), entryB.getField(StandardField.AUTHOR));
assertEquals(Optional.empty(), entryB.getField(FieldFactory.parseField("Hello, World")));
}
@Test
void renameFieldShouldDoNothingWhenThereIsAlreadyAFieldWithTheSameNameAsNewFieldName() {
renameFieldViewModel.selectField(StandardField.DATE);
renameFieldViewModel.setNewFieldName(StandardField.YEAR.getName());
renameFieldViewModel.renameField();
assertEquals(Optional.of("2014"), entryA.getField(StandardField.DATE));
assertEquals(Optional.of("2015"), entryA.getField(StandardField.YEAR));
assertEquals(Optional.empty(), entryB.getField(StandardField.DATE));
assertEquals(Optional.of("1998"), entryB.getField(StandardField.YEAR));
}
}
| 4,556 | 39.6875 | 108 | java |
null | jabref-main/src/test/java/org/jabref/gui/edit/ReplaceStringViewModelTest.java | package org.jabref.gui.edit;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import org.jabref.gui.LibraryTab;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ReplaceStringViewModelTest {
private final LibraryTab libraryTab = mock(LibraryTab.class);
private ReplaceStringViewModel viewModel;
@BeforeEach
void setUp() {
BibEntry entry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.AUTHOR, "Shatakshi Sharma and Bhim Singh and Sukumar Mishra")
.withField(StandardField.DATE, "April 2020")
.withField(StandardField.YEAR, "2020")
.withField(StandardField.DOI, "10.1109/TII.2019.2935531")
.withField(StandardField.FILE, ":https\\://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8801912:PDF")
.withField(StandardField.ISSUE, "4")
.withField(StandardField.ISSN, "1941-0050")
.withField(StandardField.JOURNALTITLE, "IEEE Transactions on Industrial Informatics")
.withField(StandardField.PAGES, "2346--2356")
.withField(StandardField.PUBLISHER, "IEEE")
.withField(StandardField.TITLE, "Economic Operation and Quality Control in PV-BES-DG-Based Autonomous System")
.withField(StandardField.VOLUME, "16")
.withField(StandardField.KEYWORDS, "Batteries, Generators, Economics, Power quality, State of charge, Harmonic analysis, Control systems, Battery, diesel generator (DG), distributed generation, power quality, photovoltaic (PV), voltage source converter (VSC)");
List<BibEntry> entries = new ArrayList<>();
entries.add(entry);
when(libraryTab.getSelectedEntries()).thenReturn(entries);
when(libraryTab.getDatabase()).thenReturn(new BibDatabase(entries));
viewModel = new ReplaceStringViewModel(libraryTab);
}
@ParameterizedTest(name = "findString={0}, replaceString={1}, fieldString={2}, selectOnly={3}, allFieldReplace={4}, expectedResult={5}")
@CsvSource({
"randomText, replaceText, author, TRUE, FALSE, 0", // does not replace when findString does not exist in the selected field
"Informatics, replaceText, randomField, TRUE, FALSE, 0", // does not replace if the BibEntry does not have selected field
"Informatics, replaceText, journaltitle, TRUE, FALSE, 1", // replace "Informatics" in the JOURNALTITLE field to "replaceText" in the BibEntry
"Informatics, replaceText, journaltitle, TRUE, TRUE, 1", // replace "Informatics" in the JOURNALTITLE field to "replaceText" in the BibEntry
"Informatics, replaceText, journaltitle, FALSE, FALSE, 1", // replace "Informatics" in the JOURNALTITLE field to "replaceText" in the BibEntry
"Informatics, replaceText, journaltitle, FALSE, TRUE, 1", // replace "Informatics" in the JOURNALTITLE field to "replaceText" in the BibEntry
"2020, 2021, date, TRUE, FALSE, 1", // only replace "2020" in the DATE field to "2021" in the BibEntry
"2020, 2021, date, FALSE, TRUE, 2", // replace all the "2020"s in the entries
"2020, 2021, date, FALSE, FALSE, 1", // only replace "2020" in the DATE field to "2021" in the BibEntry
"2020, 2021, date, TRUE, TRUE, 2", // replace all the "2020"s in the entries
"System, replaceText, title, FALSE, TRUE, 1", // replace "System" in all entries is case sensitive
"and, '', author, TRUE, FALSE, 2", // replace two "and"s with empty string in the same AUTHOR field
"' ', ',', date, TRUE, FALSE, 1" // replace space with comma in DATE field
})
void testReplace(String findString, String replaceString, String fieldString, boolean selectOnly, boolean allFieldReplace, int expectedResult) {
viewModel.findStringProperty().bind(new SimpleStringProperty(findString));
viewModel.replaceStringProperty().bind(new SimpleStringProperty(replaceString));
viewModel.fieldStringProperty().bind(new SimpleStringProperty(fieldString));
viewModel.selectOnlyProperty().bind(new SimpleBooleanProperty(selectOnly));
viewModel.allFieldReplaceProperty().bind(new SimpleBooleanProperty(allFieldReplace));
assertEquals(expectedResult, viewModel.replace());
}
}
| 4,885 | 60.075 | 277 | java |
null | jabref-main/src/test/java/org/jabref/gui/entryeditor/CommentsTabTest.java | package org.jabref.gui.entryeditor;
import java.util.Optional;
import java.util.Set;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.logic.preferences.OwnerPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UserSpecificCommentField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.preferences.PreferencesService;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testfx.framework.junit5.ApplicationExtension;
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;
@GUITest
@ExtendWith(ApplicationExtension.class)
class CommentsTabTest {
private final String ownerName = "user1";
private CommentsTab commentsTab;
@Mock
private BibEntryTypesManager entryTypesManager;
@Mock
private BibDatabaseContext databaseContext;
@Mock
private SuggestionProviders suggestionProviders;
@Mock
private UndoManager undoManager;
@Mock
private DialogService dialogService;
@Mock
private PreferencesService preferences;
@Mock
private StateManager stateManager;
@Mock
private ThemeManager themeManager;
@Mock
private TaskExecutor taskExecutor;
@Mock
private JournalAbbreviationRepository journalAbbreviationRepository;
@Mock
private IndexingTaskManager indexingTaskManager;
@Mock
private OwnerPreferences ownerPreferences;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
when(preferences.getOwnerPreferences()).thenReturn(ownerPreferences);
when(ownerPreferences.getDefaultOwner()).thenReturn(ownerName);
when(databaseContext.getMode()).thenReturn(BibDatabaseMode.BIBLATEX);
BibEntryType entryTypeMock = mock(BibEntryType.class);
when(entryTypesManager.enrich(any(), any())).thenReturn(Optional.of(entryTypeMock));
commentsTab = new CommentsTab(
preferences,
databaseContext,
suggestionProviders,
undoManager,
dialogService,
stateManager,
themeManager,
indexingTaskManager,
taskExecutor,
journalAbbreviationRepository
);
}
@Test
void testDetermineFieldsToShowWorksForASingleUser() {
final UserSpecificCommentField ownerComment = new UserSpecificCommentField(ownerName);
BibEntry entry = new BibEntry(StandardEntryType.Book)
.withField(StandardField.COMMENT, "Standard comment text")
.withField(ownerComment, "User-specific comment text");
Set<Field> fields = commentsTab.determineFieldsToShow(entry);
assertEquals(Set.of(StandardField.COMMENT, ownerComment), fields);
}
@Test
void testDetermineFieldsToShowWorksForMultipleUsers() {
final UserSpecificCommentField ownerComment = new UserSpecificCommentField(ownerName);
final UserSpecificCommentField otherUsersComment = new UserSpecificCommentField("other-user-id");
BibEntry entry = new BibEntry(StandardEntryType.Book)
.withField(StandardField.COMMENT, "Standard comment text")
.withField(ownerComment, "User-specific comment text")
.withField(otherUsersComment, "other-user-id comment text");
Set<Field> fields = commentsTab.determineFieldsToShow(entry);
assertEquals(Set.of(StandardField.COMMENT, ownerComment, otherUsersComment), fields);
}
@Test
public void testDifferentiateCaseInUserName() {
UserSpecificCommentField field1 = new UserSpecificCommentField("USER");
UserSpecificCommentField field2 = new UserSpecificCommentField("user");
assertNotEquals(field1, field2, "Two UserSpecificCommentField instances with usernames that differ only by case should be considered different");
}
}
| 4,911 | 35.932331 | 153 | java |
null | jabref-main/src/test/java/org/jabref/gui/entryeditor/SourceTabTest.java | package org.jabref.gui.entryeditor;
import java.util.Collections;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.stage.Stage;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.testutils.category.GUITest;
import org.fxmisc.richtext.CodeArea;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Answers;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@GUITest
@ExtendWith(ApplicationExtension.class)
class SourceTabTest {
private Stage stage;
private Scene scene;
private CodeArea area;
private TabPane pane;
private SourceTab sourceTab;
@Start
public void onStart(Stage stage) {
area = new CodeArea();
area.appendText("some example\n text to go here\n across a couple of \n lines....");
StateManager stateManager = mock(StateManager.class);
when(stateManager.activeSearchQueryProperty()).thenReturn(OptionalObjectProperty.empty());
KeyBindingRepository keyBindingRepository = new KeyBindingRepository(Collections.emptyList(), Collections.emptyList());
ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
when(importFormatPreferences.bibEntryPreferences().getKeywordSeparator()).thenReturn(',');
FieldPreferences fieldPreferences = mock(FieldPreferences.class);
when(fieldPreferences.getNonWrappableFields()).thenReturn(FXCollections.emptyObservableList());
sourceTab = new SourceTab(
new BibDatabaseContext(),
new CountingUndoManager(),
fieldPreferences,
importFormatPreferences,
new DummyFileUpdateMonitor(),
mock(DialogService.class),
stateManager,
keyBindingRepository);
pane = new TabPane(
new Tab("main area", area),
new Tab("other tab", new Label("some text")),
sourceTab
);
scene = new Scene(pane);
this.stage = stage;
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
// select the area's tab
pane.getSelectionModel().select(0);
}
@Test
void switchingFromSourceTabDoesNotThrowException(FxRobot robot) {
BibEntry entry = new BibEntry();
entry.setField(new UnknownField("test"), "testvalue");
// Update source editor
robot.interact(() -> pane.getSelectionModel().select(2));
robot.interact(() -> sourceTab.notifyAboutFocus(entry));
robot.clickOn(1200, 500);
robot.interrupt(100);
// Switch to different tab & update entry
robot.interact(() -> pane.getSelectionModel().select(1));
robot.interact(() -> stage.setWidth(600));
robot.interact(() -> entry.setField(new UnknownField("test"), "new value"));
// No exception should be thrown
robot.interrupt(100);
}
}
| 3,808 | 35.625 | 127 | java |
null | jabref-main/src/test/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationViewModelTest.java | package org.jabref.gui.entryeditor.fileannotationtab;
import java.time.LocalDateTime;
import java.util.Optional;
import org.jabref.model.pdf.FileAnnotation;
import org.jabref.model.pdf.FileAnnotationType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FileAnnotationViewModelTest {
private FileAnnotationViewModel annotationViewModel;
private FileAnnotationViewModel annotationViewModelWithoutFileAnnotation;
@BeforeEach
void setup() {
String content = "This is content";
String marking = String.format("This is paragraph 1.%n" +
"This is paragr-%naph 2, and it crosses%nseveral lines,%nnow you can see next paragraph:%n"
+ "This is paragraph%n3.");
FileAnnotation linkedFileAnnotation = new FileAnnotation("John", LocalDateTime.now(), 3, content, FileAnnotationType.FREETEXT, Optional.empty());
FileAnnotation annotation = new FileAnnotation("Jaroslav Kucha ˇr", LocalDateTime.parse("2017-07-20T10:11:30"), 1, marking, FileAnnotationType.HIGHLIGHT, Optional.of(linkedFileAnnotation));
FileAnnotation annotationWithoutFileAnnotation = new FileAnnotation("Jaroslav Kucha ˇr", LocalDateTime.parse("2017-07-20T10:11:30"), 1, marking, FileAnnotationType.HIGHLIGHT, Optional.empty());
annotationViewModel = new FileAnnotationViewModel(annotation);
annotationViewModelWithoutFileAnnotation = new FileAnnotationViewModel(annotationWithoutFileAnnotation);
}
@Test
public void sameAuthor() {
assertEquals("Jaroslav Kucha ˇr", annotationViewModel.getAuthor());
}
@Test
public void retrieveCorrectPageNumberAsString() {
assertEquals("1", annotationViewModel.getPage());
}
@Test
public void retrieveCorrectDateAsString() {
assertEquals("2017-07-20 10:11:30", annotationViewModel.getDate());
}
@Test
public void retrieveCorrectContent() {
assertEquals("This is content", annotationViewModel.getContent());
}
@Test
public void retrieveCorrectContentWithoutLinkedFileAnnotation() {
String expectedMarking = String.format("This is paragraph 1.%n" +
"This is paragraph 2, and it crosses several lines, now you can see next paragraph:%n"
+ "This is paragraph 3.");
assertEquals(expectedMarking, annotationViewModelWithoutFileAnnotation.getContent());
}
@Test
public void removeOnlyLineBreaksNotPrecededByPeriodOrColon() {
String expectedMarking = String.format("This is paragraph 1.%n" +
"This is paragraph 2, and it crosses several lines, now you can see next paragraph:%n"
+ "This is paragraph 3.");
assertEquals(expectedMarking, annotationViewModel.getMarking());
}
@Test
public void retrieveCorrectMarkingWithoutLinkedFileAnnotation() {
assertEquals("", annotationViewModelWithoutFileAnnotation.getMarking());
}
}
| 3,048 | 39.118421 | 201 | java |
null | jabref-main/src/test/java/org/jabref/gui/exporter/ExportToClipboardActionTest.java | package org.jabref.gui.exporter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.exporter.Exporter;
import org.jabref.logic.exporter.SaveConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.logic.xmp.XmpPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.metadata.MetaData;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.LibraryPreferences;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ExportToClipboardActionTest {
private ExportToClipboardAction exportToClipboardAction;
private final DialogService dialogService = spy(DialogService.class);
private final ClipBoardManager clipBoardManager = mock(ClipBoardManager.class);
private final BibDatabaseContext databaseContext = mock(BibDatabaseContext.class);
private final PreferencesService preferences = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS);
private final StateManager stateManager = mock(StateManager.class);
private TaskExecutor taskExecutor;
private ObservableList<BibEntry> selectedEntries;
@BeforeEach
public void setUp() {
BibEntry entry = new BibEntry(StandardEntryType.Misc)
.withField(StandardField.AUTHOR, "Souti Chattopadhyay and Nicholas Nelson and Audrey Au and Natalia Morales and Christopher Sanchez and Rahul Pandita and Anita Sarma")
.withField(StandardField.TITLE, "A tale from the trenches")
.withField(StandardField.YEAR, "2020")
.withField(StandardField.DOI, "10.1145/3377811.3380330")
.withField(StandardField.SUBTITLE, "cognitive biases and software development");
selectedEntries = FXCollections.observableArrayList(entry);
when(stateManager.getSelectedEntries()).thenReturn(selectedEntries);
taskExecutor = new CurrentThreadTaskExecutor();
when(preferences.getExportPreferences().getCustomExporters()).thenReturn(FXCollections.observableList(List.of()));
when(preferences.getExportConfiguration()).thenReturn(mock(SaveConfiguration.class));
when(preferences.getXmpPreferences()).thenReturn(mock(XmpPreferences.class));
exportToClipboardAction = new ExportToClipboardAction(dialogService, stateManager, clipBoardManager, taskExecutor, preferences);
}
@Test
public void testExecuteIfNoSelectedEntries() {
when(stateManager.getSelectedEntries()).thenReturn(FXCollections.emptyObservableList());
exportToClipboardAction.execute();
verify(dialogService, times(1)).notify(Localization.lang("This operation requires one or more entries to be selected."));
}
@Test
public void testExecuteOnSuccess() {
Exporter selectedExporter = new Exporter("html", "HTML", StandardFileType.HTML) {
@Override
public void export(BibDatabaseContext databaseContext, Path file, List<BibEntry> entries) {
}
};
LibraryPreferences libraryPreferences = mock(LibraryPreferences.class, Answers.RETURNS_DEEP_STUBS);
FilePreferences filePreferences = mock(FilePreferences.class, Answers.RETURNS_DEEP_STUBS);
when(preferences.getFilePreferences()).thenReturn(filePreferences);
when(preferences.getLibraryPreferences()).thenReturn(libraryPreferences);
when(preferences.getExportPreferences().getLastExportExtension()).thenReturn("HTML");
when(stateManager.getSelectedEntries()).thenReturn(selectedEntries);
when(stateManager.getActiveDatabase()).thenReturn(Optional.ofNullable(databaseContext));
// noinspection ConstantConditions since databaseContext is mocked
when(databaseContext.getFileDirectories(preferences.getFilePreferences())).thenReturn(new ArrayList<>(List.of(Path.of("path"))));
when(databaseContext.getMetaData()).thenReturn(new MetaData());
when(dialogService.showChoiceDialogAndWait(
eq(Localization.lang("Export")),
eq(Localization.lang("Select export format")),
eq(Localization.lang("Export")),
any(Exporter.class),
anyCollection())
).thenReturn(Optional.of(selectedExporter));
exportToClipboardAction.execute();
verify(dialogService, times(1)).showChoiceDialogAndWait(
eq(Localization.lang("Export")), eq(Localization.lang("Select export format")),
eq(Localization.lang("Export")), any(Exporter.class), anyCollection());
verify(dialogService, times(1)).notify(Localization.lang("Entries exported to clipboard") + ": " + selectedEntries.size());
}
}
| 5,698 | 48.556522 | 183 | java |
null | jabref-main/src/test/java/org/jabref/gui/exporter/SaveDatabaseActionTest.java | package org.jabref.gui.exporter;
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.stream.Collectors;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences;
import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern;
import org.jabref.logic.exporter.BibDatabaseWriter;
import org.jabref.logic.exporter.SaveConfiguration;
import org.jabref.logic.shared.DatabaseLocation;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.metadata.MetaData;
import org.jabref.model.metadata.SaveOrder;
import org.jabref.preferences.ExportPreferences;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.JabRefPreferences;
import org.jabref.preferences.LibraryPreferences;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class SaveDatabaseActionTest {
private static final String TEST_BIBTEX_LIBRARY_LOCATION = "C:\\Users\\John_Doe\\Jabref\\literature.bib";
private Path file = Path.of(TEST_BIBTEX_LIBRARY_LOCATION);
private final DialogService dialogService = mock(DialogService.class);
private final FilePreferences filePreferences = mock(FilePreferences.class);
private final JabRefPreferences preferences = mock(JabRefPreferences.class);
private LibraryTab libraryTab = mock(LibraryTab.class);
private final JabRefFrame jabRefFrame = mock(JabRefFrame.class);
private BibDatabaseContext dbContext = spy(BibDatabaseContext.class);
private SaveDatabaseAction saveDatabaseAction;
@BeforeEach
public void setUp() {
when(libraryTab.frame()).thenReturn(jabRefFrame);
when(libraryTab.getBibDatabaseContext()).thenReturn(dbContext);
when(filePreferences.getWorkingDirectory()).thenReturn(Path.of(TEST_BIBTEX_LIBRARY_LOCATION));
when(preferences.getFilePreferences()).thenReturn(filePreferences);
when(preferences.getExportPreferences()).thenReturn(mock(ExportPreferences.class));
when(jabRefFrame.getDialogService()).thenReturn(dialogService);
saveDatabaseAction = spy(new SaveDatabaseAction(libraryTab, preferences, mock(BibEntryTypesManager.class)));
}
@Test
public void saveAsShouldSetWorkingDirectory() {
when(dialogService.showFileSaveDialog(any(FileDialogConfiguration.class))).thenReturn(Optional.of(file));
doReturn(true).when(saveDatabaseAction).saveAs(any());
saveDatabaseAction.saveAs();
verify(filePreferences, times(1)).setWorkingDirectory(file.getParent());
}
@Test
public void saveAsShouldNotSetWorkingDirectoryIfNotSelected() {
when(dialogService.showFileSaveDialog(any(FileDialogConfiguration.class))).thenReturn(Optional.empty());
doReturn(false).when(saveDatabaseAction).saveAs(any());
saveDatabaseAction.saveAs();
verify(filePreferences, times(0)).setWorkingDirectory(any());
}
@Test
public void saveShouldShowSaveAsIfDatabaseNotSelected() {
when(dbContext.getDatabasePath()).thenReturn(Optional.empty());
when(dbContext.getLocation()).thenReturn(DatabaseLocation.LOCAL);
when(preferences.getBoolean(JabRefPreferences.LOCAL_AUTO_SAVE)).thenReturn(false);
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(file));
doReturn(true).when(saveDatabaseAction).saveAs(any(), any());
saveDatabaseAction.save();
verify(saveDatabaseAction, times(1)).saveAs(file, SaveDatabaseAction.SaveDatabaseMode.NORMAL);
}
private SaveDatabaseAction createSaveDatabaseActionForBibDatabase(BibDatabase database) throws IOException {
file = Files.createTempFile("JabRef", ".bib");
file.toFile().deleteOnExit();
FieldPreferences fieldPreferences = mock(FieldPreferences.class);
SaveConfiguration saveConfiguration = mock(SaveConfiguration.class);
// In case a "thenReturn" is modified, the whole mock has to be recreated
dbContext = mock(BibDatabaseContext.class);
libraryTab = mock(LibraryTab.class);
MetaData metaData = mock(MetaData.class);
when(saveConfiguration.withSaveType(any(BibDatabaseWriter.SaveType.class))).thenReturn(saveConfiguration);
when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder());
GlobalCitationKeyPattern emptyGlobalCitationKeyPattern = GlobalCitationKeyPattern.fromPattern("");
when(metaData.getCiteKeyPattern(any(GlobalCitationKeyPattern.class))).thenReturn(emptyGlobalCitationKeyPattern);
when(dbContext.getDatabasePath()).thenReturn(Optional.of(file));
when(dbContext.getLocation()).thenReturn(DatabaseLocation.LOCAL);
when(dbContext.getDatabase()).thenReturn(database);
when(dbContext.getMetaData()).thenReturn(metaData);
when(dbContext.getEntries()).thenReturn(database.getEntries());
when(preferences.getBoolean(JabRefPreferences.LOCAL_AUTO_SAVE)).thenReturn(false);
when(preferences.getFieldPreferences()).thenReturn(fieldPreferences);
when(preferences.getCitationKeyPatternPreferences()).thenReturn(mock(CitationKeyPatternPreferences.class));
when(preferences.getCitationKeyPatternPreferences().getKeyPattern()).thenReturn(emptyGlobalCitationKeyPattern);
when(preferences.getFieldPreferences().getNonWrappableFields()).thenReturn(FXCollections.emptyObservableList());
when(preferences.getLibraryPreferences()).thenReturn(mock(LibraryPreferences.class));
when(libraryTab.frame()).thenReturn(jabRefFrame);
when(libraryTab.getBibDatabaseContext()).thenReturn(dbContext);
when(libraryTab.getUndoManager()).thenReturn(mock(CountingUndoManager.class));
when(libraryTab.getBibDatabaseContext()).thenReturn(dbContext);
saveDatabaseAction = new SaveDatabaseAction(libraryTab, preferences, mock(BibEntryTypesManager.class));
return saveDatabaseAction;
}
@Test
public void saveKeepsChangedFlag() throws Exception {
BibEntry firstEntry = new BibEntry().withField(StandardField.AUTHOR, "first");
firstEntry.setChanged(true);
BibEntry secondEntry = new BibEntry().withField(StandardField.AUTHOR, "second");
secondEntry.setChanged(true);
BibDatabase database = new BibDatabase(List.of(firstEntry, secondEntry));
saveDatabaseAction = createSaveDatabaseActionForBibDatabase(database);
saveDatabaseAction.save();
assertEquals(database
.getEntries().stream()
.map(BibEntry::hasChanged).filter(changed -> false).collect(Collectors.toList()),
Collections.emptyList());
}
@Test
public void saveShouldNotSaveDatabaseIfPathNotSet() {
when(dbContext.getDatabasePath()).thenReturn(Optional.empty());
boolean result = saveDatabaseAction.save();
assertFalse(result);
}
}
| 7,931 | 47.962963 | 120 | java |
null | jabref-main/src/test/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtilTest.java | package org.jabref.gui.externalfiles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import javafx.collections.FXCollections;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.logic.util.io.AutoLinkPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.preferences.FilePreferences;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AutoSetFileLinksUtilTest {
private final FilePreferences filePreferences = mock(FilePreferences.class);
private final AutoLinkPreferences autoLinkPrefs = new AutoLinkPreferences(
AutoLinkPreferences.CitationKeyDependency.START,
"",
false,
';');
private final BibDatabaseContext databaseContext = mock(BibDatabaseContext.class);
private final BibEntry entry = new BibEntry(StandardEntryType.Article);
private Path path = null;
@BeforeEach
public void setUp(@TempDir Path folder) throws Exception {
path = folder.resolve("CiteKey.pdf");
Files.createFile(path);
entry.setCitationKey("CiteKey");
when(filePreferences.getExternalFileTypes())
.thenReturn(FXCollections.observableSet(new TreeSet<>(ExternalFileTypes.getDefaultExternalFileTypes())));
}
@Test
public void testFindAssociatedNotLinkedFilesSuccess() throws Exception {
when(databaseContext.getFileDirectories(any())).thenReturn(Collections.singletonList(path.getParent()));
List<LinkedFile> expected = Collections.singletonList(new LinkedFile("", Path.of("CiteKey.pdf"), "PDF"));
AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(databaseContext, filePreferences, autoLinkPrefs);
List<LinkedFile> actual = util.findAssociatedNotLinkedFiles(entry);
assertEquals(expected, actual);
}
@Test
public void testFindAssociatedNotLinkedFilesForEmptySearchDir() throws Exception {
when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(false);
AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(databaseContext, filePreferences, autoLinkPrefs);
List<LinkedFile> actual = util.findAssociatedNotLinkedFiles(entry);
assertEquals(Collections.emptyList(), actual);
}
}
| 2,742 | 40.560606 | 121 | java |
null | jabref-main/src/test/java/org/jabref/gui/externalfiles/FileFilterUtilsTest.java | package org.jabref.gui.externalfiles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class FileFilterUtilsTest {
private final FileFilterUtils fileFilterUtils = new FileFilterUtils();
private final LocalDateTime time = LocalDateTime.now();
@Test
public void isDuringLastDayNegativeTest() {
assertEquals(fileFilterUtils.isDuringLastDay(time.minusHours(24)), false);
}
@Test
public void isDuringLastDayPositiveTest() {
assertEquals(fileFilterUtils.isDuringLastDay(time.minusHours(23)), true);
}
@Test
public void isDuringLastWeekNegativeTest() {
assertEquals(fileFilterUtils.isDuringLastWeek(time.minusDays(7)), false);
}
@Test
public void isDuringLastWeekPositiveTest() {
assertEquals(fileFilterUtils.isDuringLastWeek(time.minusDays(6).minusHours(23)), true);
}
@Test
public void isDuringLastMonthNegativeTest() {
assertEquals(fileFilterUtils.isDuringLastMonth(time.minusDays(30)), false);
}
@Test
public void isDuringLastMonthPositiveTest() {
assertEquals(fileFilterUtils.isDuringLastMonth(time.minusDays(29).minusHours(23)), true);
}
@Test
public void isDuringLastYearNegativeTest() {
assertEquals(fileFilterUtils.isDuringLastYear(time.minusDays(365)), false);
}
@Test
public void isDuringLastYearPositiveTest() {
assertEquals(fileFilterUtils.isDuringLastYear(time.minusDays(364).minusHours(23)), true);
}
@Nested
class SortingTests {
private final List<Path> files = new ArrayList<>();
private final List<String> expectedSortByDateAscending = new ArrayList<>();
private final List<String> expectedSortByDateDescending = new ArrayList<>();
private final List<String> wrongOrder = new ArrayList<>();
/* Initialize the directory and files used in the sorting tests, and change their last edited dates. */
@BeforeEach
public void setUp(@TempDir Path tempDir) throws Exception {
Path firstPath = tempDir.resolve("firstFile.pdf");
Path secondPath = tempDir.resolve("secondFile.pdf");
Path thirdPath = tempDir.resolve("thirdFile.pdf");
Path fourthPath = tempDir.resolve("fourthFile.pdf");
Files.createFile(firstPath);
Files.createFile(secondPath);
Files.createFile(thirdPath);
Files.createFile(fourthPath);
// change the files last edited times.
Files.setLastModifiedTime(firstPath, FileTime.fromMillis(10));
Files.setLastModifiedTime(secondPath, FileTime.fromMillis(5));
Files.setLastModifiedTime(thirdPath, FileTime.fromMillis(1));
Files.setLastModifiedTime(fourthPath, FileTime.fromMillis(2));
// fill the list to be sorted by the tests.
files.add(firstPath);
files.add(secondPath);
files.add(thirdPath);
files.add(fourthPath);
// fill the expected values lists.
expectedSortByDateAscending.add(thirdPath.toString());
expectedSortByDateAscending.add(fourthPath.toString());
expectedSortByDateAscending.add(secondPath.toString());
expectedSortByDateAscending.add(firstPath.toString());
expectedSortByDateDescending.add(firstPath.toString());
expectedSortByDateDescending.add(secondPath.toString());
expectedSortByDateDescending.add(fourthPath.toString());
expectedSortByDateDescending.add(thirdPath.toString());
wrongOrder.add(firstPath.toString());
wrongOrder.add(secondPath.toString());
wrongOrder.add(thirdPath.toString());
wrongOrder.add(fourthPath.toString());
}
@Test
public void sortByDateAscendingPositiveTest() {
List<String> sortedPaths = fileFilterUtils
.sortByDateAscending(files)
.stream()
.map(Path::toString)
.collect(Collectors.toList());
assertEquals(sortedPaths, expectedSortByDateAscending);
}
@Test
public void sortByDateAscendingNegativeTest() {
List<String> sortedPaths = fileFilterUtils
.sortByDateAscending(files)
.stream()
.map(Path::toString)
.collect(Collectors.toList());
assertNotEquals(sortedPaths, wrongOrder);
}
@Test
public void sortByDateDescendingPositiveTest() {
List<String> sortedPaths = fileFilterUtils
.sortByDateDescending(files)
.stream()
.map(Path::toString)
.collect(Collectors.toList());
assertEquals(sortedPaths, expectedSortByDateDescending);
}
@Test
public void testSortByDateDescendingNegativeTest() {
List<String> sortedPaths = fileFilterUtils
.sortByDateDescending(files)
.stream()
.map(Path::toString)
.collect(Collectors.toList());
assertNotEquals(sortedPaths, wrongOrder);
}
}
@Nested
class filteringTests {
private final List<Path> files = new ArrayList<>();
private final List<Path> targetFiles = new ArrayList<>();
private final Set<String> ignoreFileSet = new HashSet<>();
@BeforeEach
public void setUp(@TempDir Path tempDir) throws Exception {
ignoreFileSet.add(".DS_Store");
ignoreFileSet.add("Thumbs.db");
Path firstPath = tempDir.resolve("firstFile.pdf");
Path secondPath = tempDir.resolve("secondFile.pdf");
Path thirdPath = tempDir.resolve("thirdFile.pdf");
Path fourthPath = tempDir.resolve("fourthFile.pdf");
Path fifthPath = tempDir.resolve(".DS_Store");
Path sixthPath = tempDir.resolve("Thumbs.db");
Files.createFile(firstPath);
Files.createFile(secondPath);
Files.createFile(thirdPath);
Files.createFile(fourthPath);
Files.createFile(fifthPath);
Files.createFile(sixthPath);
files.add(firstPath);
files.add(secondPath);
files.add(thirdPath);
files.add(fourthPath);
files.add(fifthPath);
files.add(sixthPath);
targetFiles.add(firstPath);
targetFiles.add(secondPath);
targetFiles.add(thirdPath);
targetFiles.add(fourthPath);
}
}
}
| 7,143 | 35.263959 | 111 | java |
null | jabref-main/src/test/java/org/jabref/gui/externalfiles/GitIgnoreFileFilterTest.java | package org.jabref.gui.externalfiles;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class GitIgnoreFileFilterTest {
@Test
public void checkSimpleGitIgnore(@TempDir Path dir) throws Exception {
Files.writeString(dir.resolve(".gitignore"), """
*.png
""");
GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
assertFalse(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
}
@Test
public void checkSimpleGitIgnoreWithAllowing(@TempDir Path dir) throws Exception {
Files.writeString(dir.resolve(".gitignore"), """
!*.png
""");
GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
assertTrue(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
}
@Test
public void checkSimpleGitIgnoreWithOverwritingDefs(@TempDir Path dir) throws Exception {
Files.writeString(dir.resolve(".gitignore"), """
!*.png
*.png
""");
GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
assertFalse(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
}
@Test
public void checkDirectoryGitIgnore(@TempDir Path dir) throws Exception {
Files.writeString(dir.resolve(".gitignore"), """
**/*.png
""");
GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
assertFalse(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
}
}
| 1,774 | 33.803922 | 93 | java |
null | jabref-main/src/test/java/org/jabref/gui/externalfiles/ImportHandlerTest.java | package org.jabref.gui.externalfiles;
import java.util.List;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
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 ImportHandlerTest {
@Test
void handleBibTeXData() {
ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
PreferencesService preferencesService = mock(PreferencesService.class);
when(preferencesService.getImportFormatPreferences()).thenReturn(importFormatPreferences);
when(preferencesService.getFilePreferences()).thenReturn(mock(FilePreferences.class));
ImportHandler importHandler = new ImportHandler(
mock(BibDatabaseContext.class),
preferencesService,
new DummyFileUpdateMonitor(),
mock(UndoManager.class),
mock(StateManager.class),
mock(DialogService.class),
new CurrentThreadTaskExecutor());
List<BibEntry> bibEntries = importHandler.handleBibTeXData("""
@InProceedings{Wen2013,
library = {Tagungen\\2013\\KWTK45\\},
}
""");
BibEntry expected = new BibEntry(StandardEntryType.InProceedings)
.withCitationKey("Wen2013")
.withField(StandardField.LIBRARY, "Tagungen\\2013\\KWTK45\\");
assertEquals(List.of(expected), bibEntries.stream().toList());
}
}
| 2,166 | 36.362069 | 122 | java |
null | jabref-main/src/test/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawlerTest.java | package org.jabref.gui.externalfiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.jabref.gui.util.FileNodeViewModel;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.FilePreferences;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static java.nio.file.DirectoryStream.Filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class UnlinkedFilesCrawlerTest {
@Test
public void minimalGitIgnore(@TempDir Path testRoot) throws Exception {
Files.writeString(testRoot.resolve(".gitignore"), """
*.png
""");
Path subDir = testRoot.resolve("subdir");
Files.createDirectories(subDir);
Files.createFile(subDir.resolve("test.png"));
UnlinkedPDFFileFilter unlinkedPDFFileFilter = mock(UnlinkedPDFFileFilter.class);
when(unlinkedPDFFileFilter.accept(any(Path.class))).thenReturn(true);
UnlinkedFilesCrawler unlinkedFilesCrawler = new UnlinkedFilesCrawler(testRoot, unlinkedPDFFileFilter, DateRange.ALL_TIME, ExternalFileSorter.DEFAULT, mock(BibDatabaseContext.class), mock(FilePreferences.class));
FileNodeViewModel fileNodeViewModel = unlinkedFilesCrawler.searchDirectory(testRoot, unlinkedPDFFileFilter);
assertEquals(new FileNodeViewModel(testRoot), fileNodeViewModel);
}
@Test
public void excludingTheCurrentLibraryTest(@TempDir Path testRoot) throws IOException {
// Adding 3 files one of which is the database file
Files.createFile(testRoot.resolve("unlinkedPdf.pdf"));
Files.createFile(testRoot.resolve("another-unlinkedPdf.pdf"));
Path databasePath = testRoot.resolve("test.bib");
Files.createFile(databasePath);
BibDatabaseContext databaseContext = new BibDatabaseContext();
databaseContext.setDatabasePath(databasePath);
FilePreferences filePreferences = mock(FilePreferences.class);
Filter<Path> fileExtensionFilter = new FileExtensionViewModel(StandardFileType.ANY_FILE, filePreferences).dirFilter();
UnlinkedPDFFileFilter unlinkedPdfFileFilter = new UnlinkedPDFFileFilter(fileExtensionFilter, databaseContext, filePreferences);
UnlinkedFilesCrawler unlinkedFilesCrawler = new UnlinkedFilesCrawler(testRoot, unlinkedPdfFileFilter, DateRange.ALL_TIME, ExternalFileSorter.DEFAULT, databaseContext, filePreferences);
FileNodeViewModel fileNodeViewModel = unlinkedFilesCrawler.searchDirectory(testRoot, unlinkedPdfFileFilter);
// checking to see if the database file has been filtered
try (Stream<Path> filesInitially = Files.list(testRoot)) {
int count = (int) filesInitially.count();
assertEquals(fileNodeViewModel.getFileCount(), count - 1);
}
}
}
| 3,072 | 44.191176 | 219 | java |
null | jabref-main/src/test/java/org/jabref/gui/externalfiletype/ExternalFileTypesTest.java | package org.jabref.gui.externalfiletype;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import javafx.collections.FXCollections;
import org.jabref.gui.icon.IconTheme;
import org.jabref.model.entry.LinkedFile;
import org.jabref.preferences.FilePreferences;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ExternalFileTypesTest {
private static final Set<ExternalFileType> TEST_LIST = Set.of(
StandardExternalFileType.MARKDOWN,
StandardExternalFileType.PDF,
StandardExternalFileType.URL,
StandardExternalFileType.JPG,
StandardExternalFileType.TXT);
private static final String TEST_STRINGLIST = "PostScript:REMOVED;" +
"Word:REMOVED;" +
"Word 2007+:REMOVED;" +
"OpenDocument text:REMOVED;" +
"Excel:REMOVED;" +
"Excel 2007+:REMOVED;" +
"OpenDocument spreadsheet:REMOVED;" +
"PowerPoint:REMOVED;" +
"PowerPoint 2007+:REMOVED;" +
"OpenDocument presentation:REMOVED;" +
"Rich Text Format:REMOVED;" +
"PNG image:REMOVED;" +
"GIF image:REMOVED;" +
"Djvu:REMOVED;" +
"LaTeX:REMOVED;" +
"CHM:REMOVED;" +
"TIFF image:REMOVED;" +
"MHT:REMOVED;" +
"ePUB:REMOVED";
private final FilePreferences filePreferences = mock(FilePreferences.class);
@BeforeEach
void setUp() {
when(filePreferences.getExternalFileTypes()).thenReturn(FXCollections.observableSet(TEST_LIST));
}
@Test
void getExternalFileTypeByName() {
assertEquals(Optional.of(StandardExternalFileType.PDF), ExternalFileTypes.getExternalFileTypeByName("PDF", filePreferences));
}
@Test
void getExternalFileTypeByExt() {
assertEquals(Optional.of(StandardExternalFileType.URL), ExternalFileTypes.getExternalFileTypeByExt("html", filePreferences));
}
@Test
void isExternalFileTypeByExt() {
assertTrue(ExternalFileTypes.isExternalFileTypeByExt("html", filePreferences));
assertFalse(ExternalFileTypes.isExternalFileTypeByExt("tst", filePreferences));
}
@Test
void getExternalFileTypeForName() {
assertEquals(Optional.of(StandardExternalFileType.JPG), ExternalFileTypes.getExternalFileTypeForName("testfile.jpg", filePreferences));
}
@Test
void getExternalFileTypeByMimeType() {
assertEquals(Optional.of(StandardExternalFileType.TXT), ExternalFileTypes.getExternalFileTypeByMimeType("text/plain", filePreferences));
}
@Test
void getExternalFileTypeByFile() {
Path testfile = Path.of("testfile.txt");
assertEquals(Optional.of(StandardExternalFileType.TXT), ExternalFileTypes.getExternalFileTypeByFile(testfile, filePreferences));
}
@Test
void getExternalFileTypeByLinkedFile() {
LinkedFile testfile = new LinkedFile("A testfile", "https://testserver.com/testfile.pdf", "PDF");
assertEquals(Optional.of(StandardExternalFileType.PDF), ExternalFileTypes.getExternalFileTypeByLinkedFile(testfile, false, filePreferences));
}
@Test
void toStringList() {
String testString = ExternalFileTypes.toStringList(TEST_LIST);
assertEquals(TEST_STRINGLIST, testString);
}
@Test
void fromString() {
Set<ExternalFileType> testList = ExternalFileTypes.fromString(TEST_STRINGLIST);
assertEquals(TEST_LIST, testList);
}
@Test
void externalFileTypetoStringArray() {
ExternalFileType type = new CustomExternalFileType(
"testEntry",
"tst",
"text/plain",
"emacs",
"close",
IconTheme.JabRefIcons.CLOSE);
assertEquals("[testEntry, tst, text/plain, emacs, CLOSE]", Arrays.toString(type.toStringArray()));
}
}
| 4,242 | 33.495935 | 149 | java |
null | jabref-main/src/test/java/org/jabref/gui/fieldeditors/LinkedFileViewModelTest.java | package org.jabref.gui.fieldeditors;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.TreeSet;
import javafx.collections.FXCollections;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import org.jabref.gui.DialogService;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.externalfiletype.StandardExternalFileType;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.externalfiles.LinkedFileHandler;
import org.jabref.logic.net.URLDownload;
import org.jabref.logic.xmp.XmpPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
import org.jabref.testutils.category.FetcherTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class LinkedFileViewModelTest {
private Path tempFile;
private LinkedFile linkedFile;
private BibEntry entry;
private BibDatabaseContext databaseContext;
private TaskExecutor taskExecutor;
private DialogService dialogService;
private final FilePreferences filePreferences = mock(FilePreferences.class);
private final PreferencesService preferences = mock(PreferencesService.class);
private CookieManager cookieManager;
@BeforeEach
void setUp(@TempDir Path tempFolder) throws Exception {
entry = new BibEntry()
.withCitationKey("asdf");
databaseContext = new BibDatabaseContext();
taskExecutor = mock(TaskExecutor.class);
dialogService = mock(DialogService.class);
when(filePreferences.getExternalFileTypes()).thenReturn(FXCollections.observableSet(new TreeSet<>(ExternalFileTypes.getDefaultExternalFileTypes())));
when(preferences.getFilePreferences()).thenReturn(filePreferences);
when(preferences.getXmpPreferences()).thenReturn(mock(XmpPreferences.class));
tempFile = tempFolder.resolve("temporaryFile");
Files.createFile(tempFile);
// Check if there exists a system-wide cookie handler
if (CookieHandler.getDefault() == null) {
cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
} else {
cookieManager = (CookieManager) CookieHandler.getDefault();
}
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
}
@AfterEach
void tearDown() {
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_NONE);
}
@Test
void deleteWhenFilePathNotPresentReturnsTrue() {
// Making this a spy, so we can inject an empty optional without digging into the implementation
linkedFile = spy(new LinkedFile("", Path.of("nonexistent file"), ""));
doReturn(Optional.empty()).when(linkedFile).findIn(any(BibDatabaseContext.class), any(FilePreferences.class));
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
boolean removed = viewModel.delete();
assertTrue(removed);
verifyNoInteractions(dialogService); // dialog was never shown
}
@Test
void deleteWhenRemoveChosenReturnsTrueButDoesNotDeletesFile() {
linkedFile = new LinkedFile("", tempFile, "");
when(dialogService.showCustomButtonDialogAndWait(
any(AlertType.class),
anyString(),
anyString(),
any(ButtonType.class),
any(ButtonType.class),
any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(3))); // first vararg - remove button
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
boolean removed = viewModel.delete();
assertTrue(removed);
assertTrue(Files.exists(tempFile));
}
@Test
void deleteWhenDeleteChosenReturnsTrueAndDeletesFile() {
linkedFile = new LinkedFile("", tempFile, "");
when(dialogService.showCustomButtonDialogAndWait(
any(AlertType.class),
anyString(),
anyString(),
any(ButtonType.class),
any(ButtonType.class),
any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(4))); // second vararg - delete button
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
boolean removed = viewModel.delete();
assertTrue(removed);
assertFalse(Files.exists(tempFile));
}
@Test
void deleteMissingFileReturnsTrue() {
linkedFile = new LinkedFile("", Path.of("!!nonexistent file!!"), "");
when(dialogService.showCustomButtonDialogAndWait(
any(AlertType.class),
anyString(),
anyString(),
any(ButtonType.class),
any(ButtonType.class),
any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(4))); // second vararg - delete button
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
boolean removed = viewModel.delete();
assertTrue(removed);
}
@Test
void deleteWhenDialogCancelledReturnsFalseAndDoesNotRemoveFile() {
linkedFile = new LinkedFile("desc", tempFile, "pdf");
when(dialogService.showCustomButtonDialogAndWait(
any(AlertType.class),
anyString(),
anyString(),
any(ButtonType.class),
any(ButtonType.class),
any(ButtonType.class))).thenAnswer(invocation -> Optional.of(invocation.getArgument(5))); // third vararg - cancel button
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
boolean removed = viewModel.delete();
assertFalse(removed);
assertTrue(Files.exists(tempFile));
}
@Test
void downloadHtmlFileCausesWarningDisplay() throws MalformedURLException {
when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(true);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]");
databaseContext.setDatabasePath(tempFile);
URL url = new URL("https://www.google.com/");
String fileType = StandardExternalFileType.URL.getName();
linkedFile = new LinkedFile(url, fileType);
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, new CurrentThreadTaskExecutor(), dialogService, preferences);
viewModel.download();
verify(dialogService, atLeastOnce()).notify("Downloaded website as an HTML file.");
}
@FetcherTest
@Test
void downloadOfFileReplacesLink(@TempDir Path tempFolder) throws Exception {
linkedFile = new LinkedFile(new URL("http://arxiv.org/pdf/1207.0408v1"), "");
entry.setFiles(new ArrayList<>(List.of(linkedFile)));
databaseContext = mock(BibDatabaseContext.class);
when(databaseContext.getFirstExistingFileDir(any())).thenReturn(Optional.of(tempFolder));
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("");
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, new CurrentThreadTaskExecutor(), dialogService, preferences);
viewModel.download();
assertEquals(List.of(new LinkedFile("", tempFolder.resolve("asdf.pdf"), "PDF")), entry.getFiles());
}
@FetcherTest
@Test
void downloadDoesNotOverwriteFileTypeExtension() throws Exception {
linkedFile = new LinkedFile(new URL("http://arxiv.org/pdf/1207.0408v1"), "");
databaseContext = mock(BibDatabaseContext.class);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("");
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, new CurrentThreadTaskExecutor(), dialogService, preferences);
BackgroundTask<Path> task = viewModel.prepareDownloadTask(tempFile.getParent(), new URLDownload("http://arxiv.org/pdf/1207.0408v1"));
task.onSuccess(destination -> {
LinkedFile newLinkedFile = LinkedFilesEditorViewModel.fromFile(destination, Collections.singletonList(tempFile.getParent()), filePreferences);
assertEquals("asdf.pdf", newLinkedFile.getLink());
assertEquals("PDF", newLinkedFile.getFileType());
});
task.onFailure(Assertions::fail);
new CurrentThreadTaskExecutor().execute(task);
}
@FetcherTest
@Test
void downloadHtmlWhenLinkedFilePointsToHtml() throws MalformedURLException {
// use google as test url, wiley is protected by CloudFlare
String url = "https://google.com";
String fileType = StandardExternalFileType.URL.getName();
linkedFile = new LinkedFile(new URL(url), fileType);
when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(true);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]");
databaseContext.setDatabasePath(tempFile);
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, new CurrentThreadTaskExecutor(), dialogService, preferences);
viewModel.download();
List<LinkedFile> linkedFiles = entry.getFiles();
for (LinkedFile file: linkedFiles) {
if ("Misc/asdf.html".equalsIgnoreCase(file.getLink())) {
assertEquals("URL", file.getFileType());
return;
}
}
// If the file was not found among the linked files to the entry
fail();
}
@Test
void isNotSamePath() {
linkedFile = new LinkedFile("desc", tempFile, "pdf");
databaseContext = mock(BibDatabaseContext.class);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("");
when(databaseContext.getFirstExistingFileDir(filePreferences)).thenReturn(Optional.of(Path.of("/home")));
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
assertFalse(viewModel.isGeneratedPathSameAsOriginal());
}
@Test
void isSamePath() {
linkedFile = new LinkedFile("desc", tempFile, "pdf");
databaseContext = mock(BibDatabaseContext.class);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("");
when(databaseContext.getFirstExistingFileDir(filePreferences)).thenReturn(Optional.of(tempFile.getParent()));
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
assertTrue(viewModel.isGeneratedPathSameAsOriginal());
}
// Tests if isGeneratedPathSameAsOriginal takes into consideration File directory pattern
@Test
void isNotSamePathWithPattern() {
linkedFile = new LinkedFile("desc", tempFile, "pdf");
databaseContext = mock(BibDatabaseContext.class);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]");
when(databaseContext.getFirstExistingFileDir(filePreferences)).thenReturn(Optional.of(tempFile.getParent()));
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
assertFalse(viewModel.isGeneratedPathSameAsOriginal());
}
// Tests if isGeneratedPathSameAsOriginal takes into consideration File directory pattern
@Test
void isSamePathWithPattern() throws IOException {
linkedFile = new LinkedFile("desc", tempFile, "pdf");
databaseContext = mock(BibDatabaseContext.class);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]");
when(databaseContext.getFirstExistingFileDir(filePreferences)).thenReturn(Optional.of(tempFile.getParent()));
LinkedFileHandler fileHandler = new LinkedFileHandler(linkedFile, entry, databaseContext, filePreferences);
fileHandler.moveToDefaultDirectory();
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences);
assertTrue(viewModel.isGeneratedPathSameAsOriginal());
}
// Tests if added parameters to mimeType gets parsed to correct format.
@Test
void mimeTypeStringWithParameterIsReturnedAsWithoutParameter() {
Optional<ExternalFileType> test = ExternalFileTypes.getExternalFileTypeByMimeType("text/html; charset=UTF-8", filePreferences);
String actual = test.get().toString();
assertEquals("URL", actual);
}
@Test
void downloadPdfFileWhenLinkedFilePointsToPdfUrl() throws MalformedURLException {
linkedFile = new LinkedFile(new URL("http://arxiv.org/pdf/1207.0408v1"), "pdf");
// Needed Mockito stubbing methods to run test
when(filePreferences.shouldStoreFilesRelativeToBibFile()).thenReturn(true);
when(filePreferences.getFileNamePattern()).thenReturn("[citationkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("[entrytype]");
databaseContext.setDatabasePath(tempFile);
LinkedFileViewModel viewModel = new LinkedFileViewModel(linkedFile, entry, databaseContext, new CurrentThreadTaskExecutor(), dialogService, preferences);
viewModel.download();
// Loop through downloaded files to check for filetype='pdf'
List<LinkedFile> linkedFiles = entry.getFiles();
for (LinkedFile files : linkedFiles) {
if ("Misc/asdf.pdf".equalsIgnoreCase(files.getLink())) {
assertEquals("pdf", files.getFileType().toLowerCase());
return;
}
}
// Assert fail if no PDF type was found
fail();
}
}
| 16,144 | 44.22409 | 161 | java |
null | jabref-main/src/test/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModelTest.java | package org.jabref.gui.fieldeditors;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.EmptySuggestionProvider;
import org.jabref.gui.externalfiletype.StandardExternalFileType;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
import org.jabref.testutils.category.FetcherTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@FetcherTest("Downloads a PDF file")
class LinkedFilesEditorViewModelTest {
private LinkedFilesEditorViewModel viewModel;
private final PreferencesService preferencesService = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS);
private final FilePreferences filePreferences = mock(FilePreferences.class, Answers.RETURNS_DEEP_STUBS);
private final BibDatabaseContext bibDatabaseContext = mock(BibDatabaseContext.class);
@Test
void urlFieldShouldDownloadFile(@TempDir Path tempDir) {
when(preferencesService.getFilePreferences()).thenReturn(filePreferences);
when(filePreferences.getExternalFileTypes()).thenReturn(FXCollections.observableSet(StandardExternalFileType.values()));
when(filePreferences.getFileNamePattern()).thenReturn("[bibtexkey]");
when(filePreferences.getFileDirectoryPattern()).thenReturn("");
when(bibDatabaseContext.getFirstExistingFileDir(any())).thenReturn(Optional.of(tempDir));
viewModel = new LinkedFilesEditorViewModel(StandardField.FILE, new EmptySuggestionProvider(), mock(DialogService.class), bibDatabaseContext,
new CurrentThreadTaskExecutor(), mock(FieldCheckers.class), preferencesService);
BibEntry entry = new BibEntry().withCitationKey("test")
.withField(StandardField.URL, "https://ceur-ws.org/Vol-847/paper6.pdf");
viewModel.entry = entry;
viewModel.fetchFulltext();
assertTrue(Files.exists(tempDir.resolve("test.pdf")));
}
}
| 2,545 | 44.464286 | 148 | java |
null | jabref-main/src/test/java/org/jabref/gui/groups/GroupDialogViewModelTest.java | package org.jabref.gui.groups;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import org.jabref.gui.DialogService;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.metadata.MetaData;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.preferences.BibEntryPreferences;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class GroupDialogViewModelTest {
private GroupDialogViewModel viewModel;
private Path temporaryFolder;
private BibDatabaseContext bibDatabaseContext;
private final MetaData metaData = mock(MetaData.class);
private final GroupsPreferences groupsPreferences = mock(GroupsPreferences.class);
private final DialogService dialogService = mock(DialogService.class);
private final AbstractGroup group = mock(AbstractGroup.class);
private final PreferencesService preferencesService = mock(PreferencesService.class);
@BeforeEach
void setUp(@TempDir Path temporaryFolder) {
this.temporaryFolder = temporaryFolder;
bibDatabaseContext = new BibDatabaseContext();
when(group.getName()).thenReturn("Group");
when(preferencesService.getBibEntryPreferences()).thenReturn(mock(BibEntryPreferences.class));
when(preferencesService.getBibEntryPreferences().getKeywordSeparator()).thenReturn(',');
when(preferencesService.getFilePreferences()).thenReturn(mock(FilePreferences.class));
when(preferencesService.getFilePreferences().getUserAndHost()).thenReturn("MockedUser-mockedhost");
when(preferencesService.getGroupsPreferences()).thenReturn(groupsPreferences);
bibDatabaseContext.setMetaData(metaData);
viewModel = new GroupDialogViewModel(dialogService, bibDatabaseContext, preferencesService, group, new DummyFileUpdateMonitor());
}
@Test
void validateExistingAbsolutePath() throws Exception {
var anAuxFile = temporaryFolder.resolve("auxfile.aux").toAbsolutePath();
Files.createFile(anAuxFile);
when(metaData.getLatexFileDirectory(any(String.class))).thenReturn(Optional.of(temporaryFolder));
viewModel.texGroupFilePathProperty().setValue(anAuxFile.toString());
assertTrue(viewModel.texGroupFilePathValidatonStatus().isValid());
}
@Test
void validateNonExistingAbsolutePath() {
var notAnAuxFile = temporaryFolder.resolve("notanauxfile.aux").toAbsolutePath();
viewModel.texGroupFilePathProperty().setValue(notAnAuxFile.toString());
assertFalse(viewModel.texGroupFilePathValidatonStatus().isValid());
}
@Test
void validateExistingRelativePath() throws Exception {
var anAuxFile = Path.of("auxfile.aux");
// The file needs to exist
Files.createFile(temporaryFolder.resolve(anAuxFile));
when(metaData.getLatexFileDirectory(any(String.class))).thenReturn(Optional.of(temporaryFolder));
viewModel.texGroupFilePathProperty().setValue(anAuxFile.toString());
assertTrue(viewModel.texGroupFilePathValidatonStatus().isValid());
}
@Test
void testHierarchicalContextFromGroup() throws Exception {
GroupHierarchyType groupHierarchyType = GroupHierarchyType.INCLUDING;
when(group.getHierarchicalContext()).thenReturn(groupHierarchyType);
viewModel = new GroupDialogViewModel(dialogService, bibDatabaseContext, preferencesService, group, new DummyFileUpdateMonitor());
assertEquals(groupHierarchyType, viewModel.groupHierarchySelectedProperty().getValue());
}
@Test
void testDefaultHierarchicalContext() throws Exception {
GroupHierarchyType defaultHierarchicalContext = GroupHierarchyType.REFINING;
when(preferencesService.getGroupsPreferences().getDefaultHierarchicalContext()).thenReturn(defaultHierarchicalContext);
viewModel = new GroupDialogViewModel(dialogService, bibDatabaseContext, preferencesService, null, new DummyFileUpdateMonitor());
assertEquals(defaultHierarchicalContext, viewModel.groupHierarchySelectedProperty().getValue());
}
}
| 4,672 | 43.504762 | 137 | java |
null | jabref-main/src/test/java/org/jabref/gui/groups/GroupNodeViewModelTest.java | package org.jabref.gui.groups;
import java.util.Arrays;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.DroppingMouseLocation;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.AutomaticKeywordGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.groups.WordKeywordGroup;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class GroupNodeViewModelTest {
private StateManager stateManager;
private BibDatabaseContext databaseContext;
private GroupNodeViewModel viewModel;
private TaskExecutor taskExecutor;
private PreferencesService preferencesService;
@BeforeEach
void setUp() {
stateManager = mock(StateManager.class);
when(stateManager.getSelectedEntries()).thenReturn(FXCollections.emptyObservableList());
databaseContext = new BibDatabaseContext();
taskExecutor = new CurrentThreadTaskExecutor();
preferencesService = mock(PreferencesService.class);
when(preferencesService.getGroupsPreferences()).thenReturn(new GroupsPreferences(
GroupViewMode.UNION,
true,
true,
GroupHierarchyType.INDEPENDENT
));
viewModel = getViewModelForGroup(
new WordKeywordGroup("Test group", GroupHierarchyType.INDEPENDENT, StandardField.TITLE, "search", true, ',', false));
}
@Test
void getDisplayNameConvertsLatexToUnicode() {
GroupNodeViewModel viewModel = getViewModelForGroup(
new WordKeywordGroup("\\beta", GroupHierarchyType.INDEPENDENT, StandardField.TITLE, "search", true, ',', false));
assertEquals("β", viewModel.getDisplayName());
}
@Test
void alwaysMatchedByEmptySearchString() {
assertTrue(viewModel.isMatchedBy(""));
}
@Test
void isMatchedIfContainsPartOfSearchString() {
assertTrue(viewModel.isMatchedBy("est"));
}
@Test
void treeOfAutomaticKeywordGroupIsCombined() {
BibEntry entryOne = new BibEntry().withField(StandardField.KEYWORDS, "A > B > B1, A > C");
BibEntry entryTwo = new BibEntry().withField(StandardField.KEYWORDS, "A > D, E");
BibEntry entryThree = new BibEntry().withField(StandardField.KEYWORDS, "A > B > B2");
databaseContext.getDatabase().insertEntries(entryOne, entryTwo, entryThree);
AutomaticKeywordGroup group = new AutomaticKeywordGroup("Keywords", GroupHierarchyType.INDEPENDENT, StandardField.KEYWORDS, ',', '>');
GroupNodeViewModel groupViewModel = getViewModelForGroup(group);
WordKeywordGroup expectedGroupA = new WordKeywordGroup("A", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true);
WordKeywordGroup expectedGroupB = new WordKeywordGroup("B", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B", true, ',', true);
WordKeywordGroup expectedGroupB1 = new WordKeywordGroup("B1", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B > B1", true, ',', true);
WordKeywordGroup expectedGroupB2 = new WordKeywordGroup("B2", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B > B2", true, ',', true);
WordKeywordGroup expectedGroupC = new WordKeywordGroup("C", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > C", true, ',', true);
WordKeywordGroup expectedGroupD = new WordKeywordGroup("D", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > D", true, ',', true);
WordKeywordGroup expectedGroupE = new WordKeywordGroup("E", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "E", true, ',', true);
GroupNodeViewModel expectedA = getViewModelForGroup(expectedGroupA);
GroupTreeNode expectedB = expectedA.addSubgroup(expectedGroupB);
expectedB.addSubgroup(expectedGroupB1);
expectedB.addSubgroup(expectedGroupB2);
expectedA.addSubgroup(expectedGroupC);
expectedA.addSubgroup(expectedGroupD);
GroupNodeViewModel expectedE = getViewModelForGroup(expectedGroupE);
ObservableList<GroupNodeViewModel> expected = FXCollections.observableArrayList(expectedA, expectedE);
assertEquals(expected, groupViewModel.getChildren());
}
@Test
void draggedOnTopOfGroupAddsBeforeIt() {
GroupNodeViewModel rootViewModel = getViewModelForGroup(new WordKeywordGroup("root", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true));
WordKeywordGroup groupA = new WordKeywordGroup("A", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true);
WordKeywordGroup groupB = new WordKeywordGroup("B", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B", true, ',', true);
WordKeywordGroup groupC = new WordKeywordGroup("C", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B > B1", true, ',', true);
GroupNodeViewModel groupAViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupA));
GroupNodeViewModel groupBViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupB));
GroupNodeViewModel groupCViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupC));
groupCViewModel.draggedOn(groupBViewModel, DroppingMouseLocation.TOP);
assertEquals(Arrays.asList(groupAViewModel, groupCViewModel, groupBViewModel), rootViewModel.getChildren());
}
@Test
void draggedOnBottomOfGroupAddsAfterIt() {
GroupNodeViewModel rootViewModel = getViewModelForGroup(new WordKeywordGroup("root", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true));
WordKeywordGroup groupA = new WordKeywordGroup("A", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true);
WordKeywordGroup groupB = new WordKeywordGroup("B", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B", true, ',', true);
WordKeywordGroup groupC = new WordKeywordGroup("C", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B > B1", true, ',', true);
GroupNodeViewModel groupAViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupA));
GroupNodeViewModel groupBViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupB));
GroupNodeViewModel groupCViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupC));
groupCViewModel.draggedOn(groupAViewModel, DroppingMouseLocation.BOTTOM);
assertEquals(Arrays.asList(groupAViewModel, groupCViewModel, groupBViewModel), rootViewModel.getChildren());
}
@Test
void draggedOnBottomOfGroupAddsAfterItWhenSourceGroupWasBefore() {
GroupNodeViewModel rootViewModel = getViewModelForGroup(new WordKeywordGroup("root", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true));
WordKeywordGroup groupA = new WordKeywordGroup("A", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true);
WordKeywordGroup groupB = new WordKeywordGroup("B", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B", true, ',', true);
WordKeywordGroup groupC = new WordKeywordGroup("C", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B > B1", true, ',', true);
GroupNodeViewModel groupAViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupA));
GroupNodeViewModel groupBViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupB));
GroupNodeViewModel groupCViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupC));
groupAViewModel.draggedOn(groupBViewModel, DroppingMouseLocation.BOTTOM);
assertEquals(Arrays.asList(groupBViewModel, groupAViewModel, groupCViewModel), rootViewModel.getChildren());
}
@Test
void draggedOnTopOfGroupAddsBeforeItWhenSourceGroupWasBefore() {
GroupNodeViewModel rootViewModel = getViewModelForGroup(new WordKeywordGroup("root", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true));
WordKeywordGroup groupA = new WordKeywordGroup("A", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A", true, ',', true);
WordKeywordGroup groupB = new WordKeywordGroup("B", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B", true, ',', true);
WordKeywordGroup groupC = new WordKeywordGroup("C", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "A > B > B1", true, ',', true);
GroupNodeViewModel groupAViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupA));
GroupNodeViewModel groupBViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupB));
GroupNodeViewModel groupCViewModel = getViewModelForGroup(rootViewModel.addSubgroup(groupC));
groupAViewModel.draggedOn(groupCViewModel, DroppingMouseLocation.TOP);
assertEquals(Arrays.asList(groupBViewModel, groupAViewModel, groupCViewModel), rootViewModel.getChildren());
}
@Test
void entriesAreAddedCorrectly() {
String groupName = "group";
ExplicitGroup group = new ExplicitGroup(groupName, GroupHierarchyType.INDEPENDENT, ',');
BibEntry entry = new BibEntry();
databaseContext.getDatabase().insertEntry(entry);
GroupNodeViewModel model = new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, group, new CustomLocalDragboard(), preferencesService);
model.addEntriesToGroup(databaseContext.getEntries());
assertEquals(databaseContext.getEntries(), model.getGroupNode().getEntriesInGroup(databaseContext.getEntries()));
assertEquals(groupName, entry.getField(StandardField.GROUPS).get());
}
private GroupNodeViewModel getViewModelForGroup(AbstractGroup group) {
return new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, group, new CustomLocalDragboard(), preferencesService);
}
private GroupNodeViewModel getViewModelForGroup(GroupTreeNode group) {
return new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, group, new CustomLocalDragboard(), preferencesService);
}
}
| 10,843 | 57.301075 | 170 | java |
null | jabref-main/src/test/java/org/jabref/gui/groups/GroupTreeViewModelTest.java | package org.jabref.gui.groups;
import java.util.Optional;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.AllEntriesGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.groups.WordKeywordGroup;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class GroupTreeViewModelTest {
private StateManager stateManager;
private GroupTreeViewModel groupTree;
private BibDatabaseContext databaseContext;
private TaskExecutor taskExecutor;
private PreferencesService preferencesService;
private DialogService dialogService;
@BeforeEach
void setUp() {
databaseContext = new BibDatabaseContext();
stateManager = new StateManager();
stateManager.activeDatabaseProperty().setValue(Optional.of(databaseContext));
taskExecutor = new CurrentThreadTaskExecutor();
preferencesService = mock(PreferencesService.class);
dialogService = mock(DialogService.class, Answers.RETURNS_DEEP_STUBS);
when(preferencesService.getGroupsPreferences()).thenReturn(new GroupsPreferences(
GroupViewMode.UNION,
true,
true,
GroupHierarchyType.INDEPENDENT));
groupTree = new GroupTreeViewModel(stateManager, mock(DialogService.class), preferencesService, taskExecutor, new CustomLocalDragboard());
}
@Test
void rootGroupIsAllEntriesByDefault() {
AllEntriesGroup allEntriesGroup = new AllEntriesGroup("All entries");
assertEquals(new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, allEntriesGroup, new CustomLocalDragboard(), preferencesService), groupTree.rootGroupProperty().getValue());
}
@Test
void rootGroupIsSelectedByDefault() {
assertEquals(groupTree.rootGroupProperty().get().getGroupNode(), stateManager.getSelectedGroup(databaseContext).get(0));
}
@Test
void explicitGroupsAreRemovedFromEntriesOnDelete() {
ExplicitGroup group = new ExplicitGroup("group", GroupHierarchyType.INDEPENDENT, ',');
BibEntry entry = new BibEntry();
databaseContext.getDatabase().insertEntry(entry);
GroupNodeViewModel model = new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, group, new CustomLocalDragboard(), preferencesService);
model.addEntriesToGroup(databaseContext.getEntries());
groupTree.removeGroupsAndSubGroupsFromEntries(model);
assertEquals(Optional.empty(), entry.getField(StandardField.GROUPS));
}
@Test
void keywordGroupsAreNotRemovedFromEntriesOnDelete() {
String groupName = "A";
WordKeywordGroup group = new WordKeywordGroup(groupName, GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, groupName, true, ',', true);
BibEntry entry = new BibEntry();
databaseContext.getDatabase().insertEntry(entry);
GroupNodeViewModel model = new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, group, new CustomLocalDragboard(), preferencesService);
model.addEntriesToGroup(databaseContext.getEntries());
groupTree.removeGroupsAndSubGroupsFromEntries(model);
assertEquals(groupName, entry.getField(StandardField.KEYWORDS).get());
}
@Test
void shouldNotShowDialogWhenGroupNameChanges() {
AbstractGroup oldGroup = new ExplicitGroup("group", GroupHierarchyType.INDEPENDENT, ',');
AbstractGroup newGroup = new ExplicitGroup("newGroupName", GroupHierarchyType.INDEPENDENT, ',');
BibEntry entry = new BibEntry();
databaseContext.getDatabase().insertEntry(entry);
GroupTreeViewModel model = new GroupTreeViewModel(stateManager, dialogService, preferencesService, taskExecutor, new CustomLocalDragboard());
assertTrue(model.onlyMinorChanges(oldGroup, newGroup));
}
@Test
void shouldNotShowDialogWhenGroupsAreEqual() {
AbstractGroup oldGroup = new WordKeywordGroup("group", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "keywordTest", true, ',', true);
AbstractGroup newGroup = new WordKeywordGroup("group", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "keywordTest", true, ',', true);
BibEntry entry = new BibEntry();
databaseContext.getDatabase().insertEntry(entry);
GroupTreeViewModel model = new GroupTreeViewModel(stateManager, dialogService, preferencesService, taskExecutor, new CustomLocalDragboard());
assertTrue(model.onlyMinorChanges(oldGroup, newGroup));
}
@Test
void shouldShowDialogWhenKeywordDiffers() {
AbstractGroup oldGroup = new WordKeywordGroup("group", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "keywordTest", true, ',', true);
AbstractGroup newGroup = new WordKeywordGroup("group", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "keywordChanged", true, ',', true);
BibEntry entry = new BibEntry();
databaseContext.getDatabase().insertEntry(entry);
GroupTreeViewModel model = new GroupTreeViewModel(stateManager, dialogService, preferencesService, taskExecutor, new CustomLocalDragboard());
assertFalse(model.onlyMinorChanges(oldGroup, newGroup));
}
@Test
void shouldShowDialogWhenCaseSensitivyDiffers() {
AbstractGroup oldGroup = new WordKeywordGroup("group", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "keywordTest", false, ',', true);
AbstractGroup newGroup = new WordKeywordGroup("group", GroupHierarchyType.INCLUDING, StandardField.KEYWORDS, "keywordChanged", true, ',', true);
BibEntry entry = new BibEntry();
databaseContext.getDatabase().insertEntry(entry);
GroupTreeViewModel model = new GroupTreeViewModel(stateManager, dialogService, preferencesService, taskExecutor, new CustomLocalDragboard());
assertFalse(model.onlyMinorChanges(oldGroup, newGroup));
}
}
| 6,682 | 46.397163 | 197 | java |
null | jabref-main/src/test/java/org/jabref/gui/importer/NewEntryActionTest.java | package org.jabref.gui.importer;
import org.jabref.gui.DialogService;
import org.jabref.gui.EntryTypeView;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class NewEntryActionTest {
private NewEntryAction newEntryAction;
private LibraryTab libraryTab = mock(LibraryTab.class);
private JabRefFrame jabRefFrame = mock(JabRefFrame.class);
private DialogService dialogService = spy(DialogService.class);
private PreferencesService preferencesService = mock(PreferencesService.class);
private StateManager stateManager = mock(StateManager.class);
@BeforeEach
public void setUp() {
when(jabRefFrame.getCurrentLibraryTab()).thenReturn(libraryTab);
when(stateManager.activeDatabaseProperty()).thenReturn(OptionalObjectProperty.empty());
newEntryAction = new NewEntryAction(jabRefFrame, dialogService, preferencesService, stateManager);
}
@Test
public void testExecuteIfNoBasePanel() {
when(jabRefFrame.getBasePanelCount()).thenReturn(0);
newEntryAction.execute();
verify(libraryTab, times(0)).insertEntry(any(BibEntry.class));
verify(dialogService, times(0)).showCustomDialogAndWait(any(EntryTypeView.class));
}
@Test
public void testExecuteOnSuccessWithFixedType() {
EntryType type = StandardEntryType.Article;
newEntryAction = new NewEntryAction(jabRefFrame, type, dialogService, preferencesService, stateManager);
when(jabRefFrame.getBasePanelCount()).thenReturn(1);
newEntryAction.execute();
verify(libraryTab, times(1)).insertEntry(new BibEntry(type));
}
}
| 2,244 | 37.050847 | 112 | java |
null | jabref-main/src/test/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModelTest.java | package org.jabref.gui.importer.fetcher;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
class WebSearchPaneViewModelTest {
private PreferencesService preferencesService;
private DialogService dialogService;
private StateManager stateManager;
private WebSearchPaneViewModel viewModel;
@BeforeEach
void setUp() {
preferencesService = Mockito.mock(PreferencesService.class, RETURNS_DEEP_STUBS);
dialogService = Mockito.mock(DialogService.class);
stateManager = Mockito.mock(StateManager.class);
viewModel = new WebSearchPaneViewModel(preferencesService, dialogService, stateManager);
}
@Test
void queryConsistingOfASingleAndIsNotValid() {
viewModel.queryProperty().setValue("AND");
assertFalse(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void falseQueryValidationStatus() {
viewModel.queryProperty().setValue("Miami !Beach AND OR Blue");
assertFalse(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void correctQueryValidationStatus() {
viewModel.queryProperty().setValue("Miami AND Beach OR Houston AND Texas");
assertTrue(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void notFalseQueryValidationStatus() {
viewModel.queryProperty().setValue("Miami !Beach AND OR Blue");
assertTrue(viewModel.queryValidationStatus().validProperty().not().getValue());
}
@Test
void notCorrectQueryValidationStatus() {
viewModel.queryProperty().setValue("Miami AND Beach OR Houston AND Texas");
assertFalse(viewModel.queryValidationStatus().validProperty().not().getValue());
}
@Test
void queryConsistingOfDOIIsValid() {
viewModel.queryProperty().setValue("10.1007/JHEP02(2023)082");
assertTrue(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void canExtractDOIFromQueryText() {
viewModel.queryProperty().setValue("this is the DOI: 10.1007/JHEP02(2023)082, other text");
assertTrue(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void queryConsistingOfInvalidDOIIsInvalid() {
viewModel.queryProperty().setValue("101.1007/JHEP02(2023)082");
assertFalse(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void queryConsistingOfISBNIsValid() {
viewModel.queryProperty().setValue("9780134685991");
assertTrue(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void canExtractISBNFromQueryText() {
viewModel.queryProperty().setValue(";:isbn (9780134685991), text2");
assertTrue(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void queryConsistingOfArXivIdIsValid() {
viewModel.queryProperty().setValue("arXiv:2110.02957");
assertTrue(viewModel.queryValidationStatus().validProperty().getValue());
}
@Test
void canExtractArXivIdFromQueryText() {
viewModel.queryProperty().setValue("this query contains an ArXiv identifier 2110.02957");
assertTrue(viewModel.queryValidationStatus().validProperty().getValue());
}
}
| 3,641 | 34.359223 | 99 | java |
null | jabref-main/src/test/java/org/jabref/gui/keyboard/KeyBindingsTabModelTest.java | package org.jabref.gui.keyboard;
import java.util.Optional;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.DialogService;
import org.jabref.gui.preferences.keybindings.KeyBindingViewModel;
import org.jabref.gui.preferences.keybindings.KeyBindingsTabViewModel;
import org.jabref.logic.util.OS;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.mockito.Mockito.mock;
/**
* Test class for the keybindings dialog view model
*/
class KeyBindingsTabModelTest {
private KeyBindingsTabViewModel model;
private KeyBindingRepository keyBindingRepository;
@BeforeEach
void setUp() {
keyBindingRepository = new KeyBindingRepository();
model = new KeyBindingsTabViewModel(keyBindingRepository, mock(DialogService.class), mock(PreferencesService.class));
}
@Test
void testInvalidKeyBindingIsNotSaved() {
setKeyBindingViewModel(KeyBinding.COPY);
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_RELEASED, "Q", "Q", KeyCode.Q, false, false, false,
false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.COPY, shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
KeyCombination combination = KeyCombination.keyCombination(keyBindingRepository.get(KeyBinding.COPY).get());
assertFalse(KeyBindingRepository.checkKeyCombinationEquality(combination, shortcutKeyEvent));
model.storeSettings();
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.COPY, shortcutKeyEvent));
}
@Test
void testSpecialKeysValidKeyBindingIsSaved() {
setKeyBindingViewModel(KeyBinding.IMPORT_INTO_NEW_DATABASE);
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_RELEASED, "F1", "F1", KeyCode.F1, false, false, false,
false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.IMPORT_INTO_NEW_DATABASE,
shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
KeyCombination combination = KeyCombination
.keyCombination(keyBindingRepository.get(KeyBinding.IMPORT_INTO_NEW_DATABASE).get());
assertTrue(KeyBindingRepository.checkKeyCombinationEquality(combination, shortcutKeyEvent));
model.storeSettings();
assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.IMPORT_INTO_NEW_DATABASE,
shortcutKeyEvent));
}
@Test
void testKeyBindingCategory() {
KeyBindingViewModel bindViewModel = new KeyBindingViewModel(keyBindingRepository, KeyBindingCategory.FILE);
model.selectedKeyBindingProperty().set(Optional.of(bindViewModel));
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "M", "M", KeyCode.M, true, true, true, false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
assertNull(model.selectedKeyBindingProperty().get().get().getKeyBinding());
}
@Test
void testRandomNewKeyKeyBindingInRepository() {
setKeyBindingViewModel(KeyBinding.CLEANUP);
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "K", "K", KeyCode.K, true, true, true, false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
KeyCombination combination = KeyCombination.keyCombination(keyBindingRepository.get(KeyBinding.CLEANUP).get());
assertTrue(KeyBindingRepository.checkKeyCombinationEquality(combination, shortcutKeyEvent));
assertFalse(KeyBindingRepository.checkKeyCombinationEquality(KeyCombination.valueOf(KeyBinding.CLEANUP.getDefaultKeyBinding()), shortcutKeyEvent));
}
@Test
void testSaveNewKeyBindingsToPreferences() {
assumeFalse(OS.OS_X);
setKeyBindingViewModel(KeyBinding.ABBREVIATE);
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "J", "J", KeyCode.J, true, true, true, false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
model.storeSettings();
assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
}
@Test
void testSaveNewSpecialKeysKeyBindingsToPreferences() {
setKeyBindingViewModel(KeyBinding.ABBREVIATE);
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "F1", "F1", KeyCode.F1, true, false, false,
false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
model.storeSettings();
assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
}
@Test
void testSetAllKeyBindingsToDefault() {
assumeFalse(OS.OS_X);
setKeyBindingViewModel(KeyBinding.ABBREVIATE);
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "C", "C", KeyCode.C, true, true, true, false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
model.storeSettings();
assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
keyBindingRepository.resetToDefault();
model.storeSettings();
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
}
@Test
void testCloseEntryEditorCloseEntryKeybinding() {
KeyBindingViewModel viewModel = setKeyBindingViewModel(KeyBinding.CLOSE);
model.selectedKeyBindingProperty().set(Optional.of(viewModel));
KeyEvent closeEditorEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE, false, false, false, false);
assertEquals(KeyBinding.CLOSE.getDefaultKeyBinding(), KeyCode.ESCAPE.getName());
KeyCombination combi = KeyCombination.valueOf(KeyBinding.CLOSE.getDefaultKeyBinding());
assertTrue(combi.match(closeEditorEvent));
assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLOSE, closeEditorEvent));
}
@Test
void testSetSingleKeyBindingToDefault() {
assumeFalse(OS.OS_X);
KeyBindingViewModel viewModel = setKeyBindingViewModel(KeyBinding.ABBREVIATE);
model.selectedKeyBindingProperty().set(Optional.of(viewModel));
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "C", "C", KeyCode.C, true, true, true, false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
model.setNewBindingForCurrent(shortcutKeyEvent);
model.storeSettings();
assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
viewModel.resetToDefault();
model.storeSettings();
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
}
private KeyBindingViewModel setKeyBindingViewModel(KeyBinding binding) {
KeyBindingViewModel viewModel = new KeyBindingViewModel(keyBindingRepository, binding, binding.getDefaultKeyBinding());
model.selectedKeyBindingProperty().set(Optional.of(viewModel));
return viewModel;
}
}
| 8,209 | 43.378378 | 155 | java |
null | jabref-main/src/test/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModelTest.java | package org.jabref.gui.libraryproperties.constants;
import java.util.List;
import javafx.beans.property.StringProperty;
import org.jabref.gui.DialogService;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibtexString;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
class ConstantsPropertiesViewModelTest {
@DisplayName("Check that the list of strings is sorted according to their keys")
@Test
void testStringsListPropertySorting() {
BibtexString string1 = new BibtexString("TSE", "Transactions on Software Engineering");
BibtexString string2 = new BibtexString("ICSE", "International Conference on Software Engineering");
BibDatabase db = new BibDatabase();
db.setStrings(List.of(string1, string2));
BibDatabaseContext context = new BibDatabaseContext(db);
DialogService service = mock(DialogService.class);
List<String> expected = List.of(string2.getName(), string1.getName()); // ICSE before TSE
ConstantsPropertiesViewModel model = new ConstantsPropertiesViewModel(context, service);
model.setValues();
List<String> actual = model.stringsListProperty().stream()
.map(ConstantsItemModel::labelProperty)
.map(StringProperty::getValue)
.toList();
assertEquals(expected, actual);
}
@DisplayName("Check that the list of strings is sorted after resorting it")
@Test
void testStringsListPropertyResorting() {
BibDatabase db = new BibDatabase();
BibDatabaseContext context = new BibDatabaseContext(db);
DialogService service = mock(DialogService.class);
List<String> expected = List.of("ICSE", "TSE");
ConstantsPropertiesViewModel model = new ConstantsPropertiesViewModel(context, service);
var stringsList = model.stringsListProperty();
stringsList.add(new ConstantsItemModel("TSE", "Transactions on Software Engineering"));
stringsList.add(new ConstantsItemModel("ICSE", "International Conference on Software Engineering"));
model.resortStrings();
List<String> actual = model.stringsListProperty().stream()
.map(ConstantsItemModel::labelProperty)
.map(StringProperty::getValue)
.toList();
assertEquals(expected, actual);
}
}
| 2,554 | 38.307692 | 108 | java |
null | jabref-main/src/test/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModelTest.java | package org.jabref.gui.libraryproperties.contentselectors;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
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.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ContentSelectorViewModelTest {
private final DialogService dialogService = mock(DialogService.class);
private final List<StandardField> DEFAULT_FIELDS = Arrays.asList(
StandardField.AUTHOR, StandardField.JOURNAL, StandardField.KEYWORDS, StandardField.PUBLISHER);
private ContentSelectorViewModel viewModel;
private BibDatabaseContext databaseContext;
@BeforeEach
void setUp() {
databaseContext = new BibDatabaseContext();
viewModel = new ContentSelectorViewModel(databaseContext, dialogService);
viewModel.setValues();
}
@Test
void initHasDefaultFieldNames() {
ListProperty<Field> expected = new SimpleListProperty<>(FXCollections.observableArrayList(DEFAULT_FIELDS));
ListProperty<Field> result = viewModel.getFieldNamesBackingList();
assertEquals(expected, result);
}
@Test
void addsNewKeyword() {
addKeyword(StandardField.KEYWORDS, "test");
ListProperty<String> expected = new SimpleListProperty<>(
FXCollections.observableArrayList("test"));
ListProperty<String> result = viewModel.getKeywordsBackingList();
assertEquals(expected, result);
}
@Test
void addsKeywordOnlyIfUnique() {
addKeyword(StandardField.KEYWORDS, "test");
addKeyword(StandardField.KEYWORDS, "test");
ListProperty<String> expected = new SimpleListProperty<>(
FXCollections.observableArrayList("test"));
ListProperty<String> result = viewModel.getKeywordsBackingList();
assertEquals(expected, result);
}
@Test
void removesKeyword() {
addKeyword(StandardField.KEYWORDS, "test");
removeKeyword(StandardField.KEYWORDS, "test");
ListProperty<String> expected = new SimpleListProperty<>(FXCollections.observableArrayList());
ListProperty<String> result = viewModel.getKeywordsBackingList();
assertEquals(expected, result);
}
@Test
void addsNewField() {
UnknownField testField = new UnknownField("Test");
addField(testField);
ListProperty<Field> fields = viewModel.getFieldNamesBackingList();
boolean fieldsContainTestValue = fields.stream().anyMatch(field -> "Test".equals(field.getDisplayName()));
assertTrue(fieldsContainTestValue);
}
@Test
void removesField() {
UnknownField testField = new UnknownField("Test");
addField(testField);
removeField(testField);
ListProperty<Field> expected = new SimpleListProperty<>(FXCollections.observableArrayList(DEFAULT_FIELDS));
ListProperty<Field> result = viewModel.getFieldNamesBackingList();
assertEquals(expected, result);
}
@Test
void displaysKeywordsInAlphabeticalOrder() {
addKeyword(StandardField.KEYWORDS, "test1");
addKeyword(StandardField.KEYWORDS, "test2");
ListProperty<String> expected = new SimpleListProperty<>(
FXCollections.observableArrayList("test1", "test2"));
ListProperty<String> result = viewModel.getKeywordsBackingList();
assertEquals(expected, result);
}
@Test
void savingPersistsDataInDatabase() {
UnknownField testField = new UnknownField("Test");
addField(testField);
addKeyword(testField, "test1");
addKeyword(testField, "test2");
viewModel.storeSettings();
List<String> result = databaseContext.getMetaData()
.getContentSelectorValuesForField(testField);
List<String> expected = Arrays.asList("test1", "test2");
assertEquals(expected, result);
}
private void addKeyword(Field field, String keyword) {
when(dialogService.showInputDialogAndWait(
Localization.lang("Add new keyword"), Localization.lang("Keyword:")))
.thenReturn(Optional.of(keyword));
viewModel.showInputKeywordDialog(field);
}
private void removeKeyword(Field field, String keyword) {
when(dialogService.showConfirmationDialogAndWait(Localization.lang("Remove keyword"),
Localization.lang("Are you sure you want to remove keyword: \"%0\"?", keyword)))
.thenReturn(true);
viewModel.showRemoveKeywordConfirmationDialog(field, keyword);
}
private void addField(Field field) {
when(dialogService.showInputDialogAndWait(
Localization.lang("Add new field name"), Localization.lang("Field name")))
.thenReturn(Optional.of(field.getDisplayName()));
viewModel.showInputFieldNameDialog();
}
private void removeField(Field field) {
when(dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove field name"),
Localization.lang("Are you sure you want to remove field name: \"%0\"?", field.getDisplayName())))
.thenReturn(true);
viewModel.showRemoveFieldNameConfirmationDialog(field);
}
}
| 5,885 | 34.672727 | 115 | java |
null | jabref-main/src/test/java/org/jabref/gui/maintable/MainTableColumnModelTest.java | package org.jabref.gui.maintable;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MainTableColumnModelTest {
private static String testName = "field:author";
private static MainTableColumnModel.Type testType = MainTableColumnModel.Type.NORMALFIELD;
private static String testQualifier = "author";
private static String testTypeOnlyName = "linked_id";
private static MainTableColumnModel.Type testTypeOnlyType = MainTableColumnModel.Type.LINKED_IDENTIFIER;
@Test
public void mainTableColumnModelParserRetrievesCorrectType() {
MainTableColumnModel testColumnModel = MainTableColumnModel.parse(testQualifier);
assertEquals(testColumnModel.getType(), testType);
}
@Test
public void mainTableColumnModelParserRetrievesCorrectQualifier() {
MainTableColumnModel testColumnModel = MainTableColumnModel.parse(testQualifier);
assertEquals(testColumnModel.getQualifier(), testQualifier);
}
@Test
public void fullMainTableColumnModelParserRetrievesCorrectType() {
MainTableColumnModel testColumnModel = MainTableColumnModel.parse(testName);
assertEquals(testColumnModel.getType(), testType);
}
@Test
public void fullMainTableColumnModelParserRetrievesCorrectQualifier() {
MainTableColumnModel testColumnModel = MainTableColumnModel.parse(testName);
assertEquals(testColumnModel.getQualifier(), testQualifier);
}
@Test
public void typeOnlyMainTableColumnModelParserRetrievesCorrectType() {
MainTableColumnModel testColumnModel = MainTableColumnModel.parse(testTypeOnlyName);
assertEquals(testColumnModel.getType(), testTypeOnlyType);
}
@Test
public void typeOnlyMainTableColumnModelParserRetrievesCorrectQualifier() {
MainTableColumnModel testColumnModel = MainTableColumnModel.parse(testTypeOnlyName);
assertEquals(testColumnModel.getQualifier(), "");
}
}
| 2,010 | 33.672414 | 108 | java |
null | jabref-main/src/test/java/org/jabref/gui/menus/FileHistoryMenuTest.java | package org.jabref.gui.menus;
import java.nio.file.Path;
import org.jabref.gui.DialogService;
import org.jabref.gui.importer.actions.OpenDatabaseAction;
import org.jabref.logic.util.io.FileHistory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.testfx.framework.junit5.ApplicationExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.MockitoAnnotations.openMocks;
@ExtendWith(ApplicationExtension.class)
public class FileHistoryMenuTest {
private static final String BIBTEX_LIBRARY_PATH = "src/test/resources/org/jabref/";
private FileHistoryMenu fileHistoryMenu;
@Mock
private FileHistory fileHistory;
@Mock
private DialogService dialogService;
@Mock
private OpenDatabaseAction openDatabaseAction;
@BeforeEach
public void setUp() {
openMocks(this);
fileHistoryMenu = new FileHistoryMenu(fileHistory, dialogService, openDatabaseAction);
}
@Test
void recentLibrariesAreCleared() {
fileHistoryMenu.newFile(Path.of(BIBTEX_LIBRARY_PATH.concat("bibtexFiles/test.bib")));
fileHistoryMenu.clearLibrariesHistory();
assertTrue(fileHistoryMenu.isDisable());
assertEquals(0, fileHistory.size());
}
}
| 1,421 | 29.913043 | 94 | java |
null | jabref-main/src/test/java/org/jabref/gui/mergeentries/DiffHighlightingTest.java | package org.jabref.gui.mergeentries;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javafx.scene.text.Text;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.framework.junit5.ApplicationExtension;
@GUITest
@ExtendWith(ApplicationExtension.class)
class DiffHighlightingTest {
public static void assertEquals(List<Text> expected, List<Text> actual) {
// Need to compare string values since Texts with the same string are not considered equal
Assertions.assertEquals(expected.toString(), actual.toString());
// Moreover, make sure that style classes are correct
List<String> expectedStyles = expected.stream().map(text -> text.getStyleClass().toString()).collect(Collectors.toList());
List<String> actualStyles = actual.stream().map(text -> text.getStyleClass().toString()).collect(Collectors.toList());
Assertions.assertEquals(expectedStyles, actualStyles);
}
@Test
void testGenerateDiffHighlightingBothNullThrowsNPE() {
Assertions.assertThrows(NullPointerException.class, () -> DiffHighlighting.generateDiffHighlighting(null, null, ""));
}
@Test
void testNullSeparatorThrowsNPE() {
Assertions.assertThrows(NullPointerException.class, () -> DiffHighlighting.generateDiffHighlighting("", "", null));
}
@Test
void testGenerateDiffHighlightingNoDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forUnchanged("f"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forUnchanged("o")
),
DiffHighlighting.generateDiffHighlighting("foo", "foo", ""));
}
@Test
void testGenerateDiffHighlightingSingleWordAddTextWordDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forRemoved("foo "),
DiffHighlighting.forAdded("foobar")
),
DiffHighlighting.generateDiffHighlighting("foo", "foobar", " "));
}
@Test
void testGenerateDiffHighlightingSingleWordAddTextCharacterDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forUnchanged("f"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forAdded("bar")
),
DiffHighlighting.generateDiffHighlighting("foo", "foobar", ""));
}
@Test
void testGenerateDiffHighlightingSingleWordDeleteTextWordDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forRemoved("foobar "),
DiffHighlighting.forAdded("foo")
),
DiffHighlighting.generateDiffHighlighting("foobar", "foo", " "));
}
@Test
void testGenerateDiffHighlightingSingleWordDeleteTextCharacterDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forUnchanged("f"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forRemoved("b"),
DiffHighlighting.forRemoved("a"),
DiffHighlighting.forRemoved("r")
),
DiffHighlighting.generateDiffHighlighting("foobar", "foo", ""));
}
@Test
void generateSymmetricHighlightingSingleWordAddTextWordDiff() {
assertEquals(
Collections.singletonList(DiffHighlighting.forChanged("foo ")),
DiffHighlighting.generateSymmetricHighlighting("foo", "foobar", " "));
}
@Test
void generateSymmetricHighlightingSingleWordAddTextCharacterDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forUnchanged("f"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forUnchanged("o")
),
DiffHighlighting.generateSymmetricHighlighting("foo", "foobar", ""));
}
@Test
void generateSymmetricHighlightingSingleWordDeleteTextWordDiff() {
assertEquals(
Collections.singletonList(DiffHighlighting.forChanged("foobar ")),
DiffHighlighting.generateSymmetricHighlighting("foobar", "foo", " "));
}
@Test
void generateSymmetricHighlightingSingleWordDeleteTextCharacterDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forUnchanged("f"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forAdded("b"),
DiffHighlighting.forAdded("a"),
DiffHighlighting.forAdded("r")
),
DiffHighlighting.generateSymmetricHighlighting("foobar", "foo", ""));
}
@Test
void generateSymmetricHighlightingMultipleWordsDeleteTextCharacterDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forUnchanged("f"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forUnchanged("o"),
DiffHighlighting.forAdded("b"),
DiffHighlighting.forAdded("a"),
DiffHighlighting.forAdded("r"),
DiffHighlighting.forUnchanged(" "),
DiffHighlighting.forUnchanged("a"),
DiffHighlighting.forUnchanged("n"),
DiffHighlighting.forUnchanged("d"),
DiffHighlighting.forUnchanged(" "),
DiffHighlighting.forAdded("s"),
DiffHighlighting.forAdded("o"),
DiffHighlighting.forAdded("m"),
DiffHighlighting.forAdded("e"),
DiffHighlighting.forUnchanged("t"),
DiffHighlighting.forUnchanged("h"),
DiffHighlighting.forUnchanged("i"),
DiffHighlighting.forUnchanged("n"),
DiffHighlighting.forUnchanged("g")
),
DiffHighlighting.generateSymmetricHighlighting("foobar and something", "foo and thing", ""));
}
@Test
void generateSymmetricHighlightingMultipleWordsDeleteTextWordDiff() {
assertEquals(
Arrays.asList(
DiffHighlighting.forUnchanged("foo "),
DiffHighlighting.forAdded("bar "),
DiffHighlighting.forUnchanged("and "),
DiffHighlighting.forAdded("some "),
DiffHighlighting.forUnchanged("thing ")
),
DiffHighlighting.generateSymmetricHighlighting("foo bar and some thing", "foo and thing", " "));
}
}
| 7,326 | 40.162921 | 130 | java |
null | jabref-main/src/test/java/org/jabref/gui/mergeentries/FieldRowViewModelTest.java | package org.jabref.gui.mergeentries;
import java.util.Optional;
import org.jabref.gui.mergeentries.newmergedialog.FieldRowViewModel;
import org.jabref.gui.mergeentries.newmergedialog.fieldsmerger.FieldMergerFactory;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.Month;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.preferences.BibEntryPreferences;
import org.jbibtex.ParseException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class FieldRowViewModelTest {
BibEntry leftEntry;
BibEntry rightEntry;
BibEntry extraEntry;
BibEntry mergedEntry;
FieldMergerFactory fieldMergerFactory;
BibEntryPreferences bibEntryPreferences = mock(BibEntryPreferences.class);
@BeforeEach
public void setup() throws ParseException {
leftEntry = new BibEntry(StandardEntryType.Article)
.withCitationKey("LajnDiezScheinEtAl2012")
.withField(StandardField.AUTHOR, "Lajn, A and Diez, T and Schein, F and Frenzel, H and von Wenckstern, H and Grundmann, M")
.withField(StandardField.TITLE, "Light and temperature stability of fully transparent ZnO-based inverter circuits")
.withField(StandardField.NUMBER, "4")
.withField(StandardField.PAGES, "515--517")
.withField(StandardField.VOLUME, "32")
.withField(StandardField.GROUPS, "Skimmed")
.withField(StandardField.JOURNAL, "Electron Device Letters, IEEE")
.withField(StandardField.PUBLISHER, "IEEE")
.withField(StandardField.YEAR, "2012");
rightEntry = new BibEntry(StandardEntryType.Book)
.withCitationKey("KolbLenhardWirtz2012")
.withField(StandardField.AUTHOR, "Stefan Kolb and Guido Wirtz")
.withField(StandardField.BOOKTITLE, "Proceedings of the 5\\textsuperscript{th} {IEEE} International Conference on Service-Oriented Computing and Applications {(SOCA'12)}, Taipei, Taiwan")
.withField(StandardField.TITLE, "{Bridging the Heterogeneity of Orchestrations - A Petri Net-based Integration of BPEL and Windows Workflow}")
.withField(StandardField.ORGANIZATION, "IEEE")
.withField(StandardField.PAGES, "1--8")
.withField(StandardField.ADDRESS, "Oxford, United Kingdom")
.withField(StandardField.GROUPS, "By rating, Skimmed")
.withMonth(Month.DECEMBER)
.withField(StandardField.KEYWORDS, "a, b, c")
.withField(StandardField.YEAR, "2012");
extraEntry = new BibEntry(StandardEntryType.InProceedings)
.withCitationKey("BoopalGarridoGustafsson2013")
.withField(StandardField.AUTHOR, "Padma Prasad Boopal and Mario Garrido and Oscar Gustafsson")
.withField(StandardField.BOOKTITLE, "2013 {IEEE} International Symposium on Circuits and Systems (ISCAS2013), Beijing, China, May 19-23, 2013")
.withField(StandardField.TITLE, "A reconfigurable {FFT} architecture for variable-length and multi-streaming {OFDM} standards")
.withField(StandardField.KEYWORDS, "b, c, a")
.withField(StandardField.YEAR, "2013");
mergedEntry = new BibEntry();
fieldMergerFactory = new FieldMergerFactory(bibEntryPreferences);
when(bibEntryPreferences.getKeywordSeparator()).thenReturn(',');
}
@Test
public void selectNonEmptyValueShouldSelectLeftFieldValueIfItIsNotEmpty() {
var numberFieldViewModel = createViewModelForField(StandardField.NUMBER);
numberFieldViewModel.selectNonEmptyValue();
assertEquals(FieldRowViewModel.Selection.LEFT, numberFieldViewModel.getSelection());
var authorFieldViewModel = createViewModelForField(StandardField.AUTHOR);
authorFieldViewModel.selectNonEmptyValue();
assertEquals(FieldRowViewModel.Selection.LEFT, authorFieldViewModel.getSelection());
}
@Test
public void selectNonEmptyValueShouldSelectRightFieldValueIfLeftValueIsEmpty() {
var monthFieldViewModel = createViewModelForField(StandardField.MONTH);
monthFieldViewModel.selectNonEmptyValue();
assertEquals(FieldRowViewModel.Selection.RIGHT, monthFieldViewModel.getSelection());
var addressFieldViewModel = createViewModelForField(StandardField.ADDRESS);
addressFieldViewModel.selectNonEmptyValue();
assertEquals(FieldRowViewModel.Selection.RIGHT, addressFieldViewModel.getSelection());
}
@Test
public void hasEqualLeftAndRightValuesShouldReturnFalseIfOneOfTheValuesIsEmpty() {
var monthFieldViewModel = createViewModelForField(StandardField.MONTH);
monthFieldViewModel.selectNonEmptyValue();
assertFalse(monthFieldViewModel.hasEqualLeftAndRightValues());
}
@Test
public void hasEqualLeftAndRightValuesShouldReturnTrueIfLeftAndRightAreEqual() {
var yearFieldViewModel = createViewModelForField(StandardField.YEAR);
yearFieldViewModel.selectNonEmptyValue();
assertTrue(yearFieldViewModel.hasEqualLeftAndRightValues());
}
@Test
@Disabled("This test is kept as a reminder to implement a different comparison logic based on the given field.")
public void hasEqualLeftAndRightValuesShouldReturnTrueIfKeywordsAreEqual() {
FieldRowViewModel keywordsField = new FieldRowViewModel(StandardField.KEYWORDS, rightEntry, extraEntry, mergedEntry, fieldMergerFactory);
assertTrue(keywordsField.hasEqualLeftAndRightValues());
}
@Test
public void selectLeftValueShouldBeCorrect() {
var monthFieldViewModel = createViewModelForField(StandardField.MONTH);
monthFieldViewModel.selectLeftValue();
assertEquals(FieldRowViewModel.Selection.LEFT, monthFieldViewModel.getSelection());
assertEquals(Optional.of(""), Optional.ofNullable(monthFieldViewModel.getMergedFieldValue()));
monthFieldViewModel.selectRightValue();
monthFieldViewModel.selectLeftValue();
assertEquals(FieldRowViewModel.Selection.LEFT, monthFieldViewModel.getSelection());
assertEquals(Optional.of(""), Optional.of(monthFieldViewModel.getMergedFieldValue()));
}
@Test
public void selectRightValueShouldBeCorrect() {
var monthFieldViewModel = createViewModelForField(StandardField.MONTH);
monthFieldViewModel.selectRightValue();
assertEquals(FieldRowViewModel.Selection.RIGHT, monthFieldViewModel.getSelection());
assertEquals(rightEntry.getField(StandardField.MONTH), Optional.of(monthFieldViewModel.getMergedFieldValue()));
monthFieldViewModel.selectLeftValue();
monthFieldViewModel.selectRightValue();
assertEquals(FieldRowViewModel.Selection.RIGHT, monthFieldViewModel.getSelection());
assertEquals(rightEntry.getField(StandardField.MONTH), Optional.of(monthFieldViewModel.getMergedFieldValue()));
}
@Test
public void isFieldsMergedShouldReturnTrueIfLeftAndRightValuesAreEqual() {
var yearFieldViewModel = createViewModelForField(StandardField.YEAR);
assertTrue(yearFieldViewModel.isFieldsMerged());
}
@Test
public void isFieldsMergedShouldReturnFalseIfLeftAndRightValuesAreNotEqual() {
var monthFieldViewModel = createViewModelForField(StandardField.MONTH);
assertFalse(monthFieldViewModel.isFieldsMerged());
var addressFieldViewModel = createViewModelForField(StandardField.ADDRESS);
assertFalse(addressFieldViewModel.isFieldsMerged());
var authorFieldViewModel = createViewModelForField(StandardField.AUTHOR);
assertFalse(authorFieldViewModel.isFieldsMerged());
}
@Test
public void mergeFieldsShouldResultInLeftAndRightValuesBeingEqual() {
var groupsField = createViewModelForField(StandardField.GROUPS);
groupsField.mergeFields();
assertEquals(groupsField.getLeftFieldValue(), groupsField.getRightFieldValue());
}
@Test
public void mergeFieldsShouldBeCorrectEvenWhenOnOfTheValuesIsEmpty() {
var keywordsField = createViewModelForField(StandardField.KEYWORDS);
keywordsField.mergeFields();
assertEquals(keywordsField.getLeftFieldValue(), keywordsField.getRightFieldValue());
}
@Test
public void mergeFieldsShouldThrowUnsupportedOperationExceptionIfTheGivenFieldCanBeMerged() {
var authorField = createViewModelForField(StandardField.AUTHOR);
assertThrows(UnsupportedOperationException.class, authorField::mergeFields);
}
@Test
public void mergeFieldsShouldSelectLeftFieldValue() {
var groupsField = createViewModelForField(StandardField.GROUPS);
groupsField.mergeFields();
assertEquals(FieldRowViewModel.Selection.LEFT, groupsField.getSelection());
}
@Test
public void unmergeFieldsShouldBeCorrect() {
var groupsField = createViewModelForField(StandardField.GROUPS);
var oldLeftGroups = groupsField.getLeftFieldValue();
var oldRightGroups = groupsField.getRightFieldValue();
groupsField.mergeFields();
groupsField.unmergeFields();
assertEquals(oldLeftGroups, groupsField.getLeftFieldValue());
assertEquals(oldRightGroups, groupsField.getRightFieldValue());
}
@Test
public void unmergeFieldsShouldDoNothingIfFieldsAreNotMerged() {
var groupsField = createViewModelForField(StandardField.GROUPS);
var oldLeftGroups = groupsField.getLeftFieldValue();
var oldRightGroups = groupsField.getRightFieldValue();
groupsField.unmergeFields();
assertEquals(oldLeftGroups, groupsField.getLeftFieldValue());
assertEquals(oldRightGroups, groupsField.getRightFieldValue());
}
public FieldRowViewModel createViewModelForField(Field field) {
return new FieldRowViewModel(field, leftEntry, rightEntry, mergedEntry, fieldMergerFactory);
}
}
| 10,500 | 46.301802 | 203 | java |
null | jabref-main/src/test/java/org/jabref/gui/mergeentries/GroupMergerTest.java | package org.jabref.gui.mergeentries;
import java.util.stream.Stream;
import org.jabref.gui.mergeentries.newmergedialog.fieldsmerger.GroupMerger;
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 GroupMergerTest {
GroupMerger groupMerger;
@BeforeEach
void setup() {
this.groupMerger = new GroupMerger();
}
private static Stream<Arguments> mergeShouldMergeGroupsCorrectly() {
return Stream.of(
Arguments.of("a", "b", "a, b"),
Arguments.of("a", "", "a"),
Arguments.of("", "", ""),
Arguments.of("", "b", "b"),
Arguments.of("a, b", "c", "a, b, c"),
Arguments.of("a, b, c", "c", "a, b, c"),
Arguments.of("a, b", "c, d", "a, b, c, d"),
Arguments.of("a, b, c", "b, z", "a, b, c, z")
);
}
@ParameterizedTest
@MethodSource
public void mergeShouldMergeGroupsCorrectly(String groupsA, String groupsB, String expected) {
assertEquals(expected, groupMerger.merge(groupsA, groupsB));
}
}
| 1,302 | 30.02381 | 98 | java |
null | jabref-main/src/test/java/org/jabref/gui/mergeentries/ThreeWayMergeCellViewModelTest.java | package org.jabref.gui.mergeentries;
import java.util.stream.Stream;
import org.jabref.gui.mergeentries.newmergedialog.cell.ThreeWayMergeCellViewModel;
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 ThreeWayMergeCellViewModelTest {
ThreeWayMergeCellViewModel viewModel;
@BeforeEach
void setup() {
viewModel = new ThreeWayMergeCellViewModel("Hello", 0);
}
private static Stream<Arguments> testOddEvenLogic() {
return Stream.of(
Arguments.of(true, false, true, false),
Arguments.of(false, false, true, false),
Arguments.of(true, true, false, true),
Arguments.of(false, true, false, true)
);
}
private static Stream<Arguments> isEvenShouldReturnTrueIfRowIndexIsEven() {
return Stream.of(
Arguments.of(0, true),
Arguments.of(100, true),
Arguments.of(1, false),
Arguments.of(2, true),
Arguments.of(9999, false),
Arguments.of(Integer.MAX_VALUE, false)
);
}
private static Stream<Arguments> isOddShouldReturnTrueIfRowIndexIsOdd() {
return Stream.of(
Arguments.of(1, true),
Arguments.of(101, true),
Arguments.of(3, true),
Arguments.of(7777, true),
Arguments.of(9999, true),
Arguments.of(Integer.MAX_VALUE, true),
Arguments.of(0, false)
);
}
private static Stream<Arguments> getTextAndSetTextShouldBeConsistent() {
return Stream.of(
Arguments.of(""),
Arguments.of("Hello"),
Arguments.of("World"),
Arguments.of("" + null),
Arguments.of("Hello, World"),
Arguments.of("عربي")
);
}
@ParameterizedTest
@MethodSource
void testOddEvenLogic(boolean setIsOdd, boolean setIsEven, boolean expectedIsOdd, boolean expectedIsEven) {
viewModel.setOdd(setIsOdd);
viewModel.setEven(setIsEven);
assertEquals(expectedIsOdd, viewModel.isOdd());
assertEquals(expectedIsEven, viewModel.isEven());
}
@ParameterizedTest
@MethodSource
void isEvenShouldReturnTrueIfRowIndexIsEven(int rowIndex, boolean expected) {
ThreeWayMergeCellViewModel newViewModel = new ThreeWayMergeCellViewModel("", rowIndex);
assertEquals(expected, newViewModel.isEven());
}
@ParameterizedTest
@MethodSource
void isOddShouldReturnTrueIfRowIndexIsOdd(int rowIndex, boolean expected) {
ThreeWayMergeCellViewModel newViewModel = new ThreeWayMergeCellViewModel("", rowIndex);
assertEquals(expected, newViewModel.isOdd());
}
@ParameterizedTest
@MethodSource
void getTextAndSetTextShouldBeConsistent(String setText) {
viewModel.setText(setText);
assertEquals(viewModel.getText(), setText);
}
}
| 3,202 | 32.364583 | 111 | java |
null | jabref-main/src/test/java/org/jabref/gui/mergeentries/ThreeWayMergeViewModelTest.java | package org.jabref.gui.mergeentries;
import java.util.HashSet;
import java.util.List;
import org.jabref.gui.mergeentries.newmergedialog.ThreeWayMergeViewModel;
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.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.StandardEntryType;
import com.google.common.collect.Comparators;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ThreeWayMergeViewModelTest {
ThreeWayMergeViewModel viewModel;
BibEntry leftEntry;
BibEntry rightEntry;
List<Field> visibleFields;
@BeforeEach
void setup() {
leftEntry = new BibEntry(StandardEntryType.Article)
.withField(StandardField.AUTHOR, "Erik G. Larsson and Oscar Gustafsson")
.withField(StandardField.TITLE, "The Impact of Dynamic Voltage and Frequency Scaling on Multicore {DSP} Algorithm Design [Exploratory {DSP]}")
.withField(StandardField.NUMBER, "1")
.withField(new UnknownField("custom"), "1.2.3");
rightEntry = new BibEntry(StandardEntryType.InProceedings)
.withField(StandardField.AUTHOR, "Henrik Ohlsson and Oscar Gustafsson and Lars Wanhammar")
.withField(StandardField.TITLE, "Arithmetic transformations for increased maximal sample rate of bit-parallel bireciprocal lattice wave digital filters")
.withField(StandardField.BOOKTITLE, "Proceedings of the 2001 International Symposium on Circuits and Systems, {ISCAS} 2001, Sydney, Australia, May 6-9, 2001")
.withField(StandardField.NUMBER, "2");
viewModel = new ThreeWayMergeViewModel(leftEntry, rightEntry, "left", "right");
visibleFields = viewModel.getVisibleFields();
}
@Test
void getVisibleFieldsShouldReturnASortedListOfFieldsWithEntryTypeAtTheHeadOfTheList() {
List<String> names = visibleFields.stream().map(Field::getName).skip(1).toList();
Comparators.isInOrder(names, String::compareTo);
}
@Test
void getVisibleFieldsShouldNotHaveDuplicates() {
assertEquals(new HashSet<>(visibleFields).size(), viewModel.numberOfVisibleFields());
}
@Test
void getVisibleFieldsShouldHaveEntryTypeFieldAtTheHeadOfTheList() {
assertEquals(InternalField.TYPE_HEADER, visibleFields.get(0));
}
@Test
void getVisibleFieldsShouldContainAllNonInternalFieldsInRightAndLeftEntry() {
assertTrue(visibleFields.containsAll(leftEntry.getFields().stream().filter(this::isNotInternalField).toList()));
assertTrue(visibleFields.containsAll(rightEntry.getFields().stream().filter(this::isNotInternalField).toList()));
}
@Test
void getVisibleFieldsShouldIncludeCustomFields() {
assertTrue(visibleFields.contains(new UnknownField("custom")));
}
private boolean isNotInternalField(Field field) {
return !FieldFactory.isInternalField(field);
}
}
| 3,276 | 41.558442 | 174 | java |
null | jabref-main/src/test/java/org/jabref/gui/preferences/journals/AbbreviationViewModelTest.java | package org.jabref.gui.preferences.journals;
import java.util.stream.Stream;
import org.jabref.logic.journals.Abbreviation;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AbbreviationViewModelTest {
@ParameterizedTest
@MethodSource("provideContainsCaseIndependentContains")
void containsCaseIndependentContains(String searchTerm, AbbreviationViewModel abbreviation) {
assertTrue(abbreviation.containsCaseIndependent(searchTerm));
}
private static Stream<Arguments> provideContainsCaseIndependentContains() {
return Stream.of(
Arguments.of("name", new AbbreviationViewModel(new Abbreviation("Long Name", "abbr", "unique"))),
Arguments.of("bBr", new AbbreviationViewModel(new Abbreviation("Long Name", "abbr", "unique"))),
Arguments.of("Uniq", new AbbreviationViewModel(new Abbreviation("Long Name", "abbr", "unique"))),
Arguments.of("", new AbbreviationViewModel(new Abbreviation("Long Name", "abbr", "unique"))),
Arguments.of("", new AbbreviationViewModel(new Abbreviation("", "", "")))
);
}
@ParameterizedTest
@MethodSource("provideContainsCaseIndependentDoesNotContain")
void containsCaseIndependentDoesNotContain(String searchTerm, AbbreviationViewModel abbreviation) {
assertFalse(abbreviation.containsCaseIndependent(searchTerm));
}
private static Stream<Arguments> provideContainsCaseIndependentDoesNotContain() {
return Stream.of(
Arguments.of("Something else", new AbbreviationViewModel(new Abbreviation("Long Name", "abbr", "unique"))),
Arguments.of("Something", new AbbreviationViewModel(new Abbreviation("", "", "")))
);
}
}
| 1,989 | 43.222222 | 123 | java |
null | jabref-main/src/test/java/org/jabref/gui/preferences/journals/JournalAbbreviationsViewModelTabTest.java | package org.jabref.gui.preferences.journals;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.Abbreviation;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.journals.JournalAbbreviationPreferences;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class JournalAbbreviationsViewModelTabTest {
private final static TestAbbreviation ABBREVIATION_0 = new TestAbbreviation("Full0", "Abb0");
private final static TestAbbreviation ABBREVIATION_0_OTHER_SHORT_UNIQUE = new TestAbbreviation("Full0", "Abb0", "A0");
private final static TestAbbreviation ABBREVIATION_1 = new TestAbbreviation("Full1", "Abb1");
private final static TestAbbreviation ABBREVIATION_1_SHOW = new TestAbbreviation("Full1", "Abb1", true);
private final static TestAbbreviation ABBREVIATION_1_OTHER_SHORT_UNIQUE = new TestAbbreviation("Full1", "Abb1", "A1");
private final static TestAbbreviation ABBREVIATION_2 = new TestAbbreviation("Full2", "Abb2");
private final static TestAbbreviation ABBREVIATION_2_OTHER_SHORT_UNIQUE = new TestAbbreviation("Full2", "Abb2", "A2");
private final static TestAbbreviation ABBREVIATION_3 = new TestAbbreviation("Full3", "Abb3");
private final static TestAbbreviation ABBREVIATION_3_OTHER_SHORT_UNIQUE = new TestAbbreviation("Full3", "Abb3", "A3");
private final static TestAbbreviation ABBREVIATION_4 = new TestAbbreviation("Full4", "Abb4");
private final static TestAbbreviation ABBREVIATION_5 = new TestAbbreviation("Full5", "Abb5");
private final static TestAbbreviation ABBREVIATION_6 = new TestAbbreviation("Full6", "Abb6");
private JournalAbbreviationsTabViewModel viewModel;
private Path emptyTestFile;
private Path tempFolder;
private final JournalAbbreviationRepository repository = JournalAbbreviationLoader.loadBuiltInRepository();
private DialogService dialogService;
static class TestAbbreviation extends Abbreviation {
private final boolean showShortestUniqueAbbreviation;
public TestAbbreviation(String name, String abbreviation) {
this(name, abbreviation, false);
}
public TestAbbreviation(String name, String abbreviation, boolean showShortestUniqueAbbreviation) {
super(name, abbreviation);
this.showShortestUniqueAbbreviation = showShortestUniqueAbbreviation;
}
public TestAbbreviation(String name, String abbreviation, String shortestUniqueAbbreviation) {
super(name, abbreviation, shortestUniqueAbbreviation);
this.showShortestUniqueAbbreviation = true;
}
@Override
public String toString() {
if (showShortestUniqueAbbreviation) {
return this.getName() + ";" + this.getAbbreviation() + ";" + this.getShortestUniqueAbbreviation();
}
return this.getName() + ";" + this.getAbbreviation();
}
}
private static String csvListOfAbbreviations(List<TestAbbreviation> testAbbreviations) {
return testAbbreviations.stream()
.map(TestAbbreviation::toString)
.collect(Collectors.joining("\n"));
}
private static String csvListOfAbbreviations(TestAbbreviation... testAbbreviations) {
return csvListOfAbbreviations(Arrays.stream(testAbbreviations).toList());
}
private record CsvFileNameAndContent(String fileName, String content) {
CsvFileNameAndContent(String fileName, TestAbbreviation... testAbbreviations) {
this(fileName, csvListOfAbbreviations(testAbbreviations));
}
}
private record TestData(
List<CsvFileNameAndContent> csvFiles,
TestAbbreviation abbreviationToCheck,
List<String> finalContentsOfFile2,
List<String> finalContentsOfFile3
) {
/**
* Note that we have a **different** ordering at the constructor, because Java generics have "type erasure"
*/
public TestData(
List<CsvFileNameAndContent> csvFiles,
List<TestAbbreviation> finalContentsOfFile2,
List<TestAbbreviation> finalContentsOfFile3,
TestAbbreviation abbreviationToCheck
) {
this(csvFiles,
abbreviationToCheck,
finalContentsOfFile2.stream().map(TestAbbreviation::toString).toList(),
finalContentsOfFile3.stream().map(TestAbbreviation::toString).toList());
}
}
public static Stream<TestData> provideTestFiles() {
// filenameing: testfileXY, where X is the number of test (count starts at 1), and Y is the number of the file in the test (count starts at 0)
// testfile_3 has 5 entries after de-duplication
return Stream.of(
// No shortest unique abbreviations in files
// Shortest unique abbreviations in entries (being the same then the abbreviation)
new TestData(
List.of(
new CsvFileNameAndContent("testFile10.csv", ABBREVIATION_1),
new CsvFileNameAndContent("testFile11.csv", ABBREVIATION_0, ABBREVIATION_1, ABBREVIATION_2),
new CsvFileNameAndContent("testFile12.csv", ABBREVIATION_0, ABBREVIATION_1, ABBREVIATION_2, ABBREVIATION_3),
new CsvFileNameAndContent("testFile13.csv", ABBREVIATION_0, ABBREVIATION_1, ABBREVIATION_1, ABBREVIATION_2, ABBREVIATION_3, ABBREVIATION_4)),
List.of(ABBREVIATION_0, ABBREVIATION_1, ABBREVIATION_2, ABBREVIATION_5),
List.of(ABBREVIATION_0, ABBREVIATION_1, ABBREVIATION_2, ABBREVIATION_3, ABBREVIATION_6),
ABBREVIATION_1_SHOW),
// Shortest unique abbreviations
new TestData(
List.of(
new CsvFileNameAndContent("testFile20.csv", ABBREVIATION_1_OTHER_SHORT_UNIQUE),
new CsvFileNameAndContent("testFile21.csv", ABBREVIATION_0_OTHER_SHORT_UNIQUE, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_2_OTHER_SHORT_UNIQUE),
new CsvFileNameAndContent("testFile22.csv", ABBREVIATION_0_OTHER_SHORT_UNIQUE, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_3_OTHER_SHORT_UNIQUE),
// contains duplicate entry ABBREVIATION_1_OTHER_SHORT_UNIQUE, therefore 6 entries
new CsvFileNameAndContent("testFile23.csv", ABBREVIATION_0_OTHER_SHORT_UNIQUE, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_3, ABBREVIATION_4)),
List.of(ABBREVIATION_0_OTHER_SHORT_UNIQUE, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_5),
// without duplicates
List.of(ABBREVIATION_0_OTHER_SHORT_UNIQUE, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_3, ABBREVIATION_6),
ABBREVIATION_1_OTHER_SHORT_UNIQUE),
// Mixed abbreviations (some have shortest unique, some have not)
new TestData(
List.of(
new CsvFileNameAndContent("testFile30.csv", ABBREVIATION_1),
new CsvFileNameAndContent("testFile31.csv", ABBREVIATION_0_OTHER_SHORT_UNIQUE, ABBREVIATION_1, ABBREVIATION_2_OTHER_SHORT_UNIQUE),
new CsvFileNameAndContent("testFile32.csv", ABBREVIATION_0, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_3),
// contains ABBREVIATION_1 in two variants, therefore 5 in total
new CsvFileNameAndContent("testFile33.csv", ABBREVIATION_0, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_1, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_4)),
// Entries of testFile2 plus ABBREVIATION_5_SHOW minus ABBREVIATION_3
List.of(ABBREVIATION_0, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_5),
// Entries of testFile3 plus ABBREVIATION_6_SHOW minus ABBREVIATION_4
List.of(ABBREVIATION_0, ABBREVIATION_1_OTHER_SHORT_UNIQUE, ABBREVIATION_1, ABBREVIATION_2_OTHER_SHORT_UNIQUE, ABBREVIATION_6),
ABBREVIATION_1_OTHER_SHORT_UNIQUE)
);
}
@BeforeEach
void setUpViewModel(@TempDir Path tempFolder) throws Exception {
JournalAbbreviationPreferences abbreviationPreferences = mock(JournalAbbreviationPreferences.class);
dialogService = mock(DialogService.class);
this.tempFolder = tempFolder;
TaskExecutor taskExecutor = new CurrentThreadTaskExecutor();
viewModel = new JournalAbbreviationsTabViewModel(abbreviationPreferences, dialogService, taskExecutor, repository);
emptyTestFile = createTestFile(new CsvFileNameAndContent("emptyTestFile.csv", ""));
}
@Test
void testInitialHasNoFilesAndNoAbbreviations() {
assertEquals(0, viewModel.journalFilesProperty().size());
assertEquals(0, viewModel.abbreviationsProperty().size());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testInitialWithSavedFilesIncrementsFilesCounter(TestData testData) throws IOException {
addFourTestFileToViewModelAndPreferences(testData);
assertEquals(4, viewModel.journalFilesProperty().size());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testRemoveDuplicatesWhenReadingFiles(TestData testData) throws IOException {
addFourTestFileToViewModelAndPreferences(testData);
viewModel.selectLastJournalFile();
assertEquals(4, viewModel.journalFilesProperty().size());
assertEquals(5, viewModel.abbreviationsProperty().size());
}
@Test
void addFileIncreasesCounterOfOpenFilesAndHasNoAbbreviations() {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
viewModel.addNewFile();
assertEquals(1, viewModel.journalFilesProperty().size());
assertEquals(0, viewModel.abbreviationsProperty().size());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void addDuplicatedFileResultsInErrorDialog(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(0))));
viewModel.addNewFile();
viewModel.addNewFile();
verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testOpenDuplicatedFileResultsInAnException(TestData testData) throws IOException {
when(dialogService.showFileOpenDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(0))));
viewModel.openFile();
viewModel.openFile();
verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testSelectLastJournalFileSwitchesFilesAndTheirAbbreviations(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
assertEquals(0, viewModel.abbreviationsCountProperty().get());
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(0))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
assertEquals(1, viewModel.abbreviationsCountProperty().get());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testOpenValidFileContainsTheSpecificEntryAndEnoughAbbreviations(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(2))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
assertEquals(1, viewModel.journalFilesProperty().size());
assertEquals(4, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testData.abbreviationToCheck)));
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testRemoveLastListSetsCurrentFileAndCurrentAbbreviationToNull(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(0))));
viewModel.addNewFile();
viewModel.removeCurrentFile();
assertEquals(0, viewModel.journalFilesProperty().size());
assertEquals(0, viewModel.abbreviationsProperty().size());
assertNull(viewModel.currentFileProperty().get());
assertNull(viewModel.currentAbbreviationProperty().get());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testMixedFileUsage(TestData testData) throws IOException {
// simulate open file button twice
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(1))));
viewModel.addNewFile();
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(2))));
viewModel.addNewFile();
viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(1));
// size of the list of journal files should be incremented by two
assertEquals(2, viewModel.journalFilesProperty().size());
// our third test file has 4 abbreviations
assertEquals(4, viewModel.abbreviationsProperty().size());
// check "arbitrary" abbreviation
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testData.abbreviationToCheck)));
// simulate add new file button
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
viewModel.addNewFile();
viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(2));
// size of the list of journal files should be incremented by one
assertEquals(3, viewModel.journalFilesProperty().size());
// a new file has zero abbreviations
assertEquals(0, viewModel.abbreviationsProperty().size());
// simulate opening of testFile_3
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(3))));
viewModel.addNewFile();
viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(3));
// size of the list of journal files should have been incremented by one
assertEquals(4, viewModel.journalFilesProperty().size());
// after de-duplication
assertEquals(5, viewModel.abbreviationsProperty().size());
// check "arbitrary" abbreviation
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testData.abbreviationToCheck)));
}
@Test
void testBuiltInListsIncludeAllBuiltInAbbreviations() {
viewModel.addBuiltInList();
assertEquals(1, viewModel.journalFilesProperty().getSize());
viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0));
ObservableList<Abbreviation> expected = FXCollections.observableArrayList(repository.getAllLoaded());
ObservableList<Abbreviation> actualAbbreviations = FXCollections
.observableArrayList(viewModel.abbreviationsProperty().stream()
.map(AbbreviationViewModel::getAbbreviationObject)
.collect(Collectors.toList()));
assertEquals(expected, actualAbbreviations);
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testCurrentFilePropertyChangeActiveFile(TestData testData) throws IOException {
for (CsvFileNameAndContent testFile : testData.csvFiles) {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testFile)));
viewModel.addNewFile();
}
viewModel.selectLastJournalFile();
AbbreviationsFileViewModel test1 = viewModel.journalFilesProperty().get(0);
AbbreviationsFileViewModel test3 = viewModel.journalFilesProperty().get(1);
AbbreviationsFileViewModel test4 = viewModel.journalFilesProperty().get(2);
AbbreviationsFileViewModel test5 = viewModel.journalFilesProperty().get(3);
// test if the last opened file is active, but duplicated entry has been removed
assertEquals(5, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test1);
// test if the current abbreviations matches with the ones in testFile1Entries
assertEquals(1, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test3);
assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test1);
assertEquals(1, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test4);
assertEquals(4, viewModel.abbreviationsProperty().size());
viewModel.currentFileProperty().set(test5);
assertEquals(5, viewModel.abbreviationsProperty().size());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testAddAbbreviationIncludesAbbreviationsInAbbreviationList(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(2))));
viewModel.addNewFile();
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(3))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
viewModel.addAbbreviation(testAbbreviation);
assertEquals(6, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testAddDuplicatedAbbreviationResultsInException(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
viewModel.addAbbreviation(new Abbreviation("YetAnotherEntry", "YAE"));
viewModel.addAbbreviation(new Abbreviation("YetAnotherEntry", "YAE"));
verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
}
@Test
void testEditSameAbbreviationWithNoChangeDoesNotResultInException() {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
viewModel.addAbbreviation(testAbbreviation);
viewModel.editAbbreviation(testAbbreviation);
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testEditAbbreviationIncludesNewAbbreviationInAbbreviationsList(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(2))));
viewModel.addNewFile();
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(3))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
Abbreviation testAbbreviation = new Abbreviation("YetAnotherEntry", "YAE");
viewModel.addAbbreviation(testAbbreviation);
assertEquals(6, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(emptyTestFile));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
// addAbbreviation(testAbbreviation);
assertEquals(0, viewModel.abbreviationsProperty().size());
assertFalse(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(testAbbreviation)));
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testEditAbbreviationToExistingOneResultsInException(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.editAbbreviation(new Abbreviation("YetAnotherEntry", "YAE"));
viewModel.currentAbbreviationProperty().set(viewModel.abbreviationsProperty().get(1));
viewModel.editAbbreviation(new Abbreviation("YetAnotherEntry", "YAE"));
verify(dialogService).showErrorDialogAndWait(anyString(), anyString());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testEditAbbreviationToEmptyNameResultsInException(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.editAbbreviation(new Abbreviation("", "YAE"));
verify(dialogService).showErrorDialogAndWait(anyString());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testEditAbbreviationToEmptyAbbreviationResultsInException(TestData testData) throws IOException {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(testData.csvFiles.get(1))));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
assertEquals(3, viewModel.abbreviationsProperty().size());
viewModel.editAbbreviation(new Abbreviation("YetAnotherEntry", ""));
verify(dialogService).showErrorDialogAndWait(anyString());
}
@ParameterizedTest
@MethodSource("provideTestFiles")
void testSaveAbbreviationsToFilesCreatesNewFilesWithWrittenAbbreviations(TestData testData) throws Exception {
Path testFile2 = createTestFile(testData.csvFiles.get(2));
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile2));
viewModel.addNewFile();
viewModel.selectLastJournalFile();
selectLastAbbreviation();
viewModel.editAbbreviation(ABBREVIATION_5);
assertEquals(4, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(ABBREVIATION_5)));
Path testFile3 = createTestFile(testData.csvFiles.get(3));
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile3));
viewModel.addNewFile();
assertEquals(5, viewModel.abbreviationsProperty().size());
viewModel.selectLastJournalFile();
assertTrue(viewModel.currentFileProperty().get().getAbsolutePath().get().getFileName().toString().endsWith("3.csv"));
selectLastAbbreviation();
viewModel.deleteAbbreviation();
viewModel.addAbbreviation(ABBREVIATION_6);
// deletion and addition of an entry leads to same size
assertEquals(5, viewModel.abbreviationsProperty().size());
assertTrue(viewModel.abbreviationsProperty().contains(new AbbreviationViewModel(ABBREVIATION_6)));
// overwrite all files
viewModel.saveJournalAbbreviationFiles();
List<String> actual = Files.readAllLines(testFile2, StandardCharsets.UTF_8);
assertEquals(testData.finalContentsOfFile2, actual);
actual = Files.readAllLines(testFile3, StandardCharsets.UTF_8);
assertEquals(testData.finalContentsOfFile3, actual);
}
/**
* Select the last abbreviation in the list of abbreviations
*/
private void selectLastAbbreviation() {
viewModel.currentAbbreviationProperty()
.set(viewModel.abbreviationsProperty().get(viewModel.abbreviationsCountProperty().get() - 1));
}
private void addFourTestFileToViewModelAndPreferences(TestData testData) throws IOException {
for (CsvFileNameAndContent csvFile : testData.csvFiles) {
when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(createTestFile(csvFile)));
viewModel.addNewFile();
}
viewModel.storeSettings();
}
private Path createTestFile(CsvFileNameAndContent testFile) throws IOException {
Path file = this.tempFolder.resolve(testFile.fileName);
Files.writeString(file, testFile.content);
return file;
}
}
| 26,982 | 49.341418 | 249 | java |
null | jabref-main/src/test/java/org/jabref/gui/preferences/keybindings/KeyBindingViewModelTest.java | package org.jabref.gui.preferences.keybindings;
import java.util.Optional;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.DialogService;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
class KeyBindingViewModelTest {
@Test
void resetToDefault() {
// Set new key binding
KeyBindingRepository keyBindingRepository = new KeyBindingRepository();
KeyBindingsTabViewModel keyBindingsTabViewModel = new KeyBindingsTabViewModel(keyBindingRepository, mock(DialogService.class), mock(PreferencesService.class));
KeyBinding binding = KeyBinding.ABBREVIATE;
KeyBindingViewModel viewModel = new KeyBindingViewModel(keyBindingRepository, binding, binding.getDefaultKeyBinding());
keyBindingsTabViewModel.selectedKeyBindingProperty().set(Optional.of(viewModel));
KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "F1", "F1", KeyCode.F1, true, false, false,
false);
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
keyBindingsTabViewModel.setNewBindingForCurrent(shortcutKeyEvent);
keyBindingsTabViewModel.storeSettings();
assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
// Reset to default
viewModel.resetToDefault();
assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent));
}
}
| 1,760 | 36.468085 | 163 | java |
null | jabref-main/src/test/java/org/jabref/gui/preview/CopyCitationActionTest.java | package org.jabref.gui.preview;
import java.util.Arrays;
import javafx.scene.input.ClipboardContent;
import org.jabref.logic.util.OS;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CopyCitationActionTest {
@Test
void processPreviewText() throws Exception {
String expected = "Article (Smith2016)" + OS.NEWLINE +
"Smith, B.; Jones, B. & Williams, J." + OS.NEWLINE +
"Taylor, P. (Ed.)" + OS.NEWLINE +
"Title of the test entry " + OS.NEWLINE +
"BibTeX Journal, JabRef Publishing, 2016, 34, 45-67 " + OS.NEWLINE +
"" + OS.NEWLINE +
"Abstract: This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger. " + OS.NEWLINE +
"<br>" + OS.NEWLINE +
"Article (Smith2016)" + OS.NEWLINE +
"Smith, B.; Jones, B. & Williams, J." + OS.NEWLINE +
"Taylor, P. (Ed.)" + OS.NEWLINE +
"Title of the test entry " + OS.NEWLINE +
"BibTeX Journal, JabRef Publishing, 2016, 34, 45-67 " + OS.NEWLINE +
"" + OS.NEWLINE +
"Abstract: This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger. ";
String citation = "Article (Smith2016)" + OS.NEWLINE +
"Smith, B.; Jones, B. & Williams, J." + OS.NEWLINE +
"Taylor, P. (Ed.)" + OS.NEWLINE +
"Title of the test entry " + OS.NEWLINE +
"BibTeX Journal, JabRef Publishing, 2016, 34, 45-67 " + OS.NEWLINE +
OS.NEWLINE +
"Abstract: This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger. ";
ClipboardContent clipboardContent = CopyCitationAction.processPreview(Arrays.asList(citation, citation));
String actual = clipboardContent.getString();
assertEquals(expected, actual);
}
@Test
void processPreviewHtml() throws Exception {
String expected = "<font face=\"sans-serif\"><b><i>Article</i><a name=\"Smith2016\"> (Smith2016)</a></b><br>" + OS.NEWLINE +
" Smith, B.; Jones, B. & Williams, J.<BR>" + OS.NEWLINE +
" Taylor, P. <i>(Ed.)</i><BR>" + OS.NEWLINE +
" Title of the test entry <BR>" + OS.NEWLINE +
OS.NEWLINE +
" <em>BibTeX Journal, </em>" + OS.NEWLINE +
OS.NEWLINE +
OS.NEWLINE +
OS.NEWLINE +
" <em>JabRef Publishing, </em>" + OS.NEWLINE +
"<b>2016</b><i>, 34</i>, 45-67 " + OS.NEWLINE +
"<BR><BR><b>Abstract: </b> This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger. " + OS.NEWLINE +
"</dd>" + OS.NEWLINE +
"<p></p></font>" + OS.NEWLINE +
"<br>" + OS.NEWLINE +
"<font face=\"sans-serif\"><b><i>Article</i><a name=\"Smith2016\"> (Smith2016)</a></b><br>" + OS.NEWLINE +
" Smith, B.; Jones, B. & Williams, J.<BR>" + OS.NEWLINE +
" Taylor, P. <i>(Ed.)</i><BR>" + OS.NEWLINE +
" Title of the test entry <BR>" + OS.NEWLINE +
OS.NEWLINE +
" <em>BibTeX Journal, </em>" + OS.NEWLINE +
OS.NEWLINE +
OS.NEWLINE +
OS.NEWLINE +
" <em>JabRef Publishing, </em>" + OS.NEWLINE +
"<b>2016</b><i>, 34</i>, 45-67 " + OS.NEWLINE +
"<BR><BR><b>Abstract: </b> This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger. " + OS.NEWLINE +
"</dd>" + OS.NEWLINE +
"<p></p></font>";
String citation = "<font face=\"sans-serif\"><b><i>Article</i><a name=\"Smith2016\"> (Smith2016)</a></b><br>" + OS.NEWLINE +
" Smith, B.; Jones, B. & Williams, J.<BR>" + OS.NEWLINE +
" Taylor, P. <i>(Ed.)</i><BR>" + OS.NEWLINE +
" Title of the test entry <BR>" + OS.NEWLINE +
OS.NEWLINE +
" <em>BibTeX Journal, </em>" + OS.NEWLINE +
OS.NEWLINE +
OS.NEWLINE +
OS.NEWLINE +
" <em>JabRef Publishing, </em>" + OS.NEWLINE +
"<b>2016</b><i>, 34</i>, 45-67 " + OS.NEWLINE +
"<BR><BR><b>Abstract: </b> This entry describes a test scenario which may be useful in JabRef. By providing a test entry it is possible to see how certain things will look in this graphical BIB-file mananger. " + OS.NEWLINE +
"</dd>" + OS.NEWLINE +
"<p></p></font>";
ClipboardContent clipboardContent = CopyCitationAction.processPreview(Arrays.asList(citation, citation));
String actual = clipboardContent.getString();
assertEquals(expected, actual);
}
@Test
void processText() throws Exception {
String expected = "[1]B. Smith, B. Jones, and J. Williams, “Title of the test entry,” BibTeX Journal, vol. 34, no. 3, pp. 45–67, Jul. 2016." + OS.NEWLINE +
"[1]B. Smith, B. Jones, and J. Williams, “Title of the test entry,” BibTeX Journal, vol. 34, no. 3, pp. 45–67, Jul. 2016." + OS.NEWLINE;
String citation = "[1]B. Smith, B. Jones, and J. Williams, “Title of the test entry,” BibTeX Journal, vol. 34, no. 3, pp. 45–67, Jul. 2016." + OS.NEWLINE;
ClipboardContent textTransferable = CopyCitationAction.processText(Arrays.asList(citation, citation));
String actual = textTransferable.getString();
assertEquals(expected, actual);
}
@Test
void processHtmlAsHtml() throws Exception {
String expected = "<!DOCTYPE html>" + OS.NEWLINE +
"<html>" + OS.NEWLINE +
" <head>" + OS.NEWLINE +
" <meta charset=\"utf-8\">" + OS.NEWLINE +
" </head>" + OS.NEWLINE +
" <body>" + OS.NEWLINE +
OS.NEWLINE +
" <div class=\"csl-entry\">" + OS.NEWLINE +
" <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">B. Smith, B. Jones, and J. Williams, “Title of the test entry,” <i>BibTeX Journal</i>, vol. 34, no. 3, pp. 45–67, Jul. 2016.</div>" + OS.NEWLINE +
" </div>" + OS.NEWLINE +
OS.NEWLINE +
"<br>" + OS.NEWLINE +
" <div class=\"csl-entry\">" + OS.NEWLINE +
" <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">B. Smith, B. Jones, and J. Williams, “Title of the test entry,” <i>BibTeX Journal</i>, vol. 34, no. 3, pp. 45–67, Jul. 2016.</div>" + OS.NEWLINE +
" </div>" + OS.NEWLINE +
OS.NEWLINE +
" </body>" + OS.NEWLINE +
"</html>" + OS.NEWLINE;
String citation = " <div class=\"csl-entry\">" + OS.NEWLINE +
" <div class=\"csl-left-margin\">[1]</div><div class=\"csl-right-inline\">B. Smith, B. Jones, and J. Williams, “Title of the test entry,” <i>BibTeX Journal</i>, vol. 34, no. 3, pp. 45–67, Jul. 2016.</div>" + OS.NEWLINE +
" </div>" + OS.NEWLINE;
ClipboardContent htmlTransferable = CopyCitationAction.processHtml(Arrays.asList(citation, citation));
Object actual = htmlTransferable.getHtml();
assertEquals(expected, actual);
}
}
| 8,047 | 56.078014 | 241 | java |
null | jabref-main/src/test/java/org/jabref/gui/search/ContainsAndRegexBasedSearchRuleDescriberTest.java | package org.jabref.gui.search;
import java.util.EnumSet;
import java.util.List;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
import org.jabref.gui.search.rules.describer.ContainsAndRegexBasedSearchRuleDescriber;
import org.jabref.gui.util.TooltipTextUtil;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
@GUITest
@ExtendWith(ApplicationExtension.class)
class ContainsAndRegexBasedSearchRuleDescriberTest {
@Start
void onStart(Stage stage) {
// Needed to init JavaFX thread
stage.show();
}
@Test
void testSimpleTerm() {
String query = "test";
List<Text> expectedTexts = List.of(
TooltipTextUtil.createText("This search contains entries in which any field contains the term "),
TooltipTextUtil.createText("test", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case insensitive). "));
TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.noneOf(SearchFlags.class), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testNoAst() {
String query = "a b";
List<Text> expectedTexts = List.of(
TooltipTextUtil.createText("This search contains entries in which any field contains the term "),
TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case insensitive). "));
TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.noneOf(SearchFlags.class), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testNoAstRegex() {
String query = "a b";
List<Text> expectedTexts = List.of(
TooltipTextUtil.createText("This search contains entries in which any field contains the regular expression "),
TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case insensitive). "));
TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testNoAstRegexCaseSensitive() {
String query = "a b";
List<Text> expectedTexts = List.of(
TooltipTextUtil.createText("This search contains entries in which any field contains the regular expression "),
TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case sensitive). "));
TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testNoAstCaseSensitive() {
String query = "a b";
List<Text> expectedTexts = List.of(
TooltipTextUtil.createText("This search contains entries in which any field contains the term "),
TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" and "),
TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" (case sensitive). "));
TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE), query).getDescription();
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
}
| 4,508 | 44.545455 | 196 | java |
null | jabref-main/src/test/java/org/jabref/gui/search/GetLastSearchHistoryTest.java | package org.jabref.gui.search;
import java.util.List;
import javafx.stage.Stage;
import org.jabref.gui.StateManager;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
@GUITest
@ExtendWith(ApplicationExtension.class)
public class GetLastSearchHistoryTest {
@Start
void onStart(Stage stage) {
// Needed to init JavaFX thread
stage.show();
}
@Test
void testGetLastSearchHistory() {
StateManager stateManager = new StateManager();
stateManager.addSearchHistory("test1");
stateManager.addSearchHistory("test2");
stateManager.addSearchHistory("test3");
List<String> lastSearchHistory = stateManager.getLastSearchHistory(2);
List<String> expected = List.of("test2", "test3");
Assertions.assertEquals(expected, lastSearchHistory);
}
@Test
void testduplicateSearchHistory() {
StateManager stateManager = new StateManager();
stateManager.addSearchHistory("test1");
stateManager.addSearchHistory("test2");
stateManager.addSearchHistory("test3");
stateManager.addSearchHistory("test1");
List<String> lastSearchHistory = stateManager.getWholeSearchHistory();
List<String> expected = List.of("test2", "test3", "test1");
Assertions.assertEquals(expected, lastSearchHistory);
}
@Test
void testclearSearchHistory() {
StateManager stateManager = new StateManager();
stateManager.addSearchHistory("test1");
stateManager.addSearchHistory("test2");
stateManager.addSearchHistory("test3");
List<String> lastSearchHistory = stateManager.getWholeSearchHistory();
List<String> expected = List.of("test1", "test2", "test3");
Assertions.assertEquals(expected, lastSearchHistory);
stateManager.clearSearchHistory();
lastSearchHistory = stateManager.getWholeSearchHistory();
expected = List.of();
Assertions.assertEquals(expected, lastSearchHistory);
}
}
| 2,230 | 33.323077 | 78 | java |
null | jabref-main/src/test/java/org/jabref/gui/search/GlobalSearchBarTest.java | package org.jabref.gui.search;
import java.util.EnumSet;
import java.util.List;
import javafx.scene.Scene;
import javafx.scene.control.TextInputControl;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SearchPreferences;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Answers;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@GUITest
@ExtendWith(ApplicationExtension.class)
public class GlobalSearchBarTest {
private Stage stage;
private Scene scene;
private HBox hBox;
private GlobalSearchBar searchBar;
private StateManager stateManager;
@Start
public void onStart(Stage stage) {
SearchPreferences searchPreferences = mock(SearchPreferences.class);
when(searchPreferences.getSearchFlags()).thenReturn(EnumSet.noneOf(SearchRules.SearchFlags.class));
PreferencesService prefs = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS);
when(prefs.getSearchPreferences()).thenReturn(searchPreferences);
stateManager = new StateManager();
// Need for active database, otherwise the searchField will be disabled
stateManager.setActiveDatabase(new BibDatabaseContext());
// Instantiate GlobalSearchBar class, so the change listener is registered
searchBar = new GlobalSearchBar(
mock(JabRefFrame.class),
stateManager,
prefs,
mock(CountingUndoManager.class),
mock(DialogService.class)
);
hBox = new HBox(searchBar);
scene = new Scene(hBox, 400, 400);
this.stage = stage;
stage.setScene(scene);
stage.show();
}
@Test
void recordingSearchQueriesOnFocusLostOnly(FxRobot robot) throws InterruptedException {
stateManager.clearSearchHistory();
String searchQuery = "Smith";
// Track the node, that the search query will be typed into
TextInputControl searchField = robot.lookup("#searchField").queryTextInputControl();
// The focus is on searchField node, as we click on the search box
var searchFieldRoboto = robot.clickOn(searchField);
for (char c : searchQuery.toCharArray()) {
searchFieldRoboto.write(String.valueOf(c));
Thread.sleep(401);
assertTrue(stateManager.getWholeSearchHistory().isEmpty());
}
// Set the focus to another node to trigger the listener and finally record the query.
DefaultTaskExecutor.runAndWaitInJavaFXThread(hBox::requestFocus);
List<String> lastSearchHistory = stateManager.getWholeSearchHistory().stream().toList();
assertEquals(List.of("Smith"), lastSearchHistory);
}
@Test
void emptyQueryIsNotRecorded(FxRobot robot) {
stateManager.clearSearchHistory();
String searchQuery = "";
TextInputControl searchField = robot.lookup("#searchField").queryTextInputControl();
var searchFieldRoboto = robot.clickOn(searchField);
searchFieldRoboto.write(searchQuery);
DefaultTaskExecutor.runAndWaitInJavaFXThread(hBox::requestFocus);
List<String> lastSearchHistory = stateManager.getWholeSearchHistory().stream().toList();
assertEquals(List.of(), lastSearchHistory);
}
}
| 4,040 | 35.736364 | 107 | java |
null | jabref-main/src/test/java/org/jabref/gui/search/GrammarBasedSearchRuleDescriberTest.java | package org.jabref.gui.search;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
import org.jabref.gui.search.rules.describer.GrammarBasedSearchRuleDescriber;
import org.jabref.gui.util.TooltipTextUtil;
import org.jabref.model.search.rules.GrammarBasedSearchRule;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.testutils.category.GUITest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
import static org.junit.jupiter.api.Assertions.assertTrue;
@GUITest
@ExtendWith(ApplicationExtension.class)
class GrammarBasedSearchRuleDescriberTest {
@Start
void onStart(Stage stage) {
// Needed to init JavaFX thread
stage.show();
}
private TextFlow createDescription(String query, EnumSet<SearchFlags> searchFlags) {
GrammarBasedSearchRule grammarBasedSearchRule = new GrammarBasedSearchRule(searchFlags);
assertTrue(grammarBasedSearchRule.validateSearchStrings(query));
GrammarBasedSearchRuleDescriber describer = new GrammarBasedSearchRuleDescriber(searchFlags, grammarBasedSearchRule.getTree());
return describer.getDescription();
}
@Test
void testSimpleQueryCaseSensitiveRegex() {
String query = "a=b";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case-sensitive."));
TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testSimpleQueryCaseSensitive() {
String query = "a=b";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case-sensitive."));
TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testSimpleQuery() {
String query = "a=b";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case-insensitive."));
TextFlow description = createDescription(query, EnumSet.noneOf(SearchFlags.class));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testSimpleQueryRegex() {
String query = "a=b";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "),
TooltipTextUtil.createText("The search is case-insensitive."));
TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testComplexQueryCaseSensitiveRegex() {
String query = "not a=b and c=e or e=\"x\"";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("not "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case-sensitive."));
TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE, SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testComplexQueryRegex() {
String query = "not a=b and c=e or e=\"x\"";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("not "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the regular expression "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the regular expression "),
TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case-insensitive."));
TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.REGULAR_EXPRESSION));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testComplexQueryCaseSensitive() {
String query = "not a=b and c=e or e=\"x\"";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("not "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case-sensitive."));
TextFlow description = createDescription(query, EnumSet.of(SearchRules.SearchFlags.CASE_SENSITIVE));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
@Test
void testComplexQuery() {
String query = "not a=b and c=e or e=\"x\"";
List<Text> expectedTexts = Arrays.asList(TooltipTextUtil.createText("This search contains entries in which "), TooltipTextUtil.createText("not "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("a", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("b", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" and "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("c", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD),
TooltipTextUtil.createText(" or "), TooltipTextUtil.createText("the field "), TooltipTextUtil.createText("e", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(" contains the term "), TooltipTextUtil.createText("x", TooltipTextUtil.TextType.BOLD), TooltipTextUtil.createText(". "), TooltipTextUtil.createText("The search is case-insensitive."));
TextFlow description = createDescription(query, EnumSet.noneOf(SearchFlags.class));
TextFlowEqualityHelper.assertEquals(expectedTexts, description);
}
}
| 9,843 | 73.575758 | 388 | java |
null | jabref-main/src/test/java/org/jabref/gui/search/TextFlowEqualityHelper.java | package org.jabref.gui.search;
import java.util.List;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import org.junit.jupiter.api.Assertions;
public class TextFlowEqualityHelper {
public static void assertEquals(List<Text> expectedTexts, TextFlow description) {
if (expectedTexts.size() != description.getChildren().size()) {
Assertions.assertEquals(expectedTexts, description.getChildren());
return;
}
Text expectedText;
for (int i = 0; i < expectedTexts.size(); i++) {
expectedText = expectedTexts.get(i);
// the strings contain not only the text but also the font and other properties
// so comparing them compares the Text object as a whole
// the equals method is not implemented...
if (!expectedText.toString().equals(description.getChildren().get(i).toString())) {
Assertions.assertEquals(expectedTexts, description.getChildren());
return;
}
}
}
public static boolean checkIfTextsEqualsExpectedTexts(List<Text> texts, List<Text> expectedTexts) {
if (expectedTexts.size() != texts.size()) {
return false;
}
Text expectedText;
for (int i = 0; i < expectedTexts.size(); i++) {
expectedText = expectedTexts.get(i);
// the strings contain not only the text but also the font and other properties
// so comparing them compares the Text object as a whole
// the equals method is not implemented...
if (!expectedText.toString().equals(texts.get(i).toString())) {
return false;
}
}
return true;
}
}
| 1,754 | 36.340426 | 103 | java |
null | jabref-main/src/test/java/org/jabref/gui/sidepane/SidePaneViewModelTest.java | package org.jabref.gui.sidepane;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.undo.UndoManager;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SidePanePreferences;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.framework.junit5.ApplicationExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ExtendWith(ApplicationExtension.class)
class SidePaneViewModelTest {
PreferencesService preferencesService = mock(PreferencesService.class);
JournalAbbreviationRepository abbreviationRepository = mock(JournalAbbreviationRepository.class);
StateManager stateManager = mock(StateManager.class);
TaskExecutor taskExecutor = mock(TaskExecutor.class);
DialogService dialogService = mock(DialogService.class);
UndoManager undoManager = mock(UndoManager.class);
SidePanePreferences sidePanePreferences = new SidePanePreferences(new HashSet<>(), new HashMap<>(), 0);
ObservableList<SidePaneType> sidePaneComponents = FXCollections.observableArrayList();
SidePaneViewModel sidePaneViewModel;
@BeforeEach
void setUp() {
when(stateManager.getVisibleSidePaneComponents()).thenReturn(sidePaneComponents);
when(stateManager.getLocalDragboard()).thenReturn(mock(CustomLocalDragboard.class));
when(stateManager.activeDatabaseProperty()).thenReturn(OptionalObjectProperty.empty());
when(preferencesService.getSidePanePreferences()).thenReturn(sidePanePreferences);
sidePanePreferences.visiblePanes().addAll(EnumSet.allOf(SidePaneType.class));
sidePanePreferences.getPreferredPositions().put(SidePaneType.GROUPS, 0);
sidePanePreferences.getPreferredPositions().put(SidePaneType.WEB_SEARCH, 1);
sidePanePreferences.getPreferredPositions().put(SidePaneType.OPEN_OFFICE, 2);
sidePaneViewModel = new SidePaneViewModel(preferencesService, abbreviationRepository, stateManager, taskExecutor, dialogService, undoManager);
}
@Test
void moveUp() {
sidePaneViewModel.moveUp(SidePaneType.WEB_SEARCH);
assertEquals(sidePaneComponents.get(0), SidePaneType.WEB_SEARCH);
assertEquals(sidePaneComponents.get(1), SidePaneType.GROUPS);
}
@Test
void moveUpFromFirstPosition() {
sidePaneViewModel.moveUp(SidePaneType.GROUPS);
assertEquals(sidePaneComponents.get(0), SidePaneType.GROUPS);
}
@Test
void moveDown() {
sidePaneViewModel.moveDown(SidePaneType.WEB_SEARCH);
assertEquals(sidePaneComponents.get(1), SidePaneType.OPEN_OFFICE);
assertEquals(sidePaneComponents.get(2), SidePaneType.WEB_SEARCH);
}
@Test
void moveDownFromLastPosition() {
sidePaneViewModel.moveDown(SidePaneType.OPEN_OFFICE);
assertEquals(sidePaneComponents.get(2), SidePaneType.OPEN_OFFICE);
}
@Test
void sortByPreferredPositions() {
sidePanePreferences.getPreferredPositions().put(SidePaneType.GROUPS, 2);
sidePanePreferences.getPreferredPositions().put(SidePaneType.OPEN_OFFICE, 0);
sidePaneComponents.sort(new SidePaneViewModel.PreferredIndexSort(sidePanePreferences));
assertTrue(sidePaneComponents.get(0) == SidePaneType.OPEN_OFFICE && sidePaneComponents.get(2) == SidePaneType.GROUPS);
}
}
| 3,939 | 38.4 | 150 | java |
null | jabref-main/src/test/java/org/jabref/gui/slr/ManageStudyDefinitionViewModelTest.java | package org.jabref.gui.slr;
import java.nio.file.Path;
import java.util.List;
import org.jabref.gui.DialogService;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ImporterPreferences;
import org.jabref.model.study.Study;
import org.jabref.model.study.StudyDatabase;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
class ManageStudyDefinitionViewModelTest {
private ImportFormatPreferences importFormatPreferences;
private ImporterPreferences importerPreferences;
private DialogService dialogService;
@BeforeEach
void setUp() {
// code taken from org.jabref.logic.importer.WebFetchersTest.setUp
importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
importerPreferences = mock(ImporterPreferences.class);
dialogService = mock(DialogService.class);
}
@Test
public void emptyStudyConstructorFillsDatabasesCorrectly() {
ManageStudyDefinitionViewModel manageStudyDefinitionViewModel = new ManageStudyDefinitionViewModel(importFormatPreferences, importerPreferences, dialogService);
assertEquals(List.of(
new StudyCatalogItem("ACM Portal", true),
new StudyCatalogItem("ArXiv", false),
new StudyCatalogItem("Bibliotheksverbund Bayern (Experimental)", false),
new StudyCatalogItem("Biodiversity Heritage", false),
new StudyCatalogItem("CiteSeerX", false),
new StudyCatalogItem("Collection of Computer Science Bibliographies", false),
new StudyCatalogItem("Crossref", false),
new StudyCatalogItem("DBLP", true),
new StudyCatalogItem("DOAB", false),
new StudyCatalogItem("DOAJ", false),
new StudyCatalogItem("GVK", false),
new StudyCatalogItem("IEEEXplore", true),
new StudyCatalogItem("INSPIRE", false),
new StudyCatalogItem("MathSciNet", false),
new StudyCatalogItem("Medline/PubMed", false),
new StudyCatalogItem("ResearchGate", false),
new StudyCatalogItem("SAO/NASA ADS", false),
new StudyCatalogItem("SemanticScholar", false),
new StudyCatalogItem("Springer", true),
new StudyCatalogItem("zbMATH", false)
), manageStudyDefinitionViewModel.getCatalogs());
}
@Test
public void studyConstructorFillsDatabasesCorrectly(@TempDir Path tempDir) {
List<StudyDatabase> databases = List.of(
new StudyDatabase("ACM Portal", true));
Study study = new Study(
List.of("Name"),
"title",
List.of("Q1"),
List.of(),
databases
);
ManageStudyDefinitionViewModel manageStudyDefinitionViewModel = new ManageStudyDefinitionViewModel(
study,
tempDir,
importFormatPreferences,
importerPreferences,
dialogService);
assertEquals(List.of(
new StudyCatalogItem("ACM Portal", true),
new StudyCatalogItem("ArXiv", false),
new StudyCatalogItem("Bibliotheksverbund Bayern (Experimental)", false),
new StudyCatalogItem("Biodiversity Heritage", false),
new StudyCatalogItem("CiteSeerX", false),
new StudyCatalogItem("Collection of Computer Science Bibliographies", false),
new StudyCatalogItem("Crossref", false),
new StudyCatalogItem("DBLP", false),
new StudyCatalogItem("DOAB", false),
new StudyCatalogItem("DOAJ", false),
new StudyCatalogItem("GVK", false),
new StudyCatalogItem("IEEEXplore", false),
new StudyCatalogItem("INSPIRE", false),
new StudyCatalogItem("MathSciNet", false),
new StudyCatalogItem("Medline/PubMed", false),
new StudyCatalogItem("ResearchGate", false),
new StudyCatalogItem("SAO/NASA ADS", false),
new StudyCatalogItem("SemanticScholar", false),
new StudyCatalogItem("Springer", false),
new StudyCatalogItem("zbMATH", false)
), manageStudyDefinitionViewModel.getCatalogs());
}
}
| 4,619 | 44.742574 | 168 | java |
null | jabref-main/src/test/java/org/jabref/gui/theme/ThemeManagerTest.java | package org.jabref.gui.theme;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import org.jabref.gui.util.DefaultFileUpdateMonitor;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.preferences.WorkspacePreferences;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import org.testfx.framework.junit5.ApplicationExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ExtendWith(ApplicationExtension.class)
class ThemeManagerTest {
private static final String TEST_CSS_DATA = "data:text/css;charset=utf-8;base64,LyogQmlibGF0ZXggU291cmNlIENvZGUgKi8KLmNvZGUtYXJlYSAudGV4dCB7CiAgICAtZngtZm9udC1mYW1pbHk6IG1vbm9zcGFjZTsKfQ==";
private static final String TEST_CSS_CONTENT = """
/* Biblatex Source Code */
.code-area .text {
-fx-font-family: monospace;
}""";
private Path tempFolder;
@BeforeEach
void setUp(@TempDir Path tempFolder) {
this.tempFolder = tempFolder;
}
@Test
public void themeManagerUsesProvidedTheme() throws IOException {
Path testCss = tempFolder.resolve("test.css");
Files.writeString(testCss, TEST_CSS_CONTENT, StandardOpenOption.CREATE);
WorkspacePreferences workspacePreferences = mock(WorkspacePreferences.class, Answers.RETURNS_DEEP_STUBS);
when(workspacePreferences.getTheme()).thenReturn(new Theme(testCss.toString()));
ThemeManager themeManager = new ThemeManager(workspacePreferences, new DummyFileUpdateMonitor(), Runnable::run);
assertEquals(Theme.Type.CUSTOM, themeManager.getActiveTheme().getType());
assertEquals(testCss.toString(), themeManager.getActiveTheme().getName());
Optional<String> cssLocationBeforeDeletion = themeManager.getActiveTheme()
.getAdditionalStylesheet()
.map(StyleSheet::getWebEngineStylesheet);
assertTrue(cssLocationBeforeDeletion.isPresent(), "expected custom theme location to be available");
assertEquals(TEST_CSS_DATA, cssLocationBeforeDeletion.get());
}
@Test
public void customThemeAvailableEvenWhenDeleted() throws IOException {
/* Create a temporary custom theme that is just a small snippet of CSS. There is no CSS
validation (at the moment) but by making a valid CSS block we don't preclude adding validation later */
Path testCss = tempFolder.resolve("test.css");
Files.writeString(testCss, TEST_CSS_CONTENT, StandardOpenOption.CREATE);
WorkspacePreferences workspacePreferences = mock(WorkspacePreferences.class, Answers.RETURNS_DEEP_STUBS);
when(workspacePreferences.getTheme()).thenReturn(new Theme(testCss.toString()));
// ActiveTheme should provide the additionalStylesheet that was created before
ThemeManager themeManagerCreatedBeforeFileDeleted = new ThemeManager(workspacePreferences, new DummyFileUpdateMonitor(), Runnable::run);
Files.delete(testCss);
// ActiveTheme should keep the additionalStylesheet in memory and provide it
Optional<String> cssLocationAfterDeletion = themeManagerCreatedBeforeFileDeleted.getActiveTheme()
.getAdditionalStylesheet()
.map(StyleSheet::getWebEngineStylesheet);
assertTrue(cssLocationAfterDeletion.isPresent(), "expected custom theme location to be available");
assertEquals(TEST_CSS_DATA, cssLocationAfterDeletion.get());
}
/**
* This test was orinially part of a more complex test. After a major refactor and simplification of the theme
* subsystem, it was decided to drop this functionality in particular, as there is no use case for it and removing
* this does simplify the implementation of the theme system.
* See https://github.com/JabRef/jabref/pull/7336#issuecomment-874267375
*
* @throws IOException when the testfile cannot be created
*/
@Disabled
@Test
public void customThemeBecomesAvailableAfterFileIsCreated() throws IOException {
Path testCss = tempFolder.resolve("test.css");
WorkspacePreferences workspacePreferences = mock(WorkspacePreferences.class);
when(workspacePreferences.getTheme()).thenReturn(new Theme(testCss.toString()));
// ActiveTheme should provide no additionalStylesheet when no file exists
ThemeManager themeManagerCreatedBeforeFileExists = new ThemeManager(workspacePreferences, new DummyFileUpdateMonitor(), Runnable::run);
assertEquals(Optional.empty(), themeManagerCreatedBeforeFileExists.getActiveTheme()
.getAdditionalStylesheet(),
"didn't expect additional stylesheet to be available because it didn't exist when theme was created");
Files.writeString(testCss, TEST_CSS_CONTENT, StandardOpenOption.CREATE);
// ActiveTheme should provide an additionalStylesheet after the file was created
Optional<String> cssLocationAfterFileCreated = themeManagerCreatedBeforeFileExists.getActiveTheme()
.getAdditionalStylesheet()
.map(StyleSheet::getWebEngineStylesheet);
assertTrue(cssLocationAfterFileCreated.isPresent(), "expected custom theme location to be available");
assertEquals(TEST_CSS_DATA, cssLocationAfterFileCreated.get());
}
@Test
public void largeCustomThemeNotHeldInMemory() throws IOException {
/* Create a temporary custom theme that is just a large comment over 48 kilobytes in size. There is no CSS
validation (at the moment) but by making a valid CSS comment we don't preclude adding validation later */
Path largeCssTestFile = tempFolder.resolve("test.css");
Files.createFile(largeCssTestFile);
Files.writeString(largeCssTestFile, "/* ", StandardOpenOption.CREATE);
final String testString = "ALL WORK AND NO PLAY MAKES JACK A DULL BOY\n";
for (int i = 0; i <= (48000 / testString.length()); i++) {
Files.writeString(largeCssTestFile, testString, StandardOpenOption.APPEND);
}
Files.writeString(largeCssTestFile, " */", StandardOpenOption.APPEND);
WorkspacePreferences workspacePreferences = mock(WorkspacePreferences.class, Answers.RETURNS_DEEP_STUBS);
when(workspacePreferences.getTheme()).thenReturn(new Theme(largeCssTestFile.toString()));
// ActiveTheme should provide the large additionalStylesheet that was created before
ThemeManager themeManager = new ThemeManager(workspacePreferences, new DummyFileUpdateMonitor(), Runnable::run);
Optional<String> cssLocationBeforeRemoved = themeManager.getActiveTheme()
.getAdditionalStylesheet()
.map(StyleSheet::getWebEngineStylesheet);
assertTrue(cssLocationBeforeRemoved.isPresent(), "expected custom theme location to be available");
assertTrue(cssLocationBeforeRemoved.get().startsWith("file:"), "expected large custom theme to be a file");
Files.move(largeCssTestFile, largeCssTestFile.resolveSibling("renamed.css"));
// getAdditionalStylesheet() should no longer offer the deleted stylesheet as it is not been held in memory
assertEquals(themeManager.getActiveTheme().getAdditionalStylesheet().get().getWebEngineStylesheet(), "",
"didn't expect additional stylesheet after css was deleted");
Files.move(largeCssTestFile.resolveSibling("renamed.css"), largeCssTestFile);
// Check that it is available once more, if the file is restored
Optional<String> cssLocationAfterFileIsRestored = themeManager.getActiveTheme().getAdditionalStylesheet().map(StyleSheet::getWebEngineStylesheet);
assertTrue(cssLocationAfterFileIsRestored.isPresent(), "expected custom theme location to be available");
assertTrue(cssLocationAfterFileIsRestored.get().startsWith("file:"), "expected large custom theme to be a file");
}
@Test
public void installThemeOnScene() throws IOException {
Scene scene = mock(Scene.class);
when(scene.getStylesheets()).thenReturn(FXCollections.observableArrayList());
when(scene.getRoot()).thenReturn(mock(Parent.class));
Path testCss = tempFolder.resolve("reload.css");
Files.writeString(testCss, TEST_CSS_CONTENT, StandardOpenOption.CREATE);
WorkspacePreferences workspacePreferences = mock(WorkspacePreferences.class, Answers.RETURNS_DEEP_STUBS);
when(workspacePreferences.getTheme()).thenReturn(new Theme(testCss.toString()));
ThemeManager themeManager = new ThemeManager(workspacePreferences, new DummyFileUpdateMonitor(), Runnable::run);
themeManager.installCss(scene);
assertEquals(2, scene.getStylesheets().size());
assertTrue(scene.getStylesheets().contains(testCss.toUri().toURL().toExternalForm()));
}
@Test
public void installThemeOnWebEngine() throws IOException {
Path testCss = tempFolder.resolve("reload.css");
Files.writeString(testCss, TEST_CSS_CONTENT, StandardOpenOption.CREATE);
WorkspacePreferences workspacePreferences = mock(WorkspacePreferences.class, Answers.RETURNS_DEEP_STUBS);
when(workspacePreferences.getTheme()).thenReturn(new Theme(testCss.toString()));
ThemeManager themeManager = new ThemeManager(workspacePreferences, new DummyFileUpdateMonitor(), Runnable::run);
CompletableFuture<String> webEngineStyleSheetLocation = new CompletableFuture<>();
Platform.runLater(() -> {
WebEngine webEngine = new WebEngine();
themeManager.installCss(webEngine);
webEngineStyleSheetLocation.complete(webEngine.getUserStyleSheetLocation());
});
try {
assertEquals(webEngineStyleSheetLocation.get(), TEST_CSS_DATA);
} catch (InterruptedException | ExecutionException e) {
fail(e);
}
}
/**
* Since the DefaultFileUpdateMonitor runs in a separate thread we have to wait for some arbitrary number of msecs
* for the thread to start up and the changed css to reload.
*/
@Test
public void liveReloadCssDataUrl() throws IOException, InterruptedException {
Path testCss = tempFolder.resolve("reload.css");
Files.writeString(testCss, TEST_CSS_CONTENT, StandardOpenOption.CREATE);
WorkspacePreferences workspacePreferences = mock(WorkspacePreferences.class, Answers.RETURNS_DEEP_STUBS);
when(workspacePreferences.getTheme()).thenReturn(new Theme(testCss.toString()));
final ThemeManager themeManager;
DefaultFileUpdateMonitor fileUpdateMonitor = new DefaultFileUpdateMonitor();
Thread thread = new Thread(fileUpdateMonitor);
thread.start();
// Wait for the watch service to start
Thread.sleep(500);
themeManager = new ThemeManager(workspacePreferences, fileUpdateMonitor, Runnable::run);
Scene scene = mock(Scene.class);
when(scene.getStylesheets()).thenReturn(FXCollections.observableArrayList());
when(scene.getRoot()).thenReturn(mock(Parent.class));
themeManager.installCss(scene);
Files.writeString(testCss, """
/* And now for something slightly different */
.code-area .text {
-fx-font-family: serif;
}""", StandardOpenOption.CREATE);
// Wait for the stylesheet to be reloaded
Thread.sleep(500);
fileUpdateMonitor.shutdown();
thread.join();
Optional<String> testCssLocation2 = themeManager.getActiveTheme().getAdditionalStylesheet().map(StyleSheet::getWebEngineStylesheet);
assertTrue(testCssLocation2.isPresent(), "expected custom theme location to be available");
assertEquals(
"data:text/css;charset=utf-8;base64,LyogQW5kIG5vdyBmb3Igc29tZXRoaW5nIHNsaWdodGx5IGRpZmZlcmVudCAqLwouY29kZS1hcmVhIC50ZXh0IHsKICAgIC1meC1mb250LWZhbWlseTogc2VyaWY7Cn0=",
testCssLocation2.get(),
"stylesheet embedded in data: url should have reloaded");
}
}
| 13,360 | 52.019841 | 194 | java |
null | jabref-main/src/test/java/org/jabref/gui/theme/ThemeTest.java | package org.jabref.gui.theme;
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.assertTrue;
public class ThemeTest {
@Test
public void lightThemeUsedWhenPathIsBlank() {
Theme theme = new Theme("");
assertEquals(Theme.Type.DEFAULT, theme.getType());
assertEquals(Optional.empty(), theme.getAdditionalStylesheet(),
"didn't expect additional stylesheet to be available");
}
@Test
public void lightThemeUsedWhenPathIsBaseCss() {
Theme theme = new Theme("Base.css");
assertEquals(Theme.Type.DEFAULT, theme.getType());
assertEquals(Optional.empty(), theme.getAdditionalStylesheet(),
"didn't expect additional stylesheet to be available");
}
@Test
public void darkThemeUsedWhenPathIsDarkCss() {
Theme theme = new Theme("Dark.css");
assertEquals(Theme.Type.EMBEDDED, theme.getType());
assertTrue(theme.getAdditionalStylesheet().isPresent());
assertEquals("Dark.css", theme.getAdditionalStylesheet().get().getWatchPath().getFileName().toString(),
"expected dark theme stylesheet to be available");
}
@Test
public void customThemeIgnoredIfDirectory() {
Theme theme = new Theme(".");
assertEquals(Theme.Type.DEFAULT, theme.getType());
assertEquals(Optional.empty(), theme.getAdditionalStylesheet(),
"didn't expect additional stylesheet to be available when location is a directory");
}
@Test
public void customThemeIgnoredIfInvalidPath() {
Theme theme = new Theme("\0\0\0");
assertEquals(Theme.Type.DEFAULT, theme.getType());
assertEquals(Optional.empty(), theme.getAdditionalStylesheet(),
"didn't expect additional stylesheet when CSS location is just some null terminators!");
}
@Test
public void customThemeIfFileNotFound() {
Theme theme = new Theme("Idonotexist.css");
assertEquals(Theme.Type.CUSTOM, theme.getType());
assertTrue(theme.getAdditionalStylesheet().isPresent());
assertEquals("Idonotexist.css", theme.getAdditionalStylesheet().get().getWatchPath().getFileName().toString());
}
}
| 2,332 | 34.348485 | 119 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/ColorUtilTest.java | package org.jabref.gui.util;
import java.util.stream.Stream;
import javafx.scene.paint.Color;
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 ColorUtilTest {
private static final Color C1 = Color.color(0.2, 0.4, 1);
private static final Color C2 = Color.rgb(255, 255, 255);
private static final Color C3 = Color.color(0, 0, 0, 0);
private static final Color C4 = Color.color(1, 1, 1, 1);
private static final Color C5 = Color.color(0.6, 0.8, 0.5, 0.3);
private ColorUtil colorUtil = new ColorUtil();
@Test
public void toRGBCodeTest() {
assertEquals("#3366FF", ColorUtil.toRGBCode(C1));
assertEquals("#FFFFFF", ColorUtil.toRGBCode(C2));
}
@ParameterizedTest
@MethodSource("provideToRGBACodeTest")
public void toRGBACodeTest(Color color, String expected) {
assertEquals(expected, ColorUtil.toRGBACode(color));
}
private static Stream<Arguments> provideToRGBACodeTest() {
return Stream.of(
Arguments.of(C1, String.format("rgba(51,102,255,%f)", 1.0)),
Arguments.of(C2, String.format("rgba(255,255,255,%f)", 1.0)),
Arguments.of(C3, String.format("rgba(0,0,0,%f)", 0.0)),
Arguments.of(C4, String.format("rgba(255,255,255,%f)", 1.0)),
Arguments.of(C5, String.format("rgba(153,204,127,%f)", 0.3))
);
}
@Test
public void toHexTest() {
assertEquals("#000001", ColorUtil.toHex(C1));
assertEquals("#010101", ColorUtil.toHex(C2));
}
}
| 1,760 | 32.865385 | 77 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/ControlHelperTest.java | package org.jabref.gui.util;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.NullSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ControlHelperTest {
private final String TEXT = "abcdef";
private final int MAX_CHARACTERS = 5;
private final int DEFAULT_MAX_CHARACTERS = -1;
private final String ELLIPSIS_STRING = "***";
private final ControlHelper.EllipsisPosition ELLIPSIS_POSITION = ControlHelper.EllipsisPosition.ENDING;
@ParameterizedTest
@NullAndEmptySource
void truncateWithTextNullAndEmptyReturnsSource(String text) {
String truncatedText = ControlHelper.truncateString(text, MAX_CHARACTERS, ELLIPSIS_STRING, ELLIPSIS_POSITION);
assertEquals(text, truncatedText);
}
@Test
void truncateWithDefaultMaxCharactersReturnsText() {
String truncatedText = ControlHelper.truncateString(TEXT, DEFAULT_MAX_CHARACTERS, ELLIPSIS_STRING, ELLIPSIS_POSITION);
assertEquals(TEXT, truncatedText);
}
@Test
void truncateWithEllipsisPositionBeginningReturnsTruncatedText() {
String truncatedText = ControlHelper.truncateString(TEXT, MAX_CHARACTERS, ELLIPSIS_STRING, ControlHelper.EllipsisPosition.BEGINNING);
assertEquals("***ef", truncatedText);
}
@Test
void truncateWithEllipsisPositionCenterReturnsTruncatedText() {
String truncatedText = ControlHelper.truncateString(TEXT, MAX_CHARACTERS, ELLIPSIS_STRING, ControlHelper.EllipsisPosition.CENTER);
assertEquals("a***f", truncatedText);
}
@Test
void truncateWithDefaultMaxCharactersAndNullEllipsisAndPositionEndingReturnsTruncatedText() {
String text = "a".repeat(75) + "b".repeat(25);
String truncatedText = ControlHelper.truncateString(text, DEFAULT_MAX_CHARACTERS, null, ControlHelper.EllipsisPosition.ENDING);
assertEquals("a".repeat(75), truncatedText);
}
@ParameterizedTest
@NullSource
void truncateWithNullEllipsisPositionThrowsNullPointerException(ControlHelper.EllipsisPosition ellipsisPosition) {
assertThrows(
NullPointerException.class,
() -> ControlHelper.truncateString(TEXT, MAX_CHARACTERS, ELLIPSIS_STRING, ellipsisPosition)
);
}
}
| 2,456 | 39.95 | 141 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/FileDialogConfigurationTest.java | package org.jabref.gui.util;
import java.nio.file.Path;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.stage.FileChooser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.FileType;
import org.jabref.logic.util.StandardFileType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FileDialogConfigurationTest {
@Test
void testWithValidDirectoryString(@TempDir Path folder) {
String tempFolder = folder.toAbsolutePath().toString();
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory(tempFolder).build();
assertEquals(Optional.of(Path.of(tempFolder)), fileDialogConfiguration.getInitialDirectory());
}
@Test
void testWithValidDirectoryPath(@TempDir Path tempFolder) {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory(tempFolder).build();
assertEquals(Optional.of(tempFolder), fileDialogConfiguration.getInitialDirectory());
}
@Test
void testWithNullStringDirectory() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory((String) null).build();
assertEquals(Optional.empty(), fileDialogConfiguration.getInitialDirectory());
}
@Test
void testWithNullPathDirectory() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory((Path) null).build();
assertEquals(Optional.empty(), fileDialogConfiguration.getInitialDirectory());
}
@Test
void testWithNonExistingDirectoryAndParentNull() {
String tempFolder = "workingDirectory";
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory(tempFolder).build();
assertEquals(Optional.empty(), fileDialogConfiguration.getInitialDirectory());
}
@Test
void testSingleExtension() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withDefaultExtension(StandardFileType.BIBTEX_DB).build();
FileChooser.ExtensionFilter filter = toFilter(String.format("%1s %2s", "BibTex", Localization.lang("Library")), StandardFileType.BIBTEX_DB);
assertEquals(filter.getExtensions(), fileDialogConfiguration.getDefaultExtension().getExtensions());
}
private FileChooser.ExtensionFilter toFilter(String description, FileType extension) {
return new FileChooser.ExtensionFilter(description,
extension.getExtensions().stream().map(ending -> "*." + ending).collect(Collectors.toList()));
}
}
| 2,913 | 36.358974 | 148 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/OpenConsoleActionTest.java | package org.jabref.gui.util;
import java.util.Optional;
import org.jabref.gui.OpenConsoleAction;
import org.jabref.gui.StateManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class OpenConsoleActionTest {
private final StateManager stateManager = mock(StateManager.class);
private final PreferencesService preferences = mock(PreferencesService.class);
private final BibDatabaseContext current = mock(BibDatabaseContext.class);
private final BibDatabaseContext other = mock(BibDatabaseContext.class);
@BeforeEach
public void setup() {
when(stateManager.activeDatabaseProperty()).thenReturn(OptionalObjectProperty.empty());
when(stateManager.getActiveDatabase()).thenReturn(Optional.of(current));
}
@Test
public void newActionGetsCurrentDatabase() {
OpenConsoleAction action = new OpenConsoleAction(stateManager, preferences, null);
action.execute();
verify(stateManager, times(1)).getActiveDatabase();
verify(current, times(1)).getDatabasePath();
}
@Test
public void newActionGetsSuppliedDatabase() {
OpenConsoleAction action = new OpenConsoleAction(() -> other, stateManager, preferences, null);
action.execute();
verify(stateManager, never()).getActiveDatabase();
verify(other, times(1)).getDatabasePath();
}
@Test
public void actionDefaultsToCurrentDatabase() {
OpenConsoleAction action = new OpenConsoleAction(() -> null, stateManager, preferences, null);
action.execute();
verify(stateManager, times(1)).getActiveDatabase();
verify(current, times(1)).getDatabasePath();
}
}
| 2,012 | 34.946429 | 103 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/RecursiveTreeItemTest.java | package org.jabref.gui.util;
import java.util.Collections;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.TreeItem;
import org.jabref.model.TreeNode;
import org.jabref.model.TreeNodeTestData;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RecursiveTreeItemTest {
private RecursiveTreeItem<TreeNodeTestData.TreeNodeMock> rootTreeItem;
private TreeNodeTestData.TreeNodeMock root;
private ObjectProperty<Predicate<TreeNodeTestData.TreeNodeMock>> filterPredicate;
private TreeNodeTestData.TreeNodeMock node;
@BeforeEach
void setUp() throws Exception {
root = new TreeNodeTestData.TreeNodeMock();
node = TreeNodeTestData.getNodeInSimpleTree(root);
node.setName("test node");
filterPredicate = new SimpleObjectProperty<>();
rootTreeItem = new RecursiveTreeItem<>(root, TreeNode::getChildren, filterPredicate);
}
@Test
void addsAllChildrenNodes() throws Exception {
assertEquals(root.getChildren(), rootTreeItem.getChildren().stream().map(TreeItem::getValue).collect(Collectors.toList()));
}
@Test
void addsAllChildrenOfChildNode() throws Exception {
assertEquals(
root.getChildAt(1).get().getChildren(),
rootTreeItem.getChildren().get(1).getChildren().stream().map(TreeItem::getValue).collect(Collectors.toList()));
}
@Test
void respectsFilter() throws Exception {
filterPredicate.setValue(item -> item.getName().contains("test"));
assertEquals(Collections.singletonList(node.getParent().get()), rootTreeItem.getChildren().stream().map(TreeItem::getValue).collect(Collectors.toList()));
assertEquals(
Collections.singletonList(node),
rootTreeItem.getChildren().get(0).getChildren().stream().map(TreeItem::getValue).collect(Collectors.toList()));
}
}
| 2,112 | 34.813559 | 162 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/TooltipTextUtilTest.java | package org.jabref.gui.util;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.text.Text;
import org.jabref.gui.search.TextFlowEqualityHelper;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TooltipTextUtilTest {
private String testText = "this is a test text";
@Test
public void retrieveCorrectTextStyleNormal() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.NORMAL);
String textStyle = "Regular";
assertEquals(textStyle, text.getFont().getStyle());
}
@Test
public void stringRemainsTheSameAfterTransformationToNormal() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.NORMAL);
assertEquals(testText, text.getText());
}
@Test
public void retrieveCorrectTextStyleBold() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.BOLD);
String textStyle = "tooltip-text-bold";
assertEquals(textStyle, text.getStyleClass().toString());
}
@Test
public void stringRemainsTheSameAfterTransformationToBold() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.BOLD);
assertEquals(testText, text.getText());
}
@Test
public void retrieveCorrectTextStyleItalic() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.ITALIC);
String textStyle = "tooltip-text-italic";
assertEquals(textStyle, text.getStyleClass().toString());
}
@Test
public void stringRemainsTheSameAfterTransformationToItalic() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.ITALIC);
assertEquals(testText, text.getText());
}
@Test
public void testCreateTextMonospaced() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.MONOSPACED);
assertEquals("tooltip-text-monospaced", text.getStyleClass().toString());
assertEquals(testText, text.getText());
}
@Test
public void retrieveCorrectStyleMonospaced() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.MONOSPACED);
String textStyle = "tooltip-text-monospaced";
assertEquals(textStyle, text.getStyleClass().toString());
}
@Test
public void stringRemainsTheSameAfterTransformationToMonospaced() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.MONOSPACED);
assertEquals(testText, text.getText());
}
@Test
public void transformTextToHtmlStringBold() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.BOLD);
String htmlString = TooltipTextUtil.textToHtmlString(text);
String expectedString = "<b>" + testText + "</b>";
assertEquals(expectedString, htmlString);
}
@Test
public void transformTextToHtmlStringItalic() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.ITALIC);
String htmlString = TooltipTextUtil.textToHtmlString(text);
String expectedString = "<i>" + testText + "</i>";
assertEquals(expectedString, htmlString);
}
@Test
public void transformTextToHtmlStringMonospaced() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.MONOSPACED);
String htmlString = TooltipTextUtil.textToHtmlString(text);
String expectedString = "<tt>" + testText + "</tt>";
assertEquals(expectedString, htmlString);
}
@Test
public void transformTextToHtmlStringMonospacedBold() {
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.MONOSPACED);
text.getStyleClass().add("tooltip-text-bold");
String htmlString = TooltipTextUtil.textToHtmlString(text);
String expectedString = "<b><tt>" + testText + "</tt></b>";
assertEquals(expectedString, htmlString);
}
@Test
public void transformTextToHtmlStringWithLinebreaks() {
String testText = "this\nis a\ntest text";
Text text = TooltipTextUtil.createText(testText, TooltipTextUtil.TextType.NORMAL);
String htmlString = TooltipTextUtil.textToHtmlString(text);
String expectedString = "this<br>is a<br>test text";
assertEquals(expectedString, htmlString);
}
@Test
public void formatToTextsNoReplacements() {
List<Text> expectedTextList = new ArrayList<>();
expectedTextList.add(TooltipTextUtil.createText("This search contains entries in which any field contains the regular expression "));
String test = "This search contains entries in which any field contains the regular expression ";
List<Text> textList = TooltipTextUtil.formatToTexts(test);
assertTrue(TextFlowEqualityHelper.checkIfTextsEqualsExpectedTexts(expectedTextList, textList));
}
@Test
public void formatToTextsEnd() {
List<Text> expectedTextList = new ArrayList<>();
expectedTextList.add(TooltipTextUtil.createText("This search contains entries in which any field contains the regular expression "));
expectedTextList.add(TooltipTextUtil.createText("replacing text", TooltipTextUtil.TextType.BOLD));
String test = "This search contains entries in which any field contains the regular expression <b>%0</b>";
List<Text> textList = TooltipTextUtil.formatToTexts(test, new TooltipTextUtil.TextReplacement("<b>%0</b>", "replacing text", TooltipTextUtil.TextType.BOLD));
assertTrue(TextFlowEqualityHelper.checkIfTextsEqualsExpectedTexts(expectedTextList, textList));
}
@Test
public void formatToTextsBegin() {
List<Text> expectedTextList = new ArrayList<>();
expectedTextList.add(TooltipTextUtil.createText("replacing text", TooltipTextUtil.TextType.BOLD));
expectedTextList.add(TooltipTextUtil.createText(" This search contains entries in which any field contains the regular expression"));
String test = "<b>%0</b> This search contains entries in which any field contains the regular expression";
List<Text> textList = TooltipTextUtil.formatToTexts(test, new TooltipTextUtil.TextReplacement("<b>%0</b>", "replacing text", TooltipTextUtil.TextType.BOLD));
assertTrue(TextFlowEqualityHelper.checkIfTextsEqualsExpectedTexts(expectedTextList, textList));
}
@Test
public void formatToTextsMiddle() {
List<Text> expectedTextList = new ArrayList<>();
expectedTextList.add(TooltipTextUtil.createText("This search contains entries "));
expectedTextList.add(TooltipTextUtil.createText("replacing text", TooltipTextUtil.TextType.BOLD));
expectedTextList.add(TooltipTextUtil.createText(" in which any field contains the regular expression"));
String test = "This search contains entries <b>%0</b> in which any field contains the regular expression";
List<Text> textList = TooltipTextUtil.formatToTexts(test, new TooltipTextUtil.TextReplacement("<b>%0</b>", "replacing text", TooltipTextUtil.TextType.BOLD));
assertTrue(TextFlowEqualityHelper.checkIfTextsEqualsExpectedTexts(expectedTextList, textList));
}
}
| 7,375 | 40.672316 | 165 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/comparator/NumericFieldComparatorTest.java | package org.jabref.gui.util.comparator;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class NumericFieldComparatorTest {
private final NumericFieldComparator comparator = new NumericFieldComparator();
@Test
public void compareTwoNumericInputs() {
assertEquals(2, comparator.compare("4", "2"));
}
@Test
public void compareTwoNullInputs() {
assertEquals(0, comparator.compare(null, null));
}
@Test
public void compareTwoInputsWithFirstNull() {
assertEquals(-1, comparator.compare(null, "2"));
}
@Test
public void compareTwoInputsWithSecondNull() {
assertEquals(1, comparator.compare("4", null));
}
@Test
public void compareTwoNotNumericInputs() {
assertEquals(-32, comparator.compare("HELLO", "hello"));
}
@Test
public void compareStringWithInteger() {
assertEquals(-1, comparator.compare("hi", "2"));
}
@Test
public void compareIntegerWithString() {
assertEquals(1, comparator.compare("4", "hi"));
}
@Test
public void compareNegativeInteger() {
assertEquals(1, comparator.compare("-4", "-5"));
}
@Test
public void compareWithMinusString() {
assertEquals(-1, comparator.compare("-", "-5"));
}
@Test
public void compareWithPlusString() {
assertEquals(-1, comparator.compare("+", "-5"));
}
@Test
public void compareWordWithMinus() {
assertEquals(-1, comparator.compare("-abc", "-5"));
}
@Test
void compareNumericSignalWithoutNumberWithLenghtBiggerThanOne() {
assertEquals(2, comparator.compare("- ", "+ "));
}
@Test
void compareNumericSignalAfterNumber() {
assertEquals(-2, comparator.compare("5- ", "7+ "));
}
}
| 1,847 | 23.315789 | 83 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/comparator/RankingFieldComparatorTest.java | package org.jabref.gui.util.comparator;
import java.util.Optional;
import org.jabref.gui.specialfields.SpecialFieldValueViewModel;
import org.jabref.model.entry.field.SpecialFieldValue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RankingFieldComparatorTest {
private RankingFieldComparator comparator;
private final SpecialFieldValue value1 = SpecialFieldValue.RANK_1;
private final SpecialFieldValue value2 = SpecialFieldValue.RANK_2;
private final SpecialFieldValue value3 = SpecialFieldValue.RANK_3;
private final Optional<SpecialFieldValueViewModel> rank1 = Optional.of(new SpecialFieldValueViewModel(value1));
private final Optional<SpecialFieldValueViewModel> rank2 = Optional.of(new SpecialFieldValueViewModel(value2));
private final Optional<SpecialFieldValueViewModel> rank3 = Optional.of(new SpecialFieldValueViewModel(value3));
@BeforeEach
public void setUp() {
comparator = new RankingFieldComparator();
}
@Test
public void compareHigherRankFirst() {
assertEquals(-2, comparator.compare(rank3, rank1));
assertEquals(-1, comparator.compare(rank2, rank1));
}
@Test
public void compareLowerRankFirst() {
assertEquals(1, comparator.compare(rank1, rank2));
assertEquals(2, comparator.compare(rank1, rank3));
}
@Test
public void compareSameRank() {
assertEquals(0, comparator.compare(rank1, rank1));
}
@Test
public void compareTwoEmptyInputs() {
assertEquals(0, comparator.compare(Optional.empty(), Optional.empty()));
}
@Test
public void compareTwoInputsWithFirstEmpty() {
assertEquals(1, comparator.compare(Optional.empty(), rank1));
}
@Test
public void compareTwoInputsWithSecondEmpty() {
assertEquals(-1, comparator.compare(rank1, Optional.empty()));
}
}
| 1,968 | 31.816667 | 115 | java |
null | jabref-main/src/test/java/org/jabref/gui/util/comparator/SpecialFieldComparatorTest.java | package org.jabref.gui.util.comparator;
import java.util.Optional;
import org.jabref.gui.specialfields.SpecialFieldValueViewModel;
import org.jabref.model.entry.field.SpecialFieldValue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SpecialFieldComparatorTest {
private SpecialFieldComparator comparator;
private final SpecialFieldValue value1 = SpecialFieldValue.PRIORITY_HIGH;
private final SpecialFieldValue value2 = SpecialFieldValue.PRIORITY_LOW;
private final SpecialFieldValue value3 = SpecialFieldValue.READ;
private final Optional<SpecialFieldValueViewModel> prio1 = Optional.of(new SpecialFieldValueViewModel(value1));
private final Optional<SpecialFieldValueViewModel> prio3 = Optional.of(new SpecialFieldValueViewModel(value2));
private final Optional<SpecialFieldValueViewModel> read = Optional.of(new SpecialFieldValueViewModel(value3));
@BeforeEach
public void setUp() {
comparator = new SpecialFieldComparator();
}
@Test
public void compareHigherPriorityFirst() {
assertEquals(-2, comparator.compare(prio1, prio3));
}
@Test
public void compareLowerPriorityFirst() {
assertEquals(2, comparator.compare(prio3, prio1));
}
@Test
public void compareSamePriority() {
assertEquals(0, comparator.compare(prio1, prio1));
}
@Test
public void compareUnrelatedFields() {
assertEquals(-11, comparator.compare(prio1, read));
}
@Test
public void compareTwoEmptyInputs() {
assertEquals(0, comparator.compare(Optional.empty(), Optional.empty()));
}
@Test
public void compareTwoInputsWithFirstEmpty() {
assertEquals(1, comparator.compare(Optional.empty(), prio1));
}
@Test
public void compareTwoInputsWithSecondEmpty() {
assertEquals(-1, comparator.compare(prio1, Optional.empty()));
}
}
| 1,991 | 30.619048 | 115 | java |
null | jabref-main/src/test/java/org/jabref/logic/TypedBibEntryTest.java | package org.jabref.logic;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.entry.types.UnknownEntryType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TypedBibEntryTest {
private BibEntryTypesManager entryTypesManager;
@BeforeEach
void setUp() {
entryTypesManager = new BibEntryTypesManager();
}
@Test
public void hasAllRequiredFieldsFail() {
BibEntry e = new BibEntry(StandardEntryType.Article);
e.setField(StandardField.AUTHOR, "abc");
e.setField(StandardField.TITLE, "abc");
e.setField(StandardField.JOURNAL, "abc");
TypedBibEntry typedEntry = new TypedBibEntry(e, BibDatabaseMode.BIBTEX);
assertFalse(typedEntry.hasAllRequiredFields(entryTypesManager));
}
@Test
public void hasAllRequiredFields() {
BibEntry e = new BibEntry(StandardEntryType.Article);
e.setField(StandardField.AUTHOR, "abc");
e.setField(StandardField.TITLE, "abc");
e.setField(StandardField.JOURNAL, "abc");
e.setField(StandardField.YEAR, "2015");
TypedBibEntry typedEntry = new TypedBibEntry(e, BibDatabaseMode.BIBTEX);
assertTrue(typedEntry.hasAllRequiredFields(entryTypesManager));
}
@Test
public void hasAllRequiredFieldsForUnknownTypeReturnsTrue() {
BibEntry e = new BibEntry(new UnknownEntryType("articlllleeeee"));
TypedBibEntry typedEntry = new TypedBibEntry(e, BibDatabaseMode.BIBTEX);
assertTrue(typedEntry.hasAllRequiredFields(entryTypesManager));
}
@Test
public void getTypeForDisplayReturnsTypeName() {
BibEntry e = new BibEntry(StandardEntryType.InProceedings);
TypedBibEntry typedEntry = new TypedBibEntry(e, BibDatabaseMode.BIBTEX);
assertEquals("InProceedings", typedEntry.getTypeForDisplay());
}
@Test
public void getTypeForDisplayForUnknownTypeCapitalizeFirstLetter() {
BibEntry e = new BibEntry(new UnknownEntryType("articlllleeeee"));
TypedBibEntry typedEntry = new TypedBibEntry(e, BibDatabaseMode.BIBTEX);
assertEquals("Articlllleeeee", typedEntry.getTypeForDisplay());
}
}
| 2,590 | 34.986111 | 80 | java |
null | jabref-main/src/test/java/org/jabref/logic/autosaveandbackup/BackupManagerDiscardedTest.java | package org.jabref.logic.autosaveandbackup;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jabref.logic.exporter.AtomicFileWriter;
import org.jabref.logic.exporter.BibWriter;
import org.jabref.logic.exporter.BibtexDatabaseWriter;
import org.jabref.logic.exporter.SaveConfiguration;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.metadata.SaveOrder;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test for "discarded" flag
*/
class BackupManagerDiscardedTest {
private BibDatabaseContext bibDatabaseContext;
private BackupManager backupManager;
private Path testBib;
private SaveConfiguration saveConfiguration;
private PreferencesService preferencesService;
private BibEntryTypesManager bibEntryTypesManager;
private Path backupDir;
@BeforeEach
public void setup(@TempDir Path tempDir) throws Exception {
this.backupDir = tempDir.resolve("backups");
Files.createDirectories(backupDir);
testBib = tempDir.resolve("test.bib");
bibDatabaseContext = new BibDatabaseContext(new BibDatabase());
bibDatabaseContext.setDatabasePath(testBib);
bibEntryTypesManager = new BibEntryTypesManager();
saveConfiguration = mock(SaveConfiguration.class);
when(saveConfiguration.shouldMakeBackup()).thenReturn(false);
when(saveConfiguration.getSaveOrder()).thenReturn(SaveOrder.getDefaultSaveOrder());
when(saveConfiguration.withMakeBackup(anyBoolean())).thenReturn(saveConfiguration);
preferencesService = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS);
saveDatabase();
backupManager = new BackupManager(bibDatabaseContext, bibEntryTypesManager, preferencesService);
makeBackup();
}
private void saveDatabase() throws IOException {
try (Writer writer = new AtomicFileWriter(testBib, StandardCharsets.UTF_8, false)) {
BibWriter bibWriter = new BibWriter(writer, bibDatabaseContext.getDatabase().getNewLineSeparator());
new BibtexDatabaseWriter(
bibWriter,
saveConfiguration,
preferencesService.getFieldPreferences(),
preferencesService.getCitationKeyPatternPreferences(),
bibEntryTypesManager)
.saveDatabase(bibDatabaseContext);
}
}
private void databaseModification() {
bibDatabaseContext.getDatabase().insertEntry(new BibEntry().withField(StandardField.NOTE, "test"));
}
private void makeBackup() {
backupManager.determineBackupPathForNewBackup(backupDir).ifPresent(path -> backupManager.performBackup(path));
}
@Test
public void noDiscardingAChangeLeadsToNewerBackupBeReported() throws Exception {
databaseModification();
makeBackup();
assertTrue(BackupManager.backupFileDiffers(testBib, backupDir));
}
@Test
public void noDiscardingASavedChange() throws Exception {
databaseModification();
makeBackup();
saveDatabase();
assertFalse(BackupManager.backupFileDiffers(testBib, backupDir));
}
@Test
public void discardingAChangeLeadsToNewerBackupToBeIgnored() throws Exception {
databaseModification();
makeBackup();
backupManager.discardBackup(backupDir);
assertFalse(BackupManager.backupFileDiffers(testBib, backupDir));
}
}
| 4,155 | 35.45614 | 118 | java |
null | jabref-main/src/test/java/org/jabref/logic/autosaveandbackup/BackupManagerTest.java | package org.jabref.logic.autosaveandbackup;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.jabref.logic.util.BackupFileType;
import org.jabref.logic.util.OS;
import org.jabref.logic.util.io.BackupFileUtil;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.groups.event.GroupUpdatedEvent;
import org.jabref.model.metadata.MetaData;
import org.jabref.model.metadata.event.MetaDataChangedEvent;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BackupManagerTest {
Path backupDir;
@BeforeEach
void setup(@TempDir Path tempDir) {
backupDir = tempDir.resolve("backup");
}
@Test
public void backupFileNameIsCorrectlyGeneratedInAppDataDirectory() {
Path bibPath = Path.of("tmp", "test.bib");
backupDir = OS.getNativeDesktop().getBackupDirectory();
Path bakPath = BackupManager.getBackupPathForNewBackup(bibPath, backupDir);
// Pattern is "27182d3c--test.bib--", but the hashing is implemented differently on Linux than on Windows
assertNotEquals("", bakPath);
}
@Test
public void backupFileIsEqualForNonExistingBackup() throws Exception {
Path originalFile = Path.of(BackupManagerTest.class.getResource("no-autosave.bib").toURI());
assertFalse(BackupManager.backupFileDiffers(originalFile, backupDir));
}
@Test
public void backupFileIsEqual() throws Exception {
// Prepare test: Create backup file on "right" path
Path source = Path.of(BackupManagerTest.class.getResource("no-changes.bib.bak").toURI());
Path target = BackupFileUtil.getPathForNewBackupFileAndCreateDirectory(Path.of(BackupManagerTest.class.getResource("no-changes.bib").toURI()), BackupFileType.BACKUP, backupDir);
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Path originalFile = Path.of(BackupManagerTest.class.getResource("no-changes.bib").toURI());
assertFalse(BackupManager.backupFileDiffers(originalFile, backupDir));
}
@Test
public void backupFileDiffers() throws Exception {
// Prepare test: Create backup file on "right" path
Path source = Path.of(BackupManagerTest.class.getResource("changes.bib.bak").toURI());
Path target = BackupFileUtil.getPathForNewBackupFileAndCreateDirectory(Path.of(BackupManagerTest.class.getResource("changes.bib").toURI()), BackupFileType.BACKUP, backupDir);
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Path originalFile = Path.of(BackupManagerTest.class.getResource("changes.bib").toURI());
assertTrue(BackupManager.backupFileDiffers(originalFile, backupDir));
}
@Test
public void correctBackupFileDeterminedForMultipleBakFiles() throws Exception {
Path noChangesBib = Path.of(BackupManagerTest.class.getResource("no-changes.bib").toURI());
Path noChangesBibBak = Path.of(BackupManagerTest.class.getResource("no-changes.bib.bak").toURI());
// Prepare test: Create backup files on "right" path
// most recent file does not have any changes
Path target = BackupFileUtil.getPathForNewBackupFileAndCreateDirectory(noChangesBib, BackupFileType.BACKUP, backupDir);
Files.copy(noChangesBibBak, target, StandardCopyOption.REPLACE_EXISTING);
// create "older" .bak files containing changes
for (int i = 0; i < 10; i++) {
Path changesBibBak = Path.of(BackupManagerTest.class.getResource("changes.bib").toURI());
Path directory = backupDir;
String timeSuffix = "2020-02-03--00.00.0" + Integer.toString(i);
String fileName = BackupFileUtil.getUniqueFilePrefix(noChangesBib) + "--no-changes.bib--" + timeSuffix + ".bak";
target = directory.resolve(fileName);
Files.copy(changesBibBak, target, StandardCopyOption.REPLACE_EXISTING);
}
Path originalFile = noChangesBib;
assertFalse(BackupManager.backupFileDiffers(originalFile, backupDir));
}
@Test
public void bakFileWithNewerTimeStampLeadsToDiff() throws Exception {
Path changesBib = Path.of(BackupManagerTest.class.getResource("changes.bib").toURI());
Path changesBibBak = Path.of(BackupManagerTest.class.getResource("changes.bib.bak").toURI());
Path target = BackupFileUtil.getPathForNewBackupFileAndCreateDirectory(changesBib, BackupFileType.BACKUP, backupDir);
Files.copy(changesBibBak, target, StandardCopyOption.REPLACE_EXISTING);
assertTrue(BackupManager.backupFileDiffers(changesBib, backupDir));
}
@Test
public void bakFileWithOlderTimeStampDoesNotLeadToDiff() throws Exception {
Path changesBib = Path.of(BackupManagerTest.class.getResource("changes.bib").toURI());
Path changesBibBak = Path.of(BackupManagerTest.class.getResource("changes.bib.bak").toURI());
Path target = BackupFileUtil.getPathForNewBackupFileAndCreateDirectory(changesBib, BackupFileType.BACKUP, backupDir);
Files.copy(changesBibBak, target, StandardCopyOption.REPLACE_EXISTING);
// Make .bak file very old
Files.setLastModifiedTime(target, FileTime.fromMillis(0));
assertFalse(BackupManager.backupFileDiffers(changesBib, backupDir));
}
@Test
public void shouldNotCreateABackup(@TempDir Path customDir) throws Exception {
Path backupDir = customDir.resolve("subBackupDir");
Files.createDirectories(backupDir);
var database = new BibDatabaseContext(new BibDatabase());
database.setDatabasePath(customDir.resolve("Bibfile.bib"));
var preferences = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS);
var filePreferences = mock(FilePreferences.class);
when(preferences.getFilePreferences()).thenReturn(filePreferences);
when(filePreferences.getBackupDirectory()).thenReturn(backupDir);
BackupManager manager = BackupManager.start(database, mock(BibEntryTypesManager.class, Answers.RETURNS_DEEP_STUBS), preferences);
manager.listen(new MetaDataChangedEvent(new MetaData()));
BackupManager.shutdown(database, backupDir, false);
List<Path> files = Files.list(backupDir).toList();
assertEquals(Collections.emptyList(), files);
}
@Test
public void shouldCreateABackup(@TempDir Path customDir) throws Exception {
Path backupDir = customDir.resolve("subBackupDir");
Files.createDirectories(backupDir);
var database = new BibDatabaseContext(new BibDatabase());
database.setDatabasePath(customDir.resolve("Bibfile.bib"));
var preferences = mock(PreferencesService.class, Answers.RETURNS_DEEP_STUBS);
var filePreferences = mock(FilePreferences.class);
when(preferences.getFilePreferences()).thenReturn(filePreferences);
when(filePreferences.getBackupDirectory()).thenReturn(backupDir);
when(filePreferences.shouldCreateBackup()).thenReturn(true);
BackupManager manager = BackupManager.start(database, mock(BibEntryTypesManager.class, Answers.RETURNS_DEEP_STUBS), preferences);
manager.listen(new MetaDataChangedEvent(new MetaData()));
Optional<Path> fullBackupPath = manager.determineBackupPathForNewBackup(backupDir);
fullBackupPath.ifPresent(manager::performBackup);
manager.listen(new GroupUpdatedEvent(new MetaData()));
BackupManager.shutdown(database, backupDir, true);
List<Path> files = Files.list(backupDir).sorted().toList();
// we only know the first backup path because the second one is created on shutdown
// due to timing issues we cannot test that reliable
assertEquals(fullBackupPath.get(), files.get(0));
}
}
| 8,546 | 45.961538 | 185 | java |
null | jabref-main/src/test/java/org/jabref/logic/auxparser/AuxParserTest.java | package org.jabref.logic.auxparser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
class AuxParserTest {
private ImportFormatPreferences importFormatPreferences;
@BeforeEach
void setUp() {
importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
}
@AfterEach
void tearDown() {
importFormatPreferences = null;
}
@Test
void testNormal() throws URISyntaxException, IOException {
InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib");
Path auxFile = Path.of(AuxParserTest.class.getResource("paper.aux").toURI());
try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) {
ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader);
AuxParser auxParser = new DefaultAuxParser(result.getDatabase());
AuxParserResult auxResult = auxParser.parse(auxFile);
assertTrue(auxResult.getGeneratedBibDatabase().hasEntries());
assertEquals(0, auxResult.getUnresolvedKeysCount());
BibDatabase newDB = auxResult.getGeneratedBibDatabase();
List<BibEntry> newEntries = newDB.getEntries();
assertEquals(2, newEntries.size());
assertTrue(newEntries.get(0).hasChanged());
assertTrue(newEntries.get(1).hasChanged());
assertEquals(2, auxResult.getResolvedKeysCount());
assertEquals(2, auxResult.getFoundKeysInAux());
assertEquals(auxResult.getFoundKeysInAux() + auxResult.getCrossRefEntriesCount(),
auxResult.getResolvedKeysCount() + auxResult.getUnresolvedKeysCount());
assertEquals(0, auxResult.getCrossRefEntriesCount());
}
}
@Test
void testTwoArgMacro() throws URISyntaxException, IOException {
// Result should be identical to that of testNormal
InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib");
Path auxFile = Path.of(AuxParserTest.class.getResource("papertwoargmacro.aux").toURI());
try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) {
ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader);
AuxParser auxParser = new DefaultAuxParser(result.getDatabase());
AuxParserResult auxResult = auxParser.parse(auxFile);
assertTrue(auxResult.getGeneratedBibDatabase().hasEntries());
assertEquals(0, auxResult.getUnresolvedKeysCount());
BibDatabase newDB = auxResult.getGeneratedBibDatabase();
List<BibEntry> newEntries = newDB.getEntries();
assertEquals(2, newEntries.size());
assertTrue(newEntries.get(0).hasChanged());
assertTrue(newEntries.get(1).hasChanged());
assertEquals(2, auxResult.getResolvedKeysCount());
assertEquals(2, auxResult.getFoundKeysInAux());
assertEquals(auxResult.getFoundKeysInAux() + auxResult.getCrossRefEntriesCount(),
auxResult.getResolvedKeysCount() + auxResult.getUnresolvedKeysCount());
assertEquals(0, auxResult.getCrossRefEntriesCount());
}
}
@Test
void testNotAllFound() throws URISyntaxException, IOException {
InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib");
Path auxFile = Path.of(AuxParserTest.class.getResource("badpaper.aux").toURI());
try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) {
ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader);
AuxParser auxParser = new DefaultAuxParser(result.getDatabase());
AuxParserResult auxResult = auxParser.parse(auxFile);
assertTrue(auxResult.getGeneratedBibDatabase().hasEntries());
assertEquals(1, auxResult.getUnresolvedKeysCount());
BibDatabase newDB = auxResult.getGeneratedBibDatabase();
assertEquals(2, newDB.getEntries().size());
assertEquals(2, auxResult.getResolvedKeysCount());
assertEquals(3, auxResult.getFoundKeysInAux());
assertEquals(auxResult.getFoundKeysInAux() + auxResult.getCrossRefEntriesCount(),
auxResult.getResolvedKeysCount() + auxResult.getUnresolvedKeysCount());
assertEquals(0, auxResult.getCrossRefEntriesCount());
}
}
@Test
void duplicateBibDatabaseConfiguration() throws URISyntaxException, IOException {
InputStream originalStream = AuxParserTest.class.getResourceAsStream("config.bib");
Path auxFile = Path.of(AuxParserTest.class.getResource("paper.aux").toURI());
try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) {
ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader);
AuxParser auxParser = new DefaultAuxParser(result.getDatabase());
AuxParserResult auxResult = auxParser.parse(auxFile);
BibDatabase db = auxResult.getGeneratedBibDatabase();
assertEquals(Optional.of("\"Maintained by \" # maintainer"), db.getPreamble());
assertEquals(1, db.getStringCount());
}
}
@Test
void testNestedAux() throws URISyntaxException, IOException {
InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib");
Path auxFile = Path.of(AuxParserTest.class.getResource("nested.aux").toURI());
try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) {
ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader);
AuxParser auxParser = new DefaultAuxParser(result.getDatabase());
AuxParserResult auxResult = auxParser.parse(auxFile);
assertTrue(auxResult.getGeneratedBibDatabase().hasEntries());
assertEquals(0, auxResult.getUnresolvedKeysCount());
BibDatabase newDB = auxResult.getGeneratedBibDatabase();
assertEquals(2, newDB.getEntries().size());
assertEquals(2, auxResult.getResolvedKeysCount());
assertEquals(2, auxResult.getFoundKeysInAux());
assertEquals(auxResult.getFoundKeysInAux() + auxResult.getCrossRefEntriesCount(),
auxResult.getResolvedKeysCount() + auxResult.getUnresolvedKeysCount());
assertEquals(0, auxResult.getCrossRefEntriesCount());
}
}
@Test
void testCrossRef() throws URISyntaxException, IOException {
InputStream originalStream = AuxParserTest.class.getResourceAsStream("origin.bib");
Path auxFile = Path.of(AuxParserTest.class.getResource("crossref.aux").toURI());
try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) {
ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader);
AuxParser auxParser = new DefaultAuxParser(result.getDatabase());
AuxParserResult auxResult = auxParser.parse(auxFile);
assertTrue(auxResult.getGeneratedBibDatabase().hasEntries());
assertEquals(2, auxResult.getUnresolvedKeysCount());
BibDatabase newDB = auxResult.getGeneratedBibDatabase();
assertEquals(4, newDB.getEntries().size());
assertEquals(3, auxResult.getResolvedKeysCount());
assertEquals(4, auxResult.getFoundKeysInAux());
assertEquals(auxResult.getFoundKeysInAux() + auxResult.getCrossRefEntriesCount(),
auxResult.getResolvedKeysCount() + auxResult.getUnresolvedKeysCount());
assertEquals(1, auxResult.getCrossRefEntriesCount());
}
}
@Test
void testFileNotFound() {
AuxParser auxParser = new DefaultAuxParser(new BibDatabase());
AuxParserResult auxResult = auxParser.parse(Path.of("unknownfile.aux"));
assertFalse(auxResult.getGeneratedBibDatabase().hasEntries());
assertEquals(0, auxResult.getUnresolvedKeysCount());
BibDatabase newDB = auxResult.getGeneratedBibDatabase();
assertEquals(0, newDB.getEntries().size());
assertEquals(0, auxResult.getResolvedKeysCount());
assertEquals(0, auxResult.getFoundKeysInAux());
assertEquals(auxResult.getFoundKeysInAux() + auxResult.getCrossRefEntriesCount(),
auxResult.getResolvedKeysCount() + auxResult.getUnresolvedKeysCount());
assertEquals(0, auxResult.getCrossRefEntriesCount());
}
}
| 9,617 | 49.356021 | 112 | java |
null | jabref-main/src/test/java/org/jabref/logic/auxparser/DefaultAuxParserTest.java | package org.jabref.logic.auxparser;
/**
* Please see {@link AuxParserTest} for the test cases
*/
class DefaultAuxParserTest {
}
| 131 | 15.5 | 54 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java | package org.jabref.logic.bibtex;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.model.entry.BibEntry;
import org.junit.jupiter.api.Assertions;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
public class BibEntryAssert {
/**
* Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to
* contain a single entry
*
* @param clazz the class where to call `getResourceAsStream`
* @param resourceName the resource to read
* @param entry the entry to compare with
*/
public static void assertEquals(Class<?> clazz, String resourceName, BibEntry entry)
throws IOException {
assertNotNull(clazz);
assertNotNull(resourceName);
assertNotNull(entry);
try (InputStream shouldBeIs = clazz.getResourceAsStream(resourceName)) {
BibEntryAssert.assertEquals(shouldBeIs, entry);
}
}
/**
* Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to
* contain a single entry
*
* @param clazz the class where to call `getResourceAsStream`
* @param resourceName the resource to read
* @param asIsEntries a list containing a single entry to compare with
*/
public static void assertEquals(Class<?> clazz, String resourceName, List<BibEntry> asIsEntries)
throws IOException {
assertNotNull(clazz);
assertNotNull(resourceName);
assertNotNull(asIsEntries);
try (InputStream shouldBeIs = clazz.getResourceAsStream(resourceName)) {
BibEntryAssert.assertEquals(shouldBeIs, asIsEntries);
}
}
private static List<BibEntry> getListFromInputStream(InputStream is) throws IOException {
ParserResult result;
try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
BibtexParser parser = new BibtexParser(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS));
result = parser.parse(reader);
}
assertNotNull(result);
assertNotNull(result.getDatabase());
assertNotNull(result.getDatabase().getEntries());
return result.getDatabase().getEntries();
}
/**
* Reads a bibtex database from the given InputStream. The list is compared with the given list.
*
* @param expectedInputStream the inputStream reading the entry from
* @param actualEntries a list containing a single entry to compare with
*/
public static void assertEquals(InputStream expectedInputStream, List<BibEntry> actualEntries)
throws IOException {
assertNotNull(expectedInputStream);
assertNotNull(actualEntries);
// explicit reference of Assertions is needed here to disambiguate from the methods defined by this class
List<BibEntry> expectedEntries = getListFromInputStream(expectedInputStream);
Assertions.assertEquals(expectedEntries, actualEntries);
}
public static void assertEquals(List<BibEntry> expectedEntries, InputStream actualInputStream)
throws IOException {
assertNotNull(actualInputStream);
assertNotNull(expectedEntries);
// explicit reference of Assertions is needed here to disambiguate from the methods defined by this class
Assertions.assertEquals(expectedEntries, getListFromInputStream(actualInputStream));
}
/**
* Reads a bibtex database from the given InputStream. The result has to contain a single BibEntry. This entry is
* compared to the given entry
*
* @param expected the inputStream reading the entry from
* @param actual the entry to compare with
*/
public static void assertEquals(InputStream expected, BibEntry actual)
throws IOException {
assertEquals(expected, Collections.singletonList(actual));
}
/**
* Compares two InputStreams. For each InputStream a list will be created. expectedIs is read directly, actualIs is
* filtered through importer to convert to a list of BibEntries.
*
* @param expectedIs A BibtexImporter InputStream.
* @param fileToImport The path to the file to be imported.
* @param importer The fileformat you want to use to read the passed file to get the list of expected
* BibEntries
*/
public static void assertEquals(InputStream expectedIs, Path fileToImport, Importer importer)
throws IOException {
assertEquals(getListFromInputStream(expectedIs), fileToImport, importer);
}
public static void assertEquals(InputStream expectedIs, URL fileToImport, Importer importer)
throws URISyntaxException, IOException {
assertEquals(expectedIs, Path.of(fileToImport.toURI()), importer);
}
/**
* Compares a list of BibEntries to an InputStream. actualIs is filtered through importerForActualIs to convert to a
* list of BibEntries.
*
* @param expected A BibtexImporter InputStream.
* @param fileToImport The path to the file to be imported.
* @param importer The fileformat you want to use to read the passed file to get the list of expected
* BibEntries
*/
public static void assertEquals(List<BibEntry> expected, Path fileToImport, Importer importer)
throws IOException {
List<BibEntry> actualEntries = importer.importDatabase(fileToImport)
.getDatabase().getEntries();
// explicit reference of Assertions is needed here to disambiguate from the methods defined by this class
Assertions.assertEquals(expected, actualEntries);
}
public static void assertEquals(List<BibEntry> expected, URL fileToImport, Importer importer)
throws URISyntaxException, IOException {
assertEquals(expected, Path.of(fileToImport.toURI()), importer);
}
}
| 6,563 | 42.184211 | 120 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java | package org.jabref.logic.bibtex;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import org.jabref.logic.exporter.BibWriter;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.util.OS;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.EntryTypeFactory;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.entry.types.UnknownEntryType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Answers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
class BibEntryWriterTest {
private static ImportFormatPreferences importFormatPreferences;
private final StringWriter stringWriter = new StringWriter();
private BibWriter bibWriter = new BibWriter(stringWriter, OS.NEWLINE);
private BibEntryWriter bibEntryWriter;
@BeforeEach
void setUpWriter() {
importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS);
FieldPreferences fieldPreferences = new FieldPreferences(true, List.of(StandardField.MONTH), Collections.emptyList());
bibEntryWriter = new BibEntryWriter(new FieldWriter(fieldPreferences), new BibEntryTypesManager());
}
@Test
void testSerialization() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article);
// set a required field
entry.setField(StandardField.AUTHOR, "Foo Bar");
entry.setField(StandardField.JOURNAL, "International Journal of Something");
// set an optional field
entry.setField(StandardField.NUMBER, "1");
entry.setField(StandardField.NOTE, "some note");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expected = """
@Article{,
author = {Foo Bar},
journal = {International Journal of Something},
note = {some note},
number = {1},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void writeOtherTypeTest() throws Exception {
String expected = """
@Other{test,
comment = {testentry},
}
""".replaceAll("\n", OS.NEWLINE);
BibEntry entry = new BibEntry(new UnknownEntryType("other"));
entry.setField(StandardField.COMMENT, "testentry");
entry.setCitationKey("test");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(expected, stringWriter.toString());
}
@Test
void writeEntryWithFile() throws Exception {
BibEntry entry = new BibEntry(StandardEntryType.Article);
LinkedFile file = new LinkedFile("test", Path.of("/home/uers/test.pdf"), "PDF");
entry.addFile(file);
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals("""
@Article{,
file = {test:/home/uers/test.pdf:PDF},
}
""".replaceAll("\n", OS.NEWLINE), stringWriter.toString());
}
@Test
void writeEntryWithOrField() throws Exception {
BibEntry entry = new BibEntry(StandardEntryType.InBook);
// set an required OR field (author/editor)
entry.setField(StandardField.EDITOR, "Foo Bar");
entry.setField(StandardField.JOURNAL, "International Journal of Something");
// set an optional field
entry.setField(StandardField.NUMBER, "1");
entry.setField(StandardField.NOTE, "some note");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expected = """
@InBook{,
editor = {Foo Bar},
note = {some note},
number = {1},
journal = {International Journal of Something},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void writeEntryWithOrFieldBothFieldsPresent() throws Exception {
BibEntry entry = new BibEntry(StandardEntryType.InBook);
// set an required OR field with both fields(author/editor)
entry.setField(StandardField.AUTHOR, "Foo Thor");
entry.setField(StandardField.EDITOR, "Edi Bar");
entry.setField(StandardField.JOURNAL, "International Journal of Something");
// set an optional field
entry.setField(StandardField.NUMBER, "1");
entry.setField(StandardField.NOTE, "some note");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expected = """
@InBook{,
author = {Foo Thor},
editor = {Edi Bar},
note = {some note},
number = {1},
journal = {International Journal of Something},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void writeReallyUnknownTypeTest() throws Exception {
String expected = """
@Reallyunknowntype{test,
comment = {testentry},
}
""".replaceAll("\n", OS.NEWLINE);
BibEntry entry = new BibEntry();
entry.setType(new UnknownEntryType("ReallyUnknownType"));
entry.setField(StandardField.COMMENT, "testentry");
entry.setCitationKey("test");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(expected, stringWriter.toString());
}
@Test
void roundTripTest() throws IOException {
String bibtexEntry = """
@Article{test,
Author = {Foo Bar},
Journal = {International Journal of Something},
Note = {some note},
Number = {1}
}
""".replaceAll("\n", OS.NEWLINE);
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void roundTripKeepsFilePathWithBackslashes() throws IOException {
String bibtexEntry = """
@Article{,
file = {Tagungen\\2013\\KWTK45},
}
""".replaceAll("\n", OS.NEWLINE);
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void roundTripKeepsEscapedCharacters() throws IOException {
String bibtexEntry = """
@Article{,
demofield = {Tagungen\\2013\\KWTK45},
}
""".replaceAll("\n", OS.NEWLINE);
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void roundTripKeepsFilePathEndingWithBackslash() throws IOException {
String bibtexEntry = """
@Article{,
file = {dir\\},
}
""".replaceAll("\n", OS.NEWLINE);
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void roundTripWithPrependingNewlines() throws IOException {
// @formatter:off
String bibtexEntry = "\r\n@Article{test," + OS.NEWLINE +
" Author = {Foo Bar}," + OS.NEWLINE +
" Journal = {International Journal of Something}," + OS.NEWLINE +
" Note = {some note}," + OS.NEWLINE +
" Number = {1}" + OS.NEWLINE +
"}" + OS.NEWLINE;
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry.substring(2), stringWriter.toString());
}
@Test
void roundTripWithKeepsCRLFLineBreakStyle() throws IOException {
// @formatter:off
String bibtexEntry = "@Article{test,\r\n" +
" Author = {Foo Bar},\r\n" +
" Journal = {International Journal of Something},\r\n" +
" Note = {some note},\r\n" +
" Number = {1}\r\n" +
"}\r\n";
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
// need to reconfigure writer to use "\r\n"
bibWriter = new BibWriter(stringWriter, "\r\n");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void roundTripWithKeepsLFLineBreakStyle() throws IOException {
// @formatter:off
String bibtexEntry = "@Article{test,\n" +
" Author = {Foo Bar},\n" +
" Journal = {International Journal of Something},\n" +
" Note = {some note},\n" +
" Number = {1}\n" +
"}\n";
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
// need to reconfigure writer to use "\n"
bibWriter = new BibWriter(stringWriter, "\n");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void roundTripWithModification() throws IOException {
// @formatter:off
String bibtexEntry = """
@Article{test,
Author = {Foo Bar},
Journal = {International Journal of Something},
Note = {some note},
Number = {1},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// Modify entry
entry.setField(StandardField.AUTHOR, "BlaBla");
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expected = """
@Article{test,
author = {BlaBla},
journal = {International Journal of Something},
note = {some note},
number = {1},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void roundTripWithCamelCasingInTheOriginalEntryAndResultInLowerCase() throws IOException {
// @formatter:off
String bibtexEntry = """
@Article{test,
Author = {Foo Bar},
Journal = {International Journal of Something},
Number = {1},
Note = {some note},
HowPublished = {asdf},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// modify entry
entry.setField(StandardField.AUTHOR, "BlaBla");
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expected = """
@Article{test,
author = {BlaBla},
journal = {International Journal of Something},
note = {some note},
number = {1},
howpublished = {asdf},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void testEntryTypeChange() throws IOException {
// @formatter:off
String expected = """
@Article{test,
author = {BlaBla},
journal = {International Journal of Something},
number = {1},
note = {some note},
howpublished = {asdf},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(expected));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// modify entry
entry.setType(StandardEntryType.InProceedings);
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expectedNewEntry = """
@InProceedings{test,
author = {BlaBla},
note = {some note},
number = {1},
howpublished = {asdf},
journal = {International Journal of Something},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expectedNewEntry, stringWriter.toString());
}
@Test
void roundTripWithAppendedNewlines() throws IOException {
// @formatter:off
String bibtexEntry = "@Article{test," + OS.NEWLINE +
" Author = {Foo Bar}," + OS.NEWLINE +
" Journal = {International Journal of Something}," + OS.NEWLINE +
" Number = {1}," + OS.NEWLINE +
" Note = {some note}" + OS.NEWLINE +
"}\n\n";
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
String actual = stringWriter.toString();
// Only one appending newline is written by the writer
// OS.NEWLINE is used, not the given one
assertEquals(bibtexEntry.substring(0, bibtexEntry.length() - 2) + OS.NEWLINE, actual);
}
@Test
void roundTripNormalizesNewLines() throws IOException {
// @formatter:off
String bibtexEntry = "@Article{test,\n" +
" Author = {Foo Bar},\r\n" +
" Journal = {International Journal of Something},\n" +
" Number = {1},\n" +
" Note = {some note}\r\n" +
"}\n\n";
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
String actual = stringWriter.toString();
String expected = "@Article{test," + OS.NEWLINE +
" Author = {Foo Bar}," + OS.NEWLINE +
" Journal = {International Journal of Something}," + OS.NEWLINE +
" Number = {1}," + OS.NEWLINE +
" Note = {some note}" + OS.NEWLINE +
"}" + OS.NEWLINE;
assertEquals(expected, actual);
}
@Test
void multipleWritesWithoutModification() throws IOException {
// @formatter:off
String bibtexEntry = """
@Article{test,
Author = {Foo Bar},
Journal = {International Journal of Something},
Note = {some note},
Number = {1}
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
String result = testSingleWrite(bibtexEntry);
result = testSingleWrite(result);
result = testSingleWrite(result);
assertEquals(bibtexEntry, result);
}
private String testSingleWrite(String bibtexEntry) throws IOException {
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
StringWriter writer = new StringWriter();
BibWriter bibWriter = new BibWriter(writer, OS.NEWLINE);
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
String actual = writer.toString();
assertEquals(bibtexEntry, actual);
return actual;
}
@Test
void monthFieldSpecialSyntax() throws IOException {
// @formatter:off
String bibtexEntry = """
@Article{test,
Author = {Foo Bar},
Month = mar,
Number = {1}
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// check month field
Set<Field> fields = entry.getFields();
assertTrue(fields.contains(StandardField.MONTH));
assertEquals("#mar#", entry.getField(StandardField.MONTH).get());
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void customTypeCanBewritten() throws IOException {
// @formatter:off
String bibtexEntry = """
@reference{Broecker1984,
title = {International Center of Photography},
subtitle = {Encyclopedia of Photography},
editor = {Broecker, William L.},
date = {1984},
eprint = {305515791},
eprinttype = {scribd},
isbn = {0-517-55271-X},
keywords = {g:photography, p:positive, c:silver, m:albumen, c:pigment, m:carbon, g:reference, c:encyclopedia},
location = {New York},
pagetotal = {678},
publisher = {Crown},
}
""";
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
entry.setField(FieldFactory.parseField("location"), "NY");
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
String expected = """
@Reference{Broecker1984,
date = {1984},
editor = {Broecker, William L.},
eprint = {305515791},
eprinttype = {scribd},
isbn = {0-517-55271-X},
keywords = {g:photography, p:positive, c:silver, m:albumen, c:pigment, m:carbon, g:reference, c:encyclopedia},
location = {NY},
pagetotal = {678},
publisher = {Crown},
subtitle = {Encyclopedia of Photography},
title = {International Center of Photography},
}
""".replaceAll("\n", OS.NEWLINE);
assertEquals(expected, stringWriter.toString());
}
@Test
void constantMonthApril() throws Exception {
BibEntry entry = new BibEntry(StandardEntryType.Misc)
.withField(StandardField.MONTH, "#apr#");
// enable writing
entry.setChanged(true);
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals("""
@Misc{,
month = apr,
}
""".replaceAll("\n", OS.NEWLINE),
stringWriter.toString());
}
@Test
void monthApril() throws Exception {
BibEntry entry = new BibEntry(StandardEntryType.Misc)
.withField(StandardField.MONTH, "apr");
// enable writing
entry.setChanged(true);
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals("""
@Misc{,
month = {apr},
}
""".replaceAll("\n", OS.NEWLINE),
stringWriter.toString());
}
@Test
void filenameIsUnmodifiedDuringWrite() throws Exception {
// source: https://github.com/JabRef/jabref/issues/7012#issuecomment-707788107
String bibtexEntry = """
@Book{Hue17,
author = {Rudolf Huebener},
date = {2017},
title = {Leiter, Halbleiter, Supraleiter},
doi = {10.1007/978-3-662-53281-2},
publisher = {Springer Berlin Heidelberg},
file = {:Hue17 - Leiter # Halbleiter # Supraleiter.pdf:PDF},
timestamp = {2020.10.13},
}
""".replaceAll("\n", OS.NEWLINE);
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void addFieldWithLongerLength() throws IOException {
// @formatter:off
String bibtexEntry = OS.NEWLINE + OS.NEWLINE + "@Article{test," + OS.NEWLINE +
" author = {BlaBla}," + OS.NEWLINE +
" journal = {International Journal of Something}," + OS.NEWLINE +
" number = {1}," + OS.NEWLINE +
" note = {some note}," + OS.NEWLINE +
"}";
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// modify entry
entry.setField(StandardField.HOWPUBLISHED, "asdf");
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expected = OS.NEWLINE + "@Article{test," + OS.NEWLINE +
" author = {BlaBla}," + OS.NEWLINE +
" journal = {International Journal of Something}," + OS.NEWLINE +
" note = {some note}," + OS.NEWLINE +
" number = {1}," + OS.NEWLINE +
" howpublished = {asdf}," + OS.NEWLINE +
"}" + OS.NEWLINE;
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void doNotWriteEmptyFields() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article);
entry.setField(StandardField.AUTHOR, " ");
entry.setField(StandardField.NOTE, "some note");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
String expected = "@Article{," + OS.NEWLINE +
" note = {some note}," + OS.NEWLINE +
"}" + OS.NEWLINE;
assertEquals(expected, stringWriter.toString());
}
@Test
void writeThrowsErrorIfFieldContainsUnbalancedBraces() {
BibEntry entry = new BibEntry(StandardEntryType.Article);
entry.setField(StandardField.NOTE, "some text with unbalanced { braces");
assertThrows(IOException.class, () -> bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX));
}
@Test
void roundTripWithPrecedingCommentTest() throws IOException {
// @formatter:off
String bibtexEntry = """
% Some random comment that should stay here
@Article{test,
Author = {Foo Bar},
Journal = {International Journal of Something},
Note = {some note},
Number = {1}
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
assertEquals(bibtexEntry, stringWriter.toString());
}
@Test
void roundTripWithPrecedingCommentAndModificationTest() throws IOException {
// @formatter:off
String bibtexEntry = """
% Some random comment that should stay here
@Article{test,
Author = {Foo Bar},
Journal = {International Journal of Something},
Number = {1},
Note = {some note}
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
// read in bibtex string
ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(bibtexEntry));
Collection<BibEntry> entries = result.getDatabase().getEntries();
BibEntry entry = entries.iterator().next();
// change the entry
entry.setField(StandardField.AUTHOR, "John Doe");
// write out bibtex string
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBTEX);
// @formatter:off
String expected = """
% Some random comment that should stay here
@Article{test,
author = {John Doe},
journal = {International Journal of Something},
note = {some note},
number = {1},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void alphabeticSerialization() throws IOException {
BibEntry entry = new BibEntry(StandardEntryType.Article);
// required fields
entry.setField(StandardField.AUTHOR, "Foo Bar");
entry.setField(StandardField.JOURNALTITLE, "International Journal of Something");
entry.setField(StandardField.TITLE, "Title");
entry.setField(StandardField.DATE, "2019-10-16");
// optional fields
entry.setField(StandardField.NUMBER, "1");
entry.setField(StandardField.NOTE, "some note");
// unknown fields
entry.setField(StandardField.YEAR, "2019");
entry.setField(StandardField.CHAPTER, "chapter");
bibEntryWriter.write(entry, bibWriter, BibDatabaseMode.BIBLATEX);
// @formatter:off
String expected = """
@Article{,
author = {Foo Bar},
date = {2019-10-16},
journaltitle = {International Journal of Something},
title = {Title},
note = {some note},
number = {1},
chapter = {chapter},
year = {2019},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected, stringWriter.toString());
}
@Test
void testSerializeAll() throws IOException {
BibEntry entry1 = new BibEntry(StandardEntryType.Article);
// required fields
entry1.setField(StandardField.AUTHOR, "Journal Author");
entry1.setField(StandardField.JOURNALTITLE, "Journal of Words");
entry1.setField(StandardField.TITLE, "Entry Title");
entry1.setField(StandardField.DATE, "2020-11-16");
// optional fields
entry1.setField(StandardField.NUMBER, "1");
entry1.setField(StandardField.NOTE, "some note");
// unknown fields
entry1.setField(StandardField.YEAR, "2019");
entry1.setField(StandardField.CHAPTER, "chapter");
BibEntry entry2 = new BibEntry(StandardEntryType.Book);
// required fields
entry2.setField(StandardField.AUTHOR, "John Book");
entry2.setField(StandardField.BOOKTITLE, "The Big Book of Books");
entry2.setField(StandardField.TITLE, "Entry Title");
entry2.setField(StandardField.DATE, "2017-12-20");
// optional fields
entry2.setField(StandardField.NUMBER, "1");
entry2.setField(StandardField.NOTE, "some note");
// unknown fields
entry2.setField(StandardField.YEAR, "2020");
entry2.setField(StandardField.CHAPTER, "chapter");
String output = bibEntryWriter.serializeAll(List.of(entry1, entry2), BibDatabaseMode.BIBLATEX);
// @formatter:off
String expected1 = """
@Article{,
author = {Journal Author},
date = {2020-11-16},
journaltitle = {Journal of Words},
title = {Entry Title},
note = {some note},
number = {1},
chapter = {chapter},
year = {2019},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
// @formatter:off
String expected2 = """
@Book{,
author = {John Book},
date = {2017-12-20},
title = {Entry Title},
chapter = {chapter},
note = {some note},
number = {1},
booktitle = {The Big Book of Books},
year = {2020},
}
""".replaceAll("\n", OS.NEWLINE);
// @formatter:on
assertEquals(expected1 + OS.NEWLINE + expected2, output);
}
static Stream<Arguments> testGetFormattedFieldNameData() {
return Stream.of(
Arguments.of(" = ", "", 0),
Arguments.of("a = ", "a", 0),
Arguments.of(" = ", "", 2),
Arguments.of("a = ", "a", 2),
Arguments.of("abc = ", "abc", 2),
Arguments.of("abcdef = ", "abcdef", 6)
);
}
@ParameterizedTest
@MethodSource("testGetFormattedFieldNameData")
void testGetFormattedFieldName(String expected, String fieldName, int indent) {
Field field = FieldFactory.parseField(fieldName);
assertEquals(expected, BibEntryWriter.getFormattedFieldName(field, indent));
}
static Stream<Arguments> testGetLengthOfLongestFieldNameData() {
return Stream.of(
Arguments.of(1, new BibEntry().withField(FieldFactory.parseField("t"), "t")),
Arguments.of(5, new BibEntry(EntryTypeFactory.parse("reference"))
.withCitationKey("Broecker1984")
.withField(StandardField.TITLE, "International Center of Photography}"))
);
}
@ParameterizedTest
@MethodSource("testGetLengthOfLongestFieldNameData")
void testGetLengthOfLongestFieldName(int expected, BibEntry entry) {
assertEquals(expected, BibEntryWriter.getLengthOfLongestFieldName(entry));
}
}
| 36,647 | 38.406452 | 130 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/FieldContentFormatterTest.java | package org.jabref.logic.bibtex;
import java.util.Collections;
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;
class FieldContentFormatterTest {
private FieldContentFormatter parser;
@BeforeEach
void setUp() {
parser = new FieldContentFormatter(new FieldPreferences(
false,
Collections.emptyList(),
Collections.emptyList()));
}
@Test
void doesNotUnifyLineBreaks() {
String original = "I\r\nunify\nline\rbreaks.";
String processed = parser.format(new StringBuilder(original), StandardField.ABSTRACT);
// Normalization is done at org.jabref.logic.exporter.BibWriter, so no need to normalize here
assertEquals(original, processed);
}
@Test
void retainsWhitespaceForMultiLineFields() {
String original = "I\nkeep\nline\nbreaks\nand\n\ttabs.";
String abstrakt = parser.format(new StringBuilder(original), StandardField.ABSTRACT);
String review = parser.format(new StringBuilder(original), StandardField.REVIEW);
assertEquals(original, abstrakt);
assertEquals(original, review);
}
@Test
void removeWhitespaceFromNonMultiLineFields() {
String original = "I\nshould\nnot\ninclude\nadditional\nwhitespaces \nor\n\ttabs.";
String expected = "I should not include additional whitespaces or tabs.";
String abstrakt = parser.format(new StringBuilder(original), StandardField.TITLE);
String any = parser.format(new StringBuilder(original), new UnknownField("anyotherfield"));
assertEquals(expected, abstrakt);
assertEquals(expected, any);
}
}
| 1,863 | 31.701754 | 101 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/FieldWriterTest.java | package org.jabref.logic.bibtex;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.jabref.logic.util.OS;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.strings.StringUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FieldWriterTest {
private FieldWriter writer;
public static Stream<Arguments> getMarkdowns() {
return Stream.of(Arguments.of("""
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
We refer to [GitHub issues](https://github.com/JabRef/jabref/issues) by using `#NUM`.
In case, there is no issue present, the pull request implementing the feature is linked.
Note that this project **does not** adhere to [Semantic Versioning](http://semver.org/).
## [Unreleased]"""),
// Source: https://github.com/JabRef/jabref/issues/7010#issue-720030293
Arguments.of(
"""
#### Goal
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
#### Achievement\s
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
#### Method
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
"""
),
// source: https://github.com/JabRef/jabref/issues/8303 --> bug2.txt
Arguments.of("Particularly, we equip SOVA – a Semantic and Ontological Variability Analysis method")
);
}
@BeforeEach
void setUp() {
FieldPreferences fieldPreferences = new FieldPreferences(true, List.of(StandardField.MONTH), Collections.emptyList());
writer = new FieldWriter(fieldPreferences);
}
@Test
void noNormalizationOfNewlinesInAbstractField() throws Exception {
String text = "lorem" + OS.NEWLINE + " ipsum lorem ipsum\nlorem ipsum \rlorem ipsum\r\ntest";
String result = writer.write(StandardField.ABSTRACT, text);
// The normalization is done at org.jabref.logic.exporter.BibWriter, so no need to normalize here
String expected = "{" + text + "}";
assertEquals(expected, result);
}
@Test
void preserveNewlineInAbstractField() throws Exception {
String text = "lorem ipsum lorem ipsum" + OS.NEWLINE + "lorem ipsum lorem ipsum";
String result = writer.write(StandardField.ABSTRACT, text);
String expected = "{" + text + "}";
assertEquals(expected, result);
}
@Test
void preserveMultipleNewlinesInAbstractField() throws Exception {
String text = "lorem ipsum lorem ipsum" + OS.NEWLINE + OS.NEWLINE + "lorem ipsum lorem ipsum";
String result = writer.write(StandardField.ABSTRACT, text);
String expected = "{" + text + "}";
assertEquals(expected, result);
}
@Test
void preserveNewlineInReviewField() throws Exception {
String text = "lorem ipsum lorem ipsum" + OS.NEWLINE + "lorem ipsum lorem ipsum";
String result = writer.write(StandardField.REVIEW, text);
String expected = "{" + text + "}";
assertEquals(expected, result);
}
@Test
void removeWhitespaceFromNonMultiLineFields() throws Exception {
String original = "I\nshould\nnot\ninclude\nadditional\nwhitespaces \nor\n\ttabs.";
String expected = "{I should not include additional whitespaces or tabs.}";
String title = writer.write(StandardField.TITLE, original);
String any = writer.write(new UnknownField("anyotherfield"), original);
assertEquals(expected, title);
assertEquals(expected, any);
}
@Test
void reportUnbalancedBracing() throws Exception {
String unbalanced = "{";
assertThrows(InvalidFieldValueException.class, () -> writer.write(new UnknownField("anyfield"), unbalanced));
}
@Test
void reportUnbalancedBracingWithEscapedBraces() throws Exception {
String unbalanced = "{\\}";
assertThrows(InvalidFieldValueException.class, () -> writer.write(new UnknownField("anyfield"), unbalanced));
}
@Test
void tolerateBalancedBrace() throws Exception {
String text = "Incorporating evolutionary {Measures into Conservation Prioritization}";
assertEquals("{" + text + "}", writer.write(new UnknownField("anyfield"), text));
}
@Test
void tolerateEscapeCharacters() throws Exception {
String text = "Incorporating {\\O}evolutionary {Measures into Conservation Prioritization}";
assertEquals("{" + text + "}", writer.write(new UnknownField("anyfield"), text));
}
@Test
void hashEnclosedWordsGetRealStringsInMonthField() throws Exception {
String text = "#jan# - #feb#";
assertEquals("jan # { - } # feb", writer.write(StandardField.MONTH, text));
}
@ParameterizedTest
@MethodSource("getMarkdowns")
void keepHashSignInComment(String text) throws Exception {
String writeResult = writer.write(StandardField.COMMENT, text);
String resultWithLfAsNewLineSeparator = StringUtil.unifyLineBreaks(writeResult, "\n");
assertEquals("{" + text + "}", resultWithLfAsNewLineSeparator);
}
}
| 5,977 | 38.328947 | 126 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/FileFieldWriterTest.java | package org.jabref.logic.bibtex;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.jabref.model.entry.LinkedFile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class FileFieldWriterTest {
@Test
public void testQuoteStandard() {
assertEquals("a", FileFieldWriter.quote("a"));
}
@Test
public void testQuoteAllCharacters() {
assertEquals("a\\:\\;\\\\", FileFieldWriter.quote("a:;\\"));
}
@Test
public void testQuoteEmpty() {
assertEquals("", FileFieldWriter.quote(""));
}
@Test
public void testQuoteNull() {
assertNull(FileFieldWriter.quote(null));
}
private static Stream<Arguments> getEncodingTestData() {
return Stream.of(
Arguments.of("a:b;c:d", new String[][]{{"a", "b"}, {"c", "d"}}),
Arguments.of("a:;c:d", new String[][]{{"a", ""}, {"c", "d"}}),
Arguments.of("a:" + null + ";c:d", new String[][]{{"a", null}, {"c", "d"}}),
Arguments.of("a:\\:b;c\\;:d", new String[][]{{"a", ":b"}, {"c;", "d"}})
);
}
@ParameterizedTest
@MethodSource("getEncodingTestData")
public void testEncodeStringArray(String expected, String[][] values) {
assertEquals(expected, FileFieldWriter.encodeStringArray(values));
}
@Test
public void testFileFieldWriterGetStringRepresentation() {
LinkedFile file = new LinkedFile("test", Path.of("X:\\Users\\abc.pdf"), "PDF");
assertEquals("test:X\\:/Users/abc.pdf:PDF", FileFieldWriter.getStringRepresentation(file));
}
}
| 1,869 | 30.694915 | 99 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/BibDatabaseDiffTest.java | package org.jabref.logic.bibtex.comparator;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
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.assertNull;
class BibDatabaseDiffTest {
@Test
void compareOfEmptyDatabasesReportsNoDifferences() throws Exception {
BibDatabaseDiff diff = BibDatabaseDiff.compare(new BibDatabaseContext(), new BibDatabaseContext());
assertEquals(Optional.empty(), diff.getPreambleDifferences());
assertEquals(Optional.empty(), diff.getMetaDataDifferences());
assertEquals(Collections.emptyList(), diff.getBibStringDifferences());
assertEquals(Collections.emptyList(), diff.getEntryDifferences());
}
@Test
void compareOfSameEntryReportsNoDifferences() throws Exception {
BibEntry entry = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "test");
BibDatabaseDiff diff = compareEntries(entry, entry);
assertEquals(Collections.emptyList(), diff.getEntryDifferences());
}
@Test
void compareOfDifferentEntriesWithSameDataReportsNoDifferences() throws Exception {
BibEntry entryOne = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "test");
BibEntry entryTwo = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "test");
BibDatabaseDiff diff = compareEntries(entryOne, entryTwo);
assertEquals(Collections.emptyList(), diff.getEntryDifferences());
}
@Test
void compareOfTwoEntriesWithSameContentAndLfEndingsReportsNoDifferences() throws Exception {
BibEntry entryOne = new BibEntry().withField(StandardField.COMMENT, "line1\n\nline3\n\nline5");
BibEntry entryTwo = new BibEntry().withField(StandardField.COMMENT, "line1\n\nline3\n\nline5");
BibDatabaseDiff diff = compareEntries(entryOne, entryTwo);
assertEquals(Collections.emptyList(), diff.getEntryDifferences());
}
@Test
void compareOfTwoEntriesWithSameContentAndCrLfEndingsReportsNoDifferences() throws Exception {
BibEntry entryOne = new BibEntry().withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5");
BibEntry entryTwo = new BibEntry().withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5");
BibDatabaseDiff diff = compareEntries(entryOne, entryTwo);
assertEquals(Collections.emptyList(), diff.getEntryDifferences());
}
@Test
void compareOfTwoEntriesWithSameContentAndMixedLineEndingsReportsNoDifferences() throws Exception {
BibEntry entryOne = new BibEntry().withField(StandardField.COMMENT, "line1\n\nline3\n\nline5");
BibEntry entryTwo = new BibEntry().withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5");
BibDatabaseDiff diff = compareEntries(entryOne, entryTwo);
assertEquals(Collections.emptyList(), diff.getEntryDifferences());
}
@Test
void compareOfTwoDifferentEntriesWithDifferentDataReportsDifferences() throws Exception {
BibEntry entryOne = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "test");
BibEntry entryTwo = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "another test");
BibDatabaseDiff diff = compareEntries(entryOne, entryTwo);
// two different entries between the databases
assertEquals(2, diff.getEntryDifferences().size(), "incorrect amount of different entries");
assertEquals(entryOne, diff.getEntryDifferences().get(0).getOriginalEntry(), "there is another value as originalEntry");
assertNull(diff.getEntryDifferences().get(0).getNewEntry(), "newEntry is not null");
assertEquals(entryTwo, diff.getEntryDifferences().get(1).getNewEntry(), "there is another value as newEntry");
assertNull(diff.getEntryDifferences().get(1).getOriginalEntry(), "originalEntry is not null");
}
@Test
void compareOfThreeDifferentEntriesWithDifferentDataReportsDifferences() throws Exception {
BibEntry entryOne = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "test");
BibEntry entryTwo = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "another test");
BibEntry entryThree = new BibEntry(BibEntry.DEFAULT_TYPE).withField(StandardField.TITLE, "again another test");
BibDatabaseContext databaseOne = new BibDatabaseContext(new BibDatabase(Collections.singletonList(entryOne)));
BibDatabaseContext databaseTwo = new BibDatabaseContext(new BibDatabase(Arrays.asList(entryTwo, entryThree)));
BibDatabaseDiff diff = BibDatabaseDiff.compare(databaseOne, databaseTwo);
// three different entries between the databases
assertEquals(3, diff.getEntryDifferences().size(), "incorrect amount of different entries");
assertEquals(entryOne, diff.getEntryDifferences().get(0).getOriginalEntry(), "there is another value as originalEntry");
assertNull(diff.getEntryDifferences().get(0).getNewEntry(), "newEntry is not null");
assertEquals(entryTwo, diff.getEntryDifferences().get(1).getNewEntry(), "there is another value as newEntry");
assertNull(diff.getEntryDifferences().get(1).getOriginalEntry(), "originalEntry is not null");
assertEquals(entryThree, diff.getEntryDifferences().get(2).getNewEntry(), "there is another value as newEntry [2]");
assertNull(diff.getEntryDifferences().get(2).getOriginalEntry(), "originalEntry is not null [2]");
}
@Test
void compareOfTwoEntriesWithEqualCitationKeysShouldReportsOneDifference() {
BibEntry entryOne = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.TITLE, "test")
.withField(StandardField.AUTHOR, "author")
.withField(StandardField.YEAR, "2001")
.withCitationKey("key");
BibEntry entryTwo = new BibEntry(BibEntry.DEFAULT_TYPE)
.withField(StandardField.TITLE, "test1")
.withField(StandardField.AUTHOR, "writer")
.withField(StandardField.YEAR, "1899")
.withCitationKey("key");
BibDatabaseDiff diff = compareEntries(entryOne, entryTwo);
// two different entries between the databases
assertEquals(1, diff.getEntryDifferences().size(), "incorrect amount of different entries");
assertEquals(entryOne, diff.getEntryDifferences().get(0).getOriginalEntry(), "there is another value as originalEntry");
assertEquals(entryTwo, diff.getEntryDifferences().get(0).getNewEntry(), "there is another value as newEntry");
}
private BibDatabaseDiff compareEntries(BibEntry entryOne, BibEntry entryTwo) {
BibDatabaseContext databaseOne = new BibDatabaseContext(new BibDatabase(Collections.singletonList(entryOne)));
BibDatabaseContext databaseTwo = new BibDatabaseContext(new BibDatabase(Collections.singletonList(entryTwo)));
return BibDatabaseDiff.compare(databaseOne, databaseTwo);
}
}
| 7,335 | 49.944444 | 128 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/BibStringDiffTest.java | package org.jabref.logic.bibtex.comparator;
import java.util.Collections;
import java.util.List;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibtexString;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BibStringDiffTest {
private final BibDatabase originalDataBase = mock(BibDatabase.class);
private final BibDatabase newDataBase = mock(BibDatabase.class);
private final BibStringDiff diff = new BibStringDiff(new BibtexString("name2", "content2"), new BibtexString("name2", "content3"));
@BeforeEach
void setUp() {
when(originalDataBase.hasNoStrings()).thenReturn(false);
when(newDataBase.hasNoStrings()).thenReturn(false);
}
@Test
void compareTest() {
when(originalDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name", "content"), new BibtexString("name2", "content2")));
when(newDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name", "content"), new BibtexString("name2", "content3")));
List<BibStringDiff> result = BibStringDiff.compare(originalDataBase, newDataBase);
assertEquals(List.of(diff), result);
}
@Test
void equalTest() {
BibStringDiff other = new BibStringDiff(diff.getOriginalString(), diff.getNewString());
assertEquals(diff, other);
assertEquals(diff.hashCode(), other.hashCode());
}
@Test
void notEqualTest() {
BibStringDiff other = new BibStringDiff(diff.getNewString(), diff.getOriginalString());
assertNotEquals(diff, other);
assertNotEquals(diff.hashCode(), other.hashCode());
}
@Test
void identicalObjectsAreEqual() {
BibStringDiff other = diff;
assertTrue(other.equals(diff));
}
@Test
void compareToNullObjectIsFalse() {
assertFalse(diff.equals(null));
}
@Test
void compareToDifferentClassIsFalse() {
assertFalse(diff.equals(new Object()));
}
@Test
void testGetters() {
BibtexString bsOne = new BibtexString("aKahle", "Kahle, Brewster");
BibtexString bsTwo = new BibtexString("iMIT", "Institute of Technology");
BibStringDiff diff = new BibStringDiff(bsOne, bsTwo);
assertEquals(diff.getOriginalString(), bsOne);
assertEquals(diff.getNewString(), bsTwo);
}
@Test
void testCompareEmptyDatabases() {
when(originalDataBase.hasNoStrings()).thenReturn(true);
when(newDataBase.hasNoStrings()).thenReturn(true);
assertEquals(Collections.emptyList(), BibStringDiff.compare(originalDataBase, newDataBase));
}
@Test
void testCompareNameChange() {
when(originalDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name", "content")));
when(newDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name2", "content")));
List<BibStringDiff> result = BibStringDiff.compare(originalDataBase, newDataBase);
BibStringDiff expectedDiff = new BibStringDiff(new BibtexString("name", "content"), new BibtexString("name2", "content"));
assertEquals(List.of(expectedDiff), result);
}
@Test
void testCompareNoDiff() {
when(originalDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name", "content")));
when(newDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name", "content")));
List<BibStringDiff> result = BibStringDiff.compare(originalDataBase, newDataBase);
assertEquals(Collections.emptyList(), result);
}
@Test
void testCompareRemovedString() {
when(originalDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name", "content")));
when(newDataBase.getStringValues()).thenReturn(Collections.emptyList());
List<BibStringDiff> result = BibStringDiff.compare(originalDataBase, newDataBase);
BibStringDiff expectedDiff = new BibStringDiff(new BibtexString("name", "content"), null);
assertEquals(List.of(expectedDiff), result);
}
@Test
void testCompareAddString() {
when(originalDataBase.getStringValues()).thenReturn(Collections.emptyList());
when(newDataBase.getStringValues()).thenReturn(List.of(new BibtexString("name", "content")));
List<BibStringDiff> result = BibStringDiff.compare(originalDataBase, newDataBase);
BibStringDiff expectedDiff = new BibStringDiff(null, new BibtexString("name", "content"));
assertEquals(List.of(expectedDiff), result);
}
}
| 4,902 | 37.912698 | 145 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/BibtexStringComparatorTest.java | package org.jabref.logic.bibtex.comparator;
import org.jabref.model.entry.BibtexString;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class BibtexStringComparatorTest {
private final BibtexStringComparator bsc1 = new BibtexStringComparator(false);
private final BibtexStringComparator bsc2 = new BibtexStringComparator(true);
@Test
public void test() {
BibtexString bs1 = new BibtexString("VLSI", "Very Large Scale Integration");
BibtexString bs2 = new BibtexString("DSP", "Digital Signal Processing");
BibtexString bs3 = new BibtexString("DSP", "Digital Signal Processing");
// Same string
assertEquals(0, bsc1.compare(bs1, bs1), "Error when comparing the same string");
// Same content
assertEquals(0, bsc1.compare(bs2, bs3), "Different strings do not contain the same content");
// Alphabetical order
assertTrue(bsc1.compare(bs1, bs2) > 0, "bs1 does not lexicographically succeed bs2");
assertTrue(bsc1.compare(bs2, bs1) < 0, "bs2 does not lexicographically precede bs1");
// Same, but with the comparator checking for internal strings (none)
assertEquals(0, bsc2.compare(bs1, bs1), "Error when comparing the same string [internal checking enabled]");
assertEquals(0, bsc2.compare(bs2, bs3), "Different strings do not contain the same content [internal checking enabled]");
assertTrue(bsc2.compare(bs1, bs2) > 0, "bs1 does not succeed bs2 [internal checking enabled]");
assertTrue(bsc2.compare(bs2, bs1) < 0, "bs2 does not precede bs1 [internal checking enabled]");
// Create string with internal string
BibtexString bs4 = new BibtexString("DSPVLSI", "#VLSI# #DSP#");
// bs4 before bs1 if not considering that bs4 contains bs1
assertTrue(bsc1.compare(bs1, bs4) > 0, "bs1 does not lexicographically succeed bs4");
assertTrue(bsc1.compare(bs4, bs1) < 0, "bs4 does not lexicographically precede bs1");
// bs4 after bs1 if considering that bs4 contains bs1
assertTrue(bsc2.compare(bs1, bs4) < 0, "bs4 does not contain bs1 [internal checking enabled]");
assertTrue(bsc2.compare(bs4, bs1) > 0, "bs4 contains bs1 [internal checking enabled]");
}
}
| 2,374 | 50.630435 | 129 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/CrossRefEntryComparatorTest.java | package org.jabref.logic.bibtex.comparator;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
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;
public class CrossRefEntryComparatorTest {
private CrossRefEntryComparator comparator;
@BeforeEach
public void setUp() {
comparator = new CrossRefEntryComparator();
}
@AfterEach
public void tearDown() {
comparator = null;
}
@Test
public void isEqualForEntriesWithoutCrossRef() {
BibEntry e1 = new BibEntry();
BibEntry e2 = new BibEntry();
assertEquals(0, comparator.compare(e1, e2));
}
@Test
public void isEqualForEntriesWithCrossRef() {
BibEntry e1 = new BibEntry();
e1.setField(StandardField.CROSSREF, "1");
BibEntry e2 = new BibEntry();
e2.setField(StandardField.CROSSREF, "2");
assertEquals(0, comparator.compare(e1, e2));
}
@Test
public void isGreaterForEntriesWithoutCrossRef() {
BibEntry e1 = new BibEntry();
BibEntry e2 = new BibEntry();
e2.setField(StandardField.CROSSREF, "1");
assertEquals(1, comparator.compare(e1, e2));
}
@Test
public void isSmallerForEntriesWithCrossRef() {
BibEntry e1 = new BibEntry();
e1.setField(StandardField.CROSSREF, "1");
BibEntry e2 = new BibEntry();
assertEquals(-1, comparator.compare(e1, e2));
}
}
| 1,583 | 26.789474 | 60 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/EntryComparatorTest.java | package org.jabref.logic.bibtex.comparator;
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;
class EntryComparatorTest {
@SuppressWarnings("EqualsWithItself")
@Test
void recognizeIdenticalObjectsAsEqual() {
BibEntry entry = new BibEntry();
assertEquals(0, new EntryComparator(false, false, StandardField.TITLE).compare(entry, entry));
}
@Test
void compareAuthorFieldBiggerAscending() {
BibEntry entry1 = new BibEntry()
.withField(StandardField.AUTHOR, "Stephen King");
BibEntry entry2 = new BibEntry()
.withField(StandardField.AUTHOR, "Henning Mankell");
EntryComparator entryComparator = new EntryComparator(false, false, StandardField.AUTHOR);
assertEquals(-2, entryComparator.compare(entry1, entry2));
}
@Test
void bothEntriesHaveNotSetTheFieldToCompareAscending() {
BibEntry entry1 = new BibEntry()
.withField(StandardField.BOOKTITLE, "Stark - The Dark Half (1989)");
BibEntry entry2 = new BibEntry()
.withField(StandardField.COMMENTATOR, "Some Commentator");
EntryComparator entryComparator = new EntryComparator(false, false, StandardField.TITLE);
assertEquals(-1, entryComparator.compare(entry1, entry2));
}
@Test
void secondEntryHasNotSetFieldToCompareAscending() {
BibEntry entry1 = new BibEntry()
.withField(StandardField.TITLE, "Stark - The Dark Half (1989)");
BibEntry entry2 = new BibEntry()
.withField(StandardField.COMMENTATOR, "Some Commentator");
EntryComparator entryComparator = new EntryComparator(false, false, StandardField.TITLE);
assertEquals(-1, entryComparator.compare(entry1, entry2));
}
@Test
void firstEntryHasNotSetFieldToCompareAscending() {
BibEntry entry1 = new BibEntry()
.withField(StandardField.COMMENTATOR, "Some Commentator");
BibEntry entry2 = new BibEntry()
.withField(StandardField.TITLE, "Stark - The Dark Half (1989)");
EntryComparator entryComparator = new EntryComparator(false, false, StandardField.TITLE);
assertEquals(1, entryComparator.compare(entry1, entry2));
}
@Test
void bothEntriesNumericAscending() {
BibEntry entry1 = new BibEntry()
.withField(StandardField.EDITION, "1");
BibEntry entry2 = new BibEntry()
.withField(StandardField.EDITION, "3");
EntryComparator entryComparator = new EntryComparator(false, false, StandardField.EDITION);
assertEquals(-1, entryComparator.compare(entry1, entry2));
}
@Test
void compareObjectsByKeyAscending() {
BibEntry e1 = new BibEntry()
.withCitationKey("Mayer2019b");
BibEntry e2 = new BibEntry()
.withCitationKey("Mayer2019a");
assertEquals(1, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e1, e2));
assertEquals(-1, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e2, e1));
}
@Test
void compareObjectsByKeyWithNull() {
BibEntry e1 = new BibEntry()
.withCitationKey("Mayer2019b");
BibEntry e2 = new BibEntry();
assertEquals(-1, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e1, e2));
assertEquals(1, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e2, e1));
}
@Test
void compareObjectsByKeyWithBlank() {
BibEntry e1 = new BibEntry()
.withCitationKey("Mayer2019b");
BibEntry e2 = new BibEntry()
.withCitationKey(" ");
assertEquals(-1, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e1, e2));
assertEquals(1, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e2, e1));
}
@Test
void compareWithCrLfFields() {
BibEntry e1 = new BibEntry()
.withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5");
BibEntry e2 = new BibEntry()
.withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5");
assertEquals(0, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e1, e2));
}
@Test
void compareWithLfFields() {
BibEntry e1 = new BibEntry()
.withField(StandardField.COMMENT, "line1\n\nline3\n\nline5");
BibEntry e2 = new BibEntry()
.withField(StandardField.COMMENT, "line1\n\nline3\n\nline5");
assertEquals(0, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e1, e2));
}
@Test
void compareWithMixedLineEndings() {
BibEntry e1 = new BibEntry()
.withField(StandardField.COMMENT, "line1\n\nline3\n\nline5");
BibEntry e2 = new BibEntry()
.withField(StandardField.COMMENT, "line1\r\n\r\nline3\r\n\r\nline5");
assertEquals(-1, new EntryComparator(false, false, InternalField.KEY_FIELD).compare(e1, e2));
}
}
| 5,294 | 38.222222 | 102 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/FieldComparatorTest.java | package org.jabref.logic.bibtex.comparator;
import java.util.stream.Stream;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.OrFields;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FieldComparatorTest {
@Test
public void compareMonthFieldIdentity() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.MONTH);
BibEntry equal = new BibEntry()
.withField(StandardField.MONTH, "1");
assertEquals(0, comparator.compare(equal, equal));
}
@Test
public void compareMonthFieldEquality() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.MONTH);
BibEntry equal = new BibEntry()
.withField(StandardField.MONTH, "1");
BibEntry equal2 = new BibEntry()
.withField(StandardField.MONTH, "1");
assertEquals(0, comparator.compare(equal, equal2));
}
@Test
public void compareMonthFieldBiggerAscending() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.MONTH);
BibEntry smaller = new BibEntry()
.withField(StandardField.MONTH, "jan");
BibEntry bigger = new BibEntry()
.withField(StandardField.MONTH, "feb");
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareMonthFieldBiggerDescending() throws Exception {
FieldComparator comparator = new FieldComparator(new OrFields(StandardField.MONTH), true);
BibEntry smaller = new BibEntry()
.withField(StandardField.MONTH, "feb");
BibEntry bigger = new BibEntry()
.withField(StandardField.MONTH, "jan");
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareYearFieldIdentity() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.YEAR);
BibEntry equal = new BibEntry()
.withField(StandardField.YEAR, "2016");
assertEquals(0, comparator.compare(equal, equal));
}
@Test
public void compareYearFieldEquality() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.YEAR);
BibEntry equal = new BibEntry()
.withField(StandardField.YEAR, "2016");
BibEntry equal2 = new BibEntry()
.withField(StandardField.YEAR, "2016");
assertEquals(0, comparator.compare(equal, equal2));
}
@Test
public void compareYearFieldBiggerAscending() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.YEAR);
BibEntry smaller = new BibEntry()
.withField(StandardField.YEAR, "2000");
BibEntry bigger = new BibEntry()
.withField(StandardField.YEAR, "2016");
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareYearFieldBiggerDescending() throws Exception {
FieldComparator comparator = new FieldComparator(new OrFields(StandardField.YEAR), true);
BibEntry smaller = new BibEntry()
.withField(StandardField.YEAR, "2016");
BibEntry bigger = new BibEntry()
.withField(StandardField.YEAR, "2000");
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareTypeFieldIdentity() throws Exception {
FieldComparator comparator = new FieldComparator(InternalField.TYPE_HEADER);
BibEntry equal = new BibEntry(StandardEntryType.Article);
assertEquals(0, comparator.compare(equal, equal));
}
@Test
public void compareTypeFieldEquality() throws Exception {
FieldComparator comparator = new FieldComparator(InternalField.TYPE_HEADER);
BibEntry equal = new BibEntry(StandardEntryType.Article);
equal.setId("1");
BibEntry equal2 = new BibEntry(StandardEntryType.Article);
equal2.setId("1");
assertEquals(0, comparator.compare(equal, equal2));
}
@Test
public void compareTypeFieldBiggerAscending() throws Exception {
FieldComparator comparator = new FieldComparator(InternalField.TYPE_HEADER);
BibEntry smaller = new BibEntry(StandardEntryType.Article);
BibEntry bigger = new BibEntry(StandardEntryType.Book);
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareTypeFieldBiggerDescending() throws Exception {
FieldComparator comparator = new FieldComparator(new OrFields(InternalField.TYPE_HEADER), true);
BibEntry bigger = new BibEntry(StandardEntryType.Article);
BibEntry smaller = new BibEntry(StandardEntryType.Book);
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareStringFieldsIdentity() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.TITLE);
BibEntry equal = new BibEntry()
.withField(StandardField.TITLE, "title");
assertEquals(0, comparator.compare(equal, equal));
}
@Test
public void compareStringFieldsEquality() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.TITLE);
BibEntry equal = new BibEntry()
.withField(StandardField.TITLE, "title");
BibEntry equal2 = new BibEntry()
.withField(StandardField.TITLE, "title");
assertEquals(0, comparator.compare(equal, equal2));
}
@Test
public void compareStringFieldsBiggerAscending() throws Exception {
FieldComparator comparator = new FieldComparator(StandardField.TITLE);
BibEntry bigger = new BibEntry()
.withField(StandardField.TITLE, "b");
BibEntry smaller = new BibEntry()
.withField(StandardField.TITLE, "a");
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareStringFieldsBiggerDescending() throws Exception {
FieldComparator comparator = new FieldComparator(new OrFields(StandardField.TITLE), true);
BibEntry bigger = new BibEntry()
.withField(StandardField.TITLE, "a");
BibEntry smaller = new BibEntry()
.withField(StandardField.TITLE, "b");
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareNumericFieldsBiggerDescending() throws Exception {
FieldComparator comparator = new FieldComparator(new OrFields(StandardField.PMID), true);
BibEntry smaller = new BibEntry()
.withField(StandardField.PMID, "234567");
BibEntry bigger = new BibEntry()
.withField(StandardField.PMID, "123456");
assertEquals(1, comparator.compare(bigger, smaller));
}
@Test
public void compareParsableWithNonParsableNumericFieldDescending() throws Exception {
FieldComparator comparator = new FieldComparator(new OrFields(StandardField.PMID), true);
BibEntry parsable = new BibEntry()
.withField(StandardField.PMID, "123456");
BibEntry unparsable = new BibEntry()
.withField(StandardField.PMID, "abc##z");
assertEquals(1, comparator.compare(parsable, unparsable));
}
@ParameterizedTest
@MethodSource("provideArgumentsForNumericalComparison")
public void compareNumericalValues(int comparisonResult, String id1, String id2, String errorMessage) {
FieldComparator comparator = new FieldComparator(StandardField.PMID);
BibEntry entry1 = new BibEntry()
.withField(StandardField.PMID, id1);
BibEntry entry2 = new BibEntry()
.withField(StandardField.PMID, id2);
assertEquals(comparisonResult, comparator.compare(entry1, entry2), errorMessage);
}
private static Stream<Arguments> provideArgumentsForNumericalComparison() {
return Stream.of(
Arguments.of(0, "123456", "123456", "IDs are lexicographically not equal [1]"),
Arguments.of(1, "234567", "123456", "234567 is lexicographically smaller than 123456"),
Arguments.of(1, "abc##z", "123456", "abc##z is lexicographically smaller than 123456 "),
Arguments.of(0, "", "", "IDs are lexicographically not equal [2]"),
Arguments.of(1, "", "123456", "No ID is lexicographically smaller than 123456"),
Arguments.of(-1, "123456", "", "123456 is lexicographically greater than no ID")
);
}
}
| 9,041 | 38.832599 | 107 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/GroupDiffTest.java | package org.jabref.logic.bibtex.comparator;
import java.util.Optional;
import org.jabref.model.groups.AllEntriesGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.metadata.MetaData;
import org.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 GroupDiffTest {
private final MetaData originalMetaData = mock(MetaData.class);
private final MetaData newMetaData = mock(MetaData.class);
private GroupTreeNode rootOriginal;
@BeforeEach
void setup() {
rootOriginal = GroupTreeNode.fromGroup(new AllEntriesGroup("All entries"));
rootOriginal.addSubgroup(new ExplicitGroup("ExplicitA", GroupHierarchyType.INCLUDING, ','));
GroupTreeNode parent = rootOriginal
.addSubgroup(new ExplicitGroup("ExplicitParent", GroupHierarchyType.INDEPENDENT, ','));
parent.addSubgroup(new ExplicitGroup("ExplicitNode", GroupHierarchyType.REFINING, ','));
}
@Test
void compareEmptyGroups() {
when(originalMetaData.getGroups()).thenReturn(Optional.empty());
when(newMetaData.getGroups()).thenReturn(Optional.empty());
assertEquals(Optional.empty(), GroupDiff.compare(originalMetaData, newMetaData));
}
@Test
void compareGroupWithItself() {
when(originalMetaData.getGroups()).thenReturn(Optional.of(rootOriginal));
when(newMetaData.getGroups()).thenReturn(Optional.of(rootOriginal));
assertEquals(Optional.empty(), GroupDiff.compare(originalMetaData, newMetaData));
}
@Test
void compareWithChangedGroup() {
GroupTreeNode rootModified = GroupTreeNode.fromGroup(new AllEntriesGroup("All entries"));
rootModified.addSubgroup(new ExplicitGroup("ExplicitA", GroupHierarchyType.INCLUDING, ','));
when(originalMetaData.getGroups()).thenReturn(Optional.of(rootOriginal));
when(newMetaData.getGroups()).thenReturn(Optional.of(rootModified));
Optional<GroupDiff> groupDiff = GroupDiff.compare(originalMetaData, newMetaData);
Optional<GroupDiff> expectedGroupDiff = Optional.of(new GroupDiff(originalMetaData.getGroups().get(), newMetaData.getGroups().get()));
assertEquals(expectedGroupDiff.get().getNewGroupRoot(), groupDiff.get().getNewGroupRoot());
assertEquals(expectedGroupDiff.get().getOriginalGroupRoot(), groupDiff.get().getOriginalGroupRoot());
}
}
| 2,645 | 39.707692 | 142 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/MetaDataDiffTest.java | package org.jabref.logic.bibtex.comparator;
import java.util.Optional;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.metadata.ContentSelector;
import org.jabref.model.metadata.MetaData;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MetaDataDiffTest {
@Test
public void compareWithSameContentSelectorsDoesNotReportAnyDiffs() throws Exception {
MetaData one = new MetaData();
one.addContentSelector(new ContentSelector(StandardField.AUTHOR, "first", "second"));
MetaData two = new MetaData();
two.addContentSelector(new ContentSelector(StandardField.AUTHOR, "first", "second"));
assertEquals(Optional.empty(), MetaDataDiff.compare(one, two));
}
}
| 795 | 32.166667 | 93 | java |
null | jabref-main/src/test/java/org/jabref/logic/bibtex/comparator/PreambleDiffTest.java | package org.jabref.logic.bibtex.comparator;
import java.util.Optional;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
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 PreambleDiffTest {
private final BibDatabaseContext originalDataBaseContext = mock(BibDatabaseContext.class);
private final BibDatabaseContext newDataBaseContext = mock(BibDatabaseContext.class);
private final BibDatabase originalDataBase = mock(BibDatabase.class);
private final BibDatabase newDataBase = mock(BibDatabase.class);
@BeforeEach
void setUp() {
when(originalDataBaseContext.getDatabase()).thenReturn(originalDataBase);
when(newDataBaseContext.getDatabase()).thenReturn(newDataBase);
}
@Test
void compareSamePreambleTest() {
when(originalDataBase.getPreamble()).thenReturn(Optional.of("preamble"));
when(newDataBase.getPreamble()).thenReturn(Optional.of("preamble"));
assertEquals(Optional.empty(), PreambleDiff.compare(originalDataBaseContext, newDataBaseContext));
}
@Test
void compareDifferentPreambleTest() {
when(originalDataBase.getPreamble()).thenReturn(Optional.of("preamble"));
when(newDataBase.getPreamble()).thenReturn(Optional.of("otherPreamble"));
Optional<PreambleDiff> expected = Optional.of(new PreambleDiff("preamble", "otherPreamble"));
Optional<PreambleDiff> result = PreambleDiff.compare(originalDataBaseContext, newDataBaseContext);
assertEquals(expected, result);
}
}
| 1,745 | 36.956522 | 106 | java |
null | jabref-main/src/test/java/org/jabref/logic/bst/BstFunctionsTest.java | package org.jabref.logic.bst;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.jabref.logic.bst.util.BstCaseChangersTest;
import org.jabref.logic.bst.util.BstNameFormatterTest;
import org.jabref.logic.bst.util.BstPurifierTest;
import org.jabref.logic.bst.util.BstTextPrefixerTest;
import org.jabref.logic.bst.util.BstWidthCalculatorTest;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.antlr.v4.runtime.RecognitionException;
import org.junit.jupiter.api.Test;
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;
/**
* For additional tests see for
* <ul>
* <li> purify: {@link BstPurifierTest}</li>
* <li> width: {@link BstWidthCalculatorTest}</li>
* <li> format.name: {@link BstNameFormatterTest}</li>
* <li> change.case: {@link BstCaseChangersTest}</li>
* <li> prefix: {@link BstTextPrefixerTest}</li>
* </ul>
*/
class BstFunctionsTest {
@Test
public void testCompareFunctions() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test.compare } {
#5 #5 = % TRUE
#1 #2 = % FALSE
#3 #4 < % TRUE
#4 #3 < % FALSE
#4 #4 < % FALSE
#3 #4 > % FALSE
#4 #3 > % TRUE
#4 #4 > % FALSE
"H" "H" = % TRUE
"H" "Ha" = % FALSE
}
EXECUTE { test.compare }
""");
vm.render(Collections.emptyList());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testArithmeticFunctions() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } {
#1 #1 + % 2
#5 #2 - % 3
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(3, vm.getStack().pop());
assertEquals(2, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testArithmeticFunctionTypeMismatch() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } {
#1 "HELLO" + % Should throw exception
}
EXECUTE { test }
""");
assertThrows(BstVMException.class, () -> vm.render(Collections.emptyList()));
}
@Test
public void testStringOperations() throws RecognitionException {
// Test for concat (*) and add.period
BstVM vm = new BstVM("""
FUNCTION { test } {
"H" "ello" * % Hello
"Johnny" add.period$ % Johnny.
"Johnny." add.period$ % Johnny.
"Johnny!" add.period$ % Johnny!
"Johnny?" add.period$ % Johnny?
"Johnny} }}}" add.period$ % Johnny.}
"Johnny!}" add.period$ % Johnny!}
"Johnny?}" add.period$ % Johnny?}
"Johnny.}" add.period$ % Johnny.}
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals("Johnny.}", vm.getStack().pop());
assertEquals("Johnny?}", vm.getStack().pop());
assertEquals("Johnny!}", vm.getStack().pop());
assertEquals("Johnny.}", vm.getStack().pop());
assertEquals("Johnny?", vm.getStack().pop());
assertEquals("Johnny!", vm.getStack().pop());
assertEquals("Johnny.", vm.getStack().pop());
assertEquals("Johnny.", vm.getStack().pop());
assertEquals("Hello", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testMissing() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { title } { } { }
FUNCTION { presort } { cite$ 'sort.key$ := }
ITERATE { presort }
READ
SORT
FUNCTION { test } { title missing$ cite$ }
ITERATE { test }
""");
List<BibEntry> testEntries = List.of(
BstVMTest.defaultTestEntry(),
new BibEntry(StandardEntryType.Article)
.withCitationKey("test")
.withField(StandardField.AUTHOR, "No title"));
vm.render(testEntries);
assertEquals("test", vm.getStack().pop()); // cite
assertEquals(BstVM.TRUE, vm.getStack().pop()); // missing title
assertEquals("canh05", vm.getStack().pop()); // cite
assertEquals(BstVM.FALSE, vm.getStack().pop()); // missing title
assertEquals(0, vm.getStack().size());
}
@Test
public void testNumNames() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } {
"Johnny Foo { and } Mary Bar" num.names$
"Johnny Foo and Mary Bar" num.names$
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(2, vm.getStack().pop());
assertEquals(1, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testSubstring() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } {
"123456789" #2 #1 substring$ % 2
"123456789" #4 global.max$ substring$ % 456789
"123456789" #1 #9 substring$ % 123456789
"123456789" #1 #10 substring$ % 123456789
"123456789" #1 #99 substring$ % 123456789
"123456789" #-7 #3 substring$ % 123
"123456789" #-1 #1 substring$ % 9
"123456789" #-1 #3 substring$ % 789
"123456789" #-2 #2 substring$ % 78
} EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals("78", vm.getStack().pop());
assertEquals("789", vm.getStack().pop());
assertEquals("9", vm.getStack().pop());
assertEquals("123", vm.getStack().pop());
assertEquals("123456789", vm.getStack().pop());
assertEquals("123456789", vm.getStack().pop());
assertEquals("123456789", vm.getStack().pop());
assertEquals("456789", vm.getStack().pop());
assertEquals("2", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testEmpty() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { title } { } { }
READ
STRINGS { s }
FUNCTION { test } {
s empty$ % TRUE
"" empty$ % TRUE
" " empty$ % TRUE
title empty$ % TRUE
" HALLO " empty$ % FALSE
}
ITERATE { test }
""");
List<BibEntry> testEntry = List.of(new BibEntry(StandardEntryType.Article));
vm.render(testEntry);
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testFormatNameStatic() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { format }{ "Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin" #1 "{vv~}{ll}{, jj}{, f}?" format.name$ }
EXECUTE { format }
""");
List<BibEntry> v = Collections.emptyList();
vm.render(v);
assertEquals("de~la Vall{\\'e}e~Poussin, C.~L. X.~J?", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testFormatNameInEntries() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { author } { } { }
FUNCTION { presort } { cite$ 'sort.key$ := }
ITERATE { presort }
READ
SORT
FUNCTION { format }{ author #2 "{vv~}{ll}{, jj}{, f}?" format.name$ }
ITERATE { format }
""");
List<BibEntry> testEntries = List.of(
BstVMTest.defaultTestEntry(),
new BibEntry(StandardEntryType.Book)
.withCitationKey("test")
.withField(StandardField.AUTHOR, "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin"));
vm.render(testEntries);
assertEquals("de~la Vall{\\'e}e~Poussin, C.~L. X.~J?", vm.getStack().pop());
assertEquals("Annabi, H?", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testChangeCase() throws RecognitionException {
BstVM vm = new BstVM("""
STRINGS { title }
READ
FUNCTION { format.title } {
duplicate$ empty$
{ pop$ "" }
{ "t" change.case$ }
if$
}
FUNCTION { test } {
"hello world" "u" change.case$ format.title
"Hello World" format.title
"" format.title
"{A}{D}/{C}ycle: {I}{B}{M}'s {F}ramework for {A}pplication {D}evelopment and {C}ase" "u" change.case$ format.title
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals("{A}{D}/{C}ycle: {I}{B}{M}'s {F}ramework for {A}pplication {D}evelopment and {C}ase",
vm.getStack().pop());
assertEquals("", vm.getStack().pop());
assertEquals("Hello world", vm.getStack().pop());
assertEquals("Hello world", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testTextLength() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } {
"hello world" text.length$ % 11
"Hello {W}orld" text.length$ % 11
"" text.length$ % 0
"{A}{D}/{Cycle}" text.length$ % 8
"{\\This is one character}" text.length$ % 1
"{\\This {is} {one} {c{h}}aracter as well}" text.length$ % 1
"{\\And this too" text.length$ % 1
"These are {\\11}" text.length$ % 11
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(11, vm.getStack().pop());
assertEquals(1, vm.getStack().pop());
assertEquals(1, vm.getStack().pop());
assertEquals(1, vm.getStack().pop());
assertEquals(8, vm.getStack().pop());
assertEquals(0, vm.getStack().pop());
assertEquals(11, vm.getStack().pop());
assertEquals(11, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testIntToStr() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } { #3 int.to.str$ #9999 int.to.str$ }
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals("9999", vm.getStack().pop());
assertEquals("3", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testChrToInt() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } { "H" chr.to.int$ }
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(72, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testChrToIntIntToChr() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { test } { "H" chr.to.int$ int.to.chr$ }
EXECUTE {test}
""");
vm.render(Collections.emptyList());
assertEquals("H", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testType() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { } { } { }
FUNCTION { presort } { cite$ 'sort.key$ := }
ITERATE { presort }
SORT
FUNCTION { test } { type$ }
ITERATE { test }
""");
List<BibEntry> testEntries = List.of(
new BibEntry(StandardEntryType.Article).withCitationKey("a"),
new BibEntry(StandardEntryType.Book).withCitationKey("b"),
new BibEntry(StandardEntryType.Misc).withCitationKey("c"),
new BibEntry(StandardEntryType.InProceedings).withCitationKey("d"));
vm.render(testEntries);
assertEquals("inproceedings", vm.getStack().pop());
assertEquals("misc", vm.getStack().pop());
assertEquals("book", vm.getStack().pop());
assertEquals("article", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testCallType() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { title } { } { }
FUNCTION { presort } { cite$ 'sort.key$ := }
ITERATE { presort }
READ
SORT
FUNCTION { inproceedings }{ "InProceedings called on " title * }
FUNCTION { book }{ "Book called on " title * }
ITERATE { call.type$ }
""");
List<BibEntry> testEntries = List.of(
BstVMTest.defaultTestEntry(),
new BibEntry(StandardEntryType.Book)
.withCitationKey("test")
.withField(StandardField.TITLE, "Test"));
vm.render(testEntries);
assertEquals("Book called on Test", vm.getStack().pop());
assertEquals(
"InProceedings called on Effective work practices for floss development: A model and propositions",
vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testSwap() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { a } { #3 "Hallo" swap$ }
EXECUTE { a }
""");
List<BibEntry> v = Collections.emptyList();
vm.render(v);
assertEquals(3, vm.getStack().pop());
assertEquals("Hallo", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
void testAssignFunction() {
BstVM vm = new BstVM("""
INTEGERS { test.var }
FUNCTION { test.func } { #1 'test.var := }
EXECUTE { test.func }
""");
vm.render(Collections.emptyList());
Map<String, BstFunctions.BstFunction> functions = vm.latestContext.functions();
assertTrue(functions.containsKey("test.func"));
assertNotNull(functions.get("test.func"));
assertEquals(1, vm.latestContext.integers().get("test.var"));
}
@Test
void testSimpleIf() {
BstVM vm = new BstVM("""
FUNCTION { path1 } { #1 }
FUNCTION { path0 } { #0 }
FUNCTION { test } {
#1 path1 path0 if$
#0 path1 path0 if$
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(0, vm.getStack().pop());
assertEquals(1, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
void testSimpleWhile() {
BstVM vm = new BstVM("""
INTEGERS { i }
FUNCTION { test } {
#3 'i :=
{ i }
{
i
i #1 -
'i :=
}
while$
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(1, vm.getStack().pop());
assertEquals(2, vm.getStack().pop());
assertEquals(3, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testNestedControlFunctions() throws RecognitionException {
BstVM vm = new BstVM("""
STRINGS { t }
FUNCTION { not } { { #0 } { #1 } if$ }
FUNCTION { n.dashify } {
"HELLO-WORLD" 't :=
""
{ t empty$ not } % while
{
t #1 #1 substring$ "-" = % if
{
t #1 #2 substring$ "--" = not % if
{
"--" *
t #2 global.max$ substring$ 't :=
}
{
{ t #1 #1 substring$ "-" = } % while
{
"-" *
t #2 global.max$ substring$ 't :=
}
while$
}
if$
}
{
t #1 #1 substring$ *
t #2 global.max$ substring$ 't :=
}
if$
}
while$
}
EXECUTE { n.dashify }
""");
List<BibEntry> v = Collections.emptyList();
vm.render(v);
assertEquals(1, vm.getStack().size());
assertEquals("HELLO--WORLD", vm.getStack().pop());
}
@Test
public void testLogic() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { not } { { #0 } { #1 } if$ }
FUNCTION { and } { 'skip$ { pop$ #0 } if$ }
FUNCTION { or } { { pop$ #1 } 'skip$ if$ }
FUNCTION { test } {
#1 #1 and
#0 #1 and
#1 #0 and
#0 #0 and
#0 not
#1 not
#1 #1 or
#0 #1 or
#1 #0 or
#0 #0 or
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.FALSE, vm.getStack().pop());
assertEquals(BstVM.TRUE, vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
/**
* See also {@link BstWidthCalculatorTest}
*/
@Test
public void testWidth() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { address author title type } { } { label }
STRINGS { longest.label }
INTEGERS { number.label longest.label.width }
FUNCTION { initialize.longest.label } {
"" 'longest.label :=
#1 'number.label :=
#0 'longest.label.width :=
}
FUNCTION {longest.label.pass} {
number.label int.to.str$ 'label :=
number.label #1 + 'number.label :=
label width$ longest.label.width >
{
label 'longest.label :=
label width$ 'longest.label.width :=
}
'skip$
if$
}
EXECUTE { initialize.longest.label }
ITERATE { longest.label.pass }
FUNCTION { begin.bib } {
preamble$ empty$
'skip$
{ preamble$ write$ newline$ }
if$
"\\begin{thebibliography}{" longest.label * "}" *
}
EXECUTE {begin.bib}
""");
List<BibEntry> testEntries = List.of(BstVMTest.defaultTestEntry());
vm.render(testEntries);
assertTrue(vm.latestContext.integers().containsKey("longest.label.width"));
assertEquals("\\begin{thebibliography}{1}", vm.getStack().pop());
}
@Test
public void testDuplicateEmptyPopSwapIf() throws RecognitionException {
BstVM vm = new BstVM("""
FUNCTION { emphasize } {
duplicate$ empty$
{ pop$ "" }
{ "{\\em " swap$ * "}" * }
if$
}
FUNCTION { test } {
"" emphasize
"Hello" emphasize
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals("{\\em Hello}", vm.getStack().pop());
assertEquals("", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
public void testPreambleWriteNewlineQuote() {
BstVM vm = new BstVM("""
FUNCTION { test } {
preamble$
write$
newline$
"hello"
write$
quote$ "quoted" * quote$ *
write$
}
EXECUTE { test }
""");
BibDatabase testDatabase = new BibDatabase();
testDatabase.setPreamble("A Preamble");
String result = vm.render(Collections.emptyList(), testDatabase);
assertEquals("A Preamble\nhello\"quoted\"", result);
}
}
| 24,302 | 35.436282 | 134 | java |
null | jabref-main/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java | package org.jabref.logic.bst;
import java.nio.file.Path;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
class BstPreviewLayoutTest {
private final BibDatabaseContext bibDatabaseContext = new BibDatabaseContext();
@Test
public void generatePreviewForSimpleEntryUsingAbbr() throws Exception {
BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI()));
BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Oliver Kopp")
.withField(StandardField.TITLE, "Thoughts on Development");
BibDatabase bibDatabase = mock(BibDatabase.class);
String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext);
assertEquals("O. Kopp. Thoughts on development.", preview);
}
@Test
public void monthMayIsCorrectlyRendered() throws Exception {
BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI()));
BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Oliver Kopp")
.withField(StandardField.TITLE, "Thoughts on Development")
.withField(StandardField.MONTH, "#May#");
BibDatabase bibDatabase = mock(BibDatabase.class);
String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext);
assertEquals("O. Kopp. Thoughts on development, May.", preview);
}
@Test
public void generatePreviewForSliceTheoremPaperUsingAbbr() throws Exception {
BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI()));
String preview = bstPreviewLayout.generatePreview(getSliceTheoremPaper(), bibDatabaseContext);
assertEquals("T. Diez. Slice theorem for fréchet group actions and covariant symplectic field theory. May 2014.", preview);
}
@Test
public void generatePreviewForSliceTheoremPaperUsingIEEE() throws Exception {
BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(ClassLoader.getSystemResource("bst/IEEEtran.bst").toURI()));
String preview = bstPreviewLayout.generatePreview(getSliceTheoremPaper(), bibDatabaseContext);
assertEquals("T. Diez, \"Slice theorem for fréchet group actions and covariant symplectic field theory\" May 2014.", preview);
}
private static BibEntry getSliceTheoremPaper() {
return new BibEntry(StandardEntryType.Article)
.withField(StandardField.AUTHOR, "Tobias Diez")
.withField(StandardField.TITLE, "Slice theorem for Fréchet group actions and covariant symplectic field theory")
.withField(StandardField.DATE, "2014-05-09")
.withField(StandardField.ABSTRACT, "A general slice theorem for the action of a Fr\\'echet Lie group on a Fr\\'echet manifolds is established. The Nash-Moser theorem provides the fundamental tool to generalize the result of Palais to this infinite-dimensional setting. The presented slice theorem is illustrated by its application to gauge theories: the action of the gauge transformation group admits smooth slices at every point and thus the gauge orbit space is stratified by Fr\\'echet manifolds. Furthermore, a covariant and symplectic formulation of classical field theory is proposed and extensively discussed. At the root of this novel framework is the incorporation of field degrees of freedom F and spacetime M into the product manifold F * M. The induced bigrading of differential forms is used in order to carry over the usual symplectic theory to this new setting. The examples of the Klein-Gordon field and general Yang-Mills theory illustrate that the presented approach conveniently handles the occurring symmetries.")
.withField(StandardField.EPRINT, "1405.2249v1")
.withField(StandardField.FILE, ":http\\://arxiv.org/pdf/1405.2249v1:PDF")
.withField(StandardField.EPRINTTYPE, "arXiv")
.withField(StandardField.EPRINTCLASS, "math-ph")
.withField(StandardField.KEYWORDS, "math-ph, math.DG, math.MP, math.SG, 58B99, 58Z05, 58B25, 22E65, 58D19, 53D20, 53D42");
}
}
| 4,670 | 67.691176 | 1,050 | java |
null | jabref-main/src/test/java/org/jabref/logic/bst/BstVMTest.java | package org.jabref.logic.bst;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.antlr.v4.runtime.RecognitionException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class BstVMTest {
public static BibEntry defaultTestEntry() {
return new BibEntry(StandardEntryType.InProceedings)
.withCitationKey("canh05")
.withField(StandardField.AUTHOR, "Crowston, K. and Annabi, H. and Howison, J. and Masango, C.")
.withField(StandardField.TITLE, "Effective work practices for floss development: A model and propositions")
.withField(StandardField.BOOKTITLE, "Hawaii International Conference On System Sciences (HICSS)")
.withField(StandardField.YEAR, "2005")
.withField(StandardField.OWNER, "oezbek")
.withField(StandardField.TIMESTAMP, "2006.05.29")
.withField(StandardField.URL, "http://james.howison.name/publications.html");
}
@Test
public void testAbbrv() throws RecognitionException, IOException {
BstVM vm = new BstVM(Path.of("src/test/resources/org/jabref/logic/bst/abbrv.bst"));
List<BibEntry> testEntries = List.of(defaultTestEntry());
String expected = "\\begin{thebibliography}{1}\\bibitem{canh05}K.~Crowston, H.~Annabi, J.~Howison, and C.~Masango.\\newblock Effective work practices for floss development: A model and propositions.\\newblock In {\\em Hawaii International Conference On System Sciences (HICSS)}, 2005.\\end{thebibliography}";
String result = vm.render(testEntries);
assertEquals(
expected.replaceAll("\\s", ""),
result.replaceAll("\\s", ""));
}
@Test
public void testSimple() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { address author title type } { } { label }
INTEGERS { output.state before.all mid.sentence after.sentence after.block }
FUNCTION { init.state.consts }{
#0 'before.all :=
#1 'mid.sentence :=
#2 'after.sentence :=
#3 'after.block :=
}
STRINGS { s t }
READ
""");
List<BibEntry> testEntries = List.of(defaultTestEntry());
vm.render(testEntries);
assertEquals(2, vm.latestContext.strings().size());
assertEquals(7, vm.latestContext.integers().size());
assertEquals(1, vm.latestContext.entries().size());
assertEquals(5, vm.latestContext.entries().get(0).fields.size());
assertEquals(38, vm.latestContext.functions().size());
}
@Test
public void testLabel() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { title } {} { label }
FUNCTION { test } {
label #0 =
title 'label :=
#5 label #6 pop$ }
READ
ITERATE { test }
""");
List<BibEntry> testEntries = List.of(defaultTestEntry());
vm.render(testEntries);
assertEquals(
"Effective work practices for floss development: A model and propositions",
vm.latestContext.stack().pop());
}
@Test
public void testQuote() throws RecognitionException {
BstVM vm = new BstVM("FUNCTION { a }{ quote$ quote$ * } EXECUTE { a }");
vm.render(Collections.emptyList());
assertEquals("\"\"", vm.latestContext.stack().pop());
}
@Test
public void testBuildIn() throws RecognitionException {
BstVM vm = new BstVM("EXECUTE { global.max$ }");
vm.render(Collections.emptyList());
assertEquals(Integer.MAX_VALUE, vm.latestContext.stack().pop());
assertTrue(vm.latestContext.stack().empty());
}
@Test
public void testVariables() throws RecognitionException {
BstVM vm = new BstVM("""
STRINGS { t }
FUNCTION { not } {
{ #0 } { #1 } if$
}
FUNCTION { n.dashify } {
"HELLO-WORLD" 't :=
t empty$ not
}
EXECUTE { n.dashify }
""");
vm.render(Collections.emptyList());
assertEquals(BstVM.TRUE, vm.latestContext.stack().pop());
}
@Test
public void testHypthenatedName() throws RecognitionException, IOException {
BstVM vm = new BstVM(Path.of("src/test/resources/org/jabref/logic/bst/abbrv.bst"));
List<BibEntry> testEntries = List.of(
new BibEntry(StandardEntryType.Article)
.withCitationKey("canh05")
.withField(StandardField.AUTHOR, "Jean-Paul Sartre")
);
String result = vm.render(testEntries);
assertTrue(result.contains("J.-P. Sartre"));
}
@Test
void testAbbrevStyleChopWord() {
BstVM vm = new BstVM("""
STRINGS { s }
INTEGERS { len }
FUNCTION { chop.word }
{
's :=
'len :=
s #1 len substring$ =
{ s len #1 + global.max$ substring$ }
's
if$
}
FUNCTION { test } {
"A " #2
"A Colorful Morning"
chop.word
"An " #3
"A Colorful Morning"
chop.word
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals("A Colorful Morning", vm.latestContext.stack().pop());
assertEquals("Colorful Morning", vm.latestContext.stack().pop());
assertEquals(0, vm.latestContext.stack().size());
}
@Test
void testAbbrevStyleSortFormatTitle() {
BstVM vm = new BstVM("""
STRINGS { s t }
INTEGERS { len }
FUNCTION { sortify } {
purify$
"l" change.case$
}
FUNCTION { chop.word }
{
's :=
'len :=
s #1 len substring$ =
{ s len #1 + global.max$ substring$ }
's
if$
}
FUNCTION { sort.format.title }
{ 't :=
"A " #2
"An " #3
"The " #4 t chop.word
chop.word
chop.word
sortify
#1 global.max$ substring$
}
FUNCTION { test } {
"A Colorful Morning"
sort.format.title
}
EXECUTE {test}
""");
vm.render(Collections.emptyList());
assertEquals("colorful morning", vm.latestContext.stack().pop());
}
}
| 7,516 | 33.013575 | 317 | java |
null | jabref-main/src/test/java/org/jabref/logic/bst/BstVMVisitorTest.java | package org.jabref.logic.bst;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.types.StandardEntryType;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BstVMVisitorTest {
@Test
public void testVisitStringsCommand() {
BstVM vm = new BstVM("STRINGS { test.string1 test.string2 test.string3 }");
vm.render(Collections.emptyList());
Map<String, String> strList = vm.latestContext.strings();
assertTrue(strList.containsKey("test.string1"));
assertNull(strList.get("test.string1"));
assertTrue(strList.containsKey("test.string2"));
assertNull(strList.get("test.string2"));
assertTrue(strList.containsKey("test.string3"));
assertNull(strList.get("test.string3"));
}
@Test
public void testVisitIntegersCommand() {
BstVM vm = new BstVM("INTEGERS { variable.a variable.b variable.c }");
vm.render(Collections.emptyList());
Map<String, Integer> integersList = vm.latestContext.integers();
assertTrue(integersList.containsKey("variable.a"));
assertEquals(0, integersList.get("variable.a"));
assertTrue(integersList.containsKey("variable.b"));
assertEquals(0, integersList.get("variable.b"));
assertTrue(integersList.containsKey("variable.c"));
assertEquals(0, integersList.get("variable.c"));
}
@Test
void testVisitFunctionCommand() {
BstVM vm = new BstVM("""
FUNCTION { test.func } { #1 'test.var := }
EXECUTE { test.func }
""");
vm.render(Collections.emptyList());
Map<String, BstFunctions.BstFunction> functions = vm.latestContext.functions();
assertTrue(functions.containsKey("test.func"));
assertNotNull(functions.get("test.func"));
}
@Test
void testVisitMacroCommand() {
BstVM vm = new BstVM("""
MACRO { jan } { "January" }
EXECUTE { jan }
""");
vm.render(Collections.emptyList());
Map<String, BstFunctions.BstFunction> functions = vm.latestContext.functions();
assertTrue(functions.containsKey("jan"));
assertNotNull(functions.get("jan"));
assertEquals("January", vm.latestContext.stack().pop());
assertTrue(vm.latestContext.stack().isEmpty());
}
@Test
void testVisitEntryCommand() {
BstVM vm = new BstVM("ENTRY { address author title type } { variable } { label }");
List<BibEntry> testEntries = List.of(BstVMTest.defaultTestEntry());
vm.render(testEntries);
BstEntry bstEntry = vm.latestContext.entries().get(0);
assertTrue(bstEntry.fields.containsKey("address"));
assertTrue(bstEntry.fields.containsKey("author"));
assertTrue(bstEntry.fields.containsKey("title"));
assertTrue(bstEntry.fields.containsKey("type"));
assertTrue(bstEntry.localIntegers.containsKey("variable"));
assertTrue(bstEntry.localStrings.containsKey("label"));
assertTrue(bstEntry.localStrings.containsKey("sort.key$"));
}
@Test
void testVisitReadCommand() {
BstVM vm = new BstVM("""
ENTRY { author title booktitle year owner timestamp url } { } { }
READ
""");
List<BibEntry> testEntries = List.of(BstVMTest.defaultTestEntry());
vm.render(testEntries);
Map<String, String> fields = vm.latestContext.entries().get(0).fields;
assertEquals("Crowston, K. and Annabi, H. and Howison, J. and Masango, C.", fields.get("author"));
assertEquals("Effective work practices for floss development: A model and propositions", fields.get("title"));
assertEquals("Hawaii International Conference On System Sciences (HICSS)", fields.get("booktitle"));
assertEquals("2005", fields.get("year"));
assertEquals("oezbek", fields.get("owner"));
assertEquals("2006.05.29", fields.get("timestamp"));
assertEquals("http://james.howison.name/publications.html", fields.get("url"));
}
@Test
public void testVisitExecuteCommand() throws RecognitionException {
BstVM vm = new BstVM("""
INTEGERS { variable.a }
FUNCTION { init.state.consts } { #5 'variable.a := }
EXECUTE { init.state.consts }
""");
vm.render(Collections.emptyList());
assertEquals(5, vm.latestContext.integers().get("variable.a"));
}
@Test
public void testVisitIterateCommand() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { } { } { }
FUNCTION { test } { cite$ }
READ
ITERATE { test }
""");
List<BibEntry> testEntries = List.of(
BstVMTest.defaultTestEntry(),
new BibEntry(StandardEntryType.Article)
.withCitationKey("test"));
vm.render(testEntries);
assertEquals(2, vm.getStack().size());
assertEquals("test", vm.getStack().pop());
assertEquals("canh05", vm.getStack().pop());
}
@Test
public void testVisitReverseCommand() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { } { } { }
FUNCTION { test } { cite$ }
READ
REVERSE { test }
""");
List<BibEntry> testEntries = List.of(
BstVMTest.defaultTestEntry(),
new BibEntry(StandardEntryType.Article)
.withCitationKey("test"));
vm.render(testEntries);
assertEquals(2, vm.getStack().size());
assertEquals("canh05", vm.getStack().pop());
assertEquals("test", vm.getStack().pop());
}
@Test
public void testVisitSortCommand() throws RecognitionException {
BstVM vm = new BstVM("""
ENTRY { } { } { }
FUNCTION { presort } { cite$ 'sort.key$ := }
ITERATE { presort }
SORT
""");
List<BibEntry> testEntries = List.of(
new BibEntry(StandardEntryType.Article).withCitationKey("c"),
new BibEntry(StandardEntryType.Article).withCitationKey("b"),
new BibEntry(StandardEntryType.Article).withCitationKey("d"),
new BibEntry(StandardEntryType.Article).withCitationKey("a"));
vm.render(testEntries);
List<BstEntry> sortedEntries = vm.latestContext.entries();
assertEquals(Optional.of("a"), sortedEntries.get(0).entry.getCitationKey());
assertEquals(Optional.of("b"), sortedEntries.get(1).entry.getCitationKey());
assertEquals(Optional.of("c"), sortedEntries.get(2).entry.getCitationKey());
assertEquals(Optional.of("d"), sortedEntries.get(3).entry.getCitationKey());
}
@Test
void testVisitIdentifier() {
BstVM vm = new BstVM("""
ENTRY { } { local.variable } { local.label }
READ
STRINGS { label }
INTEGERS { variable }
FUNCTION { test } {
#1 'local.variable :=
#2 'variable :=
"TEST" 'local.label :=
"TEST-GLOBAL" 'label :=
local.label local.variable
label variable
}
ITERATE { test }
""");
List<BibEntry> testEntries = List.of(BstVMTest.defaultTestEntry());
vm.render(testEntries);
assertEquals(2, vm.getStack().pop());
assertEquals("TEST-GLOBAL", vm.getStack().pop());
assertEquals(1, vm.getStack().pop());
assertEquals("TEST", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
@Test
void testVisitStackitem() {
BstVM vm = new BstVM("""
STRINGS { t }
FUNCTION { test2 } { #3 }
FUNCTION { test } {
"HELLO"
#1
't
{ #2 }
test2
}
EXECUTE { test }
""");
vm.render(Collections.emptyList());
assertEquals(3, vm.getStack().pop());
assertTrue(vm.getStack().pop() instanceof ParseTree);
assertEquals(new BstVMVisitor.Identifier("t"), vm.getStack().pop());
assertEquals(1, vm.getStack().pop());
assertEquals("HELLO", vm.getStack().pop());
assertEquals(0, vm.getStack().size());
}
// stackitem
}
| 9,097 | 35.392 | 118 | java |
null | jabref-main/src/test/java/org/jabref/logic/bst/util/BstCaseChangersTest.java | package org.jabref.logic.bst.util;
import java.util.stream.Stream;
import org.jabref.logic.bst.util.BstCaseChanger.FormatMode;
import org.junit.jupiter.api.Disabled;
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 BstCaseChangersTest {
@ParameterizedTest
@MethodSource("provideStringsForTitleLowers")
public void testChangeCaseTitleLowers(String expected, String toBeFormatted) {
assertEquals(expected, BstCaseChanger.changeCase(toBeFormatted, FormatMode.TITLE_LOWERS));
}
private static Stream<Arguments> provideStringsForTitleLowers() {
return Stream.of(
Arguments.of("i", "i"),
Arguments.of("0i~ ", "0I~ "),
Arguments.of("Hi hi ", "Hi Hi "),
Arguments.of("{\\oe}", "{\\oe}"),
Arguments.of("Hi {\\oe }hi ", "Hi {\\oe }Hi "),
Arguments.of("Jonathan meyer and charles louis xavier joseph de la vall{\\'e}e poussin", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin"),
Arguments.of("{\\'{E}}douard masterly", "{\\'{E}}douard Masterly"),
Arguments.of("Ulrich {\\\"{u}}nderwood and ned {\\~n}et and paul {\\={p}}ot", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot"),
Arguments.of("An {$O(n \\log n / \\! \\log\\log n)$} sorting algorithm", "An {$O(n \\log n / \\! \\log\\log n)$} Sorting Algorithm"),
Arguments.of("On notions of information transfer in {VLSI} circuits", "On Notions of Information Transfer in {VLSI} Circuits"),
Arguments.of("hallo", "hallo"),
Arguments.of("Hallo", "HAllo"),
Arguments.of("Hallo world", "HAllo World"),
Arguments.of("Hallo world. how", "HAllo WORLD. HOW"),
Arguments.of("Hallo {WORLD}. how", "HAllo {WORLD}. HOW"),
Arguments.of("Hallo {\\world}. how", "HAllo {\\WORLD}. HOW"),
// testSpecialCharacters
Arguments.of("Hallo world: How", "HAllo WORLD: HOW"),
Arguments.of("Hallo world! how", "HAllo WORLD! HOW"),
Arguments.of("Hallo world? how", "HAllo WORLD? HOW"),
Arguments.of("Hallo world. how", "HAllo WORLD. HOW"),
Arguments.of("Hallo world, how", "HAllo WORLD, HOW"),
Arguments.of("Hallo world; how", "HAllo WORLD; HOW"),
Arguments.of("Hallo world- how", "HAllo WORLD- HOW"),
// testSpecialBracketPlacement
Arguments.of("this i{S REALLY CraZy ST}uff", "tHIS I{S REALLY CraZy ST}UfF"),
Arguments.of("this i{S R{\\'E}ALLY CraZy ST}uff", "tHIS I{S R{\\'E}ALLY CraZy ST}UfF"),
Arguments.of("this is r{\\'e}ally crazy stuff", "tHIS IS R{\\'E}ALLY CraZy STUfF")
);
}
@ParameterizedTest
@MethodSource("provideStringsForAllLowers")
public void testChangeCaseAllLowers(String expected, String toBeFormatted) {
assertEquals(expected, BstCaseChanger.changeCase(toBeFormatted, FormatMode.ALL_LOWERS));
}
private static Stream<Arguments> provideStringsForAllLowers() {
return Stream.of(
Arguments.of("i", "i"),
Arguments.of("0i~ ", "0I~ "),
Arguments.of("hi hi ", "Hi Hi "),
Arguments.of("{\\oe}", "{\\oe}"),
Arguments.of("hi {\\oe }hi ", "Hi {\\oe }Hi "),
Arguments.of("jonathan meyer and charles louis xavier joseph de la vall{\\'e}e poussin", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin"),
Arguments.of("{\\'e}", "{\\'e}"),
Arguments.of("{\\'{e}}douard masterly", "{\\'{E}}douard Masterly"),
Arguments.of("ulrich {\\\"{u}}nderwood and ned {\\~n}et and paul {\\={p}}ot", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot"),
Arguments.of("an {$O(n \\log n / \\! \\log\\log n)$} sorting algorithm", "An {$O(n \\log n / \\! \\log\\log n)$} Sorting Algorithm"),
Arguments.of("hallo", "hallo"),
Arguments.of("hallo", "HAllo"),
Arguments.of("hallo world", "HAllo World"),
Arguments.of("hallo world. how", "HAllo WORLD. HOW"),
Arguments.of("hallo {worLD}. how", "HAllo {worLD}. HOW"),
Arguments.of("hallo {\\world}. how", "HAllo {\\WORLD}. HOW"),
// testSpecialBracketPlacement
Arguments.of("an {$O(n \\log n)$} sorting algorithm", "An {$O(n \\log n)$} Sorting Algorithm")
);
}
@ParameterizedTest
@MethodSource("provideStringsForAllUppers")
public void testChangeCaseAllUppers(String expected, String toBeFormatted) {
assertEquals(expected, BstCaseChanger.changeCase(toBeFormatted, FormatMode.ALL_UPPERS));
}
private static Stream<Arguments> provideStringsForAllUppers() {
return Stream.of(
Arguments.of("I", "i"),
Arguments.of("0I~ ", "0I~ "),
Arguments.of("HI HI ", "Hi Hi "),
Arguments.of("{\\OE}", "{\\oe}"),
Arguments.of("HI {\\OE }HI ", "Hi {\\oe }Hi "),
Arguments.of("JONATHAN MEYER AND CHARLES LOUIS XAVIER JOSEPH DE LA VALL{\\'E}E POUSSIN", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin"),
Arguments.of("{\\'E}", "{\\'e}"),
Arguments.of("{\\'{E}}DOUARD MASTERLY", "{\\'{E}}douard Masterly"),
Arguments.of("ULRICH {\\\"{U}}NDERWOOD AND NED {\\~N}ET AND PAUL {\\={P}}OT", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot"),
Arguments.of("AN {$O(n \\log n / \\! \\log\\log n)$} SORTING ALGORITHM", "An {$O(n \\log n / \\! \\log\\log n)$} Sorting Algorithm"),
Arguments.of("HALLO", "hallo"),
Arguments.of("HALLO", "HAllo"),
Arguments.of("HALLO WORLD", "HAllo World"),
Arguments.of("HALLO WORLD. HOW", "HAllo World. How"),
Arguments.of("HALLO {worLD}. HOW", "HAllo {worLD}. how"),
Arguments.of("HALLO {\\WORLD}. HOW", "HAllo {\\woRld}. hoW"),
// testSpecialBracketPlacement
Arguments.of("AN {$O(n \\log n)$} SORTING ALGORITHM", "An {$O(n \\log n)$} Sorting Algorithm")
);
}
@ParameterizedTest
@MethodSource("provideTitleCaseAllLowers")
public void testTitleCaseAllLowers(String expected, String toBeFormatted) {
assertEquals(expected, BstCaseChanger.changeCase(toBeFormatted, FormatMode.ALL_LOWERS));
}
private static Stream<Arguments> provideTitleCaseAllLowers() {
return Stream.of(
// CaseChangers.TITLE is good at keeping some words lower case
// Here some modified test cases to show that escaping with BibtexCaseChanger also works
// Examples taken from https://github.com/JabRef/jabref/pull/176#issuecomment-142723792
Arguments.of("this is a simple example {TITLE}", "This is a simple example {TITLE}"),
Arguments.of("this {IS} another simple example tit{LE}", "This {IS} another simple example tit{LE}"),
Arguments.of("{What ABOUT thIS} one?", "{What ABOUT thIS} one?"),
Arguments.of("{And {thIS} might {a{lso}} be possible}", "{And {thIS} might {a{lso}} be possible}")
);
}
@Disabled
@Test
public void testTitleCaseAllUppers() {
/* the real test would look like as follows. Also from the comment of issue 176, order reversed as the "should be" comes first */
// assertCaseChangerTitleUppers("This is a Simple Example {TITLE}", "This is a simple example {TITLE}");
// assertCaseChangerTitleUppers("This {IS} Another Simple Example Tit{LE}", "This {IS} another simple example tit{LE}");
// assertCaseChangerTitleUppers("{What ABOUT thIS} one?", "{What ABOUT thIS} one?");
// assertCaseChangerTitleUppers("{And {thIS} might {a{lso}} be possible}", "{And {thIS} might {a{lso}} be possible}")
}
}
| 8,383 | 55.268456 | 181 | java |
null | jabref-main/src/test/java/org/jabref/logic/bst/util/BstNameFormatterTest.java | package org.jabref.logic.bst.util;
import org.jabref.model.entry.AuthorList;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BstNameFormatterTest {
@Test
public void testUmlautsFullNames() {
AuthorList list = AuthorList.parse("Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin");
assertEquals("de~laVall{\\'e}e~PoussinCharles Louis Xavier~Joseph",
BstNameFormatter.formatName(list.getAuthor(0), "{vv}{ll}{jj}{ff}"));
}
@Test
public void testUmlautsAbbreviations() {
AuthorList list = AuthorList.parse("Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin");
assertEquals("de~la Vall{\\'e}e~Poussin, C.~L. X.~J.",
BstNameFormatter.formatName(list.getAuthor(0), "{vv~}{ll}{, jj}{, f.}"));
}
@Test
public void testUmlautsAbbreviationsWithQuestionMark() {
AuthorList list = AuthorList.parse("Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin");
assertEquals("de~la Vall{\\'e}e~Poussin, C.~L. X.~J?",
BstNameFormatter.formatName(list.getAuthor(0), "{vv~}{ll}{, jj}{, f}?"));
}
@Test
public void testFormatName() {
AuthorList list = AuthorList.parse("Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin");
assertEquals("dlVP", BstNameFormatter.formatName(list.getAuthor(0), "{v{}}{l{}}"));
assertNameFormatA("Meyer, J?", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin");
assertNameFormatB("J.~Meyer", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin");
assertNameFormatC("Jonathan Meyer", "Jonathan Meyer and Charles Louis Xavier Joseph de la Vall{\\'e}e Poussin");
assertNameFormatA("Masterly, {\\'{E}}?", "{\\'{E}}douard Masterly");
assertNameFormatB("{\\'{E}}.~Masterly", "{\\'{E}}douard Masterly");
assertNameFormatC("{\\'{E}}douard Masterly", "{\\'{E}}douard Masterly");
assertNameFormatA("{\\\"{U}}nderwood, U?", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot");
assertNameFormatB("U.~{\\\"{U}}nderwood", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot");
assertNameFormatC("Ulrich {\\\"{U}}nderwood", "Ulrich {\\\"{U}}nderwood and Ned {\\~N}et and Paul {\\={P}}ot");
assertNameFormatA("Victor, P.~{\\'E}?", "Paul {\\'E}mile Victor and and de la Cierva y Codorn{\\’\\i}u, Juan");
assertNameFormatB("P.~{\\'E}. Victor", "Paul {\\'E}mile Victor and and de la Cierva y Codorn{\\’\\i}u, Juan");
assertNameFormatC("Paul~{\\'E}mile Victor",
"Paul {\\'E}mile Victor and and de la Cierva y Codorn{\\’\\i}u, Juan");
}
private void assertNameFormat(String string, String string2, int which, String format) {
assertEquals(string, BstNameFormatter.formatName(string2, which, format));
}
private void assertNameFormatC(String string, String string2) {
assertNameFormat(string, string2, 1, "{ff }{vv }{ll}{ jj}");
}
private void assertNameFormatB(String string, String string2) {
assertNameFormat(string, string2, 1, "{f.~}{vv~}{ll}{, jj}");
}
private void assertNameFormatA(String string, String string2) {
assertNameFormat(string, string2, 1, "{vv~}{ll}{, jj}{, f}?");
}
@Test
public void matchingBraceConsumedForCompleteWords() {
StringBuilder sb = new StringBuilder();
assertEquals(6, BstNameFormatter.consumeToMatchingBrace(sb, "{HELLO} {WORLD}".toCharArray(), 0));
assertEquals("{HELLO}", sb.toString());
}
@Test
public void matchingBraceConsumedForBracesInWords() {
StringBuilder sb = new StringBuilder();
assertEquals(18, BstNameFormatter.consumeToMatchingBrace(sb, "{HE{L{}L}O} {WORLD}".toCharArray(), 12));
assertEquals("{WORLD}", sb.toString());
}
@Test
public void testConsumeToMatchingBrace() {
StringBuilder sb = new StringBuilder();
assertEquals(10, BstNameFormatter.consumeToMatchingBrace(sb, "{HE{L{}L}O} {WORLD}".toCharArray(), 0));
assertEquals("{HE{L{}L}O}", sb.toString());
}
@Test
public void testGetFirstCharOfString() {
assertEquals("C", BstNameFormatter.getFirstCharOfString("Charles"));
assertEquals("V", BstNameFormatter.getFirstCharOfString("Vall{\\'e}e"));
assertEquals("{\\'e}", BstNameFormatter.getFirstCharOfString("{\\'e}"));
assertEquals("{\\'e", BstNameFormatter.getFirstCharOfString("{\\'e"));
assertEquals("E", BstNameFormatter.getFirstCharOfString("{E"));
}
@Test
public void testNumberOfChars() {
assertEquals(6, BstNameFormatter.numberOfChars("Vall{\\'e}e", -1));
assertEquals(2, BstNameFormatter.numberOfChars("Vall{\\'e}e", 2));
assertEquals(1, BstNameFormatter.numberOfChars("Vall{\\'e}e", 1));
assertEquals(6, BstNameFormatter.numberOfChars("Vall{\\'e}e", 6));
assertEquals(6, BstNameFormatter.numberOfChars("Vall{\\'e}e", 7));
assertEquals(8, BstNameFormatter.numberOfChars("Vall{e}e", -1));
assertEquals(6, BstNameFormatter.numberOfChars("Vall{\\'e this will be skipped}e", -1));
}
}
| 5,257 | 45.530973 | 120 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.