0
0
PyTesttesting~5 mins

monkeypatch.setattr in PyTest

Choose your learning style9 modes available
Introduction

We use monkeypatch.setattr to temporarily change how a part of the code works during a test. This helps us test without changing the real code.

When you want to replace a function or variable with a fake one to control test behavior.
When you need to avoid calling slow or external services during tests.
When you want to simulate different return values from a function to test various cases.
When you want to fix the value of a variable that normally changes during runtime.
When you want to isolate the part of code you are testing from other parts.
Syntax
PyTest
monkeypatch.setattr(target, name, value, raising=True)

target can be a module, class, or object where the attribute lives.

name is the attribute name as a string.

value is the new value or function you want to set temporarily.

Examples
Replace a function in a module with a fake function.
PyTest
monkeypatch.setattr(module, "function_name", fake_function)
Change an object's attribute to 42 during the test.
PyTest
monkeypatch.setattr(obj, "attribute", 42)
Change a class attribute by its full path as a string.
PyTest
monkeypatch.setattr("module.ClassName.attribute", "new_value")
Sample Program

This test replaces the multiply method of Calculator with a fake function that always returns 42. It checks that the replacement works by asserting the result is 42.

PyTest
import pytest

class Calculator:
    def multiply(self, a, b):
        return a * b

def fake_multiply(a, b):
    return 42

def test_multiply(monkeypatch):
    calc = Calculator()
    # Replace multiply method with fake_multiply
    monkeypatch.setattr(calc, "multiply", fake_multiply)
    result = calc.multiply(3, 5)
    assert result == 42
    print(f"Result after monkeypatch: {result}")
OutputSuccess
Important Notes

The change made by monkeypatch.setattr lasts only during the test. After the test ends, the original code is restored.

Use monkeypatch as a test function argument to get access to it.

Setting raising=False prevents errors if the attribute does not exist.

Summary

monkeypatch.setattr lets you temporarily change code parts during tests.

It helps test code in isolation by replacing functions or variables.

Changes are undone automatically after the test finishes.