0
0
PyTesttesting~3 mins

Why monkeypatch.setattr in PyTest? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change how your code behaves just for tests, without touching the real code?

The Scenario

Imagine you have a function that calls another function to get data from the internet. You want to test your function without actually making the slow network call every time.

Doing this manually means changing the original code or running the real network call during tests.

The Problem

Manually changing code to avoid network calls is risky and time-consuming.

Running real network calls in tests makes tests slow and flaky because of internet issues.

It's easy to forget to undo changes, causing bugs later.

The Solution

Using monkeypatch.setattr lets you temporarily replace parts of your code during tests.

You can swap the real network call with a fake function that returns quick, predictable data.

This keeps your tests fast, reliable, and safe without changing your real code.

Before vs After
Before
def test_fetch():
    # manually change code or call real network
    result = fetch_data()
    assert result == expected
After
def test_fetch(monkeypatch):
    monkeypatch.setattr('module.fetch_data', lambda: 'fake data')
    result = module.fetch_data()
    assert result == 'fake data'
What It Enables

You can test code parts in isolation by swapping real functions with fake ones easily and safely.

Real Life Example

Testing a weather app without calling the real weather service every time by replacing the data fetch function with a fixed response.

Key Takeaways

Manual code changes for testing are slow and risky.

monkeypatch.setattr swaps functions temporarily during tests.

This makes tests faster, safer, and more reliable.