Skip to content

pytest

pytest finds functions named test_*, runs them and reports every failed assert with the values involved. This page is a reference for writing and running tests in any Python project: libraries, web back ends, scripts and data pipelines.

I want to… Use… Example
run every test pytest pytest -q
run one file, class or test a node ID pytest tests/test_prices.py::test_parse
run tests whose name matches -k EXPR pytest -k "parse and not slow"
run tests with a marker -m EXPR pytest -m "not slow"
stop at the first failure -x pytest -x
rerun only the failures --lf (--ff: failures first) pytest --lf
see one line per test -v pytest -v
see print() output -s pytest -s -k report
list tests without running them --collect-only -q pytest --co -q
find slow tests --durations=N pytest --durations=5
debug a failure --pdb pytest -x --pdb
check a value plain assert assert total == 304.09
compare floats pytest.approx assert mean == pytest.approx(0.3)
check that code raises pytest.raises(E, match=...) with pytest.raises(ValueError, match="price"):
check that code warns pytest.warns(W, match=...) with pytest.warns(DeprecationWarning):
share setup between tests a fixture @pytest.fixture def orders(): ...
clean up after a test a yield fixture conn = connect(); yield conn; conn.close()
share fixtures across files conftest.py tests/conftest.py
build expensive data once a wider scope @pytest.fixture(scope="session")
a temporary folder tmp_path path = tmp_path / "out.csv"
set an environment variable monkeypatch.setenv monkeypatch.setenv("API_KEY", "test")
replace a function or attribute monkeypatch.setattr monkeypatch.setattr(app, "fetch", fake)
capture print() output capsys capsys.readouterr().out
capture log records caplog assert "dropped" in caplog.text
run one test on many inputs @pytest.mark.parametrize @pytest.mark.parametrize("raw", ["$1", "1"])
name parametrized cases pytest.param(..., id=...) or ids= pytest.param("", None, id="empty")
skip a test skip, skipif, importorskip @pytest.mark.skipif(sys.platform == "win32", reason="posix")
mark a known bug xfail(strict=True) @pytest.mark.xfail(reason="bug 42", strict=True)
a fake object with recorded calls unittest.mock.Mock fake.assert_called_once_with("P001")
measure coverage pytest-cov pytest --cov=mypkg --cov-report=term-missing
fail CI below a coverage level --cov-fail-under pytest --cov=mypkg --cov-fail-under=90
compare DataFrames pd.testing.assert_frame_equal assert_frame_equal(got, expected)
run the examples in docstrings --doctest-modules pytest --doctest-modules src/
test async def functions a plugin marker: pytest-asyncio or anyio @pytest.mark.asyncio / @pytest.mark.anyio
test a rule on many generated inputs property-based testing (plugin: hypothesis) @given(st.floats(min_value=0))
src layout with tests
project/
├── pyproject.toml # [tool.pytest] settings
├── src/
│ └── shop/
│ ├── __init__.py
│ └── prices.py
└── tests/
├── conftest.py # fixtures for every test below this folder
├── test_prices.py # one test file per module
└── integration/
├── conftest.py # extra fixtures for this subfolder only
└── test_api.py
pytest collects Rule Config key
files test_*.py or *_test.py python_files
functions names starting with test python_functions
classes Test* classes without __init__ python_classes
methods test* methods inside a Test* class python_functions
folders the arguments, or testpaths, recursively testpaths
Rule Why
tests import your package by name (from shop.prices import parse) they test what users import
install the project editable (uv sync) or set pythonpath = ["src"] so the import works
unique test file names, or __init__.py in test folders avoids “import file mismatch” errors
one behavior per test, named after the rule test_parse_rejects_negative_price
arrange, act, assert set up, call once, check
build data paths from Path(__file__).parent tests pass from any working folder
Terminal
cat > test_demo.py <<'EOF'
import pytest
def parse_price(text: str) -> float | None:
cleaned = text.strip().removeprefix("$").replace(",", "")
if cleaned in {"", "N/A", "-"}:
return None
return float(cleaned)
@pytest.fixture
def raw_prices() -> list[str]:
return ["$79.99", "$1,299.00", "N/A"]
def test_parses_a_list(raw_prices):
assert [parse_price(p) for p in raw_prices] == [79.99, 1299.0, None]
@pytest.mark.parametrize(
("text", "expected"),
[("$79.99", 79.99), (" 14.99 ", 14.99), pytest.param("", None, id="empty")],
)
def test_parse_price(text, expected):
assert parse_price(text) == expected
def test_garbage_raises():
with pytest.raises(ValueError, match="could not convert"):
parse_price("$12.x0")
def test_writes_file(tmp_path):
out = tmp_path / "prices.txt"
out.write_text("79.99\n", encoding="utf-8")
assert out.read_text(encoding="utf-8").strip() == "79.99"
EOF
pytest -v --no-header test_demo.py
Output
======================================= test session starts ========================================
collecting ... collected 6 items
test_demo.py::test_parses_a_list PASSED [ 16%]
test_demo.py::test_parse_price[$79.99-79.99] PASSED [ 33%]
test_demo.py::test_parse_price[ 14.99 -14.99] PASSED [ 50%]
test_demo.py::test_parse_price[empty] PASSED [ 66%]
test_demo.py::test_garbage_raises PASSED [ 83%]
test_demo.py::test_writes_file PASSED [100%]
======================================== 6 passed in 0.01s =========================================

