Mock a function to test return values and side effects
Preconditions (2)
✅ Expected Result: The test passes verifying the function returns the mocked value and correctly handles the side effect exception
from unittest.mock import patch import pytest # Example external service function to be mocked def external_service(): # Imagine this calls a real external API return "real data" # Function under test that uses the external service def process_data(): try: data = external_service() return f"Processed {data}" except Exception: return "Error handled" @patch('__main__.external_service') def test_process_data(mock_service): # Mock return value mock_service.return_value = "mocked data" result = process_data() assert result == "Processed mocked data", f"Expected 'Processed mocked data' but got {result}" # Mock side effect to raise exception mock_service.side_effect = Exception("Service failure") result = process_data() assert result == "Error handled", f"Expected 'Error handled' but got {result}"
This test uses patch to replace external_service with a mock.
First, it sets return_value to simulate a successful call returning "mocked data". The test calls process_data and asserts the returned string includes the mocked data.
Next, it sets side_effect to raise an exception to simulate a failure. The test calls process_data again and asserts it returns the error handling message.
This approach isolates the function from the real external service, allowing controlled testing of different scenarios.
Now add data-driven testing with 3 different mocked return values and verify the function output for each
mock.return_value do in a pytest mock object?return_valuereturn_value attribute sets a fixed return value for the mock when it is called.side_effect which can raise exceptions or return different values, return_value always returns the same fixed value.side_effect to an exception causes the mock to raise that exception when called.mock.side_effect = Exception('Error') is valid syntax to raise an exception on call.from unittest.mock import Mock mock = Mock() mock.side_effect = [1, 2, 3] print(mock()) print(mock()) print(mock())
side_effect is a list, each call to the mock returns the next item in the list.from unittest.mock import Mock
mock = Mock()
mock.side_effect = Exception('Fail')
mock.side_effect = [1, 2, 3]
print(mock())side_effect replaces the first one; no error occurs.side_effect = [1, 2, 3], the mock returns 1 on first call, so print(mock()) outputs 1.side_effect is a list, the mock returns successive items from the list on each call. Non-callable items like numbers or exception instances are returned directly.Pass the test and this pattern moves unknown