Pytest Mock: mocker.patch, spy, side_effect and autospec Explained
pytest-mock gives every test a mocker fixture that patches functions, fakes API responses, simulates failures and checks how code was called, then cleans everything up automatically. Learn mocker.patch, return_value and side_effect, call assertions, spy, PropertyMock, autospec and the mistakes that make mock tests pass for the wrong reasons, with 9 passing tests.
- pytest mock means the
mockerfixture from the pytest-mock plugin: a thin wrapper aroundunittest.mockthat undoes patches after each test. return_valuefixes what a fake returns;side_effectreturns a sequence, raises exceptions or runs a function.mocker.spywatches a real function without replacing it.- Without
autospec, a mock accepted a call with wrong arguments; with it, the same call raisedTypeError.
Unit tests should not call real weather APIs, payment gateways or email servers. They should be fast, deterministic and able to simulate failures that are hard to trigger for real. Mocking makes that possible, and in pytest the most convenient way to mock is the pytest mock plugin, pytest-mock, which provides a mocker fixture with the full power of Python’s unittest.mock and none of the cleanup headaches.
We wrote a small weather module and 9 tests, all passing on Python 3.13.6 with pytest 9.2.0 and pytest-mock 3.17.0. For mocking concepts without the plugin, see our Python mocking guide.
What is pytest-mock?
pytest-mock is a pytest plugin that adds the mocker fixture. Its mocker.patch has the same API as unittest.mock.patch, but you call it as a normal function inside the test instead of using decorators or with blocks, and every patch is reverted automatically when the test finishes, even if it fails. The fixture also exposes mocker.Mock, mocker.MagicMock, mocker.PropertyMock and a useful extra, mocker.spy.
Installing pytest-mock
pip install pytest-mock
That is all; pytest discovers the plugin and every test can now request mocker as an argument, just like any pytest fixture.
The code under test
# weather.py
import requests_like as http
import time
class WeatherError(Exception): pass
def get_temp(city):
r = http.get(f"https://api.example.com/weather/{city}", timeout=5)
if r.status_code != 200:
raise WeatherError(f"bad status {r.status_code}")
return r.json()["temp_c"]
def advice(city):
t = get_temp(city)
return "jacket" if t < 15 else "t-shirt"
def get_with_retry(city, tries=3):
for i in range(tries):
try:
return get_temp(city)
except WeatherError:
time.sleep(1)
raise WeatherError("gave up")
The requests_like module is a stand-in for an HTTP library; its get raises an error if anything tries to use the real network, so any missed mock fails loudly.
Example 1: mocker.patch with return_value
def test_patch_return_value(mocker):
mocker.patch("weather.get_temp", return_value=10)
assert weather.advice("Pune") == "jacket"
mocker.patch takes the dotted path of the name to replace and installs a MagicMock there. advice looks up get_temp in the weather module, so patching weather.get_temp controls exactly what it sees. As with all patching, target the module where the name is looked up; our monkeypatch guide shows what happens when you patch the wrong place.
Example 2: faking an HTTP response
def test_mock_http_response(mocker):
fake = mocker.Mock(status_code=200)
fake.json.return_value = {"temp_c": 28}
get = mocker.patch("weather.http.get", return_value=fake)
assert weather.get_temp("Goa") == 28
get.assert_called_once_with("https://api.example.com/weather/Goa", timeout=5)
Patch at the network boundary and build a fake response object. A Mock accepts attributes in its constructor and lets you configure methods through .return_value. The final assertion checks the URL and the timeout argument, so the test also verifies how the API was called, not just what was returned. More on this pattern in our API testing guide.
Example 3: side_effect as a sequence
def test_side_effect_sequence(mocker):
mocker.patch("weather.time.sleep")
m = mocker.patch("weather.get_temp",
side_effect=[weather.WeatherError("x"), weather.WeatherError("y"), 21])
assert weather.get_with_retry("Delhi") == 21
assert m.call_count == 3
When side_effect is a list, each call takes the next item; exception instances are raised, other values returned. Two failures followed by success exercise the retry logic precisely. We also patched time.sleep, so the test ran instantly instead of waiting two seconds.
Example 4: side_effect that always fails
def test_side_effect_exception(mocker):
mocker.patch("weather.time.sleep")
mocker.patch("weather.get_temp", side_effect=weather.WeatherError("down"))
with pytest.raises(weather.WeatherError, match="gave up"):
weather.get_with_retry("Delhi")
A single exception as side_effect is raised on every call, perfect for testing outage handling. Combined with pytest raises, the test checks that the function gives up with the right error after its retries. side_effect can also be a function that receives the call’s arguments and computes a result.
Example 5: spy on a real function
def test_spy(mocker):
fake = mocker.Mock(status_code=200); fake.json.return_value = {"temp_c": 5}
mocker.patch("weather.http.get", return_value=fake)
spy = mocker.spy(weather, "get_temp")
assert weather.advice("Leh") == "jacket"
spy.assert_called_once_with("Leh")
assert spy.spy_return == 5
A spy wraps the real function: it still runs, but calls are recorded, and spy_return holds the last return value. Use spies when you want real behaviour plus evidence of how a function was called. This is a pytest-mock feature, not part of unittest.mock.
Example 6: PropertyMock
def test_property_mock(mocker):
mocker.patch.object(weather.Cache, "size",
new_callable=mocker.PropertyMock, return_value=99)
assert weather.Cache().size == 99
Properties live on the class, so patch the class attribute with PropertyMock. mocker.patch.object takes the object and attribute name instead of a dotted string, which is handy when you already have the class imported.
Example 7: autospec catches wrong calls
# without autospec: this test FAILED only because of a typo in the assertion
def test_no_autospec_hides_bug(mocker):
m = mocker.patch("weather.get_temp", return_value=1)
weather.get_temp("Pune", "extra", units="F") # wrong arguments, accepted silently
m.asert_called_once()
# AttributeError: 'asert_called_once' is not a valid assertion. Did you mean: 'assert_called_once'?
# with autospec
def test_autospec_catches_wrong_signature(mocker):
mocker.patch("weather.get_temp", autospec=True, return_value=1)
with pytest.raises(TypeError):
weather.get_temp("Pune", "extra")
A plain MagicMock accepts any arguments and any attribute, so code that calls a function with the wrong signature still “works” in tests and breaks in production. autospec=True makes the mock copy the real signature, raising TypeError on bad calls. Modern unittest.mock also rejects misspelled assertion methods like asert_called_once, which is what caught our typo; older versions silently passed.
Tip: use autospec=True by default when patching functions and classes. It keeps mocks honest when the real code changes.
Example 8: inspecting call history
def test_call_args(mocker):
m = mocker.patch("weather.get_temp", return_value=30)
weather.advice("Agra"); weather.advice("Jaipur")
assert [c.args for c in m.call_args_list] == [("Agra",), ("Jaipur",)]
Every mock records its calls. Useful attributes and assertions:
| API | Checks |
|---|---|
assert_called_once_with(...) |
Exactly one call with these arguments |
assert_called_with(...) |
The most recent call’s arguments |
assert_any_call(...) |
Some call had these arguments |
assert_not_called() |
Never called |
call_count, call_args_list |
Number and details of calls |
Example 9: automatic cleanup
def test_restored_after():
with pytest.raises(RuntimeError, match="real network"):
weather.get_temp("Pune")
This test uses no mocks and runs after the others. It hit the real http.get stand-in and got its error, proving every earlier patch was undone. Leaking patches between tests is a major source of order-dependent flaky tests, and the fixture removes that risk.
mocker vs monkeypatch vs unittest.mock
| Tool | Strength |
|---|---|
mocker (pytest-mock) |
Full mock objects, call assertions, spy, automatic cleanup |
monkeypatch (built in) |
Simple replacements, env vars, dict items, no extra install |
unittest.mock.patch |
Same power, used as decorator or context manager |
They are complementary: use monkeypatch for environment and simple stubs, mocker when you need to assert calls or simulate sequences. The vocabulary of fakes, stubs and spies is covered in test doubles.
Tips for good mock tests
- Mock at the boundary (network, clock, filesystem), not your own business logic.
- Prefer
autospec=True. - Assert outcomes first, interactions second; over-asserting calls makes tests brittle.
- Patch where a name is used, not where it is defined.
- Keep at least a few integration tests that use the real dependency, so mocks do not drift from reality.
patch.dict, patch.object and AsyncMock
def test_env(mocker):
mocker.patch.dict(os.environ, {"API_KEY": "test-key"})
assert config_mod.api_key() == "test-key"
def test_env_restored():
assert os.environ.get("API_KEY") is None
def test_object(mocker):
m = mocker.patch.object(config_mod.Client, "fetch", return_value={"ok": True})
assert config_mod.Client().fetch("/x") == {"ok": True}
m.assert_called_once_with("/x")
def test_async(mocker):
m = mocker.patch("config_mod.get_price",
new_callable=mocker.AsyncMock, return_value=42)
assert asyncio.run(config_mod.total(3)) == 126
m.assert_awaited_once_with()
# 4 passed in 0.02s
Three more helpers cover most of what is left. mocker.patch.dict adds or changes keys in a dictionary, most often os.environ, and puts the original back afterwards: the second test proved that API_KEY was gone again once the first test finished. mocker.patch.object takes the object itself rather than a dotted string, so a typo in the attribute name fails at once instead of patching the wrong place.
For coroutines, pass new_callable=mocker.AsyncMock. Awaiting the mock returns return_value, and assert_awaited_once_with checks it was actually awaited, not just called, which catches the classic bug of forgetting await. We drove it with asyncio.run, so no async plugin was needed; with pytest-asyncio installed you could write async def tests directly, though we did not run that variant. Environment handling is covered further in our environment variables guide.
Final thoughts
pytest mock combines the full unittest.mock toolkit with pytest’s fixture model: patch with one line, shape behaviour with return_value and side_effect, observe with call assertions and spies, and never worry about cleanup. Add autospec so your fakes respect real signatures, and mock only at the edges of your system. Your tests will be fast, focused and honest. For the unittest side of the story, see our Python unittest guide.
Frequently asked questions
What is mocker in pytest?
mocker is a fixture provided by the pytest-mock plugin. It wraps unittest.mock so you can patch objects inside a test, and it undoes all patches automatically when the test ends.
What is the difference between return_value and side_effect?
return_value is returned on every call. side_effect can return a different item per call from a list, raise an exception, or call a function to compute the result.
What does mocker.spy do?
It wraps a real function so it still runs normally, while recording calls, arguments and the return value so the test can assert on them.
Why should I use autospec when mocking?
A plain mock accepts any arguments, hiding calls that would fail on the real function. autospec copies the real signature, so wrong calls raise TypeError in your tests.
Should I use pytest-mock or monkeypatch?
Use monkeypatch for simple replacements and environment variables. Use pytest-mock when you need mock objects, call assertions, side effect sequences or spies.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.