Bookmarks
ReferenceTesting (QA)BackendVerified

pytest

pytest is a Python test framework. This reference covers installation, assert, fixtures and conftest.py, parametrisation, markers, configuration and plugins.

checked 1 Nov · next check 8 Nov · 42 min read

Sections
11
Reading
42 min
Current version
9.2.0
Written from
docs.pytest.org/en/stable

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What pytest is and how it works

pytest is a framework for automated tests in Python. A test is an ordinary test_… function with an assert statement, and fixtures prepare the data and environment for it. pytest finds tests by file and function names and explains every failure in detail.

pytest suits unit, integration and functional tests of Python code, including checks of HTTP APIs. It also runs tests written with unittest, so an old test suite can be migrated gradually. Browser tests are covered in the Playwright reference.

A test has four steps: arrange, act, assert and cleanup. In pytest, fixtures take care of arrange and cleanup, leaving only the act and assert steps in the test body:

pythontests/test_cart.py
import pytest  @pytest.fixturedef cart():    # arrange: item, price, quantity    return [("book", 100, 2), ("pen", 15, 4)]  def test_cart_total(cart):    # act    total = sum(price * qty for _, price, qty in cart)    # assert    assert total == 260

A run has two stages. First comes collection: pytest walks the directories, opens test_*.py and *_test.py files, and collects test… functions and methods of Test… classes. Then each test goes through three phases: setup prepares the fixtures, call runs the test, and teardown finalises the fixtures. The outcome depends on where the error occurred. A failed assert or any other exception in the test body is failed. An exception in a fixture is error, and if a fixture fails during setup, the test itself does not run.

The setup, call and teardown phases repeat for every collected test.

How it differs from unittest

Featurepytestunittest
Testa test_… function or a method of a Test… class, no inheritancea method of a class that inherits from unittest.TestCase
Assertionsplain assert; pytest shows the values of the expressionmethods such as self.assertEqual() and self.assertTrue()
Setup and cleanupfixtures; a test requests them by argument namesetUp() and tearDown(), setUpClass() and tearDownClass()
Parametrisation@pytest.mark.parametrizesubTest(); pytest parametrisation does not work in TestCase classes
Pluginsplugin fixtures and hooks work in all teststhird-party plugins do not always work in TestCase classes

Write new tests in the pytest style: functions, assert and fixtures. Run existing unittest tests with pytest as they are. In TestCase classes, the skip, skipif and xfail markers and fixtures with autouse=True work, but regular fixtures and parametrisation do not.

What you need to know first

  • Python: functions, modules, imports and the venv virtual environment — see the Python reference.
  • How to choose test values: equivalence classes and boundary values — see the “Test design” reference.
  • What to check in HTTP API responses — see the “API testing” reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday pytest commands and constructs. Replace the names in the examples (tests/test_orders.py, test_total, smoke) with your own; assertions, fixtures, parametrisation and markers are covered in detail in their own sections, and pytest --help prints the full list of flags.

Running tests

TaskSyntax
All tests in the projectpytest
Short output: no header or file namespytest -q
Verbose: one line per testpytest -v
Stop at the first failurepytest -x
Stop after two failurespytest --maxfail=2
One filepytest tests/test_orders.py
One testpytest tests/test_orders.py::test_total
Via the interpreter, with the current directory in sys.pathpython -m pytest

Selecting tests

TaskSyntax
By part of the namepytest -k total
By an expression over namespytest -k "total and not refund"
By markerpytest -m smoke
Everything except slow testspytest -m "not slow"
Only tests that failed last timepytest --lf
Failed tests first, then the restpytest --ff
Show what will runpytest --collect-only -q
Skip a directorypytest --ignore=tests/e2e

Output and debugging

TaskSyntax
Show print output from testspytest -s
Summary of all outcomes at the endpytest -rA
Short tracebackspytest --tb=short
The 10 slowest testspytest --durations=10
Debugger on failurepytest --pdb
JUnit XML report for CIpytest --junit-xml=report.xml
pytest versionpytest --version

Assertions

TaskSyntax
Equalityassert order_total(items) == 250
Assertion with a messageassert total > 0, "empty order"
Expect an exceptionwith pytest.raises(ValueError):
Exception with matching textwith pytest.raises(ValueError, match="quantity"):
Floating-point numbersassert 0.1 + 0.2 == pytest.approx(0.3)
Expect a warningwith pytest.warns(DeprecationWarning):

Fixtures

TaskSyntax
Declare a fixture@pytest.fixture above a function
Clean up after a testyield client, then client.close()
One for the whole run@pytest.fixture(scope="session")
For all tests without requesting it@pytest.fixture(autouse=True)
Temporary directory for a testthe tmp_path argument
Environment variable for the duration of a testmonkeypatch.setenv("APP_ENV", "test")
Captured print outputcapsys.readouterr().out
List available fixturespytest --fixtures

Parametrisation and markers

TaskSyntax
Run a test with several values@pytest.mark.parametrize("age", [17, 18, 60, 61])
Several arguments@pytest.mark.parametrize("age,ok", [(17, False), (18, True)])
Name of a case in the reportpytest.param(61, False, id="above-max")
Skip a test@pytest.mark.skip(reason="no test database")
Skip conditionally@pytest.mark.skipif(sys.platform == "win32", reason="POSIX only")
Expected failure@pytest.mark.xfail(reason="bug 214", strict=True)
Custom marker@pytest.mark.smoke
List markerspytest --markers

Caution

TaskSyntax
Clear the cache before a runpytest --cache-clear
Delete the cache manuallyrm -rf .pytest_cache
Disable a plugin for one runpytest -p no:cacheprovider
Do not load plugins automaticallypytest --disable-plugin-autoload