The IDs in brackets come from the parameter values: $79.99-79.99 joins the two arguments with -, and empty is the id of the pytest.param.

Check Write Note
equality assert got == expected pytest shows both values and a diff
None assert value is None is, not ==
truthiness assert result, assert not errors
membership assert "P001" in ids
subset assert {"a", "b"} <= set(keys)
type assert isinstance(x, float)
float assert x == pytest.approx(0.3) never == on computed floats
an exception with pytest.raises(KeyError): only the failing call inside
a message assert ok, f"bad row: {row}" the message shows on failure
sorted output assert sorted(got) == sorted(expected) when order does not matter
a DataFrame pd.testing.assert_frame_equal(got, expected) assert df1 == df2 raises ValueError
a NumPy array np.testing.assert_allclose(got, expected)
import warnings
import pytest
print(0.1 + 0.2 == pytest.approx(0.3)) # default rel=1e-6
print([0.1 + 0.2, 1.0] == pytest.approx([0.3, 1.0])) # lists, tuples, dicts
print(1e-9 == pytest.approx(0.0), 1e-9 == pytest.approx(0.0, abs=1e-6))
print(1213 == pytest.approx(1200, rel=0.02)) # 2% tolerance
with pytest.raises(ValueError, match=r"out of range: 1\.5") as excinfo:
raise ValueError("discount out of range: 1.5")
print(excinfo.type.__name__, excinfo.value.args)
with pytest.warns(DeprecationWarning, match="old_api"):
warnings.warn("old_api() is deprecated", DeprecationWarning, stacklevel=1)
print("warning seen")
Output
True
True
False True
True
ValueError ('discount out of range: 1.5',)
warning seen
Tool Argument Meaning
pytest.approx(x) rel=1e-6 relative tolerance
abs=1e-12 absolute tolerance; set it near 0
nan_ok=True treat nan == nan as equal
pytest.raises(E) match=r"..." re.search on str(exception)
a tuple of types any of them
as excinfo .value, .type, .traceback
pytest.raises(SystemExit) excinfo.value.code test a CLI’s exit code
pytest.warns(W, match=...) as record the list of warnings
pytest.fail("msg"), pytest.skip("msg") inside a test fail or skip from code
tests/conftest.py
import sqlite3
from collections.abc import Iterator
import pytest
@pytest.fixture
def order() -> dict[str, object]: # function scope: a fresh dict per test
return {"order_id": "O000001", "quantity": 1, "unit_price": 69.99}
@pytest.fixture(scope="session") # built once per pytest run
def products() -> list[str]:
return ["P001", "P002", "P003"]
@pytest.fixture
def db() -> Iterator[sqlite3.Connection]: # setup, yield, teardown
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE orders (id TEXT, qty INTEGER)")
yield conn # the test runs here
conn.close() # runs even when the test fails
@pytest.fixture
def make_order(order): # a factory fixture uses another fixture
def _make(**changes):
return order | changes
return _make
@pytest.fixture(params=["sqlite", "duckdb"]) # every test using it runs twice
def backend(request) -> str:
return request.param
@pytest.fixture(autouse=True) # applies to every test without naming it
def fixed_env(monkeypatch):
monkeypatch.setenv("APP_ENV", "test")
Scope Created once per Use for
function (default) test anything a test may change
class test class shared setup for a group
module test file a loaded dataset read by many tests
package test folder (package)
session whole run a database server, a large read-only fixture
Fact Detail
request a fixture name it as a test parameter: def test_total(order):
conftest.py fixtures there are visible in its folder and below; no import needed
teardown code after yield runs after the test, pass or fail
a wider scope cannot use a narrower one a session fixture cannot use tmp_path; use tmp_path_factory
list fixtures and where they live pytest --fixtures
watch setup and teardown pytest --setup-show
Fixture Gives Example
tmp_path a new empty pathlib.Path per test (tmp_path / "a.csv").write_text("x")
tmp_path_factory session-wide temp folders tmp_path_factory.mktemp("data")
monkeypatch temporary changes, undone after the test see the table below
capsys captured sys.stdout and sys.stderr out, err = capsys.readouterr()
capfd capture at the file-descriptor level output of subprocesses and C code
caplog captured log records caplog.set_level("INFO"); caplog.records
recwarn recorded warnings len(recwarn)
request the running test; request.param parametrized fixtures
monkeypatch. Does
setenv("K", "v"), delenv("K", raising=False) change environment variables
setattr(module, "name", value) replace a function, constant or method
setattr("pkg.module.name", value) the same, by dotted path
setitem(d, "k", v), delitem(d, "k") change a dict, such as a settings dict
chdir(tmp_path) change the working folder
syspath_prepend(path) add an import path
tests/test_report.py
import logging
import shop.report as report
def test_summary_prints(capsys):
report.print_summary({"rows": 1200})
assert capsys.readouterr().out == "rows: 1,200\n"
def test_uses_fake_fetch(monkeypatch):
monkeypatch.setattr(report, "fetch", lambda url: {"status": "ok"}) # no network
assert report.health() == "ok"
def test_logs_drops(caplog):
with caplog.at_level(logging.WARNING):
report.clean([{"qty": -1}])
assert "dropped 1 row" in caplog.text
tests/test_dates.py
from datetime import date
import pytest
from shop.dates import parse_date
JAN_7 = date(2023, 1, 7)
@pytest.mark.parametrize(
("text", "expected"), # tuple of names, or "text,expected"
[
("2023-01-07", JAN_7),
pytest.param("07/01/2023", JAN_7, id="day-first"),
pytest.param("1/7/2023", JAN_7, id="us", marks=pytest.mark.xfail(strict=True)),
],
)
def test_parse_date(text, expected):
assert parse_date(text) == expected
@pytest.mark.parametrize("field", ["region", "channel"])
@pytest.mark.parametrize("token", ["", "N/A"], ids=["empty", "na"])
def test_missing(field, token): ... # stacked: 2 x 2 = 4 tests
Value Automatic ID part
str, int, float, bool, None the value: north, 79.99, None
other objects (date, dict) argument name and index: expected0
several arguments joined with -: $79.99-79.99
ids=[...], ids=func, pytest.param(id=...) your names

