Sub topic 17
Habits of a maintainable test suite
This chapter assumes you can write pytest tests, use fixtures and parametrize, and run pytest from a terminal. It collects habits that keep a suite useful as the project grows.
Test one behavior per test
A test should fail for one reason. When it fails, its name should tell you what broke. Name tests after the behavior, not the function: test_tax_is_added_to_subtotal says more than test_total_2.
Arrange the data, act once, then assert. Blank lines between the three steps make the test easy to scan.
# test_cart_habits.py
import pytest
from cart import total
def test_tax_is_added_to_subtotal():
prices = [10, 20]
result = total(prices, tax_rate=0.1)
assert result == pytest.approx(33.0)Several asserts in one test are fine when they check one behavior, such as the fields of a single returned object. Split the test when the asserts check different behaviors.
Keep tests independent
Each test must pass alone, in any order, and in a suite run. Shared mutable state breaks this. The second test below passes or fails depending on which test ran first:
# test_shared_state.py
items = []
def test_add_item():
items.append(5)
assert len(items) == 1
def test_starts_empty():
assert items == []Move the state into a fixture, so each test gets a fresh copy:
# test_fresh_state.py
import pytest
@pytest.fixture
def items():
return []
def test_add_item(items):
items.append(5)
assert len(items) == 1
def test_starts_empty(items):
assert items == []Make tests fast and deterministic
A slow suite gets run less often. A flaky suite gets ignored. Both defeat the purpose of testing.
- Replace network calls, clocks, and randomness with
monkeypatchorMock. - Use
tmp_pathinstead of fixed file paths. - Mark genuinely slow tests with a custom marker, so
pytest -m "not slow"stays quick. - Never depend on the current date or on the order of unordered data such as sets.
Mock at the boundary, not everywhere
Replace only what you cannot run cheaply: HTTP clients, email senders, payment services. If you mock your own internal helpers, the test checks how the code is wired, not what it does. It then breaks on every refactor even when behavior is unchanged.
Test behavior, not implementation
Assert on results the caller can observe: return values, raised errors, and calls to external systems. Do not assert on private attributes or the order of internal calls. A good test survives a rewrite that keeps behavior the same.
Use coverage as a signal
Coverage shows which lines never ran. It does not show whether the assertions are meaningful. A test that calls a function and asserts nothing still raises the number. Use the term-missing report to find untested branches, then write tests for behavior you care about. Do not chase 100% as a goal.
Quick checklist
| Habit | Warning sign |
|---|---|
| Descriptive names | Names like `test_1` or `test_total_works` |
| One behavior per test | A failure message that doesn't say what broke |
| Independence | Tests pass alone but fail together |
| Fast and deterministic | Tests that sometimes fail on rerun |
| Mock only boundaries | Mocks of your own private functions |
Exercise
A test passes when you run pytest test_orders.py::test_refund alone, but fails when you run the whole file. What is the most likely cause, and how do you fix it?
Show answer
The tests share state, such as a module-level list, dictionary, or database, that an earlier test changed. Fix it by moving the state into a fixture, so each test gets its own fresh copy, and by making sure teardown cleans up anything the test created.