Code Reference

Plugins

Pytest · Reference cheat sheet

Plugins

Pytest · Reference cheat sheet


📋 Overview

Plugins extend pytest via entry points or local modules. Popular ones cover coverage, Django, asyncio, timeouts, random order, and HTML reports.

🔧 Core concepts

PluginPurpose
pytest-covCoverage
pytest-xdistParallel
pytest-asyncioAsync
pytest-djangoDjango
pytest-timeoutHang protection
pytest-mockmocker fixture
pytest-htmlHTML report

Local plugins: modules with hooks, loaded via pytest_plugins or -p.

💡 Examples

Install common set:

python -m pip install pytest-cov pytest-xdist pytest-asyncio pytest-mock

Minimal local plugin:

# tests/plugins/env.py
def pytest_addoption(parser):
    parser.addoption("--runslow", action="store_true")

def pytest_configure(config):
    config.addinivalue_line("markers", "slow: slow tests")
# conftest.py
pytest_plugins = ["tests.plugins.env"]

List plugins:

pytest --trace-config
pytest -p no:cacheprovider

Entry-point plugin sketch:

# myplugin.py
def pytest_runtest_setup(item):
    if "network" in item.keywords and not item.config.getoption("--network"):
        pytest.skip("needs --network")

⚠️ Pitfalls

  • Plugin version skew with pytest major upgrades.
  • Loading the same plugin twice (entry point + pytest_plugins).
  • Order-dependent plugins mutating collection unexpectedly.
  • Disabling builtin plugins accidentally with -p no:....
  • Heavy plugins imported at collection time slowing startup.

On this page