pytest Cheat Sheet: Fixtures, Parametrize, Markers and CLI
Checked against pytest pytest 9.2.0 (released 27 Oct 2026), run locally on Python 3.12.8 on 28 November 2026. Each section links to the official docs it was checked against.
This sheet covers the parts of pytest you use every week: fixtures, parametrize, markers and the flags that choose which tests run. Everything not marked untested was run on pytest 9.2.0 with Python 3.12.8 in a scratch virtual environment. It assumes you already write plain assert statements in test_*.py files.
When to use what
Reach for a fixture whenever two tests need the same setup. Give it the narrowest scope that is fast enough: the default function scope rebuilds it for every test and keeps tests independent, while module or session is for expensive things such as a database connection that tests only read from. Put shared fixtures in conftest.py instead of importing them, and use yield so the cleanup sits right under the setup.
Use parametrize when the same assertion runs over a table of inputs, and a parametrized fixture when the variation is in the setup (two database backends, say). Prefer the built-in fixtures over hand-rolled ones: tmp_path gives each test its own folder and monkeypatch undoes every change after the test, which beats remembering to reset environment variables yourself. For test inputs, the test data generator produces realistic rows to paste into a parametrize table, and the test case generator helps list edge cases before you write them. Our testing strategies guide covers where unit tests stop and integration tests begin.
Valid scopes are function (default), class, module, package and session. Teardown runs in reverse order of setup.
@pytest.fixture
def user(): return {"name": "ada"}Define a fixture; any test that names user as an argument receives the return value
@pytest.fixture(scope="module")Build the fixture once per test file instead of once per test
yield conn
conn.close()Hand the value to the test, then run the code after yield as teardown
@pytest.fixture(autouse=True)Apply the fixture to every test in its scope without naming it
conftest.pyPut fixtures here to share them with every test file in the folder and below, with no import
@pytest.fixture(params=["sqlite", "postgres"])Run each dependent test once per value, read inside the fixture as request.param
@pytest.mark.usefixtures("cleandir")Apply a fixture to a test or class that doesn't need its return value
pytest --fixturesList available fixtures with their scope and where they are defined
@pytest.mark.parametrize("raw,expected", [("Hello World", "hello-world"), ("x", "x")])Run one test function once per tuple, each with its own test ID
pytest.param("a_b", "a-b", marks=pytest.mark.xfail)Mark a single parameter set, for example as an expected failure
pytest.param(1, 2, id="small")Give one parameter set a readable ID in the output
pytest "test_demo.py::test_slugify[Hello World-hello-world]"Run one parametrized case by its node ID
Register your own markers under markers = in pytest.ini (or [tool.pytest] in pyproject.toml); with --strict-markers an unregistered one is an error.
@pytest.mark.skip(reason="not ready")Always skip the test and show the reason with -rA or -rs
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX only")Skip when the condition is true
@pytest.mark.xfail(reason="known bug")Expect the test to fail; it is reported as xfailed rather than failed
@pytest.mark.slowTag a custom marker so you can include or exclude it with -m
with pytest.raises(ValueError, match="invalid literal"):Pass only if the block raises ValueError whose message matches the regex (re.search)
pytest --strict-markersFail on unknown marker names in code, and since 9.2 in -m expressions
def test_x(tmp_path): p = tmp_path / "out.txt"Get a fresh pathlib.Path directory unique to this test
monkeypatch.setenv("APP_MODE", "test")Set an environment variable for one test; it is restored afterwards
monkeypatch.setattr(module, "now", lambda: fixed)Replace an attribute or function for the test's duration
monkeypatch.delenv("API_KEY", raising=False)Remove a variable without failing if it isn't set
out, err = capsys.readouterr()Read what the code printed to stdout and stderr so far
pytest -qQuiet output: dots and a one-line summary
pytest -k slugifyRun tests whose names match the keyword expression; supports and, or, not
pytest -m "not slow"Run everything except tests marked slow
pytest tests/test_mod.py::TestClass::test_methodRun a single test by node ID
pytest -xStop at the first failure or error
pytest --maxfail=3Stop after three failures
pytest --lfRe-run only the tests that failed last time
pytest --ffRun last run's failures first, then the rest
pytest -sTurn off output capture so print() shows up live
pytest -rAPrint a short summary line for every outcome, including skip reasons
pytest --durations=10List the ten slowest setup, call and teardown phases
pytest --pdbDrop into the Python debugger at the point of failure
python -m pytestSame as pytest, but also puts the current directory on sys.path
Worked example: Watch a module-scoped fixture, then re-run only the failure
A conftest.py with a module-scoped fixture that prints on setup and teardown, and a test file with one deliberately broken test:
# conftest.py
@pytest.fixture(scope="module")
def db():
print("\nopen db")
yield {"users": []}
print("\nclose db")
$ pytest -q
FAILED test_demo.py::test_fail - AssertionError: assert 'a-b' == 'a_b'
1 failed, 8 passed, 1 skipped, 1 xfailed in 0.03s
$ pytest --lf -q
FAILED test_demo.py::test_fail - AssertionError: assert 'a-b' == 'a_b'
1 failed in 0.02s
$ pytest -s -q -k db
open db
.
close db
The first run collected 11 items: three parametrized slugify cases plus the others, one skipped, one expected failure and one real failure. The assertion message shows both sides of the comparison because pytest rewrites assert statements. --lf read the cache in .pytest_cache and ran only the one failure, which is what you want while fixing it. The last run used -s so the fixture's prints appear in order: setup before the test, teardown after the yield.
Common mistakes
Making a fixture
sessionscoped and then letting tests write to the object it returns.Keep mutable fixtures at function scope, or return a fresh copy from a wider-scoped factory fixture.
Importing fixtures from a helpers module into each test file.
Move them into
conftest.py; pytest finds them by name and imports cause shadowing surprises.Using
pytest.raises(Exception)with nomatch, so any unrelated error makes the test pass.Catch the narrowest exception type and add
match=with a regex for the message.Typing
@pytest.mark.slwoand getting only a warning while the test runs anyway.Register markers in config and run with
--strict-markers(or setstrict_markers = true) so typos fail collection.Setting
os.environdirectly in a test and leaking the value into later tests.Use
monkeypatch.setenv, which restores the original value when the test ends.
Related cheat sheets
Sources
- https://docs.pytest.org/en/stable/how-to/fixtures.html
- https://docs.pytest.org/en/stable/how-to/usage.html
- https://docs.pytest.org/en/stable/reference/reference.html
- https://docs.pytest.org/en/stable/changelog.html
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.