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 |