Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/runner.py

raw
1 # mypy: allow-untyped-defs
2 """Basic collect and runtest protocol implementations."""
3
4 import bdb
5 import dataclasses
6 import os
7 import sys
8 from typing import Callable
9 from typing import cast
10 from typing import Dict
11 from typing import final
12 from typing import Generic
13 from typing import List
14 from typing import Literal
15 from typing import Optional
16 from typing import Tuple
17 from typing import Type
18 from typing import TYPE_CHECKING
19 from typing import TypeVar
20 from typing import Union
21
22 from .reports import BaseReport
23 from .reports import CollectErrorRepr
24 from .reports import CollectReport
25 from .reports import TestReport
26 from _pytest import timing
27 from _pytest._code.code import ExceptionChainRepr
28 from _pytest._code.code import ExceptionInfo
29 from _pytest._code.code import TerminalRepr
30 from _pytest.config.argparsing import Parser
31 from _pytest.deprecated import check_ispytest
32 from _pytest.nodes import Collector
33 from _pytest.nodes import Directory
34 from _pytest.nodes import Item
35 from _pytest.nodes import Node
36 from _pytest.outcomes import Exit
37 from _pytest.outcomes import OutcomeException
38 from _pytest.outcomes import Skipped
39 from _pytest.outcomes import TEST_OUTCOME
40
41
42 if sys.version_info < (3, 11):
43 from exceptiongroup import BaseExceptionGroup
44
45 if TYPE_CHECKING:
46 from _pytest.main import Session
47 from _pytest.terminal import TerminalReporter
48
49 #
50 # pytest plugin hooks.
51
52
53 def pytest_addoption(parser: Parser) -> None:
54 group = parser.getgroup("terminal reporting", "Reporting", after="general")
55 group.addoption(
56 "--durations",
57 action="store",
58 type=int,
59 default=None,
60 metavar="N",
61 help="Show N slowest setup/test durations (N=0 for all)",
62 )
63 group.addoption(
64 "--durations-min",
65 action="store",
66 type=float,
67 default=0.005,
68 metavar="N",
69 help="Minimal duration in seconds for inclusion in slowest list. "
70 "Default: 0.005.",
71 )
72
73
74 def pytest_terminal_summary(terminalreporter: "TerminalReporter") -> None:
75 durations = terminalreporter.config.option.durations
76 durations_min = terminalreporter.config.option.durations_min
77 verbose = terminalreporter.config.getvalue("verbose")
78 if durations is None:
79 return
80 tr = terminalreporter
81 dlist = []
82 for replist in tr.stats.values():
83 for rep in replist:
84 if hasattr(rep, "duration"):
85 dlist.append(rep)
86 if not dlist:
87 return
88 dlist.sort(key=lambda x: x.duration, reverse=True)
89 if not durations:
90 tr.write_sep("=", "slowest durations")
91 else:
92 tr.write_sep("=", "slowest %s durations" % durations)
93 dlist = dlist[:durations]
94
95 for i, rep in enumerate(dlist):
96 if verbose < 2 and rep.duration < durations_min:
97 tr.write_line("")
98 tr.write_line(
99 f"({len(dlist) - i} durations < {durations_min:g}s hidden. Use -vv to show these durations.)"
100 )
101 break
102 tr.write_line(f"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}")
103
104
105 def pytest_sessionstart(session: "Session") -> None:
106 session._setupstate = SetupState()
107
108
109 def pytest_sessionfinish(session: "Session") -> None:
110 session._setupstate.teardown_exact(None)
111
112
113 def pytest_runtest_protocol(item: Item, nextitem: Optional[Item]) -> bool:
114 ihook = item.ihook
115 ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
116 runtestprotocol(item, nextitem=nextitem)
117 ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
118 return True
119
120
121 def runtestprotocol(
122 item: Item, log: bool = True, nextitem: Optional[Item] = None
123 ) -> List[TestReport]:
124 hasrequest = hasattr(item, "_request")
125 if hasrequest and not item._request: # type: ignore[attr-defined]
126 # This only happens if the item is re-run, as is done by
127 # pytest-rerunfailures.
128 item._initrequest() # type: ignore[attr-defined]
129 rep = call_and_report(item, "setup", log)
130 reports = [rep]
131 if rep.passed:
132 if item.config.getoption("setupshow", False):
133 show_test_item(item)
134 if not item.config.getoption("setuponly", False):
135 reports.append(call_and_report(item, "call", log))
136 reports.append(call_and_report(item, "teardown", log, nextitem=nextitem))
137 # After all teardown hooks have been called
138 # want funcargs and request info to go away.
139 if hasrequest:
140 item._request = False # type: ignore[attr-defined]
141 item.funcargs = None # type: ignore[attr-defined]
142 return reports
143
144
145 def show_test_item(item: Item) -> None:
146 """Show test function, parameters and the fixtures of the test item."""
147 tw = item.config.get_terminal_writer()
148 tw.line()
149 tw.write(" " * 8)
150 tw.write(item.nodeid)
151 used_fixtures = sorted(getattr(item, "fixturenames", []))
152 if used_fixtures:
153 tw.write(" (fixtures used: {})".format(", ".join(used_fixtures)))
154 tw.flush()
155
156
157 def pytest_runtest_setup(item: Item) -> None:
158 _update_current_test_var(item, "setup")
159 item.session._setupstate.setup(item)
160
161
162 def pytest_runtest_call(item: Item) -> None:
163 _update_current_test_var(item, "call")
164 try:
165 del sys.last_type
166 del sys.last_value
167 del sys.last_traceback
168 if sys.version_info >= (3, 12, 0):
169 del sys.last_exc # type: ignore[attr-defined]
170 except AttributeError:
171 pass
172 try:
173 item.runtest()
174 except Exception as e:
175 # Store trace info to allow postmortem debugging
176 sys.last_type = type(e)
177 sys.last_value = e
178 if sys.version_info >= (3, 12, 0):
179 sys.last_exc = e # type: ignore[attr-defined]
180 assert e.__traceback__ is not None
181 # Skip *this* frame
182 sys.last_traceback = e.__traceback__.tb_next
183 raise e
184
185
186 def pytest_runtest_teardown(item: Item, nextitem: Optional[Item]) -> None:
187 _update_current_test_var(item, "teardown")
188 item.session._setupstate.teardown_exact(nextitem)
189 _update_current_test_var(item, None)
190
191
192 def _update_current_test_var(
193 item: Item, when: Optional[Literal["setup", "call", "teardown"]]
194 ) -> None:
195 """Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage.
196
197 If ``when`` is None, delete ``PYTEST_CURRENT_TEST`` from the environment.
198 """
199 var_name = "PYTEST_CURRENT_TEST"
200 if when:
201 value = f"{item.nodeid} ({when})"
202 # don't allow null bytes on environment variables (see #2644, #2957)
203 value = value.replace("\x00", "(null)")
204 os.environ[var_name] = value
205 else:
206 os.environ.pop(var_name)
207
208
209 def pytest_report_teststatus(report: BaseReport) -> Optional[Tuple[str, str, str]]:
210 if report.when in ("setup", "teardown"):
211 if report.failed:
212 # category, shortletter, verbose-word
213 return "error", "E", "ERROR"
214 elif report.skipped:
215 return "skipped", "s", "SKIPPED"
216 else:
217 return "", "", ""
218 return None
219
220
221 #
222 # Implementation
223
224
225 def call_and_report(
226 item: Item, when: Literal["setup", "call", "teardown"], log: bool = True, **kwds
227 ) -> TestReport:
228 ihook = item.ihook
229 if when == "setup":
230 runtest_hook: Callable[..., None] = ihook.pytest_runtest_setup
231 elif when == "call":
232 runtest_hook = ihook.pytest_runtest_call
233 elif when == "teardown":
234 runtest_hook = ihook.pytest_runtest_teardown
235 else:
236 assert False, f"Unhandled runtest hook case: {when}"
237 reraise: Tuple[Type[BaseException], ...] = (Exit,)
238 if not item.config.getoption("usepdb", False):
239 reraise += (KeyboardInterrupt,)
240 call = CallInfo.from_call(
241 lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise
242 )
243 report: TestReport = ihook.pytest_runtest_makereport(item=item, call=call)
244 if log:
245 ihook.pytest_runtest_logreport(report=report)
246 if check_interactive_exception(call, report):
247 ihook.pytest_exception_interact(node=item, call=call, report=report)
248 return report
249
250
251 def check_interactive_exception(call: "CallInfo[object]", report: BaseReport) -> bool:
252 """Check whether the call raised an exception that should be reported as
253 interactive."""
254 if call.excinfo is None:
255 # Didn't raise.
256 return False
257 if hasattr(report, "wasxfail"):
258 # Exception was expected.
259 return False
260 if isinstance(call.excinfo.value, (Skipped, bdb.BdbQuit)):
261 # Special control flow exception.
262 return False
263 return True
264
265
266 TResult = TypeVar("TResult", covariant=True)
267
268
269 @final
270 @dataclasses.dataclass
271 class CallInfo(Generic[TResult]):
272 """Result/Exception info of a function invocation."""
273
274 _result: Optional[TResult]
275 #: The captured exception of the call, if it raised.
276 excinfo: Optional[ExceptionInfo[BaseException]]
277 #: The system time when the call started, in seconds since the epoch.
278 start: float
279 #: The system time when the call ended, in seconds since the epoch.
280 stop: float
281 #: The call duration, in seconds.
282 duration: float
283 #: The context of invocation: "collect", "setup", "call" or "teardown".
284 when: Literal["collect", "setup", "call", "teardown"]
285
286 def __init__(
287 self,
288 result: Optional[TResult],
289 excinfo: Optional[ExceptionInfo[BaseException]],
290 start: float,
291 stop: float,
292 duration: float,
293 when: Literal["collect", "setup", "call", "teardown"],
294 *,
295 _ispytest: bool = False,
296 ) -> None:
297 check_ispytest(_ispytest)
298 self._result = result
299 self.excinfo = excinfo
300 self.start = start
301 self.stop = stop
302 self.duration = duration
303 self.when = when
304
305 @property
306 def result(self) -> TResult:
307 """The return value of the call, if it didn't raise.
308
309 Can only be accessed if excinfo is None.
310 """
311 if self.excinfo is not None:
312 raise AttributeError(f"{self!r} has no valid result")
313 # The cast is safe because an exception wasn't raised, hence
314 # _result has the expected function return type (which may be
315 # None, that's why a cast and not an assert).
316 return cast(TResult, self._result)
317
318 @classmethod
319 def from_call(
320 cls,
321 func: Callable[[], TResult],
322 when: Literal["collect", "setup", "call", "teardown"],
323 reraise: Optional[
324 Union[Type[BaseException], Tuple[Type[BaseException], ...]]
325 ] = None,
326 ) -> "CallInfo[TResult]":
327 """Call func, wrapping the result in a CallInfo.
328
329 :param func:
330 The function to call. Called without arguments.
331 :param when:
332 The phase in which the function is called.
333 :param reraise:
334 Exception or exceptions that shall propagate if raised by the
335 function, instead of being wrapped in the CallInfo.
336 """
337 excinfo = None
338 start = timing.time()
339 precise_start = timing.perf_counter()
340 try:
341 result: Optional[TResult] = func()
342 except BaseException:
343 excinfo = ExceptionInfo.from_current()
344 if reraise is not None and isinstance(excinfo.value, reraise):
345 raise
346 result = None
347 # use the perf counter
348 precise_stop = timing.perf_counter()
349 duration = precise_stop - precise_start
350 stop = timing.time()
351 return cls(
352 start=start,
353 stop=stop,
354 duration=duration,
355 when=when,
356 result=result,
357 excinfo=excinfo,
358 _ispytest=True,
359 )
360
361 def __repr__(self) -> str:
362 if self.excinfo is None:
363 return f"<CallInfo when={self.when!r} result: {self._result!r}>"
364 return f"<CallInfo when={self.when!r} excinfo={self.excinfo!r}>"
365
366
367 def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport:
368 return TestReport.from_item_and_call(item, call)
369
370
371 def pytest_make_collect_report(collector: Collector) -> CollectReport:
372 def collect() -> List[Union[Item, Collector]]:
373 # Before collecting, if this is a Directory, load the conftests.
374 # If a conftest import fails to load, it is considered a collection
375 # error of the Directory collector. This is why it's done inside of the
376 # CallInfo wrapper.
377 #
378 # Note: initial conftests are loaded early, not here.
379 if isinstance(collector, Directory):
380 collector.config.pluginmanager._loadconftestmodules(
381 collector.path,
382 collector.config.getoption("importmode"),
383 rootpath=collector.config.rootpath,
384 consider_namespace_packages=collector.config.getini(
385 "consider_namespace_packages"
386 ),
387 )
388
389 return list(collector.collect())
390
391 call = CallInfo.from_call(
392 collect, "collect", reraise=(KeyboardInterrupt, SystemExit)
393 )
394 longrepr: Union[None, Tuple[str, int, str], str, TerminalRepr] = None
395 if not call.excinfo:
396 outcome: Literal["passed", "skipped", "failed"] = "passed"
397 else:
398 skip_exceptions = [Skipped]
399 unittest = sys.modules.get("unittest")
400 if unittest is not None:
401 skip_exceptions.append(unittest.SkipTest)
402 if isinstance(call.excinfo.value, tuple(skip_exceptions)):
403 outcome = "skipped"
404 r_ = collector._repr_failure_py(call.excinfo, "line")
405 assert isinstance(r_, ExceptionChainRepr), repr(r_)
406 r = r_.reprcrash
407 assert r
408 longrepr = (str(r.path), r.lineno, r.message)
409 else:
410 outcome = "failed"
411 errorinfo = collector.repr_failure(call.excinfo)
412 if not hasattr(errorinfo, "toterminal"):
413 assert isinstance(errorinfo, str)
414 errorinfo = CollectErrorRepr(errorinfo)
415 longrepr = errorinfo
416 result = call.result if not call.excinfo else None
417 rep = CollectReport(collector.nodeid, outcome, longrepr, result)
418 rep.call = call # type: ignore # see collect_one_node
419 return rep
420
421
422 class SetupState:
423 """Shared state for setting up/tearing down test items or collectors
424 in a session.
425
426 Suppose we have a collection tree as follows:
427
428 <Session session>
429 <Module mod1>
430 <Function item1>
431 <Module mod2>
432 <Function item2>
433
434 The SetupState maintains a stack. The stack starts out empty:
435
436 []
437
438 During the setup phase of item1, setup(item1) is called. What it does
439 is:
440
441 push session to stack, run session.setup()
442 push mod1 to stack, run mod1.setup()
443 push item1 to stack, run item1.setup()
444
445 The stack is:
446
447 [session, mod1, item1]
448
449 While the stack is in this shape, it is allowed to add finalizers to
450 each of session, mod1, item1 using addfinalizer().
451
452 During the teardown phase of item1, teardown_exact(item2) is called,
453 where item2 is the next item to item1. What it does is:
454
455 pop item1 from stack, run its teardowns
456 pop mod1 from stack, run its teardowns
457
458 mod1 was popped because it ended its purpose with item1. The stack is:
459
460 [session]
461
462 During the setup phase of item2, setup(item2) is called. What it does
463 is:
464
465 push mod2 to stack, run mod2.setup()
466 push item2 to stack, run item2.setup()
467
468 Stack:
469
470 [session, mod2, item2]
471
472 During the teardown phase of item2, teardown_exact(None) is called,
473 because item2 is the last item. What it does is:
474
475 pop item2 from stack, run its teardowns
476 pop mod2 from stack, run its teardowns
477 pop session from stack, run its teardowns
478
479 Stack:
480
481 []
482
483 The end!
484 """
485
486 def __init__(self) -> None:
487 # The stack is in the dict insertion order.
488 self.stack: Dict[
489 Node,
490 Tuple[
491 # Node's finalizers.
492 List[Callable[[], object]],
493 # Node's exception, if its setup raised.
494 Optional[Union[OutcomeException, Exception]],
495 ],
496 ] = {}
497
498 def setup(self, item: Item) -> None:
499 """Setup objects along the collector chain to the item."""
500 needed_collectors = item.listchain()
501
502 # If a collector fails its setup, fail its entire subtree of items.
503 # The setup is not retried for each item - the same exception is used.
504 for col, (finalizers, exc) in self.stack.items():
505 assert col in needed_collectors, "previous item was not torn down properly"
506 if exc:
507 raise exc
508
509 for col in needed_collectors[len(self.stack) :]:
510 assert col not in self.stack
511 # Push onto the stack.
512 self.stack[col] = ([col.teardown], None)
513 try:
514 col.setup()
515 except TEST_OUTCOME as exc:
516 self.stack[col] = (self.stack[col][0], exc)
517 raise exc
518
519 def addfinalizer(self, finalizer: Callable[[], object], node: Node) -> None:
520 """Attach a finalizer to the given node.
521
522 The node must be currently active in the stack.
523 """
524 assert node and not isinstance(node, tuple)
525 assert callable(finalizer)
526 assert node in self.stack, (node, self.stack)
527 self.stack[node][0].append(finalizer)
528
529 def teardown_exact(self, nextitem: Optional[Item]) -> None:
530 """Teardown the current stack up until reaching nodes that nextitem
531 also descends from.
532
533 When nextitem is None (meaning we're at the last item), the entire
534 stack is torn down.
535 """
536 needed_collectors = nextitem and nextitem.listchain() or []
537 exceptions: List[BaseException] = []
538 while self.stack:
539 if list(self.stack.keys()) == needed_collectors[: len(self.stack)]:
540 break
541 node, (finalizers, _) = self.stack.popitem()
542 these_exceptions = []
543 while finalizers:
544 fin = finalizers.pop()
545 try:
546 fin()
547 except TEST_OUTCOME as e:
548 these_exceptions.append(e)
549
550 if len(these_exceptions) == 1:
551 exceptions.extend(these_exceptions)
552 elif these_exceptions:
553 msg = f"errors while tearing down {node!r}"
554 exceptions.append(BaseExceptionGroup(msg, these_exceptions[::-1]))
555
556 if len(exceptions) == 1:
557 raise exceptions[0]
558 elif exceptions:
559 raise BaseExceptionGroup("errors during test teardown", exceptions[::-1])
560 if nextitem is None:
561 assert not self.stack
562
563
564 def collect_one_node(collector: Collector) -> CollectReport:
565 ihook = collector.ihook
566 ihook.pytest_collectstart(collector=collector)
567 rep: CollectReport = ihook.pytest_make_collect_report(collector=collector)
568 call = rep.__dict__.pop("call", None)
569 if call and check_interactive_exception(call, rep):
570 ihook.pytest_exception_interact(node=collector, call=call, report=rep)
571 return rep