DevPath
Mid lesson · 12 min

Build tests that explain behavior

Use focused fixtures and parametrized cases without obscuring the scenario.

Keep setup minimal

A fixture should create only the state a test needs and clean it up reliably. Deep chains of automatic fixtures make it hard to see why a test passes. Give shared fixtures names that describe a real dependency, such as an empty repository or authenticated client.

Parameterize one rule

When several inputs should produce the same error, parametrization keeps the rule visible and avoids repeated setup. Name cases so a failure identifies the rejected input. Keep materially different workflows in separate tests; squeezing them into a large parameter matrix often hides the story.

@pytest.mark.parametrize('value', ['', None, -1], ids=['blank', 'missing', 'negative'])
def test_rejects_invalid_quantity(value):
    with pytest.raises(ValueError):
        parse_quantity(value)

Assert the final state

For a rejected write, verify the database or fake repository is unchanged. For successful work, assert the public result and important side effects. Avoid asserting private call order unless order is the actual contract. This lets implementation improve without weakening the test.

Check your understanding

What makes a parametrized test case useful when it fails?

Show explanation

A clear case name and one visible rule make the failing input and expected behavior easy to understand.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Fix a SQL injection

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.