Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Mocking and Monkeypatching

patch, Where to Patch and autospec

Use unittest.mock.patch as a decorator or context manager in pytest, learn the golden rule of where to patch, and use autospec so mocks cannot drift from the real API.

Mocks are easy to create. The hard part is getting them into the code under test when that code builds its own collaborators or imports them at the top of a module. unittest.mock.patch solves this: it temporarily replaces a name with a mock and restores it afterwards.

Most of the confusion around patch comes from one question: which name do I patch? This lesson gives you the rule, shows the three ways to apply patch, and introduces autospec, the feature that stops your mocks from lying.

The golden rule: patch where it is looked up

Imagine two modules:

Python
# weather.py
import requests

def temperature(city):
    data = requests.get(f"https://api.example.com/{city}").json()
    return data["temp"]
Python
# report.py
from weather import temperature
from time import sleep

def summary(city):
    return f"{city}: {temperature(city)} degrees"

report.py does from weather import temperature, which copies the name into report's namespace. Patching weather.temperature replaces the original, but report.temperature still points at the old function. You must patch the name in the module that uses it: report.temperature.

flowchart LR
    W["weather.temperature<br/>(original function)"]
    R["report.temperature<br/>(copy of the name)"]
    W -. "from weather import temperature" .-> R
    S["summary() looks up report.temperature"] --> R
    P1["patch('weather.temperature')"] -->|"does NOT affect"| R
    P2["patch('report.temperature')"] -->|"replaces what summary sees"| R

Patch the name at the place where the code under test looks it up.

Python Wrong target versus right target

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.

If the module did import weather and called weather.temperature(city), then patching weather.temperature would be correct, because the lookup happens through the module object every time. Read the import line first, then choose.

Three ways to apply patch

All three forms install the same MagicMock and undo it afterwards.

Python
from unittest.mock import patch

# 1. context manager: scoped to the with block
def test_a():
    with patch("report.temperature") as fake_temp:
        fake_temp.return_value = 18
        ...

# 2. decorator: the mock is passed as an extra argument
@patch("report.temperature")
def test_b(fake_temp):
    fake_temp.return_value = 18
    ...

# 3. start/stop (useful inside fixtures)
patcher = patch("report.temperature")
fake_temp = patcher.start()
...
patcher.stop()

With decorators, pytest cannot see the extra argument as a fixture request because patch consumes it. Stacked decorators pass mocks bottom-up: the decorator closest to the function supplies the first argument. When tests also use fixtures, put the mock arguments first, or avoid the decorator and use with or the pytest-mock plugin.

Useful keyword arguments: return_value=..., side_effect=..., new=value (replace with a specific object instead of a mock; no extra argument is passed), and patch.object(SomeClass, "method") and patch.dict(os.environ, {...}) for objects and dictionaries.

Python patch.object and patch.dict

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.

autospec: mocks that cannot drift

A plain mock accepts any call. Suppose temperature(city) is later changed to temperature(city, unit). A test using patch("report.temperature") keeps passing even though the real function now needs two arguments, because the mock never complained. The test passes, production breaks.

autospec=True makes the mock copy the signature and attributes of the real object. Calling it with wrong arguments, or accessing a missing attribute, raises an error.

Python autospec catches a wrong call

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.

Two details worth remembering. With autospec=True on a method patched from the class, the mock receives self as its first argument, so assertions include the instance. create_autospec(Class, instance=True) builds a ready-made fake object whose methods have the real signatures, ideal for dependency injection.

You can also write spec=Class (checks attribute names only) or spec_set=Class (also forbids setting unknown attributes). Prefer autospec unless you hit a limitation.

Patching a class

When code does client = Client(...), patch the class in the module where it is used. The mock class returns return_value, which stands for the instance:

Python Patching a class used by the code

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.

Habits that keep patching healthy

  • Patch at the boundary. Replace the HTTP client, the clock, the filesystem call: things outside your process. Do not patch your own pure functions.
  • Prefer injection when you own the code. Passing the dependency as an argument needs no patch and no import trickery.
  • Use autospec by default. The few extra characters buy you protection against API drift.
  • Keep the patch inside the test. A patch that is active longer than needed hides bugs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. report.py contains from weather import temperature. Which target patches the function that report.summary() calls?

    The from-import copied the name into report's namespace. Patch it where it is looked up: report.temperature.
  2. 2. What is the main benefit of autospec=True?

    An autospecced mock copies the specification of the real object, so it cannot silently accept calls that the real function would reject.
  3. 3. When patch is used as a decorator, how is the created mock delivered to the test?

    The decorator passes the mock as an additional positional argument, with stacked decorators supplying arguments bottom-up.
  4. 4. Which tool temporarily changes values in os.environ and restores the dictionary afterwards?

    patch.dict updates a dictionary in place and restores its original contents on exit, optionally clearing it first.

Summary

  • patch("module.name") swaps a name for a MagicMock and restores it; use it as a context manager, a decorator or via start()/stop().
  • Patch the name where the code under test looks it up, which depends on how it was imported.
  • patch.object targets an attribute of an object; patch.dict changes a dictionary temporarily.
  • autospec=True (or create_autospec) makes mocks respect real signatures and catch typos.
  • Patch at the boundary of your system and prefer dependency injection when you control the code.

Next: The pytest-mock Plugin