In this lesson, you will learn how to make your test suite more robust by forcing your dependencies to simulate real-world failures and dynamic behaviors.
Why Simulate Failures?
When your code interacts with external systems—like an API, a database, or a file system—those systems aren't always available or well-behaved. If your application crashes because a service times out or returns bad data, you need to know how your code handles that. Using unittest.mock within your pytest suite, you can simulate these "side effects" to verify your error handling without ever touching an actual network or server.
Raising Exceptions
You can configure a mock object to raise an exception when it is called. This is the gold standard for testing your try...except blocks.
from unittest.mock import Mock
import pytest
def test_api_failure_handling(mocker):
# Create a mock for an external service
mock_service = Mock()
# Configure the mock to raise a TimeoutError when called
mock_service.get_data.side_effect = TimeoutError("Connection lost")
# Verify that your app catches the exception gracefully
with pytest.raises(TimeoutError):
mock_service.get_data()
Dynamic Side Effects
Sometimes you want a mock to behave differently over multiple calls. By passing an iterable (like a list) to side_effect, the mock will return the next value in the sequence each time it is invoked.
def test_dynamic_responses():
mock_db = Mock()
# First call returns True, second call returns False
mock_db.is_connected.side_effect = [True, False]
assert mock_db.is_connected() is True
assert mock_db.is_connected() is False
Using side_effect allows you to define complex scenarios—such as a system failing after several successful attempts—which helps you identify edge cases that would be difficult to trigger with a live system. This keeps your tests deterministic, fast, and focused purely on how your business logic reacts to the unpredictable nature of external dependencies.
Key Takeaway: Use the side_effect attribute on mock objects to force your code down specific error paths or to simulate stateful responses, ensuring your application remains resilient even when its dependencies fail.