diff --git a/src/main/java/org/jabref/Globals.java b/src/main/java/org/jabref/Globals.java index f3e40b17609..f45b08b3df7 100644 --- a/src/main/java/org/jabref/Globals.java +++ b/src/main/java/org/jabref/Globals.java @@ -6,7 +6,7 @@ import org.jabref.collab.FileUpdateMonitor; import org.jabref.gui.GlobalFocusListener; import org.jabref.gui.StateManager; -import org.jabref.gui.keyboard.KeyBindingPreferences; +import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.importer.ImportFormatReader; @@ -48,7 +48,7 @@ public class Globals { */ public static StateManager stateManager = new StateManager(); // Key binding preferences - private static KeyBindingPreferences keyPrefs; + private static KeyBindingRepository keyBindingRepository; // Background tasks private static GlobalFocusListener focusListener; private static FileUpdateMonitor fileUpdateMonitor; @@ -58,11 +58,11 @@ private Globals() { } // Key binding preferences - public static KeyBindingPreferences getKeyPrefs() { - if (keyPrefs == null) { - keyPrefs = new KeyBindingPreferences(prefs); + public static KeyBindingRepository getKeyPrefs() { + if (keyBindingRepository == null) { + keyBindingRepository = prefs.getKeyBindingRepository(); } - return keyPrefs; + return keyBindingRepository; } diff --git a/src/main/java/org/jabref/gui/DefaultInjector.java b/src/main/java/org/jabref/gui/DefaultInjector.java index bb90b263c39..c4239c9ef8f 100644 --- a/src/main/java/org/jabref/gui/DefaultInjector.java +++ b/src/main/java/org/jabref/gui/DefaultInjector.java @@ -3,8 +3,9 @@ import java.util.function.Function; import org.jabref.Globals; -import org.jabref.gui.keyboard.KeyBindingPreferences; +import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.util.TaskExecutor; +import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.preferences.JabRefPreferences; import com.airhacks.afterburner.injection.Injector; @@ -28,8 +29,10 @@ private static Object createDependency(Class clazz) { return Globals.taskExecutor; } else if (clazz == JabRefPreferences.class) { return Globals.prefs; - } else if (clazz == KeyBindingPreferences.class) { + } else if (clazz == KeyBindingRepository.class) { return Globals.getKeyPrefs(); + } else if (clazz == JournalAbbreviationLoader.class) { + return Globals.journalAbbreviationLoader; } else if (clazz == StateManager.class) { return Globals.stateManager; } else { diff --git a/src/main/java/org/jabref/gui/FXDialog.java b/src/main/java/org/jabref/gui/FXDialog.java index cd0da6592fd..d59ccaecda4 100644 --- a/src/main/java/org/jabref/gui/FXDialog.java +++ b/src/main/java/org/jabref/gui/FXDialog.java @@ -16,7 +16,7 @@ import org.jabref.Globals; import org.jabref.JabRefGUI; import org.jabref.gui.keyboard.KeyBinding; -import org.jabref.gui.keyboard.KeyBindingPreferences; +import org.jabref.gui.keyboard.KeyBindingRepository; /** * This class provides a super class for all dialogs implemented in JavaFX. @@ -101,9 +101,9 @@ public FXDialog(AlertType type, boolean isModal) { dialogWindow.setOnCloseRequest(evt -> this.close()); - dialogWindow.getScene().setOnKeyPressed(evt -> { - KeyBindingPreferences keyPreferences = Globals.getKeyPrefs(); - if (keyPreferences.checkKeyCombinationEquality(KeyBinding.CLOSE_DIALOG, evt)) { + dialogWindow.getScene().setOnKeyPressed(event -> { + KeyBindingRepository keyBindingRepository = Globals.getKeyPrefs(); + if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLOSE_DIALOG, event)) { dialogWindow.close(); } }); diff --git a/src/main/java/org/jabref/gui/errorconsole/ErrorConsoleController.java b/src/main/java/org/jabref/gui/errorconsole/ErrorConsoleController.java index 0f7f8e601d3..641cec00f88 100644 --- a/src/main/java/org/jabref/gui/errorconsole/ErrorConsoleController.java +++ b/src/main/java/org/jabref/gui/errorconsole/ErrorConsoleController.java @@ -22,7 +22,7 @@ import org.jabref.gui.DialogService; import org.jabref.gui.IconTheme; import org.jabref.gui.keyboard.KeyBinding; -import org.jabref.gui.keyboard.KeyBindingPreferences; +import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.logic.util.BuildInfo; public class ErrorConsoleController extends AbstractController { @@ -36,7 +36,7 @@ public class ErrorConsoleController extends AbstractController selectedEntries = messagesListView.getSelectionModel().getSelectedItems(); viewModel.copyLog(selectedEntries); } diff --git a/src/main/java/org/jabref/gui/importer/fetcher/IEEEXploreFetcher.java b/src/main/java/org/jabref/gui/importer/fetcher/IEEEXploreFetcher.java index cb3aa4c84e9..623a7eff224 100644 --- a/src/main/java/org/jabref/gui/importer/fetcher/IEEEXploreFetcher.java +++ b/src/main/java/org/jabref/gui/importer/fetcher/IEEEXploreFetcher.java @@ -29,6 +29,7 @@ import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.journals.JournalAbbreviationLoader; +import org.jabref.logic.journals.JournalAbbreviationPreferences; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.URLDownload; import org.jabref.model.entry.BibEntry; @@ -67,9 +68,8 @@ public class IEEEXploreFetcher implements EntryFetcher { private final UnitsToLatexFormatter unitsToLatexFormatter = new UnitsToLatexFormatter(); private final HtmlToLatexFormatter htmlToLatexFormatter = new HtmlToLatexFormatter(); private final JCheckBox absCheckBox = new JCheckBox(Localization.lang("Include abstracts"), false); - - private boolean shouldContinue; private final JournalAbbreviationLoader abbreviationLoader; + private boolean shouldContinue; public IEEEXploreFetcher(JournalAbbreviationLoader abbreviationLoader) { @@ -406,9 +406,10 @@ private BibEntry cleanup(BibEntry entry) { fullName = fullName.replace(" - ", "-"); //IEE Proceedings- fullName = fullName.trim(); - if (Globals.prefs.getBoolean(JabRefPreferences.USE_IEEE_ABRV)) { + JournalAbbreviationPreferences journalAbbreviationPreferences = Globals.prefs.getJournalAbbreviationPreferences(); + if (journalAbbreviationPreferences.useIEEEAbbreviations()) { fullName = abbreviationLoader - .getRepository(Globals.prefs.getJournalAbbreviationPreferences()) + .getRepository(journalAbbreviationPreferences) .getMedlineAbbreviation(fullName) .orElse(fullName); } diff --git a/src/main/java/org/jabref/gui/journals/ManageJournalAbbreviationsController.java b/src/main/java/org/jabref/gui/journals/ManageJournalAbbreviationsController.java index ff8ade44058..cb71a21f0c9 100644 --- a/src/main/java/org/jabref/gui/journals/ManageJournalAbbreviationsController.java +++ b/src/main/java/org/jabref/gui/journals/ManageJournalAbbreviationsController.java @@ -20,10 +20,13 @@ import org.jabref.gui.IconTheme; import org.jabref.gui.util.TaskExecutor; import org.jabref.gui.util.ValueTableCellFactory; -import org.jabref.preferences.JabRefPreferences; +import org.jabref.logic.journals.JournalAbbreviationLoader; +import org.jabref.preferences.PreferencesService; public class ManageJournalAbbreviationsController extends AbstractController { + @FXML public Label loadingLabel; + @FXML public ProgressIndicator progressIndicator; @FXML private TableView journalAbbreviationsTable; @FXML private TableColumn journalTableNameColumn; @FXML private TableColumn journalTableAbbreviationColumn; @@ -34,17 +37,14 @@ public class ManageJournalAbbreviationsController extends AbstractController { @@ -124,7 +126,7 @@ void addBuiltInLists() { BackgroundTask .wrap(() -> { - if (preferences.getBoolean(JabRefPreferences.USE_IEEE_ABRV)) { + if (abbreviationsPreferences.useIEEEAbbreviations()) { return JournalAbbreviationLoader.getOfficialIEEEAbbreviations(); } else { return JournalAbbreviationLoader.getStandardIEEEAbbreviations(); @@ -150,7 +152,7 @@ private void addList(String name, List abbreviations) { * Read all saved file paths and read their abbreviations */ public void createFileObjects() { - List externalFiles = preferences.getStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS); + List externalFiles = abbreviationsPreferences.getExternalJournalLists(); externalFiles.forEach(name -> openFile(Paths.get(name))); } @@ -316,14 +318,14 @@ public void saveJournalAbbreviationFiles() { * This method stores all file paths of the files in the journalFiles property * to the global JabRef preferences. Pseudo abbreviation files will not be stored. */ - public void saveExternalFilesList() { + private void saveExternalFilesList() { List extFiles = new ArrayList<>(); journalFiles.forEach(file -> { if (!file.isBuiltInListProperty().get()) { file.getAbsolutePath().ifPresent(path -> extFiles.add(path.toAbsolutePath().toString())); } }); - preferences.putStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS, extFiles); + abbreviationsPreferences.setExternalJournalLists(extFiles); } /** @@ -346,8 +348,11 @@ public void selectLastJournalFile() { public void saveEverythingAndUpdateAutoCompleter() { saveExternalFilesList(); saveJournalAbbreviationFiles(); + // Update journal abbreviation loader - journalAbbreviationLoader.update(JournalAbbreviationPreferences.fromPreferences(preferences)); + journalAbbreviationLoader.update(abbreviationsPreferences); + + preferences.storeJournalAbbreviationPreferences(abbreviationsPreferences); } public SimpleListProperty journalFilesProperty() { diff --git a/src/main/java/org/jabref/gui/keyboard/KeyBindingPreferences.java b/src/main/java/org/jabref/gui/keyboard/KeyBindingPreferences.java deleted file mode 100644 index 38b29d9e011..00000000000 --- a/src/main/java/org/jabref/gui/keyboard/KeyBindingPreferences.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.jabref.gui.keyboard; - -import java.awt.AWTError; -import java.awt.HeadlessException; -import java.awt.Toolkit; -import java.awt.event.InputEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.SortedMap; -import java.util.stream.Collectors; - -import javax.swing.KeyStroke; - -import javafx.scene.input.KeyCode; -import javafx.scene.input.KeyCombination; -import javafx.scene.input.KeyEvent; - -import org.jabref.logic.util.OS; -import org.jabref.preferences.JabRefPreferences; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class KeyBindingPreferences { - - private static final Log LOGGER = LogFactory.getLog(KeyBindingPreferences.class); - - private int shortcutMask = -1; - - private final JabRefPreferences prefs; - - private KeyBindingRepository keyBindingRepository = new KeyBindingRepository(); - - - public KeyBindingPreferences(JabRefPreferences prefs) { - this.prefs = Objects.requireNonNull(prefs); - restoreKeyBindings(); - } - - /** - * Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences. - */ - public KeyStroke getKey(KeyBinding bindName) { - - String s = keyBindingRepository.get(bindName.getKey()); - - if (OS.OS_X) { - return getKeyForMac(KeyStroke.getKeyStroke(s)); - } else { - return KeyStroke.getKeyStroke(s); - } - } - - public KeyCombination getKeyCombination(KeyBinding bindName) { - String binding = keyBindingRepository.get(bindName.getKey()); - return KeyCombination.valueOf(binding); - } - - /** - * Check if the given keyCombination equals the given keyEvent - * - * @param combination as KeyCombination - * @param keyEvent as KeEvent - * @return true if matching, else false - */ - public boolean checkKeyCombinationEquality(KeyCombination combination, KeyEvent keyEvent) { - KeyCode code = keyEvent.getCode(); - if (code == KeyCode.UNDEFINED) { - return false; - } - // gather the pressed modifier keys - String modifiers = ""; - if (keyEvent.isControlDown()) { - modifiers = "ctrl"; - } - if (keyEvent.isShiftDown()) { - modifiers += " shift"; - } - if (keyEvent.isAltDown()) { - modifiers += " alt"; - } - modifiers = modifiers.trim(); - String newShortcut = (modifiers.isEmpty()) ? code.toString() : modifiers + " " + code; - KeyCombination pressedCombination = KeyCombination.valueOf(newShortcut); - return combination.equals(pressedCombination); - } - - /** - * Check if the given KeyBinding equals the given keyEvent - * - * @param binding as KeyBinding - * @param keyEvent as KeEvent - * @return true if matching, else false - */ - public boolean checkKeyCombinationEquality(KeyBinding binding, KeyEvent keyEvent) { - KeyCombination keyCombination = getKeyCombination(binding); - return checkKeyCombinationEquality(keyCombination, keyEvent); - } - - /** - * Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences, but adapted for Mac - * users, with the Command key preferred instead of Control. - * TODO: Move to OS.java? Or replace with portable Java key codes, i.e. KeyEvent - */ - private KeyStroke getKeyForMac(KeyStroke ks) { - if (ks == null) { - return null; - } - int keyCode = ks.getKeyCode(); - if ((ks.getModifiers() & InputEvent.CTRL_MASK) == 0) { - return ks; - } else { - int modifiers = 0; - if ((ks.getModifiers() & InputEvent.SHIFT_MASK) != 0) { - modifiers = modifiers | InputEvent.SHIFT_MASK; - } - if ((ks.getModifiers() & InputEvent.ALT_MASK) != 0) { - modifiers = modifiers | InputEvent.ALT_MASK; - } - - if (shortcutMask == -1) { - try { - shortcutMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); - } catch (AWTError | HeadlessException e) { - LOGGER.warn("Problem geting shortcut mask", e); - } - } - - return KeyStroke.getKeyStroke(keyCode, shortcutMask + modifiers); - } - } - - /** - * Stores new key bindings into Preferences, provided they actually differ from the old ones. - */ - public void setNewKeyBindings(SortedMap newBindings) { - if (!newBindings.equals(keyBindingRepository.getKeyBindings())) { - // This confirms that the bindings have actually changed. - List bindNames = newBindings.keySet().stream().map(KeyBinding::getKey).collect(Collectors.toList()); - List bindings = new ArrayList<>(newBindings.values()); - prefs.putStringList(JabRefPreferences.BIND_NAMES, bindNames); - prefs.putStringList(JabRefPreferences.BINDINGS, bindings); - keyBindingRepository.overwriteBindings(newBindings); - } - } - - private void restoreKeyBindings() { - // First read the bindings, and their names. - List bindNames = prefs.getStringList(JabRefPreferences.BIND_NAMES); - List bindings = prefs.getStringList(JabRefPreferences.BINDINGS); - - // Then set up the key bindings HashMap. - if ((bindNames.isEmpty()) || (bindings.isEmpty()) || (bindNames.size() != bindings.size())) { - // Nothing defined in Preferences, or something is wrong. - keyBindingRepository = new KeyBindingRepository(); - return; - } - - for (int i = 0; i < bindNames.size(); i++) { - keyBindingRepository.put(bindNames.get(i), bindings.get(i)); - } - } - - - /** - * Returns the HashMap containing all key bindings. - */ - public SortedMap getKeyBindings() { - return keyBindingRepository.getKeyBindings(); - } -} diff --git a/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java b/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java index 3a830150008..7c23c772c6c 100644 --- a/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java +++ b/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java @@ -1,26 +1,56 @@ package org.jabref.gui.keyboard; +import java.awt.AWTError; +import java.awt.HeadlessException; +import java.awt.Toolkit; +import java.awt.event.InputEvent; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import java.util.Optional; import java.util.SortedMap; import java.util.TreeMap; +import java.util.stream.Collectors; + +import javax.swing.KeyStroke; + +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyCombination; +import javafx.scene.input.KeyEvent; + +import org.jabref.logic.util.OS; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; public class KeyBindingRepository { + private static final Log LOGGER = LogFactory.getLog(KeyBindingRepository.class); /** * sorted by localization */ private final SortedMap bindings; + private int shortcutMask = -1; public KeyBindingRepository() { - bindings = new TreeMap<>((k1, k2) -> k1.getLocalization().compareTo(k2.getLocalization())); - for (KeyBinding keyBinding : KeyBinding.values()) { - bindings.put(keyBinding, keyBinding.getDefaultBinding()); - } + this(Collections.emptyList(), Collections.emptyList()); } - public KeyBindingRepository(SortedMap bindings) { - this.bindings = bindings; + public KeyBindingRepository(List bindNames, List bindings) { + this.bindings = new TreeMap<>(Comparator.comparing(KeyBinding::getLocalization)); + + if ((bindNames.isEmpty()) || (bindings.isEmpty()) || (bindNames.size() != bindings.size())) { + // Use default key bindings + for (KeyBinding keyBinding : KeyBinding.values()) { + put(keyBinding, keyBinding.getDefaultBinding()); + } + } else { + for (int i = 0; i < bindNames.size(); i++) { + put(bindNames.get(i), bindings.get(i)); + } + } } public Optional get(KeyBinding key) { @@ -29,26 +59,24 @@ public Optional get(KeyBinding key) { public String get(String key) { Optional keyBinding = getKeyBinding(key); - Optional result = keyBinding.flatMap(k -> Optional.ofNullable(bindings.get(k))); + Optional result = keyBinding.flatMap(k -> Optional.ofNullable(bindings.get(k))); - if(result.isPresent()) { + if (result.isPresent()) { return result.get(); - } else if(keyBinding.isPresent()){ + } else if (keyBinding.isPresent()) { return keyBinding.get().getDefaultBinding(); } else { return "Not associated"; } } + /** + * Returns the HashMap containing all key bindings. + */ public SortedMap getKeyBindings() { return new TreeMap<>(bindings); } - public void overwriteBindings(SortedMap newBindings) { - bindings.clear(); - newBindings.forEach(this::put); - } - public void put(KeyBinding key, String value) { getKeyBinding(key).ifPresent(binding -> bindings.put(binding, value)); } @@ -77,4 +105,104 @@ public int size() { return this.bindings.size(); } + /** + * Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences. + */ + public KeyStroke getKey(KeyBinding bindName) { + + String s = get(bindName.getKey()); + + if (OS.OS_X) { + return getKeyForMac(KeyStroke.getKeyStroke(s)); + } else { + return KeyStroke.getKeyStroke(s); + } + } + + private KeyCombination getKeyCombination(KeyBinding bindName) { + String binding = get(bindName.getKey()); + return KeyCombination.valueOf(binding); + } + + /** + * Check if the given keyCombination equals the given keyEvent + * + * @param combination as KeyCombination + * @param keyEvent as KeEvent + * @return true if matching, else false + */ + public boolean checkKeyCombinationEquality(KeyCombination combination, KeyEvent keyEvent) { + KeyCode code = keyEvent.getCode(); + if (code == KeyCode.UNDEFINED) { + return false; + } + // gather the pressed modifier keys + String modifiers = ""; + if (keyEvent.isControlDown()) { + modifiers = "ctrl"; + } + if (keyEvent.isShiftDown()) { + modifiers += " shift"; + } + if (keyEvent.isAltDown()) { + modifiers += " alt"; + } + modifiers = modifiers.trim(); + String newShortcut = (modifiers.isEmpty()) ? code.toString() : modifiers + " " + code; + KeyCombination pressedCombination = KeyCombination.valueOf(newShortcut); + return combination.equals(pressedCombination); + } + + /** + * Check if the given KeyBinding equals the given keyEvent + * + * @param binding as KeyBinding + * @param keyEvent as KeEvent + * @return true if matching, else false + */ + public boolean checkKeyCombinationEquality(KeyBinding binding, KeyEvent keyEvent) { + KeyCombination keyCombination = getKeyCombination(binding); + return checkKeyCombinationEquality(keyCombination, keyEvent); + } + + /** + * Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences, but adapted for Mac + * users, with the Command key preferred instead of Control. + * TODO: Move to OS.java? Or replace with portable Java key codes, i.e. KeyEvent + */ + private KeyStroke getKeyForMac(KeyStroke ks) { + if (ks == null) { + return null; + } + int keyCode = ks.getKeyCode(); + if ((ks.getModifiers() & InputEvent.CTRL_MASK) == 0) { + return ks; + } else { + int modifiers = 0; + if ((ks.getModifiers() & InputEvent.SHIFT_MASK) != 0) { + modifiers = modifiers | InputEvent.SHIFT_MASK; + } + if ((ks.getModifiers() & InputEvent.ALT_MASK) != 0) { + modifiers = modifiers | InputEvent.ALT_MASK; + } + + if (shortcutMask == -1) { + try { + shortcutMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); + } catch (AWTError | HeadlessException e) { + LOGGER.warn("Problem geting shortcut mask", e); + } + } + + return KeyStroke.getKeyStroke(keyCode, shortcutMask + modifiers); + } + } + + public List getBindNames() { + return bindings.keySet().stream().map(KeyBinding::getKey).collect(Collectors.toList()); + } + + public List getBindings() { + return new ArrayList<>(bindings.values()); + } } diff --git a/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogController.java b/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogController.java index 74a68b9f88b..21767bb255d 100644 --- a/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogController.java +++ b/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogController.java @@ -14,6 +14,7 @@ import org.jabref.gui.IconTheme; import org.jabref.gui.util.RecursiveTreeItem; import org.jabref.gui.util.ViewModelTreeTableCellFactory; +import org.jabref.preferences.PreferencesService; import org.fxmisc.easybind.EasyBind; @@ -24,12 +25,13 @@ public class KeyBindingsDialogController extends AbstractController shortcutColumn; @FXML private TreeTableColumn resetColumn; - @Inject private KeyBindingPreferences keyBindingPreferences; + @Inject private KeyBindingRepository keyBindingRepository; @Inject private DialogService dialogService; + @Inject private PreferencesService preferences; @FXML private void initialize() { - viewModel = new KeyBindingsDialogViewModel(keyBindingPreferences, dialogService); + viewModel = new KeyBindingsDialogViewModel(keyBindingRepository, dialogService, preferences); keyBindingsTable.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); viewModel.selectedKeyBindingProperty().bind( diff --git a/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModel.java b/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModel.java index 1eb4f203687..c0f3c414af0 100644 --- a/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModel.java @@ -12,31 +12,31 @@ import org.jabref.gui.AbstractViewModel; import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; +import org.jabref.preferences.PreferencesService; public class KeyBindingsDialogViewModel extends AbstractViewModel { - private final KeyBindingPreferences keyBindingPreferences; - private KeyBindingRepository keyBindingRepository; + private final KeyBindingRepository keyBindingRepository; + private final PreferencesService preferences; + private final ObjectProperty selectedKeyBinding = new SimpleObjectProperty<>(); + private final ObjectProperty rootKeyBinding = new SimpleObjectProperty<>(); private DialogService dialogService; + public KeyBindingsDialogViewModel(KeyBindingRepository keyBindingRepository, DialogService dialogService, PreferencesService preferences) { + this.keyBindingRepository = Objects.requireNonNull(keyBindingRepository); + this.dialogService = Objects.requireNonNull(dialogService); + this.preferences = Objects.requireNonNull(preferences); + populateTable(); + } + public ObjectProperty selectedKeyBindingProperty() { return selectedKeyBinding; } - private final ObjectProperty selectedKeyBinding = new SimpleObjectProperty<>(); - private final ObjectProperty rootKeyBinding = new SimpleObjectProperty<>(); - public ObjectProperty rootKeyBindingProperty() { return rootKeyBinding; } - public KeyBindingsDialogViewModel(KeyBindingPreferences keyBindingPreferences, DialogService dialogService) { - this.keyBindingPreferences = Objects.requireNonNull(keyBindingPreferences); - this.dialogService = Objects.requireNonNull(dialogService); - keyBindingRepository = new KeyBindingRepository(keyBindingPreferences.getKeyBindings()); - populateTable(); - } - /** * Read all keybindings from the keybinding repository and create table keybinding models for them */ @@ -71,7 +71,7 @@ public void setNewBindingForCurrent(KeyEvent event) { } public void saveKeyBindings() { - keyBindingPreferences.setNewKeyBindings(keyBindingRepository.getKeyBindings()); + preferences.storeKeyBindingRepository(keyBindingRepository); String title = Localization.lang("Key bindings changed"); String content = Localization.lang("Your new key bindings have been stored.") + '\n' diff --git a/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java b/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java index ae967c7fcf7..d83cdcc85b5 100644 --- a/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java +++ b/src/main/java/org/jabref/gui/preftabs/AdvancedTab.java @@ -14,6 +14,7 @@ import org.jabref.gui.help.HelpAction; import org.jabref.gui.remote.JabRefMessageHandler; import org.jabref.logic.help.HelpFile; +import org.jabref.logic.journals.JournalAbbreviationPreferences; import org.jabref.logic.l10n.Localization; import org.jabref.logic.remote.RemotePreferences; import org.jabref.logic.remote.RemoteUtil; @@ -95,16 +96,18 @@ public AdvancedTab(JabRefPreferences prefs) { public void setValues() { useRemoteServer.setSelected(remotePreferences.useRemoteServer()); remoteServerPort.setText(String.valueOf(remotePreferences.getPort())); - useIEEEAbrv.setSelected(Globals.prefs.getBoolean(JabRefPreferences.USE_IEEE_ABRV)); + useIEEEAbrv.setSelected(Globals.prefs.getJournalAbbreviationPreferences().useIEEEAbbreviations()); useCaseKeeperOnSearch.setSelected(Globals.prefs.getBoolean(JabRefPreferences.USE_CASE_KEEPER_ON_SEARCH)); useUnitFormatterOnSearch.setSelected(Globals.prefs.getBoolean(JabRefPreferences.USE_UNIT_FORMATTER_ON_SEARCH)); } @Override public void storeSettings() { - if (preferences.getBoolean(JabRefPreferences.USE_IEEE_ABRV) != useIEEEAbrv.isSelected()) { - preferences.putBoolean(JabRefPreferences.USE_IEEE_ABRV, useIEEEAbrv.isSelected()); - Globals.journalAbbreviationLoader.update(Globals.prefs.getJournalAbbreviationPreferences()); + JournalAbbreviationPreferences journalAbbreviationPreferences = Globals.prefs.getJournalAbbreviationPreferences(); + if (journalAbbreviationPreferences.useIEEEAbbreviations() != useIEEEAbrv.isSelected()) { + journalAbbreviationPreferences.setUseIEEEAbbreviations(useIEEEAbrv.isSelected()); + Globals.prefs.storeJournalAbbreviationPreferences(journalAbbreviationPreferences); + Globals.journalAbbreviationLoader.update(journalAbbreviationPreferences); } storeRemoteSettings(); diff --git a/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java b/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java index 0554f4053d7..21f4f59f5bf 100644 --- a/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java +++ b/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java @@ -20,6 +20,37 @@ public class JournalAbbreviationLoader { private static final String JOURNALS_IEEE_ABBREVIATION_LIST_WITH_TEXT = "/journals/IEEEJournalListText.txt"; private JournalAbbreviationRepository journalAbbrev; + public static List getOfficialIEEEAbbreviations() { + return readJournalListFromResource(JOURNALS_IEEE_ABBREVIATION_LIST_WITH_CODE); + } + + public static List getStandardIEEEAbbreviations() { + return readJournalListFromResource(JOURNALS_IEEE_ABBREVIATION_LIST_WITH_TEXT); + } + + public static List getBuiltInAbbreviations() { + return readJournalListFromResource(JOURNALS_FILE_BUILTIN); + } + + public static List readJournalListFromResource(String resource) { + AbbreviationParser parser = new AbbreviationParser(); + parser.readJournalListFromResource(Objects.requireNonNull(resource)); + return parser.getAbbreviations(); + } + + public static List readJournalListFromFile(File file) throws FileNotFoundException { + LOGGER.debug("Reading journal list from file " + file); + AbbreviationParser parser = new AbbreviationParser(); + parser.readJournalListFromFile(Objects.requireNonNull(file)); + return parser.getAbbreviations(); + } + + public static List readJournalListFromFile(File file, Charset encoding) throws FileNotFoundException { + LOGGER.debug("Reading journal list from file " + file); + AbbreviationParser parser = new AbbreviationParser(); + parser.readJournalListFromFile(Objects.requireNonNull(file), Objects.requireNonNull(encoding)); + return parser.getAbbreviations(); + } public void update(JournalAbbreviationPreferences journalAbbreviationPreferences) { journalAbbrev = new JournalAbbreviationRepository(); @@ -32,7 +63,7 @@ public void update(JournalAbbreviationPreferences journalAbbreviationPreferences journalAbbrev.addEntries(readJournalListFromResource(JOURNALS_FILE_BUILTIN)); // read IEEE list - if (journalAbbreviationPreferences.isUseIEEEAbbreviations()) { + if (journalAbbreviationPreferences.useIEEEAbbreviations()) { journalAbbrev.addEntries(getOfficialIEEEAbbreviations()); } else { journalAbbrev.addEntries(getStandardIEEEAbbreviations()); @@ -66,42 +97,10 @@ public void update(JournalAbbreviationPreferences journalAbbreviationPreferences } - public static List getOfficialIEEEAbbreviations() { - return readJournalListFromResource(JOURNALS_IEEE_ABBREVIATION_LIST_WITH_CODE); - } - - public static List getStandardIEEEAbbreviations() { - return readJournalListFromResource(JOURNALS_IEEE_ABBREVIATION_LIST_WITH_TEXT); - } - - public static List getBuiltInAbbreviations() { - return readJournalListFromResource(JOURNALS_FILE_BUILTIN); - } - public JournalAbbreviationRepository getRepository(JournalAbbreviationPreferences journalAbbreviationPreferences) { if (journalAbbrev == null) { update(journalAbbreviationPreferences); } return journalAbbrev; } - - public static List readJournalListFromResource(String resource) { - AbbreviationParser parser = new AbbreviationParser(); - parser.readJournalListFromResource(Objects.requireNonNull(resource)); - return parser.getAbbreviations(); - } - - public static List readJournalListFromFile(File file) throws FileNotFoundException { - LOGGER.debug("Reading journal list from file " + file); - AbbreviationParser parser = new AbbreviationParser(); - parser.readJournalListFromFile(Objects.requireNonNull(file)); - return parser.getAbbreviations(); - } - - public static List readJournalListFromFile(File file, Charset encoding) throws FileNotFoundException { - LOGGER.debug("Reading journal list from file " + file); - AbbreviationParser parser = new AbbreviationParser(); - parser.readJournalListFromFile(Objects.requireNonNull(file), Objects.requireNonNull(encoding)); - return parser.getAbbreviations(); - } } diff --git a/src/main/java/org/jabref/logic/journals/JournalAbbreviationPreferences.java b/src/main/java/org/jabref/logic/journals/JournalAbbreviationPreferences.java index 3a1463c6ef7..994e5114552 100644 --- a/src/main/java/org/jabref/logic/journals/JournalAbbreviationPreferences.java +++ b/src/main/java/org/jabref/logic/journals/JournalAbbreviationPreferences.java @@ -3,16 +3,12 @@ import java.nio.charset.Charset; import java.util.List; -import org.jabref.preferences.JabRefPreferences; - public class JournalAbbreviationPreferences { - private final List externalJournalLists; private final String personalJournalLists; - private final boolean useIEEEAbbreviations; private final Charset defaultEncoding; - - + private List externalJournalLists; + private boolean useIEEEAbbreviations; public JournalAbbreviationPreferences(List externalJournalLists, String personalJournalLists, boolean useIEEEAbbreviations, Charset defaultEncoding) { this.externalJournalLists = externalJournalLists; @@ -21,22 +17,23 @@ public JournalAbbreviationPreferences(List externalJournalLists, String this.defaultEncoding = defaultEncoding; } - public static JournalAbbreviationPreferences fromPreferences(JabRefPreferences jabRefPreferences) { - return new JournalAbbreviationPreferences( - jabRefPreferences.getStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS), - jabRefPreferences.get(JabRefPreferences.PERSONAL_JOURNAL_LIST), - jabRefPreferences.getBoolean(JabRefPreferences.USE_IEEE_ABRV), jabRefPreferences.getDefaultEncoding()); + public void setUseIEEEAbbreviations(boolean useIEEEAbbreviations) { + this.useIEEEAbbreviations = useIEEEAbbreviations; } public List getExternalJournalLists() { return externalJournalLists; } + public void setExternalJournalLists(List externalJournalLists) { + this.externalJournalLists = externalJournalLists; + } + public String getPersonalJournalLists() { return personalJournalLists; } - public boolean isUseIEEEAbbreviations() { + public boolean useIEEEAbbreviations() { return useIEEEAbbreviations; } diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index 48ac595fc42..11f49fe69c1 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -38,6 +38,7 @@ import org.jabref.JabRefMain; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.gui.entryeditor.EntryEditorTabList; +import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.preftabs.ImportSettingsTab; import org.jabref.logic.autocompleter.AutoCompletePreferences; import org.jabref.logic.bibtex.FieldContentParserPreferences; @@ -79,7 +80,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -public class JabRefPreferences { +public class JabRefPreferences implements PreferencesService { // Push to application preferences public static final String EMACS_PATH = "emacsPath"; @@ -250,8 +251,6 @@ public class JabRefPreferences { public static final String MERGE_ENTRIES_DIFF_MODE = "mergeEntriesDiffMode"; public static final String CUSTOM_EXPORT_FORMAT = "customExportFormat"; public static final String CUSTOM_IMPORT_FORMAT = "customImportFormat"; - public static final String BINDINGS = "bindings"; - public static final String BIND_NAMES = "bindNames"; public static final String KEY_PATTERN_REGEX = "KeyPatternRegex"; public static final String KEY_PATTERN_REPLACEMENT = "KeyPatternReplacement"; public static final String CONSOLE_COMMAND = "consoleCommand"; @@ -274,8 +273,6 @@ public class JabRefPreferences { public static final String LAST_USED_EXPORT = "lastUsedExport"; public static final String FLOAT_MARKED_ENTRIES = "floatMarkedEntries"; public static final String CITE_COMMAND = "citeCommand"; - public static final String EXTERNAL_JOURNAL_LISTS = "externalJournalLists"; - public static final String PERSONAL_JOURNAL_LIST = "personalJournalList"; public static final String GENERATE_KEYS_BEFORE_SAVING = "generateKeysBeforeSaving"; public static final String EMAIL_SUBJECT = "emailSubject"; public static final String OPEN_FOLDERS_OF_ATTACHED_FILES = "openFoldersOfAttachedFiles"; @@ -296,7 +293,6 @@ public class JabRefPreferences { public static final String CUSTOM_TAB_FIELDS = "customTabFields_"; public static final String USE_UNIT_FORMATTER_ON_SEARCH = "useUnitFormatterOnSearch"; public static final String USE_CASE_KEEPER_ON_SEARCH = "useCaseKeeperOnSearch"; - public static final String USE_IEEE_ABRV = "useIEEEAbrv"; public static final String ASK_AUTO_NAMING_PDFS_AGAIN = "AskAutoNamingPDFsAgain"; public static final String CLEANUP_DOI = "CleanUpDOI"; public static final String CLEANUP_ISSN = "CleanUpISSN"; @@ -360,13 +356,6 @@ public class JabRefPreferences { public static final String CUSTOMIZED_BIBLATEX_TYPES = "customizedBiblatexTypes"; // Version public static final String VERSION_IGNORED_UPDATE = "versionIgnoreUpdate"; - // User - private static final String USER_ID = "userId"; - - // Telemetry collection - private static final String COLLECT_TELEMETRY = "collectTelemetry"; - private static final String ALREADY_ASKED_TO_COLLECT_TELEMETRY = "askedCollectTelemetry"; - // Dropped file handler public static final String DROPPEDFILEHANDLER_RENAME = "DroppedFileHandler_RenameFile"; public static final String DROPPEDFILEHANDLER_MOVE = "DroppedFileHandler_MoveFile"; @@ -375,6 +364,16 @@ public class JabRefPreferences { // Remote public static final String USE_REMOTE_SERVER = "useRemoteServer"; public static final String REMOTE_SERVER_PORT = "remoteServerPort"; + private static final String EXTERNAL_JOURNAL_LISTS = "externalJournalLists"; + private static final String PERSONAL_JOURNAL_LIST = "personalJournalList"; + private static final String USE_IEEE_ABRV = "useIEEEAbrv"; + private static final String BINDINGS = "bindings"; + private static final String BIND_NAMES = "bindNames"; + // User + private static final String USER_ID = "userId"; + // Telemetry collection + private static final String COLLECT_TELEMETRY = "collectTelemetry"; + private static final String ALREADY_ASKED_TO_COLLECT_TELEMETRY = "askedCollectTelemetry"; private static final Log LOGGER = LogFactory.getLog(JabRefPreferences.class); private static final Class PREFS_BASE_CLASS = JabRefMain.class; private static final String DB_CONNECT_USERNAME = "dbConnectUsername"; @@ -1493,6 +1492,7 @@ public void setProtectedTermsPreferences(ProtectedTermsLoader loader) { } + @Override public JournalAbbreviationPreferences getJournalAbbreviationPreferences() { return new JournalAbbreviationPreferences(getStringList(EXTERNAL_JOURNAL_LISTS), get(PERSONAL_JOURNAL_LIST), getBoolean(USE_IEEE_ABRV), getDefaultEncoding()); @@ -1576,4 +1576,21 @@ public Boolean shouldAskToCollectTelemetry() { public void askedToCollectTelemetry() { putBoolean(ALREADY_ASKED_TO_COLLECT_TELEMETRY, true); } + + @Override + public void storeKeyBindingRepository(KeyBindingRepository keyBindingRepository) { + putStringList(JabRefPreferences.BIND_NAMES, keyBindingRepository.getBindNames()); + putStringList(JabRefPreferences.BINDINGS, keyBindingRepository.getBindings()); + } + + @Override + public KeyBindingRepository getKeyBindingRepository() { + return new KeyBindingRepository(getStringList(BIND_NAMES), getStringList(BINDINGS)); + } + + @Override + public void storeJournalAbbreviationPreferences(JournalAbbreviationPreferences abbreviationsPreferences) { + putStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS, abbreviationsPreferences.getExternalJournalLists()); + putBoolean(JabRefPreferences.USE_IEEE_ABRV, abbreviationsPreferences.useIEEEAbbreviations()); + } } diff --git a/src/main/java/org/jabref/preferences/PreferencesService.java b/src/main/java/org/jabref/preferences/PreferencesService.java new file mode 100644 index 00000000000..6ea1a9d56dc --- /dev/null +++ b/src/main/java/org/jabref/preferences/PreferencesService.java @@ -0,0 +1,14 @@ +package org.jabref.preferences; + +import org.jabref.gui.keyboard.KeyBindingRepository; +import org.jabref.logic.journals.JournalAbbreviationPreferences; + +public interface PreferencesService { + JournalAbbreviationPreferences getJournalAbbreviationPreferences(); + + void storeKeyBindingRepository(KeyBindingRepository keyBindingRepository); + + KeyBindingRepository getKeyBindingRepository(); + + void storeJournalAbbreviationPreferences(JournalAbbreviationPreferences abbreviationsPreferences); +} diff --git a/src/test/java/org/jabref/ArchitectureTests.java b/src/test/java/org/jabref/MainArchitectureTests.java similarity index 94% rename from src/test/java/org/jabref/ArchitectureTests.java rename to src/test/java/org/jabref/MainArchitectureTests.java index 0430481b600..ea72ed250ab 100644 --- a/src/test/java/org/jabref/ArchitectureTests.java +++ b/src/test/java/org/jabref/MainArchitectureTests.java @@ -20,17 +20,15 @@ import org.junit.runners.Parameterized; @RunWith(Parameterized.class) -public class ArchitectureTests { +public class MainArchitectureTests { + public static final String CLASS_ORG_JABREF_GLOBALS = "org.jabref.Globals"; private static final String PACKAGE_JAVAX_SWING = "javax.swing"; private static final String PACKAGE_JAVA_AWT = "java.awt"; private static final String PACKAGE_JAVA_FX = "javafx"; - 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 CLASS_ORG_JABREF_GLOBALS = "org.jabref.Globals"; - private static final String EXCEPTION_PACKAGE_JAVA_AWT_GEOM = "java.awt.geom"; private static final String EXCEPTION_PACKAGE_JAVA_FX_COLLECTIONS = "javafx.collections"; private static final String EXCEPTION_PACKAGE_JAVA_FX_BEANS = "javafx.beans"; @@ -40,7 +38,7 @@ public class ArchitectureTests { private final String secondPackage; private Map> exceptions; - public ArchitectureTests(String firstPackage, String secondPackage) { + public MainArchitectureTests(String firstPackage, String secondPackage) { this.firstPackage = firstPackage; this.secondPackage = secondPackage; @@ -60,8 +58,7 @@ public ArchitectureTests(String firstPackage, String secondPackage) { modelExceptions.add(EXCEPTION_PACKAGE_JAVA_FX_COLLECTIONS); modelExceptions.add(EXCEPTION_PACKAGE_JAVA_FX_BEANS); - exceptions.put(PACKAGE_ORG_JABREF_LOGIC, - logicExceptions); + exceptions.put(PACKAGE_ORG_JABREF_LOGIC, logicExceptions); exceptions.put(PACKAGE_ORG_JABREF_MODEL, modelExceptions); } diff --git a/src/test/java/org/jabref/TestArchitectureTests.java b/src/test/java/org/jabref/TestArchitectureTests.java new file mode 100644 index 00000000000..955d731f8c8 --- /dev/null +++ b/src/test/java/org/jabref/TestArchitectureTests.java @@ -0,0 +1,76 @@ +package org.jabref; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.jabref.MainArchitectureTests.CLASS_ORG_JABREF_GLOBALS; + +@RunWith(Parameterized.class) +public class TestArchitectureTests { + + private static final String CLASS_ORG_JABREF_PREFERENCES = "org.jabref.preferences.JabRefPreferences"; + private static final String CLASS_ORG_JABREF_PREFERENCES_TEST = "JabRefPreferencesTest"; + + private final String forbiddenPackage; + + private List exceptions; + + public TestArchitectureTests(String forbiddenPackage) { + this.forbiddenPackage = forbiddenPackage; + + // Add exceptions for the architectural test here + // Note that bending the architectural constraints should not be done inconsiderately + exceptions = new ArrayList<>(); + exceptions.add(CLASS_ORG_JABREF_PREFERENCES_TEST); + } + + @Parameterized.Parameters(name = "tests independent of {0}?") + public static Iterable data() { + return Arrays.asList( + new Object[][]{ + {CLASS_ORG_JABREF_PREFERENCES}, + {CLASS_ORG_JABREF_GLOBALS} + } + ); + } + + @Test + public void testsAreIndependent() throws IOException { + Predicate isForbiddenPackage = (s) -> s.startsWith("import " + forbiddenPackage); + Predicate isExceptionClass = (s) -> exceptions.stream().anyMatch(exception -> s.startsWith("public class " + exception)); + + List files = Files.walk(Paths.get("src/test/")) + .filter(p -> p.toString().endsWith(".java")) + .filter(p -> { + try { + return Files.readAllLines(p, StandardCharsets.UTF_8).stream().noneMatch(isExceptionClass); + } catch (IOException e) { + return false; + } + }) + .filter(p -> { + try { + return Files.readAllLines(p, StandardCharsets.UTF_8).stream().anyMatch(isForbiddenPackage); + } catch (IOException e) { + return false; + } + }).collect(Collectors.toList()); + + Assert.assertEquals("The following classes are not allowed to depend on " + forbiddenPackage, + Collections.emptyList(), files); + } +} diff --git a/src/test/java/org/jabref/cli/AuxCommandLineTest.java b/src/test/java/org/jabref/cli/AuxCommandLineTest.java index 524d55dd489..a2f81aa0392 100644 --- a/src/test/java/org/jabref/cli/AuxCommandLineTest.java +++ b/src/test/java/org/jabref/cli/AuxCommandLineTest.java @@ -8,23 +8,34 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Paths; +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.preferences.JabRefPreferences; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; public class AuxCommandLineTest { + private ImportFormatPreferences importFormatPreferences; + + @Before + 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 = Paths.get(AuxCommandLineTest.class.getResource("paper.aux").toURI()).toFile(); try (InputStreamReader originalReader = new InputStreamReader(originalStream, StandardCharsets.UTF_8)) { - ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(originalReader); + ParserResult result = new BibtexParser(importFormatPreferences).parse(originalReader); AuxCommandLine auxCommandLine = new AuxCommandLine(auxFile.getAbsolutePath(), result.getDatabase()); BibDatabase newDB = auxCommandLine.perform(); diff --git a/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java b/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java index 133052f1d9e..d6415ab89cb 100644 --- a/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java +++ b/src/test/java/org/jabref/gui/importer/EntryFromFileCreatorManagerTest.java @@ -9,13 +9,12 @@ import java.util.ArrayList; import java.util.List; -import org.jabref.Globals; import org.jabref.logic.importer.ImportDataTest; +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.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.GUITests; import org.junit.Assert; @@ -24,13 +23,15 @@ import org.junit.Test; import org.junit.experimental.categories.Category; +import static org.mockito.Mockito.mock; + @Category(GUITests.class) public class EntryFromFileCreatorManagerTest { // Needed to initialize ExternalFileTypes @Before public void setUp() { - Globals.prefs = JabRefPreferences.getInstance(); + } @Test @@ -49,7 +50,7 @@ public void testGetCreator() { public void testAddEntrysFromFiles() throws FileNotFoundException, IOException { try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { - ParserResult result = new BibtexParser(Globals.prefs.getImportFormatPreferences()).parse(reader); + ParserResult result = new BibtexParser(mock(ImportFormatPreferences.class)).parse(reader); BibDatabase database = result.getDatabase(); List files = new ArrayList<>(); diff --git a/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java b/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java index e477f64709c..6bfda070754 100644 --- a/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java +++ b/src/test/java/org/jabref/gui/importer/EntryFromPDFCreatorTest.java @@ -3,12 +3,10 @@ import java.io.File; import java.util.Optional; -import org.jabref.Globals; import org.jabref.JabRefGUI; import org.jabref.gui.JabRefFrame; import org.jabref.logic.importer.ImportDataTest; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.GUITests; import org.junit.Assert; @@ -27,7 +25,6 @@ public class EntryFromPDFCreatorTest { @Before public void setUp() { - Globals.prefs = JabRefPreferences.getInstance(); // Needed to initialize ExternalFileTypes entryCreator = new EntryFromPDFCreator(); // Needed for PdfImporter - still not enough diff --git a/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java b/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java index 3cf9176f4ba..9716581818a 100644 --- a/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java +++ b/src/test/java/org/jabref/gui/journals/ManageJournalAbbreviationsViewModelTest.java @@ -20,7 +20,8 @@ import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.journals.Abbreviation; import org.jabref.logic.journals.JournalAbbreviationLoader; -import org.jabref.preferences.JabRefPreferences; +import org.jabref.logic.journals.JournalAbbreviationPreferences; +import org.jabref.preferences.PreferencesService; import org.assertj.core.util.Files; import org.junit.Assert; @@ -39,28 +40,29 @@ public class ManageJournalAbbreviationsViewModelTest { - private ManageJournalAbbreviationsViewModel viewModel; - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - @ClassRule public static CatchExceptionsFromThread catchExceptions = new CatchExceptionsFromThread(); - + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + private ManageJournalAbbreviationsViewModel viewModel; private Path emptyTestFile; private Path testFile1Entries; private Path testFile3Entries; private Path testFile4Entries; private Path testFile5EntriesWithDuplicate; - private JabRefPreferences preferences; + private JournalAbbreviationPreferences abbreviationPreferences; private DialogService dialogService; @Before public void setUpViewModel() throws Exception { - preferences = mock(JabRefPreferences.class); + abbreviationPreferences = mock(JournalAbbreviationPreferences.class); + PreferencesService preferences = mock(PreferencesService.class); + when(preferences.getJournalAbbreviationPreferences()).thenReturn(abbreviationPreferences); + dialogService = mock(DialogService.class); TaskExecutor taskExecutor = new CurrentThreadTaskExecutor(); - viewModel = new ManageJournalAbbreviationsViewModel(preferences, dialogService, taskExecutor); + JournalAbbreviationLoader journalAbbreviationLoader = mock(JournalAbbreviationLoader.class); + viewModel = new ManageJournalAbbreviationsViewModel(preferences, dialogService, taskExecutor, journalAbbreviationLoader); emptyTestFile = createTemporaryTestFile("emptyTestFile.txt", ""); testFile1Entries = createTemporaryTestFile("testFile1Entries.txt", "Test Entry = TE" + NEWLINE + ""); testFile3Entries = createTemporaryTestFile("testFile3Entries.txt", @@ -203,7 +205,7 @@ public void testMixedFileUsage() throws Exception { @Test public void testBuiltInListsIncludeAllBuiltInAbbreviations() { - when(preferences.getBoolean(JabRefPreferences.USE_IEEE_ABRV)).thenReturn(false); + when(abbreviationPreferences.useIEEEAbbreviations()).thenReturn(false); viewModel.addBuiltInLists(); Assert.assertEquals(2, viewModel.journalFilesProperty().getSize()); viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0)); @@ -218,7 +220,7 @@ public void testBuiltInListsIncludeAllBuiltInAbbreviations() { @Test public void testBuiltInListsStandardIEEEIncludesAllBuiltIEEEAbbreviations() throws Exception { - when(preferences.getBoolean(JabRefPreferences.USE_IEEE_ABRV)).thenReturn(true); + when(abbreviationPreferences.useIEEEAbbreviations()).thenReturn(true); viewModel.addBuiltInLists(); viewModel.selectLastJournalFile(); Assert.assertEquals(2, viewModel.journalFilesProperty().getSize()); @@ -440,7 +442,7 @@ public void testSaveExternalFilesListToPreferences() throws Exception { addFourTestFileToViewModelAndPreferences(); List expected = Stream.of(testFile1Entries, testFile3Entries, testFile4Entries, testFile5EntriesWithDuplicate) .map(Path::toString).collect(Collectors.toList()); - verify(preferences).putStringList(JabRefPreferences.EXTERNAL_JOURNAL_LISTS, expected); + verify(abbreviationPreferences).setExternalJournalLists(expected); } private Path createTemporaryTestFile(String name, String content) throws Exception { @@ -468,7 +470,7 @@ private void addFourTestFileToViewModelAndPreferences() throws Exception { viewModel.addNewFile(); when(dialogService.showFileSaveDialog(any())).thenReturn(Optional.of(testFile5EntriesWithDuplicate)); viewModel.addNewFile(); - viewModel.saveExternalFilesList(); + viewModel.saveEverythingAndUpdateAutoCompleter(); } /** diff --git a/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java b/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java index b599ee9f759..b5a1bb7bae0 100644 --- a/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java +++ b/src/test/java/org/jabref/gui/keyboard/KeyBindingsDialogViewModelTest.java @@ -5,7 +5,7 @@ import javafx.scene.input.KeyEvent; import org.jabref.gui.DialogService; -import org.jabref.preferences.JabRefPreferences; +import org.jabref.preferences.PreferencesService; import org.junit.Before; import org.junit.Ignore; @@ -23,18 +23,14 @@ public class KeyBindingsDialogViewModelTest { private KeyBindingsDialogViewModel model; - private KeyBindingPreferences keyBindingsPreferences; private KeyBindingRepository keyBindingRepository ; private DialogService dialogService; - @Before public void setUp() { - JabRefPreferences mockedPreferences = mock(JabRefPreferences.class); - keyBindingsPreferences = new KeyBindingPreferences(mockedPreferences); - keyBindingRepository = new KeyBindingRepository(keyBindingsPreferences.getKeyBindings()); + keyBindingRepository = new KeyBindingRepository(); dialogService = mock(DialogService.class); - model = new KeyBindingsDialogViewModel(keyBindingsPreferences, dialogService); + model = new KeyBindingsDialogViewModel(keyBindingRepository, dialogService, mock(PreferencesService.class)); } @Test @@ -42,12 +38,12 @@ public void testInvalidKeyBindingIsNotSaved() { setKeyBindingViewModel(KeyBinding.COPY); KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_RELEASED, "Q", "Q", KeyCode.Q, false, false, false, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.COPY, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.COPY, shortcutKeyEvent)); model.setNewBindingForCurrent(shortcutKeyEvent); KeyCombination combination = KeyCombination.keyCombination(keyBindingRepository.get(KeyBinding.COPY).get()); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(combination, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(combination, shortcutKeyEvent)); model.saveKeyBindings(); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.COPY, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.COPY, shortcutKeyEvent)); } @Test @@ -56,18 +52,18 @@ public void testSpecialKeysValidKeyBindingIsSaved() { setKeyBindingViewModel(KeyBinding.IMPORT_INTO_NEW_DATABASE); KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_RELEASED, "F1", "F1", KeyCode.F1, false, false, false, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.IMPORT_INTO_NEW_DATABASE, + 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(keyBindingsPreferences.checkKeyCombinationEquality(combination, shortcutKeyEvent)); + assertTrue(keyBindingRepository.checkKeyCombinationEquality(combination, shortcutKeyEvent)); model.saveKeyBindings(); - assertTrue(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.IMPORT_INTO_NEW_DATABASE, + assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.IMPORT_INTO_NEW_DATABASE, shortcutKeyEvent)); } @@ -76,7 +72,7 @@ public void testKeyBindingCategory() { KeyBindingViewModel bindViewModel = new KeyBindingViewModel(keyBindingRepository, KeyBindingCategory.FILE); model.selectedKeyBindingProperty().set(bindViewModel); KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "M", "M", KeyCode.M, true, true, true, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent)); model.setNewBindingForCurrent(shortcutKeyEvent); assertNull(model.selectedKeyBindingProperty().get().getKeyBinding()); } @@ -86,26 +82,26 @@ public void testKeyBindingCategory() { public void testRandomNewKeyKeyBindingInRepository() { setKeyBindingViewModel(KeyBinding.CLEANUP); KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "K", "K", KeyCode.K, true, true, true, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent)); model.setNewBindingForCurrent(shortcutKeyEvent); KeyCombination combination = KeyCombination.keyCombination(keyBindingRepository.get(KeyBinding.CLEANUP).get()); - assertTrue(keyBindingsPreferences.checkKeyCombinationEquality(combination, shortcutKeyEvent)); + assertTrue(keyBindingRepository.checkKeyCombinationEquality(combination, shortcutKeyEvent)); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLEANUP, shortcutKeyEvent)); } @Test public void testSaveNewKeyBindingsToPreferences() { setKeyBindingViewModel(KeyBinding.ABBREVIATE); KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "J", "J", KeyCode.J, true, true, true, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); model.setNewBindingForCurrent(shortcutKeyEvent); model.saveKeyBindings(); - assertTrue(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); } @Test @@ -114,12 +110,12 @@ public void testSaveNewSpecialKeysKeyBindingsToPreferences() { KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "F1", "F1", KeyCode.F1, true, false, false, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.UNMARK_ENTRIES, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.UNMARK_ENTRIES, shortcutKeyEvent)); model.setNewBindingForCurrent(shortcutKeyEvent); model.saveKeyBindings(); - assertTrue(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.UNMARK_ENTRIES, shortcutKeyEvent)); + assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.UNMARK_ENTRIES, shortcutKeyEvent)); } @Test @@ -128,17 +124,17 @@ public void testSetAllKeyBindingsToDefault() { setKeyBindingViewModel(KeyBinding.ABBREVIATE); KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "C", "C", KeyCode.C, true, true, true, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); model.setNewBindingForCurrent(shortcutKeyEvent); model.saveKeyBindings(); - assertTrue(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); keyBindingRepository.resetToDefault(); model.saveKeyBindings(); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); } @Test @@ -148,17 +144,17 @@ public void testSetSingleKeyBindingToDefault() { model.selectedKeyBindingProperty().set(viewModel); KeyEvent shortcutKeyEvent = new KeyEvent(KeyEvent.KEY_PRESSED, "C", "C", KeyCode.C, true, true, true, false); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); model.setNewBindingForCurrent(shortcutKeyEvent); model.saveKeyBindings(); - assertTrue(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertTrue(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); viewModel.resetToDefault(); model.saveKeyBindings(); - assertFalse(keyBindingsPreferences.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); + assertFalse(keyBindingRepository.checkKeyCombinationEquality(KeyBinding.ABBREVIATE, shortcutKeyEvent)); } private KeyBindingViewModel setKeyBindingViewModel(KeyBinding binding) { diff --git a/src/test/java/org/jabref/logic/auxparser/AuxParserTest.java b/src/test/java/org/jabref/logic/auxparser/AuxParserTest.java index 797e859d5c8..82549d7c678 100644 --- a/src/test/java/org/jabref/logic/auxparser/AuxParserTest.java +++ b/src/test/java/org/jabref/logic/auxparser/AuxParserTest.java @@ -13,22 +13,23 @@ import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.database.BibDatabase; -import org.jabref.preferences.JabRefPreferences; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; public class AuxParserTest { private ImportFormatPreferences importFormatPreferences; @Before public void setUp() { - importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @After diff --git a/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java b/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java index 549bef8fabc..957d951392e 100644 --- a/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java +++ b/src/test/java/org/jabref/logic/bibtex/BibEntryAssert.java @@ -12,13 +12,16 @@ 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.jabref.preferences.JabRefPreferences; import org.junit.Assert; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; public class BibEntryAssert { @@ -61,7 +64,7 @@ public static void assertEquals(Class clazz, String resourceName, List getListFromInputStream(InputStream is) throws IOException { ParserResult result; try (Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { - BibtexParser parser = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()); + BibtexParser parser = new BibtexParser(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); result = parser.parse(reader); } Assert.assertNotNull(result); diff --git a/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java b/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java index 8e8902aa4e6..017522753fa 100644 --- a/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java +++ b/src/test/java/org/jabref/logic/bibtex/BibEntryWriterTest.java @@ -12,13 +12,14 @@ import org.jabref.logic.util.OS; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; public class BibEntryWriterTest { @@ -27,9 +28,9 @@ public class BibEntryWriterTest { @Before public void setUpWriter() { - importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); - writer = new BibEntryWriter( - new LatexFieldFormatter(JabRefPreferences.getInstance().getLatexFieldFormatterPreferences()), true); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); + LatexFieldFormatterPreferences latexFieldFormatterPreferences = mock(LatexFieldFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); + writer = new BibEntryWriter(new LatexFieldFormatter(latexFieldFormatterPreferences), true); } @Test diff --git a/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java b/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java index be5be454be9..c9c6c7ce63f 100644 --- a/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java +++ b/src/test/java/org/jabref/logic/bibtex/LatexFieldFormatterTests.java @@ -3,12 +3,13 @@ import java.util.Collections; import org.jabref.logic.util.OS; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; public class LatexFieldFormatterTests { @@ -16,7 +17,7 @@ public class LatexFieldFormatterTests { @Before public void setUp() { - this.formatter = new LatexFieldFormatter(JabRefPreferences.getInstance().getLatexFieldFormatterPreferences()); + this.formatter = new LatexFieldFormatter(mock(LatexFieldFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java b/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java index 8b7da969d6a..623374e3201 100644 --- a/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java +++ b/src/test/java/org/jabref/logic/bibtexkeypattern/BibtexKeyPatternUtilTest.java @@ -7,13 +7,14 @@ import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; public class BibtexKeyPatternUtilTest { @@ -43,7 +44,7 @@ public class BibtexKeyPatternUtilTest { @Before public void setUp() { - importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test diff --git a/src/test/java/org/jabref/logic/bst/TestVM.java b/src/test/java/org/jabref/logic/bst/TestVM.java index 58ad4ca4890..9f48c9d46b6 100644 --- a/src/test/java/org/jabref/logic/bst/TestVM.java +++ b/src/test/java/org/jabref/logic/bst/TestVM.java @@ -10,14 +10,17 @@ import org.jabref.logic.bst.VM.BstEntry; import org.jabref.logic.bst.VM.StackFunction; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.antlr.runtime.RecognitionException; import org.junit.Assert; import org.junit.Test; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; public class TestVM { @@ -640,7 +643,7 @@ public void testVMSwap() throws RecognitionException { } private static BibEntry bibtexString2BibtexEntry(String s) throws IOException { - ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(new StringReader(s)); + ParserResult result = new BibtexParser(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)).parse(new StringReader(s)); Collection c = result.getDatabase().getEntries(); Assert.assertEquals(1, c.size()); return c.iterator().next(); diff --git a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java index aa3d6408122..c81b39cbdb1 100644 --- a/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java +++ b/src/test/java/org/jabref/logic/cleanup/CleanupWorkerTest.java @@ -15,7 +15,7 @@ import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import org.jabref.logic.formatter.bibtexfields.UnitsToLatexFormatter; import org.jabref.logic.formatter.casechanger.ProtectTermsFormatter; -import org.jabref.logic.journals.JournalAbbreviationLoader; +import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.protectedterms.ProtectedTermsPreferences; import org.jabref.model.Defaults; @@ -29,7 +29,6 @@ import org.jabref.model.entry.LinkedFile; import org.jabref.model.metadata.FileDirectoryPreferences; import org.jabref.model.metadata.MetaData; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; @@ -61,12 +60,10 @@ public void setUp() throws IOException { FileDirectoryPreferences fileDirPrefs = mock(FileDirectoryPreferences.class); when(fileDirPrefs.isBibLocationAsPrimary()).thenReturn(true); //Biblocation as Primary overwrites all other dirs - JabRefPreferences prefs = JabRefPreferences.getInstance(); - worker = new CleanupWorker(context, - new CleanupPreferences(JabRefPreferences.getInstance().get(JabRefPreferences.IMPORT_FILENAMEPATTERN), + new CleanupPreferences("\\bibtexkey", "", //empty fileDirPattern for backwards compatibility - prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), + mock(LayoutFormatterPreferences.class), fileDirPrefs)); } diff --git a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java index 31a3d41f867..3b698f85a11 100644 --- a/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java +++ b/src/test/java/org/jabref/logic/cleanup/RenamePdfCleanupTest.java @@ -5,7 +5,6 @@ import java.util.Arrays; import java.util.Optional; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.Defaults; import org.jabref.model.database.BibDatabase; @@ -15,12 +14,12 @@ import org.jabref.model.entry.LinkedFile; import org.jabref.model.metadata.FileDirectoryPreferences; import org.jabref.model.metadata.MetaData; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; @@ -32,13 +31,12 @@ public class RenamePdfCleanupTest { public TemporaryFolder testFolder = new TemporaryFolder(); private BibDatabaseContext context; private BibEntry entry; - private JabRefPreferences prefs; private FileDirectoryPreferences fileDirPrefs; + private LayoutFormatterPreferences layoutFormatterPreferences; @Before public void setUp() throws Exception { - prefs = JabRefPreferences.getInstance(); MetaData metaData = new MetaData(); context = new BibDatabaseContext(new BibDatabase(), metaData, new Defaults()); context.setDatabaseFile(testFolder.newFile("test.bib")); @@ -48,6 +46,7 @@ public void setUp() throws Exception { entry = new BibEntry(); entry.setCiteKey("Toot"); + layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); } /** @@ -113,7 +112,7 @@ public void cleanupRenamePdfRenamesFileInSameFolder() throws IOException { entry.setField("title", "test title"); RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, - prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), + layoutFormatterPreferences, fileDirPrefs); cleanup.cleanup(entry); @@ -129,7 +128,7 @@ public void cleanupSingleField() throws IOException { entry.setField("file", FileFieldWriter.getStringRepresentation(fileField)); entry.setField("title", "test title"); RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, - prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), + layoutFormatterPreferences, fileDirPrefs, fileField); cleanup.cleanup(entry); @@ -145,7 +144,7 @@ public void cleanupGetTargetFilename() throws IOException { testFolder.newFile("Toot.pdf"); LinkedFile fileField = new LinkedFile("", "Toot.pdf", "PDF"); RenamePdfCleanup cleanup = new RenamePdfCleanup(false, context, fileNamePattern, - prefs.getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)), + layoutFormatterPreferences, fileDirPrefs); entry.setField("file", FileFieldWriter.getStringRepresentation(fileField)); entry.setField("title", "test title"); diff --git a/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java b/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java index 97bae559290..1c0fc05a526 100644 --- a/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/BibTeXMLExporterTestFiles.java @@ -13,10 +13,10 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; @@ -27,12 +27,15 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; +import org.mockito.Answers; import org.xmlunit.builder.Input; import org.xmlunit.builder.Input.Builder; import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher; +import static org.mockito.Mockito.mock; + @RunWith(Parameterized.class) public class BibTeXMLExporterTestFiles { @@ -64,7 +67,7 @@ public void setUp() throws Exception { charset = StandardCharsets.UTF_8; bibtexmlExportFormat = new BibTeXMLExportFormat(); tempFile = testFolder.newFile(); - testImporter = new BibtexImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + testImporter = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java b/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java index 468ef220f22..140474f094e 100644 --- a/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java +++ b/src/test/java/org/jabref/logic/exporter/BibtexDatabaseWriterTest.java @@ -19,6 +19,7 @@ import org.jabref.model.EntryTypes; import org.jabref.model.bibtexkeypattern.AbstractBibtexKeyPattern; import org.jabref.model.bibtexkeypattern.DatabaseBibtexKeyPattern; +import org.jabref.model.bibtexkeypattern.GlobalBibtexKeyPattern; import org.jabref.model.cleanup.FieldFormatterCleanup; import org.jabref.model.cleanup.FieldFormatterCleanups; import org.jabref.model.database.BibDatabase; @@ -34,13 +35,14 @@ import org.jabref.model.groups.GroupTreeNode; import org.jabref.model.metadata.MetaData; import org.jabref.model.metadata.SaveOrderConfig; -import org.jabref.preferences.JabRefPreferences; import com.google.common.base.Charsets; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; public class BibtexDatabaseWriterTest { @@ -49,19 +51,16 @@ public class BibtexDatabaseWriterTest { private MetaData metaData; private BibDatabaseContext bibtexContext; private ImportFormatPreferences importFormatPreferences; - private JabRefPreferences prefs; @Before public void setUp() { - prefs = JabRefPreferences.getInstance(); - // Write to a string instead of to a file databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new); database = new BibDatabase(); metaData = new MetaData(); bibtexContext = new BibDatabaseContext(database, metaData, new Defaults(BibDatabaseMode.BIBTEX)); - importFormatPreferences = prefs.getImportFormatPreferences(); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test(expected = NullPointerException.class) @@ -160,7 +159,7 @@ public void writeEpilogueAndEncoding() throws Exception { @Test public void writeMetadata() throws Exception { - DatabaseBibtexKeyPattern bibtexKeyPattern = new DatabaseBibtexKeyPattern(prefs.getKeyPattern()); + DatabaseBibtexKeyPattern bibtexKeyPattern = new DatabaseBibtexKeyPattern(mock(GlobalBibtexKeyPattern.class)); bibtexKeyPattern.setDefaultValue("test"); metaData.setCiteKeyPattern(bibtexKeyPattern); @@ -173,7 +172,7 @@ public void writeMetadata() throws Exception { @Test public void writeMetadataAndEncoding() throws Exception { SavePreferences preferences = new SavePreferences().withEncoding(Charsets.US_ASCII); - DatabaseBibtexKeyPattern bibtexKeyPattern = new DatabaseBibtexKeyPattern(prefs.getKeyPattern()); + DatabaseBibtexKeyPattern bibtexKeyPattern = new DatabaseBibtexKeyPattern(mock(GlobalBibtexKeyPattern.class)); bibtexKeyPattern.setDefaultValue("test"); metaData.setCiteKeyPattern(bibtexKeyPattern); @@ -441,7 +440,7 @@ public void writeSaveOrderConfig() throws Exception { @Test public void writeCustomKeyPattern() throws Exception { - AbstractBibtexKeyPattern pattern = new DatabaseBibtexKeyPattern(prefs.getKeyPattern()); + AbstractBibtexKeyPattern pattern = new DatabaseBibtexKeyPattern(mock(GlobalBibtexKeyPattern.class)); pattern.setDefaultValue("test"); pattern.addBibtexKeyPattern("article", "articleTest"); metaData.setCiteKeyPattern(pattern); diff --git a/src/test/java/org/jabref/logic/exporter/ExportFormatTest.java b/src/test/java/org/jabref/logic/exporter/ExportFormatTest.java index 90d61f3e07c..c44af983fb9 100644 --- a/src/test/java/org/jabref/logic/exporter/ExportFormatTest.java +++ b/src/test/java/org/jabref/logic/exporter/ExportFormatTest.java @@ -6,14 +6,13 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import com.google.common.base.Charsets; import org.junit.Before; @@ -24,6 +23,7 @@ import org.junit.runners.Parameterized; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; @RunWith(Parameterized.class) public class ExportFormatTest { @@ -75,14 +75,10 @@ public void testExportingNullEntriesThrowsNPE() throws Exception { @Parameterized.Parameters(name = "{index}: {1}") public static Collection exportFormats() { Collection result = new ArrayList<>(); - JabRefPreferences prefs = JabRefPreferences.getInstance(); - JournalAbbreviationLoader journalAbbreviationLoader = new JournalAbbreviationLoader(); - - Map customFormats = prefs.customExports.getCustomExportFormats(prefs, - journalAbbreviationLoader); - LayoutFormatterPreferences layoutPreferences = prefs - .getLayoutFormatterPreferences(journalAbbreviationLoader); - SavePreferences savePreferences = SavePreferences.loadForExportFromPreferences(prefs); + + Map customFormats = new HashMap<>(); + LayoutFormatterPreferences layoutPreferences = mock(LayoutFormatterPreferences.class); + SavePreferences savePreferences = mock(SavePreferences.class); ExportFormats.initAllExports(customFormats, layoutPreferences, savePreferences); for (IExportFormat format : ExportFormats.getExportFormats().values()) { diff --git a/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java b/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java index f9e1cb1fbce..1901812a1fa 100644 --- a/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java +++ b/src/test/java/org/jabref/logic/exporter/HtmlExportFormatTest.java @@ -4,14 +4,13 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import com.google.common.base.Charsets; import org.junit.After; @@ -19,8 +18,10 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; public class HtmlExportFormatTest { private IExportFormat exportFormat; @@ -33,12 +34,9 @@ public class HtmlExportFormatTest { @Before public void setUp() { - JabRefPreferences prefs = JabRefPreferences.getInstance(); - JournalAbbreviationLoader journalAbbreviationLoader = new JournalAbbreviationLoader(); - Map customFormats = prefs.customExports.getCustomExportFormats(prefs, - journalAbbreviationLoader); - LayoutFormatterPreferences layoutPreferences = prefs.getLayoutFormatterPreferences(journalAbbreviationLoader); - SavePreferences savePreferences = SavePreferences.loadForExportFromPreferences(prefs); + Map customFormats = new HashMap<>(); + LayoutFormatterPreferences layoutPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); + SavePreferences savePreferences = mock(SavePreferences.class); ExportFormats.initAllExports(customFormats, layoutPreferences, savePreferences); exportFormat = ExportFormats.getExportFormat("html"); diff --git a/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java b/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java index 1e7e2a22ea5..b49ba27c409 100644 --- a/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/MSBibExportFormatTestFiles.java @@ -13,10 +13,10 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Rule; @@ -26,6 +26,7 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; +import org.mockito.Answers; import org.xmlunit.builder.Input; import org.xmlunit.builder.Input.Builder; import org.xmlunit.diff.DefaultNodeMatcher; @@ -33,6 +34,7 @@ import org.xmlunit.matchers.CompareMatcher; import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; @RunWith(Parameterized.class) public class MSBibExportFormatTestFiles { @@ -66,7 +68,7 @@ public void setUp() throws Exception { charset = StandardCharsets.UTF_8; msBibExportFormat = new MSBibExportFormat(); tempFile = testFolder.newFile(); - testImporter = new BibtexImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + testImporter = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java index 3386e1c99b5..112e7354915 100644 --- a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java +++ b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java @@ -9,16 +9,19 @@ import java.util.Collections; import java.util.List; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; public class ModsExportFormatTest { @@ -39,15 +42,14 @@ public void setUp() throws Exception { databaseContext = new BibDatabaseContext(); charset = StandardCharsets.UTF_8; modsExportFormat = new ModsExportFormat(); - bibtexImporter = new BibtexImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + bibtexImporter = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); tempFile = testFolder.newFile(); importFile = Paths.get(ModsExportFormatTest.class.getResource("ModsExportFormatTestAllFields.bib").toURI()); } @Test(expected = SaveException.class) public final void testPerformExportTrowsSaveException() throws Exception { - List entries = bibtexImporter.importDatabase(importFile, charset).getDatabase() - .getEntries(); + List entries = bibtexImporter.importDatabase(importFile, charset).getDatabase().getEntries(); modsExportFormat.performExport(databaseContext, "", charset, entries); } diff --git a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java index febd1a74460..bd774557ea9 100644 --- a/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java +++ b/src/test/java/org/jabref/logic/exporter/ModsExportFormatTestFiles.java @@ -12,11 +12,11 @@ import java.util.stream.Stream; import org.jabref.logic.bibtex.BibEntryAssert; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.fileformat.BibtexImporter; import org.jabref.logic.importer.fileformat.ModsImporter; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; @@ -27,12 +27,15 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; +import org.mockito.Answers; import org.xmlunit.builder.Input; import org.xmlunit.builder.Input.Builder; import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher; +import static org.mockito.Mockito.mock; + @RunWith(Parameterized.class) public class ModsExportFormatTestFiles { @@ -68,7 +71,7 @@ public void setUp() throws Exception { charset = StandardCharsets.UTF_8; modsExportFormat = new ModsExportFormat(); tempFile = testFolder.newFile(); - bibtexImporter = new BibtexImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + bibtexImporter = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); modsImporter = new ModsImporter(); } diff --git a/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java b/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java index d254d3991b1..a72d250cb60 100644 --- a/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java +++ b/src/test/java/org/jabref/logic/importer/BibDatabaseTestsWithFiles.java @@ -7,12 +7,13 @@ import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.database.BibDatabase; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; public class BibDatabaseTestsWithFiles { @@ -20,7 +21,7 @@ public class BibDatabaseTestsWithFiles { @Before public void setUp() { - importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test diff --git a/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java b/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java index 44ba9f9d533..adc7349521a 100644 --- a/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java +++ b/src/test/java/org/jabref/logic/importer/DatabaseFileLookupTest.java @@ -8,11 +8,13 @@ import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; /** * @author Nosh&Dan @@ -31,7 +33,7 @@ public class DatabaseFileLookupTest { public void setUp() throws Exception { try (FileInputStream stream = new FileInputStream(ImportDataTest.UNLINKED_FILES_TEST_BIB); InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { - ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(reader); + ParserResult result = new BibtexParser(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)).parse(reader); database = result.getDatabase(); entries = database.getEntries(); diff --git a/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java b/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java index 5a5fc48675b..fc979f008f7 100644 --- a/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java +++ b/src/test/java/org/jabref/logic/importer/ImportFormatReaderIntegrationTest.java @@ -1,19 +1,23 @@ package org.jabref.logic.importer; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; -import org.jabref.preferences.JabRefPreferences; +import org.jabref.logic.xmp.XMPPreferences; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; @RunWith(Parameterized.class) public class ImportFormatReaderIntegrationTest { @@ -35,8 +39,9 @@ public ImportFormatReaderIntegrationTest(String resource, String format, int cou @Before public void setUp() { reader = new ImportFormatReader(); - reader.resetImportFormats(JabRefPreferences.getInstance().getImportFormatPreferences(), - JabRefPreferences.getInstance().getXMPPreferences()); + ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); + when(importFormatPreferences.getEncoding()).thenReturn(StandardCharsets.UTF_8); + reader.resetImportFormats(importFormatPreferences, mock(XMPPreferences.class)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java b/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java index 7aa4026cb1d..479cef9eb0f 100644 --- a/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java +++ b/src/test/java/org/jabref/logic/importer/ImportFormatReaderTestParameterless.java @@ -1,14 +1,18 @@ package org.jabref.logic.importer; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; -import org.jabref.preferences.JabRefPreferences; +import org.jabref.logic.xmp.XMPPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class ImportFormatReaderTestParameterless { @@ -17,8 +21,9 @@ public class ImportFormatReaderTestParameterless { @Before public void setUp() { reader = new ImportFormatReader(); - reader.resetImportFormats(JabRefPreferences.getInstance().getImportFormatPreferences(), - JabRefPreferences.getInstance().getXMPPreferences()); + ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); + when(importFormatPreferences.getEncoding()).thenReturn(StandardCharsets.UTF_8); + reader.resetImportFormats(importFormatPreferences, mock(XMPPreferences.class)); } @Test(expected = ImportException.class) diff --git a/src/test/java/org/jabref/logic/importer/ImporterTest.java b/src/test/java/org/jabref/logic/importer/ImporterTest.java index 2e9e9e2e4ac..aed59c010e8 100644 --- a/src/test/java/org/jabref/logic/importer/ImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/ImporterTest.java @@ -24,7 +24,6 @@ import org.jabref.logic.importer.fileformat.RisImporter; import org.jabref.logic.importer.fileformat.SilverPlatterImporter; import org.jabref.logic.xmp.XMPPreferences; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Test; @@ -34,6 +33,7 @@ import org.junit.runners.Parameterized.Parameters; import org.mockito.Mockito; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(Parameterized.class) @@ -75,7 +75,7 @@ public void getIdDoesNotContainWhitespace() { @Test public void getIdStripsSpecialCharactersAndConvertsToLowercase() { - Importer importer = Mockito.mock(Importer.class, Mockito.CALLS_REAL_METHODS); + Importer importer = mock(Importer.class, Mockito.CALLS_REAL_METHODS); when(importer.getName()).thenReturn("*Test-Importer"); Assert.assertEquals("testimporter", importer.getId()); } @@ -90,8 +90,8 @@ public static Collection instancesToTest() { // all classes implementing {@link Importer} // sorted alphabetically - ImportFormatPreferences importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); - XMPPreferences xmpPreferences = JabRefPreferences.getInstance().getXMPPreferences(); + ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class); + XMPPreferences xmpPreferences = mock(XMPPreferences.class); // @formatter:off return Arrays.asList( new Object[]{new BiblioscapeImporter()}, diff --git a/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java b/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java index 614669c68bf..e4d3d2701b7 100644 --- a/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java +++ b/src/test/java/org/jabref/logic/importer/OpenDatabaseTest.java @@ -11,11 +11,14 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class OpenDatabaseTest { @@ -40,7 +43,8 @@ public OpenDatabaseTest() throws URISyntaxException { @Before public void setUp() { - importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); + when(importFormatPreferences.getEncoding()).thenReturn(StandardCharsets.UTF_8); } @Test diff --git a/src/test/java/org/jabref/logic/importer/ParsedBibEntryTests.java b/src/test/java/org/jabref/logic/importer/ParsedBibEntryTests.java index 30fb678620a..79c80fec9ee 100644 --- a/src/test/java/org/jabref/logic/importer/ParsedBibEntryTests.java +++ b/src/test/java/org/jabref/logic/importer/ParsedBibEntryTests.java @@ -3,11 +3,13 @@ import java.util.Optional; import org.jabref.logic.importer.fileformat.BibtexParser; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; public class ParsedBibEntryTests { @@ -17,7 +19,7 @@ public class ParsedBibEntryTests { @Before public void setUp() { - importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fetcher/AstrophysicsDataSystemTest.java b/src/test/java/org/jabref/logic/importer/fetcher/AstrophysicsDataSystemTest.java index fc85d11080d..dac41c42c83 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/AstrophysicsDataSystemTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/AstrophysicsDataSystemTest.java @@ -72,7 +72,7 @@ public void setUp() throws Exception { famaeyMcGaughEntry.setField("journal", "Living Reviews in Relativity"); famaeyMcGaughEntry.setField("year", "2012"); famaeyMcGaughEntry.setField("volume", "15"); - famaeyMcGaughEntry.setField("month", "#dec#"); + famaeyMcGaughEntry.setField("month", "#sep#"); famaeyMcGaughEntry.setField("archiveprefix", "arXiv"); famaeyMcGaughEntry.setField("doi", "10.12942/lrr-2012-10"); famaeyMcGaughEntry.setField("eid", "10"); @@ -142,7 +142,7 @@ public void testGetName() { @Test public void searchByQueryFindsEntry() throws Exception { - List fetchedEntries = fetcher.performSearch("Diez slice theorem"); + List fetchedEntries = fetcher.performSearch("Diez slice theorem Lie"); assertEquals(Collections.singletonList(diezSliceTheoremEntry), fetchedEntries); } diff --git a/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java b/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java index 67c6d25b573..ef075780195 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/DiVATest.java @@ -3,17 +3,19 @@ import java.util.Optional; import org.jabref.logic.help.HelpFile; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.FetcherTests; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; @Category(FetcherTests.class) public class DiVATest { @@ -22,7 +24,7 @@ public class DiVATest { @Before public void setUp() { - fetcher = new DiVA(JabRefPreferences.getInstance().getImportFormatPreferences()); + fetcher = new DiVA(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java index 3bf222b3ee1..5c6efa24e76 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/DoiFetcherTest.java @@ -3,17 +3,19 @@ import java.util.Optional; import org.jabref.logic.importer.FetcherException; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BiblatexEntryTypes; -import org.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.FetcherTests; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; @Category(FetcherTests.class) public class DoiFetcherTest { @@ -23,7 +25,7 @@ public class DoiFetcherTest { @Before public void setUp() { - fetcher = new DoiFetcher(JabRefPreferences.getInstance().getImportFormatPreferences()); + fetcher = new DoiFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); bibEntryBurd2011 = new BibEntry(); bibEntryBurd2011.setType(BiblatexEntryTypes.BOOK); diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java index 3774a88e985..8f77ecd98c9 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/IsbnFetcherTest.java @@ -3,17 +3,19 @@ import java.util.Optional; import org.jabref.logic.importer.FetcherException; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BiblatexEntryTypes; -import org.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.FetcherTests; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.mockito.Mockito.mock; @Category(FetcherTests.class) public class IsbnFetcherTest { @@ -23,7 +25,7 @@ public class IsbnFetcherTest { @Before public void setUp() { - fetcher = new IsbnFetcher(JabRefPreferences.getInstance().getImportFormatPreferences()); + fetcher = new IsbnFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); bibEntry = new BibEntry(); bibEntry.setType(BiblatexEntryTypes.BOOK); diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java index 4ee3b955b34..f1dd10f016c 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaChimboriFetcherTest.java @@ -3,17 +3,19 @@ import java.util.Optional; import org.jabref.logic.importer.FetcherException; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BiblatexEntryTypes; -import org.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.FetcherTests; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.mockito.Mockito.mock; @Category(FetcherTests.class) public class IsbnViaChimboriFetcherTest extends AbstractIsbnFetcherTest { @@ -31,7 +33,7 @@ public void setUp() { bibEntry.setField("url", "https://www.amazon.com/Effective-Java-Joshua-Bloch-ebook/dp/B00B8V09HY?SubscriptionId=0JYN1NVW651KCA56C102&tag=techkie-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B00B8V09HY"); - fetcher = new IsbnViaChimboriFetcher(JabRefPreferences.getInstance().getImportFormatPreferences()); + fetcher = new IsbnViaChimboriFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java index 593c414cdac..5cc1606de18 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/IsbnViaEbookDeFetcherTest.java @@ -3,16 +3,18 @@ import java.util.Optional; import org.jabref.logic.importer.FetcherException; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BiblatexEntryTypes; -import org.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.FetcherTests; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; @Category(FetcherTests.class) public class IsbnViaEbookDeFetcherTest extends AbstractIsbnFetcherTest { @@ -32,7 +34,7 @@ public void setUp() { bibEntry.setField("pagetotal", "384"); bibEntry.setField("url", "http://www.ebook.de/de/product/6441328/joshua_bloch_effective_java.html"); - fetcher = new IsbnViaEbookDeFetcher(JabRefPreferences.getInstance().getImportFormatPreferences()); + fetcher = new IsbnViaEbookDeFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java b/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java index 23441555d00..ad5ebf1538a 100644 --- a/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java +++ b/src/test/java/org/jabref/logic/importer/fetcher/TitleFetcherTest.java @@ -3,16 +3,18 @@ import java.util.Optional; import org.jabref.logic.importer.FetcherException; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BiblatexEntryTypes; -import org.jabref.preferences.JabRefPreferences; import org.jabref.testutils.category.FetcherTests; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; @Category(FetcherTests.class) public class TitleFetcherTest { @@ -22,7 +24,7 @@ public class TitleFetcherTest { @Before public void setUp() { - fetcher = new TitleFetcher(JabRefPreferences.getInstance().getImportFormatPreferences()); + fetcher = new TitleFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); bibEntryBischof2009 = new BibEntry(); bibEntryBischof2009.setType(BiblatexEntryTypes.INPROCEEDINGS); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java index 673448a743c..58df1830dcc 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibtexImporterTest.java @@ -8,15 +8,17 @@ import java.util.List; import java.util.Optional; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.FileExtensions; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; /** * This class tests the BibtexImporter. @@ -33,7 +35,7 @@ public class BibtexImporterTest { @Before public void setUp() { - importer = new BibtexImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + importer = new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java b/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java index 89013c0ed58..d2124b9473f 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/BibtexParserTest.java @@ -35,15 +35,17 @@ import org.jabref.model.groups.RegexKeywordGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.SaveOrderConfig; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Test the BibtexParser @@ -56,7 +58,8 @@ public class BibtexParserTest { @Before public void setUp() { - importFormatPreferences = JabRefPreferences.getInstance().getImportFormatPreferences(); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); + when(importFormatPreferences.getKeywordSeparator()).thenReturn(','); parser = new BibtexParser(importFormatPreferences); } @@ -1159,9 +1162,11 @@ public void parseConvertsMultipleTabsToSpace() throws IOException { * @author Andrei Haralevich */ @Test - public void parsePreservesMultipleSpacesInFileField() throws IOException { + public void parsePreservesMultipleSpacesInNonWrappableField() throws IOException { + when(importFormatPreferences.getFieldContentParserPreferences().getNonWrappableFields()) + .thenReturn(Collections.singletonList("file")); ParserResult result = parser - .parse(new StringReader("@article{canh05,file = {ups sala}}")); + .parse(new StringReader("@article{canh05,file = {ups sala}}"), importFormatPreferences); Collection c = result.getDatabase().getEntries(); BibEntry e = c.iterator().next(); @@ -1413,7 +1418,7 @@ public void integrationTestCustomKeyPattern() throws IOException { .parse(new StringReader("@comment{jabref-meta: keypattern_article:articleTest;}" + OS.NEWLINE + "@comment{jabref-meta: keypatterndefault:test;}"), importFormatPreferences); - GlobalBibtexKeyPattern pattern = JabRefPreferences.getInstance().getKeyPattern(); + GlobalBibtexKeyPattern pattern = mock(GlobalBibtexKeyPattern.class); AbstractBibtexKeyPattern bibtexKeyPattern = result.getMetaData().getCiteKeyPattern(pattern); AbstractBibtexKeyPattern expectedPattern = new DatabaseBibtexKeyPattern(pattern); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java index c2204447f1e..233c5d9a6b5 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/EndnoteImporterTest.java @@ -12,16 +12,18 @@ import java.util.List; import java.util.Optional; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.FileExtensions; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; public class EndnoteImporterTest { @@ -30,7 +32,7 @@ public class EndnoteImporterTest { @Before public void setUp() { - importer = new EndnoteImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + importer = new EndnoteImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fileformat/FreeCiteImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/FreeCiteImporterTest.java index 23534d1488e..7af17740dda 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/FreeCiteImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/FreeCiteImporterTest.java @@ -6,14 +6,15 @@ import java.util.List; import java.util.Optional; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.FileExtensions; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; public class FreeCiteImporterTest { @@ -22,7 +23,7 @@ public class FreeCiteImporterTest { @Before public void setUp() { - importer = new FreeCiteImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + importer = new FreeCiteImporter(mock(ImportFormatPreferences.class)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java index a32138acce2..792ea6c75bb 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTest.java @@ -7,14 +7,15 @@ import java.util.Collections; import java.util.List; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.FileExtensions; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; public class PdfContentImporterTest { @@ -23,7 +24,7 @@ public class PdfContentImporterTest { @Before public void setUp() { - importer = new PdfContentImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + importer = new PdfContentImporter(mock(ImportFormatPreferences.class)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java index a8aa7bffee4..c23e067503a 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/PdfContentImporterTestFiles.java @@ -10,8 +10,8 @@ import java.util.List; import org.jabref.logic.bibtex.BibEntryAssert; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,6 +19,8 @@ import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; +import static org.mockito.Mockito.mock; + @RunWith(Parameterized.class) public class PdfContentImporterTestFiles { @@ -43,8 +45,7 @@ public static Collection fileNames() { public void correctContent() throws IOException, URISyntaxException { String pdfFileName = fileName + ".pdf"; String bibFileName = fileName + ".bib"; - PdfContentImporter importer = new PdfContentImporter( - JabRefPreferences.getInstance().getImportFormatPreferences()); + PdfContentImporter importer = new PdfContentImporter(mock(ImportFormatPreferences.class)); Path pdfFile = Paths.get(PdfContentImporter.class.getResource(pdfFileName).toURI()); List result = importer.importDatabase(pdfFile, StandardCharsets.UTF_8).getDatabase().getEntries(); BibEntryAssert.assertEquals(PdfContentImporterTest.class, bibFileName, result); diff --git a/src/test/java/org/jabref/logic/importer/fileformat/PdfXmpImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/PdfXmpImporterTest.java index 32242c61d5c..b4cf96accd2 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/PdfXmpImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/PdfXmpImporterTest.java @@ -11,8 +11,8 @@ import org.jabref.logic.importer.ParserResult; import org.jabref.logic.util.FileExtensions; +import org.jabref.logic.xmp.XMPPreferences; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; public class PdfXmpImporterTest { @@ -29,7 +30,7 @@ public class PdfXmpImporterTest { @Before public void setUp() { - importer = new PdfXmpImporter(JabRefPreferences.getInstance().getXMPPreferences()); + importer = new PdfXmpImporter(mock(XMPPreferences.class)); } @Test diff --git a/src/test/java/org/jabref/logic/importer/fileformat/RepecNepImporterTest.java b/src/test/java/org/jabref/logic/importer/fileformat/RepecNepImporterTest.java index 691d93cf256..03084a88464 100644 --- a/src/test/java/org/jabref/logic/importer/fileformat/RepecNepImporterTest.java +++ b/src/test/java/org/jabref/logic/importer/fileformat/RepecNepImporterTest.java @@ -10,14 +10,17 @@ import java.util.List; import org.jabref.logic.bibtex.BibEntryAssert; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.util.FileExtensions; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class RepecNepImporterTest { private RepecNepImporter testImporter; @@ -25,7 +28,9 @@ public class RepecNepImporterTest { @Before public void setUp() { - testImporter = new RepecNepImporter(JabRefPreferences.getInstance().getImportFormatPreferences()); + ImportFormatPreferences importFormatPreferences = mock(ImportFormatPreferences.class); + when(importFormatPreferences.getKeywordSeparator()).thenReturn(','); + testImporter = new RepecNepImporter(importFormatPreferences); } @Test @@ -52,8 +57,7 @@ public final void testIsNotRecognizedFormat() throws IOException, URISyntaxExcep public final void testImportEntries1() throws IOException, URISyntaxException { Path file = Paths.get(RepecNepImporter.class.getResource("RepecNepImporterTest1.txt").toURI()); try (InputStream bibIn = RepecNepImporter.class.getResourceAsStream("RepecNepImporterTest1.bib")) { - List entries = testImporter.importDatabase(file, StandardCharsets.UTF_8).getDatabase() - .getEntries(); + List entries = testImporter.importDatabase(file, StandardCharsets.UTF_8).getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntryAssert.assertEquals(bibIn, entries.get(0)); } diff --git a/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java b/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java index b2471496ac3..a6e1b39226f 100644 --- a/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java +++ b/src/test/java/org/jabref/logic/integrity/IntegrityCheckTest.java @@ -18,8 +18,8 @@ import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.InternalBibtexFields; +import org.jabref.model.metadata.FileDirectoryPreferences; import org.jabref.model.metadata.MetaData; -import org.jabref.preferences.JabRefPreferences; import org.junit.Rule; import org.junit.Test; @@ -29,6 +29,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; public class IntegrityCheckTest { @@ -207,7 +208,7 @@ public void testJournalIsKnownInAbbreviationList() { @Test public void testFileChecks() { - MetaData metaData = Mockito.mock(MetaData.class); + MetaData metaData = mock(MetaData.class); Mockito.when(metaData.getDefaultFileDirectory()).thenReturn(Optional.of(".")); Mockito.when(metaData.getUserFileDirectory(any(String.class))).thenReturn(Optional.empty()); // FIXME: must be set as checkBibtexDatabase only activates title checker based on database mode @@ -337,7 +338,7 @@ public void testEntryIsUnchangedAfterChecks() { BibDatabaseContext context = new BibDatabaseContext(bibDatabase, new Defaults()); new IntegrityCheck(context, - JabRefPreferences.getInstance().getFileDirectoryPreferences(), + mock(FileDirectoryPreferences.class), createBibtexKeyPatternPreferences(), new JournalAbbreviationRepository(new Abbreviation("IEEE Software", "IEEE SW"))) .checkBibtexDatabase(); @@ -375,7 +376,7 @@ private BibDatabaseContext createContext(String field, String value) { private void assertWrong(BibDatabaseContext context) { List messages = new IntegrityCheck(context, - JabRefPreferences.getInstance().getFileDirectoryPreferences(), + mock(FileDirectoryPreferences.class), createBibtexKeyPatternPreferences(), new JournalAbbreviationRepository(new Abbreviation("IEEE Software", "IEEE SW"))) .checkBibtexDatabase(); @@ -384,7 +385,7 @@ private void assertWrong(BibDatabaseContext context) { private void assertCorrect(BibDatabaseContext context) { List messages = new IntegrityCheck(context, - JabRefPreferences.getInstance().getFileDirectoryPreferences(), + mock(FileDirectoryPreferences.class), createBibtexKeyPatternPreferences(), new JournalAbbreviationRepository(new Abbreviation("IEEE Software", "IEEE SW")) ).checkBibtexDatabase(); diff --git a/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java b/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java index ed2a904bb99..641cc83c5b8 100644 --- a/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java +++ b/src/test/java/org/jabref/logic/journals/AbbreviationsTest.java @@ -23,7 +23,7 @@ public void setUp() throws Exception { @Test public void getNextAbbreviationAbbreviatesIEEEJournalTitle() { - when(prefs.isUseIEEEAbbreviations()).thenReturn(true); + when(prefs.useIEEEAbbreviations()).thenReturn(true); assertEquals("#IEEE_J_PROC#", abbreviations.getRepository(prefs) @@ -32,7 +32,7 @@ public void getNextAbbreviationAbbreviatesIEEEJournalTitle() { @Test public void getNextAbbreviationExpandsIEEEAbbreviation() { - when(prefs.isUseIEEEAbbreviations()).thenReturn(true); + when(prefs.useIEEEAbbreviations()).thenReturn(true); assertEquals("Proceedings of the IEEE", abbreviations.getRepository(prefs) diff --git a/src/test/java/org/jabref/logic/l10n/LocalizationTest.java b/src/test/java/org/jabref/logic/l10n/LocalizationTest.java index 81c509ea7ae..8f9f6496064 100644 --- a/src/test/java/org/jabref/logic/l10n/LocalizationTest.java +++ b/src/test/java/org/jabref/logic/l10n/LocalizationTest.java @@ -2,8 +2,6 @@ import java.util.Locale; -import org.jabref.preferences.JabRefPreferences; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -23,7 +21,6 @@ public void storeDefaultLocale() { public void restoreDefaultLocale() { Locale.setDefault(locale); javax.swing.JComponent.setDefaultLocale(locale); - Localization.setLanguage(JabRefPreferences.getInstance().get(JabRefPreferences.LANGUAGE)); } @Test diff --git a/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java b/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java index 59b928e17e1..b20af305c10 100644 --- a/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java +++ b/src/test/java/org/jabref/logic/layout/LayoutEntryTest.java @@ -3,9 +3,7 @@ import java.io.IOException; import java.io.StringReader; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; @@ -74,9 +72,7 @@ public void setUp() { public String layout(String layoutFile, BibEntry entry) throws IOException { StringReader sr = new StringReader(layoutFile.replace("__NEWLINE__", "\n")); - Layout layout = new LayoutHelper(sr, - JabRefPreferences.getInstance().getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class))) - .getLayoutFromText(); + Layout layout = new LayoutHelper(sr, mock(LayoutFormatterPreferences.class)).getLayoutFromText(); return layout.doLayout(entry, null); } diff --git a/src/test/java/org/jabref/logic/layout/LayoutTest.java b/src/test/java/org/jabref/logic/layout/LayoutTest.java index fe230707ca9..5f123da8efd 100644 --- a/src/test/java/org/jabref/logic/layout/LayoutTest.java +++ b/src/test/java/org/jabref/logic/layout/LayoutTest.java @@ -6,30 +6,31 @@ import java.util.Collection; import java.util.Collections; +import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; -import org.jabref.logic.journals.JournalAbbreviationLoader; -import org.jabref.logic.journals.JournalAbbreviationPreferences; import org.jabref.logic.layout.format.FileLinkPreferences; -import org.jabref.logic.layout.format.NameFormatterPreferences; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class LayoutTest { - private LayoutFormatterPreferences prefs; + private static ImportFormatPreferences importFormatPreferences; + private LayoutFormatterPreferences layoutFormatterPreferences; /** * Initialize Preferences. */ @Before public void setUp() { - prefs = JabRefPreferences.getInstance().getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)); + layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } /** @@ -45,7 +46,7 @@ public String t1BibtexString() { } public static BibEntry bibtexString2BibtexEntry(String s) throws IOException { - ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(new StringReader(s)); + ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(s)); Collection c = result.getDatabase().getEntries(); Assert.assertEquals(1, c.size()); return c.iterator().next(); @@ -54,8 +55,7 @@ public static BibEntry bibtexString2BibtexEntry(String s) throws IOException { public String layout(String layoutFile, String entry) throws IOException { BibEntry be = LayoutTest.bibtexString2BibtexEntry(entry); StringReader sr = new StringReader(layoutFile.replace("__NEWLINE__", "\n")); - Layout layout = new LayoutHelper(sr, prefs) - .getLayoutFromText(); + Layout layout = new LayoutHelper(sr, layoutFormatterPreferences).getLayoutFromText(); return layout.doLayout(be, null); } @@ -103,7 +103,6 @@ public void testHTMLCharDoubleLineBreak() throws IOException { */ @Test public void testLayout() throws IOException { - String layoutText = layout( "\\begin{abstract}

Abstract: \\format[HTMLChars]{\\abstract}\\end{abstract}
", t1BibtexString()); @@ -116,12 +115,12 @@ public void testLayout() throws IOException { @Test // Test for http://discourse.jabref.org/t/the-wrapfilelinks-formatter/172 (the example in the help files) public void testWrapFileLinksLayout() throws IOException { - prefs = new LayoutFormatterPreferences(mock(NameFormatterPreferences.class), - mock(JournalAbbreviationPreferences.class), - new FileLinkPreferences(Collections.emptyList(), Collections.singletonList("src/test/resources/pdfs/")), - mock(JournalAbbreviationLoader.class)); + when(layoutFormatterPreferences.getFileLinkPreferences()).thenReturn( + new FileLinkPreferences(Collections.emptyList(), Collections.singletonList("src/test/resources/pdfs/"))); + String layoutText = layout("\\begin{file}\\format[WrapFileLinks(\\i. \\d (\\p))]{\\file}\\end{file}", "@other{bla, file={Test file:encrypted.pdf:PDF}}"); + Assert.assertEquals( "1. Test file (" + new File("src/test/resources/pdfs/encrypted.pdf").getCanonicalPath() + ")", layoutText); diff --git a/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java b/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java index abf5939e9a3..4876f79c20b 100644 --- a/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java +++ b/src/test/java/org/jabref/logic/layout/format/FileLinkTest.java @@ -1,12 +1,12 @@ package org.jabref.logic.layout.format; import org.jabref.logic.layout.ParamLayoutFormatter; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; public class FileLinkTest { @@ -14,7 +14,7 @@ public class FileLinkTest { private FileLinkPreferences prefs; @Before public void setUp() throws Exception { - prefs = JabRefPreferences.getInstance().getFileLinkPreferences(); + prefs = mock(FileLinkPreferences.class); } @Test diff --git a/src/test/java/org/jabref/logic/net/URLDownloadTest.java b/src/test/java/org/jabref/logic/net/URLDownloadTest.java index 8af5396a089..0f17db0851c 100644 --- a/src/test/java/org/jabref/logic/net/URLDownloadTest.java +++ b/src/test/java/org/jabref/logic/net/URLDownloadTest.java @@ -3,10 +3,9 @@ import java.io.File; import java.io.IOException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import org.jabref.preferences.JabRefPreferences; - import org.junit.Assert; import org.junit.Test; @@ -24,7 +23,7 @@ public void testStringDownload() throws IOException { URLDownload dl = new URLDownload(new URL("http://www.google.com")); Assert.assertTrue("google.com should contain google", - dl.asString(JabRefPreferences.getInstance().getDefaultEncoding()).contains("Google")); + dl.asString(StandardCharsets.UTF_8).contains("Google")); } @Test diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index f182e3bc568..286ceb28895 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -14,18 +14,18 @@ import java.util.Set; import org.jabref.JabRefMain; +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.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -35,11 +35,12 @@ public class OOBibStyleTest { private LayoutFormatterPreferences layoutFormatterPreferences; + private ImportFormatPreferences importFormatPreferences; @Before public void setUp() { - layoutFormatterPreferences = JabRefPreferences.getInstance() - .getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)); + layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test @@ -61,8 +62,7 @@ public void testAuthorYearAsFile() throws URISyntaxException, IOException { File defFile = Paths.get(JabRefMain.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile(); - OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, - JabRefPreferences.getInstance().getDefaultEncoding()); + OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); assertTrue(style.isValid()); assertFalse(style.isFromResource()); assertFalse(style.isBibtexKeyCiteMarkers()); @@ -139,7 +139,7 @@ public void testGetCitProperty() throws IOException { @Test public void testGetCitationMarker() throws IOException { Path testBibtexFile = Paths.get("src/test/resources/testbib/complex.bib"); - ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8)); + ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8)); OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); Map entryDBMap = new HashMap<>(); @@ -160,7 +160,7 @@ public void testGetCitationMarker() throws IOException { @Test public void testLayout() throws IOException { Path testBibtexFile = Paths.get("src/test/resources/testbib/complex.bib"); - ParserResult result = new BibtexParser(JabRefPreferences.getInstance().getImportFormatPreferences()).parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8)); + ParserResult result = new BibtexParser(importFormatPreferences).parse(Importer.getReader(testBibtexFile, StandardCharsets.UTF_8)); OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); BibDatabase db = result.getDatabase(); diff --git a/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java b/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java index ed35f45eb2c..2cd65802de0 100644 --- a/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java +++ b/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java @@ -2,23 +2,25 @@ import java.net.URISyntaxException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.layout.LayoutFormatterPreferences; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class StyleLoaderTest { @@ -32,10 +34,9 @@ public class StyleLoaderTest { @Before public void setUp() { - preferences = new OpenOfficePreferences(JabRefPreferences.getInstance()); - layoutPreferences = JabRefPreferences.getInstance() - .getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)); - encoding = JabRefPreferences.getInstance().getDefaultEncoding(); + preferences = mock(OpenOfficePreferences.class, Answers.RETURNS_DEEP_STUBS); + layoutPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); + encoding = StandardCharsets.UTF_8; } @@ -46,9 +47,8 @@ public void throwNPEWithNullPreferences() { } @Test(expected = NullPointerException.class) - public void throwNPEWithNullRepository() { - loader = new StyleLoader(mock(OpenOfficePreferences.class), - JabRefPreferences.getInstance().getLayoutFormatterPreferences(null), mock(Charset.class)); + public void throwNPEWithNullLayoutPreferences() { + loader = new StyleLoader(mock(OpenOfficePreferences.class), null, mock(Charset.class)); fail(); } @@ -90,7 +90,7 @@ public void testAddInvalidStyleLeadsToNoMoreStyle() { public void testInitalizeWithOneExternalFile() throws URISyntaxException { String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); - preferences.setExternalStyles(Collections.singletonList(filename)); + when(preferences.getExternalStyles()).thenReturn(Collections.singletonList(filename)); loader = new StyleLoader(preferences, layoutPreferences, encoding); assertEquals(numberOfInternalStyles + 1, loader.getStyles().size()); } @@ -107,7 +107,7 @@ public void testInitalizeWithIncorrectExternalFile() { public void testInitalizeWithOneExternalFileRemoveStyle() throws URISyntaxException { String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); - preferences.setExternalStyles(Collections.singletonList(filename)); + when(preferences.getExternalStyles()).thenReturn(Collections.singletonList(filename)); loader = new StyleLoader(preferences, layoutPreferences, encoding); List toremove = new ArrayList<>(); @@ -125,10 +125,11 @@ public void testInitalizeWithOneExternalFileRemoveStyle() throws URISyntaxExcept } @Test + @Ignore("This tests the preferences that are mocked away") public void testInitalizeWithOneExternalFileRemoveStyleUpdatesPreferences() throws URISyntaxException { String filename = Paths.get(StyleLoader.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) .toFile().getPath(); - preferences.setExternalStyles(Collections.singletonList(filename)); + when(preferences.getExternalStyles()).thenReturn(Collections.singletonList(filename)); loader = new StyleLoader(preferences, layoutPreferences, encoding); List toremove = new ArrayList<>(); @@ -165,6 +166,7 @@ public void testAddNullStyleThrowsNPE() { @Test public void testGetDefaultUsedStyleWhenEmpty() { + when(preferences.getCurrentStyle()).thenReturn(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH); preferences.clearCurrentStyle(); loader = new StyleLoader(preferences, layoutPreferences, encoding); OOBibStyle style = loader.getUsedStyle(); @@ -175,7 +177,7 @@ public void testGetDefaultUsedStyleWhenEmpty() { @Test public void testGetStoredUsedStyle() { - preferences.setCurrentStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH); + when(preferences.getCurrentStyle()).thenReturn(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH); loader = new StyleLoader(preferences, layoutPreferences, encoding); OOBibStyle style = loader.getUsedStyle(); assertTrue(style.isValid()); @@ -184,8 +186,9 @@ public void testGetStoredUsedStyle() { } @Test + @Ignore("This tests the preferences that are mocked away") public void testGtDefaultUsedStyleWhenIncorrect() { - preferences.setCurrentStyle("ljlkjlkjnljnvdlsjniuhwelfhuewfhlkuewhfuwhelu"); + when(preferences.getCurrentStyle()).thenReturn("ljlkjlkjnljnvdlsjniuhwelfhuewfhlkuewhfuwhelu"); loader = new StyleLoader(preferences, layoutPreferences, encoding); OOBibStyle style = loader.getUsedStyle(); assertTrue(style.isValid()); diff --git a/src/test/java/org/jabref/logic/util/io/FileHistoryTest.java b/src/test/java/org/jabref/logic/util/io/FileHistoryTest.java index 80a54d4d58e..280d24630c2 100644 --- a/src/test/java/org/jabref/logic/util/io/FileHistoryTest.java +++ b/src/test/java/org/jabref/logic/util/io/FileHistoryTest.java @@ -1,35 +1,17 @@ package org.jabref.logic.util.io; -import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; -import org.jabref.preferences.JabRefPreferences; - -import org.junit.After; -import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class FileHistoryTest { - private JabRefPreferences prefs; - private List oldFileNames; - - @Before - public void setUp() { - prefs = JabRefPreferences.getInstance(); - oldFileNames = prefs.getStringList(JabRefPreferences.RECENT_DATABASES); - } - - @After - public void restore() { - prefs.putStringList(JabRefPreferences.RECENT_DATABASES, oldFileNames); - } - @Test public void testFileHistory() { - FileHistory fh = prefs.getFileHistory(); + FileHistory fh = new FileHistory(new ArrayList<>()); fh.newFile("aa"); assertEquals("aa", fh.getFileName(0)); @@ -63,9 +45,8 @@ public void testFileHistory() { fh.removeItem("cc"); fh.removeItem("cc"); fh.removeItem("aa"); - prefs.storeFileHistory(fh); - assertArrayEquals(new String[] {"ii", "hh", "gg"}, - prefs.getStringList(JabRefPreferences.RECENT_DATABASES).toArray(new String[0])); + + assertEquals(Arrays.asList("ii", "hh", "gg"), fh.getHistory()); } } diff --git a/src/test/java/org/jabref/logic/util/io/FileUtilTest.java b/src/test/java/org/jabref/logic/util/io/FileUtilTest.java index 2739f3c1804..63e57cdcb18 100644 --- a/src/test/java/org/jabref/logic/util/io/FileUtilTest.java +++ b/src/test/java/org/jabref/logic/util/io/FileUtilTest.java @@ -11,16 +11,15 @@ import java.util.List; import java.util.Optional; -import org.jabref.logic.journals.JournalAbbreviationLoader; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.FileHelper; -import org.jabref.preferences.JabRefPreferences; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -36,12 +35,14 @@ public class FileUtilTest { private final Path nonExistingTestPath = Paths.get("nonExistingTestPath"); private Path existingTestFile; private Path otherExistingTestFile; + private LayoutFormatterPreferences layoutFormatterPreferences; @Before public void setUpViewModel() throws IOException { existingTestFile = createTemporaryTestFile("existingTestFile.txt"); otherExistingTestFile = createTemporaryTestFile("otherExistingTestFile.txt"); otherTemporaryFolder.create(); + layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); } @Test @@ -65,8 +66,7 @@ public void testGetLinkedFileNameDefault() { entry.setField("title", "mytitle"); assertEquals("1234 - mytitle", - FileUtil.createFileNameFromPattern(null, entry, fileNamePattern, JabRefPreferences.getInstance() - .getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)))); + FileUtil.createFileNameFromPattern(null, entry, fileNamePattern, layoutFormatterPreferences)); } @Test @@ -79,7 +79,7 @@ public void testGetLinkedFileNameBibTeXKey() { assertEquals("1234", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern, - mock(LayoutFormatterPreferences.class))); + layoutFormatterPreferences)); } @Test @@ -90,7 +90,7 @@ public void testGetLinkedFileNameNoPattern() { entry.setField("title", "mytitle"); assertEquals("1234", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern, - mock(LayoutFormatterPreferences.class))); + layoutFormatterPreferences)); } @Test @@ -100,7 +100,7 @@ public void testGetDefaultFileNameNoPatternNoBibTeXKey() { entry.setField("title", "mytitle"); assertEquals("default", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern, - mock(LayoutFormatterPreferences.class))); + layoutFormatterPreferences)); } @Test @@ -111,7 +111,7 @@ public void testGetLinkedFileNameGetKeyIfEmptyField() { entry.setCiteKey("1234"); assertEquals("1234", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern, - JabRefPreferences.getInstance().getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)))); + layoutFormatterPreferences)); } @Test @@ -121,7 +121,7 @@ public void testGetLinkedFileNameGetDefaultIfEmptyFieldNoKey() { BibEntry entry = new BibEntry(); assertEquals("default", FileUtil.createFileNameFromPattern(null, entry, fileNamePattern, - JabRefPreferences.getInstance().getLayoutFormatterPreferences(mock(JournalAbbreviationLoader.class)))); + layoutFormatterPreferences)); } @Test diff --git a/src/test/java/org/jabref/logic/xmp/XMPUtilTest.java b/src/test/java/org/jabref/logic/xmp/XMPUtilTest.java index 5885b3a603b..6f65bab0b64 100644 --- a/src/test/java/org/jabref/logic/xmp/XMPUtilTest.java +++ b/src/test/java/org/jabref/logic/xmp/XMPUtilTest.java @@ -31,6 +31,7 @@ import org.jabref.cli.XMPUtilMain; import org.jabref.logic.bibtex.BibEntryWriter; import org.jabref.logic.bibtex.LatexFieldFormatter; +import org.jabref.logic.bibtex.LatexFieldFormatterPreferences; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; @@ -38,7 +39,6 @@ import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibtexEntryTypes; -import org.jabref.preferences.JabRefPreferences; import com.google.common.io.CharStreams; import org.apache.jempbox.xmp.XMPMetadata; @@ -52,12 +52,15 @@ import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDMetadata; import org.apache.pdfbox.util.XMLUtil; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.Answers; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Limitations: The test suite only handles UTF8. Not UTF16. @@ -71,12 +74,6 @@ public class XMPUtilTest { */ private File pdfFile; - private JabRefPreferences prefs; - - private boolean use; - - private List privacyFilters; - private XMPPreferences xmpPreferences; @@ -140,7 +137,7 @@ public void writeManually(File tempFile, String xmpString) throws IOException, C } } - public static BibEntry bibtexString2BibtexEntry(String s, ImportFormatPreferences importFormatPreferences) + private static BibEntry bibtexString2BibtexEntry(String s, ImportFormatPreferences importFormatPreferences) throws IOException { ParserResult result = new BibtexParser(importFormatPreferences).parse(new StringReader(s)); Collection c = result.getDatabase().getEntries(); @@ -148,14 +145,14 @@ public static BibEntry bibtexString2BibtexEntry(String s, ImportFormatPreference return c.iterator().next(); } - public static String bibtexEntry2BibtexString(BibEntry e, JabRefPreferences preferences) throws IOException { + private static String bibtexEntry2BibtexString(BibEntry e) throws IOException { StringWriter sw = new StringWriter(); - new BibEntryWriter(new LatexFieldFormatter(preferences.getLatexFieldFormatterPreferences()), + new BibEntryWriter(new LatexFieldFormatter(mock(LatexFieldFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS)), false).write(e, sw, BibDatabaseMode.BIBTEX); return sw.getBuffer().toString(); } - public String t1BibtexString() { + private String t1BibtexString() { return "@article{canh05,\n" + " author = {Crowston, K. and Annabi, H. and Howison, J. and Masango, C.},\n" + " title = {Effective work practices for floss development: A model and propositions},\n" + " booktitle = {Hawaii International Conference On System Sciences (HICSS)},\n" + " year = {2005},\n" @@ -163,11 +160,11 @@ public String t1BibtexString() { + " url = {http://james.howison.name/publications.html}}\n"; } - public BibEntry t1BibtexEntry() throws IOException { + private BibEntry t1BibtexEntry() throws IOException { return XMPUtilTest.bibtexString2BibtexEntry(t1BibtexString(), importFormatPreferences); } - public String t2XMP() { + private String t2XMP() { return "\n" + "YeKis03 - Towards.pdf\n" + "\n"; } - public String t2BibtexString() throws IOException { - return XMPUtilTest.bibtexEntry2BibtexString(t2BibtexEntry(), prefs); + private String t2BibtexString() throws IOException { + return XMPUtilTest.bibtexEntry2BibtexString(t2BibtexEntry()); } - public BibEntry t2BibtexEntry() { + private BibEntry t2BibtexEntry() { BibEntry e = new BibEntry(BibtexEntryTypes.INCOLLECTION.getName()); e.setField("title", "�pt�mz�t��n"); e.setField("bibtexkey", "OezbekC06"); @@ -190,7 +187,7 @@ public BibEntry t2BibtexEntry() { return e; } - public BibEntry t3BibtexEntry() { + private BibEntry t3BibtexEntry() { BibEntry e = new BibEntry(); e.setType(BibtexEntryTypes.INPROCEEDINGS); e.setField("title", "Hypersonic ultra-sound"); @@ -209,7 +206,7 @@ public BibEntry t3BibtexEntry() { } public String t3BibtexString() throws IOException { - return XMPUtilTest.bibtexEntry2BibtexString(t3BibtexEntry(), prefs); + return XMPUtilTest.bibtexEntry2BibtexString(t3BibtexEntry()); } public String t3XMP() { @@ -239,23 +236,13 @@ public void setUp() throws IOException, COSVisitorException { pdf.save(pdfFile.getAbsolutePath()); } - // Store Privacy Settings - prefs = JabRefPreferences.getInstance(); - - use = prefs.getBoolean(JabRefPreferences.USE_XMP_PRIVACY_FILTER); - privacyFilters = prefs.getStringList(JabRefPreferences.XMP_PRIVACY_FILTERS); - + importFormatPreferences = mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS); + when(importFormatPreferences.getEncoding()).thenReturn(StandardCharsets.UTF_8); + xmpPreferences = mock(XMPPreferences.class); // The code assumes privacy filters to be off - prefs.putBoolean("useXmpPrivacyFilter", false); - - importFormatPreferences = prefs.getImportFormatPreferences(); - xmpPreferences = prefs.getXMPPreferences(); - } + when(xmpPreferences.isUseXMPPrivacyFilter()).thenReturn(false); - @After - public void tearDown() { - prefs.putBoolean(JabRefPreferences.USE_XMP_PRIVACY_FILTER, use); - prefs.putStringList(JabRefPreferences.XMP_PRIVACY_FILTERS, privacyFilters); + when(xmpPreferences.getKeywordSeparator()).thenReturn(','); } /** @@ -316,34 +303,14 @@ public void testReadXMPUTF8() throws COSVisitorException, IOException { */ @Test public void testPrivacyFilter() throws IOException, TransformerException { - - { - BibEntry e = t1BibtexEntry(); - - prefs.putBoolean("useXmpPrivacyFilter", true); - prefs.putStringList(JabRefPreferences.XMP_PRIVACY_FILTERS, Arrays.asList("author", "title", "note")); - - XMPUtil.writeXMP(pdfFile, e, null, prefs.getXMPPreferences()); - - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), prefs.getXMPPreferences()); - Assert.assertEquals(1, l.size()); - BibEntry x = l.get(0); - - Set expectedFields = new HashSet<>( - Arrays.asList("bibtexkey", "booktitle", "owner", "timestamp", "url", "year")); - - Assert.assertEquals(expectedFields, x.getFieldNames()); - } - // First set: - prefs.putBoolean("useXmpPrivacyFilter", true); - prefs.putStringList(JabRefPreferences.XMP_PRIVACY_FILTERS, - Arrays.asList("author;title;note;booktitle;year;owner;timestamp")); + when(xmpPreferences.isUseXMPPrivacyFilter()).thenReturn(true); + when(xmpPreferences.getXmpPrivacyFilter()).thenReturn(Arrays.asList("author;title;note;booktitle;year;owner;timestamp")); BibEntry e = t1BibtexEntry(); - XMPUtil.writeXMP(pdfFile, e, null, prefs.getXMPPreferences()); + XMPUtil.writeXMP(pdfFile, e, null, xmpPreferences); - List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), prefs.getXMPPreferences()); + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); Assert.assertEquals(1, l.size()); BibEntry x = l.get(0); Set ts = x.getFieldNames(); @@ -353,7 +320,25 @@ public void testPrivacyFilter() throws IOException, TransformerException { Assert.assertTrue(ts.contains("bibtexkey")); Assert.assertTrue(ts.contains("year")); Assert.assertTrue(ts.contains("url")); + } + + @Test + public void testPrivacyFilter2() throws Exception { + BibEntry e = t1BibtexEntry(); + + when(xmpPreferences.isUseXMPPrivacyFilter()).thenReturn(true); + when(xmpPreferences.getXmpPrivacyFilter()).thenReturn(Arrays.asList("author", "title", "note")); + + XMPUtil.writeXMP(pdfFile, e, null, xmpPreferences); + + List l = XMPUtil.readXMP(pdfFile.getAbsoluteFile(), xmpPreferences); + Assert.assertEquals(1, l.size()); + BibEntry x = l.get(0); + + Set expectedFields = new HashSet<>( + Arrays.asList("bibtexkey", "booktitle", "owner", "timestamp", "url", "year")); + Assert.assertEquals(expectedFields, x.getFieldNames()); } /**