1. Home
  2. Blog
  3. Test Automation

Test Automation

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.

9 min read
Pytest mock: mocker.patch, spy, side_effect and autospec explained

Key takeaways

  • pytest mock means the mocker fixture from the pytest-mock plugin: a thin wrapper around unittest.mock that undoes patches after each test.
  • return_value fixes what a fake returns; side_effect returns a sequence, raises exceptions or runs a function.
  • mocker.spy watches a real function without replacing it.
  • Without autospec, a mock accepted a call with wrong arguments; with it, the same call raised TypeError.

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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

Python abstract class explained: ABC and abstractmethod, abstract properties, shared logic with super, register, collections.abc and ABC vs Protocol, tested.

Read article →
Software Development

Python Subprocess Explained: run, Capture Output, Timeouts and Safety

Python subprocess explained with tested examples: run, capture_output, check, timeouts, input, environment, shell injection, encoding on Windows and Popen streaming.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →