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.

Easy Python 3.9+ Aug 9, 2026 Reliability & rate limiting 13 views 0 copies

Python code

21 lines
Python 3.9+
import 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

stdout
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

  1. Use `unittest.mock.patch` as a decorator to wrap the entire test function
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Reliability & rate limiting

Related tutorials and quizzes for this topic.