Test Overview
This test uses the monkeypatch fixture in pytest to replace a function temporarily. It verifies that the patched function returns the expected mocked value during the test.
This test uses the monkeypatch fixture in pytest to replace a function temporarily. It verifies that the patched function returns the expected mocked value during the test.
import pytest def get_data(): return "original data" def test_monkeypatch_example(monkeypatch): def mock_get_data(): return "mocked data" monkeypatch.setattr(__name__, "get_data", mock_get_data) result = get_data() assert result == "mocked data"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | pytest injects monkeypatch fixture into test function | monkeypatch object ready to patch attributes | — | PASS |
| 3 | Define mock_get_data function returning 'mocked data' | mock_get_data function available in test scope | — | PASS |
| 4 | Use monkeypatch.setattr to replace get_data with mock_get_data | get_data function temporarily replaced by mock_get_data | — | PASS |
| 5 | Call get_data() which now points to mock_get_data | mock_get_data executes and returns 'mocked data' | Check if returned value is 'mocked data' | PASS |
| 6 | Assert that result equals 'mocked data' | Assertion compares expected and actual values | assert result == 'mocked data' | PASS |
| 7 | Test ends successfully | monkeypatch reverts changes after test | — | PASS |
monkeypatch fixture in pytest?monkeypatch to replace a function get_data in a module my_module?monkeypatch.setattr(target, value) where target is a string path.def get_value():
return 10
def test_value(monkeypatch):
monkeypatch.setattr('__main__.get_value', lambda: 5)
assert get_value() == ?get_value in the __main__ module with a lambda returning 5.get_value() now returns 5, so assert get_value() == 5 passes.def test_env(monkeypatch):
monkeypatch.setenv('API_KEY')
assert os.getenv('API_KEY') is Nonesetenv method requires both a key and a value to set an environment variable.open. How can you use monkeypatch to avoid reading a real file and instead provide fake content?open with a function returning a StringIO object simulates file reading without disk access.builtins.open with a lambda or function returning StringIO containing fake content.Pass the test and this pattern moves unknown