Section sources

the section is written from these pages

Installation and first run

Install pytest from PyPI into the project’s virtual environment with pip install -U pytest, then check it with pytest --version. A first test is a test_*.py file with a test_… function: pytest finds it on its own.

Linux

Create a virtual environment in the project directory, activate it and install pytest. On Debian and Ubuntu, the venv module comes in a separate package, python3-venv. pytest 9 runs on Python 3.10 and newer. For more on virtual environments, see the Python reference, section “Installation and first run”.

bashin the project directory
sudo apt install python3-venvpython3 -m venv .venvsource .venv/bin/activatepip install -U pytestpytest --version

macOS and Windows

On macOS and Windows, venv and pip come with Python itself: skip the first line, and the other commands are the same. On Windows, activate the environment with .venv\Scripts\activate. If uv manages your project, add pytest to the development dependencies with uv add --dev pytest and run tests with uv run pytest.

First test

Create a test_sample.py file with a function and a test for it, then run pytest in the same directory:

pythontest_sample.py
def total(prices):    return sum(prices)  def test_total():    assert total([100, 50]) == 200
textexample output
=================== test session starts ====================platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.yrootdir: /home/user/shopcollected 1 item test_sample.py F                                     [100%] ========================= FAILURES =========================________________________ test_total ________________________     def test_total():>       assert total([100, 50]) == 200E       assert 150 == 200E        +  where 150 = total([100, 50]) test_sample.py:6: AssertionError================= short test summary info ==================FAILED test_sample.py::test_total - assert 150 == 200==================== 1 failed in 0.01s =====================

The F in the progress line is a failed test; a dot is a passed one. The line starting with > shows the failed assertion, and the lines starting with E show its values: pytest took the expression apart and showed that total([100, 50]) returned 150. The exit code of this run is 1. Change the expected value to 150 and the test passes.

How pytest finds tests

  • With no arguments, pytest looks for tests in the directories listed in testpaths if it is set in the configuration, and otherwise in the current directory and all its subdirectories.
  • Test files are test_*.py and *_test.py.
  • Tests are functions with the test prefix and, in classes with the Test prefix, methods with the same prefix; the classes do not need to inherit from anything.
  • pytest does not collect a class without the Test prefix or with an __init__ method, so its tests do not run. The exception is subclasses of unittest.TestCase, which pytest collects whatever their name.
  • Each test in a class gets its own instance of the class: an attribute set through self in one test is not visible in another.

First project

Keep the code in src/ and the tests in tests/ next to it. The pytest documentation recommends this src layout, especially with the default import mode. The tests then check the installed package rather than files that happen to be on the import path.

textproject tree
shop/├── pyproject.toml├── src/│   └── shop/│       ├── __init__.py│       └── orders.py└── tests/    ├── conftest.py    └── test_orders.py

Add pytest to the development dependency group in pyproject.toml. Install the project code into the environment in editable mode, so that changes in src/ are immediately visible to the tests. The --group flag is available in pip from 25.1.

tomlpyproject.toml
[build-system]requires = ["hatchling"]build-backend = "hatchling.build" [project]name = "shop"version = "0.1.0" [dependency-groups]dev = ["pytest"]
bashin the shop directory
pip install -e . --group devpytest

The same pyproject.toml also holds the pytest settings, in the [tool.pytest] table; see the “Configuration” section for details.

Section sources

the section is written from these pages

Assertions: assert, raises, approx

An assertion in pytest is a plain assert statement: when it fails, pytest shows the values of every part of the expression. Exceptions are checked with pytest.raises, warnings with pytest.warns, and floating-point numbers are compared with pytest.approx.

The detailed report is possible because pytest rewrites assert statements when it imports test modules, adding the intermediate values to the message. So instead of assertEqual(), assertIn() and other methods, you write ordinary Python expressions: ==, in, not, <. The running example is an order total and an error for a negative quantity:

pythonsrc/shop/orders.py
def order_total(items):    total = 0    for price, quantity in items:        if quantity < 0:            raise ValueError(f"negative quantity: {quantity}")        total += price * quantity    return total
pythontests/test_orders.py
import pytest from shop.orders import order_total  def test_total():    items = [(100, 2), (50, 1)]    assert order_total(items) == 250  def test_negative_quantity():    with pytest.raises(ValueError, match="quantity"):        order_total([(100, -1)])

What the report shows

For common comparisons, pytest prints the difference. For long strings it is a line-by-line diff, for lists the first differing index, for dictionaries the differing pairs, and for sets the extra elements on each side. The difference is more detailed with -v and complete with -vv.

pythontests/test_orders.py
def test_order_json():    expected = {"id": 7, "sum": 260}    actual = {"id": 7, "sum": 250}    assert actual == expected
textexample output
>       assert actual == expectedE       AssertionError: assert {'id': 7, 'sum': 250} == {'id': 7, 'sum': 260}EE         Omitting 1 identical items, use -vv to showE         Differing items:E         {'sum': 250} != {'sum': 260}E         Use -v to get more diff

The second operand of assert is a message that pytest prints next to the breakdown of the expression. Use it for what the values do not show: which object was being checked.

pythonin a test
assert status == 201, f"order {order_id} was not created"

Exceptions: pytest.raises

pytest.raises is a context manager: the test passes only if the code inside with raises an exception of the given type or a subclass of it. match is a regular expression searched for in the exception text with re.search(). The object after as gives access to the exception itself: .type, .value, .traceback.

pythontests/test_orders.py
def test_error_details():    with pytest.raises(ValueError) as excinfo:        order_total([(100, -3)])    assert excinfo.type is ValueError    assert "-3" in str(excinfo.value)

