Python Testing: Mocks, Fixtures, and Parametrize
The difference between a test suite people trust and one they work around is almost never coverage â it is boundary discipline. Tests that patch internal functions break whenever the code is refactored; tests that share mutable fixture state fail in random order; tests that mock everything assert only that the mock was called. This lesson treats mocking and fixtures as design tools: what belongs inside a test double, what should be a real object with a temporary home, how parametrisation keeps data-driven cases readable, and how to keep async and side-effecting code deterministic enough to run in CI without flakiness.
What You'll Learn
- 1Design fixtures with correct scope, factories, and teardown
- 2Choose patch targets that survive refactoring
- 3Drive large case tables with parametrize and readable ids
- 4Mock async calls and control side effects for repeatable runs
Fixture scope, factories, and teardown
A fixture is setup plus teardown expressed as a generator, and the two decisions that matter are scope and sharing. Session-scoped fixtures run once for the whole run and are right for expensive, immutable resources such as a schema migration or a container. Function-scoped fixtures run per test and are right for anything the test might mutate â which, if the object is shared, means one test can corrupt another and produce failures that appear and vanish.
The classic escape from the shared-state trap is a fixture factory: a fixture that returns a factory function, so each test creates its own instance explicitly while the teardown logic stays in one place. When a test needs a variation â a different country code, a zero balance â it asks the factory for that variation instead of mutating the shared object and hoping nobody notices. Fixture resolution order also matters: a test can request several fixtures, and dependencies pull each other in the right order automatically.
import pytest
class Ledger:
def __init__(self, currency="USD"):
self.currency = currency
self.entries = []
def post(self, amount):
self.entries.append(amount)
return len(self.entries)
@pytest.fixture
def ledger_factory():
created = []
def factory(currency="USD"):
ledger = Ledger(currency)
created.append(ledger)
return ledger
yield factory
assert all(isinstance(item, Ledger) for item in created)
@pytest.fixture(scope="module")
def reference_rates():
return {"USD": 1.0, "EUR": 0.92, "GBP": 0.79}
def test_posts_are_independent(ledger_factory):
first = ledger_factory()
second = ledger_factory("EUR")
first.post(10)
assert first.currency == "USD"
assert second.entries == []
def test_uses_shared_reference(reference_rates):
assert reference_rates["EUR"] < reference_rates["USD"]
The factory fixture's teardown asserts a structural property rather than a specific value, which keeps it valid as tests evolve. Avoid over-scoping for speed: a module-scoped mutable fixture saves milliseconds and costs debugging hours, and it also hides state that would otherwise be created fresh by the code under test.
Patching at the boundary you own
unittest.mock.patch replaces an attribute for the duration of a test, and the rule that keeps tests stable is to patch where the name is looked up, not where it was defined â usually the consuming module, not the library. Patching requests.get in your module's namespace is correct; patching it where requests defines it works only while the import style cooperates. Beyond that, prefer dependency injection: pass the client in, and the test passes a fake instead of patching anything.
Mock objects earn their place at system boundaries â network calls, clocks, random sources, databases â where determinism is impossible otherwise. Inside a module's own logic, mocks usually mean the test is asserting call counts rather than outcomes, which breaks on harmless refactors. Assert on returned values and observable state first; assert on interactions only when the interaction itself is the contract, such as verifying a message was published exactly once.
from unittest.mock import MagicMock, patch, call
import json
def fetch_profile(client, user_id):
response = client.get(f"/users/{user_id}")
if response.status_code != 200:
raise LookupError(user_id)
return json.dumps(response.json())
def test_profile_happy_path():
client = MagicMock()
client.get.return_value.status_code = 200
client.get.return_value.json.return_value = {"id": 7, "name": "Ada"}
body = json.loads(fetch_profile(client, 7))
assert body["name"] == "Ada"
client.get.assert_called_once_with("/users/7")
def test_profile_missing_user():
client = MagicMock()
client.get.return_value.status_code = 404
with pytest.raises(LookupError):
fetch_profile(client, 99)
def build_client(base_url):
return MagicMock()
def get_client():
return build_client("https://internal")
def test_patch_where_the_name_is_looked_up():
# patch the consuming module's reference, not the function's definition
with patch(f"{__name__}.build_client") as builder:
builder.return_value = MagicMock()
assert get_client() is builder.return_value
builder.assert_called_once_with("https://internal")
The third test shows the patching rule in action: the name is resolved through the consuming module at call time, so replacing build_client in that module's namespace is what the test must do â patching it where it was defined would miss the reference the caller actually uses. Use monkeypatch for simple attribute, environment, and dictionary patches; it is scoped to the test automatically and restores state without the ceremony of patch context managers.
Parametrisation instead of copy-paste
Data-driven tests shrink maintenance: a case table is edited in one place, new combinations cost a row rather than a function, and the reported test id tells you exactly which input failed. pytest.mark.parametrize accepts one or more argument lists, and when several decorators are stacked the cases multiply â useful, but worth naming with ids so the output stays readable.
The craft is choosing what to parametrise. Split on axes that vary independently â currency pairs, boundary values, error codes â and keep related assertions in one test rather than fanning out into dozens of near-identical functions. When a case needs a different expectation shape, parametrise the expected value alongside the input, or use pytest.param(..., marks=pytest.mark.skip) to encode known failures as data rather than as commented-out code.
import pytest
def grade(score):
if score >= 90:
return "A"
if score >= 60:
return "pass"
return "fail"
@pytest.mark.parametrize("score,expected", [
(95, "A"),
(90, "A"),
(89, "pass"),
(60, "pass"),
(59, "fail"),
(0, "fail"),
], ids=["top", "boundary-a", "just-below-a", "boundary-pass", "just-below-pass", "zero"])
def test_grade(score, expected):
assert grade(score) == expected
@pytest.mark.parametrize("currency", ["USD", "EUR"])
@pytest.mark.parametrize("amount", [0, 10, -5])
def test_amount_signs(amount, currency):
assert isinstance(amount * currency, str)
@pytest.mark.parametrize("value,reason", [
(None, pytest.param("None rejected", marks=pytest.mark.xfail(reason="not implemented"))),
("ok", "accepted"),
])
def test_validation(value, reason):
assert reason
Keep tables near the function they test. Splitting cases across files turns a five-minute review of boundary behaviour into a search, and the ids above â boundary-a, just-below-a â are what make a CI failure self-explanatory without opening a debugger.
Mocks for async and side-effecting code
Asynchronous code needs doubles that await correctly: AsyncMock returns awaitables from __call__, and patch produces one automatically when the target is detected as an async function. Mixing them up produces tests that fail with object NoneType can't be used in 'await' expression, which is a sign the double and the caller disagree about whether the call is a coroutine.
Side effects deserve explicit control. side_effect accepts a function called on every invocation, which lets a test script a sequence of behaviours â succeed twice, then fail â instead of a fixed return value. For iteration order and randomness, inject a seeded generator rather than patching the module, and for time, inject a clock function. Both keep the test deterministic without knowing which module the implementation imports from.
from unittest.mock import AsyncMock, patch
import asyncio
async def notify(client, user_id):
try:
await client.send(user_id, "hello")
except ConnectionError:
return "failed"
return "sent"
def test_async_send_success():
client = AsyncMock()
result = asyncio.run(notify(client, 5))
assert result == "sent"
client.send.assert_awaited_once_with(5, "hello")
def test_async_send_connection_error():
client = AsyncMock(side_effect=ConnectionError)
assert asyncio.run(notify(client, 5)) == "failed"
def test_scripted_sequence():
responses = [1, 2, ConnectionError("boom")]
def next_response(*args, **kwargs):
item = responses.pop(0)
if isinstance(item, Exception):
raise item
return item
mock = MagicMock(side_effect=next_response)
assert mock() == 1
assert mock() == 2
with pytest.raises(ConnectionError):
mock()
assert_awaited_once_with checks that the coroutine was awaited, not merely called â an important distinction, because a test that forgets to await will pass assertions on assert_called_once while the production code silently does nothing.
Isolation: temp files, output, and environment
Tests that touch the filesystem, environment variables, or process-wide state leak by default. pytest supplies tmp_path for files, monkeypatch for environment and dictionary entries, and capsys for captured output, each of which restores state at the end of the test. Using them is usually cheaper than mocking the OS, and the tests end up exercising the real code path.
The rule is to prefer a real implementation in a sandbox over a fake implementation of the same thing. A real file in tmp_path validates your encoding and newline handling; a mocked open validates only that you called open. Reach for fakes when the real dependency cannot run in CI â remote services, licensed software, hardware â and keep those fakes at the same interface so swapping in the real one is a configuration change.
import json
import os
def load_config(path):
with open(path, encoding="utf-8") as handle:
return json.load(handle)
def test_load_config(tmp_path, monkeypatch, capsys):
config = tmp_path / "app.json"
config.write_text(json.dumps({"timeout": 5}), encoding="utf-8")
monkeypatch.setenv("APP_CONFIG", str(config))
monkeypatch.setenv("APP_MODE", "test")
assert load_config(os.environ["APP_CONFIG"]) == {"timeout": 5}
print("loaded", os.environ["APP_MODE"])
assert "loaded test" in capsys.readouterr().out
def test_missing_config(tmp_path):
with pytest.raises(FileNotFoundError):
load_config(tmp_path / "absent.json")
Environment assertions are the part people skip, and it shows: a test that depends on APP_MODE without setting it passes locally under one shell configuration and fails in CI under another. Setting the variable inside the test â even when it seems redundant â documents the dependency and makes the test runnable anywhere.
Keeping the suite fast and honest
Speed is a correctness feature: a suite that takes twelve minutes gets run once a day, and defects found a day later cost more than any mock saved. Fixture scope, avoiding network calls, and parametrisation instead of repetition all help, but the structural win comes from a pyramid â many fast unit tests, a smaller number of integration tests against real dependencies, and a handful of end-to-end checks.
Honesty is the other half. Tests that assert only assert result is not None encode nothing; tests that mock every collaborator assert a design rather than behaviour. Review tests the way you review production code: if a test cannot fail for the reason you care about, it is documentation, not verification, and it belongs in a docstring instead.
Common Mistakes
Patching an internal function inside the module under test
Fix: Inject the dependency or patch the boundary the test does not own, so refactors do not break the test
Sharing a mutable fixture across tests at module or session scope
Fix: Use function scope or a fixture factory so each test builds its own state
Asserting only that a mock was called
Fix: Assert outcomes and state first; verify interactions only when the interaction is the contract
Awaiting an AsyncMock but asserting with assert_called_once
Fix: Use assert_awaited_once_with so the test proves the coroutine actually ran
Reading environment variables or the real filesystem in a unit test
Fix: Set them with monkeypatch and use tmp_path so the test runs in any environment
Best Practices
- Name parametrised cases so CI output identifies the failing input without a debugger
- Keep fakes at the production interface so switching back to the real dependency is configuration
- Seed randomness and inject clocks instead of patching time modules deep in the stack
- Prefer real code in a sandbox over a mock of the same behaviour
- Measure suite duration and treat a slow test as a defect worth fixing
Interview Questions
Q1: Where should you patch when mocking a library used by your code?
Patch where the name is looked up â the attribute on your module â or avoid patching entirely by injecting the dependency. Patching the library's own definition only works if your code references it through that exact path.
Q2: What is the difference between return_value and side_effect?
return_value is returned on every call. side_effect can be a function or iterable called on each invocation, so it can raise, return different values in sequence, or compute results â which is what you need to script failure paths.
Q3: When are mocks the wrong tool?
When the real implementation is fast, deterministic, and safe in CI â files in tmp_path, real parsers, in-memory databases. Mocks are for boundaries you cannot run: networks, clocks, third-party services, and hardware.
Key Takeaways
- Scope fixtures by mutation risk, not by speed; use factories for per-test variation
- Patch at boundaries the test does not own, and prefer injection over patching
- Parametrisation with explicit ids turns case tables into readable failure reports
- Async code needs AsyncMock and assert_awaited checks to prove the coroutine ran
- Isolate environment, filesystem, and output so tests run identically in CI