Skip to content

Commit edb5653

Browse files
committed
Addditional tests
1 parent 861f373 commit edb5653

File tree

5 files changed

+237
-9
lines changed

5 files changed

+237
-9
lines changed

src/ansible_dev_environment/arg_parser.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@
2323

2424

2525
ENVVAR_MAPPING: dict[str, str] = {
26+
"ansi": "NO_COLOR",
2627
"isolation_mode": "ADE_ISOLATION_MODE",
2728
"seed": "ADE_SEED",
2829
"uv": "ADE_UV",
29-
"verbose": "ADE_VERBOSE",
30-
"ansi": "NO_COLOR",
3130
"venv": "VIRTUAL_ENV",
31+
"verbose": "ADE_VERBOSE",
3232
}
3333

3434
try:
@@ -305,9 +305,9 @@ def apply_envvars(args: list[str], parser: ArgumentParser) -> argparse.Namespace
305305
raise NotImplementedError(err)
306306

307307
present = any(
308-
o
309-
for o in action.option_strings
310-
if any(arg for arg in args if arg.startswith(o.split()[0]))
308+
option
309+
for option in action.option_strings
310+
if any(arg for arg in args if arg.startswith(option.split()[0]))
311311
)
312312
envvar_value = os.environ.get(envvar)
313313

@@ -321,14 +321,14 @@ def apply_envvars(args: list[str], parser: ArgumentParser) -> argparse.Namespace
321321
if envvar == "NO_COLOR" and envvar_value != "":
322322
final_value = False
323323
elif isinstance(action, (argparse.BooleanOptionalAction, argparse._StoreTrueAction)): # noqa: SLF001
324-
final_value = str_to_bool(envvar_value)
325324
named_type = "boolean"
325+
final_value = str_to_bool(envvar_value)
326326
elif isinstance(action, argparse._CountAction) or action.type is int: # noqa: SLF001
327-
final_value = int(envvar_value)
328327
named_type = "int"
328+
final_value = int(envvar_value)
329329
elif action.type is str or action.type is None:
330-
final_value = envvar_value
331330
named_type = "str"
331+
final_value = envvar_value
332332
else:
333333
err = f"Action type {action.type} not implemented for envvar {envvar}"
334334
raise NotImplementedError(err)

tests/unit/test_cli.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import pytest
99

10+
from ansible_dev_environment.arg_parser import ArgumentParser, apply_envvars
1011
from ansible_dev_environment.cli import Cli, main
1112

1213

