Debian Codegraph @

testing/conftest.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Generator
5 import importlib.metadata
6 import re
7 import sys
8
9 from packaging.version import Version
10
11 from _pytest.monkeypatch import MonkeyPatch
12 from _pytest.pytester import Pytester
13 import pytest
14
15
16 if sys.gettrace():
17
18 @pytest.fixture(autouse=True)
19 def restore_tracing():
20 """Restore tracing function (when run with Coverage.py).
21
22 https://bugs.python.org/issue37011
23 """
24 orig_trace = sys.gettrace()
25 yield
26 if sys.gettrace() != orig_trace:
27 sys.settrace(orig_trace)
28
29
30 @pytest.fixture(autouse=True)
31 def set_column_width(monkeypatch: pytest.MonkeyPatch) -> None:
32 """
33 Force terminal width to 80: some tests check the formatting of --help, which is sensible
34 to terminal width.
35 """
36 monkeypatch.setenv("COLUMNS", "80")
37
38
39 @pytest.fixture(autouse=True)
40 def reset_colors(monkeypatch: pytest.MonkeyPatch) -> None:
41 """
42 Reset all color-related variables to prevent them from affecting internal pytest output
43 in tests that depend on it.
44 """
45 monkeypatch.delenv("PY_COLORS", raising=False)
46 monkeypatch.delenv("NO_COLOR", raising=False)
47 monkeypatch.delenv("FORCE_COLOR", raising=False)
48
49
50 @pytest.hookimpl(wrapper=True, tryfirst=True)
51 def pytest_collection_modifyitems(items) -> Generator[None]:
52 """Prefer faster tests.
53
54 Use a hook wrapper to do this in the beginning, so e.g. --ff still works
55 correctly.
56 """
57 fast_items = []
58 slow_items = []
59 slowest_items = []
60 neutral_items = []
61
62 spawn_names = {"spawn_pytest", "spawn"}
63
64 for item in items:
65 try:
66 fixtures = item.fixturenames
67 except AttributeError:
68 # doctest at least
69 # (https://github.com/pytest-dev/pytest/issues/5070)
70 neutral_items.append(item)
71 else:
72 if "pytester" in fixtures:
73 co_names = item.function.__code__.co_names
74 if spawn_names.intersection(co_names):
75 item.add_marker(pytest.mark.uses_pexpect)
76 slowest_items.append(item)
77 elif "runpytest_subprocess" in co_names:
78 slowest_items.append(item)
79 else:
80 slow_items.append(item)
81 item.add_marker(pytest.mark.slow)
82 else:
83 marker = item.get_closest_marker("slow")
84 if marker:
85 slowest_items.append(item)
86 else:
87 fast_items.append(item)
88
89 items[:] = fast_items + neutral_items + slow_items + slowest_items
90
91 return (yield)
92
93
94 @pytest.fixture
95 def tw_mock():
96 """Returns a mock terminal writer"""
97
98 class TWMock:
99 WRITE = object()
100
101 def __init__(self):
102 self.lines = []
103 self.is_writing = False
104
105 def sep(self, sep, line=None):
106 self.lines.append((sep, line))
107
108 def write(self, msg, **kw):
109 self.lines.append((TWMock.WRITE, msg))
110
111 def _write_source(self, lines, indents=()):
112 if not indents:
113 indents = [""] * len(lines)
114 for indent, line in zip(indents, lines, strict=True):
115 self.line(indent + line)
116
117 def line(self, line, **kw):
118 self.lines.append(line)
119
120 def markup(self, text, **kw):
121 return text
122
123 def get_write_msg(self, idx):
124 assert self.lines[idx][0] == TWMock.WRITE
125 msg = self.lines[idx][1]
126 return msg
127
128 fullwidth = 80
129
130 return TWMock()
131
132
133 @pytest.fixture
134 def dummy_yaml_custom_test(pytester: Pytester) -> None:
135 """Writes a conftest file that collects and executes a dummy yaml test.
136
137 Taken from the docs, but stripped down to the bare minimum, useful for
138 tests which needs custom items collected.
139 """
140 pytester.makeconftest(
141 """
142 import pytest
143
144 def pytest_collect_file(parent, file_path):
145 if file_path.suffix == ".yaml" and file_path.name.startswith("test"):
146 return YamlFile.from_parent(path=file_path, parent=parent)
147
148 class YamlFile(pytest.File):
149 def collect(self):
150 yield YamlItem.from_parent(name=self.path.name, parent=self)
151
152 class YamlItem(pytest.Item):
153 def runtest(self):
154 pass
155 """
156 )
157 pytester.makefile(".yaml", test1="")
158
159
160 @pytest.fixture
161 def pytester(pytester: Pytester, monkeypatch: MonkeyPatch) -> Pytester:
162 monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
163 return pytester
164
165
166 @pytest.fixture(scope="session")
167 def color_mapping():
168 """Returns a utility class which can replace keys in strings in the form "{NAME}"
169 by their equivalent ASCII codes in the terminal.
170
171 Used by tests which check the actual colors output by pytest.
172 """
173 # https://github.com/pygments/pygments/commit/d24e272894a56a98b1b718d9ac5fabc20124882a
174 pygments_version = Version(importlib.metadata.version("pygments"))
175 pygments_has_kwspace_hl = pygments_version >= Version("2.19")
176
177 class ColorMapping:
178 COLORS = {
179 "red": "\x1b[31m",
180 "green": "\x1b[32m",
181 "yellow": "\x1b[33m",
182 "light-gray": "\x1b[90m",
183 "light-red": "\x1b[91m",
184 "light-green": "\x1b[92m",
185 "bold": "\x1b[1m",
186 "reset": "\x1b[0m",
187 "kw": "\x1b[94m",
188 "kwspace": "\x1b[90m \x1b[39;49;00m" if pygments_has_kwspace_hl else " ",
189 "hl-reset": "\x1b[39;49;00m",
190 "function": "\x1b[92m",
191 "number": "\x1b[94m",
192 "str": "\x1b[33m",
193 "print": "\x1b[96m",
194 "endline": "\x1b[90m\x1b[39;49;00m",
195 }
196 RE_COLORS = {k: re.escape(v) for k, v in COLORS.items()}
197 NO_COLORS = {k: "" for k in COLORS.keys()}
198
199 @classmethod
200 def format(cls, lines: list[str]) -> list[str]:
201 """Straightforward replacement of color names to their ASCII codes."""
202 return [line.format(**cls.COLORS) for line in lines]
203
204 @classmethod
205 def format_for_fnmatch(cls, lines: list[str]) -> list[str]:
206 """Replace color names for use with LineMatcher.fnmatch_lines"""
207 return [line.format(**cls.COLORS).replace("[", "[[]") for line in lines]
208
209 @classmethod
210 def format_for_rematch(cls, lines: list[str]) -> list[str]:
211 """Replace color names for use with LineMatcher.re_match_lines"""
212 return [line.format(**cls.RE_COLORS) for line in lines]
213
214 @classmethod
215 def strip_colors(cls, lines: list[str]) -> list[str]:
216 """Entirely remove every color code"""
217 return [line.format(**cls.NO_COLORS) for line in lines]
218
219 return ColorMapping
220
221
222 @pytest.fixture
223 def mock_timing(monkeypatch: MonkeyPatch):
224 """Mocks _pytest.timing with a known object that can be used to control timing in tests
225 deterministically.
226
227 pytest itself should always use functions from `_pytest.timing` instead of `time` directly.
228
229 This then allows us more control over time during testing, if testing code also
230 uses `_pytest.timing` functions.
231
232 Time is static, and only advances through `sleep` calls, thus tests might sleep over large
233 numbers and obtain accurate time() calls at the end, making tests reliable and instant.
234 """
235 from _pytest.timing import MockTiming
236
237 result = MockTiming()
238 result.patch(monkeypatch)
239 return result
240
241
242 @pytest.fixture(autouse=True)
243 def remove_ci_env_var(monkeypatch: MonkeyPatch, request: pytest.FixtureRequest) -> None:
244 """Make the test insensitive if it is running in CI or not.
245
246 Use `@pytest.mark.keep_ci_var` in a test to avoid applying this fixture, letting the test
247 see the real `CI` variable (if present).
248 """
249 has_keep_ci_mark = request.node.get_closest_marker("keep_ci_var") is not None
250 if not has_keep_ci_mark:
251 monkeypatch.delenv("CI", raising=False)