Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some tests #160

Merged
merged 6 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .config/dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ cpart
cpath
crepository
csource
delenv
excinfo
fileh
fqcn
jsonschema
levelname
levelno
netcommon
Expand All @@ -23,5 +25,6 @@ setenv
specp
treemaker
uninstallation
usefixtures
vuuid
xmltodict
2 changes: 1 addition & 1 deletion src/ansible_dev_environment/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
via :command:`python -m ansible_dev_environment`.
"""

from .cli import main
from ansible_dev_environment.cli import main


if __name__ == "__main__":
Expand Down
23 changes: 14 additions & 9 deletions src/ansible_dev_environment/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,20 +200,25 @@ def parse() -> argparse.Namespace:
help="Uninstall a collection.",
)

for grp in parser._action_groups: # noqa: SLF001
if grp.title is None:
continue
grp.title = grp.title.capitalize()
_group_titles(parser)
for subparser in subparsers.choices.values():
for grp in subparser._action_groups: # noqa: SLF001
if grp.title is None:
continue
grp.title = grp.title.capitalize()
# pylint: enable=protected-access
_group_titles(subparser)

return parser.parse_args()


def _group_titles(parser: ArgumentParser) -> None:
"""Set the group titles to be capitalized.
Args:
parser: The parser to set the group titles for
"""
for group in parser._action_groups: # noqa: SLF001
if group.title is None:
continue
group.title = group.title.capitalize()


class ArgumentParser(argparse.ArgumentParser):
"""A custom argument parser."""

Expand Down
4 changes: 0 additions & 4 deletions src/ansible_dev_environment/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,3 @@ def main() -> None:
cli.args_sanity()
cli.ensure_isolated()
cli.run()


if __name__ == "__main__":
main()
16 changes: 5 additions & 11 deletions src/ansible_dev_environment/subcommands/treemaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, cast

from ansible_dev_environment.tree import Tree
from ansible_dev_environment.utils import builder_introspect, collect_manifests
Expand Down Expand Up @@ -44,10 +44,7 @@
target=self._config.site_pkg_collections_path,
venv_cache_dir=self._config.venv_cache_dir,
)
tree_dict: JSONVal = {c: {} for c in collections}
if not isinstance(tree_dict, dict):
msg = "Tree dict is not a dict."
raise TypeError(msg)
tree_dict: dict[str, dict[str, JSONVal]] = {c: {} for c in collections}

links: dict[str, str] = {}
for collection_name, collection in collections.items():
Expand All @@ -65,10 +62,6 @@
self._output.error(err)
continue
target = tree_dict[collection_name]
if not isinstance(target, dict):
msg = "Tree dict is not a dict."
raise TypeError(msg)

target[dep] = tree_dict[dep]

docs = collection["collection_info"].get("documentation")
Expand Down Expand Up @@ -97,7 +90,8 @@

more_verbose = 2
if self._config.args.verbose >= more_verbose:
tree = Tree(obj=tree_dict, term_features=self._config.term_features)
j_tree_dict = cast(JSONVal, tree_dict)
tree = Tree(obj=j_tree_dict, term_features=self._config.term_features)

Check warning on line 94 in src/ansible_dev_environment/subcommands/treemaker.py

View check run for this annotation

Codecov / codecov/patch

src/ansible_dev_environment/subcommands/treemaker.py#L93-L94

Added lines #L93 - L94 were not covered by tests
tree.links = links
tree.green.extend(green)
rendered = tree.render()
Expand Down Expand Up @@ -132,7 +126,7 @@


def add_python_reqs(
tree_dict: dict[str, JSONVal],
tree_dict: dict[str, dict[str, JSONVal]],
collection_name: str,
python_deps: list[str],
) -> None:
Expand Down
9 changes: 3 additions & 6 deletions tests/integration/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,16 +137,13 @@ def test_non_local(
assert string in captured.out
monkeypatch.setattr(
"sys.argv",
["ade", "tree", f"--venv={tmp_path / 'venv'}"],
["ade", "tree", f"--venv={tmp_path / 'venv'}", "-v"],
)
with pytest.raises(SystemExit):
main()
captured = capsys.readouterr()
with pytest.raises(SystemExit):
main()
captured = capsys.readouterr()
string = "ansible.scm\n└──ansible.utils\n\n"
assert string == captured.out
assert "ansible.scm\n├──ansible.utils" in captured.out
assert "├──jsonschema" in captured.out


def test_requirements(
Expand Down
92 changes: 92 additions & 0 deletions tests/test_argparser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Tests for the arg_parser module."""

import pytest

from ansible_dev_environment.arg_parser import (
ArgumentParser,
CustomHelpFormatter,
_group_titles,
)


def test_no_option_string(
capsys: pytest.CaptureFixture[str],
) -> None:
"""Test an argument without an option string.
Args:
capsys: Pytest fixture.
"""
parser = ArgumentParser(
formatter_class=CustomHelpFormatter,
)
parser.add_argument(
dest="test",
action="store_true",
help="Test this",
)
parser.print_help()
captured = capsys.readouterr()
assert "Test this" in captured.out


def test_one_string(
capsys: pytest.CaptureFixture[str],
) -> None:
"""Test an argument without an option string.
Args:
capsys: Pytest fixture.
"""
parser = ArgumentParser(
formatter_class=CustomHelpFormatter,
)
parser.add_argument(
"-t",
dest="test",
action="store_true",
help="Test this",
)
parser.print_help()
captured = capsys.readouterr()
assert "-t Test this" in captured.out


def test_too_many_string(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test an argument with too many option strings.
Args:
monkeypatch: Pytest fixture.
"""
monkeypatch.setattr("sys.argv", ["prog", "--help"])

parser = ArgumentParser(
formatter_class=CustomHelpFormatter,
)
parser.add_argument(
"-t",
"-test",
"--test",
action="store_true",
help="Test this",
)
with pytest.raises(ValueError, match="Too many option strings"):
parser.parse_args()


def test_group_no_title(capsys: pytest.CaptureFixture[str]) -> None:
"""Test a group without a title.
Args:
capsys: Pytest fixture.
"""
parser = ArgumentParser(
formatter_class=CustomHelpFormatter,
)
parser.add_argument_group()
_group_titles(parser)
parser.print_help()
captured = capsys.readouterr()
assert "--help" in captured.out
22 changes: 22 additions & 0 deletions tests/unit/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,25 @@ def output(tmp_path: Path) -> Output:
term_features=TermFeatures(color=False, links=False),
verbosity=0,
)


@pytest.fixture(name="_wide_console")
def _wide_console(monkeypatch: pytest.MonkeyPatch) -> None:
"""Fixture to set the terminal width to 1000 to prevent wrapping.
Args:
monkeypatch: Pytest fixture.
"""

def _console_width() -> int:
"""Return a large console width.
Returns:
int: Console width.
"""
return 1000

monkeypatch.setattr(
"ansible_dev_environment.output.console_width",
_console_width,
)
Loading
Loading