Skip to content
tezvyn:
Menu

Mocking with Pytest's monkeypatch

Source: docs.pytest.orgHardHow cards are made

Pytest's monkeypatch is a temporary stunt double for your code, safely swapping out functions or environment variables for a single test. Use it to isolate tests from network calls or filesystem access.

Why it exists

Tests need to be fast, reliable, and isolated. Code that calls external APIs, connects to databases, or reads from the filesystem breaks these rules by introducing slow, unpredictable dependencies. The monkeypatch fixture was created to temporarily replace these unpredictable parts of your code with predictable fakes during a test run.

The mental model

Think of monkeypatch as a safe, temporary "stunt double" for parts of your Python environment. For one test, you can tell it: "Instead of calling the real requests.get, call this fake function that returns a canned JSON response." After the test finishes, pytest ensures the original requests.get is put back, leaving no side effects.

How it works

By including monkeypatch as a test function argument, you get access to its methods. The most common is monkeypatch.setattr(target, name, value), where you specify the object to patch, the attribute name, and the replacement value (your mock). Other methods handle dictionary items (setitem) and environment variables (setenv). The pytest fixture mechanism guarantees that all changes are automatically reverted after the test concludes, even if it fails.

When to use it

Use monkeypatch to isolate your code from external boundaries. Three common scenarios: first, replacing functions that make network calls or database queries (setattr); second, modifying global configuration loaded from a dictionary (setitem); third, setting environment variables needed for a specific test case (setenv). This makes your tests deterministic and fast.

When not to use it

Avoid monkeypatch for testing interactions between your own internal components if you can achieve the same result with dependency injection. Overusing monkeypatching can make tests brittle and hard to understand, as they become tightly coupled to the implementation details you're patching over. It's for faking external systems, not for redesigning your internal logic on the fly.

One canonical example

To test a function that depends on the user's home directory, you can't rely on a specific path existing on the test runner. monkeypatch can force pathlib.Path.home() to return a predictable value. In a test, you would use monkeypatch.setattr(Path, "home", lambda: Path("/tmp/fake_home")). When your application code calls Path.home(), it will receive the fake path, making the test deterministic and independent of the environment it runs in.

Interview question

Which scenario best illustrates the primary purpose of Pytest's monkeypatch fixture?

  • a.Substituting one of your application's internal utility functions with an alternative implementation for a specific test.
  • b.Temporarily disabling a complex method within a class to simplify debugging during development.
  • c.Modifying a global configuration setting to apply across an entire test suite.
  • d.Simulating responses from external dependencies like network APIs or filesystem operations to ensure test isolation.Correct
Why?

The card emphasizes that monkeypatch is for isolating tests from external boundaries like network calls or filesystem access by providing predictable fakes. While monkeypatch can modify global settings or internal functions, its changes are temporary per test, and for internal components, dependency injection is often preferred to avoid brittleness.

Just read this? Test yourself on what you have been reading.

Read the original → docs.pytest.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on python — each one lists the topics its interview covers.

See open roles