monkeypatch
- Python course
- Advanced
- Lesson 17/83
- 5 min
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.
Practice 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").
Starter code
# import the os module
# get_mode(): return MODE env var, default "prod"
# test_mode(monkeypatch): set MODE and check
# build a stub object with setenv method to call test_mode
# then print("ok")Sample 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")Expected output
ok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is monkeypatch used for?
- Temporarily changing values and rolling back Correct answer
- Increasing the number of tests
- Making permanent code changes
- Renaming test names
Explanation: monkeypatch changes values during the test; it restores them when the test ends.
2 Complete the setattr call
def test_with_attr(monkeypatch):
monkeypatch.____(math, "pi", 3)
def test_with_attr(monkeypatch):
monkeypatch.setattr(math, "pi", 3)
Explanation: monkeypatch.setattr(math, "pi", 3) sets math.pi to 3 during the test; it rolls back at the end.
3 Match the monkeypatch methods
| Term | Meaning |
|---|---|
setattr |
Changes an attribute |
setenv |
Sets an env variable |
delattr |
Deletes an attribute |
monkeypatch (parameter) |
Injected into the test |