Dependency Injection and Test Doubles
unittest.mock and Controlled Dependencies
BOTIE
Python added unittest.mock to the standard library in version 3.3. It can record calls and supply controlled responses. An explicit callable parameter also makes that boundary visible without a mocking library. The resulting test still needs a clear account of what it establishes and which real integrations remain unchecked.
Sources for this history
The Report Test Needed a Live Thermometer
Botie's shared report rule is tested, but its next test depends on whichever readings a connected device returns. A stopped device or a changed temperature makes the test unreliable before the calculation is even checked.
The composition lesson gave the collector a source with a read method. We can retain that interface and supply a controlled source, then record how the existing collector uses it.
Both sources are supplied local records. The blocks do not contact a sensor. The Python collector also handles calibration, per-record limits and a complete report payload.
Step 1 of 1
Retain the complete source and sink agreements
A source supplies named records; the collector builds the complete payload before the sink sees it.
| Boundary | Data | Controlled check |
|---|---|---|
| ReadingSource.read | Named Celsius records with optional limits | Snapshot ownership and one read |
| collect_report | Numerical report plus notes | Existing calculation and validation |
| ReportSink.send | One complete payload | Acceptance and acknowledgment |
ReadingSource.read
- Data
- Named Celsius records with optional limits
- Controlled check
- Snapshot ownership and one read
collect_report
- Data
- Numerical report plus notes
- Controlled check
- Existing calculation and validation
ReportSink.send
- Data
- One complete payload
- Controlled check
- Acceptance and acknowledgment
Supply the capability the report needs
The input source changes, while the alert calculation stays the same. Returning the original records keeps the house name attached to each reading.
Replace the sensor input
The report should work with a saved recording while the physical sensor is unavailable. The two source names below contain small lists of named readings. Select one source, then keep its readings at or above the shared limit.
BOTIE
Selected source records that reach the alert limit
- house
- south
- temperature_c
- 25
| house | temperature_c |
|---|---|
| south | 25 |
Follow the operations
1. Source name to use
recording
2. Recorded and device readings
- recording
- house
- north
- temperature_c
- 18
- house
- south
- temperature_c
- 25
house temperature_c north 18 south 25 - device
- house
- north
- temperature_c
- 30
- house
- south
- temperature_c
- 19
house temperature_c north 30 south 19
3. Look up one name
- house
- north
- temperature_c
- 18
- house
- south
- temperature_c
- 25
house temperature_c north 18 south 25 4. Read a field from every record
- 018
- 125
5. Alert limit in C
25
6. Check the alert limit
- 0false
- 1true
7. Keep flagged entries
- house
- south
- temperature_c
- 25
house temperature_c south 25 8. Result
- house
- south
- temperature_c
- 25
house temperature_c south 25
Both sources are supplied local records. The blocks do not contact a sensor. The Python collector also handles calibration, per-record limits and a complete report payload.
1. Supply the capability the report needs
The existing collector asks ReadingSource.read for named Celsius records. collect_report then applies calibration, resolves per-record limits and builds its report-and-notes payload. Passing the source explicitly keeps device construction out of that calculation.
Keep the role small. A source can be a local recording, a device client or a test object, provided it supplies the stated operation and data contract. There is no need for an injection framework merely to pass one object.
Supply the named-record interface
The retained collector expects named Celsius records from read(). This small fixture shows only that input boundary.
class FixedSource:
def read(self):
return [{"house":"north", "temperature_c":18.0}]
print(FixedSource().read())[{'house': 'north', 'temperature_c': 18.0}]The complete collect_report helper keeps calibration, per-record limit rules and report construction separate from this source.
2. Observe calls as well as the result
A result can happen to match even when a collector reads twice or uses the wrong operation. A recording source lets a test inspect that interaction. Check calls when they are part of the requirement, rather than freezing every private implementation detail.
A stub supplies controlled responses. A fake implements a simplified working substitute. Mock libraries can record interactions and assert expectations. These roles describe testing behavior; they do not guarantee that a substitute matches a real device.
Record a named-record read
The fixed source counts use of its method. The challenge adds supplied records and independent ownership.
class FixedSource:
def __init__(self):
self.calls = 0
def read(self):
self.calls += 1
return [{"house":"north", "temperature_c":12.0}]
source = FixedSource()
print(source.read())
print(source.calls)[{'house': 'north', 'temperature_c': 12.0}]
1The count comes from actual method calls. A configurable fixture must also protect its supplied record snapshot.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
What has the test controlled?
Question data
collect_report receives a source whose read() returns a fixed list of named Celsius record dictionaries.3. Constrain a substitute to the real interface
A permissive mock can accept a misspelled method such as raed even though the actual source only exposes read. unittest.mock provides spec and autospec controls to restrict attributes or call signatures. They do not validate every runtime reading or establish a working connection.
Exercise known failures too. A source timeout should reach the layer that has a deliberate recovery policy. Silently substituting an empty batch would turn missing data into a successful report with no alerts.
4. Keep delivery effects local during coordination tests
The earlier deliver_report function sends one complete payload to ReportSink.send. A recording sink can retain that payload and fail either before acceptance or after accepting it, exposing the difference without contacting a destination.
A raised error after acceptance does not prove that nothing happened. Keep the coordinator’s no-retry policy visible and check both attempted calls and accepted payloads. A real destination still needs its own authorization, acknowledgment and reconciliation behavior.
Check yourself
Questions on Parts 1 to 4
Question 1 of 4
Which practice can expose the interface mismatch?
Question data
The actual source has read(), but a permissive mock accepts raed().Try it with Botie
Build with Botie
Write and run Python