Debian Codegraph @

tests/conftest.py

raw symbols SCIP
1 import inspect
2 import sys
3 from pathlib import Path
4
5 import pytest
6 from rich.console import Console
7 from syrupy.extensions.single_file import SingleFileSnapshotExtension, WriteMode
8
9 import cyclopts
10 from cyclopts import Group, Parameter
11
12
13 def pytest_addoption(parser):
14 parser.addoption(
15 "--run-slow",
16 action="store_true",
17 default=False,
18 help="Run slow tests (e.g., documentation build tests)",
19 )
20
21
22 def pytest_configure(config):
23 # If --run-slow is passed, remove the default "-m 'not slow'" filter
24 if config.getoption("--run-slow"):
25 # Override the marker expression to include all tests
26 config.option.markexpr = ""
27
28
29 class MarkdownSnapshotExtension(SingleFileSnapshotExtension):
30 _write_mode = WriteMode.TEXT
31 file_extension = "md"
32
33
34 class RstSnapshotExtension(SingleFileSnapshotExtension):
35 _write_mode = WriteMode.TEXT
36 file_extension = "rst"
37
38
39 @pytest.fixture
40 def md_snapshot(snapshot):
41 return snapshot.use_extension(MarkdownSnapshotExtension)
42
43
44 @pytest.fixture
45 def rst_snapshot(snapshot):
46 return snapshot.use_extension(RstSnapshotExtension)
47
48
49 def pytest_ignore_collect(collection_path):
50 for minor in range(8, 20):
51 if sys.version_info < (3, minor) and collection_path.stem.startswith(f"test_py3{minor}_"):
52 return True
53
54 # Ignore py312/ directory on Python < 3.12
55 if sys.version_info < (3, 12) and "py312" in collection_path.parts:
56 return True
57
58
59 @pytest.fixture(autouse=True)
60 def patch_sys_argv(request, monkeypatch):
61 """Ensure consistent sys.argv[0] regardless of how pytest is invoked.
62
63 When tests run, cyclopts derives app names from sys.argv[0].
64 This can vary based on how pytest is invoked:
65 - `pytest`: sys.argv[0] is the pytest executable path
66 - `python -m pytest`: sys.argv[0] is the pytest module's __main__.py
67
68 We patch it to always be the test module's __main__.py to trigger
69 consistent stack-based name derivation.
70 """
71 monkeypatch.setattr(sys, "argv", ["__main__.py"] + sys.argv[1:])
72
73
74 @pytest.fixture(autouse=True)
75 def chdir_to_tmp_path(tmp_path, monkeypatch):
76 """Automatically change current directory to tmp_path"""
77 monkeypatch.chdir(tmp_path)
78
79
80 @pytest.fixture
81 def app():
82 return cyclopts.App(result_action="return_value")
83
84
85 @pytest.fixture
86 def console():
87 return Console(width=70, force_terminal=True, highlight=False, color_system=None, legacy_windows=False)
88
89
90 @pytest.fixture
91 def rich_console():
92 """Console that emits ANSI escapes -- for asserting styled output."""
93 return Console(width=70, force_terminal=True, highlight=False, color_system="truecolor", legacy_windows=False)
94
95
96 @pytest.fixture
97 def normalize_trailing_whitespace():
98 """Remove trailing whitespace from each line while preserving line breaks.
99
100 Useful for comparing console output where text wrapping may add trailing spaces.
101 """
102
103 def _normalize(text: str) -> str:
104 return "\n".join(line.rstrip() for line in text.split("\n"))
105
106 return _normalize
107
108
109 @pytest.fixture
110 def default_function_groups():
111 return (Parameter(), Group("Arguments"), Group("Parameters"))
112
113
114 @pytest.fixture
115 def assert_parse_args(app):
116 def inner(f, cmd: str, *args, **kwargs):
117 signature = inspect.signature(f)
118 expected_bind = signature.bind(*args, **kwargs)
119 actual_command, actual_bind, _ = app.parse_args(cmd, print_error=False, exit_on_error=False)
120 assert actual_command == f
121 assert actual_bind == expected_bind
122
123 return inner
124
125
126 @pytest.fixture
127 def assert_parse_args_config(app):
128 def inner(config: dict, f, cmd: str, *args, **kwargs):
129 signature = inspect.signature(f)
130 expected_bind = signature.bind(*args, **kwargs)
131 actual_command, actual_bind, _ = app.parse_args(cmd, print_error=False, exit_on_error=False, **config)
132 assert actual_command == f
133 assert actual_bind == expected_bind
134
135 return inner
136
137
138 @pytest.fixture
139 def assert_parse_args_partial(app):
140 def inner(f, cmd: str, *args, **kwargs):
141 signature = inspect.signature(f)
142 expected_bind = signature.bind_partial(*args, **kwargs)
143 actual_command, actual_bind, _ = app.parse_args(cmd, print_error=False, exit_on_error=False)
144 assert actual_command == f
145 assert actual_bind == expected_bind
146
147 return inner
148
149
150 @pytest.fixture
151 def convert():
152 """Function that performs a conversion for a given type/cmd pair.
153
154 Goes through the whole app stack.
155 """
156
157 def inner(type_, cmd):
158 app = cyclopts.App(result_action="return_value")
159
160 if isinstance(cmd, Path):
161 cmd = cmd.as_posix()
162
163 @app.default
164 def target(arg1: type_): # pyright: ignore
165 return arg1
166
167 return app(cmd, exit_on_error=False)
168
169 return inner