Debian Codegraph @

src/_pytest/subtests.py

raw
1 """Builtin plugin that adds subtests support."""
2
3 from __future__ import annotations
4
5 from collections import defaultdict
6 from collections.abc import Callable
7 from collections.abc import Iterator
8 from collections.abc import Mapping
9 from contextlib import AbstractContextManager
10 from contextlib import contextmanager
11 from contextlib import ExitStack
12 from contextlib import nullcontext
13 import dataclasses
14 import time
15 from types import TracebackType
16 from typing import Any
17 from typing import TYPE_CHECKING
18
19 import pluggy
20
21 from _pytest._code import ExceptionInfo
22 from _pytest._io.saferepr import saferepr
23 from _pytest.capture import CaptureFixture
24 from _pytest.capture import FDCapture
25 from _pytest.capture import SysCapture
26 from _pytest.config import Config
27 from _pytest.config import hookimpl
28 from _pytest.config.argparsing import Parser
29 from _pytest.deprecated import check_ispytest
30 from _pytest.fixtures import fixture
31 from _pytest.fixtures import SubRequest
32 from _pytest.logging import catching_logs
33 from _pytest.logging import LogCaptureHandler
34 from _pytest.logging import LoggingPlugin
35 from _pytest.reports import TestReport
36 from _pytest.runner import CallInfo
37 from _pytest.runner import check_interactive_exception
38 from _pytest.runner import get_reraise_exceptions
39 from _pytest.stash import StashKey
40
41
42 if TYPE_CHECKING:
43 from typing_extensions import Self
44
45
46 def pytest_addoption(parser: Parser) -> None:
47 Config._add_verbosity_ini(
48 parser,
49 Config.VERBOSITY_SUBTESTS,
50 help=(
51 "Specify verbosity level for subtests. "
52 "Higher levels will generate output for passed subtests. Failed subtests are always reported."
53 ),
54 )
55
56
57 @dataclasses.dataclass(frozen=True, slots=True, kw_only=True)
58 class SubtestContext:
59 """The values passed to Subtests.test() that are included in the test report."""
60
61 msg: str | None
62 kwargs: Mapping[str, Any]
63
64 def __post_init__(self) -> None:
65 # Brute-force the returned kwargs dict to be JSON serializable (pytest-dev/pytest-xdist#1273).
66 object.__setattr__(
67 self, "kwargs", {k: saferepr(v) for (k, v) in self.kwargs.items()}
68 )
69
70 def _to_json(self) -> dict[str, Any]:
71 result = dataclasses.asdict(self)
72 return result
73
74 @classmethod
75 def _from_json(cls, d: dict[str, Any]) -> Self:
76 return cls(msg=d["msg"], kwargs=d["kwargs"])
77
78
79 @dataclasses.dataclass(init=False)
80 class SubtestReport(TestReport):
81 context: SubtestContext
82
83 @property
84 def head_line(self) -> str:
85 _, _, domain = self.location
86 return f"{domain} {self._sub_test_description()}"
87
88 def _sub_test_description(self) -> str:
89 parts = []
90 if self.context.msg is not None:
91 parts.append(f"[{self.context.msg}]")
92 if self.context.kwargs:
93 params_desc = ", ".join(
94 f"{k}={v}" for (k, v) in self.context.kwargs.items()
95 )
96 parts.append(f"({params_desc})")
97 return " ".join(parts) or "(<subtest>)"
98
99 def _to_json(self) -> dict[str, Any]:
100 data = super()._to_json()
101 del data["context"]
102 data["_report_type"] = "SubTestReport"
103 data["_subtest.context"] = self.context._to_json()
104 return data
105
106 @classmethod
107 def _from_json(cls, reportdict: dict[str, Any]) -> SubtestReport:
108 report = super()._from_json(reportdict)
109 report.context = SubtestContext._from_json(reportdict["_subtest.context"])
110 return report
111
112 @classmethod
113 def _new(
114 cls,
115 test_report: TestReport,
116 context: SubtestContext,
117 captured_output: Captured | None,
118 captured_logs: CapturedLogs | None,
119 ) -> Self:
120 result = super()._from_json(test_report._to_json())
121 result.context = context
122
123 if captured_output:
124 if captured_output.out:
125 result.sections.append(("Captured stdout call", captured_output.out))
126 if captured_output.err:
127 result.sections.append(("Captured stderr call", captured_output.err))
128
129 if captured_logs and (log := captured_logs.handler.stream.getvalue()):
130 result.sections.append(("Captured log call", log))
131
132 return result
133
134
135 @fixture
136 def subtests(request: SubRequest) -> Subtests:
137 """Provides subtests functionality."""
138 capmam = request.node.config.pluginmanager.get_plugin("capturemanager")
139 suspend_capture_ctx = (
140 capmam.global_and_fixture_disabled if capmam is not None else nullcontext
141 )
142 return Subtests(request.node.ihook, suspend_capture_ctx, request, _ispytest=True)
143
144
145 class Subtests:
146 """Subtests fixture, enables declaring subtests inside test functions via the :meth:`test` method."""
147
148 def __init__(
149 self,
150 ihook: pluggy.HookRelay,
151 suspend_capture_ctx: Callable[[], AbstractContextManager[None]],
152 request: SubRequest,
153 *,
154 _ispytest: bool = False,
155 ) -> None:
156 check_ispytest(_ispytest)
157 self._ihook = ihook
158 self._suspend_capture_ctx = suspend_capture_ctx
159 self._request = request
160
161 def test(
162 self,
163 msg: str | None = None,
164 **kwargs: Any,
165 ) -> _SubTestContextManager:
166 """
167 Context manager for subtests, capturing exceptions raised inside the subtest scope and
168 reporting assertion failures and errors individually.
169
170 Usage
171 -----
172
173 .. code-block:: python
174
175 def test(subtests):
176 for i in range(5):
177 with subtests.test("custom message", i=i):
178 assert i % 2 == 0
179
180 :param msg:
181 If given, the message will be shown in the test report in case of subtest failure.
182
183 :param kwargs:
184 Arbitrary values that are also added to the subtest report.
185 """
186 return _SubTestContextManager(
187 self._ihook,
188 msg,
189 kwargs,
190 request=self._request,
191 suspend_capture_ctx=self._suspend_capture_ctx,
192 config=self._request.config,
193 )
194
195
196 @dataclasses.dataclass
197 class _SubTestContextManager:
198 """
199 Context manager for subtests, capturing exceptions raised inside the subtest scope and handling
200 them through the pytest machinery.
201 """
202
203 # Note: initially the logic for this context manager was implemented directly
204 # in Subtests.test() as a @contextmanager, however, it is not possible to control the output fully when
205 # exiting from it due to an exception when in `--exitfirst` mode, so this was refactored into an
206 # explicit context manager class (pytest-dev/pytest-subtests#134).
207
208 ihook: pluggy.HookRelay
209 msg: str | None
210 kwargs: dict[str, Any]
211 suspend_capture_ctx: Callable[[], AbstractContextManager[None]]
212 request: SubRequest
213 config: Config
214
215 def __enter__(self) -> None:
216 __tracebackhide__ = True
217
218 self._start = time.time()
219 self._precise_start = time.perf_counter()
220 self._exc_info = None
221
222 self._exit_stack = ExitStack()
223 self._captured_output = self._exit_stack.enter_context(
224 capturing_output(self.request)
225 )
226 self._captured_logs = self._exit_stack.enter_context(
227 capturing_logs(self.request)
228 )
229
230 def __exit__(
231 self,
232 exc_type: type[BaseException] | None,
233 exc_val: BaseException | None,
234 exc_tb: TracebackType | None,
235 ) -> bool:
236 __tracebackhide__ = True
237 if exc_val is not None:
238 exc_info = ExceptionInfo.from_exception(exc_val)
239 else:
240 exc_info = None
241
242 self._exit_stack.close()
243
244 precise_stop = time.perf_counter()
245 duration = precise_stop - self._precise_start
246 stop = time.time()
247
248 call_info = CallInfo[None](
249 None,
250 exc_info,
251 start=self._start,
252 stop=stop,
253 duration=duration,
254 when="call",
255 _ispytest=True,
256 )
257 report = self.ihook.pytest_runtest_makereport(
258 item=self.request.node, call=call_info
259 )
260 sub_report = SubtestReport._new(
261 report,
262 SubtestContext(msg=self.msg, kwargs=self.kwargs),
263 captured_output=self._captured_output,
264 captured_logs=self._captured_logs,
265 )
266
267 if sub_report.failed:
268 failed_subtests = self.config.stash[failed_subtests_key]
269 failed_subtests[self.request.node.nodeid] += 1
270
271 with self.suspend_capture_ctx():
272 self.ihook.pytest_runtest_logreport(report=sub_report)
273
274 if check_interactive_exception(call_info, sub_report):
275 self.ihook.pytest_exception_interact(
276 node=self.request.node, call=call_info, report=sub_report
277 )
278
279 if exc_val is not None:
280 if isinstance(exc_val, get_reraise_exceptions(self.config)):
281 return False
282 if self.request.session.shouldfail:
283 return False
284 return True
285
286
287 @contextmanager
288 def capturing_output(request: SubRequest) -> Iterator[Captured]:
289 option = request.config.getoption("capture", None)
290
291 capman = request.config.pluginmanager.getplugin("capturemanager")
292 if getattr(capman, "_capture_fixture", None):
293 # capsys or capfd are active, subtest should not capture.
294 fixture = None
295 elif option == "sys":
296 fixture = CaptureFixture(SysCapture, request, _ispytest=True)
297 elif option == "fd":
298 fixture = CaptureFixture(FDCapture, request, _ispytest=True)
299 else:
300 fixture = None
301
302 if fixture is not None:
303 fixture._start()
304
305 captured = Captured()
306 try:
307 yield captured
308 finally:
309 if fixture is not None:
310 out, err = fixture.readouterr()
311 fixture.close()
312 captured.out = out
313 captured.err = err
314
315
316 @contextmanager
317 def capturing_logs(
318 request: SubRequest,
319 ) -> Iterator[CapturedLogs | None]:
320 logging_plugin: LoggingPlugin | None = request.config.pluginmanager.getplugin(
321 "logging-plugin"
322 )
323 if logging_plugin is None:
324 yield None
325 else:
326 handler = LogCaptureHandler()
327 handler.setFormatter(logging_plugin.formatter)
328
329 captured_logs = CapturedLogs(handler)
330 with catching_logs(handler, level=logging_plugin.log_level):
331 yield captured_logs
332
333
334 @dataclasses.dataclass
335 class Captured:
336 out: str = ""
337 err: str = ""
338
339
340 @dataclasses.dataclass
341 class CapturedLogs:
342 handler: LogCaptureHandler
343
344
345 def pytest_report_to_serializable(report: TestReport) -> dict[str, Any] | None:
346 if isinstance(report, SubtestReport):
347 return report._to_json()
348 return None
349
350
351 def pytest_report_from_serializable(data: dict[str, Any]) -> SubtestReport | None:
352 if data.get("_report_type") == "SubTestReport":
353 return SubtestReport._from_json(data)
354 return None
355
356
357 # Dict of nodeid -> number of failed subtests.
358 # Used to fail top-level tests that passed but contain failed subtests.
359 failed_subtests_key = StashKey[defaultdict[str, int]]()
360
361
362 def pytest_configure(config: Config) -> None:
363 config.stash[failed_subtests_key] = defaultdict(int)
364
365
366 @hookimpl(tryfirst=True)
367 def pytest_report_teststatus(
368 report: TestReport,
369 config: Config,
370 ) -> tuple[str, str, str | Mapping[str, bool]] | None:
371 if report.when != "call":
372 return None
373
374 quiet = config.get_verbosity(Config.VERBOSITY_SUBTESTS) == 0
375 if isinstance(report, SubtestReport):
376 outcome = report.outcome
377 description = report._sub_test_description()
378
379 if hasattr(report, "wasxfail"):
380 if quiet:
381 return "", "", ""
382 elif outcome == "skipped":
383 category = "xfailed"
384 short = "y" # x letter is used for regular xfail, y for subtest xfail
385 status = "SUBXFAIL"
386 # outcome == "passed" in an xfail is only possible via a @pytest.mark.xfail mark, which
387 # is not applicable to a subtest, which only handles pytest.xfail().
388 else: # pragma: no cover
389 # This should not normally happen, unless some plugin is setting wasxfail without
390 # the correct outcome. Pytest expects the call outcome to be either skipped or
391 # passed in case of xfail.
392 # Let's pass this report to the next hook.
393 return None
394 return category, short, f"{status}{description}"
395
396 if report.failed:
397 return outcome, "u", f"SUBFAILED{description}"
398 else:
399 if report.passed:
400 if quiet:
401 return "", "", ""
402 else:
403 return f"subtests {outcome}", "u", f"SUBPASSED{description}"
404 elif report.skipped:
405 if quiet:
406 return "", "", ""
407 else:
408 return outcome, "-", f"SUBSKIPPED{description}"
409
410 else:
411 failed_subtests_count = config.stash[failed_subtests_key][report.nodeid]
412 # Top-level test, fail if it contains failed subtests and it has passed.
413 if report.passed and failed_subtests_count > 0:
414 report.outcome = "failed"
415 suffix = "s" if failed_subtests_count > 1 else ""
416 report.longrepr = f"contains {failed_subtests_count} failed subtest{suffix}"
417
418 return None