Python
monkeypatch
Learn patching with monkeypatch.
monkeypatch
monkeypatch temporarily changes values during a test and rolls them back when it ends. It mimics environment variables, module attributes or function behavior.
It is injected as a parameter like a fixture: def test_x(monkeypatch):. monkeypatch.setattr(obj, "name", value) changes an attribute; monkeypatch.setenv("KEY", "v") sets an environment variable.
def test_with_env(monkeypatch):
monkeypatch.setenv("MODE", "test")
assert os.environ["MODE"] == "test"
When the test ends, pytest restores the old value; other tests are not affected.
monkeypatch and function mocking
You can also mock functions with monkeypatch. Writing monkeypatch.setattr(requests, "get", fake_get) replaces requests.get with your own function; no real network call happens.
Example: def fake_get(url): return {"status": 200} returns a fixed response. The test is fast and deterministic; it does not break on network issues.
This separates external dependencies from the test. It resembles the patch decorator of unittest.mock; but monkeypatch offers a simpler API.
Exercise Environment variable with monkeypatch
Start with import os. The function get_mode() returns os.environ.get("MODE", "prod"). The function test_mode(monkeypatch) runs monkeypatch.setenv("MODE", "test") and adds assert get_mode() == "test". At the end build a small stub object with a setenv method and call test_mode(stub); finish with print("ok").
Show example solution
import os
def get_mode():
return os.environ.get("MODE", "prod")
def test_mode(monkeypatch):
monkeypatch.setenv("MODE", "test")
assert get_mode() == "test"
class Stub:
def setenv(self, key, value):
os.environ[key] = value
test_mode(Stub())
print("ok")
Test yourself
-
What is monkeypatch used for?
- Temporarily changing values and rolling back
- Increasing the number of tests
- Making permanent code changes
- Renaming test names
Show answer
Temporarily changing values and rolling back — monkeypatch changes values during the test; it restores them when the test ends.
-
Complete the setattr call
def test_with_attr(monkeypatch):
monkeypatch.____(math, "pi", 3)
Show answer
def test_with_attr(monkeypatch):
monkeypatch.setattr(math, "pi", 3)
-
Match the monkeypatch methods
- setattr
- Changes an attribute
- setenv
- Sets an env variable
- delattr
- Deletes an attribute
- monkeypatch (parameter)
- Injected into the test
Next lesson: Summary - Pytest