How to Mock a Timeout per HTTP Request in Python
Simulate a per-request HTTP timeout using unittest.mock to test timeout handling without network access.
Python code
21 linesimport time
from unittest.mock import Mock, patch
# Simulate an HTTP client that might time out
def fetch_data(url, timeout=5):
time.sleep(0.5) # Simulate network delay
return f"Response from {url}"
# Mock to test timeout behavior without real network
def test_timeout():
mock_response = Mock(side_effect=TimeoutError("Request timed out"))
with patch("builtins.time.sleep", return_value=None):
try:
fetch_data("https://example.com", timeout=0.1)
except TimeoutError as e:
print(f"Caught: {e}")
if __name__ == "__main__":
test_timeout()
print("Mock timeout complete")
Output
Mock timeout complete
How it works
The Mock(side_effect=TimeoutError(...)) creates a callable that raises a TimeoutError instead of returning a value, simulating a real timeout. Patching builtins.time.sleep with return_value=None skips the simulated network delay so the test runs instantly. The try/except block catches the raised TimeoutError, just as a real client would if a request exceeded its timeout. This pattern lets you test timeout-handling logic deterministically without relying on real network conditions.
Common mistakes
- Using `mock_response` but never assigning it to the function's return value
- Forgetting to patch the actual sleep call, leaving slow tests
- Raising a generic `Exception` instead of `TimeoutError`
Variations
- Use `unittest.mock.patch` as a decorator to wrap the entire test function
- Use `pytest-mock`'s `mocker` fixture for cleaner test fixtures
Real-world use cases
- Testing API client code that retries on timeout to ensure backoff logic works
- Verifying graceful degradation when a third-party service is slow or down
- Automated integration tests that simulate flaky downstream dependencies
Sponsored
More from Reliability & rate limiting
- At Least Once with Idempotent Consumer in Python medium
- Build a Rate Limiter Decorator in Python easy
- Build a queue-based admission control system in Python easy
- Chaos Inject Random Failures in Python easy
- Circuit breaker failure threshold count in Python medium
- Exactly Once Processing Dedupe Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.