DEV Community

Mhamed Askoure
Mhamed Askoure

Posted on

Test HTTP client failure paths in Python without network access

An HTTP client can work perfectly against a healthy server and still fail in production when a request times out or a response has an unexpected status.

A small, deterministic test can check how the caller handles these failures without contacting a remote API. Here is an example using HTTPX and pytest.

1. Keep the client injectable

import httpx

def fetch_status(client: httpx.Client) -> str:
    try:
        response = client.get("https://example.test/health")
        response.raise_for_status()
    except httpx.TimeoutException:
        return "timeout"
    except httpx.HTTPStatusError:
        return "http_error"
    except httpx.RequestError:
        return "transport_error"
    return "ok"
Enter fullscreen mode Exit fullscreen mode

The caller supplies the client, so tests can substitute a transport without changing the function.

2. Inject failures rather than waiting for them

import httpx
import pytest

@pytest.mark.parametrize(
    ("scenario", "expected"),
    [
        ("success", "ok"),
        ("timeout", "timeout"),
        ("unavailable", "http_error"),
        ("connection", "transport_error"),
    ],
)
def test_fetch_status(scenario, expected):
    def handler(request):
        if scenario == "timeout":
            raise httpx.ReadTimeout(
                "simulated read timeout", request=request
            )
        if scenario == "connection":
            raise httpx.ConnectError(
                "simulated connection failure", request=request
            )
        status = 503 if scenario == "unavailable" else 200
        return httpx.Response(status, request=request)

    with httpx.Client(
        transport=httpx.MockTransport(handler)
    ) as client:
        assert fetch_status(client) == expected
Enter fullscreen mode Exit fullscreen mode

Place both snippets in a file named test_http_client.py. With HTTPX and pytest installed, run:

python -m pytest -q test_http_client.py
Enter fullscreen mode Exit fullscreen mode

3. Know what the test proves

This tests exception handling and status classification. The simulated timeout does not measure actual socket timing, DNS behavior or production availability. A separate integration test is necessary for those properties.

For requests that change data, avoid automatically retrying an ambiguous timeout: the server may already have completed the operation. Define retry limits and application-level idempotency before enabling retries.

This is a small educational example, not a production-ready HTTP wrapper.

AI disclosure: this article was generated with AI. No production performance claims are made.

Top comments (0)