Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Mocking and Monkeypatching

The monkeypatch Fixture

Replace functions, attributes, dictionary items, environment variables and the working directory for one test with pytest's monkeypatch fixture, and get them restored automatically.

Real code talks to things you do not want in a unit test: the clock, environment variables, the network, the current directory. Sooner or later you need to swap one of those for something simple and predictable, run the test, and put everything back. Doing the undo by hand is error-prone: one failing test that skips the cleanup can break every test after it.

pytest ships a built-in fixture, monkeypatch, that does exactly this. Every change you make through it is recorded and undone when the test ends, whether the test passes, fails or raises. In this lesson you will meet its main methods and the rules for using them well.

The examples run for real in your browser: each one writes a few files into a scratch folder and calls pytest.main() on them, which is the same engine you run from a terminal.

A first monkeypatch

Suppose a function reads its configuration from the environment:

Python
import os

def api_url():
    return os.environ.get("API_URL", "https://api.example.com")

A test must not depend on whatever happens to be set on the developer's machine. With monkeypatch.setenv the test controls the variable, and nothing leaks into the next test.

Python setenv and delenv

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.

delenv(name, raising=False) removes a variable and does not complain if it was never set. Leave out raising=False when you want the test to fail if the variable is missing, which proves your assumption about the environment.

The main methods

flowchart LR
    M["monkeypatch"] --> A["setattr / delattr<br/>objects, modules, classes"]
    M --> B["setitem / delitem<br/>dicts, os.environ"]
    M --> C["setenv / delenv<br/>environment variables"]
    M --> D["syspath_prepend<br/>import path"]
    M --> E["chdir<br/>working directory"]
    M --> F["context()<br/>undo early"]

Every change is recorded and reverted in reverse order when the test finishes.

Method What it does
setattr(obj, name, value) Replace an attribute; raising=False allows creating a new one
setattr("pkg.mod.name", value) The same, using a dotted import path as one string
delattr(obj, name) Remove an attribute
setitem(mapping, key, value) / delitem Change or remove a dictionary entry
setenv(name, value) / delenv(name) Change or remove an environment variable
syspath_prepend(path) Add a folder at the front of sys.path
chdir(path) Change the working directory

Replacing a function with setattr

The most common use is swapping a function. Imagine a greeting that depends on the time of day. A test that calls it gets a different answer depending on when it runs, so we put the clock behind a tiny function and replace that function for the duration of one test:

Python Freezing the clock with setattr

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.

The code under test calls current_hour() through its own module namespace, so patching greeter.current_hour works. Small seams like this make code easy to test. The next lessons (unittest.mock and where to patch) explain what happens when the name was imported into a different module.

monkeypatch.setattr raises AttributeError if the attribute does not exist. That is a feature: a typo in the name fails loudly instead of silently patching nothing. Pass raising=False only when you really are adding a new attribute.

Dictionaries, paths and the working directory

setitem is perfect for module-level configuration dictionaries, and chdir pairs well with the tmp_path fixture so a test can read and write files relative to the current folder without touching your project.

Python setitem, chdir and syspath_prepend

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.

Patching things you do not own

You can patch library code too, which is how you stop a test from touching the real world. A classic example is making input() predictable:

Python
def test_reads_a_name(monkeypatch):
    monkeypatch.setattr("builtins.input", lambda prompt="": "Ada")
    assert ask_name() == "Hello, Ada!"

Patch the smallest thing that cuts the connection to the outside world. Replacing requests.get is fine; replacing your whole business function defeats the point of the test.

Undoing early with context()

Normally you never undo manually. When you need a patch for only part of a test, use monkeypatch.context() as a with block. Changes made on the context object are reverted when the block exits:

Python
def test_partial(monkeypatch):
    with monkeypatch.context() as m:
        m.setattr(greeter, "current_hour", lambda: 9)
        assert greeter.greeting() == "Good morning"
    assert greeter.current_hour() in range(24)   # back to the real one

Common mistakes

  • Patching the wrong name. If app.py does from time import sleep, patch app.sleep, not time.sleep. This is the number one source of "my patch does nothing".
  • Patching too much. A test that replaces five things mostly tests the replacements. Prefer a real object when it is cheap and deterministic.
  • Using monkeypatch outside a test. It is a function-scoped fixture. For a patch shared by a wider scope, build your own with pytest.MonkeyPatch.context() inside a wider-scoped fixture.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When are the changes made through monkeypatch undone?

    monkeypatch is a function-scoped fixture. Its teardown reverts every recorded change after each test, regardless of the outcome.
  2. 2. What does monkeypatch.setattr(obj, "missing", 1) do when obj has no attribute named missing?

    By default setattr insists the attribute exists, which catches typos. raising=False allows adding a new attribute.
  3. 3. Which call makes a test run with an environment variable guaranteed to be absent, without failing if it was never set?

    delenv with raising=False removes the variable when present and quietly does nothing when it is not.
  4. 4. A module does from time import sleep and calls sleep(). Which patch affects it?

    from-import copies the name into the importing module's namespace, so you must patch the name where it is looked up.

Summary

  • monkeypatch records every change and restores it after each test.
  • Use setattr/delattr for functions and attributes, setitem/delitem for dicts, setenv/delenv for environment variables, chdir and syspath_prepend for paths.
  • A dotted string such as "pkg.mod.func" works as the target of setattr.
  • Patch the name where the code under test looks it up, and keep patches small.
  • monkeypatch.context() limits a patch to a with block.

Next: unittest.mock Basics