Debian Codegraph @

src/_pytest/runner.py

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