@@ -300,3 +301,87 @@ def test_exit_code_two(
300301
assert excinfo.value.code == expected
301302
captured = capsys.readouterr()
302303
assert "Test warning" in captured.out
304+
305+
306+
def test_envvar_mapping_error(monkeypatch: pytest.MonkeyPatch) -> None:
307+
"""Test environment mapping error.
308+
309+
Args:
310+
monkeypatch: Pytest fixture.
311+
"""
312+
monkeypatch.setattr(
313+
"ansible_dev_environment.arg_parser.ENVVAR_MAPPING",
314+
{"foo": "FOO"},
315+
)
316+
monkeypatch.setattr(
317+
"sys.argv",
318+
["ansible-dev-environment", "install"],
319+
)
320+
cli = Cli()
321+
with pytest.raises(NotImplementedError):
322+
cli.parse_args()
323+
324+
325+
def test_apply_envvar_error(monkeypatch: pytest.MonkeyPatch) -> None:
326+
"""Test environment mapping error.
327+
328+
Args:
329+
monkeypatch: Pytest fixture.
330+
"""
331+
monkeypatch.setattr(
332+
"ansible_dev_environment.arg_parser.ENVVAR_MAPPING",
333+
{"foo": "FOO"},
334+
)
335+
monkeypatch.setenv("FOO", "42.0")
336+
337+
parser = ArgumentParser()
338+
parser.add_argument("--foo", type=float)
339+
340+
with pytest.raises(NotImplementedError) as excinfo:
341+
apply_envvars(args=[], parser=parser)
342+
343+
assert "not implemented for envvar FOO" in str(excinfo.value)
344+
345+
346+
def test_env_wrong_type(
347+
monkeypatch: pytest.MonkeyPatch,
348+
capsys: pytest.CaptureFixture[str],
349+
) -> None:
350+
"""Test wrong type.
351+
352+
Args:
353+
monkeypatch: Pytest fixture.
354+
capsys: Pytest stdout capture fixture.
355+
"""
356+
monkeypatch.setattr(
357+
"sys.argv",
358+
["ansible-dev-environment", "install"],
359+
)
360+
monkeypatch.setenv("ADE_VERBOSE", "not_an_int")
361+
cli = Cli()
362+
with pytest.raises(SystemExit):
363+
cli.parse_args()
364+
captured = capsys.readouterr()
365+
assert "could not convert to int" in captured.err
366+
367+
368+
def test_env_wrong_choice(
369+
monkeypatch: pytest.MonkeyPatch,
370+
capsys: pytest.CaptureFixture[str],
371+
) -> None:
372+
"""Test wrong choice.
373+
374+
Args:
375+
monkeypatch: Pytest fixture.
376+
capsys: Pytest stdout capture fixture.
377+
"""
378+
monkeypatch.setattr(
379+
"sys.argv",
380+
["ansible-dev-environment", "install"],
381+
)
382+
monkeypatch.setenv("ADE_ISOLATION_MODE", "wrong_choice")
383+
cli = Cli()
384+
with pytest.raises(SystemExit):
385+
cli.parse_args()
386+
captured = capsys.readouterr()
387+
assert "choose from 'restrictive', 'cfg', 'none'" in captured.err

tests/unit/test_cli_deprecated.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""Test some deprecated values in the CLI."""
2+
3+
from __future__ import annotations
4+
5+
from typing import TYPE_CHECKING
6+
7+
from ansible_dev_environment.cli import main
8+
9+
10+
if TYPE_CHECKING:
11+
import pytest
12+
13+
14+
def test_adt(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> None:
15+
"""Test the seed option.
16+
17+
Args:
18+
capsys: Pytest stdout capture fixture.
19+
monkeypatch: Pytest fixture.
20+
"""
21+
# Test the seed option
22+
monkeypatch.setattr(
23+
"sys.argv",
24+
["ansible-dev-environment", "install", "--adt"],
25+
)
26+
main(dry=True)
27+
captured = capsys.readouterr()
28+
assert "'--adt' is deprecated" in captured.out
29+
30+
31+
def test_skip_uv(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> None:
32+
"""Test the skip uv option.
33+
34+
Args:
35+
capsys: Pytest stdout capture fixture.
36+
monkeypatch: Pytest fixture.
37+
"""
38+
# Test the skip uv option
39+
monkeypatch.setattr(
40+
"sys.argv",
41+
["ansible-dev-environment", "install"],
42+
)
43+
monkeypatch.setenv("SKIP_UV", "1")
44+
main(dry=True)
45+
captured = capsys.readouterr()
46+
assert "'SKIP_UV' is deprecated" in captured.out

tests/unit/test_cli_precedence.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""Test for cli and environment variable precedence."""
2+
3+
from __future__ import annotations
4+
5+
from typing import TypedDict
6+
7+
import pytest
8+
9+
from ansible_dev_environment.cli import Cli
10+
11+
12+
class Data(TypedDict):
13+
"""Test data dictionary.
14+
15+
Attributes:
16+
attr: Attribute name.
17+
args: Command line argument.
18+
env: Environment variable name.
19+
cli_expected: Expected value from command line argument.
20+
env_expected: Expected value from environment variable.
21+
22+
"""
23+
24+
attr: str
25+
args: str
26+
env: str
27+
cli_expected: bool | int | str
28+
env_expected: bool | int | str
29+
30+
31+
params: list[Data] = [
32+
{
33+
"attr": "ansi",
34+
"args": "--ansi",
35+
"env": "NO_COLOR",
36+
"env_expected": False,
37+
"cli_expected": True,
38+
},
39+
{
40+
"attr": "seed",
41+
"args": "--seed",
42+
"env": "ADE_SEED",
43+
"env_expected": False,
44+
"cli_expected": True,
45+
},
46+
{"attr": "verbose", "args": "-vvv", "env": "ADE_VERBOSE", "env_expected": 2, "cli_expected": 3},
47+
{"attr": "uv", "args": "--uv", "env": "ADE_UV", "env_expected": False, "cli_expected": True},
48+
]
49+
50+
51+
@pytest.mark.parametrize("data", params, ids=lambda d: d["attr"])
52+
def test_cli_precedence_flag(
53+
data: Data,
54+
monkeypatch: pytest.MonkeyPatch,
55+
) -> None:
56+
"""Test CLI precedence over environment variables.
57+
58+
Args:
59+
data: Test data dictionary.
60+
monkeypatch: Pytest fixture.
61+
62+
"""
63+
cli = Cli()
64+
65+
args = ["ade", "install"]
66+
monkeypatch.setenv(data["env"], str(data["env_expected"]))
67+
monkeypatch.setattr("sys.argv", args)
68+
69+
cli.parse_args()
70+
71+
assert getattr(cli.args, data["attr"]) == data["env_expected"]
72+
73+
args.append(data["args"])
74+
cli.parse_args()
75+
assert getattr(cli.args, data["attr"]) == data["cli_expected"]

tests/unit/test_utils.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
)
1414
from ansible_dev_environment.config import Config
1515
from ansible_dev_environment.output import Output
16-
from ansible_dev_environment.utils import TermFeatures, builder_introspect
16+
from ansible_dev_environment.utils import TermFeatures, builder_introspect, str_to_bool
1717

1818

1919
term_features = TermFeatures(color=False, links=False)
@@ -174,3 +174,25 @@ def cache_dir(_self: Config) -> Path:
174174

175175
assert cfg.discovered_bindep_reqs.exists() is True
176176
assert cfg.discovered_python_reqs.exists() is True
177+
178+
179+
def test_str_to_bool() -> None:
180+
"""Test the str_to_bool function.
181+
182+
This function tests the conversion of string values to boolean values.
183+
"""
184+
assert str_to_bool("true") is True
185+
assert str_to_bool("True") is True
186+
assert str_to_bool("1") is True
187+
assert str_to_bool("yes") is True
188+
assert str_to_bool("y") is True
189+
assert str_to_bool("on") is True
190+
191+
assert str_to_bool("false") is False
192+
assert str_to_bool("False") is False
193+
assert str_to_bool("0") is False
194+
assert str_to_bool("no") is False
195+
assert str_to_bool("n") is False
196+
assert str_to_bool("off") is False
197+
198+
assert str_to_bool("anything else") is None

0 commit comments

Comments
 (0)