To check an exception group (ExceptionGroup), use pytest.RaisesGroup and list all the exceptions you expect in the group: with pytest.RaisesGroup(ValueError, TypeError):. An extra or missing exception in the group fails the assertion.

Floating-point numbers: pytest.approx

Because of binary representation, 0.1 + 0.2 == 0.3 is false in Python. pytest.approx compares with a tolerance: by default a relative 1e-6 of the expected value and an absolute 1e-12, the second being needed for comparisons with zero. Change the tolerance with the rel and abs arguments. It compares numbers, ordered sequences, dictionaries and NumPy arrays, but not sets. The < and > operators with pytest.approx raise TypeError.

pythontests/test_prices.py
import pytest  def test_prices():    assert 0.1 + 0.2 == pytest.approx(0.3)    assert 99.95 == pytest.approx(100, abs=0.1)    assert [0.1 + 0.2, 0.2 + 0.4] == pytest.approx([0.3, 0.6])

Warnings: pytest.warns

pytest.warns checks that the code issued a warning of the given class; match works as in pytest.raises. For deprecated functions there is pytest.deprecated_call(), which expects DeprecationWarning, PendingDeprecationWarning or FutureWarning.

pythontests/test_orders.py
import warnings import pytest  def old_total(items):    warnings.warn("use order_total()", DeprecationWarning)    return sum(price * qty for price, qty in items)  def test_old_total_is_deprecated():    with pytest.deprecated_call(match="order_total"):        assert old_total([(10, 2)]) == 20

Where assert is rewritten

pytest rewrites assert only in test modules (files matching the python_files pattern), in conftest.py and in plugin modules. In an ordinary helper module, a failed assert gives a bare AssertionError without values. Register such a module before it is imported, preferably in the root conftest.py:

pythontests/conftest.py
import pytest # src/shop/testing.py: shared assertions for testspytest.register_assert_rewrite("shop.testing")

Section sources

the section is written from these pages

Fixtures

A fixture is a function decorated with @pytest.fixture that prepares data or an environment for a test. The test receives the fixture through an argument with the same name, and the code after yield runs once the test is over and cleans up.

pytest looks at the names of a test’s arguments, finds the fixtures with those names, runs them and passes the results to the test. A fixture can request other fixtures. Within a single test each fixture runs only once: if both the test and another fixture need order, they get the same object. The running example is a session-wide HTTP API client and an API address taken from an environment variable:

pythontests/conftest.py
import os import pytestimport requests  @pytest.fixture(scope="session")def base_url():    return os.environ.get("API_URL", "https://api.example.com")  @pytest.fixture(scope="session")def api_client():    session = requests.Session()    session.headers["Accept"] = "application/json"    # the code after yield runs after the last test    yield session    session.close()
pythontests/test_orders.py
def test_orders_list(api_client, base_url):    response = api_client.get(f"{base_url}/orders")    assert response.status_code == 200

requests is a third-party library (pip install requests); any client that must be closed after use will do.

Teardown: the code after yield

The fixture code before yield is setup; the code after it is teardown, which runs whatever the outcome of the test. Teardown runs in reverse order: the fixture set up last is torn down first. If a fixture fails before yield, its teardown does not run, but pytest still tears down the fixtures that were already set up. Instead of yield you can register a teardown function with request.addfinalizer(), but the documentation recommends yield.

Scopes

The scope defines how long a fixture value lives. The default is function: a new value for each test. A fixture of any scope is created on first request and destroyed after the last test of its scope. Among the fixtures of one test, those with a wider scope are set up first.

ScopeWhen it is destroyedUsed for
function (default)at the end of each testmutable data: an order, a user
classafter the last test in the classshared setup for the tests of one class
moduleafter the last test in the modulean expensive resource for one test file
packageafter the last test in the package, including nested directoriesa resource for a directory of tests
sessionat the end of the runan API client, a database connection, a test server

Example: api_client has the session scope, catalog has module, and order has function. For two tests in one module, api_client and catalog are set up once and order is set up afresh for each test; the fixtures are torn down in reverse order.

pytest --setup-plan tests/test_orders.py prints the same plan for your own tests without running them.

conftest.py: shared fixtures

Fixtures from a conftest.py file are available to all tests in its directory and nested directories, with no import needed. A test looks for a fixture upwards from itself: in its own module, then in the conftest.py of its directory and of the parent directories, and finally in installed plugins. The search never enters neighbouring directories. A fixture with the same name lower in the tree overrides the upper one and can request it as an argument.

The arrows show where a test goes for a fixture: from its own directory up to the tests/ root.

autouse and usefixtures

autouse=True enables a fixture for every test that can see it, without requesting it in the arguments. The @pytest.mark.usefixtures("clean_cart") marker attaches a fixture to a test or class when the test does not need the value itself.

pythontests/test_cart.py
import pytest  @pytest.fixture(autouse=True)def sandbox_payments(monkeypatch):    # no test will reach the real payment system    monkeypatch.setenv("PAYMENTS_MODE", "sandbox")  @pytest.fixturedef clean_cart(tmp_path, monkeypatch):    monkeypatch.setenv("CART_DIR", str(tmp_path))  @pytest.mark.usefixtures("clean_cart")class TestCart:    def test_starts_empty(self, tmp_path):        assert list(tmp_path.iterdir()) == []

Factories and fixture parameters

If a test needs several objects, the fixture returns a factory function and, after yield, cleans up everything the factory created. The params argument runs every test that depends on the fixture once per value; the current value is in request.param.

