Skip to main content

Testing and QA · Intermediate · 20 min

Test code that calls other services with a fake HTTP server

By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · httpx 0.29.0 · respx 0.23.1 · pytest-httpserver 1.2.1 · pytest 9.2.0 · uv 0.13

You will test a small exchange-rate client against faked HTTP answers, first in-process with respx and then over real sockets with pytest-httpserver, covering retries, 500s, timeouts, slow responses and malformed JSON without touching the real service.

On this page

Code that calls another service is hard to test against the real thing. The service is slow, costs money or data per call, rate-limits you, and almost never fails on demand, so the code paths that matter most (retries, timeouts, bad answers) go untested. A fake HTTP server fixes that: your test decides exactly what the "service" answers, then checks what your code did with it and what it sent.

There are two ways to fake HTTP in Python, and you use both here:

  • respx swaps out httpx's transport inside your test process. No socket opens. It is fast and lets you inspect every request, but it only works when the code under test uses httpx in the same process.
  • pytest-httpserver starts a real HTTP server on 127.0.0.1 for each test session. Any client can call it, including a different library, a subprocess or a compiled tool, because it is a listening HTTP server.

The code under test is a small client for an exchange-rate service: it asks for one rate, retries on server errors and timeouts, and rejects answers it cannot read. That shape matters anywhere networks are unreliable. On a prepaid mobile connection in Lagos or Nairobi, a request that hangs for twenty seconds is a normal day, not an edge case. These tests also run fully offline, so they cost no data.

Step 1 · Create the project and the code under test

Make a throwaway project. httpx is a runtime dependency; pytest and the two faking libraries are development dependencies. The version ranges allow patch releases and nothing newer:

Bash
mkdir -p ~/fake-http-demo/tests
cd ~/fake-http-demo
uv init --no-package
uv add "httpx>=0.29,<0.30"
uv add --dev "pytest>=9.2,<9.3" "respx>=0.23,<0.24" "pytest-httpserver>=1.2,<1.3"
rm main.py
cat >> pyproject.toml <<'TOML'

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
TOML

Now rates.py. The service lives at the address in RATES_API_URL and takes an optional key from RATES_API_KEY. Both come from the environment, so no secret is written into the code. get_rate retries a 5xx status or a timeout up to three times, waiting 0.2 s, then 0.4 s. It does not retry a 4xx, because asking again for a currency that does not exist will not help. The sleep argument exists so tests can record the waits instead of sitting through them.

Bash
cat > rates.py <<'PY'
"""A small client for an exchange-rate service."""

import os
import time
from decimal import Decimal, InvalidOperation

import httpx

RETRY_STATUSES = {500, 502, 503, 504}


class RateServiceError(Exception):
    """The rate service could not give a usable answer."""


def make_client(base_url=None, timeout=None):
    base_url = base_url or os.environ["RATES_API_URL"]
    timeout = timeout or float(os.environ.get("RATES_TIMEOUT", "2.0"))
    headers = {"Accept": "application/json"}
    api_key = os.environ.get("RATES_API_KEY")
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    return httpx.Client(base_url=base_url, headers=headers, timeout=timeout)


def get_rate(client, base, quote, attempts=3, backoff=0.2, sleep=time.sleep):
    """Return how many units of `quote` one unit of `base` buys."""
    problem = None
    for attempt in range(1, attempts + 1):
        try:
            response = client.get("/v1/rates", params={"base": base, "quote": quote})
        except httpx.TimeoutException:
            problem = "timeout"
        else:
            if response.status_code in RETRY_STATUSES:
                problem = f"status {response.status_code}"
            elif response.is_error:
                raise RateServiceError(f"status {response.status_code}")
            else:
                return _read_rate(response, quote)
        if attempt < attempts:
            sleep(backoff * 2 ** (attempt - 1))
    raise RateServiceError(f"gave up after {attempts} attempts: {problem}")


def _read_rate(response, quote):
    try:
        return Decimal(response.json()["rates"][quote])
    except (ValueError, KeyError, TypeError, InvalidOperation) as err:
        raise RateServiceError(f"unexpected response: {err!r}") from err
PY

Add a command-line wrapper too. You will test it later as a separate process, which is where respx can no longer help:

Bash
cat > rates_cli.py <<'PY'
"""Print one exchange rate, for example: python rates_cli.py USD NGN"""

import sys

from rates import RateServiceError, get_rate, make_client


