Skip to content

Commit b7c9bf4

Browse files
authored
Move tests for file_utils out of generic TestUtils file (#1873)
1 parent 34a2798 commit b7c9bf4

File tree

2 files changed

+202
-188
lines changed

2 files changed

+202
-188
lines changed

test/TestUtils.py

Lines changed: 3 additions & 188 deletions
Original file line numberDiff line numberDiff line change
@@ -28,28 +28,19 @@
2828
import sys
2929
from argparse import Namespace
3030
from pathlib import Path
31-
from typing import Any, Dict, List, Sequence, Tuple, Union
31+
from typing import Any, Dict, List, Sequence, Tuple
3232

3333
import pytest
3434
from _pytest.capture import CaptureFixture
3535
from _pytest.logging import LogCaptureFixture
3636
from _pytest.monkeypatch import MonkeyPatch
3737

38-
from ansiblelint import cli, constants, file_utils, utils
38+
from ansiblelint import cli, constants, utils
3939
from ansiblelint.__main__ import initialize_logger
4040
from ansiblelint.cli import get_rules_dirs
41-
from ansiblelint.constants import FileType
42-
from ansiblelint.file_utils import (
43-
Lintable,
44-
expand_path_vars,
45-
expand_paths_vars,
46-
guess_project_dir,
47-
normpath,
48-
)
41+
from ansiblelint.file_utils import Lintable
4942
from ansiblelint.testing import run_ansible_lint
5043

51-
from .conftest import cwd
52-
5344

5445
@pytest.mark.parametrize(
5546
("string", "expected_cmd", "expected_args", "expected_kwargs"),
@@ -228,116 +219,6 @@ def test_task_to_str_unicode() -> None:
228219
assert result == u"fail msg=unicode é ô à"
229220

230221

231-
@pytest.mark.parametrize(
232-
"path",
233-
(
234-
pytest.param(Path("a/b/../"), id="pathlib.Path"),
235-
pytest.param("a/b/../", id="str"),
236-
),
237-
)
238-
def test_normpath_with_path_object(path: str) -> None:
239-
"""Ensure that relative parent dirs are normalized in paths."""
240-
assert normpath(path) == "a"
241-
242-
243-
def test_expand_path_vars(monkeypatch: MonkeyPatch) -> None:
244-
"""Ensure that tilde and env vars are expanded in paths."""
245-
test_path = "/test/path"
246-
monkeypatch.setenv("TEST_PATH", test_path)
247-
assert expand_path_vars("~") == os.path.expanduser("~")
248-
assert expand_path_vars("$TEST_PATH") == test_path
249-
250-
251-
@pytest.mark.parametrize(
252-
("test_path", "expected"),
253-
(
254-
pytest.param(Path("$TEST_PATH"), "/test/path", id="pathlib.Path"),
255-
pytest.param("$TEST_PATH", "/test/path", id="str"),
256-
pytest.param(" $TEST_PATH ", "/test/path", id="stripped-str"),
257-
pytest.param("~", os.path.expanduser("~"), id="home"),
258-
),
259-
)
260-
def test_expand_paths_vars(
261-
test_path: Union[str, Path], expected: str, monkeypatch: MonkeyPatch
262-
) -> None:
263-
"""Ensure that tilde and env vars are expanded in paths lists."""
264-
monkeypatch.setenv("TEST_PATH", "/test/path")
265-
assert expand_paths_vars([test_path]) == [expected] # type: ignore
266-
267-
268-
@pytest.mark.parametrize(
269-
("reset_env_var", "message_prefix"),
270-
(
271-
# simulate absence of git command
272-
("PATH", "Failed to locate command: "),
273-
# simulate a missing git repo
274-
("GIT_DIR", "Looking up for files"),
275-
),
276-
ids=("no-git-cli", "outside-git-repo"),
277-
)
278-
def test_discover_lintables_git_verbose(
279-
reset_env_var: str,
280-
message_prefix: str,
281-
monkeypatch: MonkeyPatch,
282-
caplog: LogCaptureFixture,
283-
) -> None:
284-
"""Ensure that autodiscovery lookup failures are logged."""
285-
options = cli.get_config(["-v"])
286-
initialize_logger(options.verbosity)
287-
monkeypatch.setenv(reset_env_var, "")
288-
file_utils.discover_lintables(options)
289-
290-
assert any(m[2].startswith("Looking up for files") for m in caplog.record_tuples)
291-
assert any(m.startswith(message_prefix) for m in caplog.messages)
292-
293-
294-
@pytest.mark.parametrize(
295-
"is_in_git",
296-
(True, False),
297-
ids=("in Git", "outside Git"),
298-
)
299-
def test_discover_lintables_silent(
300-
is_in_git: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture[str]
301-
) -> None:
302-
"""Verify that no stderr output is displayed while discovering yaml files.
303-
304-
(when the verbosity is off, regardless of the Git or Git-repo presence)
305-
306-
Also checks expected number of files are detected.
307-
"""
308-
options = cli.get_config([])
309-
test_dir = Path(__file__).resolve().parent
310-
lint_path = test_dir / ".." / "examples" / "roles" / "test-role"
311-
if not is_in_git:
312-
monkeypatch.setenv("GIT_DIR", "")
313-
314-
yaml_count = len(list(lint_path.glob("**/*.yml"))) + len(
315-
list(lint_path.glob("**/*.yaml"))
316-
)
317-
318-
monkeypatch.chdir(str(lint_path))
319-
files = file_utils.discover_lintables(options)
320-
stderr = capsys.readouterr().err
321-
assert not stderr, "No stderr output is expected when the verbosity is off"
322-
assert (
323-
len(files) == yaml_count
324-
), "Expected to find {yaml_count} yaml files in {lint_path}".format_map(
325-
locals(),
326-
)
327-
328-
329-
def test_discover_lintables_umlaut(monkeypatch: MonkeyPatch) -> None:
330-
"""Verify that filenames containing German umlauts are not garbled by the discover_lintables."""
331-
options = cli.get_config([])
332-
test_dir = Path(__file__).resolve().parent
333-
lint_path = test_dir / ".." / "examples" / "playbooks"
334-
335-
monkeypatch.chdir(str(lint_path))
336-
files = file_utils.discover_lintables(options)
337-
assert '"with-umlaut-\\303\\244.yml"' not in files
338-
assert "with-umlaut-ä.yml" in files
339-
340-
341222
def test_logger_debug(caplog: LogCaptureFixture) -> None:
342223
"""Test that the double verbosity arg causes logger to be DEBUG."""
343224
options = cli.get_config(["-vv"])
@@ -395,65 +276,6 @@ def test_is_playbook() -> None:
395276
assert utils.is_playbook("examples/playbooks/always-run-success.yml")
396277

397278

398-
@pytest.mark.parametrize(
399-
("path", "kind"),
400-
(
401-
("foo/playbook.yml", "playbook"),
402-
("playbooks/foo.yml", "playbook"),
403-
("playbooks/roles/foo.yml", "yaml"),
404-
# the only yml file that is not a playbook inside molecule/ folders
405-
(".config/molecule/config.yml", "yaml"), # molecule shared config
406-
("roles/foo/molecule/scen1/base.yml", "yaml"), # molecule scenario base config
407-
("roles/foo/molecule/scen1/molecule.yml", "yaml"), # molecule scenario config
408-
("roles/foo/molecule/scen2/foobar.yml", "playbook"), # custom playbook name
409-
("roles/foo/molecule/scen3/converge.yml", "playbook"), # common playbook name
410-
("roles/foo/molecule/scen3/requirements.yml", "requirements"), # requirements
411-
("roles/foo/molecule/scen3/collections.yml", "requirements"), # requirements
412-
# tasks files:
413-
("tasks/directory with spaces/main.yml", "tasks"), # tasks
414-
("tasks/requirements.yml", "tasks"), # tasks
415-
# requirements (we do not support includes yet)
416-
("requirements.yml", "requirements"), # collection requirements
417-
("roles/foo/meta/requirements.yml", "requirements"), # inside role requirements
418-
# Undeterminable files:
419-
("test/fixtures/unknown-type.yml", "yaml"),
420-
("releasenotes/notes/run-playbooks-refactor.yaml", "reno"), # reno
421-
("examples/host_vars/localhost.yml", "vars"),
422-
("examples/group_vars/all.yml", "vars"),
423-
("examples/playbooks/vars/other.yml", "vars"),
424-
("examples/playbooks/vars/subfolder/settings.yml", "vars"), # deep vars
425-
("molecule/scenario/collections.yml", "requirements"), # deprecated 2.8 format
426-
(
427-
"../roles/geerlingguy.mysql/tasks/configure.yml",
428-
"tasks",
429-
), # relative path involved
430-
("galaxy.yml", "galaxy"),
431-
("foo.j2.yml", "jinja2"),
432-
("foo.yml.j2", "jinja2"),
433-
("foo.j2.yaml", "jinja2"),
434-
("foo.yaml.j2", "jinja2"),
435-
),
436-
)
437-
def test_default_kinds(monkeypatch: MonkeyPatch, path: str, kind: FileType) -> None:
438-
"""Verify auto-detection logic based on DEFAULT_KINDS."""
439-
options = cli.get_config([])
440-
441-
def mockreturn(options: Namespace) -> Dict[str, Any]:
442-
return {path: kind}
443-
444-
# assert Lintable is able to determine file type
445-
lintable_detected = Lintable(path)
446-
lintable_expected = Lintable(path, kind=kind)
447-
assert lintable_detected == lintable_expected
448-
449-
monkeypatch.setattr(file_utils, "discover_lintables", mockreturn)
450-
result = file_utils.discover_lintables(options)
451-
# get_lintable could return additional files and we only care to see
452-
# that the given file is among the returned list.
453-
assert lintable_detected.name in result
454-
assert lintable_detected.kind == result[lintable_expected.name]
455-
456-
457279
def test_auto_detect_exclude(monkeypatch: MonkeyPatch) -> None:
458280
"""Verify that exclude option can be used to narrow down detection."""
459281
options = cli.get_config(["--exclude", "foo"])
@@ -530,10 +352,3 @@ def test_nested_items() -> None:
530352
match=r"Call to deprecated function ansiblelint\.utils\.nested_items.*"
531353
):
532354
assert list(utils.nested_items(data)) == items
533-
534-
535-
def test_guess_project_dir(tmp_path: Path) -> None:
536-
"""Verify guess_project_dir()."""
537-
with cwd(str(tmp_path)):
538-
result = guess_project_dir(None)
539-
assert result == str(tmp_path)

0 commit comments

Comments
 (0)