Skip to content

14. Testing with pytest — Cheat sheet

The essentials of module 14 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
run all tests pytest (or pytest -q) pytest -q
run one file / one test a path / a node ID pytest "test_dates.py::test_parse_date[iso]"
run tests whose name matches -k EXPR pytest -k "price and not slow"
run tests with a marker -m EXPR pytest -m "not slow"
stop at the first failure -x (or --maxfail=N) pytest -x
rerun only the last failures --lf (--ff: failures first) pytest --lf
see one line per test -v pytest -v --no-header
short tracebacks --tb=short (line, no, long) pytest --tb=short
see print() output of passing tests -s pytest -s -k report
list tests without running them --collect-only -q pytest --collect-only -q
see fixture setup and teardown --setup-show pytest --setup-show
find the slowest tests --durations=N pytest --durations=5
open the debugger on a failure --pdb pytest -x --pdb
compare floats pytest.approx assert total == pytest.approx(304.09)
check that code raises pytest.raises(..., match=...) with pytest.raises(ValueError, match="range"):
share setup between tests a fixture @pytest.fixture def raw_row(): ...
share fixtures between files conftest.py tests/conftest.py
run one test over many inputs @pytest.mark.parametrize @pytest.mark.parametrize("raw", ["north", " East "])
a fresh folder for one test tmp_path out = tmp_path / "clean.csv"
capture printed output capsys capsys.readouterr().out
change env vars or attributes monkeypatch monkeypatch.setenv("SALES_DATA_DIR", "/srv")
compare DataFrames pd.testing.assert_frame_equal assert_frame_equal(result, expected)
compare float arrays np.testing.assert_allclose assert_allclose(z, by_hand, rtol=1e-6)
skip a test @pytest.mark.skip / skipif @pytest.mark.skipif(sys.platform == "win32", reason="...")
mark a known failure @pytest.mark.xfail(strict=True) @pytest.mark.xfail(reason="bug 42", strict=True)
measure coverage pytest-cov + coverage report pytest --cov=cleaning --cov-report=; coverage report -m
fail below a coverage threshold --fail-under coverage report --fail-under=90
Output Meaning
. passed
F failed: an assert was false or the test raised
E error outside the test body, for example in a fixture or at import
s skipped
x / X expected failure that failed / unexpectedly passed
N passed, M deselected -k or -m left out M tests
Exit code Meaning
0 all collected tests passed
1 some tests failed
2 interrupted (Ctrl+C) or a collection error
3 internal error
4 usage error (bad option)
5 no tests collected
Terminal
pytest -q # quiet: dots and a summary line
pytest -v --no-header tests/ # one line per test, no platform header
pytest -q --tb=short -x # short tracebacks, stop at the first failure
pytest --lf # only the tests that failed last time
python -m pytest -q # same, and adds the current folder to sys.path
pytest collects Default rule Config key
files test_*.py, *_test.py python_files
functions names starting with test python_functions
classes names starting with Test, no __init__ python_classes
methods names starting with test, inside a Test class python_functions
folders from the arguments, or testpaths when none are given testpaths

A file named on the command line is read even if its name does not match, but its functions must still match.

test_prices.py
import pytest
from cleaning import parse_price
def test_thousands_separator(): # name states the rule
raw = "$1,299.00" # arrange
price = parse_price(raw) # act
assert price == 1299.0 # assert
def test_missing_token():
assert parse_price("N/A") is None # `is None`, not `== None`
def test_garbage_is_rejected():
with pytest.raises(ValueError, match="could not convert"):
parse_price("$12.x0") # only the failing call inside
class TestDiscounts: # optional grouping; no __init__
def test_missing(self):
...
Assert form Checks
assert x == y equality; pytest shows both values and a diff
assert x is None identity with None
assert item in container membership
assert not flag falsy
assert isinstance(x, int) type
assert set(a) <= set(b) subset
assert x == y, "message" adds your message to the report
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
print({"mean": 177.609} == pytest.approx({"mean": 177.61}, abs=0.005))
print(1e-15 == pytest.approx(0.0), 1e-9 == pytest.approx(0.0)) # abs=1e-12 near 0
print(1213 == pytest.approx(1200, rel=0.01)) # 1% tolerance
Output
True
True
True
True False
False
Argument Default Meaning
rel 1e-6 allowed difference as a fraction of the expected value
abs 1e-12 allowed absolute difference; set it when comparing with 0
nan_ok False True treats nan == nan as equal

Rule: |actual − expected| <= max(rel × |expected|, abs).

