Test Overview
This test uses unittest.mock.patch to replace a function with a mock during the test. It verifies that the patched function is called with expected arguments and returns the mocked value.
This test uses unittest.mock.patch to replace a function with a mock during the test. It verifies that the patched function is called with expected arguments and returns the mocked value.
from unittest.mock import patch import pytest def get_data(): # Imagine this fetches data from a slow external source return "real data" def process_data(): data = get_data() return f"Processed {data}" @patch('__main__.get_data') def test_process_data(mock_get_data): mock_get_data.return_value = "mocked data" result = process_data() mock_get_data.assert_called_once() assert result == "Processed mocked data"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test runner initializes pytest environment | - | PASS |
| 2 | Patch '__main__.get_data' with a mock object | The get_data function is replaced by mock_get_data during test | - | PASS |
| 3 | Call process_data(), which calls the patched get_data() | process_data calls mock_get_data instead of real get_data | - | PASS |
| 4 | mock_get_data returns 'mocked data' as set by return_value | process_data receives 'mocked data' from mock_get_data | - | PASS |
| 5 | Assert mock_get_data was called exactly once | mock_get_data call count is 1 | mock_get_data.assert_called_once() | PASS |
| 6 | Assert process_data() returned 'Processed mocked data' | Result string is 'Processed mocked data' | assert result == 'Processed mocked data' | PASS |
| 7 | Test ends successfully | All assertions passed, test completes | - | PASS |