_pytest.hookspec module

hook specifications for pytest plugins, invoked from main.py and builtin plugins.

pytest_addhooks(pluginmanager)[source]

called at plugin registration time to allow adding new hooks via a call to pluginmanager.add_hookspecs(module_or_class, prefix).

Parameters

pluginmanager (_pytest.config.PytestPluginManager) – pytest plugin manager

Note

This hook is incompatible with hookwrapper=True.

pytest_plugin_registered(plugin, manager)[source]

a new pytest plugin got registered.

Parameters

Note

This hook is incompatible with hookwrapper=True.

pytest_addoption(parser, pluginmanager)[source]

register argparse-style options and ini-style config values, called once at the beginning of a test run.

Note

This function should be implemented only in plugins or conftest.py files situated at the tests root directory due to how pytest discovers plugins during startup.

Parameters

Options can later be accessed through the config object, respectively:

The config object is passed around on many internal objects via the .config attribute or can be retrieved as the pytestconfig fixture.

Note

This hook is incompatible with hookwrapper=True.

pytest_configure(config)[source]

Allows plugins and conftest files to perform initial configuration.

This hook is called for every plugin and initial conftest file after command line options have been parsed.

After that, the hook is called for other conftest files as they are imported.

Note

This hook is incompatible with hookwrapper=True.

Parameters

config (_pytest.config.Config) – pytest config object

pytest_cmdline_parse(pluginmanager, args)[source]

return initialized config object, parsing the specified args.

Stops at first non-None result, see firstresult

Note

This hook will only be called for plugin classes passed to the plugins arg when using `pytest.main`_ to perform an in-process test run.

Parameters
pytest_cmdline_preparse(config, args)[source]

(Deprecated) modify command line arguments before option parsing.

This hook is considered deprecated and will be removed in a future pytest version. Consider using pytest_load_initial_conftests() instead.

Note

This hook will not be called for conftest.py files, only for setuptools plugins.

Parameters
pytest_cmdline_main(config)[source]

called for performing the main command line action. The default implementation will invoke the configure hooks and runtest_mainloop.

Note

This hook will not be called for conftest.py files, only for setuptools plugins.

Stops at first non-None result, see firstresult

Parameters

config (_pytest.config.Config) – pytest config object

pytest_load_initial_conftests(early_config, parser, args)[source]

implements the loading of initial conftest files ahead of command line option parsing.

Note

This hook will not be called for conftest.py files, only for setuptools plugins.

Parameters
pytest_collection(session: Session) → Optional[Any][source]

Perform the collection protocol for the given session.

Stops at first non-None result, see firstresult.

Parameters

session (_pytest.main.Session) – the pytest session object

pytest_collection_modifyitems(session, config, items)[source]

called after collection has been performed, may filter or re-order the items in-place.

Parameters
pytest_collection_finish(session)[source]

called after collection has been performed and modified.

Parameters

session (_pytest.main.Session) – the pytest session object

pytest_ignore_collect(path, config: Config) → Optional[Union[bool, Tuple[bool, Optional[str]]]][source]

return True to prevent considering this path for collection. This hook is consulted for all files and directories prior to calling more specific hooks.

Stops at first non-None result, see firstresult, i.e. you should only return False if the file should never get ignored (by other hooks).

It can also return a tuple with a reason/description instead, which gets used for reporting:

return (True, "collect_ignore")
Parameters
pytest_collect_directory(path, parent)[source]

called before traversing a directory for collection files.

Stops at first non-None result, see firstresult

Parameters

path (py.path.local) – the path to analyze

pytest_collect_file(path, parent)[source]

return collection Node or None for the given path. Any new node needs to have the specified parent as a parent.

Parameters

path (py.path.local) – the path to collect

pytest_collectstart(collector)[source]

collector starts collecting.

pytest_itemcollected(item)[source]

we just collected a test item.

pytest_collectreport(report)[source]

collector finished collecting.

pytest_deselected(items)[source]

called for test items deselected, e.g. by keyword.

pytest_make_collect_report(collector)[source]

perform collector.collect() and return a CollectReport.

Stops at first non-None result, see firstresult

pytest_pycollect_makemodule(path, parent)[source]