import pytest
with pytest.raises(ValueError, match=r"out of range: '1\.5'") as excinfo:
raise ValueError("discount out of range: '1.5'")
print(type(excinfo.value).__name__, "|", excinfo.value)
with pytest.raises((KeyError, IndexError)): # a tuple of types
first = [][0]
print("IndexError caught")
Output
ValueError | discount out of range: '1.5'
IndexError caught
Pattern Use
pytest.raises(E, match=r"...") re.search on str(exc); escape ., (, [ or use re.escape()
excinfo.value the exception object
excinfo.type the exception class
pytest.raises(SystemExit) as e then e.value.code test a CLI’s exit code
pytest.warns(UserWarning, match=...) test that code warns
conftest.py
import sqlite3
from collections.abc import Iterator
import pytest
@pytest.fixture
def raw_row(): # function scope: fresh per test
return {"region": " North ", "unit_price": "$129.95"}
@pytest.fixture(scope="module") # once per test file
def customers():
import pandas as pd
return pd.read_csv("data/customers.csv")
@pytest.fixture
def sales_db() -> Iterator[sqlite3.Connection]: # a yield fixture is an iterator
conn = sqlite3.connect(":memory:") # setup
yield conn # the test runs here
conn.close() # teardown, even after a failure
@pytest.fixture
def make_row(raw_row): # a fixture using a fixture
def _make_row(**changes): # factory: returns a function
return raw_row | changes
return _make_row
Scope Created once per --setup-show letter
function (default) test F
class test class C
module test file M
package package of tests P
session pytest run S
Feature How
request a fixture name it as a test parameter: def test_x(raw_row):
share fixtures put them in conftest.py; applies to its folder and below
teardown yield instead of return; code after yield cleans up
run for every test without naming it @pytest.fixture(autouse=True)
parametrize a fixture @pytest.fixture(params=[...]), read request.param
see where fixtures come from pytest --fixtures
Fixture Gives Typical use
tmp_path a new empty Path per test write and read files
tmp_path_factory session-scoped; .mktemp("name") a folder shared by a session fixture
capsys .readouterr() → .out, .err test print() output and stderr
capfd like capsys, at the file-descriptor level output of subprocesses and C libraries
caplog captured log records, .text, .records test logging messages
monkeypatch setenv, delenv, setattr, chdir, syspath_prepend change settings for one test, undone afterwards
request info about the running test; request.param parametrized fixtures
recwarn recorded warnings inspect warnings in detail
test_output.py
def test_print_summary(capsys):
print_summary({"read": 1200})
assert capsys.readouterr().out == "read 1,200\n"
def test_limit(monkeypatch):
monkeypatch.setattr(cleaning, "MAX_QUANTITY", 10) # patch the module attribute
monkeypatch.setenv("SALES_DATA_DIR", "/srv/sales") # restored after the test
assert not cleaning.is_valid_quantity(50)
test_dates.py
@pytest.mark.parametrize(
("text", "expected"), # names: tuple or "a,b"
[
pytest.param("2023-01-07", JAN_7, id="iso"), # readable ID
pytest.param("07/01/2023", JAN_7, id="day-first"),
pytest.param("1/7/2023", JAN_7, id="us", marks=pytest.mark.xfail),
],
)
def test_parse_date(text, expected):
assert parse_date(text) == expected
@pytest.mark.parametrize("token", ["", "N/A", "-"], ids=["empty", "n/a", "dash"])
@pytest.mark.parametrize("field", ["region", "channel"]) # stacked: 2 × 3 = 6 tests
def test_missing(field, token): ...
Value in the list Automatic ID part
str, int, float, bool, None the value itself: north, 79.99, None
any other object (date, DataFrame) argument name + index: expected0
several arguments joined with -: $79.99-79.99
ids=[...] or ids=func your names, or func(value)
Marker Effect
@pytest.mark.skip(reason="...") never run
@pytest.mark.skipif(cond, reason="...") skip when cond is true
@pytest.mark.xfail(reason="...", strict=True) expected to fail; with strict, a pass is a failure
@pytest.mark.parametrize(...) many cases
@pytest.mark.usefixtures("name") use a fixture without a parameter
@pytest.mark.slow (your own) a label for -m "not slow"; register it in the config
pytest.importorskip("polars") skip the module when a package is missing
Check Use
DataFrames equal pd.testing.assert_frame_equal(result, expected)
…ignoring dtype / column order check_dtype=False / check_like=True
…exact floats check_exact=True (default compares with rtol=1e-5)
Series equal pd.testing.assert_series_equal(result, expected)
Index equal pd.testing.assert_index_equal(result, expected)
arrays exactly equal np.testing.assert_array_equal(a, b)
float arrays close np.testing.assert_allclose(a, b, rtol=1e-7, atol=0)
a model is useful score above a baseline, AUC above a threshold with a margin
reproducibility same random_state → assert_array_equal(m1.coef_, m2.coef_)
no leakage scaled test data equals a hand computation from train statistics
import numpy as np
import pandas as pd
result = pd.DataFrame({"region": ["West", "North"], "revenue": [2598.0, 224.1 + 79.99]})
expected = pd.DataFrame({"region": ["West", "North"], "revenue": [2598.0, 304.09]})
pd.testing.assert_frame_equal(result, expected) # float tolerance by default
np.testing.assert_allclose(result["revenue"], [2598.0, 304.09])
print("frames and arrays match")
Output
frames and arrays match
pyproject.toml
[dependency-groups]
dev = ["pytest>=9.2", "pytest-cov>=7.1"]
[tool.pytest] # pytest 9: native TOML types
testpaths = ["tests"] # folders for a bare `pytest`
pythonpath = ["src"] # extra sys.path entries (src layout without install)
strict = true # strict markers, config, xfail and parametrize IDs
markers = ["slow: reads the full raw data file"]
addopts = ["-q", "--tb=short"] # options added to every run
filterwarnings = ["error"] # turn warnings into failures
[tool.coverage.run]
branch = true # measure branches, not only lines
source = ["salesclean"]
[tool.coverage.report]
show_missing = true # the Missing column
fail_under = 90 # `coverage report` fails below 90%
exclude_also = ['if __name__ == "__main__":']

Older projects use [tool.pytest.ini_options] (string values) or pytest.ini. A file must not have both [tool.pytest] and [tool.pytest.ini_options].

src layout with tests
project/
├── pyproject.toml
├── src/
│ └── salesclean/
│ ├── __init__.py
│ └── prices.py
└── tests/
├── conftest.py # fixtures for all tests below
├── test_prices.py # mirrors src/salesclean/prices.py
└── test_real_data.py # @pytest.mark.slow integration test
Rule Why
tests/ next to src/, not inside the package tests do not ship to users
unique test file names (or __init__.py in test folders) avoids “import file mismatch”
tests import the package by name they test what users import
install editable (uv sync) or set pythonpath so import salesclean works in tests
build data paths from Path(__file__) tests work from any working folder
Terminal
pytest --cov=salesclean --cov-branch --cov-report=term-missing # table after the run
pytest -q --cov=salesclean --cov-report= # measure only
coverage report -m # table from .coverage
coverage report --fail-under=90 # exit 2 below 90%
coverage html # htmlcov/index.html
Column Meaning
Stmts statements in the file
Miss statements no test ran
Branch possible branch directions (with --cov-branch)
BrPart branches that went only one way
Cover percentage covered
Missing line numbers (and 7->9 partial branches) that no test reached

# pragma: no cover at the end of a line excludes that line or block.

Situation Do
new function red-green-refactor: failing test, least code, clean up
bug report reproduce it in a test (red), fix (green), keep the test
unclear legacy code characterization tests first, then change it
slow suite --durations=10, wider fixture scopes, mark slow tests
flaky test fix the seed, the order dependence or the shared state; never just rerun
  • A test that never failed may test nothing. Break the code once and watch the test go red.
  • check_price() or prices_check.py is never collected. pytest reports no tests ran with exit code 5.
  • assert df1 == df2 raises ValueError (ambiguous truth value). Use pd.testing.assert_frame_equal.
  • pytest.approx(0.0) with the default relative tolerance accepts only differences up to 1e-12. Pass abs= for values near 0.
  • pytest.raises(ValueError) without match= passes for any ValueError, including one from the wrong line.
  • Only the call that should raise belongs inside the with pytest.raises block. Lines after the raising line never run.
  • A module- or session-scoped fixture is shared. A test that changes it breaks later tests, but only when they run together.
  • from cleaning import MAX_QUANTITY copies the value; monkeypatch.setattr(cleaning, "MAX_QUANTITY", ...) does not change your copy. Patch the attribute where the code looks it up.
  • capsys.readouterr() empties the buffers. Call it once and keep the result.
  • tmp_path is function-scoped; a session fixture needs tmp_path_factory.mktemp().
  • A node ID with brackets needs quotes in the shell: pytest "test_dates.py::test_parse_date[iso]".
  • An unregistered marker such as @pytest.mark.slwo only warns, unless strict = true turns it into an error.
  • pytest --cov prints a header with your platform and Python version; compare the table, not the header.
  • 100% coverage does not mean correct code. It means every line ran once.