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 |