runner.py 18 KB

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