0
0
PyTesttesting~5 mins

monkeypatch fixture in PyTest

Choose your learning style9 modes available
Introduction

The monkeypatch fixture lets you change parts of your code during tests without changing the real code. It helps test tricky parts safely.

When you want to replace a function with a simple version for testing.
When you need to change environment variables temporarily during a test.
When you want to avoid calling slow or external services in tests.
When you want to change a class or method behavior just for one test.
When you want to simulate errors or special cases easily.
Syntax
PyTest
def test_example(monkeypatch):
    monkeypatch.setattr(target, "name", new_value)
    monkeypatch.setenv("VAR_NAME", "value")
    monkeypatch.delattr(target, "name", raising=False)

monkeypatch is a special argument you add to your test function.

You can change attributes, environment variables, or delete attributes safely.

Examples
This replaces module.func with fake_func during the test.
PyTest
def test_replace_function(monkeypatch):
    def fake_func():
        return "fake"
    monkeypatch.setattr("module.func", fake_func)
    assert module.func() == "fake"
This sets an environment variable API_KEY just for the test.
PyTest
def test_change_env(monkeypatch):
    monkeypatch.setenv("API_KEY", "12345")
    assert os.getenv("API_KEY") == "12345"
This deletes an attribute temporarily to test behavior without it.
PyTest
def test_remove_attribute(monkeypatch):
    monkeypatch.delattr("module.Class.attr", raising=False)
    assert not hasattr(module.Class, "attr")
Sample Program

This test uses monkeypatch to set and delete an environment variable API_KEY. It checks that get_api_key() returns the right value depending on the environment.

PyTest
import os

def get_api_key():
    return os.getenv("API_KEY", "no-key")

def test_api_key(monkeypatch):
    monkeypatch.setenv("API_KEY", "test123")
    assert get_api_key() == "test123"

    monkeypatch.delenv("API_KEY", raising=False)
    assert get_api_key() == "no-key"
OutputSuccess
Important Notes

Always use monkeypatch inside tests to avoid changing real code or environment.

Changes made by monkeypatch last only during the test and are undone automatically.

Use raising=False to avoid errors if the attribute or env variable does not exist.

Summary

monkeypatch helps change code or environment safely during tests.

It is useful to replace functions, set environment variables, or remove attributes temporarily.

Changes are only for the test and do not affect other tests or real code.