return a Module collector or None for the given path. This hook will be called for each matching test module path. The pytest_collect_file hook needs to be used if you want to create test modules for files that do not match as a test module.

Stops at first non-None result, see firstresult

Parameters

path (py.path.local) – the path of the module to collect

pytest_pycollect_makeitem(collector, name, obj)[source]

return custom item/collector for a python object in a module, or None.

Stops at first non-None result, see firstresult

pytest_pyfunc_call(pyfuncitem)[source]

call underlying test function.

Stops at first non-None result, see firstresult

pytest_generate_tests(metafunc)[source]

generate (multiple) parametrized calls to a test function.

pytest_make_parametrize_id(config, val, argname)[source]

Return a user-friendly string representation of the given val that will be used by @pytest.mark.parametrize calls. Return None if the hook doesn’t know about val. The parameter name is available as argname, if required.

Stops at first non-None result, see firstresult

Parameters
  • config (_pytest.config.Config) – pytest config object

  • val – the parametrized value

  • argname (str) – the automatic parameter name produced by pytest

pytest_runtestloop(session)[source]

called for performing the main runtest loop (after collection finished).

Stops at first non-None result, see firstresult

Parameters

session (_pytest.main.Session) – the pytest session object

pytest_runtest_protocol(item, nextitem)[source]

implements the runtest_setup/call/teardown protocol for the given test item, including capturing exceptions and calling reporting hooks.

Parameters
  • item – test item for which the runtest protocol is performed.

  • nextitem – the scheduled-to-be-next test item (or None if this is the end my friend). This argument is passed on to pytest_runtest_teardown().

Return boolean

True if no further hook implementations should be invoked.

Stops at first non-None result, see firstresult

pytest_runtest_logstart(nodeid, location)[source]

signal the start of running a single test item.

This hook will be called before pytest_runtest_setup(), pytest_runtest_call() and pytest_runtest_teardown() hooks.

Parameters
  • nodeid (str) – full id of the item

  • location – a triple of (filename, linenum, testname)

pytest_runtest_logfinish(nodeid, location)[source]

signal the complete finish of running a single test item.

This hook will be called after pytest_runtest_setup(), pytest_runtest_call() and pytest_runtest_teardown() hooks.

Parameters
  • nodeid (str) – full id of the item

  • location – a triple of (filename, linenum, testname)

pytest_runtest_setup(item)[source]

called before pytest_runtest_call(item).

pytest_runtest_call(item)[source]

called to execute the test item.

pytest_runtest_teardown(item, nextitem)[source]

called after pytest_runtest_call.

Parameters

nextitem – the scheduled-to-be-next test item (None if no further test item is scheduled). This argument can be used to perform exact teardowns, i.e. calling just enough finalizers so that nextitem only needs to call setup-functions.

pytest_runtest_makereport(item, call)[source]

return a _pytest.runner.TestReport object for the given pytest.Item and _pytest.runner.CallInfo.

Stops at first non-None result, see firstresult

pytest_runtest_logreport(report)[source]

process a test setup/call/teardown report relating to the respective phase of executing a test.

pytest_report_to_serializable(config, report)[source]

Serializes the given report object into a data structure suitable for sending over the wire, e.g. converted to JSON.

pytest_report_from_serializable(config, data)[source]

Restores a report object previously serialized with pytest_report_to_serializable().

pytest_fixture_setup(fixturedef, request)[source]

performs fixture setup execution.

Returns

The return value of the call to the fixture function

Stops at first non-None result, see firstresult

Note

If the fixture function returns None, other implementations of this hook function will continue to be called, according to the behavior of the firstresult option.

pytest_fixture_post_finalizer(fixturedef, request)[source]

Called after fixture teardown, but before the cache is cleared, so the fixture result fixturedef.cached_result is still available (not None).

pytest_sessionstart(session)[source]

called after the Session object has been created and before performing collection and entering the run test loop.

Parameters

session (_pytest.main.Session) – the pytest session object

pytest_sessionfinish(session, exitstatus)[source]

called after whole test run finished, right before returning the exit status to the system.

Parameters
  • session (_pytest.main.Session) – the pytest session object

  • exitstatus (int) – the status which pytest will return to the system

