Python Master Course V2 — 115. Test Doubles and Dependency Injection
What you will be able to do
- Distinguish fakes, stubs, mocks and real dependencies
- Inject time and storage dependencies into small functions
- Patch at the lookup location and avoid testing implementation details
Prerequisites: 099: API client boundaries; 112–114: pytest and test design.
Your local workspace
Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson115, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.
Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.
python -m pip install pytestThe examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.
Control boundaries without pretending they are real
A dependency is anything a component relies on: a clock, transport, filesystem, random generator or storage operation. A reliable unit test supplies controlled dependencies instead of relying on current time or an available network. Dependency injection means passing those dependencies explicitly. It need not involve a framework; an ordinary function argument is often enough.
A stub returns predetermined answers. A fake is a small working substitute, such as an in-memory record store. A spy records interactions for later inspection. A mock is configured to stand in for a collaborator and can make interaction assertions. Terminology varies between teams, so describe what your substitute actually does. A scripted local transport in this lesson is not an HTTP request and provides no evidence that a remote service works.
Behavioral tests check outcomes and meaningful interactions. Recording requested delays is useful because a retry policy promises how it waits. Asserting every private helper call is usually brittle: reorganizing a correct implementation then breaks tests for irrelevant reasons. Prefer explicit inputs, public outputs and a few contract-level effects.
Our policy attempts a local operation at most three times. A ConnectionError is retryable; a ValueError is not. The delays after the first and second transient failures are one and two seconds. There is no delay after the last failure. A monotonic clock measures elapsed duration without depending on wall-clock date adjustments. The fake advances its own counter instead of sleeping, so the suite stays fast and deterministic.
Implement a retry boundary
def retry(operation, sleep, now, attempts=3):
if type(attempts) is not int or attempts < 1:
raise ValueError("attempts must be a positive integer")
started = now()
for attempt in range(attempts):
try:
value = operation()
except ConnectionError:
if attempt == attempts - 1:
raise
sleep(2 ** attempt)
else:
return {"value": value, "elapsed": now() - started}The bare raise re-raises the active ConnectionError with its context. The else block runs only when the try block completed without that exception. A programming error or validation error remains visible. Save the following helpers and tests together as test_retrying.py. Each scripted outcome is either a return value or an exception object.
import pytest
from retrying import retry
class FakeClock:
def __init__(self):
self.value = 100.0
self.delays = []
def now(self):
return self.value
def sleep(self, seconds):
self.delays.append(seconds)
self.value += seconds
class ScriptedTransport:
def __init__(self, outcomes):
self.outcomes = iter(outcomes)
self.calls = 0
def __call__(self):
self.calls += 1
outcome = next(self.outcomes)
if isinstance(outcome, Exception):
raise outcome
return outcome
def test_eventual_success():
clock = FakeClock()
send = ScriptedTransport([ConnectionError("local fixture"), "ready"])
result = retry(send, clock.sleep, clock.now)
assert result == {"value": "ready", "elapsed": 1.0}
assert send.calls == 2
assert clock.delays == [1]
def test_exhaustion_does_not_sleep_again():
clock = FakeClock()
send = ScriptedTransport([ConnectionError("offline") for _ in range(3)])
with pytest.raises(ConnectionError, match="offline"):
retry(send, clock.sleep, clock.now)
assert send.calls == 3
assert clock.delays == [1, 2]
def test_permanent_error_is_not_retried():
clock = FakeClock()
send = ScriptedTransport([ValueError("bad input")])
with pytest.raises(ValueError, match="bad input"):
retry(send, clock.sleep, clock.now)
assert send.calls == 1
assert clock.delays == []python -m pytest -q test_retrying.pyExpected result: three passing tests without real sleeps or network calls. An independent deterministic demonstration uses an iterator as a tiny local operation:
from retrying import retry
values = iter(["ready"])
result = retry(lambda: next(values), lambda seconds: None, lambda: 50.0)
print(result)Expected output
{'value': 'ready', 'elapsed': 0.0}Patching: replace the name that code actually reads
Explicit injection is clearest for new code. Existing code may import a dependency at module level. If stamps.py contains from time import monotonic, then its function reads stamps.monotonic. Patching time.monotonic after the import does not replace that already-bound name. Patch the lookup location, and keep the patch scoped to the test. pytest's monkeypatch fixture restores its changes afterward.
For this optional example, save stamps.py and test_stamps.py exactly as shown. The test changes only its imported local module. It does not change the system clock. Prefer patching a narrow boundary; patching too deeply can create a substitute that no longer behaves like the real dependency.
from time import monotonic
def stamp():
return monotonic()import stamps
def test_stamp(monkeypatch):
monkeypatch.setattr(stamps, "monotonic", lambda: 42.0)
assert stamps.stamp() == 42.0Guided lab: make retry policy observable
Add an immediate-success case and a one-attempt failure case. The first should make one call with no delays; the second should also make one call with no delays before propagating its error. Together they catch unconditional initial waits and unnecessary final waits.
Then add a tiny fake storage list to an operation that appends a record before returning. Discuss what happens if the operation writes successfully but its acknowledgement is lost. Retrying can duplicate a side effect. This unit policy therefore assumes the supplied operation is safe to retry; it does not itself guarantee exactly-once behavior. Real services need an explicit idempotency contract and integration tests.
When a scripted test raises StopIteration, first check whether the script supplied enough outcomes. Do not catch it as a transient failure just to make the test green. A substitute should fail loudly when the test's arrangement is incomplete. Finally, explain which claims require a separate integration test: transport encoding, server status handling and durable writes cannot be established by these local doubles.
Questions worth asking
Why inject both sleep and now?
They represent different dependencies: waiting and observing time. The fake coordinates them so elapsed time reflects simulated delays. Replacing only sleep with a no-op while reading a real clock would make elapsed-duration expectations inconsistent and potentially flaky.
Does this prove an API will recover after two failures?
No. The outcomes are deliberately scripted fixtures. The suite proves the retry controller responds correctly to those supplied outcomes. Remote reliability, authentication and request formatting need separate evidence and are outside this network-free exercise.
Why avoid catching Exception in the retry loop?
A broad catch can repeat invalid inputs and programming defects that waiting cannot repair. The contract names ConnectionError as retryable. Production policies may recognize additional transient conditions, but each should be classified deliberately with a bounded retry budget.
When is a mock interaction assertion valuable?
When the interaction is itself required behavior, such as making no further attempt after exhaustion or requesting a particular delay. Assertions about incidental helper ordering usually couple tests too closely to implementation and make harmless refactoring expensive.
Why can patching the original library have no effect?
A from-import creates a name in the importing module. Later code reads that local name. Replace the attribute at the location where the tested code looks it up, rather than assuming every import remains linked to its original module attribute.
What is the principal retry risk for writes?
The first attempt may have taken effect even if its acknowledgement was lost. A repeated attempt can duplicate the side effect. Bounded retries limit effort, but idempotency keys or transactional semantics are separate design requirements; the fake does not supply them.
Practice, then compare your solution
1. Immediate success
Write expected calls, delays and elapsed time for success on attempt one.
Worked solution and reasoning
The expected values are one call, an empty delay list and 0.0 elapsed fake seconds. A real transport could consume time, but this scripted local operation does not advance FakeClock.
2. One attempt
Explain the outcome when attempts=1 and the operation raises ConnectionError.
Worked solution and reasoning
The original error propagates immediately after one call. No sleep is requested, because there is no next attempt. Test that fact explicitly to catch an off-by-one retry implementation.
Mastery checkpoint
Name each substitute by its responsibility, show a fast deterministic exhaustion test, and explain why the local retry controller cannot promise real-service reliability or exactly-once writes. Prefer small injected boundaries and reserve patching for names that cannot be passed explicitly.
Official documentation and next steps
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.