runner.py 18 KB

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