def main(base, quote):
    try:
        with make_client() as client:
            rate = get_rate(client, base, quote)
    except RateServiceError as err:
        print(f"error: {err}", file=sys.stderr)
        return 2
    print(f"1 {base} = {rate} {quote}")
    return 0


if __name__ == "__main__":
    sys.exit(main(*sys.argv[1:3]))
PY

Check it worked

Bash
uv run python -c "import httpx, respx; print(httpx.__version__, respx.__version__)"

The command prints 0.29.0 0.23.1, or later patch releases of each.

Step 2 · Stub the service in-process with respx

respx ships a pytest fixture, respx_mock. Inside a test that uses it, every httpx request is matched against the routes you add. A route says which requests it catches and what to answer. The test then checks two things: the value the code returned, and the request the code sent. The second half is easy to skip and is where many real bugs live, such as a missing auth header or a query parameter with the wrong name.

Bash
cat > tests/test_rates_respx.py <<'PY'
from decimal import Decimal

import httpx
import pytest
from respx.models import AllMockedAssertionError

from rates import RateServiceError, get_rate, make_client

BASE_URL = "https://rates.example.test"
RATES = f"{BASE_URL}/v1/rates"
USD_NGN = {"base": "USD", "rates": {"NGN": "1520.50"}}


@pytest.fixture
def client(monkeypatch):
    monkeypatch.setenv("RATES_API_KEY", "test-key")
    with make_client(BASE_URL) as client:
        yield client


@pytest.fixture
def waits():
    return []


def test_returns_the_rate_and_sends_the_right_request(respx_mock, client):
    route = respx_mock.get(RATES).mock(return_value=httpx.Response(200, json=USD_NGN))

    assert get_rate(client, "USD", "NGN") == Decimal("1520.50")

    assert route.call_count == 1
    request = route.calls.last.request
    assert request.url.params["base"] == "USD"
    assert request.url.params["quote"] == "NGN"
    assert request.headers["authorization"] == "Bearer test-key"
    assert request.headers["accept"] == "application/json"


def test_an_unrouted_request_fails_loudly(respx_mock, client):
    with pytest.raises(AllMockedAssertionError):
        get_rate(client, "USD", "GHS")
PY
uv run pytest -v tests/test_rates_respx.py

A few things to notice:

  • rates.example.test is not a real host. The .test top-level domain is reserved, so if a request ever escaped the fake it would fail at DNS, not reach a stranger's server.
  • The key is set with monkeypatch.setenv and removed after the test. It is a dummy value; real keys never belong in tests.
  • The second test has no routes at all. The respx_mock fixture refuses any request it has no route for, so a forgotten stub fails the test instead of quietly calling the network. It also fails a test whose routes were never called, which catches stubs left behind after a refactor.

Check it worked

pytest lists both tests as PASSED and ends with 2 passed.

Step 3 · Test retries, server errors and timeouts

A route can answer differently on each call. Pass side_effect a list and respx works through it in order: an httpx.Response is returned, an exception class is raised as if the network had failed. That is how you script "the first call gets a 503, the second succeeds" without any real outage.

Bash
cat > tests/test_rates_failures.py <<'PY'
from decimal import Decimal

import httpx
import pytest

from rates import RateServiceError, get_rate, make_client

BASE_URL = "https://rates.example.test"
RATES = f"{BASE_URL}/v1/rates"
USD_NGN = {"base": "USD", "rates": {"NGN": "1520.50"}}


@pytest.fixture
def client():
    with make_client(BASE_URL) as client:
        yield client


@pytest.fixture
def waits():
    return []


def test_retries_once_after_a_503(respx_mock, client, waits):
    route = respx_mock.get(RATES).mock(
        side_effect=[httpx.Response(503), httpx.Response(200, json=USD_NGN)]
    )

    assert get_rate(client, "USD", "NGN", sleep=waits.append) == Decimal("1520.50")
    assert route.call_count == 2
    assert waits == [0.2]


def test_retries_after_a_timeout(respx_mock, client, waits):
    route = respx_mock.get(RATES).mock(
        side_effect=[httpx.ReadTimeout, httpx.Response(200, json=USD_NGN)]
    )

    assert get_rate(client, "USD", "NGN", sleep=waits.append) == Decimal("1520.50")
    assert route.call_count == 2


