runner.py 19 KB

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