pythontests/test_orders.py
import pytest  @pytest.fixturedef make_order():    created = []     def _make_order(total):        order = {"id": len(created) + 1, "total": total}        created.append(order)        return order     yield _make_order    # delete everything the factory created here    created.clear()  @pytest.fixture(params=["UZS", "USD"])def currency(request):    return request.param  def test_two_orders(make_order, currency):    first = make_order(100)    second = make_order(250)    assert second["id"] == first["id"] + 1    assert currency in ("UZS", "USD")

Built-in fixtures

FixtureWhat it provides
tmp_patha separate temporary directory for each test, as a pathlib.Path object
tmp_path_factorytemporary directories for session-scoped fixtures
monkeypatchtemporary replacement of attributes, dictionary items and environment variables; everything is restored after the test
capsyscaptured output of sys.stdout and sys.stderr: capsys.readouterr()
caplogcaptured logging records: caplog.messages, caplog.records
requestinformation about the test that requested the fixture; request.param for a parametrised one
pytestconfigthe settings and command-line options of the current run
recwarnwarnings issued during the test
pythontests/test_report.py
def test_report_file(tmp_path, monkeypatch, capsys):    monkeypatch.setenv("REPORT_DIR", str(tmp_path))    report = tmp_path / "report.txt"    report.write_text("total=250", encoding="utf-8")    print(report.read_text(encoding="utf-8"))    assert capsys.readouterr().out == "total=250\n"

pytest keeps the temporary directories of the last three runs and deletes the rest itself. pytest --fixtures prints the full list of fixtures, including those from plugins and your own conftest.py files; fixtures whose names start with _ appear only with -v.

Section sources

the section is written from these pages

Parametrisation

Parametrisation means running one test against several sets of data. The @pytest.mark.parametrize decorator takes argument names and a list of values, and each set becomes a separate test with its own name in the report.

Example: registration is allowed from age 18 to 60 inclusive. The boundary values give four checks — 17, 18, 60 and 61; how to choose such values is covered in the “Test design” reference, section “Boundary values”. In pytest it is one test with four sets:

pythontests/test_register.py
import pytest  def can_register(age):    return 18 <= age <= 60  @pytest.mark.parametrize(    ("age", "expected"),    [        (17, False),        (18, True),        (60, True),        (61, False),    ],)def test_can_register(age, expected):    assert can_register(age) is expected
textexample output of pytest -v
tests/test_register.py::test_can_register[17-False] PASSEDtests/test_register.py::test_can_register[18-True] PASSEDtests/test_register.py::test_can_register[60-True] PASSEDtests/test_register.py::test_can_register[61-False] PASSED

Write the argument names as a comma-separated string ("age,expected") or as a tuple of strings. With a single argument, the list holds the values themselves: [17, 18, 60, 61]. Values are passed to the test as they are, without copying: if a test modifies a list or dictionary from the parameters, the next set sees the changes. An empty list of values does not abort the run: the test is marked as skipped.

Set names: ids and pytest.param

pytest builds the ID of a set from the values: numbers, strings, bool and None are used as they are, and anything else is built from the argument name plus a number (a0, a1). Set readable names with the ids list or, for each set, with pytest.param(..., id=...); marks puts a marker on a set. Select a test by its ID with -k, and pytest --collect-only -q shows all IDs in advance.

pythontests/test_register.py
@pytest.mark.parametrize(    ("age", "expected"),    [        pytest.param(17, False, id="below-min"),        pytest.param(18, True, id="min"),        pytest.param(60, True, id="max"),        pytest.param(61, False, id="above-max"),        pytest.param(            "18", True, id="as-string",            marks=pytest.mark.xfail(raises=TypeError),        ),    ],)def test_can_register_named(age, expected):    assert can_register(age) is expected

The ids, indirect and scope arguments must be passed by name: parametrize("age", values, ids=names). Passed positionally, they raise TypeError at collection time.

All combinations: stacked decorators

Several parametrize decorators on one test produce every combination of values (the Cartesian product): 2 × 3 = 6 tests. Use this to check independent parameters, such as the payment method and the currency. A decorator on a class parametrises all its tests, and a pytestmark variable in a module parametrises all tests in the module.

pythontests/test_payment.py
import pytest  @pytest.mark.parametrize("currency", ["UZS", "USD", "EUR"])@pytest.mark.parametrize("method", ["card", "cash"])def test_payment(method, currency):    payment = {"method": method, "currency": currency}    assert payment["currency"] in ("UZS", "USD", "EUR")
textoutput of --collect-only -q
tests/test_payment.py::test_payment[card-UZS]tests/test_payment.py::test_payment[card-USD]tests/test_payment.py::test_payment[card-EUR]tests/test_payment.py::test_payment[cash-UZS]...

Via a fixture: indirect

With indirect=True, the value goes not straight to the test but to the fixture of the same name, which receives it as request.param. The preparation then happens during setup rather than at collection. Use this for anything slow to prepare: a user with a role, a database connection.

pythontests/test_reports.py
import pytest  @pytest.fixturedef user(request):    # the value comes from parametrize via request.param    return {"name": "test-user", "role": request.param}  @pytest.mark.parametrize(    "user", ["admin", "manager"], indirect=True)def test_can_open_reports(user):    assert user["role"] in ("admin", "manager")

indirect also accepts a list of names: only the listed arguments go through fixtures, and the rest reach the test directly.

Sets decided at run time: pytest_generate_tests

If the sets are known only at run time, for example from a command-line option or a file, declare the pytest_generate_tests hook and call metafunc.parametrize() in it. Unlike other hooks, this one can be declared directly in a test module or class, not only in conftest.py.

Section sources

the section is written from these pages

Markers: skip, xfail and custom ones

