Skip to content

Commit

Permalink
Pathlib conversion: find_settings_file (ansible#1796)
Browse files Browse the repository at this point in the history
* Pathlib conversion: find_settings_file

* Fix tests

* Fix ruff

* Clean up test_find_many_settings_precedence

* Fix tests_internals.py
  • Loading branch information
shatakshiiii authored Jun 13, 2024
1 parent 0a5a409 commit a968138
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 26 deletions.
2 changes: 1 addition & 1 deletion src/ansible_navigator/initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def find_config() -> tuple[list[LogMessage], list[ExitMessage], str | None, C]:
message = f"Using settings file at {config_path} set by {cfg_env_var}"
messages.append(LogMessage(level=logging.DEBUG, message=message))
elif found_config_path is not None:
config_path = found_config_path
config_path = str(found_config_path)
settings_source = C.SEARCH_PATH
message = f"Using settings file at {config_path} in search path"
messages.append(LogMessage(level=logging.DEBUG, message=message))
Expand Down
26 changes: 16 additions & 10 deletions src/ansible_navigator/utils/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
logger = logging.getLogger(__name__)


def oxfordcomma(listed: Iterable[bool | str], condition: str) -> str:
def oxfordcomma(listed: Iterable[bool | str | Path], condition: str) -> str:
"""Format a list into a sentence.
:param listed: List of string entries to modify
Expand Down Expand Up @@ -210,7 +210,7 @@ def environment_variable_is_file_path(
return messages, exit_messages, file_path


def find_settings_file() -> tuple[list[LogMessage], list[ExitMessage], str | None]:
def find_settings_file() -> tuple[list[LogMessage], list[ExitMessage], Path | None]:
"""Find the settings file.
Find the file at ./ansible-navigator.(.yml,.yaml,.json),
Expand All @@ -221,27 +221,33 @@ def find_settings_file() -> tuple[list[LogMessage], list[ExitMessage], str | Non
messages: list[LogMessage] = []
exit_messages: list[ExitMessage] = []
allowed_extensions = ["yml", "yaml", "json"]
potential_paths: list[list[str]] = []
found_files: list[str] = []
potential_paths: list[Path] = []
found_files: list[Path] = []

potential_paths.append([os.path.expanduser("~"), ".ansible-navigator"])
potential_paths.append([os.getcwd(), "ansible-navigator"])
settings_file_home = Path.home() / ".ansible-navigator"
settings_file_current = Path.cwd() / "ansible-navigator"
potential_paths.append(settings_file_home)
potential_paths.append(settings_file_current)

for path in potential_paths:
message = f"Looking in {path[0]}"
message = f"Looking in {path}"
messages.append(LogMessage(level=logging.DEBUG, message=message))

candidates = [os.path.join(path[0], f"{path[1]}.{ext}") for ext in allowed_extensions]
candidates: list[Path] = []
for ext in allowed_extensions:
p = Path(f"{path}.{ext}")
candidates.append(p)
message = f"Looking for {oxfordcomma(candidates, 'and')}"
messages.append(LogMessage(level=logging.DEBUG, message=message))

found = [file for file in candidates if os.path.exists(file)]
found = [file for file in candidates if file.exists()]

message = f"Found {len(found)}: {oxfordcomma(found, 'and')}"
messages.append(LogMessage(level=logging.DEBUG, message=message))

if len(found) > 1:
exit_msg = f"Only one file among {oxfordcomma(candidates, 'and')}"
exit_msg += f" should be present in {path[0]}"
exit_msg += f" should be present in {path}"
exit_msg += f" Found: {oxfordcomma(found, 'and')}"
exit_messages.append(ExitMessage(message=exit_msg))
return messages, exit_messages, None
Expand Down
5 changes: 2 additions & 3 deletions tests/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
import os

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

from ansible_navigator.utils.functions import expand_path


FIXTURES_DIR = str(expand_path(os.path.join(os.path.dirname(__file__), "fixtures")))
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_COLLECTION_PATH = Path(FIXTURES_COLLECTION_DIR)
FIXTURES_COLLECTION_PATH = FIXTURES_COLLECTION_DIR


class BaseScenario:
Expand Down
4 changes: 1 addition & 3 deletions tests/unit/configuration_subsystem/defaults.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
"""Defaults for adjacent tests."""

import os

from tests.defaults import FIXTURES_DIR


TEST_FIXTURE_DIR = os.path.join(FIXTURES_DIR, "unit", "configuration_subsystem")
TEST_FIXTURE_DIR = FIXTURES_DIR / "unit" / "configuration_subsystem"
5 changes: 3 additions & 2 deletions tests/unit/configuration_subsystem/test_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os

from copy import deepcopy
from pathlib import Path

import pytest

Expand Down Expand Up @@ -34,10 +35,10 @@ def test_settings_file_path_file_system(monkeypatch: pytest.MonkeyPatch) -> None
args.internals.initializing = True
args.application_version = "test"

def getcwd() -> str:
def getcwd() -> Path:
return TEST_FIXTURE_DIR

monkeypatch.setattr(os, "getcwd", getcwd)
monkeypatch.setattr(Path, "cwd", getcwd)
parse_and_update(params=[], args=args)
assert args.internals.settings_file_path == settings_file_path
assert args.internals.settings_source == Constants.SEARCH_PATH
Expand Down
14 changes: 7 additions & 7 deletions tests/unit/utils/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ def test_find_many_settings_home(monkeypatch: pytest.MonkeyPatch) -> None:
]

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

monkeypatch.setattr(os.path, "exists", check_path_exists)
monkeypatch.setattr(Path, "exists", check_path_exists)
_messages, exit_messages, _found = find_settings_file()
expected = f"Only one file among {oxfordcomma(paths, 'and')}"
assert any(expected in exit_msg.message for exit_msg in exit_messages)
Expand All @@ -53,9 +53,9 @@ def test_find_many_settings_cwd(monkeypatch: pytest.MonkeyPatch) -> None:
paths = [os.path.join(os.getcwd(), "ansible-navigator" + ext) for ext in EXTENSIONS]

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

monkeypatch.setattr(os.path, "exists", check_path_exists)
monkeypatch.setattr(Path, "exists", check_path_exists)
_messages, exit_messages, _found = find_settings_file()
expected = f"Only one file among {oxfordcomma(paths, 'and')}"
assert any(expected in exit_msg.message for exit_msg in exit_messages)
Expand All @@ -66,13 +66,13 @@ def test_find_many_settings_precedence(monkeypatch: pytest.MonkeyPatch) -> None:
:param monkeypatch: The monkeypatch fixture
"""
expected = os.path.join(os.getcwd(), "ansible-navigator.yml")
paths = [expected, os.path.join(os.path.expanduser("~"), ".ansible-navigator.json")]
expected = Path.cwd() / "ansible-navigator.yml"
paths = [expected, Path.home() / ".ansible-navigator.json"]

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

monkeypatch.setattr(os.path, "exists", check_path_exists)
monkeypatch.setattr(Path, "exists", check_path_exists)
_messages, _exit_messages, found = find_settings_file()
assert expected == found

Expand Down

0 comments on commit a968138

Please sign in to comment.