Mock a function call using pytest-mock and verify it was called with expected arguments
Preconditions (2)
✅ Expected Result: The test passes confirming the mock was called correctly and the function under test returns the mocked data
import pytest from data_source import fetch_data # Function under test that calls fetch_data def process_data(): data = fetch_data() # Imagine some processing here return data def test_process_data_calls_fetch_data_once_and_returns_mocked_data(mocker): # Mock fetch_data to return fixed data mock_fetch = mocker.patch('data_source.fetch_data', return_value={'id': 1, 'value': 'test'}) result = process_data() # Assert fetch_data was called once mock_fetch.assert_called_once() # Assert fetch_data was called with no arguments mock_fetch.assert_called_with() # Assert the function under test returns the mocked data assert result == {'id': 1, 'value': 'test'}
The test uses the mocker fixture from pytest-mock to replace the fetch_data function with a mock that returns a fixed dictionary.
We call the process_data function which internally calls fetch_data. The mock ensures no real API call happens.
Assertions check that fetch_data was called exactly once and with no arguments, matching the manual test case steps.
Finally, we assert that process_data returns the mocked data, confirming the mock worked as expected.
Now add data-driven testing with 3 different mocked return values for 'fetch_data' and verify 'process_data' returns each correctly
pytest-mock in tests?get_data in module my_module using pytest-mock?mocker.patch('module.function').def fetch_data():
return 'real data'
def test_fetch(mocker):
mocker.patch('__main__.fetch_data', return_value='mocked data')
result = fetch_data()
assert result == 'mocked data'
print(result)fetch_data to always return 'mocked data'.def test_api_call(mocker):
mocker.patch('api.call', return_value=200)
response = api.call()
assert response == 200process_data() that calls fetch_from_api(). Using pytest-mock, how do you mock fetch_from_api to return different values on consecutive calls: first 'data1', then 'data2'?side_effect with a list of return values.side_effect=['data1', 'data2']. Options B, C, and D use incorrect parameters or syntax.Pass the test and this pattern moves unknown