Sub topic 6
Isolating External Dependencies with Mocks
This chapter assumes you can write and run pytest tests, read a Python function signature, and have already generated simple unit tests with an assistant. You do not need prior experience with unittest.mock.
Why isolate dependencies
A unit test should check your code, not the network, the clock, or a database. When a function calls an HTTP API, reads a file, or asks for the current time, a test that uses the real thing has three problems:
- It is slow, because each call waits on I/O.
- It is flaky, because the outside world can be down, change, or return different data each run.
- It can cause damage, such as sending an email or charging a card.
A test double is an object that stands in for a real dependency during a test. A mock is a test double that records how it was called, so the test can check both what the code returned and what it asked the dependency to do. Python ships with unittest.mock, and pytest works with it directly.
Assistants are good at writing the setup for mocks, which is repetitive. They are weaker at deciding what should be mocked and at keeping mocks faithful to the real dependency. This chapter covers both sides.
A first mock
The running example is a function that takes an HTTP client as a parameter and reads a field from the response.
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 makes no network call. Here is what each part does:
Mock()creates an object that accepts any attribute access or call and returns another mock.client.get.return_value.json.return_value = {"name": "Ada"}sets the chain of results. Callingclient.get(...)returns a mock, and calling.json()on that mock returns the dictionary.assert get_username(client, 7) == "Ada"checks the return value.client.get.assert_called_once_with("/users/7")checks the interaction: the function must callgetexactly once with that path.
The two assertions check different things. The first confirms the output. The second confirms the request that produced it. If the function built the wrong URL, the first assertion would still pass, because the mock returns the same data no matter what path it receives. Only the second assertion catches that bug.
Where to patch
get_username receives its client as an argument, so the test can pass a mock in directly. This is called dependency injection, and it is the easiest design to test. Many functions instead import their dependency and call it by name. For those you use unittest.mock.patch to replace the name temporarily.
import requests
def fetch_status(url):
response = requests.get(url, timeout=5)
return response.status_codefrom unittest.mock import patch
from status import fetch_status
def test_fetch_status_returns_code():
with patch("status.requests.get") as fake_get:
fake_get.return_value.status_code = 204
assert fetch_status("https://example.com/health") == 204
fake_get.assert_called_once_with("https://example.com/health", timeout=5)The most common patching error is patching the wrong name. The rule is to patch where the name is looked up, not where it is defined. Here status.py runs import requests and calls requests.get, so the test patches status.requests.get. If the module had written from requests import get, the name get would live in status, and the target would be status.get. Patching requests.get in that case would change the original but leave the copy that status already holds untouched, and the real network call would run.
Assistants often get this wrong, because they see the definition site in the context you gave them. When you generate patch-based tests, include the import lines of the module under test in the prompt.
Prompting for mocks
The assistant needs to know which collaborators are external and how you want them replaced. This prompt follows the pattern from earlier chapters, with mock-specific constraints added.
Write pytest tests for get_username below.
Context:
- The client is injected, so pass a unittest.mock.Mock instead of patching.
- Tests live in tests/test_users.py.
- The real client returns an object whose .json() method gives a dict.
Requirements:
- No network access in any test.
- Assert on the return value and on the exact path passed to client.get.
- Add a test for the case where the response has no "name" key. Expect KeyError.
- Do not change the function under test.
<code of get_username here>Each line closes a common failure. Stating that the client is injected prevents unneeded patch calls. Naming the real return shape keeps the mock from inventing one. Asking for assertions on the call arguments avoids tests that only check the return value.
Keeping mocks faithful with autospec
A plain Mock accepts anything. If you misspell client.gett, it returns a new mock and the test passes while the real code would crash. If the real method takes two arguments and you call it with one, the mock does not complain either.
create_autospec and patch(..., autospec=True) build a mock that copies the signature of the real object. Calls with the wrong arguments or missing attributes then raise errors.
from unittest.mock import create_autospec
class UserClient:
def get(self, path):
raise NotImplementedError
def get_username(client, user_id):
response = client.get(f"/users/{user_id}")
return response.json()["name"]
def test_get_username_with_spec():
client = create_autospec(UserClient, instance=True)
client.get.return_value.json.return_value = {"name": "Ada"}
assert get_username(client, 7) == "Ada"
client.get.assert_called_once_with("/users/7")Here client.get has the signature (path). A call like client.get("/users/7", retries=3) would raise TypeError in the test, matching what the real class would do. This protects you when the real class changes later, because a test with a spec will start failing when the signatures drift apart.
Ask the assistant for autospec explicitly. Its default output is usually a bare Mock.
Other dependencies worth isolating
The same approach applies beyond HTTP:
| Dependency | Typical replacement | Notes |
|---|---|---|
| HTTP client | `Mock` or `patch` on `requests.get` | Set `status_code` and `json()` |
| Current time | `patch` on a clock function, or a fixed value passed in | Avoids tests that fail at midnight |
| File system | pytest's `tmp_path` fixture | A real temporary directory is often better than a mock |
| Environment variables | `monkeypatch.setenv` | Restored automatically after the test |
| Randomness | Seed it, or patch the call | Makes results repeatable |
Mocking is not always the right tool. For files, tmp_path exercises real file behavior and is simple. A mock of open can pass while the real code fails on encoding or permissions. Choose the lightest real thing that is still safe and fast.
Simulating failures
Mocks are the easiest way to test error handling, because you can make a dependency fail on demand. Set side_effect to an exception and the mock raises it when called.
import pytest
from unittest.mock import Mock
def safe_get_username(client, user_id):
try:
response = client.get(f"/users/{user_id}")
except TimeoutError:
return None
return response.json()["name"]
def test_safe_get_username_returns_none_on_timeout():
client = Mock()
client.get.side_effect = TimeoutError
assert safe_get_username(client, 7) is None
client.get.assert_called_once_with("/users/7")
def test_safe_get_username_does_not_hide_other_errors():
client = Mock()
client.get.side_effect = ConnectionError
with pytest.raises(ConnectionError):
safe_get_username(client, 7)The second test checks that the function does not swallow errors it was not meant to handle. Assistants tend to write only the happy path and the one error you named, so ask for "an error that should propagate" as well.
Common errors in generated mock tests
Review mock-based tests with these checks:
- The test asserts on the mock's own setup. If you set
return_value = 5and then assert the result equals 5 without any real logic between them, the test proves nothing. Make sure the function does some work on the data. - The wrong patch target. The real call still runs, or the patch has no effect. Confirm the target is the name as imported by the module under test.
- Over-mocking. The test replaces so many pieces, including your own helper functions, that it only checks that mocks call other mocks. Mock the boundary with the outside world, not your own logic.
- No call assertions. Without
assert_called_once_with, wrong arguments go unnoticed. - Brittle call assertions. Asserting on private helper calls or call order ties the test to the implementation. A refactor then breaks the test without breaking behavior.
- A mock that does not match reality. If the real API returns
{"user": {"name": ...}}and the mock returns{"name": ...}, the test passes and production fails. Compare the mock's data to a real sample response or the API documentation.
Mocks have a limit that no review fixes: they verify your code against your belief about the dependency. If that belief is wrong, every test passes. Keep at least one integration test, run less often or in CI, that calls the real service or a realistic local substitute.
A short review exercise
Take any function in your project that calls an external service. Generate mock-based tests for it, then run a quick mutation check by hand. Change the URL, an argument, or the key being read, and rerun the tests. At least one test should fail for each change. A change that no test detects shows a missing assertion.
Exercise
A function runs from requests import get at the top of status.py and calls get(url). A generated test uses patch("requests.get"), yet the test makes a real network call. Why does this happen, and what should the patch target be?
Show answer
from requests import get copies the name get into the status module when it is imported. Patching requests.get replaces the attribute on the requests module, but status.get still points to the original function. Patch the name where it is looked up: patch("status.get").
Exercise
A test sets client.get.return_value.json.return_value = {"name": "Ada"} and asserts only that get_username(client, 7) == "Ada". Which bug would this test miss, and what assertion fixes it?
Show answer
It would miss a wrong request path, such as /user/7 instead of /users/7, because the mock returns the same data for any call. Add client.get.assert_called_once_with("/users/7").