def test_log_append_true(tmp_path): """run 5 times, append to log each time""" def side_effect(*_args, **_kwargs): return None repeat = 5 new_session_msg = "New ansible-navigator instance" log_file = tmp_path / "ansible-navigator.log" cli_args = [ "ansible-navigator", "--la", "true", "--lf", str(log_file), "--ll", "info", ] with mock.patch("sys.argv", cli_args): with mock.patch("ansible_navigator.cli.wrapper") as mocked_wrapper: mocked_wrapper.side_effect = side_effect for _ in range(repeat): cli.main() # prevent multiple handlers cli.logger.handlers.clear() assert log_file.read_text().count(new_session_msg) == repeat
def run_test(self, mocked_runner, tmpdir, cli_entry, config_fixture, expected): # pylint: disable=too-many-arguments """mock the runner call so it raises an exception mock the command line with ``sys.argv`` set the ANSIBLE_NAVIGATOR_CONFIG environment variable set the expected environmental variables call ``cli.main()``, check the ``envvars`` argument passed to the runner function """ mocked_runner.side_effect = Exception("called") cfg_path = f"{self.TEST_FIXTURE_DIR}/{config_fixture}" coll_cache_path = os.path.join(tmpdir, "collection_doc_cache.db") assert os.path.exists(cfg_path) params = shlex.split(cli_entry) + ["--pp", "never"] with mock.patch("sys.argv", params): with mock.patch.dict(os.environ, {"ANSIBLE_NAVIGATOR_CONFIG": cfg_path}): with mock.patch.dict(os.environ, { "ANSIBLE_NAVIGATOR_COLLECTION_DOC_CACHE_PATH": coll_cache_path }): with mock.patch.dict(os.environ, expected): with pytest.raises(Exception, match="called"): cli.main() _args, kwargs = mocked_runner.call_args for item in expected.items(): assert item in kwargs["envvars"].items()
def test(data: Scenario, monkeypatch: pytest.MonkeyPatch, tmp_path: Path): """Start with the CLI, create log messages and count. :param data: The test data :param monkeypatch: The monkeypatch fixture :param tmp_path: A temporary file path """ def return_none(*_args, **_kwargs) -> None: """Take no action, return none. :param _args: Arguments :param _kwargs: Keyword arguments :returns: Nothing """ return None new_session_msg = "New ansible-navigator instance" log_file = tmp_path / "ansible-navigator.log" args = data.args(log_file=log_file) monkeypatch.setattr("sys.argv", args) monkeypatch.setattr("ansible_navigator.cli.wrapper", return_none) for _ in range(data.repeat): cli.main() # prevent multiple handlers cli.logger.handlers.clear() assert log_file.read_text().count(new_session_msg) == data.session_count
def test_for_version_logged( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: Path, ): """Ensure the version is captured in the log. :param monkeypatch: The monkey patch fixture :param caplog: The log capture fixture :param tmp_path: A temporary director for this test """ logfile = tmp_path / "log.txt" command_line = [ "ansible-navigator", "exec", "ls", "--ll", "debug", "--lf", str(logfile), "--pp", "never", ] monkeypatch.setattr("sys.argv", command_line) with pytest.raises(SystemExit): # A SystemExit happens here because the container vanishes quickly main() assert "ansible-navigator==" in caplog.text assert "ansible-runner==" in caplog.text
def test_for_duplicates_sources( doc_cache_path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, mocker, ): """Ensure duplicate volume mounts are not passed to runner. :param doc_cache_path: The test data :param patch_curses: Fixture to patch curses so it doesn't traceback :param monkeypatch: The monkeypatch fixture :param arg_collector: The fixture used to collect argument passed to a function """ working_dir = tmp_path / "working_dir" working_dir.mkdir() cdc_full_path = working_dir / doc_cache_path.path command = f"ansible-navigator collections '--cdcp={cdc_full_path!s}' --pp never" monkeypatch.setattr("sys.argv", shlex.split(command)) run_cmd_mocked = mocker.patch( "ansible_navigator.runner.command.run_command", side_effect=DuplicateMountException, ) monkeypatch.chdir(working_dir) monkeypatch.setenv("ANSIBLE_NAVIGATOR_ALLOW_UI_TRACEBACK", "true") with pytest.raises(DuplicateMountException): cli.main() _args, kwargs = run_cmd_mocked.call_args host_cwd = Path(kwargs["host_cwd"]) mounts = kwargs["container_volume_mounts"] sources = [Path(mount.split(":")[0]).parents[0] for mount in mounts] assert host_cwd not in sources
def run_test(self, mocked_runner, cli_entry, config_fixture, expected): """mock the runner call so it raises an exception mock the command line with sys.argv set the ANSIBLE_NAVIGATOR_CONFIG envvar call cli.main(), check the kwarg envvars passed to the runner func """ mocked_runner.side_effect = Exception("called") with mock.patch("sys.argv", cli_entry.split()): cfg_path = f"{self.TEST_FIXTURE_DIR}/{config_fixture}" assert os.path.exists(cfg_path) with mock.patch.dict(os.environ, {"ANSIBLE_NAVIGATOR_CONFIG": cfg_path}): with pytest.raises(Exception, match="called"): cli.main() _args, kwargs = mocked_runner.call_args for item in expected.items(): assert item in kwargs["envvars"].items()
def run_test( self, mocked_runner: "MagicMock", monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cli_entry: str, config_fixture: str, expected: Dict[str, str], ): # pylint: disable=too-many-arguments """Confirm execution of ``cli.main()`` produces the desired results. :param mocked_runner: A patched instance of runner :param monkeypatch: The monkey patch fixture :param tmp_path: A test specific temporary path :param cli_entry: The CLI entry to set as ``sys.argv`` :param config_fixture: The settings fixture :param expected: the expected return value """ cfg_path = f"{self.TEST_FIXTURE_DIR}/{config_fixture}" coll_cache_path = tmp_path / "collection_doc_cache.db" assert os.path.exists(cfg_path) params = shlex.split(cli_entry) + ["--pp", "never"] monkeypatch.setattr("sys.argv", params) monkeypatch.setenv("ANSIBLE_NAVIGATOR_CONFIG", cfg_path) monkeypatch.setenv("ANSIBLE_NAVIGATOR_COLLECTION_DOC_CACHE_PATH", str(coll_cache_path)) monkeypatch.chdir(tmp_path) for env_var, value in expected.items(): monkeypatch.setenv(env_var, value) with pytest.raises(RunnerTestException): cli.main() _args, kwargs = mocked_runner.call_args for item in expected.items(): assert item in kwargs["envvars"].items() # cspell:ignore envvars
def test( data: Scenario, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ): """Start with the CLI, create log messages and match the time zone. :param caplog: The log capture fixture :param data: The test data :param monkeypatch: The monkeypatch fixture :param tmp_path: A temporary file path """ def return_none(*_args, **_kwargs) -> None: """Take no action, return none. :param _args: Arguments :param _kwargs: Keyword arguments :returns: Nothing """ return None log_file = tmp_path / "ansible-navigator.log" args = data.args(log_file=log_file) monkeypatch.setattr("sys.argv", args) monkeypatch.setattr("ansible_navigator.cli.wrapper", return_none) if data.will_exit: with pytest.raises(SystemExit): cli.main() else: cli.main() # This is a conservative number based on debug logging, it should be closer to 200 # but this assertion is here to ensure many records were retrieved. assert len(caplog.records) > 100 assert all( data.re_match.match(record.asctime) for record in caplog.records)