1. Home
  2. Blog
  3. Test Automation

Test Automation

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.

9 min read
Pytest monkeypatch: 10 tested examples for env vars, time and APIs

Key takeaways

  • pytest monkeypatch is a built-in fixture: add monkeypatch as 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
Software Development

HTTP Cookies Explained: Secure, HttpOnly, SameSite and Scope

HTTP cookies explained: Set-Cookie, Path, Domain, expiry, Secure, HttpOnly, SameSite, prefixes, deleting cookies and a secure session recipe, tested locally.

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Databases & SQL

SQL Auto Increment: MySQL, PostgreSQL, SQL Server and SQLite

SQL auto increment in MySQL, PostgreSQL, SQL Server and SQLite: syntax, reading the new ID, why gaps appear, ID reuse,…

Read article →
Databases & SQL

SQL BETWEEN: Inclusive Ranges and the Date Trap Explained

SQL BETWEEN explained with tested queries: inclusive ranges, reversed bounds, NULLs, the last-day date trap, half-open ranges and index-friendly date…

Read article →
Software Development

JavaScript Template Literals: 10 Examples Including Tagged Templates

JavaScript template literals explained with 10 tested examples: interpolation, multiline strings, escaping, tagged templates for safe HTML and SQL, and…

Read article →
Software Development

Python heapq: Priority Queues, Top N and Heaps Explained

Python heapq explained: heappush, heappop, heapify, priority queues with tie-breakers, max heaps, nlargest and merge, with real timings against sorting.

Read article →
Software Development

Python Walrus Operator (:=) Explained With 8 Real Examples

The Python walrus operator := explained with 8 tested examples: if checks, regex matches, while loops, comprehensions, scope rules, precedence…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →