Readable code in practice

Readable Tests in Python: Naming, Arrange-Act-Assert and pytest Conventions

Readable code in practice · · Published 2026-11-16

A row of women at a long factory bench checking small metal parts under desk lamps, with a foreman in a cap leaning over the young woman in the foreground
Gauge inspectors at the Animal Trap Company of America, Lititz, Pennsylvania, November 1942. Photo: Marjory Collins, US Office of War Information (Library of Congress), public domain.

Style guides are usually read with application code in mind, but in many projects the test suite is as large as the code it checks, and it is read in the worst conditions: when something has just broken. PEP 8 applies to test files like any other Python module, yet it says nothing about what makes a test easy to understand. This guide collects the conventions that pytest itself documents, and the habits that make a failing test explain itself.

Where pytest looks for tests

pytest's "Good Integration Practices" page spells out the default discovery rules. Starting from the configured testpaths or the current directory, it recurses into directories, collects files named test_*.py or *_test.py, and inside them collects functions whose names start with test, as well as test-prefixed methods of classes whose names start with Test and that have no __init__ method. It also collects classic unittest.TestCase subclasses.

Two consequences matter for readability. First, the prefix is a contract, not decoration: a helper named test_data() in a test module will be collected and run as a test. Name helpers make_order() or build_payload() instead. Second, pick one of the two file patterns for a project and keep to it. The same page recommends keeping tests in a tests/ directory next to a src/ layout for new projects, so that the tests run against the installed package rather than whatever happens to be on the import path.

Names that state a behaviour

PEP 8's naming rules still apply: test functions are functions, so they use lowercase words separated by underscores, as our guide to Python naming conventions explains. Within that rule, the useful question is what the name says when it appears in a failure report. Compare:

def test_discount():
    ...

def test_discount_is_not_applied_to_orders_below_minimum():
    ...

The first tells the reader which function is involved; the second tells them which promise the code broke. Long names are acceptable here because nobody calls a test function by hand. A common pattern is unit, condition, expected result, but any phrasing works as long as the name describes behaviour rather than implementation. Grouping related tests in a Test-prefixed class, such as TestDiscount, shortens the individual names without losing context in the report.

Arrange, act, assert

The pytest documentation describes the anatomy of a test in four steps: arrange prepares everything the test needs, act is "the singular, state-changing action" that triggers the behaviour under test, assert checks the resulting state, and cleanup makes sure the test does not influence others. Making those steps visible, with a blank line between them, is the single most effective layout rule for tests:

def test_discount_is_not_applied_to_orders_below_minimum():
    order = Order(items=[Item(price=Decimal("9.99"))])
    rule = DiscountRule(percent=10, minimum=Decimal("20.00"))

    total = rule.apply(order)

    assert total == Decimal("9.99")

The "singular" in that definition is the important part. A test that acts, asserts, acts again and asserts again is really several tests sharing a name; when it fails halfway, the report hides whether the later checks would have passed. Split it, or move the variations into parameters as shown below.

Plain asserts, precise exceptions

pytest rewrites assert statements in the test modules it collects, so that a failing assert total == expected reports both values without any helper method. That makes the unittest-style self.assertEqual() family unnecessary in pytest tests, and the plain form is shorter and reads like the condition it checks. If an assertion needs explanation, a message after a comma is printed next to the introspection output.

Two refinements keep assertions honest:

For expected errors, use pytest.raises as a context manager around the one call that should fail, and add match, a regular expression searched in the string form of the exception:

def test_negative_quantity_is_rejected():
    with pytest.raises(ValueError, match="quantity must be positive"):
        Item(price=Decimal("5.00"), quantity=-1)

The documentation notes that pytest.raises also accepts subclasses of the expected exception, just as an except clause does. Without match, the test also passes when the call fails for an unrelated reason that raises the same type; and if the block holds several statements, an earlier line can raise the exception before the call under test runs. Hence one statement per block, and a message to match.

Fixtures and parametrize, without hiding the meaning

Fixtures move repeated set-up out of the test body. A fixture is a function decorated with @pytest.fixture; a test receives its value by naming it as an argument, and a fixture that uses yield runs its cleanup code after the test. Built-in fixtures such as tmp_path, a temporary directory unique to each test, cover common needs.

The readability risk is the opposite of duplication: when a test's inputs live three files away in a conftest.py, the reader can no longer see why the expected value is right. A workable rule is to put generic plumbing (database connections, clients, temporary files) in fixtures, and to keep the values that the assertion depends on visible in the test itself.

@pytest.mark.parametrize turns one test into a table of cases. Give the cases ids, so that a failure reads test_shipping_cost[overseas] rather than test_shipping_cost[address2-Decimal3]:

@pytest.mark.parametrize(
    ("country", "expected"),
    [
        pytest.param("FR", Decimal("4.90"), id="domestic"),
        pytest.param("DE", Decimal("9.90"), id="eu"),
        pytest.param("JP", Decimal("24.00"), id="overseas"),
    ],
)
def test_shipping_cost(country, expected):
    assert shipping_cost(country) == expected

Let a linter keep the habits

Most of these conventions can be checked automatically. Ruff implements the rules of the flake8-pytest-style plugin under the PT prefix; they are not enabled by default, so add "PT" to the selected rules in pyproject.toml, as described in our ruff guide. Among them:

RuleWhat it flags
PT009unittest-style assertions such as assertEqual instead of a plain assert
PT011pytest.raises() on a broad exception without match
PT012a pytest.raises() block containing more than one simple statement
PT017an assertion on an exception inside an except block, instead of pytest.raises()
PT018a composite assertion that should be broken into several
PT006, PT007the wrong type passed for parametrize names or values

Running them in a pre-commit hook keeps the suite consistent without review comments about style. The judgement calls remain for humans: whether a name describes behaviour, whether a fixture hides a value that matters. Those belong on a code review checklist.

Sources