pytest_unconfigure(config)[source]

called before test process is exited.

Parameters

config (_pytest.config.Config) – pytest config object

pytest_assertrepr_compare(config, op, left, right)[source]

return explanation for comparisons in failing assert expressions.

Return None for no custom explanation, otherwise return a list of strings. The strings will be joined by newlines but any newlines in a string will be escaped. Note that all but the first line will be indented slightly, the intention is for the first line to be a summary.

Parameters

config (_pytest.config.Config) – pytest config object

pytest_assertion_pass(item, lineno, orig, expl)[source]

(Experimental)

New in version 5.0.

Hook called whenever an assertion passes.

Use this hook to do some processing after a passing assertion. The original assertion information is available in the orig string and the pytest introspected assertion information is available in the expl string.

This hook must be explicitly enabled by the enable_assertion_pass_hook ini-file option:

[pytest]
enable_assertion_pass_hook=true

You need to clean the .pyc files in your project directory and interpreter libraries when enabling this option, as assertions will require to be re-written.

Parameters
  • item (_pytest.nodes.Item) – pytest item object of current test

  • lineno (int) – line number of the assert statement

  • orig (string) – string with original assertion

  • expl (string) – string with assert explanation

Note

This hook is experimental, so its parameters or even the hook itself might be changed/removed without warning in any future pytest release.

If you find this hook useful, please share your feedback opening an issue.

pytest_report_header(config, startdir)[source]

return a string or list of strings to be displayed as header info for terminal reporting.

Parameters
  • config (_pytest.config.Config) – pytest config object

  • startdir (py.path.local) – object with the starting dir

Note

This function should be implemented only in plugins or conftest.py files situated at the tests root directory due to how pytest discovers plugins during startup.

pytest_report_collectionfinish(config, startdir, items)[source]

New in version 3.2.

return a string or list of strings to be displayed after collection has finished successfully.

This strings will be displayed after the standard “collected X items” message.

Parameters
  • config (_pytest.config.Config) – pytest config object

  • startdirpy.path.local object with the starting dir

  • items – list of pytest items that are going to be executed; this list should not be modified.

pytest_report_teststatus(report, config)[source]

return result-category, shortletter and verbose word for reporting.

Parameters

config (_pytest.config.Config) – pytest config object

Stops at first non-None result, see firstresult

pytest_terminal_summary(terminalreporter, exitstatus, config)[source]

Add a section to terminal summary reporting.

Parameters

New in version 4.2: The config parameter.

pytest_warning_captured(warning_message, when, item, location)[source]

Process a warning captured by the internal pytest warnings plugin.

Parameters
  • warning_message (warnings.WarningMessage) – The captured warning. This is the same object produced by warnings.catch_warnings(), and contains the same attributes as the parameters of warnings.showwarning().

  • when (str) –

    Indicates when the warning was captured. Possible values:

    • "config": during pytest configuration/initialization stage.

    • "collect": during test collection.

    • "runtest": during test execution.

  • item (pytest.Item|None) –

    DEPRECATED: This parameter is incompatible with pytest-xdist, and will always receive None in a future release.

    The item being executed if when is "runtest", otherwise None.

  • location (tuple) – Holds information about the execution context of the captured warning (filename, linenumber, function). function evaluates to <module> when the execution context is at the module level.

pytest_doctest_prepare_content(content)[source]

return processed content for a given doctest

Stops at first non-None result, see firstresult

pytest_internalerror(excrepr, excinfo)[source]

called for internal errors.

pytest_keyboard_interrupt(excinfo)[source]

called for keyboard interrupt.

pytest_exception_interact(node, call, report)[source]

called when an exception was raised which can potentially be interactively handled.

This hook is only called if an exception was raised that is not an internal exception like skip.Exception.

pytest_enter_pdb(config, pdb)[source]

called upon pdb.set_trace(), can be used by plugins to take special action just before the python debugger enters in interactive mode.

Parameters
pytest_leave_pdb(config, pdb)[source]

called when leaving pdb (e.g. with continue after pdb.set_trace()).

Can be used by plugins to take special action just after the python debugger leaves interactive mode.

Parameters