You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

892 lines
31KB

  1. """Hook specifications for pytest plugins which are invoked by pytest itself
  2. and by builtin plugins."""
  3. from typing import Any
  4. from typing import Dict
  5. from typing import List
  6. from typing import Mapping
  7. from typing import Optional
  8. from typing import Sequence
  9. from typing import Tuple
  10. from typing import TYPE_CHECKING
  11. from typing import Union
  12. import py.path
  13. from pluggy import HookspecMarker
  14. from _pytest.deprecated import WARNING_CAPTURED_HOOK
  15. if TYPE_CHECKING:
  16. import pdb
  17. import warnings
  18. from typing_extensions import Literal
  19. from _pytest._code.code import ExceptionRepr
  20. from _pytest.code import ExceptionInfo
  21. from _pytest.config import Config
  22. from _pytest.config import ExitCode
  23. from _pytest.config import PytestPluginManager
  24. from _pytest.config import _PluggyPlugin
  25. from _pytest.config.argparsing import Parser
  26. from _pytest.fixtures import FixtureDef
  27. from _pytest.fixtures import SubRequest
  28. from _pytest.main import Session
  29. from _pytest.nodes import Collector
  30. from _pytest.nodes import Item
  31. from _pytest.outcomes import Exit
  32. from _pytest.python import Function
  33. from _pytest.python import Metafunc
  34. from _pytest.python import Module
  35. from _pytest.python import PyCollector
  36. from _pytest.reports import CollectReport
  37. from _pytest.reports import TestReport
  38. from _pytest.runner import CallInfo
  39. from _pytest.terminal import TerminalReporter
  40. hookspec = HookspecMarker("pytest")
  41. # -------------------------------------------------------------------------
  42. # Initialization hooks called for every plugin
  43. # -------------------------------------------------------------------------
  44. @hookspec(historic=True)
  45. def pytest_addhooks(pluginmanager: "PytestPluginManager") -> None:
  46. """Called at plugin registration time to allow adding new hooks via a call to
  47. ``pluginmanager.add_hookspecs(module_or_class, prefix)``.
  48. :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager.
  49. .. note::
  50. This hook is incompatible with ``hookwrapper=True``.
  51. """
  52. @hookspec(historic=True)
  53. def pytest_plugin_registered(
  54. plugin: "_PluggyPlugin", manager: "PytestPluginManager"
  55. ) -> None:
  56. """A new pytest plugin got registered.
  57. :param plugin: The plugin module or instance.
  58. :param _pytest.config.PytestPluginManager manager: pytest plugin manager.
  59. .. note::
  60. This hook is incompatible with ``hookwrapper=True``.
  61. """
  62. @hookspec(historic=True)
  63. def pytest_addoption(parser: "Parser", pluginmanager: "PytestPluginManager") -> None:
  64. """Register argparse-style options and ini-style config values,
  65. called once at the beginning of a test run.
  66. .. note::
  67. This function should be implemented only in plugins or ``conftest.py``
  68. files situated at the tests root directory due to how pytest
  69. :ref:`discovers plugins during startup <pluginorder>`.
  70. :param _pytest.config.argparsing.Parser parser:
  71. To add command line options, call
  72. :py:func:`parser.addoption(...) <_pytest.config.argparsing.Parser.addoption>`.
  73. To add ini-file values call :py:func:`parser.addini(...)
  74. <_pytest.config.argparsing.Parser.addini>`.
  75. :param _pytest.config.PytestPluginManager pluginmanager:
  76. pytest plugin manager, which can be used to install :py:func:`hookspec`'s
  77. or :py:func:`hookimpl`'s and allow one plugin to call another plugin's hooks
  78. to change how command line options are added.
  79. Options can later be accessed through the
  80. :py:class:`config <_pytest.config.Config>` object, respectively:
  81. - :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to
  82. retrieve the value of a command line option.
  83. - :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve
  84. a value read from an ini-style file.
  85. The config object is passed around on many internal objects via the ``.config``
  86. attribute or can be retrieved as the ``pytestconfig`` fixture.
  87. .. note::
  88. This hook is incompatible with ``hookwrapper=True``.
  89. """
  90. @hookspec(historic=True)
  91. def pytest_configure(config: "Config") -> None:
  92. """Allow plugins and conftest files to perform initial configuration.
  93. This hook is called for every plugin and initial conftest file
  94. after command line options have been parsed.
  95. After that, the hook is called for other conftest files as they are
  96. imported.
  97. .. note::
  98. This hook is incompatible with ``hookwrapper=True``.
  99. :param _pytest.config.Config config: The pytest config object.
  100. """
  101. # -------------------------------------------------------------------------
  102. # Bootstrapping hooks called for plugins registered early enough:
  103. # internal and 3rd party plugins.
  104. # -------------------------------------------------------------------------
  105. @hookspec(firstresult=True)
  106. def pytest_cmdline_parse(
  107. pluginmanager: "PytestPluginManager", args: List[str]
  108. ) -> Optional["Config"]:
  109. """Return an initialized config object, parsing the specified args.
  110. Stops at first non-None result, see :ref:`firstresult`.
  111. .. note::
  112. This hook will only be called for plugin classes passed to the
  113. ``plugins`` arg when using `pytest.main`_ to perform an in-process
  114. test run.
  115. :param _pytest.config.PytestPluginManager pluginmanager: Pytest plugin manager.
  116. :param List[str] args: List of arguments passed on the command line.
  117. """
  118. def pytest_cmdline_preparse(config: "Config", args: List[str]) -> None:
  119. """(**Deprecated**) modify command line arguments before option parsing.
  120. This hook is considered deprecated and will be removed in a future pytest version. Consider
  121. using :func:`pytest_load_initial_conftests` instead.
  122. .. note::
  123. This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
  124. :param _pytest.config.Config config: The pytest config object.
  125. :param List[str] args: Arguments passed on the command line.
  126. """
  127. @hookspec(firstresult=True)
  128. def pytest_cmdline_main(config: "Config") -> Optional[Union["ExitCode", int]]:
  129. """Called for performing the main command line action. The default
  130. implementation will invoke the configure hooks and runtest_mainloop.
  131. .. note::
  132. This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
  133. Stops at first non-None result, see :ref:`firstresult`.
  134. :param _pytest.config.Config config: The pytest config object.
  135. """
  136. def pytest_load_initial_conftests(
  137. early_config: "Config", parser: "Parser", args: List[str]
  138. ) -> None:
  139. """Called to implement the loading of initial conftest files ahead
  140. of command line option parsing.
  141. .. note::
  142. This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
  143. :param _pytest.config.Config early_config: The pytest config object.
  144. :param List[str] args: Arguments passed on the command line.
  145. :param _pytest.config.argparsing.Parser parser: To add command line options.
  146. """
  147. # -------------------------------------------------------------------------
  148. # collection hooks
  149. # -------------------------------------------------------------------------
  150. @hookspec(firstresult=True)
  151. def pytest_collection(session: "Session") -> Optional[object]:
  152. """Perform the collection phase for the given session.
  153. Stops at first non-None result, see :ref:`firstresult`.
  154. The return value is not used, but only stops further processing.
  155. The default collection phase is this (see individual hooks for full details):
  156. 1. Starting from ``session`` as the initial collector:
  157. 1. ``pytest_collectstart(collector)``
  158. 2. ``report = pytest_make_collect_report(collector)``
  159. 3. ``pytest_exception_interact(collector, call, report)`` if an interactive exception occurred
  160. 4. For each collected node:
  161. 1. If an item, ``pytest_itemcollected(item)``
  162. 2. If a collector, recurse into it.
  163. 5. ``pytest_collectreport(report)``
  164. 2. ``pytest_collection_modifyitems(session, config, items)``
  165. 1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times)
  166. 3. ``pytest_collection_finish(session)``
  167. 4. Set ``session.items`` to the list of collected items
  168. 5. Set ``session.testscollected`` to the number of collected items
  169. You can implement this hook to only perform some action before collection,
  170. for example the terminal plugin uses it to start displaying the collection
  171. counter (and returns `None`).
  172. :param pytest.Session session: The pytest session object.
  173. """
  174. def pytest_collection_modifyitems(
  175. session: "Session", config: "Config", items: List["Item"]
  176. ) -> None:
  177. """Called after collection has been performed. May filter or re-order
  178. the items in-place.
  179. :param pytest.Session session: The pytest session object.
  180. :param _pytest.config.Config config: The pytest config object.
  181. :param List[pytest.Item] items: List of item objects.
  182. """
  183. def pytest_collection_finish(session: "Session") -> None:
  184. """Called after collection has been performed and modified.
  185. :param pytest.Session session: The pytest session object.
  186. """
  187. @hookspec(firstresult=True)
  188. def pytest_ignore_collect(path: py.path.local, config: "Config") -> Optional[bool]:
  189. """Return True to prevent considering this path for collection.
  190. This hook is consulted for all files and directories prior to calling
  191. more specific hooks.
  192. Stops at first non-None result, see :ref:`firstresult`.
  193. :param py.path.local path: The path to analyze.
  194. :param _pytest.config.Config config: The pytest config object.
  195. """
  196. def pytest_collect_file(
  197. path: py.path.local, parent: "Collector"
  198. ) -> "Optional[Collector]":
  199. """Create a Collector for the given path, or None if not relevant.
  200. The new node needs to have the specified ``parent`` as a parent.
  201. :param py.path.local path: The path to collect.
  202. """
  203. # logging hooks for collection
  204. def pytest_collectstart(collector: "Collector") -> None:
  205. """Collector starts collecting."""
  206. def pytest_itemcollected(item: "Item") -> None:
  207. """We just collected a test item."""
  208. def pytest_collectreport(report: "CollectReport") -> None:
  209. """Collector finished collecting."""
  210. def pytest_deselected(items: Sequence["Item"]) -> None:
  211. """Called for deselected test items, e.g. by keyword.
  212. May be called multiple times.
  213. """
  214. @hookspec(firstresult=True)
  215. def pytest_make_collect_report(collector: "Collector") -> "Optional[CollectReport]":
  216. """Perform ``collector.collect()`` and return a CollectReport.
  217. Stops at first non-None result, see :ref:`firstresult`.
  218. """
  219. # -------------------------------------------------------------------------
  220. # Python test function related hooks
  221. # -------------------------------------------------------------------------
  222. @hookspec(firstresult=True)
  223. def pytest_pycollect_makemodule(path: py.path.local, parent) -> Optional["Module"]:
  224. """Return a Module collector or None for the given path.
  225. This hook will be called for each matching test module path.
  226. The pytest_collect_file hook needs to be used if you want to
  227. create test modules for files that do not match as a test module.
  228. Stops at first non-None result, see :ref:`firstresult`.
  229. :param py.path.local path: The path of module to collect.
  230. """
  231. @hookspec(firstresult=True)
  232. def pytest_pycollect_makeitem(
  233. collector: "PyCollector", name: str, obj: object
  234. ) -> Union[None, "Item", "Collector", List[Union["Item", "Collector"]]]:
  235. """Return a custom item/collector for a Python object in a module, or None.
  236. Stops at first non-None result, see :ref:`firstresult`.
  237. """
  238. @hookspec(firstresult=True)
  239. def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:
  240. """Call underlying test function.
  241. Stops at first non-None result, see :ref:`firstresult`.
  242. """
  243. def pytest_generate_tests(metafunc: "Metafunc") -> None:
  244. """Generate (multiple) parametrized calls to a test function."""
  245. @hookspec(firstresult=True)
  246. def pytest_make_parametrize_id(
  247. config: "Config", val: object, argname: str
  248. ) -> Optional[str]:
  249. """Return a user-friendly string representation of the given ``val``
  250. that will be used by @pytest.mark.parametrize calls, or None if the hook
  251. doesn't know about ``val``.
  252. The parameter name is available as ``argname``, if required.
  253. Stops at first non-None result, see :ref:`firstresult`.
  254. :param _pytest.config.Config config: The pytest config object.
  255. :param val: The parametrized value.
  256. :param str argname: The automatic parameter name produced by pytest.
  257. """
  258. # -------------------------------------------------------------------------
  259. # runtest related hooks
  260. # -------------------------------------------------------------------------
  261. @hookspec(firstresult=True)
  262. def pytest_runtestloop(session: "Session") -> Optional[object]:
  263. """Perform the main runtest loop (after collection finished).
  264. The default hook implementation performs the runtest protocol for all items
  265. collected in the session (``session.items``), unless the collection failed
  266. or the ``collectonly`` pytest option is set.
  267. If at any point :py:func:`pytest.exit` is called, the loop is
  268. terminated immediately.
  269. If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the
  270. loop is terminated after the runtest protocol for the current item is finished.
  271. :param pytest.Session session: The pytest session object.
  272. Stops at first non-None result, see :ref:`firstresult`.
  273. The return value is not used, but only stops further processing.
  274. """
  275. @hookspec(firstresult=True)
  276. def pytest_runtest_protocol(
  277. item: "Item", nextitem: "Optional[Item]"
  278. ) -> Optional[object]:
  279. """Perform the runtest protocol for a single test item.
  280. The default runtest protocol is this (see individual hooks for full details):
  281. - ``pytest_runtest_logstart(nodeid, location)``
  282. - Setup phase:
  283. - ``call = pytest_runtest_setup(item)`` (wrapped in ``CallInfo(when="setup")``)
  284. - ``report = pytest_runtest_makereport(item, call)``
  285. - ``pytest_runtest_logreport(report)``
  286. - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
  287. - Call phase, if the the setup passed and the ``setuponly`` pytest option is not set:
  288. - ``call = pytest_runtest_call(item)`` (wrapped in ``CallInfo(when="call")``)
  289. - ``report = pytest_runtest_makereport(item, call)``
  290. - ``pytest_runtest_logreport(report)``
  291. - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
  292. - Teardown phase:
  293. - ``call = pytest_runtest_teardown(item, nextitem)`` (wrapped in ``CallInfo(when="teardown")``)
  294. - ``report = pytest_runtest_makereport(item, call)``
  295. - ``pytest_runtest_logreport(report)``
  296. - ``pytest_exception_interact(call, report)`` if an interactive exception occurred
  297. - ``pytest_runtest_logfinish(nodeid, location)``
  298. :param item: Test item for which the runtest protocol is performed.
  299. :param nextitem: The scheduled-to-be-next test item (or None if this is the end my friend).
  300. Stops at first non-None result, see :ref:`firstresult`.
  301. The return value is not used, but only stops further processing.
  302. """
  303. def pytest_runtest_logstart(
  304. nodeid: str, location: Tuple[str, Optional[int], str]
  305. ) -> None:
  306. """Called at the start of running the runtest protocol for a single item.
  307. See :func:`pytest_runtest_protocol` for a description of the runtest protocol.
  308. :param str nodeid: Full node ID of the item.
  309. :param location: A tuple of ``(filename, lineno, testname)``.
  310. """
  311. def pytest_runtest_logfinish(
  312. nodeid: str, location: Tuple[str, Optional[int], str]
  313. ) -> None:
  314. """Called at the end of running the runtest protocol for a single item.
  315. See :func:`pytest_runtest_protocol` for a description of the runtest protocol.
  316. :param str nodeid: Full node ID of the item.
  317. :param location: A tuple of ``(filename, lineno, testname)``.
  318. """
  319. def pytest_runtest_setup(item: "Item") -> None:
  320. """Called to perform the setup phase for a test item.
  321. The default implementation runs ``setup()`` on ``item`` and all of its
  322. parents (which haven't been setup yet). This includes obtaining the
  323. values of fixtures required by the item (which haven't been obtained
  324. yet).
  325. """
  326. def pytest_runtest_call(item: "Item") -> None:
  327. """Called to run the test for test item (the call phase).
  328. The default implementation calls ``item.runtest()``.
  329. """
  330. def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:
  331. """Called to perform the teardown phase for a test item.
  332. The default implementation runs the finalizers and calls ``teardown()``
  333. on ``item`` and all of its parents (which need to be torn down). This
  334. includes running the teardown phase of fixtures required by the item (if
  335. they go out of scope).
  336. :param nextitem:
  337. The scheduled-to-be-next test item (None if no further test item is
  338. scheduled). This argument can be used to perform exact teardowns,
  339. i.e. calling just enough finalizers so that nextitem only needs to
  340. call setup-functions.
  341. """
  342. @hookspec(firstresult=True)
  343. def pytest_runtest_makereport(
  344. item: "Item", call: "CallInfo[None]"
  345. ) -> Optional["TestReport"]:
  346. """Called to create a :py:class:`_pytest.reports.TestReport` for each of
  347. the setup, call and teardown runtest phases of a test item.
  348. See :func:`pytest_runtest_protocol` for a description of the runtest protocol.
  349. :param CallInfo[None] call: The ``CallInfo`` for the phase.
  350. Stops at first non-None result, see :ref:`firstresult`.
  351. """
  352. def pytest_runtest_logreport(report: "TestReport") -> None:
  353. """Process the :py:class:`_pytest.reports.TestReport` produced for each
  354. of the setup, call and teardown runtest phases of an item.
  355. See :func:`pytest_runtest_protocol` for a description of the runtest protocol.
  356. """
  357. @hookspec(firstresult=True)
  358. def pytest_report_to_serializable(
  359. config: "Config", report: Union["CollectReport", "TestReport"],
  360. ) -> Optional[Dict[str, Any]]:
  361. """Serialize the given report object into a data structure suitable for
  362. sending over the wire, e.g. converted to JSON."""
  363. @hookspec(firstresult=True)
  364. def pytest_report_from_serializable(
  365. config: "Config", data: Dict[str, Any],
  366. ) -> Optional[Union["CollectReport", "TestReport"]]:
  367. """Restore a report object previously serialized with pytest_report_to_serializable()."""
  368. # -------------------------------------------------------------------------
  369. # Fixture related hooks
  370. # -------------------------------------------------------------------------
  371. @hookspec(firstresult=True)
  372. def pytest_fixture_setup(
  373. fixturedef: "FixtureDef[Any]", request: "SubRequest"
  374. ) -> Optional[object]:
  375. """Perform fixture setup execution.
  376. :returns: The return value of the call to the fixture function.
  377. Stops at first non-None result, see :ref:`firstresult`.
  378. .. note::
  379. If the fixture function returns None, other implementations of
  380. this hook function will continue to be called, according to the
  381. behavior of the :ref:`firstresult` option.
  382. """
  383. def pytest_fixture_post_finalizer(
  384. fixturedef: "FixtureDef[Any]", request: "SubRequest"
  385. ) -> None:
  386. """Called after fixture teardown, but before the cache is cleared, so
  387. the fixture result ``fixturedef.cached_result`` is still available (not
  388. ``None``)."""
  389. # -------------------------------------------------------------------------
  390. # test session related hooks
  391. # -------------------------------------------------------------------------
  392. def pytest_sessionstart(session: "Session") -> None:
  393. """Called after the ``Session`` object has been created and before performing collection
  394. and entering the run test loop.
  395. :param pytest.Session session: The pytest session object.
  396. """
  397. def pytest_sessionfinish(
  398. session: "Session", exitstatus: Union[int, "ExitCode"],
  399. ) -> None:
  400. """Called after whole test run finished, right before returning the exit status to the system.
  401. :param pytest.Session session: The pytest session object.
  402. :param int exitstatus: The status which pytest will return to the system.
  403. """
  404. def pytest_unconfigure(config: "Config") -> None:
  405. """Called before test process is exited.
  406. :param _pytest.config.Config config: The pytest config object.
  407. """
  408. # -------------------------------------------------------------------------
  409. # hooks for customizing the assert methods
  410. # -------------------------------------------------------------------------
  411. def pytest_assertrepr_compare(
  412. config: "Config", op: str, left: object, right: object
  413. ) -> Optional[List[str]]:
  414. """Return explanation for comparisons in failing assert expressions.
  415. Return None for no custom explanation, otherwise return a list
  416. of strings. The strings will be joined by newlines but any newlines
  417. *in* a string will be escaped. Note that all but the first line will
  418. be indented slightly, the intention is for the first line to be a summary.
  419. :param _pytest.config.Config config: The pytest config object.
  420. """
  421. def pytest_assertion_pass(item: "Item", lineno: int, orig: str, expl: str) -> None:
  422. """**(Experimental)** Called whenever an assertion passes.
  423. .. versionadded:: 5.0
  424. Use this hook to do some processing after a passing assertion.
  425. The original assertion information is available in the `orig` string
  426. and the pytest introspected assertion information is available in the
  427. `expl` string.
  428. This hook must be explicitly enabled by the ``enable_assertion_pass_hook``
  429. ini-file option:
  430. .. code-block:: ini
  431. [pytest]
  432. enable_assertion_pass_hook=true
  433. You need to **clean the .pyc** files in your project directory and interpreter libraries
  434. when enabling this option, as assertions will require to be re-written.
  435. :param pytest.Item item: pytest item object of current test.
  436. :param int lineno: Line number of the assert statement.
  437. :param str orig: String with the original assertion.
  438. :param str expl: String with the assert explanation.
  439. .. note::
  440. This hook is **experimental**, so its parameters or even the hook itself might
  441. be changed/removed without warning in any future pytest release.
  442. If you find this hook useful, please share your feedback in an issue.
  443. """
  444. # -------------------------------------------------------------------------
  445. # Hooks for influencing reporting (invoked from _pytest_terminal).
  446. # -------------------------------------------------------------------------
  447. def pytest_report_header(
  448. config: "Config", startdir: py.path.local
  449. ) -> Union[str, List[str]]:
  450. """Return a string or list of strings to be displayed as header info for terminal reporting.
  451. :param _pytest.config.Config config: The pytest config object.
  452. :param py.path.local startdir: The starting dir.
  453. .. note::
  454. Lines returned by a plugin are displayed before those of plugins which
  455. ran before it.
  456. If you want to have your line(s) displayed first, use
  457. :ref:`trylast=True <plugin-hookorder>`.
  458. .. note::
  459. This function should be implemented only in plugins or ``conftest.py``
  460. files situated at the tests root directory due to how pytest
  461. :ref:`discovers plugins during startup <pluginorder>`.
  462. """
  463. def pytest_report_collectionfinish(
  464. config: "Config", startdir: py.path.local, items: Sequence["Item"],
  465. ) -> Union[str, List[str]]:
  466. """Return a string or list of strings to be displayed after collection
  467. has finished successfully.
  468. These strings will be displayed after the standard "collected X items" message.
  469. .. versionadded:: 3.2
  470. :param _pytest.config.Config config: The pytest config object.
  471. :param py.path.local startdir: The starting dir.
  472. :param items: List of pytest items that are going to be executed; this list should not be modified.
  473. .. note::
  474. Lines returned by a plugin are displayed before those of plugins which
  475. ran before it.
  476. If you want to have your line(s) displayed first, use
  477. :ref:`trylast=True <plugin-hookorder>`.
  478. """
  479. @hookspec(firstresult=True)
  480. def pytest_report_teststatus(
  481. report: Union["CollectReport", "TestReport"], config: "Config"
  482. ) -> Tuple[
  483. str, str, Union[str, Mapping[str, bool]],
  484. ]:
  485. """Return result-category, shortletter and verbose word for status
  486. reporting.
  487. The result-category is a category in which to count the result, for
  488. example "passed", "skipped", "error" or the empty string.
  489. The shortletter is shown as testing progresses, for example ".", "s",
  490. "E" or the empty string.
  491. The verbose word is shown as testing progresses in verbose mode, for
  492. example "PASSED", "SKIPPED", "ERROR" or the empty string.
  493. pytest may style these implicitly according to the report outcome.
  494. To provide explicit styling, return a tuple for the verbose word,
  495. for example ``"rerun", "R", ("RERUN", {"yellow": True})``.
  496. :param report: The report object whose status is to be returned.
  497. :param _pytest.config.Config config: The pytest config object.
  498. Stops at first non-None result, see :ref:`firstresult`.
  499. """
  500. def pytest_terminal_summary(
  501. terminalreporter: "TerminalReporter", exitstatus: "ExitCode", config: "Config",
  502. ) -> None:
  503. """Add a section to terminal summary reporting.
  504. :param _pytest.terminal.TerminalReporter terminalreporter: The internal terminal reporter object.
  505. :param int exitstatus: The exit status that will be reported back to the OS.
  506. :param _pytest.config.Config config: The pytest config object.
  507. .. versionadded:: 4.2
  508. The ``config`` parameter.
  509. """
  510. @hookspec(historic=True, warn_on_impl=WARNING_CAPTURED_HOOK)
  511. def pytest_warning_captured(
  512. warning_message: "warnings.WarningMessage",
  513. when: "Literal['config', 'collect', 'runtest']",
  514. item: Optional["Item"],
  515. location: Optional[Tuple[str, int, str]],
  516. ) -> None:
  517. """(**Deprecated**) Process a warning captured by the internal pytest warnings plugin.
  518. .. deprecated:: 6.0
  519. This hook is considered deprecated and will be removed in a future pytest version.
  520. Use :func:`pytest_warning_recorded` instead.
  521. :param warnings.WarningMessage warning_message:
  522. The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
  523. the same attributes as the parameters of :py:func:`warnings.showwarning`.
  524. :param str when:
  525. Indicates when the warning was captured. Possible values:
  526. * ``"config"``: during pytest configuration/initialization stage.
  527. * ``"collect"``: during test collection.
  528. * ``"runtest"``: during test execution.
  529. :param pytest.Item|None item:
  530. The item being executed if ``when`` is ``"runtest"``, otherwise ``None``.
  531. :param tuple location:
  532. When available, holds information about the execution context of the captured
  533. warning (filename, linenumber, function). ``function`` evaluates to <module>
  534. when the execution context is at the module level.
  535. """
  536. @hookspec(historic=True)
  537. def pytest_warning_recorded(
  538. warning_message: "warnings.WarningMessage",
  539. when: "Literal['config', 'collect', 'runtest']",
  540. nodeid: str,
  541. location: Optional[Tuple[str, int, str]],
  542. ) -> None:
  543. """Process a warning captured by the internal pytest warnings plugin.
  544. :param warnings.WarningMessage warning_message:
  545. The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
  546. the same attributes as the parameters of :py:func:`warnings.showwarning`.
  547. :param str when:
  548. Indicates when the warning was captured. Possible values:
  549. * ``"config"``: during pytest configuration/initialization stage.
  550. * ``"collect"``: during test collection.
  551. * ``"runtest"``: during test execution.
  552. :param str nodeid:
  553. Full id of the item.
  554. :param tuple|None location:
  555. When available, holds information about the execution context of the captured
  556. warning (filename, linenumber, function). ``function`` evaluates to <module>
  557. when the execution context is at the module level.
  558. .. versionadded:: 6.0
  559. """
  560. # -------------------------------------------------------------------------
  561. # Hooks for influencing skipping
  562. # -------------------------------------------------------------------------
  563. def pytest_markeval_namespace(config: "Config") -> Dict[str, Any]:
  564. """Called when constructing the globals dictionary used for
  565. evaluating string conditions in xfail/skipif markers.
  566. This is useful when the condition for a marker requires
  567. objects that are expensive or impossible to obtain during
  568. collection time, which is required by normal boolean
  569. conditions.
  570. .. versionadded:: 6.2
  571. :param _pytest.config.Config config: The pytest config object.
  572. :returns: A dictionary of additional globals to add.
  573. """
  574. # -------------------------------------------------------------------------
  575. # error handling and internal debugging hooks
  576. # -------------------------------------------------------------------------
  577. def pytest_internalerror(
  578. excrepr: "ExceptionRepr", excinfo: "ExceptionInfo[BaseException]",
  579. ) -> Optional[bool]:
  580. """Called for internal errors.
  581. Return True to suppress the fallback handling of printing an
  582. INTERNALERROR message directly to sys.stderr.
  583. """
  584. def pytest_keyboard_interrupt(
  585. excinfo: "ExceptionInfo[Union[KeyboardInterrupt, Exit]]",
  586. ) -> None:
  587. """Called for keyboard interrupt."""
  588. def pytest_exception_interact(
  589. node: Union["Item", "Collector"],
  590. call: "CallInfo[Any]",
  591. report: Union["CollectReport", "TestReport"],
  592. ) -> None:
  593. """Called when an exception was raised which can potentially be
  594. interactively handled.
  595. May be called during collection (see :py:func:`pytest_make_collect_report`),
  596. in which case ``report`` is a :py:class:`_pytest.reports.CollectReport`.
  597. May be called during runtest of an item (see :py:func:`pytest_runtest_protocol`),
  598. in which case ``report`` is a :py:class:`_pytest.reports.TestReport`.
  599. This hook is not called if the exception that was raised is an internal
  600. exception like ``skip.Exception``.
  601. """
  602. def pytest_enter_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
  603. """Called upon pdb.set_trace().
  604. Can be used by plugins to take special action just before the python
  605. debugger enters interactive mode.
  606. :param _pytest.config.Config config: The pytest config object.
  607. :param pdb.Pdb pdb: The Pdb instance.
  608. """
  609. def pytest_leave_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
  610. """Called when leaving pdb (e.g. with continue after pdb.set_trace()).
  611. Can be used by plugins to take special action just after the python
  612. debugger leaves interactive mode.
  613. :param _pytest.config.Config config: The pytest config object.
  614. :param pdb.Pdb pdb: The Pdb instance.
  615. """