Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Mocking and Monkeypatching

The pytest-mock Plugin

Use pytest-mock's mocker fixture to patch with automatic cleanup, spy on real functions, create stubs and mock properties, and see when it beats unittest.mock.patch.

unittest.mock.patch is powerful, but its three forms (decorator, context manager, start/stop) all have rough edges in pytest. Decorators inject arguments that fight with fixtures, context managers add indentation, and start() needs a matching stop(). The pytest-mock plugin wraps all of it in one fixture, mocker, which patches things and cleans up automatically at the end of the test.

It adds no new mocking engine: the objects it gives you are the same MagicMock objects from unittest.mock. What it adds is convenience, plus two extras, spy and stub.

Install it with pip install pytest-mock. The in-browser examples below install it with micropip, exactly like the real thing. Once installed, the mocker fixture is available in every test with no import or configuration.

mocker.patch

mocker.patch takes the same arguments as unittest.mock.patch (target string, return_value, side_effect, autospec) and returns the mock. No with, no decorator.

Python mocker.patch, with cleanup for free

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Other helpers follow the same pattern: mocker.patch.object(obj, "name"), mocker.patch.dict(mapping, values), and mocker.patch.multiple(...). The mock classes are exposed as mocker.Mock, mocker.MagicMock, mocker.call and mocker.ANY, so test modules need no from unittest.mock import ... line.

mocker.spy: watch the real thing

A spy wraps a real function or method. It still runs the original code and returns its real result, but records every call, so you can assert on it. This is ideal when you want to confirm that something happened without replacing its behaviour.

Python Spying on a real method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A spy exposes two extra attributes: spy_return (the last real return value) and spy_exception (the last exception raised, if any).

mocker.stub: a callback that accepts anything

mocker.stub(name="...") creates a mock that is only a callable placeholder, such as a callback you pass to a function. It is a MagicMock with a name that shows up in failure messages.

Python A stub as a callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mocking properties and context managers

Properties live on the class, so patch them on the class with new_callable=mocker.PropertyMock:

Python
def test_property(mocker):
    mocker.patch.object(Account, "balance", new_callable=mocker.PropertyMock,
                        return_value=100)
    assert Account().balance == 100

A MagicMock already supports with, so a patched open or database connection works as a context manager. For files specifically, mocker.mock_open(read_data="line1\nline2") builds a ready-made fake for open(). Often tmp_path and real files are simpler and more trustworthy than mocking open, and you will see that in testing real projects.

mocker versus unittest.mock.patch

unittest.mock.patch mocker.patch
Cleanup with, decorator or manual stop() Automatic at test end
Works with fixtures Decorator form is awkward Yes, it is just a fixture
Spy / stub helpers No Yes
Needs a plugin No pytest-mock
Early undo Leave the with block mocker.stopall() or mocker.stop(mock)

The plugin is not required for good tests. Choose it when you patch a lot and want less ceremony. Mixing both in one project is fine because the mock objects are identical.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does mocker.spy(obj, "method") do?

    A spy keeps the original behaviour and adds call recording, so you can assert on how the real code was used.
  2. 2. When are patches made through mocker undone?

    mocker is a function-scoped fixture; its teardown stops every patch it started.
  3. 3. How do you patch a property?

    Properties are descriptors on the class, so patch the class attribute with a PropertyMock.
  4. 4. Which statement about pytest-mock is true?

    pytest-mock is a thin wrapper. The mocks are standard unittest.mock objects.

Summary

  • pip install pytest-mock gives every test a mocker fixture.
  • mocker.patch, patch.object and patch.dict behave like their unittest.mock twins but clean up automatically.
  • mocker.spy records calls to the real code; mocker.stub makes a named callback.
  • Use PropertyMock for properties, and autospec=True here too.
  • The plugin is convenience, not a requirement: both styles produce the same mock objects.

Next: Mocking Time, Files and the Network