pytest Fixtures, Mocking, and Test Design
Difficulty: Medium | Companies: Google, Meta, Amazon, Netflix, Stripe
A test suite is a specification you can execute. Interviewers probe whether your tests describe behaviour or merely mirror your implementation, because one survives a refactor and the other breaks every time you rename a method.
Prerequisites
- !Functions, decorators, and exception handling
- !Basic unit testing concepts
- !Python imports and module structure
What You'll Learn
- 1Compose fixtures so setup is declared once and read clearly
- 2Replace hand-written loops with parametrized cases
- 3Mock at the boundary a component does not own
- 4Explain the trade-offs between stubs, mocks, fakes, and the real thing
What a good test actually asserts
A test states a precondition, performs one action, and checks one observable outcome. That discipline is what makes a failure message useful: when a test named test_expired_token_returns_401 breaks, you already know which contract changed. Tests that assert ten things at once tell you only that something, somewhere, went wrong.
The Arrange-Act-Assert rhythm is the practical form of this idea. Setup belongs in fixtures, the action is a single call, and assertions stay on the public result â not on how many times an internal helper happened to run. When you find yourself asserting on a private attribute to make a test pass, that is a signal that the design hides the outcome you actually care about, and the better fix is usually to widen the return value rather than to reach further into the object.
Equally important is deciding what a test refuses to cover. Unit tests should not assert the ordering of log lines, the exact SQL an ORM emits, or the layout of a dictionary that only exists mid-refactor. Those are implementation details, and binding to them converts every harmless change into a failing build.
Fixtures and parametrization instead of copy-paste
pytest fixtures form a dependency graph: a fixture can request other fixtures, and pytest resolves them once per test with the correct scope. The payoff is that teardown is guaranteed even when the test fails, which is exactly where hand-rolled setup goes wrong.
import pytest
@pytest.fixture(scope="module")
def ledger():
"""One in-memory ledger shared by every test in this module."""
entries = [{"account": "cash", "amount": 100},
{"account": "revenue", "amount": 100}]
return {"entries": entries, "postings": 0}
@pytest.fixture
def empty_ledger():
return {"entries": [], "postings": 0}
def balance(ledger, account):
return sum(e["amount"] for e in ledger["entries"]
if e["account"] == account)
def post(ledger, account, amount):
if amount == 0:
raise ValueError("amount must be non-zero")
ledger["entries"].append({"account": account, "amount": amount})
ledger["postings"] += 1
return ledger["postings"]
def test_opening_balances(ledger):
assert balance(ledger, "cash") == 100
def test_posting_increments_counter(empty_ledger):
assert post(empty_ledger, "cash", 25) == 1
assert post(empty_ledger, "cash", -25) == 2
def test_zero_amount_rejected(empty_ledger):
with pytest.raises(ValueError, match="non-zero"):
post(empty_ledger, "cash", 0)
@pytest.mark.parametrize("amount,expected", [
(10, 10),
(-10, -10),
(1000000, 1000000),
])
def test_posting_returns_new_count(empty_ledger, amount, expected):
post(empty_ledger, "cash", amount)
assert balance(empty_ledger, "cash") == amount
assert empty_ledger["postings"] == 1
Notice what parametrize bought: three edge cases with no duplicated body, and a failure report that names the exact row (amount=-10) instead of hiding it inside a loop. Scope matters too â scope="module" shares the expensive object across tests that only read it, while the function-scoped empty_ledger guarantees isolation for tests that mutate.
Mock at the boundary you do not own
Mocking is not a way to avoid writing code; it is a way to keep a test deterministic when the environment is not yours. The rule of thumb interviewers listen for: mock the seam â network, clock, filesystem, database â and never mock the collaborator you are trying to test.
from unittest.mock import Mock, patch, AsyncMock
import pytest
class BillingClient:
def __init__(self, transport, clock):
self.transport = transport
self.clock = clock
def charge(self, customer_id, cents):
if cents <= 0:
raise ValueError("amount must be positive")
response = self.transport.post(
"/charges", json={"customer": customer_id,
"cents": cents,
"at": self.clock()})
if response.status >= 400:
raise RuntimeError(f"gateway rejected: {response.status}")
return response.body["id"]
def test_charge_sends_expected_payload():
transport = Mock()
transport.post.return_value = Mock(status=201, body={"id": "ch_1"})
clock = Mock(return_value="2026-01-01T00:00:00Z")
client = BillingClient(transport, clock)
charge_id = client.charge("cus_42", 999)
assert charge_id == "ch_1"
transport.post.assert_called_once_with(
"/charges",
json={"customer": "cus_42", "cents": 999,
"at": "2026-01-01T00:00:00Z"})
def test_gateway_rejection_becomes_runtime_error():
transport = Mock()
transport.post.return_value = Mock(status=503, body={})
client = BillingClient(transport, Mock(return_value="now"))
with pytest.raises(RuntimeError, match="503"):
client.charge("cus_42", 999)
def test_non_positive_amount_never_touches_network():
transport = Mock()
client = BillingClient(transport, Mock(return_value="now"))
with pytest.raises(ValueError, match="positive"):
client.charge("cus_42", 0)
transport.post.assert_not_called()
Two habits separate competent mocking from cargo cult. First, configure only the attributes the code path touches; a Mock() answers everything, so a typo in your production code silently returns another mock instead of raising AttributeError. Second, assert the interaction contract â the payload you sent â rather than the fact that a method was called at all.
Async code and context managers
Async tests need an event loop, which pytest-asyncio provides once you mark the coroutine. The same mocking tools apply: AsyncMock returns an awaitable where a plain Mock would return a value, and forgetting that distinction produces the confusing error "object Mock can't be used in await expression".
import pytest
from unittest.mock import AsyncMock, patch
class ReportService:
async def build(self, user_id):
rows = await self.store.fetch_rows(user_id)
return {"user": user_id, "rows": len(rows)}
@pytest.mark.asyncio
async def test_build_counts_rows():
service = ReportService()
service.store = AsyncMock()
service.store.fetch_rows.return_value = [1, 2, 3]
assert await service.build(7) == {"user": 7, "rows": 3}
service.store.fetch_rows.assert_awaited_once_with(7)
@pytest.mark.asyncio
async def test_context_manager_cleanup_runs_on_failure():
with patch("report.open_file") as opener:
handle = opener.return_value.__enter__.return_value
handle.read.side_effect = OSError("disk gone")
with pytest.raises(OSError):
async with opener("out.csv") as f:
await f.read()
opener.return_value.__exit__.assert_called_once()
The second test makes the point that matters most in production: cleanup must run on the failure path too. A suite that only exercises the happy path will pass while leaking file handles and database connections.
Choosing the right test double
Different doubles trade fidelity for speed and control in different ways. Naming them precisely is a quick way to show that testing is a craft you have practised rather than a checkbox.
| Double | What it is | Speed | Risk of false confidence |
|---|---|---|---|
| Dummy | Fills a parameter that the path ignores | Fast | None, but proves nothing |
| Stub | Returns canned answers, no assertions | Fast | Behaviour may not match reality |
| Mock | Canned answers plus expectations you assert | Fast | Brittle if it pins internals |
| Fake | Working but lightweight implementation | Medium | Diverges from production |
| Spy | Wraps the real thing and records calls | Medium | Can slow hot paths |
| Real | The actual dependency | Slow | Deterministic only if the environment is |
An in-memory repository is a fake and is usually the best default: it exercises real logic while staying fast. A network stub is appropriate when the remote contract is documented and stable. Full integration tests against a containerized database earn their slower runtime by catching the things no mock can, such as a missing index or a constraint you forgot.
Organizing the suite as it grows
A suite that works at fifty tests becomes unusable at five thousand, and the decay is structural rather than numerical. The usual culprits are shared mutable fixtures that leak state between tests, tests reaching across module boundaries to poke internals, and a conftest.py so large that nobody can predict what a test depends on. Fixing it is mostly a matter of ownership: one directory per component, fixtures defined beside the code they serve, and helpers promoted to a shared fixture only when three or more tests need them.
Naming carries surprising weight in review. A test called test_create_user tells a reader nothing when it fails, while test_create_user_rejects_duplicate_email states the contract in the name, so the failure message confirms a suspicion instead of starting an investigation. Keep the number of assertions low enough that a failure points somewhere specific, and prefer a fresh test over another branch inside an existing one.
Execution time is a feature too. Unit tests should complete in seconds so developers run them before every commit; container-backed integration tests can take minutes but belong in a separate CI stage with parallel shards. A suite that takes ten minutes stops being run locally, and the moment people stop running it, it stops preventing anything. Quarantine flaky tests visibly with a marker and a ticket rather than retrying silently, because a retry hides the race you were about to debug.
TDD, coverage, and what they do not tell you
Test-driven development is a design feedback loop more than a testing technique. Writing the test first forces you to name the interface before you build it, and the red-green-refactor cycle keeps the implementation minimal. The discipline fails when the test is written after the code and shaped by it, which produces a suite that passes because it agrees with you.
Coverage measures execution, not understanding. A file at one hundred per cent with only happy-path assertions can still miss every error branch that matters. Use coverage to find untested regions, then decide whether each region deserves a test â a raise on an impossible state may legitimately stay uncovered, while a retry path should have a test that proves the second attempt succeeds.
Common Mistakes
Mocking the class under test or its internal helpers
Fix: Mock the boundary the component does not own â network, clock, filesystem â and let the logic run for real.
One giant test that covers a whole happy path end to end
Fix: Split into focused tests with one action and one outcome so a failure names the broken contract.
Chasing a coverage number without reading the uncovered lines
Fix: Treat coverage as a map of untested regions and decide deliberately which branches deserve tests.
Asserting on private attributes to make a test pass
Fix: Widen the public result or behaviour so the assertion describes an outcome a user can observe.
Best Practices
- Keep fixtures small, composable, and scoped to the narrowest lifetime that works
- Prefer parametrize for edge cases so every row appears individually in failure output
- Name tests after the behaviour: test_expired_token_returns_401, not test_token_2
- Run unit tests on every commit and container-backed integration tests on merge
- Delete tests that assert implementation details; they cost more than they protect
- Use pytest.raises with match= so error messages stay part of the contract
Interview Questions
Q1: What is the difference between a mock and a stub?
A stub returns canned values to let the code under test run; a mock also carries expectations you assert, so it verifies the interaction, not just the result.
Q2: When is mocking the wrong tool?
When you are mocking the unit under test or a collaborator you own. That tests your mock, not your code, and breaks on every refactor.
Q3: How do you test async code?
Mark the coroutine with pytest-asyncio, use AsyncMock for awaitable collaborators, and assert with await plus assert_awaited_once where the call matters.
Q4: What does coverage fail to capture?
Whether assertions are meaningful. A hundred per cent coverage with only happy-path checks still misses error branches and edge conditions.
Q5: Why does cleanup need its own test?
Resources must be released on the failure path too, and the happy path alone never proves that the finally branch runs.
Q6: How do you keep a suite fast as it grows?
Push slow dependencies behind boundaries, fake them in unit tests, scope shared fixtures narrowly, and quarantine container tests into a separate CI stage.
Key Takeaways
- One test, one action, one observable outcome, named after the behaviour
- Fixtures compose and guarantee teardown; parametrize removes duplicated edge cases
- Mock at seams you do not own and configure only what the path touches
- AsyncMock exists because await needs a coroutine, not a plain value
- Doubles trade fidelity for speed â choose the cheapest one that still proves the claim
- Coverage reports where to look, never whether the assertions were worth reading