Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Plugins and Coverage

conftest.py Hooks and Local Plugins

Customize pytest with hook functions in conftest.py: add command-line options, skip slow tests by default, change test order, add report lines, and package the code as a plugin.

Fixtures and marks let you shape tests. Hooks let you shape pytest itself. A hook is a function with a special name that pytest calls at a defined moment: when it parses options, collects tests, runs each test, or prints the final summary. Every plugin you have ever installed, from pytest-cov to pytest-mock, is nothing more than a bundle of hook functions and fixtures.

You do not need to publish anything to use this power. Put hook functions in a conftest.py file and pytest picks them up, a local plugin. This lesson builds three real features that way and then shows how a local plugin becomes an installable one.

Where hooks live

flowchart TB
    P["pytest core + built-in plugins"] --> I["installed plugins<br/>(entry points)"]
    I --> C["conftest.py files<br/>(rootdir and test folders)"]
    C --> H["hook functions<br/>pytest_addoption, pytest_configure,<br/>pytest_collection_modifyitems, ..."]

Hooks are discovered in installed plugins and in conftest.py files; a conftest.py applies to its own folder and below.

A hook function must carry the exact name from the pytest hook reference (they all start with pytest_) and may declare only the parameters it needs. Pytest passes them by name, the same way it passes fixtures.

Feature 1: a --runslow option

A very common recipe: tests marked slow are skipped unless you ask for them with --runslow. It uses three hooks together: pytest_addoption (register the flag), pytest_configure (register the marker, so there is no warning) and pytest_collection_modifyitems (attach a skip to the slow tests).

Python Skip slow tests unless --runslow is given

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

-rs asks for a short summary of skipped tests and their reasons. The config object gives access to options (config.getoption), ini values and the plugin manager. The items list holds every collected test; you may reorder it, filter it, or add markers.

Feature 2: reordering and adding to the report

pytest_collection_modifyitems can also sort tests. Another hook, pytest_terminal_summary, appends your own section to the end of the report, and pytest_report_header adds lines at the top. Here is a plugin that runs unit tests before integration tests and prints how many of each it saw:

Python Reorder tests and add a report section

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the order in the verbose output: both plain tests run before the integration ones, even though the file lists them interleaved.

Feature 3: wrapping hooks with hookwrapper

Some hooks let you run code around other implementations. A common use is collecting test outcomes. pytest_runtest_makereport is called for each test phase (setup, call, teardown); a wrapper can read the finished report and, for example, attach the result to the test item so a fixture can see whether the test failed:

Python
# conftest.py
import pytest

@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport(item, call):
    report = yield                     # let pytest build the report
    setattr(item, "rep_" + report.when, report)
    return report

@pytest.fixture
def screenshot_on_failure(request):
    yield
    if request.node.rep_call.failed:
        print("saving screenshot for", request.node.name)

The yield hands control to the other implementations and gives you their result. (Older code uses @pytest.hookimpl(hookwrapper=True) with outcome = yield and outcome.get_result(); both styles exist in the wild.)

From conftest.py to a real plugin

A conftest.py plugin applies to one project. To share it, move the same functions into a module and register it in the package metadata through the pytest11 entry point:

TOML
# pyproject.toml of the plugin package
[project]
name = "pytest-runslow"
version = "0.1.0"
dependencies = ["pytest>=8"]

[project.entry-points.pytest11]
runslow = "pytest_runslow.plugin"

After pip install pytest-runslow, pytest loads pytest_runslow.plugin in every project: no conftest.py needed. Name the package pytest-<something> so people can find it. Without packaging you can still load a module explicitly: pytest -p myplugin or pytest_plugins = ["myplugin"] in a top-level conftest.py.

You can even test hooks with pytest itself using the built-in pytester plugin (pytest_plugins = ["pytester"]), whose pytester.runpytest() runs a sub-session and returns its outcomes. That is how pytest tests its own plugins.

Useful hooks at a glance

Hook Use it to
pytest_addoption(parser) Add command-line options or ini keys
pytest_configure(config) Register markers, set up global state
pytest_sessionstart / pytest_sessionfinish Run once per session
pytest_collection_modifyitems(config, items) Filter, reorder or mark collected tests
pytest_generate_tests(metafunc) Parametrize tests dynamically
pytest_runtest_setup/call/teardown(item) Act around each test phase
pytest_runtest_makereport(item, call) Inspect or change a test's outcome report
pytest_terminal_summary(terminalreporter) Add a section to the end of the report
pytest_report_header(config) Add lines to the header

Keep hook code small and boring. A conftest.py that grows into hundreds of lines of cleverness is hard for a teammate to debug. When in doubt, a plain fixture is simpler than a hook.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a pytest hook?

    Hooks are called by pytest at fixed points in its lifecycle. Plugins and conftest.py files implement them.
  2. 2. Which hook would you use to add a --runslow command-line flag?

    pytest_addoption receives the parser, on which you call addoption().
  3. 3. How do you attach a skip to every test marked slow when --runslow is absent?

    The collection hook sees every test item and may add markers to them before they run.
  4. 4. How does an installed package get its hooks loaded automatically by pytest?

    Plugins declare a module under the pytest11 entry-point group; pytest loads all of them at startup.

Summary

  • Hooks are pytest_* functions called by pytest; conftest.py can implement them for a folder tree.
  • pytest_addoption, pytest_configure and pytest_collection_modifyitems together give you options, markers and test selection.
  • Reordering, report headers and summaries are one small hook each; wrappers observe results.
  • Move the same code into a package with a pytest11 entry point to share it.
  • Prefer fixtures when a hook is not needed.

Next: A Tour of Third-Party Plugins