A marker is a label on a test, such as @pytest.mark.smoke. Built-in markers skip a test (skip, skipif) or flag an expected failure (xfail), while your own markers split tests into groups so you can run the one you need with -m.

Skipping: skip and skipif

skip always skips a test; skipif skips it if the condition is true at collection time. pytest shows the reason in the summary with the -rs flag. If the condition can be checked only while the test runs, call pytest.skip() in the body.

pythontests/test_skip.py
import osimport sys import pytest  @pytest.mark.skip(reason="payment sandbox is down")def test_refund():    ...  @pytest.mark.skipif(    sys.platform == "win32", reason="POSIX only")def test_path_separator():    assert os.sep == "/"  def test_staging_only():    if os.environ.get("APP_ENV") != "staging":        pytest.skip("needs APP_ENV=staging")    assert True

To skip a whole module, assign the marker to the pytestmark variable at the top of the file: pytestmark = pytest.mark.skipif(...). pytest.importorskip() skips a test or module if a required library is missing:

pythonat the top of a test module
np = pytest.importorskip("numpy", minversion="2.0")

Since 9.1, importorskip catches only ModuleNotFoundError by default: a library that is installed but fails on import produces an error, not a skip. The previous behaviour is exc_type=ImportError.

Expected failure: xfail

A test marked xfail runs, but its failure is expected: it is a known bug or a feature not built yet. If it fails, the outcome is xfailed (letter x); if it unexpectedly passes, it is xpassed (X). By default neither fails the run.

ParameterWhat it doesDefault
reasonthe reason shown in the reportnone
raisescount only a failure with this exception; any other one is an ordinary failureany exception
strictTrue: an unexpected pass (XPASS) fails the whole runthe value of strict_xfail, which is false
runFalse: do not run the test at all, for example if it crashes the interpreterTrue
conditionthe first positional argument: expect the failure only under a condition, together with reasonTrue
pythontests/test_prices.py
import pytest  def average_price(prices):    return sum(prices) / len(prices)  @pytest.mark.xfail(    raises=ZeroDivisionError, strict=True, reason="bug 214")def test_average_price_empty():    assert average_price([]) == 0

strict=True suits known bugs: once the bug is fixed, the test becomes XPASS and the run fails, so you can see that the marker should be removed. The strict_xfail = true option in the configuration makes this the rule for every xfail in the project, and pytest --runxfail runs such tests as ordinary ones.

Custom markers

A custom marker is any name after pytest.mark. Register it in the configuration with the markers option: an unregistered marker raises the PytestUnknownMarkWarning warning, and with strict_markers = true it causes a collection error. This way a typo such as @pytest.mark.smok does not slip through unnoticed. The text after the colon is the description shown by pytest --markers.

tomlpyproject.toml
[tool.pytest]strict_markers = truemarkers = [    "smoke: fast API checks before every deploy",    "slow: takes more than a few seconds",]

The running example is fast API checks with the smoke marker and a long export with the slow marker:

pythontests/test_smoke.py
import pytest  @pytest.mark.smokedef test_health(api_client, base_url):    response = api_client.get(f"{base_url}/health")    assert response.status_code == 200  @pytest.mark.slowdef test_full_export(api_client, base_url):    response = api_client.get(f"{base_url}/orders/export")    assert response.status_code == 200

A marker on a class applies to all its tests, and pytestmark = pytest.mark.smoke in a module applies to all tests in the module. To mark a single parametrised set, use pytest.param(..., marks=...).

Running by marker: -m

CommandWhat it runs
pytest -m smokeonly tests with the smoke marker
pytest -m "not slow"everything except tests with slow
pytest -m "smoke and not slow"tests with smoke that do not have slow
pytest -m "smoke or slow"tests with at least one of the two markers
pytest -m "device(serial='123')"tests with the device marker and the argument serial='123'
pytest --markersthe list of all markers with descriptions

Names in -m are matched exactly and are case-sensitive. A -k expression works differently: it looks for case-insensitive substrings in the names of tests, files, classes and markers.

usefixtures and filterwarnings

@pytest.mark.usefixtures("clean_cart") attaches a fixture to a test that does not need its value. @pytest.mark.filterwarnings() changes the warning filter for a single test, for example turning deprecation warnings into errors. Apply markers only to tests: pytest does not accept a marker on a fixture function and aborts collection.

pythontests/test_prices.py
@pytest.mark.filterwarnings("error::DeprecationWarning")def test_no_deprecated_calls():    assert average_price([10, 20]) == 15

Section sources

the section is written from these pages

Configuration

Keep pytest settings in a single file in the project root: pytest.toml, pytest.ini or a [tool.pytest] table in pyproject.toml. The directory of that file becomes the root directory (rootdir): test names are built relative to it, and the .pytest_cache cache lives there.

Where to keep settings

FileSectionWhen to choose it
pytest.toml or .pytest.toml[pytest]a separate file with TOML types, since pytest 9.0; wins over all other files, even when empty
pytest.ini or .pytest.ini[pytest]a separate file in INI format; wins over everything except pytest.toml, even when empty
pyproject.toml[tool.pytest]settings next to the project description, with TOML types, since 9.0
pyproject.toml[tool.pytest.ini_options]the older form, with INI-style values; needed if the project still runs on pytest older than 9.0
tox.ini[pytest]the project already uses tox
setup.cfg[tool:pytest]not recommended: .cfg files use a different parser

Settings from several files are not merged: the first matching file is used. Example settings for a new project:

tomlpyproject.toml
[tool.pytest]minversion = "9.0"testpaths = ["tests"]addopts = ["-ra", "--import-mode=importlib"]strict = truemarkers = [    "smoke: fast API checks before every deploy",    "slow: takes more than a few seconds",]filterwarnings = ["error"]

