Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs
The pytest monkeypatch fixture lets a test temporarily change environment variables, functions, dictionaries, the clock and the working directory, then undoes everything automatically. Learn the methods with 10 passing tests, the wrong-target trap, and when to use mock instead.
- pytest monkeypatch is a built-in fixture: add
monkeypatchas a test argument and nothing needs installing. - Every change is reverted after the test, even when it fails. Our follow-up test confirmed the config was restored.
- Patch a name where it is looked up, not where it was defined. Our wrong-target test failed with
assert 10 == 20. - All 11 tests in our suite passed in 0.22 s, because no test touched the network or really slept.
Real code reads environment variables, calls APIs, checks the time and sleeps between retries. Unit tests should do none of those for real: they become slow, flaky and dependent on the machine running them. Pytest monkeypatch is the simplest way to swap those dependencies for the length of one test, with automatic cleanup so nothing leaks into the next one.
We ran every test on Python 3.13.6 with pytest 9.2.0. New to pytest? Read our pytest tutorial first, and our pytest fixtures guide for how fixtures like this one work.
What is monkeypatching?
Monkeypatching means changing code or data at runtime, for example replacing a module’s function with a fake. Doing it by hand is risky: forget to restore the original and every later test sees the fake. The monkeypatch fixture records each change and undoes all of them in reverse order when the test ends. Its main methods are:
| Method | What it does |
|---|---|
setattr(obj, name, value) |
Replace an attribute, function or method |
delattr(obj, name) |
Remove an attribute |
setitem(mapping, key, value) |
Change a dict entry |
delitem(mapping, key) |
Remove a dict entry |
setenv(name, value) / delenv(name) |
Set or remove an environment variable |
chdir(path) |
Change the working directory |
syspath_prepend(path) |
Add a path to sys.path |
context() |
Patch only inside a with block |
The code under test
Our small shop module, app.py, has the usual hard-to-test dependencies:
import os, time, datetime, random, urllib.request, json
CONFIG = {"currency": "INR", "timeout": 5}
def get_api_key():
key = os.environ.get("PAYMENT_API_KEY")
if not key:
raise RuntimeError("PAYMENT_API_KEY is not set")
return key
def fetch_rate(code):
with urllib.request.urlopen(f"https://api.example.com/rates/{code}",
timeout=CONFIG["timeout"]) as r:
return json.load(r)["rate"]
def price_in(amount, code):
return round(amount * fetch_rate(code), 2)
def greeting():
hour = datetime.datetime.now().hour
return "Good morning" if hour < 12 else "Good evening"
def retry(fn, tries=3):
for i in range(tries):
try:
return fn()
except ConnectionError:
time.sleep(2 ** i)
raise ConnectionError("gave up")
def coupon_code():
return "".join(random.choice("ABCDEFGH") for _ in range(6))
def config_dir():
return os.path.join(os.path.expanduser("~"), ".shopapp")
Examples 1 and 2: environment variables
def test_api_key_from_env(monkeypatch):
monkeypatch.setenv("PAYMENT_API_KEY", "test-key-123")
assert app.get_api_key() == "test-key-123"
def test_missing_api_key(monkeypatch):
monkeypatch.delenv("PAYMENT_API_KEY", raising=False)
with pytest.raises(RuntimeError, match="not set"):
app.get_api_key()
setenv injects a fake key without touching your real shell, and delenv guarantees the “missing” branch runs even on a developer machine that happens to have the variable set. raising=False avoids an error if it was not set to begin with. Values must be strings. Our environment variables guide covers configuration in general.
Example 3: replace a function to avoid the network
def test_price_without_network(monkeypatch):
monkeypatch.setattr(app, "fetch_rate", lambda code: 0.012)
assert app.price_in(1000, "USD") == 12.0
price_in looks up fetch_rate in the app module at call time, so replacing it there makes the test fast and deterministic. The fake is a lambda returning a fixed rate; it could also record its arguments for later assertions. This kind of stand-in is a stub, one of the test doubles worth knowing by name.
Examples 4 and 5: dictionary values and automatic restore
def test_config_value(monkeypatch):
monkeypatch.setitem(app.CONFIG, "currency", "USD")
assert app.CONFIG["currency"] == "USD"
def test_config_restored():
assert app.CONFIG["currency"] == "INR"
The second test does not use monkeypatch at all. It passed, proving that the first test’s change was undone. If you had written app.CONFIG["currency"] = "USD" directly, the second test would fail whenever it ran after the first, a classic order-dependent flaky test. Parallel runners such as pytest-xdist make that kind of leak even harder to debug.
Example 6: fake the current time
class FakeDatetime(datetime.datetime):
@classmethod
def now(cls, tz=None):
return cls(2026, 11, 20, 18, 30)
def test_evening_greeting(monkeypatch):
monkeypatch.setattr(app.datetime, "datetime", FakeDatetime)
assert app.greeting() == "Good evening"
You cannot set attributes on the built-in datetime.datetime type, so we replace the whole class inside the datetime module that app imported with a subclass whose now() returns a fixed moment. The test now passes at any hour of the day. Libraries such as freezegun or time-machine do this more thoroughly; we did not run them here.
Example 7: skip real sleeps in retry logic
def test_retry_does_not_sleep(monkeypatch):
sleeps = []
monkeypatch.setattr(app.time, "sleep", lambda s: sleeps.append(s))
calls = iter([ConnectionError(), ConnectionError(), "ok"])
def flaky():
v = next(calls)
if isinstance(v, Exception):
raise v
return v
assert app.retry(flaky) == "ok"
assert sleeps == [1, 2]
The real code would wait three seconds. The patched sleep records the requested delays instead, so the test runs instantly and verifies the exponential backoff: 1 second, then 2. Recording calls like this turns a stub into a simple spy.
Tip: patching a module attribute such as app.time.sleep replaces it for everyone using that module during the test, including pytest internals in rare cases. Keep such patches short-lived with monkeypatch.context() when in doubt.
Examples 8 and 9: home directory and working directory
def test_home_dir(monkeypatch, tmp_path):
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
assert app.config_dir() == os.path.join(str(tmp_path), ".shopapp")
def test_chdir(monkeypatch, tmp_path):
monkeypatch.chdir(tmp_path)
assert os.getcwd() == str(tmp_path)
Pointing the home directory at tmp_path keeps tests from reading or writing your real config files. We set both HOME and USERPROFILE because os.path.expanduser uses USERPROFILE on Windows and HOME elsewhere. chdir is restored after the test too, so relative paths in other tests keep working.
Example 10: block the network entirely
def test_block_network(monkeypatch):
def boom(*a, **k):
raise AssertionError("network call in a unit test")
monkeypatch.setattr(app.urllib.request, "urlopen", boom)
with pytest.raises(AssertionError, match="network"):
app.fetch_rate("USD")
Put a guard like this in an autouse fixture in conftest.py and any unit test that accidentally reaches the internet fails loudly instead of slowly. The pytest documentation shows the same idea for the requests library, removing its Session.request method with delattr. For tests that really should call HTTP, see our API testing with Python guide.
Scoped patches with monkeypatch.context()
def test_context_manager():
with pytest.MonkeyPatch.context() as mp:
mp.setattr(app, "coupon_code", lambda: "FIXED1")
assert app.coupon_code() == "FIXED1"
assert app.coupon_code() != "FIXED1"
The patch disappears at the end of the with block, not the end of the test. This is useful for patching only one step, and it also works outside test functions, for example inside a session-scoped fixture where the function-scoped monkeypatch fixture is not available.
The most common bug: patching the wrong place
# pricing.py
def rate(): return 1
# pricing_user.py
from pricing import rate
def total(x): return x * rate()
def test_patch_wrong_place(monkeypatch):
import pricing
monkeypatch.setattr(pricing, "rate", lambda: 2)
assert pricing_user.total(10) == 20 # FAILS: assert 10 == 20
def test_patch_right_place(monkeypatch):
monkeypatch.setattr(pricing_user, "rate", lambda: 2)
assert pricing_user.total(10) == 20 # passes
from pricing import rate copies a reference into pricing_user‘s own namespace at import time. Patching pricing.rate afterwards changes the original module, but pricing_user still holds the old function. The rule, shared with unittest.mock.patch: patch the name in the module that uses it. Our run gave 1 failed, 1 passed, exactly as predicted.
Typos fail loudly, which is good
monkeypatch.setattr(app, "fetch_rates", lambda c: 1)
# AttributeError: <module 'app' from '.../app.py'> has no attribute 'fetch_rates'
By default setattr refuses to create attributes that do not exist, so a misspelled name fails immediately instead of silently patching nothing. Only pass raising=False when you really mean to add a new attribute. (We shortened the file path in the error above.)
monkeypatch vs unittest.mock
| Need | Better tool |
|---|---|
| Env vars, dict entries, cwd, sys.path | monkeypatch |
| Swap in a simple fake function or value | monkeypatch |
| Assert how a fake was called, with what arguments, how many times | unittest.mock.MagicMock |
| Auto-generated fakes that match a real class | mock.create_autospec |
| Patching in unittest-style tests | mock.patch |
They combine well: monkeypatch.setattr(app, "fetch_rate", MagicMock(return_value=0.012)) gives automatic cleanup plus call assertions. Our Python mocking guide covers MagicMock in depth.
Best practices
- Patch the dependency at the boundary (network, clock, filesystem), not your own business logic.
- Patch where a name is used, not where it is defined.
- Prefer dependency injection in new code; it makes patching unnecessary.
- Move repeated patches into fixtures in
conftest.py. - Use an autouse fixture to block real network calls in unit tests.
- Avoid patching built-ins globally; keep the scope small.
Final thoughts
Pytest monkeypatch is the lightest way to take control of environment variables, functions, config, time and paths inside a test, with guaranteed cleanup. Our 11-test suite ran in a fifth of a second without sleeping or touching the network. Remember to patch names where they are looked up, keep patches small and scoped, and reach for MagicMock when you need to assert on calls. Faster, deterministic tests are also a strong defence against flaky tests.
Frequently asked questions
What is monkeypatch in pytest?
It is a built-in fixture that temporarily changes attributes, dictionary items, environment variables, the working directory or sys.path during a test and automatically restores everything afterwards.
How do I set an environment variable in a pytest test?
Add monkeypatch as a test argument and call monkeypatch.setenv with the name and a string value. Use monkeypatch.delenv with raising set to False to make sure a variable is absent.
Why does my monkeypatch have no effect?
You probably patched the module where the function is defined, while the code under test imported the name into its own module. Patch the name in the module that uses it instead.
What is the difference between monkeypatch and mock?
monkeypatch replaces values and restores them automatically. unittest.mock creates fake objects that record calls so you can assert on them. Many tests use monkeypatch to install a MagicMock.
Can I use monkeypatch in a session scoped fixture?
Not the monkeypatch fixture itself, because it is function scoped. Use pytest.MonkeyPatch.context in a with block inside the fixture to get the same automatic undo.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.