def test_gives_up_after_three_server_errors(respx_mock, client, waits):
    route = respx_mock.get(RATES).mock(return_value=httpx.Response(500))

    with pytest.raises(RateServiceError, match="gave up after 3 attempts: status 500"):
        get_rate(client, "USD", "NGN", sleep=waits.append)
    assert route.call_count == 3
    assert waits == [0.2, 0.4]


def test_does_not_retry_a_404(respx_mock, client, waits):
    route = respx_mock.get(RATES).mock(return_value=httpx.Response(404))

    with pytest.raises(RateServiceError, match="status 404"):
        get_rate(client, "USD", "NGN", sleep=waits.append)
    assert route.call_count == 1
    assert waits == []
PY
uv run pytest -v tests/test_rates_failures.py

Each test asserts the number of calls, not only the outcome. A client that never retries would still pass "raises after a 500"; it would not pass "made three calls". The waits list does the same for backoff: you prove the waits were 0.2 s and 0.4 s, and the suite does not pause at all.

The timeout here is simulated. respx raises httpx.ReadTimeout the instant the request is made, so this test proves the retry logic handles a timeout, not that the timeout setting is right. A later step tests a real slow server for that.

Check it worked

The run ends with 4 passed, in well under a second.

Step 4 · Reject malformed responses

Services do send nonsense: an HTML error page from a proxy with a 200 status, a currency missing from the payload, a number written as words. Add a parametrised test to the same file. Appending keeps the earlier tests as they are:

Bash
cat >> tests/test_rates_failures.py <<'PY'


@pytest.mark.parametrize(
    "response",
    [
        httpx.Response(200, text="<html>Service Unavailable</html>"),
        httpx.Response(200, json={"base": "USD", "rates": {}}),
        httpx.Response(200, json={"base": "USD", "rates": {"NGN": "about 1500"}}),
    ],
    ids=["html-not-json", "missing-currency", "rate-not-a-number"],
)
def test_rejects_a_malformed_body(respx_mock, client, response):
    respx_mock.get(RATES).mock(return_value=response)

    with pytest.raises(RateServiceError, match="unexpected response"):
        get_rate(client, "USD", "NGN")
PY
uv run pytest -v tests/test_rates_failures.py -k malformed

The test checks that the client turns all three into one clear error the caller can handle, instead of a stray KeyError or JSONDecodeError from deep inside. If you remove InvalidOperation from the except in rates.py, the rate-not-a-number case fails, which shows the test is doing its job.

Check it worked

pytest shows three tests named test_rejects_a_malformed_body[html-not-json], [missing-currency] and [rate-not-a-number], all PASSED.

Step 5 · Run a real local server with pytest-httpserver

respx cannot see requests made by another process, or by a library other than httpx. The command-line wrapper is an example: a test that runs rates_cli.py as a subprocess needs a server that is really listening. pytest-httpserver provides one through the httpserver fixture. You register what it should expect, and it answers anything else with a 500 and the text No handler found for this request.

First pin the server to 127.0.0.1 on a free port, so the subprocess and the server always agree on IPv4. A conftest.py in tests/ overrides the plugin's listen address for the whole run:

Bash
cat > tests/conftest.py <<'PY'
import pytest


@pytest.fixture(scope="session")
def httpserver_listen_address():
    return ("127.0.0.1", 0)
PY

Now the tests. run_cli points the wrapper at the server through the same environment variables a reader would set for the real service:

Bash
cat > tests/test_cli_server.py <<'PY'
import os
import subprocess
import sys
import time
from pathlib import Path

from werkzeug import Response

PROJECT = Path(__file__).resolve().parent.parent
USD_KES = {"base": "USD", "rates": {"KES": "129.30"}}


def run_cli(httpserver, *args, timeout="2.0"):
    env = {
        **os.environ,
        "RATES_API_URL": httpserver.url_for("/").rstrip("/"),
        "RATES_API_KEY": "test-key",
        "RATES_TIMEOUT": timeout,
    }
    return subprocess.run(
        [sys.executable, "rates_cli.py", *args],
        cwd=PROJECT, env=env, capture_output=True, text=True, timeout=30,
    )


def test_cli_prints_the_rate(httpserver):
    httpserver.expect_request(
        "/v1/rates",
        method="GET",
        query_string={"base": "USD", "quote": "KES"},
        headers={"Authorization": "Bearer test-key"},
    ).respond_with_json(USD_KES)

    result = run_cli(httpserver, "USD", "KES")

    assert result.returncode == 0, result.stderr
    assert result.stdout == "1 USD = 129.30 KES\n"
    httpserver.check_assertions()


