Sub topic 17
Habits of a maintainable test suite
This chapter assumes you can write tests with plain assert, use fixtures and parametrize, and run pytest from the terminal. It covers habits that keep a suite useful after hundreds of tests and many months of changes.
What maintainable means
A maintainable suite has three properties:
- It fails for real reasons. A red test means the behavior is broken, not that the test is flaky or that you renamed a private helper.
- It is cheap to run. Developers run it before every commit, so it has to stay fast.
- It is cheap to change. A small change in the code causes a small change in the tests.
Most of the habits below protect one of these properties.
Test behavior, not implementation
A test should describe what the code promises to callers. It should not describe how the code does it. Tests tied to internals break during harmless refactoring, and people learn to ignore them.
Using the total function from earlier chapters:
import pytest
from cart import total
def test_total_applies_tax():
assert total([10, 20], tax_rate=0.1) == pytest.approx(33.0)This test survives rewriting total with a loop, a generator, or math.fsum. A test that patched sum and asserted it was called once would break on any of those rewrites, even though the result is unchanged.
The same rule applies to mocks. Assert on calls that cross a boundary, such as "an email was sent to this address". Do not assert on every internal call.
Give each test one reason to fail
A test that checks five unrelated things stops at the first failing assert. It hides the other four problems and gives a vague name to the failure. Prefer small tests with names that read like sentences:
test_total_of_empty_cart_is_zerotest_negative_tax_rate_is_rejected
When one of these fails, the name tells you what broke before you open the file. A single test may contain several assert lines if they describe one outcome, for example the fields of one returned object.
Arrange, act, assert
Structure each test in three visible steps. Arrange the inputs, act by calling the code once, and assert on the result. Blank lines between the steps make this easy to scan:
import sqlite3
import pytest
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT)")
yield conn
conn.close()
def test_insert_adds_one_row(db):
db.execute("INSERT INTO users VALUES ('ada')")
count = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 1If a test needs a second act step, it is usually two tests. Keep logic such as loops and conditionals out of the body. A test with branches needs its own tests.
Keep tests independent
Every test must pass when run alone, in any order, and after other tests have run. Shared mutable state breaks this. The usual cause is a module-level object that tests modify:
import pytest
_registry = []
def register(name):
_registry.append(name)
return len(_registry)
def test_first_registration_is_one():
assert register("a") == 1
def test_second_registration_is_one():
assert register("b") == 1 # fails: the first test already ranThe second test fails because the first one left state behind. A common fix is to give the state to the test through a fixture, so each test gets a fresh copy:
import pytest
class Registry:
def __init__(self):
self.names = []
def register(self, name):
self.names.append(name)
return len(self.names)
@pytest.fixture
def registry():
return Registry()
def test_first_registration_is_one(registry):
assert registry.register("a") == 1
def test_registrations_are_counted(registry):
registry.register("a")
assert registry.register("b") == 2Prefer function-scoped fixtures. Widen the scope (module or session) only for objects that are expensive to build and that tests do not modify.
Use built-in fixtures to avoid leaking state outside the process. tmp_path gives each test its own directory, and monkeypatch restores environment variables and attributes after the test.
Make tests deterministic
A flaky test passes and fails on the same code. The causes are nearly always one of these:
| Source of flakiness | Typical fix |
|---|---|
| Current time | Pass the time in as an argument, or patch the clock |
| Randomness | Pass in a seeded `random.Random`, or assert on properties |
| Network calls | Replace the client with a test double |
| Shared files or ports | Use `tmp_path` and per-test resources |
| Test order | Remove shared state between tests |
| Dictionary or set ordering assumptions | Compare sorted values, or compare sets |
The cleanest fix is to design the code so the unstable input can be supplied by the caller:
# clock_example.py
from datetime import datetime, timezone
def greeting(now=None):
now = now or datetime.now(timezone.utc)
return "Good morning" if now.hour < 12 else "Good afternoon"# test_clock_example.py
from datetime import datetime, timezone
from clock_example import greeting
def test_greeting_before_noon():
now = datetime(2026, 1, 1, 9, 0, tzinfo=timezone.utc)
assert greeting(now) == "Good morning"
def test_greeting_after_noon():
now = datetime(2026, 1, 1, 15, 0, tzinfo=timezone.utc)
assert greeting(now) == "Good afternoon"No patching is needed, and the tests give the same result at any hour.
Use mocks sparingly
A mock replaces a collaborator so the test does not need the real thing. Each mock also removes some real behavior from the test. Follow these rules:
- Mock at the edge of your system: HTTP clients, message queues, the clock, the payment gateway. Do not mock your own pure functions.
- Patch the name where the code under test looks it up, not where it was defined.
- Prefer a small fake, such as an in-memory database, over a mock with many configured return values.
- Use
Mock(spec=RealClass)orcreate_autospecso calls with wrong method names or signatures fail instead of silently passing.
from unittest.mock import Mock
from service import send_welcome
def test_send_welcome_uses_the_client_api():
client = Mock(spec=["send"])
send_welcome(client, "ada")
client.send.assert_called_once_with(to="ada", body="Welcome!")With spec=["send"], calling any attribute other than send raises AttributeError, so a typo in the code under test cannot go unnoticed.
Keep the suite fast
Slow suites get run less often. These habits keep the cost down:
- Keep unit tests free of network, disk, and sleeps wherever possible.
- Run
pytest --durations=10now and then to list the slowest tests, and fix or mark those. - Mark slow tests with a custom marker and skip them during everyday runs with
pytest -m "not slow". - Run the full suite, including slow tests, in continuous integration.
Treat coverage as a signal
Coverage reports which lines ran. It does not report whether the assertions were meaningful. A test that calls a function and asserts nothing gives full line coverage and no protection.
Use --cov-report=term-missing to find untested branches, especially error paths. Do not chase 100% as a goal in itself. A threshold such as --cov-fail-under=80 in continuous integration is reasonable as a guard against sudden drops. Setting it higher often encourages low-value tests written only to raise the number.
Keep failures informative
When a test fails, the report should explain why without a debugger. Plain assert already shows both sides of a comparison. Help it along:
- Compare whole values instead of reducing them to booleans.
assert result == {"id": 1}shows a diff, whileassert result["id"] == 1 and "name" in resultdoes not. - Use
pytest.raises(..., match=...)so the wrong error message fails the test. - Add a message to an
assertonly when the values alone are not enough. - Use
pytest.param(..., id="empty cart")inparametrizeto give cases readable names. - Mark known bugs with
xfail(strict=True)so the test fails loudly once the bug is fixed and the marker becomes stale.
What to do when a test fails
Never delete or loosen an assertion just to get green. Decide first which of the three branches applies.
Checklist
- Each test has a descriptive name and one reason to fail.
- Tests follow arrange, act, assert and contain no branching logic.
- Tests pass alone, in any order, and in parallel.
- Time, randomness, and I/O are injected or isolated.
- Mocks sit at system boundaries and use
spec. - Slow tests carry a marker, and
--durationsis checked now and then. - Coverage is read as a map of gaps, not as a score.
Exercise
The test below passes on your machine in the morning and fails in the afternoon. Name the cause and rewrite the test so it is deterministic. The function is greeting(now=None) from this chapter.
def test_greeting():
assert greeting() == "Good morning"
Show answer
The test depends on the current time, because greeting() falls back to datetime.now. Pass a fixed time instead:
def testgreetingbefore_noon():
now = datetime(2026, 1, 1, 9, 0, tzinfo=timezone.utc)
assert greeting(now) == "Good morning"
The result no longer depends on when the suite runs. An equally valid alternative is to patch the clock, but injecting the value needs no patching.
Exercise
A teammate writes a test for send_welcome with client = Mock() and ends it with client.send.assert_called_once(). A later refactor renames the real method from send to deliver, and the test still passes. What two changes make the test catch this?
Show answer
Create the mock with a spec so unknown attributes raise errors, for example Mock(spec=["deliver"]) or create_autospec(RealClient). Then assert on the arguments as well, for example client.deliver.assert_called_once_with(to="ada", body="Welcome!"). With the spec in place, the old send call fails immediately, and the argument check also catches wrong recipients or text.