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.
monkeypatch.setattr in 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.
monkeypatch.setattr(module, "function_name", fake_function)monkeypatch.setattr(obj, "attribute", 42)
monkeypatch.setattr("module.ClassName.attribute", "new_value")
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.
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}")
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.
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.