Sub topic 13
Replacing dependencies with unittest.mock
This chapter assumes you can write pytest tests, use fixtures, and read a traceback. You also need to know how Python imports modules and passes arguments to functions.
Why replace a dependency
A unit test should check your code, not the network, the clock, or a third-party service. When a function calls an email client or an HTTP API, a real call makes the test slow, flaky, and sometimes harmful. A test double is an object that stands in for the real dependency. The standard library provides unittest.mock for this.
Mock objects record calls
A Mock accepts any attribute access and any call. It remembers how it was used, so the test can check that afterward.
# 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 the test hands over a Mock directly. No real message is sent. If send_welcome called send twice, or with different arguments, the assertion would fail.
Useful assertions on a mock:
| Assertion | Passes when |
|---|---|
| `assert_called_once_with(...)` | The mock was called exactly once, with these arguments |
| `assert_called_with(...)` | The most recent call used these arguments |
| `assert_not_called()` | The mock was never called |
| `call_count` | Attribute holding the number of calls |
Controlling return values
A mock can also supply data. Set return_value for a normal result, or side_effect to raise an exception.
from unittest.mock import Mock
import pytest
def test_return_value_and_side_effect():
client = Mock()
client.fetch.return_value = {"name": "ada"}
assert client.fetch("ada") == {"name": "ada"}
client.fetch.side_effect = TimeoutError("slow")
with pytest.raises(TimeoutError):
client.fetch("ada")Setting side_effect to an exception is the easiest way to test your error handling without causing a real failure.
Patching names your code looks up
Often the dependency is not passed in. It is imported inside the module under test. In that case use unittest.mock.patch, which swaps a name for a mock during a test and restores it afterward.
# notifier.py
import requests
def fetch_status(url):
return requests.get(url).status_code# test_notifier.py
from unittest.mock import patch
from notifier import fetch_status
def test_fetch_status_uses_requests():
with patch("notifier.requests.get") as fake_get:
fake_get.return_value.status_code = 200
assert fetch_status("http://x.test") == 200
fake_get.assert_called_once_with("http://x.test")Keeping mocks honest
A plain Mock accepts any call, so a typo like client.snd(...) passes silently. Use create_autospec or patch(..., autospec=True) to copy the real signature. A call with the wrong arguments then raises TypeError.
from unittest.mock import create_autospec
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")
try:
client.send("ada")
except TypeError:
pass
else:
raise AssertionError("expected TypeError")Exercise
A module has from requests import get and calls get(url) inside fetch_status. Your test uses patch("requests.get"), yet the real network is still called. What is the correct patch target and why?
Show answer
Patch "notifier.get", where notifier is the module under test. The from import copied the name get into the module's namespace at import time. Replacing requests.get later does not change that copy, so the code keeps using the original function.
Exercise
How can you make a mock client raise ConnectionError on its first call, so you can test your retry handling?
Show answer
Set client.send.side_effect = ConnectionError("down"). Any call to client.send then raises that exception.