Patch the Name Actually Looked Up
Core idea
A mock is a configurable substitute that records interactions. patch or patch.object temporarily replaces a name or attribute and restores it on exit. Patch the reference used by the subject, not merely the original definition: a from-import can create a separate binding. autospec can help catch incompatible call signatures.
from unittest.mock import Mocksend = Mock(return_value='queued')print(send('parcel-7'))send.assert_called_once_with('parcel-7')print(send.call_count)The mock returns a configured value and verifies the call arguments.
Replace the consumer binding
from types import SimpleNamespacefrom unittest.mock import patchsource = SimpleNamespace(rate=lambda: 5)consumer = SimpleNamespace(rate=source.rate)def cost(): return consumer.rate() * 2with patch.object(source, 'rate', return_value=8): print(cost())with patch.object(consumer, 'rate', return_value=8) as mock_rate: print(cost()) mock_rate.assert_called_once_with()print(cost())Patching source does not change the copied reference; patching the consumer works and is restored.
Common mistake
Do not replace everything in a test. Assert meaningful behavior and interactions at boundaries, not incidental implementation details. Use autospec where a known callable signature matters; it does not validate all return contracts.
Practice
Adapt the consumer example to accept a quantity argument. Patch the consumer rate, assert the exact argument and verify restoration after the context.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mocks and patching
Check your understanding of mocks and patching.
What is printed?
from unittest.mock import Mockm=Mock(return_value=6)print(m(), m.call_count)What is printed?
from types import SimpleNamespacefrom unittest.mock import patchx=SimpleNamespace(n=2)with patch.object(x,'n',9): print(x.n)print(x.n)Where should a copied imported binding be patched?
What does autospec help verify?