Select one case from the terminal with its ID, in quotes: pytest "tests/test_dates.py::test_parse_date[day-first]".

Mark Effect
@pytest.mark.skip(reason="...") never run
@pytest.mark.skipif(cond, reason="...") skip when cond is true
pytest.importorskip("polars") skip the module when a package is missing
@pytest.mark.xfail(reason="...", strict=True) expected to fail; a pass becomes a failure
@pytest.mark.parametrize(...) many cases
@pytest.mark.usefixtures("db") use a fixture without a parameter
@pytest.mark.filterwarnings("error") turn warnings into errors for one test
@pytest.mark.slow (your own) select with -m slow or -m "not slow"; register it in the config
pytestmark = pytest.mark.slow at module level: marks every test in the file
Flag Does
-q / -v / -vv quieter / one line per test / full diffs
-x, --maxfail=N stop after the first or the N-th failure
-k "expr" select by name: and, or, not, substrings
-m "expr" select by marker
--lf, --ff last failed only / failed first
--sw stepwise: stop at a failure, start there next time
-s no output capture: see print()
--tb=short, line, no, long traceback style
-l show local variables in tracebacks
-r fEsxX a short summary of failures, errors, skips, xfails
--co -q list the collected tests
--durations=N the N slowest setup, call and teardown phases
--setup-show show fixture setup and teardown
--pdb, --trace debugger on failure / at the start of each test
-p no:cacheprovider do not write .pytest_cache
-W error turn warnings into errors
-n auto run in parallel (plugin: pytest-xdist)
--cov=pkg, --cov-report=term-missing, --cov-branch coverage (plugin: pytest-cov)
--cov-fail-under=90 fail below 90% coverage
Exit code Meaning
0 all collected tests passed
1 some tests failed
2 interrupted, or an error during collection
3 internal error
4 usage error (a bad option)
5 no tests collected
pyproject.toml
[dependency-groups]
dev = ["pytest>=9.2", "pytest-cov>=7.1"]
[tool.pytest] # pytest 9: native TOML types
testpaths = ["tests"]
pythonpath = ["src"] # import the package without installing it
addopts = ["-q", "--tb=short"]
strict = true # unknown markers and config keys become errors
markers = ["slow: reads the full data files"]
filterwarnings = ["error"] # every warning fails a test
[tool.coverage.run]
branch = true
source = ["shop"]
[tool.coverage.report]
show_missing = true
fail_under = 90
exclude_also = ['if __name__ == "__main__":', "if TYPE_CHECKING:"]