Here -ra adds a summary of all outcomes except passes to the end of every run, and filterwarnings = ["error"] turns any warning into a test error.

Common options

OptionWhat it doesDefault
testpathswhere to look for tests when pytest runs from the rootdir without pathsthe current directory
addoptsflags added to every runnone
markersregistered markers with descriptionsnone
python_filespatterns for test file namestest_*.py, *_test.py
python_classes, python_functionsprefixes of classes and functions that contain testsTest, test
norecursedirsdirectories that collection does not enter; your own value replaces the default list.*, build, dist, venv, node_modules and others
filterwarningswarning filters: error, ignore::DeprecationWarningall warnings go to the summary
strict_xfailan XPASS in tests marked xfail fails the run; the former name is xfail_strictfalse
minversionthe minimum pytest version required to runnone
required_pluginsplugins without which the run fails with an errornone
pythonpathdirectories added to the start of sys.pathnone
usefixturesfixtures for all tests in the projectnone

Any option can be overridden for a single run with the -o flag: pytest -o strict_xfail=true. pytest --help lists all options, including those from installed plugins.

Strict mode

strict = true turns on four checks at once: strict_config (warnings raised while parsing pytest settings become errors), strict_markers, strict_parametrization_ids (an error on duplicate set IDs) and strict_xfail. Checks added in future versions will also be enabled by strict mode. That is why the documentation recommends it only if the project pins its pytest version; otherwise, enable the options you need one by one. You can switch off an individual check: strict = true together with strict_parametrization_ids = false.

How rootdir is determined

  1. If -c (--config-file) is given, that file is the configuration and its directory is the rootdir.
  2. Otherwise pytest takes the common parent directory of the paths on the command line (the current directory if there are none). From there it searches upwards for pytest.toml, .pytest.toml, pytest.ini, .pytest.ini, pyproject.toml, tox.ini and setup.cfg. The first suitable file becomes the configuration, and its directory becomes the rootdir.
  3. If there is no such file, the rootdir is the directory of the nearest setup.py above the common directory.
  4. If there is no setup.py either, pytest searches upwards for a configuration from each path on the command line.
  5. If nothing is found, the rootdir is the common parent directory.

A file qualifies only if it has a pytest section: pyproject.toml with [tool.pytest] or [tool.pytest.ini_options], tox.ini with [pytest], setup.cfg with [tool:pytest]. pytest.toml and pytest.ini always qualify. If there are no other candidates, a pyproject.toml without a pytest section also counts as the configuration. pytest prints the rootdir and file it found in the run header (rootdir:, configfile:). The rootdir does not change sys.path and does not affect how modules are imported.

Importing tests: import mode and pythonpath

--import-mode modeHow it importsLimitation
prepend (default)adds the test module’s directory to the start of sys.pathin directories without __init__.py, test file names must be unique
appendadds the directory to the end of sys.pathsame; tests see the installed version of the package, not the local one
importlibimports without changing sys.pathtest modules cannot import each other or helper modules from tests/

For new projects the documentation recommends importlib together with the src/ layout. Keep fixtures in conftest.py as before, and put shared helper code in the application package. If the code is not installed into the environment with pip install -e ., add its directory to the import path: pythonpath = ["src"].

Environment variables

VariableWhat it does
PYTEST_ADDOPTSflags added before the command’s arguments: PYTEST_ADDOPTS="-v"
PYTEST_PLUGINSa comma-separated list of plugins to load at startup
PYTEST_DISABLE_PLUGIN_AUTOLOADdo not load installed plugins automatically
PYTEST_DEBUG_TEMPROOTthe root for tmp_path temporary directories
PYTEST_VERSIONset only while pytest is running: code can use it to tell that it runs under pytest
NO_COLOR, PY_COLORScolour in the output: NO_COLOR switches it off, PY_COLORS=1 switches it on

Section sources

the section is written from these pages

Plugins and hooks

A plugin is a module of hooks and fixtures that extends pytest. A plugin from PyPI is picked up automatically once installed, while a local plugin is a conftest.py file in the test directory. A hook is a function named pytest_… that pytest calls at each stage: configuration, collection, running and reporting.

Installing and loading

pytest finds an installed plugin through the pytest11 entry point in the package metadata, so you don’t need to enable it. Loaded plugins appear on the plugins: line of the run header; pytest --trace-config prints a detailed list with paths.

bashin the project environment
pip install pytest-covpytest --trace-config
TaskHow to write it
Disable a plugin for one runpytest -p no:cacheprovider
Disable a plugin in the projectaddopts = ["-p", "no:cacheprovider"]
Load a plugin at the very startpytest -p pytest_cov
Load only the listed pluginspytest --disable-plugin-autoload -p xdist
Require a plugin to runrequired_plugins = ["pytest-xdist"]
Load a module of fixturespytest_plugins = ["myapp.testing.fixtures"] in the root conftest.py

Declare the pytest_plugins variable only in the root conftest.py of the test directory. It is not supported in a conftest.py lower in the tree: a plugin loaded that way would affect the whole tree, not just one directory.

Common plugins

PluginPurpose
pytest-covtest code coverage
pytest-xdistrunning tests in parallel on several CPUs
pytest-mocka pytest wrapper around unittest.mock
pytest-asynciotests for asyncio code
pytest-djangotests for Django applications
pytest-timeoutaborting tests that hang
pytest-rerunfailuresrerunning failed tests to handle flaky failures
pytest-randomlyrunning tests in random order

For the full list, see the Pytest Plugin List on the documentation site: it automatically includes PyPI packages whose names start with pytest-. The documentation warns that nobody vets the list, so judge a plugin’s quality yourself.