def test_cli_retries_through_a_503(httpserver):
    httpserver.expect_oneshot_request("/v1/rates").respond_with_data("busy", status=503)
    httpserver.expect_request("/v1/rates").respond_with_json(USD_KES)

    result = run_cli(httpserver, "USD", "KES")

    assert result.returncode == 0, result.stderr
    assert [response.status_code for _, response in httpserver.log] == [503, 200]
PY
uv run pytest -v tests/test_cli_server.py

Here the request checks live in the expectation itself: the server only answers 200 if the path, method, query string and Authorization header all match. If the wrapper forgot the key, the server would answer 500, the wrapper would print an error, and check_assertions() would report the request that matched nothing. The second test registers a one-shot 503, which pytest-httpserver uses once before the permanent handler, and httpserver.log records every request and response in order. werkzeug, used for the Response class in the next step, is installed with pytest-httpserver.

Check it worked

The run ends with 2 passed. Both tests started a real Python process that made real HTTP calls to 127.0.0.1.

Step 6 · Test slow responses and broken bodies over a real socket

A listening server can do what an in-process stub cannot: be slow. respond_with_handler takes a function that receives the request and returns a response, so it can sleep first. Set the wrapper's timeout to 0.3 s and make the server take a full second. The wrapper should time out on each of its three attempts and give up in well under three seconds:

Bash
cat >> tests/test_cli_server.py <<'PY'


def test_cli_reports_malformed_json(httpserver):
    httpserver.expect_request("/v1/rates").respond_with_data(
        "{not json", content_type="application/json"
    )

    result = run_cli(httpserver, "USD", "KES")

    assert result.returncode == 2
    assert "unexpected response" in result.stderr


def test_cli_times_out_on_a_slow_server(httpserver):
    def slow(request):
        time.sleep(1.0)
        return Response('{"rates": {"KES": "129.30"}}', content_type="application/json")

    httpserver.expect_request("/v1/rates").respond_with_handler(slow)

    started = time.monotonic()
    result = run_cli(httpserver, "USD", "KES", timeout="0.3")
    elapsed = time.monotonic() - started

    assert result.returncode == 2
    assert "gave up after 3 attempts: timeout" in result.stderr
    assert elapsed < 3
PY
uv run pytest -v tests/test_cli_server.py

This is the test that proves the timeout setting reaches httpx. The slow handler eventually sends a valid answer, so a client with no timeout, or a timeout read from the wrong variable, would wait and succeed, and the test would fail on the exit code. Keep the server delay small: the server handles one request at a time, so each extra second here is a second added to the suite.

Check it worked

The run ends with 4 passed, and the whole file takes around two to three seconds, most of it the slow-server test.

Step 7 · Record what these tests cannot prove

Every answer in these tests was written by you. They prove your code handles those answers. They do not prove the real service still sends them: if the provider renames rates to data, or starts sending numbers instead of strings, every test here stays green and production breaks. That gap is what contract testing closes, by checking both sides against a shared, versioned description of the API.

Until you have that, write the gap down where the next person will see it, and keep one opt-in check against the real service. It is skipped unless someone sets RATES_LIVE_URL, so it never runs by accident in CI or spends anyone's data:

Bash
cat > tests/test_live.py <<'PY'
"""The tests that use respx and pytest-httpserver prove how this code
behaves against the answers we wrote. They do not prove the real rate
service still sends those answers. This check does, when you point it
at the service on purpose."""

import os

import pytest

from rates import get_rate, make_client

LIVE_URL = os.environ.get("RATES_LIVE_URL")


@pytest.mark.skipif(not LIVE_URL, reason="set RATES_LIVE_URL to check the real service")
def test_real_service_still_returns_a_rate():
    with make_client(LIVE_URL) as client:
        assert get_rate(client, "USD", "NGN") > 0
PY
uv run pytest -rs

To run it for real, export RATES_LIVE_URL and RATES_API_KEY in your shell from your secrets store, then run uv run pytest tests/test_live.py. Read the key from the environment or a prompt, never type it on the command line where shell history keeps it.

Check it worked

The summary shows SKIPPED [1] tests/test_live.py:15: set RATES_LIVE_URL to check the real service and ends with 13 passed, 1 skipped.

Step 8 · Clean up

Remove the demo project. Python and uv stay installed:

Bash
cd ~
rm -rf ~/fake-http-demo

Check it worked

Bash
test ! -e ~/fake-http-demo && echo "removed"

The command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.