runner.py 18 KB

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