Test Overview
This test uses pytest-mock to mock a function call and verify that it was called with expected arguments. It checks that the mocked function returns the mocked value and that the call count and arguments are correct.
This test uses pytest-mock to mock a function call and verify that it was called with expected arguments. It checks that the mocked function returns the mocked value and that the call count and arguments are correct.
import pytest def fetch_data(): # Imagine this fetches data from a remote API return "real data" def process_data(): data = fetch_data() return f"Processed {data}" def test_process_data_calls_fetch_data(mocker): mock_fetch = mocker.patch(__name__ + ".fetch_data", return_value="mocked data") result = process_data() assert result == "Processed mocked data" mock_fetch.assert_called_once() mock_fetch.assert_called_with()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | - | PASS |
| 2 | mocker.patch replaces fetch_data with a mock returning 'mocked data' | fetch_data function is mocked | - | PASS |
| 3 | process_data() is called, which internally calls mocked fetch_data | process_data calls mocked fetch_data, receives 'mocked data' | - | PASS |
| 4 | Assert that process_data() returns 'Processed mocked data' | Returned value is 'Processed mocked data' | assert result == 'Processed mocked data' | PASS |
| 5 | Assert that fetch_data was called exactly once | Mock call count is 1 | mock_fetch.assert_called_once() | PASS |
| 6 | Assert that fetch_data was called with no arguments | Mock call arguments are empty | mock_fetch.assert_called_with() | PASS |
| 7 | Test ends successfully | All assertions passed | - | PASS |