1# -*- coding: utf-8 -*-
2""" hook specifications for pytest plugins, invoked from main.py and builtin plugins.  """
3from pluggy import HookspecMarker
4
5from _pytest.deprecated import PYTEST_LOGWARNING
6
7hookspec = HookspecMarker("pytest")
8
9# -------------------------------------------------------------------------
10# Initialization hooks called for every plugin
11# -------------------------------------------------------------------------
12
13
14@hookspec(historic=True)
15def pytest_addhooks(pluginmanager):
16    """called at plugin registration time to allow adding new hooks via a call to
17    ``pluginmanager.add_hookspecs(module_or_class, prefix)``.
18
19
20    :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager
21
22    .. note::
23        This hook is incompatible with ``hookwrapper=True``.
24    """
25
26
27@hookspec(historic=True)
28def pytest_plugin_registered(plugin, manager):
29    """ a new pytest plugin got registered.
30
31    :param plugin: the plugin module or instance
32    :param _pytest.config.PytestPluginManager manager: pytest plugin manager
33
34    .. note::
35        This hook is incompatible with ``hookwrapper=True``.
36    """
37
38
39@hookspec(historic=True)
40def pytest_addoption(parser):
41    """register argparse-style options and ini-style config values,
42    called once at the beginning of a test run.
43
44    .. note::
45
46        This function should be implemented only in plugins or ``conftest.py``
47        files situated at the tests root directory due to how pytest
48        :ref:`discovers plugins during startup <pluginorder>`.
49
50    :arg _pytest.config.Parser parser: To add command line options, call
51        :py:func:`parser.addoption(...) <_pytest.config.Parser.addoption>`.
52        To add ini-file values call :py:func:`parser.addini(...)
53        <_pytest.config.Parser.addini>`.
54
55    Options can later be accessed through the
56    :py:class:`config <_pytest.config.Config>` object, respectively:
57
58    - :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to
59      retrieve the value of a command line option.
60
61    - :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve
62      a value read from an ini-style file.
63
64    The config object is passed around on many internal objects via the ``.config``
65    attribute or can be retrieved as the ``pytestconfig`` fixture.
66
67    .. note::
68        This hook is incompatible with ``hookwrapper=True``.
69    """
70
71
72@hookspec(historic=True)
73def pytest_configure(config):
74    """
75    Allows plugins and conftest files to perform initial configuration.
76
77    This hook is called for every plugin and initial conftest file
78    after command line options have been parsed.
79
80    After that, the hook is called for other conftest files as they are
81    imported.
82
83    .. note::
84        This hook is incompatible with ``hookwrapper=True``.
85
86    :arg _pytest.config.Config config: pytest config object
87    """
88
89
90# -------------------------------------------------------------------------
91# Bootstrapping hooks called for plugins registered early enough:
92# internal and 3rd party plugins.
93# -------------------------------------------------------------------------
94
95
96@hookspec(firstresult=True)
97def pytest_cmdline_parse(pluginmanager, args):
98    """return initialized config object, parsing the specified args.
99
100    Stops at first non-None result, see :ref:`firstresult`
101
102    .. note::
103        This hook will only be called for plugin classes passed to the ``plugins`` arg when using `pytest.main`_ to
104        perform an in-process test run.
105
106    :param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager
107    :param list[str] args: list of arguments passed on the command line
108    """
109
110
111def pytest_cmdline_preparse(config, args):
112    """(**Deprecated**) modify command line arguments before option parsing.
113
114    This hook is considered deprecated and will be removed in a future pytest version. Consider
115    using :func:`pytest_load_initial_conftests` instead.
116
117    .. note::
118        This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
119
120    :param _pytest.config.Config config: pytest config object
121    :param list[str] args: list of arguments passed on the command line
122    """
123
124
125@hookspec(firstresult=True)
126def pytest_cmdline_main(config):
127    """ called for performing the main command line action. The default
128    implementation will invoke the configure hooks and runtest_mainloop.
129
130    .. note::
131        This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
132
133    Stops at first non-None result, see :ref:`firstresult`
134
135    :param _pytest.config.Config config: pytest config object
136    """
137
138
139def pytest_load_initial_conftests(early_config, parser, args):
140    """ implements the loading of initial conftest files ahead
141    of command line option parsing.
142
143    .. note::
144        This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
145
146    :param _pytest.config.Config early_config: pytest config object
147    :param list[str] args: list of arguments passed on the command line
148    :param _pytest.config.Parser parser: to add command line options
149    """
150
151
152# -------------------------------------------------------------------------
153# collection hooks
154# -------------------------------------------------------------------------
155
156
157@hookspec(firstresult=True)
158def pytest_collection(session):
159    """Perform the collection protocol for the given session.
160
161    Stops at first non-None result, see :ref:`firstresult`.
162
163    :param _pytest.main.Session session: the pytest session object
164    """
165
166
167def pytest_collection_modifyitems(session, config, items):
168    """ called after collection has been performed, may filter or re-order
169    the items in-place.
170
171    :param _pytest.main.Session session: the pytest session object
172    :param _pytest.config.Config config: pytest config object
173    :param List[_pytest.nodes.Item] items: list of item objects
174    """
175
176
177def pytest_collection_finish(session):
178    """ called after collection has been performed and modified.
179
180    :param _pytest.main.Session session: the pytest session object
181    """
182
183
184@hookspec(firstresult=True)
185def pytest_ignore_collect(path, config):
186    """ return True to prevent considering this path for collection.
187    This hook is consulted for all files and directories prior to calling
188    more specific hooks.
189
190    Stops at first non-None result, see :ref:`firstresult`
191
192    :param path: a :py:class:`py.path.local` - the path to analyze
193    :param _pytest.config.Config config: pytest config object
194    """
195
196
197@hookspec(firstresult=True)
198def pytest_collect_directory(path, parent):
199    """ called before traversing a directory for collection files.
200
201    Stops at first non-None result, see :ref:`firstresult`
202
203    :param path: a :py:class:`py.path.local` - the path to analyze
204    """
205
206
207def pytest_collect_file(path, parent):
208    """ return collection Node or None for the given path. Any new node
209    needs to have the specified ``parent`` as a parent.
210
211    :param path: a :py:class:`py.path.local` - the path to collect
212    """
213
214
215# logging hooks for collection
216
217
218def pytest_collectstart(collector):
219    """ collector starts collecting. """
220
221
222def pytest_itemcollected(item):
223    """ we just collected a test item. """
224
225
226def pytest_collectreport(report):
227    """ collector finished collecting. """
228
229
230def pytest_deselected(items):
231    """ called for test items deselected, e.g. by keyword. """
232
233
234@hookspec(firstresult=True)
235def pytest_make_collect_report(collector):
236    """ perform ``collector.collect()`` and return a CollectReport.
237
238    Stops at first non-None result, see :ref:`firstresult` """
239
240
241# -------------------------------------------------------------------------
242# Python test function related hooks
243# -------------------------------------------------------------------------
244
245
246@hookspec(firstresult=True)
247def pytest_pycollect_makemodule(path, parent):
248    """ return a Module collector or None for the given path.
249    This hook will be called for each matching test module path.
250    The pytest_collect_file hook needs to be used if you want to
251    create test modules for files that do not match as a test module.
252
253    Stops at first non-None result, see :ref:`firstresult`
254
255    :param path: a :py:class:`py.path.local` - the path of module to collect
256    """
257
258
259@hookspec(firstresult=True)
260def pytest_pycollect_makeitem(collector, name, obj):
261    """ return custom item/collector for a python object in a module, or None.
262
263    Stops at first non-None result, see :ref:`firstresult` """
264
265
266@hookspec(firstresult=True)
267def pytest_pyfunc_call(pyfuncitem):
268    """ call underlying test function.
269
270    Stops at first non-None result, see :ref:`firstresult` """
271
272
273def pytest_generate_tests(metafunc):
274    """ generate (multiple) parametrized calls to a test function."""
275
276
277@hookspec(firstresult=True)
278def pytest_make_parametrize_id(config, val, argname):
279    """Return a user-friendly string representation of the given ``val`` that will be used
280    by @pytest.mark.parametrize calls. Return None if the hook doesn't know about ``val``.
281    The parameter name is available as ``argname``, if required.
282
283    Stops at first non-None result, see :ref:`firstresult`
284
285    :param _pytest.config.Config config: pytest config object
286    :param val: the parametrized value
287    :param str argname: the automatic parameter name produced by pytest
288    """
289
290
291# -------------------------------------------------------------------------
292# generic runtest related hooks
293# -------------------------------------------------------------------------
294
295
296@hookspec(firstresult=True)
297def pytest_runtestloop(session):
298    """ called for performing the main runtest loop
299    (after collection finished).
300
301    Stops at first non-None result, see :ref:`firstresult`
302
303    :param _pytest.main.Session session: the pytest session object
304    """
305
306
307def pytest_itemstart(item, node):
308    """(**Deprecated**) use pytest_runtest_logstart. """
309
310
311@hookspec(firstresult=True)
312def pytest_runtest_protocol(item, nextitem):
313    """ implements the runtest_setup/call/teardown protocol for
314    the given test item, including capturing exceptions and calling
315    reporting hooks.
316
317    :arg item: test item for which the runtest protocol is performed.
318
319    :arg nextitem: the scheduled-to-be-next test item (or None if this
320                   is the end my friend).  This argument is passed on to
321                   :py:func:`pytest_runtest_teardown`.
322
323    :return boolean: True if no further hook implementations should be invoked.
324
325
326    Stops at first non-None result, see :ref:`firstresult` """
327
328
329def pytest_runtest_logstart(nodeid, location):
330    """ signal the start of running a single test item.
331
332    This hook will be called **before** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and
333    :func:`pytest_runtest_teardown` hooks.
334
335    :param str nodeid: full id of the item
336    :param location: a triple of ``(filename, linenum, testname)``
337    """
338
339
340def pytest_runtest_logfinish(nodeid, location):
341    """ signal the complete finish of running a single test item.
342
343    This hook will be called **after** :func:`pytest_runtest_setup`, :func:`pytest_runtest_call` and
344    :func:`pytest_runtest_teardown` hooks.
345
346    :param str nodeid: full id of the item
347    :param location: a triple of ``(filename, linenum, testname)``
348    """
349
350
351def pytest_runtest_setup(item):
352    """ called before ``pytest_runtest_call(item)``. """
353
354
355def pytest_runtest_call(item):
356    """ called to execute the test ``item``. """
357
358
359def pytest_runtest_teardown(item, nextitem):
360    """ called after ``pytest_runtest_call``.
361
362    :arg nextitem: the scheduled-to-be-next test item (None if no further
363                   test item is scheduled).  This argument can be used to
364                   perform exact teardowns, i.e. calling just enough finalizers
365                   so that nextitem only needs to call setup-functions.
366    """
367
368
369@hookspec(firstresult=True)
370def pytest_runtest_makereport(item, call):
371    """ return a :py:class:`_pytest.runner.TestReport` object
372    for the given :py:class:`pytest.Item <_pytest.main.Item>` and
373    :py:class:`_pytest.runner.CallInfo`.
374
375    Stops at first non-None result, see :ref:`firstresult` """
376
377
378def pytest_runtest_logreport(report):
379    """ process a test setup/call/teardown report relating to
380    the respective phase of executing a test. """
381
382
383@hookspec(firstresult=True)
384def pytest_report_to_serializable(config, report):
385    """
386    .. warning::
387        This hook is experimental and subject to change between pytest releases, even
388        bug fixes.
389
390        The intent is for this to be used by plugins maintained by the core-devs, such
391        as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal
392        'resultlog' plugin.
393
394        In the future it might become part of the public hook API.
395
396    Serializes the given report object into a data structure suitable for sending
397    over the wire, e.g. converted to JSON.
398    """
399
400
401@hookspec(firstresult=True)
402def pytest_report_from_serializable(config, data):
403    """
404    .. warning::
405        This hook is experimental and subject to change between pytest releases, even
406        bug fixes.
407
408        The intent is for this to be used by plugins maintained by the core-devs, such
409        as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal
410        'resultlog' plugin.
411
412        In the future it might become part of the public hook API.
413
414    Restores a report object previously serialized with pytest_report_to_serializable().
415    """
416
417
418# -------------------------------------------------------------------------
419# Fixture related hooks
420# -------------------------------------------------------------------------
421
422
423@hookspec(firstresult=True)
424def pytest_fixture_setup(fixturedef, request):
425    """ performs fixture setup execution.
426
427    :return: The return value of the call to the fixture function
428
429    Stops at first non-None result, see :ref:`firstresult`
430
431    .. note::
432        If the fixture function returns None, other implementations of
433        this hook function will continue to be called, according to the
434        behavior of the :ref:`firstresult` option.
435    """
436
437
438def pytest_fixture_post_finalizer(fixturedef, request):
439    """ called after fixture teardown, but before the cache is cleared so
440    the fixture result cache ``fixturedef.cached_result`` can
441    still be accessed."""
442
443
444# -------------------------------------------------------------------------
445# test session related hooks
446# -------------------------------------------------------------------------
447
448
449def pytest_sessionstart(session):
450    """ called after the ``Session`` object has been created and before performing collection
451    and entering the run test loop.
452
453    :param _pytest.main.Session session: the pytest session object
454    """
455
456
457def pytest_sessionfinish(session, exitstatus):
458    """ called after whole test run finished, right before returning the exit status to the system.
459
460    :param _pytest.main.Session session: the pytest session object
461    :param int exitstatus: the status which pytest will return to the system
462    """
463
464
465def pytest_unconfigure(config):
466    """ called before test process is exited.
467
468    :param _pytest.config.Config config: pytest config object
469    """
470
471
472# -------------------------------------------------------------------------
473# hooks for customizing the assert methods
474# -------------------------------------------------------------------------
475
476
477def pytest_assertrepr_compare(config, op, left, right):
478    """return explanation for comparisons in failing assert expressions.
479
480    Return None for no custom explanation, otherwise return a list
481    of strings.  The strings will be joined by newlines but any newlines
482    *in* a string will be escaped.  Note that all but the first line will
483    be indented slightly, the intention is for the first line to be a summary.
484
485    :param _pytest.config.Config config: pytest config object
486    """
487
488
489# -------------------------------------------------------------------------
490# hooks for influencing reporting (invoked from _pytest_terminal)
491# -------------------------------------------------------------------------
492
493
494def pytest_report_header(config, startdir):
495    """ return a string or list of strings to be displayed as header info for terminal reporting.
496
497    :param _pytest.config.Config config: pytest config object
498    :param startdir: py.path object with the starting dir
499
500    .. note::
501
502        This function should be implemented only in plugins or ``conftest.py``
503        files situated at the tests root directory due to how pytest
504        :ref:`discovers plugins during startup <pluginorder>`.
505    """
506
507
508def pytest_report_collectionfinish(config, startdir, items):
509    """
510    .. versionadded:: 3.2
511
512    return a string or list of strings to be displayed after collection has finished successfully.
513
514    This strings will be displayed after the standard "collected X items" message.
515
516    :param _pytest.config.Config config: pytest config object
517    :param startdir: py.path object with the starting dir
518    :param items: list of pytest items that are going to be executed; this list should not be modified.
519    """
520
521
522@hookspec(firstresult=True)
523def pytest_report_teststatus(report, config):
524    """ return result-category, shortletter and verbose word for reporting.
525
526    :param _pytest.config.Config config: pytest config object
527
528    Stops at first non-None result, see :ref:`firstresult` """
529
530
531def pytest_terminal_summary(terminalreporter, exitstatus, config):
532    """Add a section to terminal summary reporting.
533
534    :param _pytest.terminal.TerminalReporter terminalreporter: the internal terminal reporter object
535    :param int exitstatus: the exit status that will be reported back to the OS
536    :param _pytest.config.Config config: pytest config object
537
538    .. versionadded:: 4.2
539        The ``config`` parameter.
540    """
541
542
543@hookspec(historic=True, warn_on_impl=PYTEST_LOGWARNING)
544def pytest_logwarning(message, code, nodeid, fslocation):
545    """
546    .. deprecated:: 3.8
547
548        This hook is will stop working in a future release.
549
550        pytest no longer triggers this hook, but the
551        terminal writer still implements it to display warnings issued by
552        :meth:`_pytest.config.Config.warn` and :meth:`_pytest.nodes.Node.warn`. Calling those functions will be
553        an error in future releases.
554
555    process a warning specified by a message, a code string,
556    a nodeid and fslocation (both of which may be None
557    if the warning is not tied to a particular node/location).
558
559    .. note::
560        This hook is incompatible with ``hookwrapper=True``.
561    """
562
563
564@hookspec(historic=True)
565def pytest_warning_captured(warning_message, when, item):
566    """
567    Process a warning captured by the internal pytest warnings plugin.
568
569    :param warnings.WarningMessage warning_message:
570        The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
571        the same attributes as the parameters of :py:func:`warnings.showwarning`.
572
573    :param str when:
574        Indicates when the warning was captured. Possible values:
575
576        * ``"config"``: during pytest configuration/initialization stage.
577        * ``"collect"``: during test collection.
578        * ``"runtest"``: during test execution.
579
580    :param pytest.Item|None item:
581        **DEPRECATED**: This parameter is incompatible with ``pytest-xdist``, and will always receive ``None``
582        in a future release.
583
584        The item being executed if ``when`` is ``"runtest"``, otherwise ``None``.
585    """
586
587
588# -------------------------------------------------------------------------
589# doctest hooks
590# -------------------------------------------------------------------------
591
592
593@hookspec(firstresult=True)
594def pytest_doctest_prepare_content(content):
595    """ return processed content for a given doctest
596
597    Stops at first non-None result, see :ref:`firstresult` """
598
599
600# -------------------------------------------------------------------------
601# error handling and internal debugging hooks
602# -------------------------------------------------------------------------
603
604
605def pytest_internalerror(excrepr, excinfo):
606    """ called for internal errors. """
607
608
609def pytest_keyboard_interrupt(excinfo):
610    """ called for keyboard interrupt. """
611
612
613def pytest_exception_interact(node, call, report):
614    """called when an exception was raised which can potentially be
615    interactively handled.
616
617    This hook is only called if an exception was raised
618    that is not an internal exception like ``skip.Exception``.
619    """
620
621
622def pytest_enter_pdb(config, pdb):
623    """ called upon pdb.set_trace(), can be used by plugins to take special
624    action just before the python debugger enters in interactive mode.
625
626    :param _pytest.config.Config config: pytest config object
627    :param pdb.Pdb pdb: Pdb instance
628    """
629
630
631def pytest_leave_pdb(config, pdb):
632    """ called when leaving pdb (e.g. with continue after pdb.set_trace()).
633
634    Can be used by plugins to take special action just after the python
635    debugger leaves interactive mode.
636
637    :param _pytest.config.Config config: pytest config object
638    :param pdb.Pdb pdb: Pdb instance
639    """
640