What if you could change how your code behaves just for tests, without touching the real code?
Why monkeypatch.setattr in PyTest? - Purpose & Use Cases
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.
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.
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.
def test_fetch(): # manually change code or call real network result = fetch_data() assert result == expected
def test_fetch(monkeypatch): monkeypatch.setattr('module.fetch_data', lambda: 'fake data') result = module.fetch_data() assert result == 'fake data'
You can test code parts in isolation by swapping real functions with fake ones easily and safely.
Testing a weather app without calling the real weather service every time by replacing the data fetch function with a fixed response.
Manual code changes for testing are slow and risky.
monkeypatch.setattr swaps functions temporarily during tests.
This makes tests faster, safer, and more reliable.