Test Overview
This test uses monkeypatch.setattr to replace a function temporarily during the test. It verifies that the patched function is called and returns the expected mocked value.
This test uses monkeypatch.setattr to replace a function temporarily during the test. It verifies that the patched function is called and returns the expected mocked value.
import pytest def get_data(): return "original data" def test_monkeypatch_setattr(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 and pytest initializes the test environment | Test environment ready, no patches applied yet | — | PASS |
| 2 | Defines mock_get_data function returning 'mocked data' | mock_get_data function available in test scope | — | PASS |
| 3 | Calls monkeypatch.setattr to replace get_data with mock_get_data | get_data function temporarily replaced by mock_get_data | — | PASS |
| 4 | Calls get_data() which now points to mock_get_data | get_data returns 'mocked data' | Check that result equals 'mocked data' | PASS |
| 5 | Assertion verifies that returned value is 'mocked data' | Assertion passes confirming patch worked | assert result == 'mocked data' | PASS |
| 6 | Test ends and pytest restores original get_data function | Original get_data function restored after test | — | PASS |
monkeypatch.setattr in pytest?get_data in module my_module using monkeypatch in pytest?my_module, the attribute name 'get_data', and the replacement function lambda: 42.import my_module
def test_func(monkeypatch):
def fake_func():
return 10
monkeypatch.setattr(my_module, 'get_value', fake_func)
result = my_module.get_value()
print(result)my_module.get_value is replaced temporarily by fake_func which returns 10.my_module.get_value() inside the test calls fake_func(), so it prints 10.def test_example(monkeypatch):
monkeypatch.setattr('os.path.exists', lambda x: True)
assert os.path.exists('anyfile.txt') == Truemonkeypatch.setattr(os.path, 'exists', lambda x: True) to patch the function properly.fetch_data() that calls requests.get. How can you use monkeypatch.setattr to replace requests.get with a fake function that returns a mock response with status_code=200 and text='OK'?status_code=200 and text='OK'.monkeypatch.setattr(requests, 'get', fake_func) to replace the real HTTP call during the test.Pass the test and this pattern moves unknown