Prerequisites
- !pytest basics: test discovery, asserts, and simple fixtures
- !Mocking external calls with unittest.mock
What You'll Learn
- 1Pick the lightest test double that proves the behaviour
- 2Patch at the boundary your code actually owns
- 3Design fixture scopes and factories that keep suites fast
- 4Replace repetitive cases with parametrisation and properties
- 5Write failures that point directly at the broken behaviour
Unit tests rot for predictable reasons: they share state, mock too much, and repeat the same scenario with one changed value. Each of those has a mechanical fix, and applying them turns a suite that everyone avoids into one that runs in seconds and still catches regressions. This lesson covers doubles, patching boundaries, fixture design, and the two techniques that remove the most duplication from a large suite.
Choose the lightest double that proves the point
Every test double is a trade between realism and control. The lighter the substitute, the more of the real system you exercise, which usually means fewer tests that pass while production stays broken. Start from the weakest substitute that isolates the behaviour under test.
| Double | Stands in for | What it does | Use when |
|---|---|---|---|
| Stub | A collaborator | Returns canned values | The value drives your logic |
| Spy | A collaborator | Records calls for assertions | The call itself is the contract |
| Mock | A collaborator | Both, plus expectations | Interaction must be enforced |
| Fake | A whole subsystem | Real logic, lighter implementation | Speed or isolation from infra |
| Nothing | Nothing | Real object everywhere | It is fast, deterministic, and local |
The last row is the one people skip. An in-memory dictionary is a better collaborator than a mock of a cache, because your real lookup code runs. A temporary file is a better collaborator than a mocked filesystem for simple reads. Only reach for Mock when the collaborator is slow, remote, random, or has side effects you cannot undo, and even then prefer the narrowest surface you can patch.
from unittest.mock import Mock, call
def render(lookup, key):
return f"hello {lookup(key)}"
def publish_order(bus, order):
bus.publish("order.created", order)
bus.publish("order.updated", order)
class OrderService:
def __init__(self, repo):
self._repo = repo
def create(self, row):
self._repo.save(row)
return row
def get(self, row_id):
return self._repo.get(row_id)
def test_stub_drives_branches():
lookup = Mock(return_value="cached")
assert render(lookup, "user:1") == "hello cached"
lookup.assert_called_once_with("user:1")
def test_spy_records_sequence():
bus = Mock()
publish_order(bus, {"id": 7})
assert bus.publish.call_args_list == [
call("order.created", {"id": 7}),
call("order.updated", {"id": 7}),
]
def test_fake_replaces_subsystem():
class InMemoryRepo:
def __init__(self):
self._rows = {}
def save(self, row):
self._rows[row["id"]] = row
def get(self, row_id):
return self._rows.get(row_id)
service = OrderService(InMemoryRepo())
service.create({"id": 1, "total": 10})
assert service.get(1) == {"id": 1, "total": 10}
Note that the fake is a real implementation of a small part of the interface, so the code under test executes its normal paths. That is why fakes catch more bugs than mocks: a mock asserts that you called a method, while a fake proves the call actually works.
Patch at the boundary you own
patch replaces a name where it is looked up, not where it is defined, and that distinction decides whether your test proves anything. Patch the attribute on the module that performs the import, because patching the source module does nothing if the consumer already bound the name locally.
from unittest.mock import patch, MagicMock
from datetime import datetime
# the code under test lives in myapp/invoices.py; patch names as that module imports them
def get_invoice_date():
return datetime.now().strftime("%Y-%m-%d")
@patch("myapp.invoices.datetime")
def test_invoice_date_is_stable(mock_datetime):
mock_datetime.now.return_value = datetime(2024, 3, 15, 12, 0, 0)
assert get_invoice_date() == "2024-03-15"
mock_datetime.now.assert_called_once()
@patch("myapp.invoices.requests.get")
def test_client_handles_error_response(mock_get):
response = MagicMock()
response.status_code = 503
response.raise_for_error.side_effect = RuntimeError("unavailable")
mock_get.return_value = response
result = fetch_with_retry("https://example.com", attempts=1)
assert result is None
assert mock_get.call_count == 1
Two rules keep patching honest. Patch where the name is used, and never patch more than one external system in a test, because when the test fails you will not know which substitution was responsible. If you find yourself patching three things, the unit of test is too large: either drop to a smaller function or accept that you are writing an integration test and move it to the right layer. Prefer dependency injection over patching whenever you control the design, since passing a fake in is explicit, typed, and immune to rename refactors.
Fixtures that scale instead of sprawling
Fixtures are where suites go to die, usually through oversized scopes and shared mutable state. Scope a fixture only as widely as it must be shared, keep mutable objects function-scoped, and use factory fixtures when a test needs variants rather than one canonical object.
import pytest
@pytest.fixture
def user_factory():
def make(role="member", **overrides):
user = {"id": 1, "name": "ada", "role": role}
user.update(overrides)
return user
return make
@pytest.fixture
def client(app):
with app.test_client() as test_client:
yield test_client
def test_admin_sees_everything(client, user_factory):
admin = user_factory(role="admin")
with client.session_transaction() as session:
session["user"] = admin
response = client.get("/admin/users")
assert response.status_code == 200
def test_member_is_redirected(client, user_factory):
member = user_factory(role="member")
with client.session_transaction() as session:
session["user"] = member
response = client.get("/admin/users")
assert response.status_code == 302
The factory fixture gives every test its own data without repeating a dictionary literal, and the client fixture wraps cleanup in a with block so sessions close deterministically. Avoid session-scoped fixtures that hand out mutable objects, since one test's mutation becomes another test's mystery failure and the ordering dependency will surface only on some machines. When setup is expensive, share immutable, expensive resources and rebuild the mutable parts per test.
Parametrisation and properties
Most verbose suites repeat a test body for each input. Parametrisation states the case list once and generates a test per row, and each row gets a readable identifier so a failure tells you exactly which input broke.
import pytest
from hypothesis import given, strategies as st
from app.pricing import apply_discount, is_valid_username
@pytest.mark.parametrize("subtotal,rate,expected", [
(100, 0.0, 100.0),
(100, 0.1, 90.0),
(100, 0.25, 75.0),
(0, 0.5, 0.0),
])
def test_apply_discount(subtotal, rate, expected):
assert apply_discount(subtotal, rate) == pytest.approx(expected)
@given(st.text(min_size=1, max_size=20))
def test_username_is_never_blank(username):
result = is_valid_username(username)
assert isinstance(result, bool)
if not username.strip():
assert result is False
Property-based tests shine where hand-written cases cannot: they explore inputs you did not think of, shrink failures to a minimal example, and document an invariant rather than an example. The property above asserts stability under trimming, which is a claim about the function rather than a single value. Used together, parametrisation covers your known edge cases and properties cover the unknown ones, and together they remove most of the duplication that makes suites expensive to maintain.
Organising a suite people can navigate
Structure follows the code under test: one test module per source module, or one per behaviour if the source mixes concerns. Name tests after the behaviour, not the function, so a failure reads as a statement about what broke. Keep setup in fixtures rather than in helper functions called from tests, because fixtures compose and can be requested selectively.
Isolation is the property that keeps a suite trustworthy. Tests must not depend on execution order, on the network, on wall-clock time, or on leftover files from a previous run. Inject clocks, generate temporary directories with built-in fixtures, and reset module-level state in a conftest fixture if you cannot refactor it away. A suite that passes alone and fails in CI is worse than no suite, because it teaches people to rerun instead of investigating.
Reading failures as documentation
A good assertion failure names the expected contract in one line. Use pytest.approx for floats, assert on structured values rather than substrings where you can, and include the offending input in the message with a clear explanation. When a test fails deep inside a library, add a higher-level assertion so the failure surfaces at the level a reader understands.
Finally, treat skipped and xfailed tests as debt with an expiry date. A permanent skip is a test that quietly stopped protecting you, so track them the same way you track open bugs, and delete tests that no longer describe behaviour anyone expects to keep.
Coverage as a floor, not a goal
Line coverage is useful as a floor because it tells you which code no test ever reaches, and useless as a target because a test that executes a line without asserting anything adds nothing. Read the report backwards: start from uncovered branches in business logic, not from the percentage. A module at ninety-five percent with the uncovered five percent being validation is far riskier than one at eighty percent whose gaps are logging and defensive assertions.
Pair coverage with mutation testing when you can afford it, since it deliberately breaks the source and checks whether your tests notice. Even a manual version helps: change one comparison operator in a critical function, run the suite, and confirm something fails. If nothing fails, you have found a test that mirrors the implementation rather than the contract. Keep the habit occasional and targeted at high-value modules, because running a full mutation campaign is expensive, while applying it to the few functions where correctness is worth money is cheap and repeatedly proves its value.
Common Mistakes
Patching the source module instead of the name as imported by the code under test
Fix: Patch the attribute on the consuming module, which is where the lookup actually happens.
Mocking three or more collaborators in a single test
Fix: Split the test or switch to dependency injection with a fake so only one boundary is substituted.
Sharing mutable objects through session-scoped fixtures
Fix: Share expensive immutable resources and rebuild mutable state per test with a factory fixture.
Writing an example-based test for every branch of a numeric function
Fix: Use parametrisation for known cases and a property-based test for the general invariant.
Best Practices
- Prefer fakes and real local objects over mocks whenever speed allows
- Give every parametrised case an identifier so failures are self-explanatory
- Keep fixture scopes as narrow as correctness permits
- Assert on behaviour and side effects rather than on internal implementation details
- Run the suite with random ordering occasionally to expose hidden dependencies
Key Takeaways
- The lightest sufficient double keeps tests honest about real behaviour
- patch replaces a name where it is looked up, so patch the consuming module
- Factory fixtures provide variants without duplicated setup
- Parametrisation removes repetition; properties prove invariants across inputs
- Order-independent, offline tests are what make a suite trustworthy in CI