Older projects use [tool.pytest.ini_options], pytest.ini or setup.cfg. Use one place only.

import os
from unittest.mock import Mock, patch
fetch = Mock(return_value={"status": 200, "items": ["P001"]})
print(fetch("https://api.example.com/products")["items"])
fetch.assert_called_once_with("https://api.example.com/products")
print(fetch.call_count)
flaky = Mock(side_effect=[TimeoutError("slow"), {"status": 200}]) # one value per call
try:
flaky()
except TimeoutError as err:
print("first call:", err, "| second call:", flaky()["status"])
with patch("os.cpu_count", return_value=2): # patch where the name is looked up
print(os.cpu_count()) # restored after the block
Output
['P001']
1
first call: slow | second call: 200
2
Tool Use
Mock(return_value=v) a fake function that returns v
Mock(side_effect=Exc) / side_effect=[...] raise, or return a different value per call
m.assert_called_once_with(...), m.call_args, m.call_count check the calls
patch("pkg.mod.name") replace a name for a with block or a test
patch.object(obj, "attr") replace an attribute of one object
Mock(spec=RealClass) / create_autospec(func) reject attributes or signatures the real object lacks
monkeypatch.setattr the pytest way; simpler for plain replacements
Terminal
pytest --cov=shop --cov-branch --cov-report=term-missing # table after the tests
pytest --cov=shop --cov-report=html # htmlcov/index.html
pytest --cov=shop --cov-fail-under=90 # non-zero exit below 90%
coverage report -m # table from the .coverage file
Column Meaning
Stmts / Miss statements / statements that no test ran
Branch / BrPart branch directions / branches taken only one way
Cover percentage
Missing line numbers, and partial branches such as 7->9

Exclude a line with # pragma: no cover. High coverage means every line ran once, not that the results are right.

Trap Symptom Fix
a file or function without the test prefix no tests ran, exit code 5 name it test_*.py and def test_*
two test files with the same name in different folders import file mismatch unique names, or __init__.py in test folders
ModuleNotFoundError for your package tests cannot import src/ code editable install, pythonpath = ["src"] or python -m pytest
assert df1 == df2 ValueError: The truth value of a DataFrame is ambiguous pd.testing.assert_frame_equal
== on computed floats random-looking failures pytest.approx
pytest.approx(0.0) tiny differences fail pass abs= near zero
pytest.raises(ValueError) without match passes for the wrong ValueError add match=
several lines inside pytest.raises lines after the raising line never run only the failing call inside
a shared mutable fixture in a wide scope tests pass alone, fail together function scope, or return copies
patching module.name after from module import name the code still uses the original patch where the name is looked up
capsys.readouterr() called twice the second call is empty call it once and keep the result
a typo in a marker name a warning, the test runs anyway strict = true in the config
a test that never failed it may test nothing break the code once and watch it fail
flaky tests pass and fail at random fix seeds, time, order and shared state; do not just rerun
node IDs with brackets in the shell no matches found (zsh) quote the node ID