Sub topic 6
Isolating external dependencies with mocks
This chapter assumes you can write and run pytest tests, read a function signature, and have already generated basic unit tests with an assistant. It covers how to get an assistant to produce tests that replace external dependencies, and how to check that the mocks do real work.
Why mock a dependency
A unit test should run fast, give the same result every time, and fail only when your code is wrong. A function that calls an HTTP API, a database, or the system clock breaks all three. The network may be down, the data may change, and the test may be slow.
A mock is a stand-in object that records how it is called and returns values you choose. Replacing the real dependency with a mock lets the test check your logic alone.
An assistant will often write tests that call the real dependency, because the code it sees does. You must ask for mocks explicitly.
A worked example
Here is a function that takes an HTTP client as a parameter, along with a test that uses a Mock in place of the client.
from unittest.mock import Mock
def get_username(client, user_id):
response = client.get(f"/users/{user_id}")
return response.json()["name"]
def test_get_username_reads_name_from_response():
client = Mock()
client.get.return_value.json.return_value = {"name": "Ada"}
assert get_username(client, 7) == "Ada"
client.get.assert_called_once_with("/users/7")The test does two things:
- It sets up the fake response.
client.get.return_value.json.return_valuemeans "whenclient.get(...)is called, the result's.json()returns this dictionary." - It checks the output (
"Ada") and the interaction (getwas called once with"/users/7").
No network is involved, so the test runs in microseconds.
Prompting for mocks
Tell the assistant what to replace, how to replace it, and what to assert. A vague request such as "add tests" invites real calls.
Write pytest tests for get_username below.
Requirements:
- Do not make network calls. Pass a unittest.mock.Mock as the client.
- Set the response through client.get.return_value.json.return_value.
- Assert on the returned name and on the exact path passed to client.get.
- Add one test where the response lacks a "name" key and assert the error.
<code of get_username here>The last requirement matters. Assistants tend to write only the success path unless you ask for failure cases.
Where to patch
When the function creates its own dependency instead of receiving it, you must patch the name where it is looked up, not where it is defined. Suppose service.py contains import requests and calls requests.get(...). The patch target is service.requests.get.
from unittest.mock import patch
import service
def test_fetch_uses_requests_get():
with patch("service.requests.get") as fake_get:
fake_get.return_value.json.return_value = {"name": "Ada"}
assert service.fetch_name(7) == "Ada"
fake_get.assert_called_once()Assistants often patch the wrong path, such as requests.get when the code did from requests import get. The test then passes a real call through, or fails with a confusing error. If you see this, tell the assistant which import style your module uses.
Common errors in generated mocks
| Problem | What it looks like | Fix |
|---|---|---|
| Mock returns a mock | Test asserts `result == Mock()` or never sets `return_value` | Set the return value explicitly |
| Over-specified calls | Asserts every internal call, so refactors break the test | Assert only calls that are part of the contract |
| Wrong patch target | Real network call still happens | Patch where the name is used |
| Mock hides a typo | `client.gett(...)` succeeds on a plain `Mock` | Use `Mock(spec=RealClient)` or `create_autospec` |
Check that the mock earns its place
Before you accept a generated mocked test, run one check: change the code under test so it is wrong, and confirm the test fails. For get_username, change ["name"] to ["email"]. If the test still passes, the mock is returning whatever the code asks for, and the test proves nothing.
Exercise
A generated test patches requests.get, but the module under test uses from requests import get and calls get(url). The test still hits the network. Why, and what is the correct patch target?
Show answer
The module bound its own name get at import time, so patching requests.get changes a different reference. Patch the name where the module looks it up, for example service.get, where service is the module under test.
Exercise
A generated test uses a plain Mock() client and passes. You rename the real method from get to fetch in the client class, and the test still passes. How do you make the test catch this?
Show answer
Create the mock with a spec, for example Mock(spec=HttpClient) or create_autospec(HttpClient). The mock then raises AttributeError for client.get, because the real class no longer has it.