From 0211ce6eb59172128742fbf35e17ba54db2795dc Mon Sep 17 00:00:00 2001 From: Shatakshi Mishra Date: Mon, 27 May 2024 16:29:06 +0530 Subject: [PATCH 1/2] Address ruff COM (#1775) --- pyproject.toml | 1 - src/ansible_navigator/action_base.py | 5 +++- src/ansible_navigator/actions/collections.py | 9 ++++--- src/ansible_navigator/actions/images.py | 11 ++++++--- .../command_runner/command_runner.py | 3 ++- .../configuration_subsystem/definitions.py | 3 ++- .../navigator_post_processor.py | 14 +++++++---- .../data/catalog_collections.py | 6 +++-- .../data/image_introspect.py | 9 +++++-- src/ansible_navigator/runner/command_async.py | 6 ++++- src/ansible_navigator/ui_framework/form.py | 3 ++- .../ui_framework/form_handler_options.py | 4 +++- src/ansible_navigator/ui_framework/ui.py | 5 +++- src/ansible_navigator/utils/print.py | 2 +- tests/conftest.py | 5 ++-- tests/integration/_tmux_session.py | 4 +++- tests/integration/actions/builder/base.py | 3 ++- tests/integration/actions/config/base.py | 3 ++- .../doc/test_welcome_interactive_ee.py | 14 +++++++++-- .../doc/test_welcome_interactive_noee.py | 14 +++++++++-- .../replay/test_welcome_interactive_ee.py | 6 ++++- .../replay/test_welcome_interactive_noee.py | 6 ++++- tests/integration/actions/settings/base.py | 3 ++- tests/unit/actions/run/test_artifact.py | 24 +++++++++---------- .../unit/configuration_subsystem/conftest.py | 4 +++- tests/unit/configuration_subsystem/data.py | 10 ++++++-- .../post_processors/test_inventory.py | 4 +++- .../test_ansible_config_parse.py | 8 +++++-- .../test_container_engine_auto.py | 9 ++++--- .../test_invalid_params.py | 3 ++- .../test_presentable.py | 6 +++-- tests/unit/image_manager/test_image_puller.py | 15 +++++++++--- tests/unit/logger/test_time_zone.py | 5 ++-- tests/unit/test_cli.py | 15 ++++++++---- tests/unit/utils/test_dockerfile.py | 2 +- tests/unit/utils/test_unserializable.py | 4 ++-- 36 files changed, 176 insertions(+), 72 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index b2afb79315..ba50d81f13 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -277,7 +277,6 @@ ignore = [ 'C409', # [*] Unnecessary `list` literal passed to `tuple()` (rewrite as a `tuple` literal) 'C414', # [*] Unnecessary `list` call within `sorted()` 'C901', # `_params_row_for_entry` is too complex (11 > 10) - 'COM812', # [*] Trailing comma missing 'D100', # Missing docstring in public module 'D101', # Missing docstring in public class 'D102', # Missing docstring in public method diff --git a/src/ansible_navigator/action_base.py b/src/ansible_navigator/action_base.py index 7a18289fc4..329a9d373c 100644 --- a/src/ansible_navigator/action_base.py +++ b/src/ansible_navigator/action_base.py @@ -34,7 +34,10 @@ class ActionBase: """Base class for actions.""" def __init__( - self, args: ApplicationConfiguration, name: str, logger_name: str = __name__ + self, + args: ApplicationConfiguration, + name: str, + logger_name: str = __name__, ) -> None: """Initialize the App class. diff --git a/src/ansible_navigator/actions/collections.py b/src/ansible_navigator/actions/collections.py index 70c68a1d81..1f4de0d3e9 100644 --- a/src/ansible_navigator/actions/collections.py +++ b/src/ansible_navigator/actions/collections.py @@ -463,13 +463,15 @@ def _run_runner(self) -> None: mount_doc_cache = True # Determine if the doc_cache is relative to the cache directory if path_is_relative_to( - child=Path(self._args.collection_doc_cache_path), parent=(cache_path) + child=Path(self._args.collection_doc_cache_path), + parent=(cache_path), ): mount_doc_cache = False # The playbook directory will be mounted as host_cwd, so don't duplicate if path_is_relative_to( - child=Path(self._args.collection_doc_cache_path), parent=(Path(playbook_dir)) + child=Path(self._args.collection_doc_cache_path), + parent=(Path(playbook_dir)), ): mount_doc_cache = False @@ -600,7 +602,8 @@ def _parse(self, output: str) -> None: return def _get_collection_plugins_details( - self, selected_collection: dict[str, Any] + self, + selected_collection: dict[str, Any], ) -> dict[str, Any]: """Get plugin details for the given collection. diff --git a/src/ansible_navigator/actions/images.py b/src/ansible_navigator/actions/images.py index c050dc1e38..1674e31161 100644 --- a/src/ansible_navigator/actions/images.py +++ b/src/ansible_navigator/actions/images.py @@ -97,7 +97,10 @@ def color_menu(self, colno: int, colname: str, entry: dict[str, Any]) -> tuple[i return 2, 0 def generate_content_heading( - self, obj: dict[Any, Any], screen_w: int, name: str = "" + self, + obj: dict[Any, Any], + screen_w: int, + name: str = "", ) -> CursesLines: """Create a heading for image content. @@ -469,7 +472,7 @@ def _collect_image_list(self) -> None: config_label_check = False image["execution_environment"] = any( - (legacy_check, root_label_check, config_label_check) + (legacy_check, root_label_check, config_label_check), ) self._images.value = sorted(images, key=lambda i: i["name"]) @@ -574,7 +577,9 @@ def _run_runner(self, image_name: str) -> tuple[str, str, int]: kwargs.update({"container_options": self._args.container_options}) self._logger.debug( - "Invoke runner with executable_cmd: %s and kwargs: %s", python_exec_path, kwargs + "Invoke runner with executable_cmd: %s and kwargs: %s", + python_exec_path, + kwargs, ) _runner = Command(executable_cmd=python_exec_path, **kwargs) output, error, return_code = _runner.run() diff --git a/src/ansible_navigator/command_runner/command_runner.py b/src/ansible_navigator/command_runner/command_runner.py index c7b257bbf1..8daed6d244 100644 --- a/src/ansible_navigator/command_runner/command_runner.py +++ b/src/ansible_navigator/command_runner/command_runner.py @@ -79,7 +79,8 @@ def run_command(command: Command) -> None: def worker( - pending_queue: multiprocessing.Queue[Any], completed_queue: multiprocessing.Queue[Any] + pending_queue: multiprocessing.Queue[Any], + completed_queue: multiprocessing.Queue[Any], ) -> None: """Read pending, run, post process, and place in completed. diff --git a/src/ansible_navigator/configuration_subsystem/definitions.py b/src/ansible_navigator/configuration_subsystem/definitions.py index 207c9fc885..87f7fa3e8a 100644 --- a/src/ansible_navigator/configuration_subsystem/definitions.py +++ b/src/ansible_navigator/configuration_subsystem/definitions.py @@ -472,7 +472,8 @@ class PaeChangeRequest: # A type used for the settings as a dictionary SettingsFileType = NewType( - "SettingsFileType", dict[str, bool | dict[Any, Any] | int | str | list[Any]] + "SettingsFileType", + dict[str, bool | dict[Any, Any] | int | str | list[Any]], ) # A type used to describe a schema file for the settings diff --git a/src/ansible_navigator/configuration_subsystem/navigator_post_processor.py b/src/ansible_navigator/configuration_subsystem/navigator_post_processor.py index 0986bde2ca..7de7ca2bd9 100644 --- a/src/ansible_navigator/configuration_subsystem/navigator_post_processor.py +++ b/src/ansible_navigator/configuration_subsystem/navigator_post_processor.py @@ -253,7 +253,9 @@ def display_color( @_post_processor def execution_environment( - self, entry: SettingsEntry, config: ApplicationConfiguration + self, + entry: SettingsEntry, + config: ApplicationConfiguration, ) -> PostProcessorReturn: # pylint: disable=too-many-locals """Post process execution_environment. @@ -497,8 +499,9 @@ def _disable_pae_and_enforce_stdout( self._requested_mode.append(ModeChangeRequest(entry=entry.name, mode=mode)) self._requested_pae.append( PaeChangeRequest( - entry=entry.name, playbook_artifact_enable=playbook_artifact_enable - ) + entry=entry.name, + playbook_artifact_enable=playbook_artifact_enable, + ), ) message = ( f"`{entry.name} requesting mode {mode.value} and pae as {playbook_artifact_enable}" @@ -673,7 +676,7 @@ def lintables( except subprocess.CalledProcessError: exit_messages.append( ExitMessage( - message=("ansible-lint does not seem to be installed correctly.") + message=("ansible-lint does not seem to be installed correctly."), ), ) exit_messages.append( @@ -934,7 +937,8 @@ def playbook(entry: SettingsEntry, config: ApplicationConfiguration) -> PostProc exit_messages.append(ExitMessage(message=exit_msg, prefix=ExitPrefix.HINT)) return messages, exit_messages if check_playbook_type(entry.value.current) == "file" and isinstance( - entry.value.current, str + entry.value.current, + str, ): entry.value.current = abs_user_path(entry.value.current) return messages, exit_messages diff --git a/src/ansible_navigator/data/catalog_collections.py b/src/ansible_navigator/data/catalog_collections.py index 6e0d3c375b..18cfcc7f2a 100644 --- a/src/ansible_navigator/data/catalog_collections.py +++ b/src/ansible_navigator/data/catalog_collections.py @@ -356,7 +356,8 @@ def add_pseudo_builtin(self) -> None: def worker( - pending_queue: multiprocessing.Queue[Any], completed_queue: multiprocessing.Queue[Any] + pending_queue: multiprocessing.Queue[Any], + completed_queue: multiprocessing.Queue[Any], ) -> None: """Extract the documentation from a plugin, place in completed queue. @@ -419,7 +420,8 @@ def worker( def identify_missing( - collections: dict[Any, Any], collection_cache: KeyValueStore + collections: dict[Any, Any], + collection_cache: KeyValueStore, ) -> tuple[set[Any], list[Any], int]: """Identify plugins missing from the cache. diff --git a/src/ansible_navigator/data/image_introspect.py b/src/ansible_navigator/data/image_introspect.py index 8382aa7d34..444b7cb593 100644 --- a/src/ansible_navigator/data/image_introspect.py +++ b/src/ansible_navigator/data/image_introspect.py @@ -163,7 +163,10 @@ def re_partition(content: Any, separator: str) -> Any: return key, delim, content def splitter( - self, lines: list[str], line_split: str, section_delim: str | None = None + self, + lines: list[str], + line_split: str, + section_delim: str | None = None, ) -> list[dict[str, Any]] | dict[str, Any]: """Split lines given a delimiter. @@ -294,7 +297,9 @@ def commands(self) -> list[Command]: :returns: The defined command """ pre = Command( - id_="pip_freeze", command="/usr/bin/python3 -m pip freeze", parse=self.parse_freeze + id_="pip_freeze", + command="/usr/bin/python3 -m pip freeze", + parse=self.parse_freeze, ) run_command(pre) pre.parse(pre) diff --git a/src/ansible_navigator/runner/command_async.py b/src/ansible_navigator/runner/command_async.py index 700f10043f..cf6fb90a8c 100644 --- a/src/ansible_navigator/runner/command_async.py +++ b/src/ansible_navigator/runner/command_async.py @@ -20,7 +20,11 @@ class CommandAsync(CommandBase): """A wrapper for the asynchronous runner.""" def __init__( - self, executable_cmd: str, queue: Queue[Any], write_job_events: bool, **kwargs: Any + self, + executable_cmd: str, + queue: Queue[Any], + write_job_events: bool, + **kwargs: Any, ) -> None: """Initialize the arguments for the ``run_command_async`` interface of ``ansible-runner``. diff --git a/src/ansible_navigator/ui_framework/form.py b/src/ansible_navigator/ui_framework/form.py index 7882269e7d..55b6453ddb 100644 --- a/src/ansible_navigator/ui_framework/form.py +++ b/src/ansible_navigator/ui_framework/form.py @@ -341,7 +341,8 @@ def _generate_messages(form_field: FieldWorking) -> CursesLines: return CursesLines(lines) def _generate_prompt( - self, form_field: FieldText | FieldChecks | FieldRadio + self, + form_field: FieldText | FieldChecks | FieldRadio, ) -> list[CursesLinePart]: """Generate the prompt for a field. diff --git a/src/ansible_navigator/ui_framework/form_handler_options.py b/src/ansible_navigator/ui_framework/form_handler_options.py index 577c5bca78..1336d93d16 100644 --- a/src/ansible_navigator/ui_framework/form_handler_options.py +++ b/src/ansible_navigator/ui_framework/form_handler_options.py @@ -50,7 +50,9 @@ def populate(self, form_field: FieldText, active: int) -> None: text = option.text clp_text = CursesLinePart(len(option_code) + 1, text, color, decoration) self._add_line( - window=self.win, lineno=idx, line=CursesLine((clp_option_code, clp_text)) + window=self.win, + lineno=idx, + line=CursesLine((clp_option_code, clp_text)), ) def handle(self, idx: int, form_fields: list[FieldText]) -> tuple[FieldText, int]: diff --git a/src/ansible_navigator/ui_framework/ui.py b/src/ansible_navigator/ui_framework/ui.py index f21255b165..6f7e5d5086 100644 --- a/src/ansible_navigator/ui_framework/ui.py +++ b/src/ansible_navigator/ui_framework/ui.py @@ -814,7 +814,10 @@ def _get_heading_menu_items( return menu_heading, menu_items def _show_menu( - self, current: Sequence[Any], columns: list[str], await_input: bool + self, + current: Sequence[Any], + columns: list[str], + await_input: bool, ) -> Interaction: """Show a menu on the screen. diff --git a/src/ansible_navigator/utils/print.py b/src/ansible_navigator/utils/print.py index 841cba1882..204f4c07c7 100644 --- a/src/ansible_navigator/utils/print.py +++ b/src/ansible_navigator/utils/print.py @@ -112,7 +112,7 @@ def print_to_stdout( content=content, content_view=ContentView.NORMAL, serialization_format=serialization_format, - ) + ), ) output = serialized else: diff --git a/tests/conftest.py b/tests/conftest.py index 6281140693..08215d6c29 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -392,7 +392,7 @@ def pytest_configure(config: pytest.Config) -> None: ): pytest.exit( f"Please remove or empty the ansible config file '{config_file}' " - "before testing, as this will likely break the test results." + "before testing, as this will likely break the test results.", ) # look for ansible-navigator settings file @@ -417,7 +417,8 @@ def pytest_unconfigure(config: pytest.Config) -> None: @pytest.fixture() def skip_if_already_failed( # noqa: PT004 - request: pytest.FixtureRequest, failed: set[str] = set() + request: pytest.FixtureRequest, + failed: set[str] = set(), ) -> Generator[None, None, None]: """Fixture that stops parametrized tests running on first failure.""" key = request.node.name.split("[")[0] diff --git a/tests/integration/_tmux_session.py b/tests/integration/_tmux_session.py index f994056768..677da0d466 100644 --- a/tests/integration/_tmux_session.py +++ b/tests/integration/_tmux_session.py @@ -108,7 +108,9 @@ def _build_tmux_session(self) -> None: break except libtmux.exc.LibTmuxException as exc: warnings.warn( - f"tmux session failure #{count}: {exc!s}", RuntimeWarning, stacklevel=2 + f"tmux session failure #{count}: {exc!s}", + RuntimeWarning, + stacklevel=2, ) if count == tries: raise diff --git a/tests/integration/actions/builder/base.py b/tests/integration/actions/builder/base.py index c481929919..e15f8e3620 100644 --- a/tests/integration/actions/builder/base.py +++ b/tests/integration/actions/builder/base.py @@ -29,7 +29,8 @@ class BaseClass: @pytest.fixture(scope="module", name="tmux_session") def fixture_tmux_session( - self, request: pytest.FixtureRequest + self, + request: pytest.FixtureRequest, ) -> Generator[TmuxSession, None, None]: """Generate a tmux fixture for this module. diff --git a/tests/integration/actions/config/base.py b/tests/integration/actions/config/base.py index aca4de4f1f..2d1ad17d27 100644 --- a/tests/integration/actions/config/base.py +++ b/tests/integration/actions/config/base.py @@ -50,7 +50,8 @@ class BaseClass: @pytest.fixture(scope="module", name="tmux_session") def fixture_tmux_session( - self, request: pytest.FixtureRequest + self, + request: pytest.FixtureRequest, ) -> Generator[TmuxSession, None, None]: """Generate a tmux fixture for this module. diff --git a/tests/integration/actions/doc/test_welcome_interactive_ee.py b/tests/integration/actions/doc/test_welcome_interactive_ee.py index caec9524c4..03d0651512 100644 --- a/tests/integration/actions/doc/test_welcome_interactive_ee.py +++ b/tests/integration/actions/doc/test_welcome_interactive_ee.py @@ -22,7 +22,12 @@ testdata_lookup_doc = [ pytest.param(0, CLI_LOOKUP_DOC, "welcome", "lookup_doc_pass", [], id="0"), pytest.param( - 1, ":doc company_name.coll_1.lookup_1 -t lookup", "load doc", "lookup_doc_pass", [], id="1" + 1, + ":doc company_name.coll_1.lookup_1 -t lookup", + "load doc", + "lookup_doc_pass", + [], + id="1", ), ] @@ -32,7 +37,12 @@ testdata_filter_doc = [ pytest.param(0, CLI_FILTER_DOC, "welcome", "filter_doc_pass", [], id="0"), pytest.param( - 1, ":doc company_name.coll_1.filter_1 -t filter", "load doc", "filter_doc_pass", [], id="1" + 1, + ":doc company_name.coll_1.filter_1 -t filter", + "load doc", + "filter_doc_pass", + [], + id="1", ), ] diff --git a/tests/integration/actions/doc/test_welcome_interactive_noee.py b/tests/integration/actions/doc/test_welcome_interactive_noee.py index 99fd286686..b20ef0093f 100644 --- a/tests/integration/actions/doc/test_welcome_interactive_noee.py +++ b/tests/integration/actions/doc/test_welcome_interactive_noee.py @@ -22,7 +22,12 @@ testdata_lookup_doc = [ pytest.param(0, CLI_LOOKUP_DOC, "welcome", "lookup_doc_pass", [], id="0"), pytest.param( - 1, ":doc company_name.coll_1.lookup_1 -t lookup", "load doc", "lookup_doc_pass", [], id="1" + 1, + ":doc company_name.coll_1.lookup_1 -t lookup", + "load doc", + "lookup_doc_pass", + [], + id="1", ), ] @@ -32,7 +37,12 @@ testdata_filter_doc = [ pytest.param(0, CLI_FILTER_DOC, "welcome", "filter_doc_pass", [], id="0"), pytest.param( - 1, ":doc company_name.coll_1.filter_1 -t filter", "load doc", "filter_doc_pass", [], id="1" + 1, + ":doc company_name.coll_1.filter_1 -t filter", + "load doc", + "filter_doc_pass", + [], + id="1", ), ] diff --git a/tests/integration/actions/replay/test_welcome_interactive_ee.py b/tests/integration/actions/replay/test_welcome_interactive_ee.py index 317e72ca5c..6881a2c4e4 100644 --- a/tests/integration/actions/replay/test_welcome_interactive_ee.py +++ b/tests/integration/actions/replay/test_welcome_interactive_ee.py @@ -12,7 +12,11 @@ testdata = [ pytest.param(0, CLI, "welcome", ":help help", id="0"), pytest.param( - 1, f":replay {PLAYBOOK_ARTIFACT}", "Play list", ["Complete", "Successful"], id="1" + 1, + f":replay {PLAYBOOK_ARTIFACT}", + "Play list", + ["Complete", "Successful"], + id="1", ), pytest.param(2, ":0", "Task list", ":help help", id="2"), pytest.param(3, ":0", "Task 1", ":help help", id="3"), diff --git a/tests/integration/actions/replay/test_welcome_interactive_noee.py b/tests/integration/actions/replay/test_welcome_interactive_noee.py index a3484b7367..567125b6cb 100644 --- a/tests/integration/actions/replay/test_welcome_interactive_noee.py +++ b/tests/integration/actions/replay/test_welcome_interactive_noee.py @@ -11,7 +11,11 @@ testdata = [ pytest.param(0, CLI, "welcome", ":help help", id="0"), pytest.param( - 1, f":replay {PLAYBOOK_ARTIFACT}", "Play list", ["Complete", "Successful"], id="1" + 1, + f":replay {PLAYBOOK_ARTIFACT}", + "Play list", + ["Complete", "Successful"], + id="1", ), pytest.param(2, ":0", "Task list", ":help help", id="2"), pytest.param(3, ":0", "Task 1", ":help help", id="3"), diff --git a/tests/integration/actions/settings/base.py b/tests/integration/actions/settings/base.py index 4a5937d0fe..bce882db61 100644 --- a/tests/integration/actions/settings/base.py +++ b/tests/integration/actions/settings/base.py @@ -48,7 +48,8 @@ class BaseClass: @pytest.fixture(scope="module", name="tmux_session") def fixture_tmux_session( - self, request: pytest.FixtureRequest + self, + request: pytest.FixtureRequest, ) -> Generator[TmuxSession, None, None]: """Tmux fixture for this module. diff --git a/tests/unit/actions/run/test_artifact.py b/tests/unit/actions/run/test_artifact.py index 009a04f02f..08d2f5110d 100644 --- a/tests/unit/actions/run/test_artifact.py +++ b/tests/unit/actions/run/test_artifact.py @@ -85,7 +85,7 @@ def __str__(self) -> str: filename="/tmp/artifact.json", playbook="site.yml", starts_with="/tmp/artifact.json", - ) + ), ), pytest.param( Scenario( @@ -93,7 +93,7 @@ def __str__(self) -> str: filename="./artifact.json", playbook="site.yml", starts_with=f"{os.path.abspath('.')}/artifact.json", - ) + ), ), pytest.param( Scenario( @@ -101,7 +101,7 @@ def __str__(self) -> str: filename="../artifact.json", playbook="site.yml", starts_with=f"{os.path.abspath('..')}/artifact.json", - ) + ), ), pytest.param( Scenario( @@ -109,7 +109,7 @@ def __str__(self) -> str: filename="~/artifact.json", playbook="/tmp/site.yaml", starts_with="/home/test_user/artifact.json", - ) + ), ), pytest.param( Scenario( @@ -117,7 +117,7 @@ def __str__(self) -> str: filename=None, playbook="/tmp/site.yaml", starts_with="/tmp/site-artifact", - ) + ), ), pytest.param( Scenario( @@ -125,7 +125,7 @@ def __str__(self) -> str: filename=None, playbook="./site.yaml", starts_with=f"{os.path.abspath('.')}/site-artifact", - ) + ), ), pytest.param( Scenario( @@ -133,7 +133,7 @@ def __str__(self) -> str: filename=None, playbook="../site.yaml", starts_with=f"{os.path.abspath('..')}/site-artifact", - ) + ), ), pytest.param( Scenario( @@ -141,7 +141,7 @@ def __str__(self) -> str: filename=None, playbook="~/site.yaml", starts_with="/home/test_user/site-artifact", - ) + ), ), pytest.param( Scenario( @@ -151,7 +151,7 @@ def __str__(self) -> str: starts_with="/home/test_user/site-artifact", help_playbook=True, playbook_artifact_enable=False, - ) + ), ), pytest.param( Scenario( @@ -161,7 +161,7 @@ def __str__(self) -> str: starts_with="/home/test_user/site-artifact", enable_prompts=True, playbook_artifact_enable=False, - ) + ), ), pytest.param( Scenario( @@ -170,7 +170,7 @@ def __str__(self) -> str: playbook="site.yml", time_zone="America/Los_Angeles", re_match=re.compile("^/tmp/.*-0[7,8]:00"), - ) + ), ), pytest.param( Scenario( @@ -178,7 +178,7 @@ def __str__(self) -> str: playbook="site.yml", filename="/tmp/{playbook_status}/{playbook_name}.json", starts_with="/tmp/successful/site.json", - ) + ), ), ] diff --git a/tests/unit/configuration_subsystem/conftest.py b/tests/unit/configuration_subsystem/conftest.py index f6427cf58b..e54a6baf0d 100644 --- a/tests/unit/configuration_subsystem/conftest.py +++ b/tests/unit/configuration_subsystem/conftest.py @@ -62,7 +62,9 @@ def __call__( def _generate_config( - params: list[Any] | None = None, settings_file_name: str | None = None, initial: bool = True + params: list[Any] | None = None, + settings_file_name: str | None = None, + initial: bool = True, ) -> GenerateConfigResponse: """Generate a configuration given a settings file. diff --git a/tests/unit/configuration_subsystem/data.py b/tests/unit/configuration_subsystem/data.py index 39bd26a038..c8ee9fe1c9 100644 --- a/tests/unit/configuration_subsystem/data.py +++ b/tests/unit/configuration_subsystem/data.py @@ -266,7 +266,10 @@ def cli_data() -> Generator[ParameterSet, None, None]: ), pytest.param("inventory_column", "t1,t2,t3", ["t1", "t2", "t3"], id="27"), pytest.param( - "lint_config", "/tmp/ansible-lint-config.yml", "/tmp/ansible-lint-config.yml", id="28" + "lint_config", + "/tmp/ansible-lint-config.yml", + "/tmp/ansible-lint-config.yml", + id="28", ), pytest.param("lintables", "/tmp/lintables", "/tmp/lintables", id="29"), pytest.param("log_append", "false", False, id="30"), @@ -284,7 +287,10 @@ def cli_data() -> Generator[ParameterSet, None, None]: pytest.param("pull_arguments", "--tls-verify=false", ["--tls-verify=false"], id="42"), pytest.param("pull_policy", "never", "never", id="43"), pytest.param( - "set_environment_variable", "T1=A,T2=B,T3=C", {"T1": "A", "T2": "B", "T3": "C"}, id="44" + "set_environment_variable", + "T1=A,T2=B,T3=C", + {"T1": "A", "T2": "B", "T3": "C"}, + id="44", ), pytest.param("settings_effective", "false", False, id="45"), pytest.param("settings_sample", "false", False, id="46"), diff --git a/tests/unit/configuration_subsystem/post_processors/test_inventory.py b/tests/unit/configuration_subsystem/post_processors/test_inventory.py index 8e12faddfc..fa315dc32e 100644 --- a/tests/unit/configuration_subsystem/post_processors/test_inventory.py +++ b/tests/unit/configuration_subsystem/post_processors/test_inventory.py @@ -25,7 +25,9 @@ @ee_states def test_from_ansible_cfg( - ee_enabled: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ee_enabled: bool, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, ) -> None: """Confirm inventory is used from a valid ansible.cfg. diff --git a/tests/unit/configuration_subsystem/test_ansible_config_parse.py b/tests/unit/configuration_subsystem/test_ansible_config_parse.py index 665d2d0277..25488cc586 100644 --- a/tests/unit/configuration_subsystem/test_ansible_config_parse.py +++ b/tests/unit/configuration_subsystem/test_ansible_config_parse.py @@ -50,7 +50,9 @@ def test_valid_config(ee_enabled: bool, tmp_path: Path, monkeypatch: pytest.Monk @ee_states def test_valid_configurator( - ee_enabled: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ee_enabled: bool, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, ) -> None: """Confirm a valid ansible.cfg is parsed using configurator. @@ -140,7 +142,9 @@ def test_invalid_config(ee_enabled: bool, tmp_path: Path, monkeypatch: pytest.Mo @ee_states def test_invalid_configurator( - ee_enabled: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ee_enabled: bool, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, ) -> None: """Confirm a invalid ansible.cfg raises errors using configurator. diff --git a/tests/unit/configuration_subsystem/test_container_engine_auto.py b/tests/unit/configuration_subsystem/test_container_engine_auto.py index 7b699c6922..e2b861f5a2 100644 --- a/tests/unit/configuration_subsystem/test_container_engine_auto.py +++ b/tests/unit/configuration_subsystem/test_container_engine_auto.py @@ -10,7 +10,8 @@ def test_ce_auto_podman( - monkeypatch: pytest.MonkeyPatch, generate_config: GenerateConfigCallable + monkeypatch: pytest.MonkeyPatch, + generate_config: GenerateConfigCallable, ) -> None: """Ensure podman is the result. @@ -28,7 +29,8 @@ def which(arg: Any) -> bool: def test_ce_auto_docker( - monkeypatch: pytest.MonkeyPatch, generate_config: GenerateConfigCallable + monkeypatch: pytest.MonkeyPatch, + generate_config: GenerateConfigCallable, ) -> None: """Ensure docker is the result. @@ -46,7 +48,8 @@ def which(arg: Any) -> bool: def test_ce_auto_none( - monkeypatch: pytest.MonkeyPatch, generate_config: GenerateConfigCallable + monkeypatch: pytest.MonkeyPatch, + generate_config: GenerateConfigCallable, ) -> None: """Ensure error is the result. diff --git a/tests/unit/configuration_subsystem/test_invalid_params.py b/tests/unit/configuration_subsystem/test_invalid_params.py index 7ef456c721..50cb87fd65 100644 --- a/tests/unit/configuration_subsystem/test_invalid_params.py +++ b/tests/unit/configuration_subsystem/test_invalid_params.py @@ -63,7 +63,8 @@ def test_ee_false_no_ansible( """ def check_for_ansible( - *_args: Any, **_kwargs: dict[str, Any] + *_args: Any, + **_kwargs: dict[str, Any], ) -> tuple[list[LogMessage], list[ExitMessage]]: """Return the path to the container engine. diff --git a/tests/unit/configuration_subsystem/test_presentable.py b/tests/unit/configuration_subsystem/test_presentable.py index 7116c7bb48..33fe8e1053 100644 --- a/tests/unit/configuration_subsystem/test_presentable.py +++ b/tests/unit/configuration_subsystem/test_presentable.py @@ -70,7 +70,8 @@ def _settings_file_dict() -> dict[str, Any]: def test_settings_file_entry( - sample_settings: ApplicationConfiguration, settings_file_dict: dict[str, Any] + sample_settings: ApplicationConfiguration, + settings_file_dict: dict[str, Any], ) -> None: """Ensure the settings file entry is properly constructed. @@ -85,7 +86,8 @@ def test_settings_file_entry( def test_settings_entry( - sample_settings: ApplicationConfiguration, settings_file_dict: dict[str, Any] + sample_settings: ApplicationConfiguration, + settings_file_dict: dict[str, Any], ) -> None: """Ensure a settings entry is properly constructed. diff --git a/tests/unit/image_manager/test_image_puller.py b/tests/unit/image_manager/test_image_puller.py index 40551fabd3..f14f96671a 100644 --- a/tests/unit/image_manager/test_image_puller.py +++ b/tests/unit/image_manager/test_image_puller.py @@ -31,7 +31,9 @@ class TstPullPolicy(NamedTuple): @pytest.mark.parametrize("data", data_do_have) def test_do_have( - valid_container_engine: str, default_ee_image_name: str, data: TstPullPolicy + valid_container_engine: str, + default_ee_image_name: str, + data: TstPullPolicy, ) -> None: """Test using an image local. @@ -60,7 +62,9 @@ def test_do_have( @pytest.mark.parametrize("data", data_do_have_but_latest) def test_do_have_but_latest( - valid_container_engine: str, small_image_name: str, data: TstPullPolicy + valid_container_engine: str, + small_image_name: str, + data: TstPullPolicy, ) -> None: """Test using an image local. @@ -201,7 +205,12 @@ def test_pull_with_env_arg() -> None: result = image_puller._generate_pull_command() # pylint: disable=protected-access cmd_to_run = f"echo {result}" proc = subprocess.run( - cmd_to_run, check=True, shell=True, env=os.environ, capture_output=True, text=True + cmd_to_run, + check=True, + shell=True, + env=os.environ, + capture_output=True, + text=True, ) assert "XDG_RUNTIME_DIR" not in proc.stdout assert "containers/auth.json" in proc.stdout diff --git a/tests/unit/logger/test_time_zone.py b/tests/unit/logger/test_time_zone.py index 25b7b86785..7080931f57 100644 --- a/tests/unit/logger/test_time_zone.py +++ b/tests/unit/logger/test_time_zone.py @@ -54,7 +54,8 @@ def args(self, log_file: Path) -> list[str]: id="1", ), pytest.param( - Scenario(name="2", re_match=re.compile(r"^.*\+09:00$"), time_zone="Japan"), id="2" + Scenario(name="2", re_match=re.compile(r"^.*\+09:00$"), time_zone="Japan"), + id="2", ), pytest.param( Scenario(name="3", re_match=re.compile(r"^.*[+-][01][0-9]:[0-5][0-9]$"), time_zone="local"), @@ -111,5 +112,5 @@ def return_none(*_args: Any, **_kwargs: dict[str, Any]) -> None: assert len(caplog.records) > 100 for record in caplog.records: assert data.re_match.match( - record.asctime + record.asctime, ), f"{data.re_match.pattern} does not match '{record.asctime}'" diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index dc60839dd8..d42bf96bff 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -59,7 +59,10 @@ id="nested-config-option-override-by-commandline", ), pytest.param( - [], "editor_command", "emacs -nw +{line_number} {filename}", id="check-editor-command" + [], + "editor_command", + "emacs -nw +{line_number} {filename}", + id="check-editor-command", ), pytest.param( ["inventory", "-i", "/tmp/inventory.yaml"], @@ -169,7 +172,9 @@ class TstHint(NamedTuple): tst_hint_data = [ pytest.param( TstHint( - command=r"--cdcp {locked_directory}/foo.db", expected="without '--cdcp'", set_ce=True + command=r"--cdcp {locked_directory}/foo.db", + expected="without '--cdcp'", + set_ce=True, ), id="0", ), @@ -190,10 +195,12 @@ class TstHint(NamedTuple): pytest.param(TstHint(command="run", expected="with 'run "), id="9"), pytest.param(TstHint(command="run --pae not_bool", expected="with '--pae true"), id="10"), pytest.param( - TstHint(command="replay", expected="with 'replay '"), id="11" + TstHint(command="replay", expected="with 'replay '"), + id="11", ), pytest.param( - TstHint(command="--senv FOO:BAR", expected="with '--senv MY_VAR=my_value'"), id="12" + TstHint(command="--senv FOO:BAR", expected="with '--senv MY_VAR=my_value'"), + id="12", ), ] diff --git a/tests/unit/utils/test_dockerfile.py b/tests/unit/utils/test_dockerfile.py index e3254e66d3..20b058ca90 100644 --- a/tests/unit/utils/test_dockerfile.py +++ b/tests/unit/utils/test_dockerfile.py @@ -21,7 +21,7 @@ def test_count(contents: str) -> None: :param contents: The contents of the dockerfile. """ assert len(ImageEntry.__members__) == len( - [line for line in contents.splitlines() if line.startswith("FROM")] + [line for line in contents.splitlines() if line.startswith("FROM")], ) diff --git a/tests/unit/utils/test_unserializable.py b/tests/unit/utils/test_unserializable.py index 3556e32487..3ca5f50c11 100644 --- a/tests/unit/utils/test_unserializable.py +++ b/tests/unit/utils/test_unserializable.py @@ -48,7 +48,7 @@ class CustomClass: content=content, content_view=content_view[1], serialization_format=serialization_format[1], - ) + ), ) assert ( f"The requested content could not be converted to {serialization_format[0]!s}." @@ -75,7 +75,7 @@ def test_deque( content=content, # type:ignore[arg-type] content_view=content_view[1], serialization_format=serialization_format[1], - ) + ), ) assert ( f"The requested content could not be converted to {serialization_format[0]!s}." From b15e5525419b892e4ee57f0aae9bf9bd8c6b4d78 Mon Sep 17 00:00:00 2001 From: Shatakshi Mishra Date: Mon, 27 May 2024 19:22:13 +0530 Subject: [PATCH 2/2] Address ruff `PTH` (#1773) * Address ruff PTH101 exceptions * Address ruff PTH112 exceptions * Address ruff PTH115 exceptions * Address ruff PTH107 exceptions * Address ruff PTH114 exceptions * Address ruff PTH204 exceptions --- pyproject.toml | 6 ------ src/ansible_navigator/actions/inventory.py | 6 +++--- src/ansible_navigator/initialization.py | 3 ++- src/ansible_navigator/logger.py | 3 ++- src/ansible_navigator/utils/functions.py | 2 +- tests/conftest.py | 4 ++-- tests/integration/_common.py | 6 +++--- 7 files changed, 13 insertions(+), 17 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index ba50d81f13..9cf3b7c04f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -305,22 +305,16 @@ ignore = [ 'PT019', # Fixture `_mocked_func` without value is injected as parameter, use `@pytest.mark.usefixtures` instead 'PT022', # [*] No teardown in fixture `cmd_in_tty`, use `return` instead of `yield` 'PTH100', # `os.path.abspath()` should be replaced by `Path.resolve()` - 'PTH101', # `os.chmod()` should be replaced by `Path.chmod()` 'PTH103', # `os.makedirs()` should be replaced by `Path.mkdir(parents=True)` - 'PTH107', # `os.remove()` should be replaced by `Path.unlink()` 'PTH109', # `os.getcwd()` should be replaced by `Path.cwd()` 'PTH110', # `os.path.exists()` should be replaced by `Path.exists()` 'PTH111', # `os.path.expanduser()` should be replaced by `Path.expanduser()` - 'PTH112', # `os.path.isdir()` should be replaced by `Path.is_dir()` 'PTH113', # `os.path.isfile()` should be replaced by `Path.is_file()` - 'PTH114', # `os.path.islink()` should be replaced by `Path.is_symlink()` - 'PTH115', # `os.readlink()` should be replaced by `Path.readlink()` 'PTH116', # `os.stat()` should be replaced by `Path.stat()`, `Path.owner()`, or `Path.group()` 'PTH118', # `os.path.join()` should be replaced by `Path` with `/` operator 'PTH119', # `os.path.basename()` should be replaced by `Path.name` 'PTH120', # `os.path.dirname()` should be replaced by `Path.parent` 'PTH122', # `os.path.splitext()` should be replaced by `Path.suffix` - 'PTH204', # `os.path.getmtime` should be replaced by `Path.stat().st_mtime` 'PTH207', # Replace `glob` with `Path.glob` or `Path.rglob` 'RET505', # Unnecessary `else` after `return` statement 'RUF005', # [*] Consider `[self._name, *shlex.split(self._interaction.action.match.groupdict()["params"] or "")]` instead of concatenation diff --git a/src/ansible_navigator/actions/inventory.py b/src/ansible_navigator/actions/inventory.py index 36b400829b..75ab7c21fb 100644 --- a/src/ansible_navigator/actions/inventory.py +++ b/src/ansible_navigator/actions/inventory.py @@ -163,15 +163,15 @@ def _set_inventories_mtime(self) -> None: """Record the inventory modification time.""" modification_times = [] for inventory in self._inventories: - if os.path.isdir(inventory): + if Path(inventory).is_dir(): modification_times.append( max( - os.path.getmtime(e) + Path(e).stat().st_mtime for e in glob.glob(os.path.join(inventory, "**"), recursive=True) ), ) elif os.path.isfile(inventory): - modification_times.append(os.path.getmtime(inventory)) + modification_times.append(Path(inventory).stat().st_mtime) if modification_times: self._inventories_mtime = max(modification_times) else: diff --git a/src/ansible_navigator/initialization.py b/src/ansible_navigator/initialization.py index 86bc1c21bb..e494bd5e32 100644 --- a/src/ansible_navigator/initialization.py +++ b/src/ansible_navigator/initialization.py @@ -9,6 +9,7 @@ import os import sys +from pathlib import Path from typing import TYPE_CHECKING from typing import NoReturn @@ -135,7 +136,7 @@ def get_and_check_collection_doc_cache( message = "Collection doc cache: version was empty or incorrect, rebuilding" messages.append(LogMessage(level=logging.INFO, message=message)) collection_cache.close() - os.remove(collection_doc_cache_path) + Path(collection_doc_cache_path).unlink() collection_cache = KeyValueStore(collection_doc_cache_path) collection_cache["version"] = VERSION_CDC cache_version = collection_cache["version"] diff --git a/src/ansible_navigator/logger.py b/src/ansible_navigator/logger.py index f45c48fa73..b5a26af35e 100644 --- a/src/ansible_navigator/logger.py +++ b/src/ansible_navigator/logger.py @@ -7,6 +7,7 @@ import os import zoneinfo +from pathlib import Path from typing import TYPE_CHECKING from typing import Any @@ -57,7 +58,7 @@ def setup_logger(args: ApplicationConfiguration) -> None: :param args: The CLI args """ if os.path.exists(args.log_file) and args.log_append is False: - os.remove(args.log_file) + Path(args.log_file).unlink() handler = logging.FileHandler(args.log_file) time_zone = args.entry("time_zone").value.current diff --git a/src/ansible_navigator/utils/functions.py b/src/ansible_navigator/utils/functions.py index 53a4914aec..26cc5d19fa 100644 --- a/src/ansible_navigator/utils/functions.py +++ b/src/ansible_navigator/utils/functions.py @@ -503,7 +503,7 @@ def time_stamp_for_file(path: str, time_zone: str) -> tuple[float | None, str | :returns: The UNIX timestamp and an ISO 8601 string """ try: - modified = os.path.getmtime(path) + modified = Path(path).stat().st_mtime except FileNotFoundError: # It may have been mounted to a different location in the execution environment modified = None diff --git a/tests/conftest.py b/tests/conftest.py index 08215d6c29..3a2bff6292 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -119,9 +119,9 @@ def locked_directory(tmpdir: str) -> Generator[str, None, None]: :param tmpdir: Fixture for temporary directory :yields: The temporary directory """ - os.chmod(tmpdir, 0o000) + Path(tmpdir).chmod(0o000) yield tmpdir - os.chmod(tmpdir, 0o777) + Path(tmpdir).chmod(0o777) @pytest.fixture(scope="session") diff --git a/tests/integration/_common.py b/tests/integration/_common.py index 40b8b45d82..a95a4ea83a 100644 --- a/tests/integration/_common.py +++ b/tests/integration/_common.py @@ -217,10 +217,10 @@ def copytree( source_path = os.path.join(src, name) destination_path = os.path.join(dst, name) try: - if symlinks and os.path.islink(source_path): - source_link = os.readlink(source_path) + if symlinks and Path(source_path).is_symlink(): + source_link = Path(source_path).readlink() os.symlink(source_link, destination_path) - elif os.path.isdir(source_path): + elif Path(source_path).is_dir(): copytree( source_path, destination_path,