A local plugin: conftest.py

conftest.py is the plugin for its own directory: its hooks apply to the tests in that directory and below. pytest loads it automatically; there is no need to import conftest.py from tests, and doing so is discouraged. Example: a --run-slow option, without which tests marked slow are skipped.

pythontests/conftest.py
import pytest  def pytest_addoption(parser):    parser.addoption(        "--run-slow",        action="store_true",        help="run tests marked slow",    )  def pytest_configure(config):    config.addinivalue_line("markers", "slow: slow test")  def pytest_collection_modifyitems(config, items):    if config.getoption("--run-slow"):        return    skip_slow = pytest.mark.skip(reason="needs --run-slow")    for item in items:        if item.get_closest_marker("slow"):            item.add_marker(skip_slow)
bashin the project root
# slow tests are skipped; the reason is in the summarypytest -rspytest --run-slow
  • pytest_addoption adds command-line options; it is called at startup.
  • pytest_configure is called after the command line and configuration have been parsed; this is where you register markers.
  • pytest_collection_modifyitems is called after collection: you can reorder or filter the items list, or add markers to tests.
  • pytest_runtest_setup is called during the setup phase of each test.

pytest passes a hook only the arguments named in its signature, and it checks the argument names against the hook specification at registration. To change the order among plugins, use @pytest.hookimpl(tryfirst=True) and trylast=True; wrapper=True makes a hook wrap other implementations. Hooks other than pytest_runtest_* must not raise exceptions: that aborts the run.

Packaging your own plugin

To make a plugin installable with pip, declare a pytest11 entry point in pyproject.toml: after the package is installed, pytest loads the module you name. The Framework :: Pytest classifier helps people find the plugin on PyPI. pytest rewrites the entry-point module for detailed assert output by itself; register the other modules of the package with pytest.register_assert_rewrite() in __init__.py.

tomlpyproject.toml
[project]name = "pytest-shop"classifiers = ["Framework :: Pytest"] [project.entry-points.pytest11]shop = "pytest_shop.plugin"

Test plugins with the pytester fixture: enable the built-in plugin with pytest_plugins = ["pytester"] in conftest.py and run nested sessions with pytester.runpytest().

Section sources

the section is written from these pages

Common errors and diagnostics

Start with two things: what pytest collected and the exit code it finished with. pytest --collect-only -q prints the tests it found without running them, and the exit code tells failed tests apart from a collection error, a configuration error or an empty run.

  1. pytest --collect-only -q shows whether the tests you expect were found.
  2. echo $? right after a run gives the exit code.
  3. The rootdir: and configfile: lines in the run header show whether the right configuration was read.
  4. pytest --fixtures tests/orders/test_create.py shows which fixtures the test can see.
  5. pytest --lf -vv runs only the tests that failed last time, with the full diff of values.
Exit codeMeaning
0all tests were collected and passed
1tests ran and some failed
2the run was interrupted by the user
3internal pytest error, or a plugin failed on import
4usage error: a wrong flag, a plugin that is not found, or a conftest.py that cannot be imported
5no tests were collected
6tests passed, but there are more warnings than --max-warnings allows

In Python code these values are available as pytest.ExitCode, and pytest.main() returns them instead of exiting the process.

fixture 'db' not found

Cause: the test requests a fixture that is not visible from its directory. It is not in the test module or in the conftest.py of its directory or any parent, or its name has a typo. A fixture from the conftest.py of a neighbouring directory is not available. Below the error, pytest lists the fixtures the test can see.

bashcheck
pytest --fixtures tests/orders/test_create.py
  • Move the fixture to the conftest.py of a common parent directory, for example tests/conftest.py.
  • Compare the argument name with the name of the fixture function, or with the name= parameter of @pytest.fixture.
  • If the fixture comes from a plugin, install the plugin in the same environment pytest runs from.

collected 0 items and no tests ran

Cause: pytest found no tests, and the exit code is 5. The files are not named test_*.py or *_test.py, the functions don’t start with test, the class doesn’t start with Test or has an __init__, or testpaths points to the wrong place.

bashcheck
pytest --collect-only -q tests/
  • Rename the files and functions to follow the rules, or set your own patterns in python_files and python_functions.
  • Run from the project root or pass the path explicitly: testpaths applies only when pytest is run from the rootdir without paths.

PytestUnknownMarkWarning

Cause: the marker is not registered, either because its name has a typo or because it is a custom marker with no entry in the markers option. With strict_markers = true (or the strict mode strict = true), a module collection error is raised instead of a warning.

bashcheck
pytest --markers
tomlfix: pyproject.toml
[tool.pytest]markers = ["smoke: fast API checks before every deploy"]

PytestCollectionWarning

Cause: pytest found an object that looks like a test but cannot collect it. Most often this is a Test… class with an __init__ method: pytest skips such a class entirely, and its tests do not run.

  • Remove __init__ from the test class and prepare data with a fixture.
  • If an application class named Test… that was imported into a test module matches the pattern, set collect_imported_tests = false or import the module rather than the class.

A test module can’t be imported during collection

Cause: in prepend import mode, test directories without __init__.py are added to sys.path, and two files with the same name, such as tests/orders/test_api.py and tests/users/test_api.py, clash. Another common cause is a test importing project code that is not installed in the environment and not on the import path. A module that fails to import stops the run before any tests; the --continue-on-collection-errors flag lets the remaining tests run.

  • Enable --import-mode=importlib: with it, test file names need not be unique.
  • Or add __init__.py to the test directories so they become packages.
  • Install the code from src/ into the environment with pip install -e ., or add the path: pythonpath = ["src"].

