Skip to content

Commit

Permalink
Address ruff PTH118: part1 (ansible#1801)
Browse files Browse the repository at this point in the history
* Address ruff PTH118

* Fix actions/lint tests

* More fixes: part 1

* More fixes: part 2

* More fixes: part 3

* More fixes: part 4
  • Loading branch information
shatakshiiii authored Jun 15, 2024
1 parent d2d393b commit 08cae46
Show file tree
Hide file tree
Showing 18 changed files with 52 additions and 70 deletions.
8 changes: 2 additions & 6 deletions src/ansible_navigator/actions/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,17 +443,13 @@ def _run_runner(self) -> None:
if self._args.execution_environment:
self._logger.debug("running collections command with execution environment enabled")
python_exec_path = "/usr/bin/python3"
utils_lib = os.path.join(
os.path.dirname(__file__),
"..",
"utils",
)
utils_lib = Path(__file__).parent / ".." / "utils"

container_volume_mounts = [
# cache directory which has introspection script
f"{cache_path}:{cache_path}",
# KVS library used by both Navigator and the introspection script
f"{utils_lib}:/opt/ansible_navigator_utils",
f"{utils_lib!s}:/opt/ansible_navigator_utils",
]
if Path(self._adjacent_collection_dir).exists():
container_volume_mounts.append(
Expand Down
2 changes: 1 addition & 1 deletion src/ansible_navigator/tm_tokenize/grammars.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def __init__(self, *directories: str) -> None:
:param directories: A tuple of strings, each a directory in which grammar files can be found
"""
self._scope_to_files = {
Path(filename).stem: os.path.join(directory, filename)
Path(filename).stem: Path(directory) / filename
for directory in directories
if Path(directory).exists()
for filename in sorted(os.listdir(directory))
Expand Down
2 changes: 1 addition & 1 deletion src/ansible_navigator/utils/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def oxfordcomma(listed: Iterable[bool | str | Path], condition: str) -> str:
return f"{', '.join(str(x) for x in listed[:-1])} {condition} {listed[-1]}"


def expand_path(path: str) -> Path:
def expand_path(path: str | Path) -> Path:
"""Resolve a path.
:param path: The file path to resolve
Expand Down
9 changes: 3 additions & 6 deletions tests/defaults.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
"""Constants with default values used throughout the tests."""

import os

from enum import Enum
from pathlib import Path
from typing import Any

from ansible_navigator.utils.functions import expand_path


FIXTURES_DIR = expand_path(os.path.join(os.path.dirname(__file__), "fixtures"))
FIXTURES_COLLECTION_DIR = expand_path(
os.path.join(os.path.dirname(__file__), "fixtures", "common", "collections"),
)
FIXTURES_DIR = expand_path(Path(__file__).parent / "fixtures")
FIXTURES_COLLECTION_DIR = expand_path(Path(__file__).parent / "fixtures" / "common" / "collections")
FIXTURES_COLLECTION_PATH = FIXTURES_COLLECTION_DIR


Expand Down
18 changes: 9 additions & 9 deletions tests/integration/_tmux_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def __enter__(self) -> TmuxSession: # noqa: PYI034
# expect inside of tmux, so we can't depend on it. We *must* determine
# it before we enter tmux. Do this before we switch to bash
venv_path = os.environ.get("VIRTUAL_ENV")
venv = "" if venv_path is None else os.path.join(shlex.quote(venv_path), "bin", "activate")
venv = "" if venv_path is None else shlex.quote(str(Path(venv_path) / "bin" / "activate"))

# get the USER before we start a clean shell
user = os.environ.get("USER")
Expand All @@ -158,15 +158,15 @@ def __enter__(self) -> TmuxSession: # noqa: PYI034
tmux_common.append(f"export ANSIBLE_NAVIGATOR_CONFIG='{self._config_path}'")
tmux_common.append("export ANSIBLE_NAVIGATOR_LOG_LEVEL=debug")

log_file = os.path.join(self._test_log_dir, "ansible-navigator.log")
tmux_common.append(f"export ANSIBLE_NAVIGATOR_LOG_FILE='{log_file}'")
playbook_artifact = os.path.join(self._test_log_dir, "playbook-artifact.log")
log_file = self._test_log_dir / "ansible-navigator.log"
tmux_common.append(f"export ANSIBLE_NAVIGATOR_LOG_FILE='{log_file!s}'")
playbook_artifact = self._test_log_dir / "playbook-artifact.log"
tmux_common.append(
f"export ANSIBLE_NAVIGATOR_PLAYBOOK_ARTIFACT_SAVE_AS='{playbook_artifact}'",
f"export ANSIBLE_NAVIGATOR_PLAYBOOK_ARTIFACT_SAVE_AS='{playbook_artifact!s}'",
)
collection_doc_cache = os.path.join(self._test_log_dir, "collection_doc_cache.db")
collection_doc_cache = self._test_log_dir / "collection_doc_cache.db"
tmux_common.append(
f"export ANSIBLE_NAVIGATOR_COLLECTION_DOC_CACHE_PATH='{collection_doc_cache}'",
f"export ANSIBLE_NAVIGATOR_COLLECTION_DOC_CACHE_PATH='{collection_doc_cache!s}'",
)
tmux_common.append(f"export ANSIBLE_NAVIGATOR_PULL_POLICY='{self._pull_policy}'")

Expand Down Expand Up @@ -310,8 +310,8 @@ def interaction(
return showing
time.sleep(0.1)

setup_capture_path = Path(os.path.join(self._test_log_dir, "showing_setup.txt"))
timeout_capture_path = Path(os.path.join(self._test_log_dir, "showing_timeout.txt"))
setup_capture_path = self._test_log_dir / "showing_setup.txt"
timeout_capture_path = self._test_log_dir / "showing_timeout.txt"

ok_to_return = False
err_message = "RESPONSE"
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/actions/collections/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def fixture_tmux_session(
:param os_independent_tmp: An OS independent tmp directory
:yields: A tmux session
"""
tmp_coll_dir = os.path.join(os_independent_tmp, request.node.name, "")
tmp_coll_dir = Path(os_independent_tmp) / request.node.name / ""
Path(tmp_coll_dir).mkdir(parents=True, exist_ok=True)
copytree(
FIXTURES_COLLECTION_DIR,
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/actions/config/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
from tests.integration._tmux_session import TmuxSession


TEST_FIXTURE_DIR = os.path.join(FIXTURES_DIR, "integration", "actions", "config")
CONFIG_FIXTURE = os.path.join(TEST_FIXTURE_DIR, "ansible.cfg")
TEST_FIXTURE_DIR = FIXTURES_DIR / "integration" / "actions" / "config"
CONFIG_FIXTURE = TEST_FIXTURE_DIR / "ansible.cfg"


base_steps = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
),
UiTestStep(user_input=":back", comment="return to welcome screen"),
UiTestStep(
user_input=":config -c " + CONFIG_FIXTURE,
user_input=":config -c " + str(CONFIG_FIXTURE),
comment="enter config from welcome screen, custom config, (no ee)",
present=["Yaml filename extensions", "['.os2']"],
),
Expand Down
8 changes: 4 additions & 4 deletions tests/integration/actions/run/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@


# run playbook
run_fixture_dir = os.path.join(FIXTURES_DIR, "integration", "actions", "run")
inventory_path = os.path.join(run_fixture_dir, "inventory")
playbook_path = os.path.join(run_fixture_dir, "site.yaml")
run_fixture_dir = FIXTURES_DIR / "integration" / "actions" / "run"
inventory_path = run_fixture_dir / "inventory"
playbook_path = run_fixture_dir / "site.yaml"

common_fixture_dir = os.path.join(FIXTURES_DIR, "common", "collections")
common_fixture_dir = FIXTURES_DIR / "common" / "collections"
PLAYBOOK_COLLECTION = "company_name.coll_1.playbook_1"

base_steps = (
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/actions/run_unicode/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@


# run playbook
run_fixture_dir = os.path.join(FIXTURES_DIR, "integration", "actions", "run_unicode")
inventory_path = os.path.join(run_fixture_dir, "inventory")
playbook_path = os.path.join(run_fixture_dir, "site.yaml")
run_fixture_dir = FIXTURES_DIR / "integration" / "actions" / "run_unicode"
inventory_path = run_fixture_dir / "inventory"
playbook_path = run_fixture_dir / "site.yaml"

base_steps = (
UiTestStep(user_input=":0", comment="play-1 details"),
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/actions/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from tests.integration._tmux_session import TmuxSession


TEST_FIXTURE_DIR = os.path.join(FIXTURES_DIR, "integration/actions/settings")
TEST_FIXTURE_DIR = FIXTURES_DIR / "integration/actions/settings"

base_steps = (
UiTestStep(user_input=":f App", comment="filter for app settings"),
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/actions/templar/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@


# run playbook
run_fixture_dir = os.path.join(FIXTURES_DIR, "integration", "actions", "run")
inventory_path = os.path.join(run_fixture_dir, "inventory")
playbook_path = os.path.join(run_fixture_dir, "site.yaml")
run_fixture_dir = FIXTURES_DIR / "integration" / "actions" / "run"
inventory_path = run_fixture_dir / "inventory"
playbook_path = run_fixture_dir / "site.yaml"

base_steps = (
UiTestStep(user_input=":0", comment="play-1 details"),
Expand Down
6 changes: 2 additions & 4 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from __future__ import annotations

import os

from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING
Expand Down Expand Up @@ -39,12 +37,12 @@ def action_run_stdout() -> Generator[type[ActionRunTest], None, None]:


@pytest.fixture(scope="session")
def test_fixtures_dir() -> str:
def test_fixtures_dir() -> Path:
"""Return the test fixture directory.
:return: The test fixture directory.
"""
return os.path.join(os.path.dirname(__file__), "..", "fixtures")
return Path(__file__).parent / ".." / "fixtures"


@pytest.fixture(scope="session")
Expand Down
8 changes: 3 additions & 5 deletions tests/integration/test_stdout_exit_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from __future__ import annotations

import os

from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
Expand All @@ -24,7 +22,7 @@
from ._action_run_test import ActionRunTest


PLAYBOOK = os.path.join(FIXTURES_DIR, "integration", "stdout_exit_codes", "site.yml")
PLAYBOOK = FIXTURES_DIR / "integration" / "stdout_exit_codes" / "site.yml"


@pytest.fixture(name="params")
Expand Down Expand Up @@ -120,7 +118,7 @@ class StdoutTest(NamedTuple):
),
StdoutTest(
action_name="run",
action_params=(("playbook", PLAYBOOK), ("playbook_artifact_enable", False)),
action_params=(("playbook", str(PLAYBOOK)), ("playbook_artifact_enable", False)),
present="success",
return_code=0,
),
Expand Down Expand Up @@ -206,7 +204,7 @@ def command(self) -> list[str]:
name="0",
comment="run pass",
subcommand="run",
params=[PLAYBOOK],
params=[str(PLAYBOOK)],
return_code=0,
ansible_stdout="ok=1",
ansible_stderr="",
Expand Down
10 changes: 4 additions & 6 deletions tests/unit/configuration_subsystem/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from __future__ import annotations

import os

from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING
Expand Down Expand Up @@ -32,7 +30,7 @@
from ansible_navigator.utils.definitions import LogMessage


TEST_FIXTURE_DIR = os.path.join(FIXTURES_DIR, "unit", "configuration_subsystem")
TEST_FIXTURE_DIR = FIXTURES_DIR / "unit" / "configuration_subsystem"


class GenerateConfigResponse(NamedTuple):
Expand Down Expand Up @@ -77,22 +75,22 @@ def _generate_config(
params = []

if settings_file_name:
settings_file_path = os.path.join(TEST_FIXTURE_DIR, settings_file_name)
settings_file_path = TEST_FIXTURE_DIR / settings_file_name
with Path(settings_file_path).open(encoding="utf-8") as fh:
try:
settings_contents = yaml.load(fh, Loader=Loader)
except yaml.parser.ParserError:
# let the configuration subsystem catch the invalid yaml file
settings_contents = {}
else:
settings_file_path = ""
settings_file_path = "" # type:ignore[assignment]
settings_contents = {}

# make a deep copy here to ensure we do not modify the original
application_configuration = deepcopy(NavigatorConfiguration)
application_configuration.internals.initializing = initial
application_configuration.application_version = "test"
application_configuration.internals.settings_file_path = settings_file_path or None
application_configuration.internals.settings_file_path = str(settings_file_path) or None
configurator = Configurator(
application_configuration=application_configuration,
params=params,
Expand Down
6 changes: 1 addition & 5 deletions tests/unit/configuration_subsystem/test_fixture_sanity.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@
entries for for all entries.
"""

import os

from pathlib import Path

from ansible_navigator.configuration_subsystem import NavigatorConfiguration
from ansible_navigator.utils.serialize import Loader
from ansible_navigator.utils.serialize import yaml
Expand All @@ -25,7 +21,7 @@ def test_data_no_missing_env_var_data() -> None:

def test_full_settings_file() -> None:
"""Test using a full settings file."""
settings_file_path = Path(os.path.join(TEST_FIXTURE_DIR, "ansible-navigator.yml"))
settings_file_path = TEST_FIXTURE_DIR / "ansible-navigator.yml"
with settings_file_path.open(encoding="utf-8") as fh:
settings_contents = yaml.load(fh, Loader=Loader)
for entry in NavigatorConfiguration.entries:
Expand Down
12 changes: 5 additions & 7 deletions tests/unit/configuration_subsystem/test_internals.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""Test the internals of a NavigatorConfiguration."""

import os

from copy import deepcopy
from pathlib import Path

Expand Down Expand Up @@ -30,7 +28,7 @@ def test_settings_file_path_file_system(monkeypatch: pytest.MonkeyPatch) -> None
functionality in tests
"""
settings_file = "ansible-navigator.yml"
settings_file_path = os.path.join(TEST_FIXTURE_DIR, settings_file)
settings_file_path = TEST_FIXTURE_DIR / settings_file
args = deepcopy(NavigatorConfiguration)
args.internals.initializing = True
args.application_version = "test"
Expand All @@ -40,7 +38,7 @@ def getcwd() -> Path:

monkeypatch.setattr(Path, "cwd", getcwd)
parse_and_update(params=[], args=args)
assert args.internals.settings_file_path == settings_file_path
assert args.internals.settings_file_path == str(settings_file_path)
assert args.internals.settings_source == Constants.SEARCH_PATH


Expand All @@ -51,11 +49,11 @@ def test_settings_file_path_environment_variable(monkeypatch: pytest.MonkeyPatch
functionality in tests
"""
settings_file = "ansible-navigator.yml"
settings_file_path = os.path.join(TEST_FIXTURE_DIR, settings_file)
monkeypatch.setenv("ANSIBLE_NAVIGATOR_CONFIG", settings_file_path)
settings_file_path = TEST_FIXTURE_DIR / settings_file
monkeypatch.setenv("ANSIBLE_NAVIGATOR_CONFIG", str(settings_file_path))
args = deepcopy(NavigatorConfiguration)
args.internals.initializing = True
args.application_version = "test"
parse_and_update(params=[], args=args)
assert args.internals.settings_file_path == settings_file_path
assert args.internals.settings_file_path == str(settings_file_path)
assert args.internals.settings_source == Constants.ENVIRONMENT_VARIABLE
11 changes: 6 additions & 5 deletions tests/unit/utils/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from __future__ import annotations

import os
import re

from pathlib import Path
Expand Down Expand Up @@ -32,10 +31,11 @@ def test_find_many_settings_home(monkeypatch: pytest.MonkeyPatch) -> None:
:param monkeypatch: The monkeypatch fixture
"""
paths = [os.path.join(Path.home(), ".ansible-navigator" + ext) for ext in EXTENSIONS]
home_path = Path.home() / ".ansible-navigator"
paths = [Path(f"{home_path}{ext}") for ext in EXTENSIONS]

def check_path_exists(arg: Any) -> bool:
return str(arg) in paths
return arg in paths

monkeypatch.setattr(Path, "exists", check_path_exists)
_messages, exit_messages, _found = find_settings_file()
Expand All @@ -48,10 +48,11 @@ def test_find_many_settings_cwd(monkeypatch: pytest.MonkeyPatch) -> None:
:param monkeypatch: The monkeypatch fixture
"""
paths = [os.path.join(os.getcwd(), "ansible-navigator" + ext) for ext in EXTENSIONS]
cwd_path = Path.cwd() / "ansible-navigator"
paths = [Path(f"{cwd_path}{ext}") for ext in EXTENSIONS]

def check_path_exists(arg: Any) -> bool:
return str(arg) in paths
return arg in paths

monkeypatch.setattr(Path, "exists", check_path_exists)
_messages, exit_messages, _found = find_settings_file()
Expand Down

0 comments on commit 08cae46

Please sign in to comment.