Skip to main content
Quick Reference

Pytest Cheatsheet

Pytest on one page — fixtures, raises, parametrize, and the traps around scope, approx, and collection.

10 sections 10 tables 14 code snippets

A test

Plain assert

def test_add():
    assert add(2, 2) == 4

One node

# pytest tests/test_cart.py::test_add

What gets collected

PieceRule
Filetest_*.py or *_test.py
FunctionThe name starts with test_
ClassThe name starts with Test. An __init__ means the class is not collected
assertA plain assert. pytest rewrites it in the test module and shows both sides
One testpytest tests/test_cart.py::test_add runs that node only
HelperAn assert in another module is not rewritten unless that module is registered

This page is pytest. Selenium and unittest-style suites are left out.

Assertions

Floats need a tolerance

assert 0.1 + 0.2 == pytest.approx(0.3)

What to write

CheckForm
Equalityassert actual == expected
Membershipassert item in items
Identityassert left is right
Noneassert result is None
Float0.1 + 0.2 == 0.3 is false. pytest.approx allows a small relative tolerance
Bare failureAn AssertionError with no value diff means the assert was not rewritten

Exceptions

Only the raising line inside

with pytest.raises(ValueError):
    int("qty")

Match the error

CaseResult
Matching typePasses. A subclass matches, the same way except does
Exact typeAfter the block, excinfo.type is ValueError
matchA regex. re.search runs on the message, so . matches any character
Nothing raisedThe test fails
Later linesCode after the raising call, still inside the with, never runs
excinfo.valueThe exception object. Assert on it after the with block

Fixtures

Setup, then teardown

@pytest.fixture
def cart():
    c = Cart()
    yield c
    c.clear()

Default scope

# scope="function" is the default

How a fixture is used

PieceMeaning
NameThe test asks for a fixture by using that name as a parameter
Defaultfunction. A new value for every test
yieldCode before yield is setup. Code after it is teardown
TeardownThe code after yield runs even when the test fails
Setup errorA failure before the test body is an error. An assert in the test is a failure
Missing nameA parameter with no matching fixture is an error at setup

Scopes

Wider cannot ask for narrower

# a session fixture cannot request tmp_path

How long the value lives

ScopeBuilt
functionOnce per test. The default
classOnce per test class
moduleOnce per test file
packageOnce per package directory
sessionOnce per pytest run
ScopeMismatchA wider fixture that requests a narrower one, such as tmp_path or monkeypatch

Sharing fixtures

Who can see it

PlaceWho sees it
conftest.pyTests in that directory and below
ParentA nested test can use a fixture from a parent conftest
ChildA test in the parent folder cannot see a fixture that exists only in a child folder
Same nameThe nearer definition wins
autouse=TrueRuns for every test in reach, even when no test names it
Importpytest loads conftest.py itself. A test does not import that file

Patch and paths

An env var for this test

monkeypatch.setenv("API_URL", "http://test")

A directory for this test

note = tmp_path / "note.txt"

Built-in fixtures

ToolUse
monkeypatch.setattrReplaces an attribute for this test, then puts the original back
setenvSets an environment variable for this test and removes that change afterward
tmp_pathA pathlib.Path directory unique to this test function
tmp_path_factorySession scoped. A session fixture asks for this, not for tmp_path
capsysCaptures stdout and stderr. readouterr() returns both and clears them
By handAn assignment you write yourself stays after the test. monkeypatch undoes its own changes

Parameters

One function, three cases

@pytest.mark.parametrize("n", [1, 3, 5])
def test_odd(n):
    assert n % 2 == 1

Rows

FormMeaning
parametrizeOne test item per value. The string names the parameters
Several names"a, b, total" takes a row of three values
Two decoratorsEvery combination of the two lists
idsLabels in the report, in place of the raw value
indirect=TrueRequired when the name is also a fixture, so each value is passed into that fixture
Unknown nameA parameter with no fixture and no parametrize value is an error

Skip and select

Do not run this one

@pytest.mark.skip(reason="needs a network")

An expected failure

# xfail(strict=True) fails the run if the test passes

Marks and the command line

MarkEffect
skipDoes not run. The reason shows in the report
skipifSkips when the condition is true
xfailRuns, and a failure is expected. The suite still passes
strict=TrueAn unexpected pass fails the run
-kSelects by a name expression, such as add and not slow
-mSelects by mark. An unknown mark warns, and --strict-markers makes that an error

Interview traps

Leave the with block

# only the raising line belongs inside the with

Collection

# class TestCart with __init__ is not collected

Traps worth memorising

TrapWhat happensPrefer
self.assertEqualA plain test function has no selfassert actual == expected
Float ==0.1 + 0.2 == 0.3 is falsepytest.approx
match copied from the messagere.search treats . and ( as regexA substring with no metacharacters, or an escaped pattern
Module-scoped listThe next test sees items the previous test appendedFunction scope, or build a new list inside the test
Session fixture asks for tmp_pathScopeMismatchtmp_path_factory
__init__ on a Test classThe class is not collectedPut setup in a fixture

How to use this page: name the test test_*, request fixtures by parameter name, and keep teardown after yield.