Debian Codegraph @

tests/unit/test_entrypoints.py

raw
1 """Tests for all entrypints modules."""
2
3 import re
4 from io import TextIOWrapper
5 from pathlib import Path
6 from typing import Any, Sequence
7
8 import click
9 import pytest
10
11 from autoimport.entrypoints.cli import FileOrDir, flatten, get_files
12
13
14 @pytest.mark.parametrize(
15 ("sequence", "expected"),
16 [
17 ((1, (2, 3, 4), 5), (1, 2, 3, 4, 5)),
18 ([1, 2, 3, [4, 5, 6]], (1, 2, 3, 4, 5, 6)),
19 ([["a", "b", "c"], "d"], ("a", "b", "c", "d")),
20 ],
21 )
22 def test_flatten(sequence: Sequence[Any], expected: Sequence[Any]) -> None:
23 """Test the flatten function works."""
24 result = flatten(sequence)
25
26 assert result == expected
27
28
29 def test_custom_param_type_works_with_dir(test_dir: Path) -> None:
30 """Ensure the custom param type can be parsed a directory."""
31 param_type = FileOrDir()
32
33 result = param_type.convert(test_dir, None, None)
34
35 for file_ in result:
36 assert isinstance(file_, TextIOWrapper)
37 assert re.match(r".*file[1-2].py", file_.name)
38 file_.close()
39
40
41 def test_custom_param_type_works_with_file(test_dir: Path) -> None:
42 """Ensure the custom param type can be parsed a file."""
43 param_type = FileOrDir()
44
45 result = param_type.convert(test_dir / "test_file1.py", None, None)
46
47 assert re.match(r".*file[1-2].py", result[0].name)
48 result[0].close()
49
50
51 @pytest.mark.parametrize("filename", ["h.py", "new_dir"])
52 def test_custom_param_type_with_non_existing_files(
53 test_dir: Path, filename: str
54 ) -> None:
55 """Ensure an error occurs when a non existing file or dir is parsed."""
56 param_type = FileOrDir()
57
58 with pytest.raises(click.BadParameter) as error:
59 param_type.convert(test_dir / filename, None, None)
60
61 assert f"{filename}' does not exist" in error.value.args[0]
62
63
64 def test_get_files(test_dir: Path) -> None:
65 """Ensure we can get all files recursively from a given directory."""
66 result = get_files(str(test_dir))
67
68 assert all(re.match(r".*file[1-2].py", file.name) for file in result)
69 for file_path in result:
70 file_path.close()