A test fails only when run with others

Cause: tests share state, such as a mutable object in a fixture with module or session scope, a global variable or a database record, and one test corrupts the data of another. On its own the test passes, and in a parallel run first one test fails, then another.

bashcheck: alone and in its module
pytest tests/test_orders.py::test_totalpytest tests/test_orders.py
  • Give the fixture function scope again, or copy shared data inside the test.
  • Clean up after yield in the fixture: delete the records and files it created.
  • Look for order dependence with a random-order plugin, pytest-randomly or pytest-random-order.

A flaky test

A flaky test sometimes passes and sometimes fails with no change to the code. The documentation names the common causes. The test depends on system state it does not control. The check is too strict, for example an exact comparison of floating-point numbers or times. The test does not wait for threads it started.

  • Isolate the environment: use your own data in fixtures and tmp_path instead of shared directories.
  • Compare floating-point numbers with pytest.approx.
  • Wait for threads started by a test or fixture, and don’t call pytest.raises and pytest.warns from several threads: they are not thread-safe.
  • The PYTEST_CURRENT_TEST environment variable shows which test hung: pytest writes the name of the current test into it.
  • Reruns with pytest-rerunfailures and non-strict xfail are a stopgap, not a fix.

Minor problems

SymptomCauseWhat to do
print in a test shows nothingpytest captures output and shows it only for failed testsrun with -s or check the output with the capsys fixture
PytestReturnNotNoneWarning warningthe test returns a value instead of assertingreplace return with assert
--lf runs all testsnothing failed last time, or the .pytest_cache cache was clearedthis is by design; --lfnf none would run nothing instead
exit code 4 right after starta plugin from -p or PYTEST_PLUGINS is not found, or conftest.py cannot be importedinstall the plugin in the environment or fix the import error in conftest.py
addopts settings have no effectpytest read a different configuration filecheck the configfile: line in the run header

Section sources

the section is written from these pages

Versions and what’s new

This reference covers pytest 9.2. The latest release is 9.2.0, of 27 October 2026. pytest removes deprecated features only in major versions: first a PytestRemovedInXWarning warning, which becomes an error when the major version is released, and the feature is removed in the following minor release.

BranchStatusLatest releasePython
9.2current9.2.0 — 27 October 20263.10 and newer
9.1superseded by 9.29.1.1 — 19 June 20263.10 and newer
9.0superseded by 9.19.0.3 — 7 April 20263.10 and newer
8.4last pytest 8 branch8.4.2 — 3 September 20253.9 and newer

pytest does not publish support periods for its branches. Fixes ship in the current branch: according to the changelog, the last 9.0 release came out before 9.1.0, and the last 8.4 release before 9.0.0. Each release supports all Python versions that are maintained at the release date; Python 3.15 has been officially supported since 9.1.

What changed in the 9 branch

  • Parametrisation: the ids, indirect and scope arguments of parametrize are accepted by keyword only (9.2). The parametrize_long_str_id_strategy option decides what to do with long strings in IDs (9.2), and strict_parametrization_ids forbids duplicate IDs across parameter sets (9.0).
  • Markers: with strict_markers, names in a -m expression are also checked against the markers list (9.2); pytest.importorskip by default catches only ModuleNotFoundError (9.1).
  • Configuration: pytest.toml and .pytest.toml files, the [tool.pytest] table in pyproject.toml with TOML types, and the strict mode strict = true (9.0). The xfail_strict option was renamed strict_xfail, and the old name still works (9.0). -c with a missing or unsupported file is a usage error (9.2).
  • Plugins and hooks: a plugin that is not found gives exit code 4, and a plugin that fails on import gives 3 (9.2). PYTEST_PLUGINS and pytest_plugins accept entry-point names such as xdist (9.2).
  • Common errors and diagnostics: --max-warnings and the max_warnings option end the run with code 6 if there are more warnings than the threshold (9.1).
  • Assertions: the Full diff: output now includes a legend for the + and - signs (9.2).
  • Fixtures: the built-in subtests fixture provides separate checks inside one test when the data sets are not known at collection time; the feature is experimental (9.0).
  • Installation and first run: support for Python 3.9 was dropped (9.0).

Deprecated and removed

  • yield_fixture is an old alias of @pytest.fixture and will be removed in pytest 10 or 11; write @pytest.fixture.
  • A class-scoped fixture written as a regular class method has been deprecated since 9.1, and a module-, package- or session-scoped one since 9.2. Declare such fixtures with @classmethod and put @pytest.fixture above it. They will be removed in pytest 10.
  • Generators and iterators in place of a list of values for parametrize have been deprecated since 9.1: pass a list or a tuple.
  • Calling request.getfixturevalue() during teardown for a fixture that has not been requested yet has been deprecated since 9.1 and will become an error in pytest 10.
  • The --pastebin flag has been deprecated since 9.1: it moved to a separate plugin, pytest-pastebin.
  • A non-string value for a string option in [tool.pytest.ini_options] gives a PytestRemovedIn10Warning warning (9.2); in pytest 10 it will be a TypeError.
  • Removed in 9.0: a marker on a fixture function is now a collection error; it never had any effect and has given a warning since 7.4. Requesting an async fixture from a synchronous test without a plugin that handles it is also an error.

Security updates

IdentifierWhat is affectedFixed in
CVE-2025-71176use of an insecure temporary directory9.0.3

How to upgrade

A new version is installed with the same command as the first installation. Before moving to pytest 10, turn its removal warnings into errors and fix whatever fails:

bashin the project environment
pip install -U pytest# what will break in pytest 10pytest -W error::pytest.PytestRemovedIn10Warning

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “pytest” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61