Sub topic 13
Replacing dependencies with unittest.mock
This chapter assumes you can write pytest tests with plain assert, use fixtures, and use monkeypatch from the previous chapter. You should also know how Python imports names into modules. The chapter covers how to replace a collaborator with a test double. It also covers how to check the calls made to it, and the mistakes that most often make mock-based tests pass when they should fail.
Why replace a dependency
A unit test should check your code, not the network, the clock, or a payment provider. When a function sends email, calls an HTTP API, or charges a card, running the real thing makes the test slow and flaky. It can also cause side effects. A test double is an object that stands in for the real dependency. The standard library provides unittest.mock, and it works with pytest without any plugin.
There are two jobs a double can do:
- Provide canned answers, so the code under test has data to work with.
- Record how it was used, so the test can check that the code made the right calls.
Mock objects
A Mock accepts any attribute access and any call. Each attribute is another mock, created on first use. Every call is recorded.
# service.py
def send_welcome(client, user):
client.send(to=user, body="Welcome!")# test_service.py
from unittest.mock import Mock
from service import send_welcome
def test_send_welcome_sends_one_message():
client = Mock()
send_welcome(client, "ada")
client.send.assert_called_once_with(to="ada", body="Welcome!")Here the client is passed in as an argument, so no patching is needed. This is the simplest design to test. Passing collaborators as parameters is called dependency injection. Prefer it when you control the code.
Return values and side effects
Set return_value to give a call a canned answer. Set side_effect to raise an exception or to return a different value on each call.
# rates.py
def price_in_eur(client, usd):
rate = client.get_rate("USD", "EUR")
return round(usd * rate, 2)# test_rates.py
from unittest.mock import Mock
import pytest
from rates import price_in_eur
def test_price_uses_rate_from_client():
client = Mock()
client.get_rate.return_value = 0.5
assert price_in_eur(client, 10) == 5.0
client.get_rate.assert_called_once_with("USD", "EUR")
def test_price_propagates_client_failure():
client = Mock()
client.get_rate.side_effect = TimeoutError("rate service down")
with pytest.raises(TimeoutError):
price_in_eur(client, 10)The rules for side_effect are:
| Value of `side_effect` | Behavior on each call |
|---|---|
| An exception class or instance | Raises it |
| An iterable such as a list | Returns the next item, and raises `StopIteration` when exhausted. If an item is an exception, it is raised. |
| A function | Calls it with the same arguments and returns its result |
Checking calls
The common assertion methods on a mock are:
assert_called_once_with(...): exactly one call, with these arguments.assert_called_with(...): the most recent call used these arguments.assert_any_call(...): at least one call used these arguments.assert_not_called(): the mock was never called.call_countandcall_args_list: raw data for custom checks.
Use unittest.mock.call to describe a sequence:
from unittest.mock import Mock, call
def test_calls_in_order():
m = Mock()
m.save("a")
m.save("b")
assert m.save.call_args_list == [call("a"), call("b")]Patching: replacing a name in a module
When the dependency is imported inside the code under test, you cannot pass a double in. Use patch to replace the name for the duration of a test.
# notify.py
import requests
def fetch_status(url):
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()["status"]# test_notify.py
from unittest.mock import Mock, patch
import notify
def test_fetch_status_returns_status_field():
fake_response = Mock()
fake_response.json.return_value = {"status": "ok"}
with patch("notify.requests.get", return_value=fake_response) as fake_get:
assert notify.fetch_status("http://svc/health") == "ok"
fake_get.assert_called_once_with("http://svc/health", timeout=5)
fake_response.raise_for_status.assert_called_once_with()patch also works as a decorator. A decorator passes the mock as an extra argument, which conflicts with fixture arguments if you are not careful. Inside pytest, the with form is usually clearer.
Patch where the name is looked up
This is the most common mistake. patch("a.b") replaces the name b in module a. It does not change the object itself. If your module did from requests import get, then notify.get is a separate reference. Patching requests.get would not affect it.
# notify2.py
from requests import get
def fetch(url):
return get(url).text# test_notify2.py
from unittest.mock import Mock, patch
import notify2
def test_fetch_uses_name_in_notify2():
with patch("notify2.get", return_value=Mock(text="hi")):
assert notify2.fetch("http://x") == "hi"The rule is to patch the name in the module that uses it, not the module that defines it.
Patching with pytest
You can combine patch with a fixture to share the double across tests. patch used as a context manager inside a yield fixture ensures it is undone after the test.
# test_notify_fixture.py
from unittest.mock import Mock, patch
import pytest
import notify
@pytest.fixture
def fake_get():
response = Mock()
response.json.return_value = {"status": "ok"}
with patch("notify.requests.get", return_value=response) as m:
yield m
def test_fetch_status(fake_get):
assert notify.fetch_status("http://svc") == "ok"
fake_get.assert_called_once()For simple replacements such as environment variables or a single function, monkeypatch is often shorter. Choose patch when you need call recording or autospec.
Mocks that match the real thing
A plain Mock accepts everything. If you misspell a method, such as client.sned(...), the test passes without error and the bug stays hidden. Two tools prevent this.
Mock(spec=SomeClass)allows only attributes that exist on the class.create_autospec(obj)orpatch(..., autospec=True)also checks call signatures against the real function.
from unittest.mock import create_autospec
import pytest
class Client:
def send(self, to, body):
...
def test_autospec_rejects_wrong_arguments():
client = create_autospec(Client, instance=True)
client.send(to="ada", body="hi")
with pytest.raises(TypeError):
client.send("ada") # missing body
with pytest.raises(AttributeError):
client.sned(to="ada", body="hi") # typoOther tools in the module
MagicMockis aMockthat also supports magic methods such as__len__and__enter__.patchcreates aMagicMockby default, which is why a patched object works in awithstatement.AsyncMockreplaces coroutine functions. Awaiting a call returns the configuredreturn_value.patch.object(obj, "name")replaces an attribute on an object you already have.patch.dict(os.environ, {...})changes a dictionary temporarily and restores it afterward.
What not to mock
Mocking has costs. A test that mocks every collaborator checks only that your code calls those collaborators the way you wrote it. It will not fail when you refactor correctly, and it will not fail if the real dependency behaves differently from your double.
Follow these guidelines:
- Mock at the boundary of your system: network, clock, filesystem outside
tmp_path, third-party services. - Do not mock the code under test or your own pure functions. Call them for real.
- Prefer a small fake, such as an in-memory repository class, when several tests need consistent behavior.
- Assert on outcomes first. Check calls only when the call is the outcome, as with sending an email.
- Keep one integration test per boundary that uses the real dependency, so a wrong assumption in a double is eventually caught.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Patch has no effect, the real function runs | Patched the defining module instead of the name the code uses | Patch `module_under_test.name` |
| `AttributeError: module has no attribute` on patch | The target name does not exist in that module | Check the import style and spelling |
| Test passes but code is broken | Plain `Mock` accepted a wrong method or argument | Use `spec` or `autospec` |
| `StopIteration` from a mock | `side_effect` list ran out of values | Provide enough items or use a function |
| Mock leaks into other tests | Patch started with `patch.start()` and never stopped | Use `with`, a decorator, or a yield fixture |
Exercise
A module billing.py has from payments import charge and a function pay(amount) that calls charge(amount). Your test uses patch("payments.charge"), but the real charge still runs. Why, and what target should you patch?
Show answer
from payments import charge copies a reference into the billing namespace. Patching payments.charge changes the name in payments, but billing.charge still points to the original function. Patch the name where it is looked up: patch("billing.charge").
Exercise
You write client = Mock() and your test asserts client.send.assert_called_once_with(to="ada", body="Hi"). Later someone renames the real method to deliver, and the test still passes. How do you change the test setup so it fails?
Show answer
Create the double from the real class with a spec, for example client = create_autospec(Client, instance=True). Calls to send then raise AttributeError because Client no longer has that method, and calls with wrong arguments raise TypeError.