def test_rename_associated_file(self, setup: Any, preserve_files: bool) -> None: """Test removing associated files. Args: setup: the `tests.commands.command_test.CommandTest.setup` fixture. preserve_files: argument to `DeleteCommand`. """ try: config.commands.edit.editor = "sed -i 's/einstein:/dummy:/'" with tempfile.TemporaryDirectory() as tmpdirname: path = RelPath(tmpdirname + "/einstein.pdf") open( # pylint: disable=consider-using-with path.path, "w", encoding="utf-8").close() Database()["einstein"].file = str(path) args = ["einstein"] if preserve_files: args.insert(2, "--preserve-files") EditCommand().execute(args) assert "dummy" in Database().keys() target = RelPath(tmpdirname + "/dummy.pdf") if preserve_files: assert path.path.exists() else: assert target.path.exists() finally: config.defaults()
def setup() -> None: """Set linting database path. This fixture is automatically enabled for all tests in this class. """ config.defaults() config.database.file = str(TestLintDatabase.REL_PATH)
def test_handle_argument_error(self, caplog: pytest.LogCaptureFixture) -> None: """Test handling of ArgumentError. Args: caplog: the built-in pytest fixture. """ # use temporary config config.database.file = self.COBIB_TEST_DIR / "database.yaml" config.database.git = True # load temporary database os.makedirs(self.COBIB_TEST_DIR, exist_ok=True) copyfile(get_resource("example_literature.yaml"), config.database.file) Database().read() try: super().test_handle_argument_error(caplog) finally: # clean up file system os.remove(config.database.file) # clean up database Database().clear() # clean up config config.defaults()
def test_handle_argument_error(self, caplog: pytest.LogCaptureFixture) -> None: """Test handling of ArgumentError. Args: caplog: the built-in pytest fixture. """ # use temporary config config.database.file = self.COBIB_TEST_DIR / "database.yaml" config.database.git = True # initialize git-tracking self.COBIB_TEST_DIR.mkdir(parents=True, exist_ok=True) open( # pylint: disable=consider-using-with config.database.file, "w", encoding="utf-8").close() os.system("git init " + str(self.COBIB_TEST_DIR)) try: super().test_handle_argument_error(caplog) finally: # clean up file system rmtree(self.COBIB_TEST_DIR_GIT) # clean up config config.defaults()
def test_download_with_url_map(setup_remove_content_length: Any) -> None: """Test the `config.utils.file_downloader.url_map` usage. We use a Quantum Journal article because they are open-source and, thus, do not require a Proxy to get access to. Args: setup_remove_content_length: a custom fixture. """ try: config.load(get_resource("debug.py")) with tempfile.TemporaryDirectory() as tmpdirname: try: # ensure file does not exist yet remove(tmpdirname + "/dummy.pdf") except FileNotFoundError: pass path = FileDownloader().download( "https://quantum-journal.org/papers/q-2021-06-17-479/", "dummy", tmpdirname, ) if path is None: pytest.skip("Likely, a requests error occured.") assert path.path.exists() with open(path.path, "rb") as file: assert file.read().startswith(bytes("%PDF", "utf-8")) finally: config.defaults()
def setup() -> None: """Setup debugging config. This fixture is automatically enabled for all tests in this class. """ config.defaults() config.load(get_resource("debug.py"))
def setup() -> None: """Set linting database path. This fixture is automatically enabled for all tests in this class. """ config.defaults() config.database.format.label_default = "{author.split()[1]}{year}" config.database.file = str(TestUnifyLabels.REL_PATH)
def setup() -> Generator[Any, None, None]: """Setup debugging configuration. Yields: Access to the local fixture variables. """ config.load(get_resource("debug.py")) yield setup config.clear() config.defaults()
def setup() -> Generator[Any, None, None]: """Setup debugging configuration. This method also clears the `Database` after each test run. It is automatically enabled for all tests in this file. Yields: Access to the local fixture variables. """ config.load(get_resource("debug.py")) yield Database().clear() config.defaults()
def test_from_yaml_file(self, use_c_lib_yaml: bool) -> None: """Test parsing a yaml file. Args: use_c_lib_yaml: the configuration setting. """ try: config.parsers.yaml.use_c_lib_yaml = use_c_lib_yaml reference = self.EXAMPLE_ENTRY_DICT.copy() entries = YAMLParser().parse(self.EXAMPLE_YAML_FILE) entry = list(entries.values())[0] assert entry.data == reference finally: config.defaults()
def test_view_with_ansi_map(self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch) -> None: """Test `cobib.tui.buffer.TextBuffer.view` with an ANSI color map. Args: caplog: the built-in pytest fixture. monkeypatch: the built-in pytest fixture. """ monkeypatch.setattr("curses.color_pair", lambda *args: args) # create ANSI color map for testing purposes config.defaults() ansi_map = {} for attr in TUI.COLOR_NAMES: ansi_map[config.get_ansi_color( attr)] = TUI.COLOR_NAMES.index(attr) + 1 # populate buffer self.buffer.lines = [ "\x1b[31;40mLabel0\x1b[0m Title0 by Author0", "\x1b[31;40mLabel1\x1b[0m Title1 by Author1", "\x1b[31;40mLabel2\x1b[0m Title2 by Author2", "\x1b[31;40mLabel3\x1b[0m Title3 by Author3", "\x1b[31;40mLabel4\x1b[0m Title4 by Author4", ] pad = MockCursesPad() self.buffer.view(pad, 10, 40, ansi_map=ansi_map) expected_log = [ ("MockCursesPad", 10, "erase"), ("MockCursesPad", 10, "refresh: 0 0 1 0 10 40"), ("MockCursesPad", 10, "resize: 1 41"), ("MockCursesPad", 10, "addstr: 0 0 Label0 Title0 by Author0"), ("MockCursesPad", 10, "chgat: 0 0 6 (4,)"), ("MockCursesPad", 10, "addstr: 1 0 Label1 Title1 by Author1"), ("MockCursesPad", 10, "chgat: 1 0 6 (4,)"), ("MockCursesPad", 10, "addstr: 2 0 Label2 Title2 by Author2"), ("MockCursesPad", 10, "chgat: 2 0 6 (4,)"), ("MockCursesPad", 10, "addstr: 3 0 Label3 Title3 by Author3"), ("MockCursesPad", 10, "chgat: 3 0 6 (4,)"), ("MockCursesPad", 10, "addstr: 4 0 Label4 Title4 by Author4"), ("MockCursesPad", 10, "chgat: 4 0 6 (4,)"), ("MockCursesPad", 10, "refresh: 0 0 1 0 10 40"), ] assert [ record for record in caplog.record_tuples if record[0] == "MockCursesPad" ] == expected_log for message in [ "Interpreting ANSI color codes on the fly.", "Applying ANSI color map." ]: assert ("cobib.tui.buffer", 10, message) in caplog.record_tuples
def test_cache(self) -> None: """Test caching behavior.""" try: config.logging.cache = str(Path(tempfile.gettempdir()) / "cache") imported_entries = ZoteroImporter().fetch(["--user-id", "8608002"], skip_download=True) self._assert_results(imported_entries) with open(config.logging.cache, "r", encoding="utf-8") as cache: cached_data = json.load(cache) assert "Zotero" in cached_data.keys() assert "UserID" in cached_data["Zotero"].keys() assert cached_data["Zotero"]["UserID"] == "8608002" finally: config.defaults()
def setup() -> Generator[Any, None, None]: """Setup. This fixture is automatically enabled for all tests in this class. Yields: This method yields control to the actual test after which it will tear down the setup. """ # pylint: disable=attribute-defined-outside-init config.load(get_resource("debug.py")) original_keydict = copy.deepcopy(TUI.KEYDICT) yield # clean up config config.defaults() STATE.reset() TUI.KEYDICT = copy.deepcopy(original_keydict)
def test_scroll_y( self, caplog: pytest.LogCaptureFixture, initialize: Tuple[int, int], update: Union[int, str], repeat: int, top: int, cur: int, msg: str, scrolloff: Optional[int], ) -> None: """Test `cobib.tui.frame.Frame.scroll_y`. Args: caplog: the built-in pytest fixture. initialize: the initial values for `cobib.tui.state.State.top_line` and `cobib.tui.state.State.current_line`. update: the argument to send to `cobib.tui.frame.Frame.scroll_y`. repeat: the number of times to repeat the update. top: the expected value for `cobib.tui.state.State.top_line`. cur: the expected value for `cobib.tui.state.State.current_line`. msg: the expected message to be logged. scrolloff: the configuration value for `config.tui.scroll_offset`. """ config.defaults() if scrolloff: config.tui.scroll_offset = scrolloff self.frame.buffer.height = 20 self.frame.buffer.lines = ["Many lines" for _ in range(20)] STATE.reset() STATE.top_line = initialize[0] STATE.current_line = initialize[1] for _ in range(repeat): self.frame.scroll_y(update) assert ("cobib.tui.frame", 10, msg) in caplog.record_tuples assert STATE.top_line == top assert STATE.current_line == cur
def test_state_initialize(reverse_order: bool) -> None: """Test config-dependent state-initialization. Args: reverse_order: whether to add the `--reverse` flag to the `default_list_args`. """ config.tui.reverse_order = reverse_order state = copy.deepcopy(STATE) state.initialize() try: assert state.top_line == 0 assert state.left_edge == 0 assert state.current_line == 0 assert state.previous_line == -1 assert state.mode == Mode.LIST.value assert state.inactive_commands == [] assert state.topstatus == "" state.list_args = config.tui.default_list_args if config.tui.reverse_order: state.list_args += ["-r"] finally: config.defaults()
def setup( self, request: _pytest.fixtures.SubRequest ) -> Generator[Dict[str, Any], None, None]: """Setup testing environment. This method takes care of setting up the testing configuration. This involves: - using `cat` for `config.commands.edit.editor` and `config.commands.open.command` - setting up a testing database based (if requested by `request.param["database"]`) - initializing git tracking (if requested by `request.param["git"]`) After yielding to the actual test, this setup also gets torn down. Args: request: a pytest sub-request providing access to nested parameters. Yields: The internally used parameters for potential later re-use during the actual test. """ if not hasattr(request, "param"): # use default settings request.param = {"git": False, "database": True} # use temporary config config.commands.edit.editor = "cat" config.commands.open.command = "cat" config.database.file = str(self.COBIB_TEST_DIR / "database.yaml") config.database.git = request.param.get("git", False) config.utils.file_downloader.default_location = "/tmp" config.logging.version = None # load database if request.param.get("database", True): self.COBIB_TEST_DIR.mkdir(parents=True, exist_ok=True) copyfile(get_resource("example_literature.yaml"), config.database.file) Database().read() if request.param.get("git", True): root = self.COBIB_TEST_DIR msg = "Initial commit" commands = [ f"cd {root}", "git init", "git add -- database.yaml", f"git commit --no-gpg-sign --quiet --message {shlex.quote(msg)}", ] os.system("; ".join(commands)) yield request.param # clean up file system try: os.remove(config.database.file) if request.param.get("git", False): rmtree(self.COBIB_TEST_DIR_GIT) # remove all handlers from root logger as to not accumulate them during the test suite logging.getLogger().handlers = [] except FileNotFoundError: pass # clean up database if request.param.get("database", True): Database().clear() # clean up config config.defaults()
def setup(self) -> None: # pylint: disable=no-self-use """Setup.""" config.defaults()