Skip to content

monkeypatch

The monkeypatch fixture lets you temporarily modify (or "patch") the behavior of modules, classes, functions, environment variables , or the working directory for the duration of a single test. It is commonly used to replace functions, mock values, or adjust configuration without permanently altering your code or environment.

One of the most critical features of monkeypatch is its automatic teardown: Any changes made with it are automatically reverted after the test completes, regardless of whether the test passed or failed.

The monkeypatch fixture provides the following methods to modify objects, dictionaries, or environment variables:

setattr and delattr

setattr replaces an attribute on a target object. delattr removes an attribute from an object. If raising=True (default) and the attribute does not exist, an AttributeError is raised.

Syntax:

  • setattr(obj, name, value, raising=True)
  • delattr(obj, name, raising=True)
python
def test_setattr(monkeypatch):
    import myapp.utils
    monkeypatch.setattr(myapp.utils, "get_user_id", lambda: 42)
    assert myapp.utils.get_user_id() == 42

    monkeypatch.delattr(myapp.utils, "get_user_id")
    assert not hasattr(myapp.utils, "get_user_id")

setitem and delitem

setitem updates a mapping by assigning a value to a key. delitem removes a key from a mapping. If raising=True (default) and the key does not exist, an KeyError is raised.

Syntax:

  • setitem(mapping, name, value)
  • delitem(obj, name, raising=True)
python
def test_setitem_delitem(monkeypatch):
    data = {}
    monkeypatch.setitem(data, "k", "v")
    assert data["k"] == "v"

    monkeypatch.delitem(data, "k")
    assert "k" not in data

setenv and delenv

setenv temporarily sets an environment variable. If prepend=True and the variable already exists, the new value is placed before the existing value, separated by os.pathsep (so it behaves well for PATH-like variables).

delenv deletes an environment variable. If raising=True (default) and the variable does not exist, an KeyError is raised.

Syntax:

  • setenv(name, value, prepend=None)
  • delenv(name, raising=True)
python
def test_setenv_delenv(monkeypatch):
    import os

    monkeypatch.setenv("MODE", "test")
    assert os.getenv("MODE") == "test"

    monkeypatch.delenv("MODE")
    assert os.getenv("MODE") is None

Others

  • syspath_prepend(path): Adds a path to the beginning of sys.path, ensuring imports are resolved from that location first.
  • chdir(path): Temporarily changes the current working directory for the duration of the test.
  • context(): Context manager that returns a new MonkeyPatch object which undoes any patching done inside the with block upon exit.
python
import functools

def test_partial(monkeypatch):
    with monkeypatch.context() as m:
        m.setattr(functools, "partial", 3)