runner.py 19 KB

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