Skip to main content

Testing and QA · Intermediate · 26 min

Write negative tests for an API: bad input, auth and limits

By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · FastAPI 0.165.0 · uvicorn 0.54.0 · PyJWT 2.15.1 · httpx 0.29.0 · pytest 9.2.0 · uv 0.13

You will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.

On this page

A happy-path test proves an API works when everyone behaves. Real clients do not. They send a number as a string, forget a field, paste a phone number with spaces, retry a payment after a timeout, keep an expired token, or ask for someone else's record. Each of those is a request the API must refuse, clearly and the same way every time. Negative tests are the tests that send those requests on purpose and check the refusal.

In this tutorial you build a small API for ordering mobile data bundles, then a pytest suite of 65 tests that tries to break it. The tests use httpx against the API running on 127.0.0.1, so they see exactly what a client sees: status codes, headers and bodies, after the web server has had its say. They cover:

  • Bad input: missing and extra fields, wrong types, malformed JSON.
  • Limits: boundary values, very long strings, Unicode text and oversized bodies.
  • Auth: no token, malformed headers, expired, forged and tampered tokens, and one user reading another's order.
  • Abuse and retries: a rate limit, and idempotency keys reused with a different body.
  • One error format: every refusal is an RFC 9457 problem document, served as application/problem+json.

The example fits a market where many people buy data in small prepaid bundles on a phone. Mobile networks drop requests, apps retry, and a retry that creates a second order spends someone's money twice. Phone numbers come in many local formats, and notes arrive in Yorùbá, Amharic, Arabic and emoji. Those are the cases worth testing first.

Step 1 · Create the project and the API

Make a throwaway project. FastAPI, uvicorn and PyJWT are what the API needs; pytest and httpx are only for the tests. The ranges allow patch releases and nothing newer:

Bash
mkdir -p ~/negative-tests-demo/tests
cd ~/negative-tests-demo
uv init --no-package
uv add "fastapi>=0.165,<0.166" "uvicorn>=0.54,<0.55" "pyjwt>=2.15,<2.16"
uv add --dev "pytest>=9.2,<9.3" "httpx>=0.29,<0.30"
rm main.py
cat >> pyproject.toml <<'TOML'

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

Now app.py. Read it once before you test it, because every rule in it is something a test will try to break:

  • OrderIn takes a phone number in international (E.164) form, a bundle size from 50 MB to 10,240 MB and an optional note of up to 140 characters. extra="forbid" refuses unknown fields, and strict=True stops Pydantic quietly turning "500" into 500.
  • current_user reads a bearer token and checks its signature, its expiry and that it names a user. The signing key comes from the API_SIGNING_KEY environment variable, so no secret is written into the code.
  • Each user may place 5 orders a minute. An optional Idempotency-Key header lets a client retry an order safely.
  • Every error goes through problem(), which writes an RFC 9457 problem document. FastAPI's default error bodies are shaped differently for validation errors ({"detail": [...]}) and for everything else ({"detail": "Not Found"}); the three exception handlers replace both.
Bash
cat > app.py <<'PY'
"""A small API for ordering mobile data bundles, used to practise negative tests."""

import hashlib
import json
import os
import time
import uuid
from collections import defaultdict, deque
from http import HTTPStatus
from typing import Annotated

import jwt
from fastapi import Depends, FastAPI, Header, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel, ConfigDict, Field
from starlette.exceptions import HTTPException as StarletteHTTPException

SIGNING_KEY = os.environ["API_SIGNING_KEY"]
MAX_BODY_BYTES = 16 * 1024
ORDERS_PER_MINUTE = 5
PROBLEM_DOCS = "https://api.example.test/problems/"

app = FastAPI()
bearer = HTTPBearer(auto_error=False)

orders = {}
recent_orders = defaultdict(deque)
idempotency_keys = {}


class OrderIn(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)

    phone: str = Field(pattern=r"^\+[1-9][0-9]{7,14}$")
    bundle_mb: int = Field(ge=50, le=10240)
    note: str | None = Field(default=None, max_length=140)


class ApiProblem(Exception):
    def __init__(self, status, kind, title, detail, headers=None):
        super().__init__(detail)
        self.status = status
        self.kind = kind
        self.title = title
        self.detail = detail
        self.headers = headers


def problem(status, title, detail=None, kind=None, headers=None, **extra):
    body = {
        "type": PROBLEM_DOCS + kind if kind else "about:blank",
        "title": title,
        "status": status,
    }
    if detail:
        body["detail"] = detail
    body.update(extra)
    return JSONResponse(
        body, status_code=status, headers=headers, media_type="application/problem+json"
    )


@app.exception_handler(ApiProblem)
async def handle_api_problem(request, exc):
    return problem(exc.status, exc.title, exc.detail, exc.kind, exc.headers)


@app.exception_handler(StarletteHTTPException)
async def handle_http_error(request, exc):
    return problem(exc.status_code, HTTPStatus(exc.status_code).phrase, headers=exc.headers)


@app.exception_handler(RequestValidationError)
async def handle_validation_error(request, exc):
    errors = [
        {
            "in": str(error["loc"][0]),
            "name": ".".join(str(part) for part in error["loc"][1:]),
            "type": error["type"],
            "detail": error["msg"],
        }
        for error in exc.errors()
    ]
    return problem(422, "Request is not valid", "See errors for each field.", "validation", errors=errors)


@app.middleware("http")
async def limit_body_size(request: Request, call_next):
    length = request.headers.get("content-length", "")
    if length.isdigit() and int(length) > MAX_BODY_BYTES:
        return problem(413, "Request body too large", f"The limit is {MAX_BODY_BYTES} bytes.", "too-large")
    return await call_next(request)


def current_user(
    credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)],
) -> str:
    challenge = {"WWW-Authenticate": "Bearer"}
    if credentials is None:
        raise ApiProblem(401, "unauthenticated", "Authentication required", "Send a bearer token.", challenge)
    try:
        claims = jwt.decode(
            credentials.credentials,
            SIGNING_KEY,
            algorithms=["HS256"],
            options={"require": ["exp", "sub"]},
        )
    except jwt.ExpiredSignatureError:
        raise ApiProblem(401, "unauthenticated", "Authentication required", "The token has expired.", challenge)
    except jwt.InvalidTokenError:
        raise ApiProblem(401, "unauthenticated", "Authentication required", "The token is not valid.", challenge)
    return claims["sub"]


def check_rate_limit(user):
    now = time.monotonic()
    window = recent_orders[user]
    while window and now - window[0] >= 60:
        window.popleft()
    if len(window) >= ORDERS_PER_MINUTE:
        retry_after = int(60 - (now - window[0])) + 1
        raise ApiProblem(
            429, "rate-limited", "Too many requests",
            f"Up to {ORDERS_PER_MINUTE} orders a minute.", {"Retry-After": str(retry_after)},
        )
    window.append(now)


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/v1/orders", status_code=201)
def create_order(
    order: OrderIn,
    user: Annotated[str, Depends(current_user)],
    idempotency_key: Annotated[str | None, Header(min_length=1, max_length=64)] = None,
):
    fingerprint = hashlib.sha256(json.dumps(order.model_dump(), sort_keys=True).encode()).hexdigest()
    if idempotency_key is not None:
        saved = idempotency_keys.get((user, idempotency_key))
        if saved is not None:
            if saved["fingerprint"] != fingerprint:
                raise ApiProblem(
                    422, "idempotency-mismatch", "Idempotency key reused",
                    "This key was already used with a different request body.",
                )
            return saved["order"]
    check_rate_limit(user)
    created = {"id": str(uuid.uuid4()), "owner": user, **order.model_dump()}
    orders[created["id"]] = created
    if idempotency_key is not None:
        idempotency_keys[(user, idempotency_key)] = {"fingerprint": fingerprint, "order": created}
    return created


@app.get("/v1/orders/{order_id}")
def read_order(order_id: uuid.UUID, user: Annotated[str, Depends(current_user)]):
    order = orders.get(str(order_id))
    if order is None or order["owner"] != user:
        raise ApiProblem(404, "not-found", "Order not found", "No order with that id on this account.")
    return order
PY

https://api.example.test/problems/ stands in for a page in your own API documentation; replace it with yours. The .test domain is reserved and never resolves.

Check it worked

Bash
uv run python -c "import fastapi, jwt, uvicorn; print(fastapi.__version__, jwt.__version__, uvicorn.__version__)"

The command prints 0.165.0 2.15.1 0.54.0, or later patch releases of each.

Step 2 · Start the API from the tests and prove the happy path

The tests should talk to a running HTTP server, not call functions inside the app. Some refusals happen before your route code runs (unknown paths, wrong methods, oversized bodies, a header the server rejects), and only a request over a socket meets all of them.

conftest.py starts uvicorn once per test run, on a free port on 127.0.0.1. It makes a fresh random signing key for that run and hands it to the server through the environment, so the key never exists in a file. It waits until /health answers, and stops the server when the run ends. The make_token fixture signs tokens with the same key, and user_headers gives each test a brand-new user, so one test's orders never count against another's rate limit.

Bash
cat > tests/conftest.py <<'PY'
import os
import secrets
import socket
import subprocess
import sys
import time
import uuid
from pathlib import Path

import httpx
import jwt
import pytest

PROJECT = Path(__file__).resolve().parent.parent


@pytest.fixture(scope="session")
def signing_key():
    return secrets.token_urlsafe(32)


@pytest.fixture(scope="session")
def base_url(signing_key):
    with socket.socket() as probe:
        probe.bind(("127.0.0.1", 0))
        port = probe.getsockname()[1]
    server = subprocess.Popen(
        [sys.executable, "-m", "uvicorn", "app:app",
         "--host", "127.0.0.1", "--port", str(port), "--log-level", "warning"],
        cwd=PROJECT,
        env={**os.environ, "API_SIGNING_KEY": signing_key},
    )
    url = f"http://127.0.0.1:{port}"
    try:
        deadline = time.monotonic() + 15
        while True:
            try:
                if httpx.get(f"{url}/health", timeout=1).status_code == 200:
                    break
            except httpx.TransportError:
                pass
            if server.poll() is not None or time.monotonic() > deadline:
                raise RuntimeError("the API did not start")
            time.sleep(0.1)
        yield url
    finally:
        server.terminate()
        server.wait(timeout=10)


@pytest.fixture
def api(base_url):
    with httpx.Client(base_url=base_url, timeout=5) as client:
        yield client


@pytest.fixture
def make_token(signing_key):
    def make(sub=None, expires_in=300):
        claims = {
            "sub": sub or f"user-{uuid.uuid4().hex[:8]}",
            "exp": int(time.time()) + expires_in,
        }
        return jwt.encode(claims, signing_key, algorithm="HS256")

    return make


@pytest.fixture
def user_headers(make_token):
    return {"Authorization": f"Bearer {make_token()}"}
PY

helpers.py holds the one check every negative test in this tutorial shares. A refusal passes only if the status is right, the content type is application/problem+json, and the body has the type, title and status members with status matching the HTTP status:

Bash
cat > tests/helpers.py <<'PY'
VALID = {"phone": "+2348012345678", "bundle_mb": 500}


def assert_problem(response, status):
    """Check a response is an RFC 9457 problem document with this status."""
    assert response.status_code == status, response.text
    assert response.headers["content-type"].startswith("application/problem+json")
    body = response.json()
    assert body["status"] == status
    assert isinstance(body["type"], str) and body["type"]
    assert isinstance(body["title"], str) and body["title"]
    return body


def error_fields(body):
    return {(error["name"], error["type"]) for error in body["errors"]}
PY

Start with one positive test. Every negative test you write next sends something slightly different from this request, so if this one fails, nothing else means anything:

Bash
cat > tests/test_happy_path.py <<'PY'
from helpers import VALID


def test_create_and_read_an_order(api, user_headers):
    created = api.post("/v1/orders", json=VALID, headers=user_headers)
    assert created.status_code == 201, created.text
    order = created.json()
    assert order["bundle_mb"] == 500

    fetched = api.get(f"/v1/orders/{order['id']}", headers=user_headers)
    assert fetched.status_code == 200
    assert fetched.json() == order
PY
uv run pytest -v tests/test_happy_path.py

Check it worked

pytest shows test_create_and_read_an_order PASSED and ends with 1 passed. The server's own log stays quiet because it runs at warning level.

Step 3 · Send missing fields, extra fields and wrong types

Take the valid body and break it one way at a time. Each case names the field you expect the API to blame and the Pydantic error type, so a test fails if the API rejects the request for the wrong reason:

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

from helpers import VALID, assert_problem, error_fields


@pytest.mark.parametrize(
    "payload, expected",
    [
        ({"bundle_mb": 500}, ("phone", "missing")),
        ({"phone": "+2348012345678"}, ("bundle_mb", "missing")),
        ({**VALID, "price": 0}, ("price", "extra_forbidden")),
        ({**VALID, "bundle_mb": "500"}, ("bundle_mb", "int_type")),
        ({**VALID, "bundle_mb": 500.5}, ("bundle_mb", "int_type")),
        ({**VALID, "bundle_mb": True}, ("bundle_mb", "int_type")),
        ({**VALID, "phone": 2348012345678}, ("phone", "string_type")),
    ],
    ids=["no-phone", "no-bundle", "extra-field", "number-as-text",
         "fraction", "boolean", "phone-as-number"],
)
def test_rejects_a_bad_field(api, user_headers, payload, expected):
    response = api.post("/v1/orders", json=payload, headers=user_headers)
    body = assert_problem(response, 422)
    assert expected in error_fields(body)


def test_reports_every_bad_field_at_once(api, user_headers):
    response = api.post("/v1/orders", json={}, headers=user_headers)
    body = assert_problem(response, 422)
    assert error_fields(body) == {("phone", "missing"), ("bundle_mb", "missing")}


def test_rejects_malformed_json(api, user_headers):
    response = api.post(
        "/v1/orders",
        content=b'{"phone": "+2348012345678",',
        headers={**user_headers, "Content-Type": "application/json"},
    )
    body = assert_problem(response, 422)
    assert any(error["type"] == "json_invalid" for error in body["errors"])


def test_rejects_a_form_instead_of_json(api, user_headers):
    response = api.post("/v1/orders", data=VALID, headers=user_headers)
    assert_problem(response, 422)
PY
uv run pytest -v tests/test_bad_input.py

What each group is for:

  • Extra fields. Without extra="forbid", a client could send "price": 0 and the API would silently drop it. That is harmless today and a bug the day someone adds a price field. Refusing unknown fields also catches typos such as bundle_MB in client code.
  • Wrong types. These are the tests that justify strict=True. Remove it from OrderIn and run the file again: "500" is quietly converted and accepted, and the number-as-text, fraction and boolean cases fail. Put it back afterwards.
  • Every bad field at once. An API that reports only the first problem makes clients fix one field per round trip. On a slow mobile connection that is several wasted requests.
  • Malformed JSON and a form body. A truncated body must get a clean 422, not a 500 from deep inside the parser.

Check it worked

The run lists ten tests, including test_rejects_a_bad_field[extra-field] and test_rejects_malformed_json, and ends with 10 passed.

Step 4 · Test boundaries, long strings and Unicode

Bugs cluster at the edges of a range, so test both sides of every edge: the last value allowed and the first one refused. For the bundle size that is 50 and 49, 10,240 and 10,241, plus zero, a negative number and a number far too big for a 64-bit integer.

Text needs more thought. "Up to 140 characters" sounds clear until the text is not English. Python, and so Pydantic, counts Unicode code points. The Yorùbá letter ẹ is one code point but three bytes in UTF-8. A waving hand with a skin tone looks like one character but is two code points, so a person who types 71 of them sees 71 characters and gets refused. These tests pin down what the API actually does, so nobody has to guess:

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

from helpers import VALID, assert_problem


@pytest.mark.parametrize(
    "bundle_mb, status",
    [(49, 422), (50, 201), (10240, 201), (10241, 422), (0, 422), (-1, 422), (2**63, 422)],
)
def test_bundle_size_limits(api, user_headers, bundle_mb, status):
    response = api.post("/v1/orders", json={**VALID, "bundle_mb": bundle_mb}, headers=user_headers)
    assert response.status_code == status, response.text


@pytest.mark.parametrize(
    "phone, status",
    [
        ("+12345678", 201),           # 8 digits, the shortest allowed
        ("+123456789012345", 201),    # 15 digits, the longest E.164 allows
        ("+1234567", 422),            # 7 digits
        ("+1234567890123456", 422),   # 16 digits
        ("08012345678", 422),         # local format, no country code
        ("+234 801 234 5678", 422),   # spaces
        ("+2348012345678\n", 422),    # trailing newline
        ("", 422),
    ],
)
def test_phone_format(api, user_headers, phone, status):
    response = api.post("/v1/orders", json={**VALID, "phone": phone}, headers=user_headers)
    assert response.status_code == status, response.text


@pytest.mark.parametrize(
    "note, status",
    [
        ("a" * 140, 201),
        ("a" * 141, 422),
        ("ẹ" * 140, 201),           # Yoruba e with dot below: 1 code point, 3 bytes
        ("ሰላም " * 35, 201),  # Amharic "selam" and a space: 4 code points each
        ("\U0001f44b\U0001f3fe" * 70, 201),  # waving hand + skin tone: 2 code points each
        ("\U0001f44b\U0001f3fe" * 71, 422),
    ],
    ids=["ascii-140", "ascii-141", "yoruba-140", "amharic-140", "emoji-70", "emoji-71"],
)
def test_note_length_counts_code_points(api, user_headers, note, status):
    response = api.post("/v1/orders", json={**VALID, "note": note}, headers=user_headers)
    assert response.status_code == status, response.text


def test_unicode_survives_the_round_trip(api, user_headers):
    note = "Ẹ káàbọ̀, مرحبا, 你好"
    created = api.post("/v1/orders", json={**VALID, "note": note}, headers=user_headers)
    assert created.status_code == 201, created.text
    fetched = api.get(f"/v1/orders/{created.json()['id']}", headers=user_headers)
    assert fetched.json()["note"] == note


def test_a_long_string_is_not_echoed_back(api, user_headers):
    response = api.post("/v1/orders", json={**VALID, "note": "x" * 10_000}, headers=user_headers)
    assert_problem(response, 422)
    assert "x" * 200 not in response.text


def test_a_huge_body_is_refused_before_parsing(api, user_headers):
    response = api.post("/v1/orders", json={**VALID, "note": "x" * 20_000}, headers=user_headers)
    assert_problem(response, 413)
    assert api.get("/health").status_code == 200
PY
uv run pytest -v tests/test_boundaries.py

Three tests in this file are easy to forget and catch real bugs:

  • The trailing newline. In Python's re module, $ also matches just before a final newline, so "+2348012345678\n" can slip past a pattern that looks strict. Pydantic uses a Rust regex engine by default, where $ means the end of the text. The test holds that behaviour in place if anyone changes the engine or moves the check.
  • The round trip. The note mixes Yorùbá with a combining accent, Arabic and Chinese. Accepting text is not enough; the API must return it byte for byte as it arrived.
  • Not echoing input. A 10,000-character note gets a 422 whose body does not repeat the note. Error bodies that echo input grow without limit and can copy a password or token from the request into logs. The validation handler in app.py leaves Pydantic's input out for that reason.

The 20,000-character note is refused with a 413 by the middleware, before the JSON is parsed. The check that /health still answers afterwards proves the server stayed up. The middleware reads Content-Length, so a client sending a chunked body without one gets past it; set a body size limit in your reverse proxy as well.

Check it worked

The run ends with 24 passed. You see the cases by name, such as test_note_length_counts_code_points[emoji-71] and test_bundle_size_limits[49-422].

Step 5 · Refuse missing, expired and forged tokens

Authentication tests are negative tests almost by definition: the interesting question is what the API lets through by mistake. Build each bad token deliberately. alg-none is an unsigned token; tampered keeps a real signature but swaps in a different user; no-expiry would never expire if the server accepted it:

Bash
cat > tests/test_auth.py <<'PY'
import base64
import json
import secrets
import time
import uuid

import jwt
import pytest

from helpers import VALID, assert_problem


def soon():
    return int(time.time()) + 300


def tampered(key):
    header, _, signature = jwt.encode(
        {"sub": "user-a", "exp": soon()}, key, algorithm="HS256"
    ).split(".")
    claims = json.dumps({"sub": "user-b", "exp": soon()}).encode()
    payload = base64.urlsafe_b64encode(claims).rstrip(b"=").decode()
    return f"{header}.{payload}.{signature}"


BAD_TOKENS = {
    "expired": lambda key: jwt.encode({"sub": "user-a", "exp": int(time.time()) - 30}, key, algorithm="HS256"),
    "wrong-key": lambda key: jwt.encode({"sub": "user-a", "exp": soon()}, secrets.token_urlsafe(32), algorithm="HS256"),
    "alg-none": lambda key: jwt.encode({"sub": "user-a", "exp": soon()}, None, algorithm="none"),
    "no-expiry": lambda key: jwt.encode({"sub": "user-a"}, key, algorithm="HS256"),
    "no-subject": lambda key: jwt.encode({"exp": soon()}, key, algorithm="HS256"),
    "tampered": tampered,
}


def test_no_token_is_refused(api):
    response = api.post("/v1/orders", json=VALID)
    assert_problem(response, 401)
    assert response.headers["www-authenticate"].startswith("Bearer")


@pytest.mark.parametrize("value", ["Bearer", "Bearer not-a-jwt", "Basic dXNlcjpwYXNz", "Token abc"])
def test_a_malformed_authorization_header_is_refused(api, value):
    response = api.post("/v1/orders", json=VALID, headers={"Authorization": value})
    assert_problem(response, 401)


@pytest.mark.parametrize("name", BAD_TOKENS)
def test_a_bad_token_is_refused(api, signing_key, name):
    token = BAD_TOKENS[name](signing_key)
    response = api.post("/v1/orders", json=VALID, headers={"Authorization": f"Bearer {token}"})
    assert_problem(response, 401)


def test_an_expired_token_says_so(api, make_token):
    token = make_token(expires_in=-30)
    response = api.post("/v1/orders", json=VALID, headers={"Authorization": f"Bearer {token}"})
    body = assert_problem(response, 401)
    assert "expired" in body["detail"]


def test_auth_is_checked_before_the_body(api):
    response = api.post("/v1/orders", json={"price": 0})
    assert_problem(response, 401)


def test_another_user_cannot_read_an_order(api, make_token):
    amara = {"Authorization": f"Bearer {make_token('user-amara')}"}
    kofi = {"Authorization": f"Bearer {make_token('user-kofi')}"}
    order = api.post("/v1/orders", json=VALID, headers=amara).json()

    someone_elses = api.get(f"/v1/orders/{order['id']}", headers=kofi)
    no_such_order = api.get(f"/v1/orders/{uuid.uuid4()}", headers=kofi)

    assert assert_problem(someone_elses, 404) == assert_problem(no_such_order, 404)


def test_a_malformed_order_id_is_rejected(api, user_headers):
    response = api.get("/v1/orders/not-a-uuid", headers=user_headers)
    body = assert_problem(response, 422)
    assert body["errors"][0]["name"] == "order_id"
PY
uv run pytest -v tests/test_auth.py

Two tests check behaviour rather than a single refusal:

  • test_auth_is_checked_before_the_body sends a broken body with no token and expects 401, not 422. An anonymous caller should not be able to learn your field names and rules from validation errors.
  • test_another_user_cannot_read_an_order has Kofi ask for Amara's order. He gets a 404, and the test asserts that the body is identical to the one for an order that does not exist. A 403 here would confirm the order exists, and an attacker can count orders by trying ids.

Every 401 also carries a WWW-Authenticate: Bearer header, which tells clients which scheme to use.

Check it worked

The run ends with 15 passed, including all six test_a_bad_token_is_refused cases from expired to tampered.

Step 6 · Hit the rate limit

A rate limit is only tested when a test goes over it. Send five orders, check the sixth gets a 429 with a Retry-After header that a client can wait on, then check a different user is not affected. The second test makes sure requests that were refused for bad input do not use up a user's allowance:

Bash
cat > tests/test_rate_limit.py <<'PY'
from helpers import VALID, assert_problem


def test_the_sixth_order_in_a_minute_is_refused(api, user_headers, make_token):
    for _ in range(5):
        assert api.post("/v1/orders", json=VALID, headers=user_headers).status_code == 201

    refused = api.post("/v1/orders", json=VALID, headers=user_headers)
    assert_problem(refused, 429)
    assert 1 <= int(refused.headers["retry-after"]) <= 60

    someone_else = {"Authorization": f"Bearer {make_token()}"}
    assert api.post("/v1/orders", json=VALID, headers=someone_else).status_code == 201


def test_rejected_requests_do_not_use_up_the_limit(api, user_headers):
    for _ in range(10):
        assert api.post("/v1/orders", json={}, headers=user_headers).status_code == 422
    for _ in range(5):
        assert api.post("/v1/orders", json=VALID, headers=user_headers).status_code == 201
PY
uv run pytest -v tests/test_rate_limit.py

These tests run in well under a second because they never wait for the window to pass. To test that the limit resets after a minute, make the clock injectable in the app and move it forward in the test instead of sleeping.

The limiter in app.py keeps its counts in the process's memory. That is fine for one process; with several uvicorn workers or servers each one counts on its own, and the real limit becomes five times the number of processes. Move the counts to a shared store such as Redis before you run more than one, and keep these tests: they pass against either.

Check it worked

Both tests pass and the run ends with 2 passed.

Step 7 · Reuse an idempotency key with a different body

A client that times out on POST /v1/orders cannot tell whether the order was made. With an Idempotency-Key header it can send the same request again and get the first answer back instead of a second order. The negative case is the dangerous one: the same key with a different body. The IETF draft for the header says to refuse that with a 422, and the API does:

Bash
cat > tests/test_idempotency.py <<'PY'
import uuid

from helpers import VALID, assert_problem


def with_key(headers, key=None):
    return {**headers, "Idempotency-Key": key or str(uuid.uuid4())}


def test_a_retry_with_the_same_body_returns_the_same_order(api, user_headers):
    headers = with_key(user_headers)
    first = api.post("/v1/orders", json=VALID, headers=headers)
    reordered = {"bundle_mb": 500, "phone": "+2348012345678"}
    retry = api.post("/v1/orders", json=reordered, headers=headers)

    assert first.status_code == retry.status_code == 201
    assert retry.json()["id"] == first.json()["id"]


def test_the_same_key_with_a_different_body_is_refused(api, user_headers):
    headers = with_key(user_headers)
    first = api.post("/v1/orders", json=VALID, headers=headers).json()

    changed = api.post("/v1/orders", json={**VALID, "bundle_mb": 1000}, headers=headers)
    body = assert_problem(changed, 422)
    assert body["type"].endswith("/idempotency-mismatch")

    kept = api.get(f"/v1/orders/{first['id']}", headers=user_headers).json()
    assert kept["bundle_mb"] == 500


def test_retries_do_not_use_up_the_rate_limit(api, user_headers):
    headers = with_key(user_headers)
    for _ in range(8):
        assert api.post("/v1/orders", json=VALID, headers=headers).status_code == 201
    for _ in range(4):
        assert api.post("/v1/orders", json=VALID, headers=user_headers).status_code == 201
    assert_problem(api.post("/v1/orders", json=VALID, headers=user_headers), 429)


def test_keys_belong_to_one_user(api, make_token):
    key = str(uuid.uuid4())
    amina = with_key({"Authorization": f"Bearer {make_token()}"}, key)
    tunde = with_key({"Authorization": f"Bearer {make_token()}"}, key)

    first = api.post("/v1/orders", json=VALID, headers=amina)
    second = api.post("/v1/orders", json={**VALID, "bundle_mb": 1000}, headers=tunde)

    assert first.status_code == second.status_code == 201
    assert first.json()["id"] != second.json()["id"]


def test_an_overlong_key_is_rejected(api, user_headers):
    response = api.post("/v1/orders", json=VALID, headers=with_key(user_headers, "k" * 65))
    body = assert_problem(response, 422)
    assert any("idempotency" in error["name"] for error in body["errors"])
PY
uv run pytest -v tests/test_idempotency.py

What the five tests pin down:

  • A retry with the same content, even with the JSON keys in a different order, returns the same order id. app.py compares a hash of the validated body, not the raw bytes.
  • The same key with a different bundle size is refused, and the first order is left as it was.
  • Replays do not count against the rate limit, so a client on a poor connection is not locked out for retrying.
  • Keys belong to one user. Two users who happen to pick the same key each get their own order.
  • An overlong key is a validation error, not something stored.

One case is not tested here: two requests with the same key arriving at the same moment. In this app both could pass the check before either is saved. A real implementation stores the key with a unique constraint in its database, and the draft suggests a 409 for a request whose twin is still in progress.

Check it worked

The run ends with 5 passed.

Step 8 · Prove every error uses one format

Each test so far checked the format of the refusal it cared about. This last file sweeps the whole API in one place, including errors that no route of yours raises: an unknown path and a wrong method come from the router. If a later change adds an error path that bypasses problem(), this is the file that fails. It also checks that no body carries members beyond the ones the API documents:

Bash
cat > tests/test_error_format.py <<'PY'
import uuid

import pytest

from helpers import VALID, assert_problem

PROBLEM_MEMBERS = {"type", "title", "status", "detail", "instance", "errors"}

CASES = [
    ("no-token", "POST", "/v1/orders", {"json": VALID}, False, 401),
    ("bad-body", "POST", "/v1/orders", {"json": {}}, True, 422),
    ("unknown-route", "GET", "/v1/nothing-here", {}, True, 404),
    ("wrong-method", "DELETE", "/v1/orders", {}, True, 405),
    ("bad-id", "GET", "/v1/orders/not-a-uuid", {}, True, 422),
    ("missing-order", "GET", f"/v1/orders/{uuid.uuid4()}", {}, True, 404),
    ("too-large", "POST", "/v1/orders", {"json": {**VALID, "note": "x" * 20_000}}, True, 413),
]


@pytest.mark.parametrize(
    "method, path, options, signed_in, status",
    [case[1:] for case in CASES],
    ids=[case[0] for case in CASES],
)
def test_every_error_is_a_problem_document(api, user_headers, method, path, options, signed_in, status):
    headers = user_headers if signed_in else {}
    response = api.request(method, path, headers=headers, **options)
    body = assert_problem(response, status)
    assert set(body) <= PROBLEM_MEMBERS


def test_a_wrong_method_lists_the_allowed_ones(api, user_headers):
    response = api.delete("/v1/orders", headers=user_headers)
    assert_problem(response, 405)
    assert response.headers["allow"] == "POST"
PY
uv run pytest -v tests/test_error_format.py

When you add a route or a new kind of refusal, add a row to CASES. That is cheaper than finding out from a client that one endpoint sends HTML error pages.

Then run everything together:

Bash
uv run pytest -q

Check it worked

The error-format file ends with 8 passed, and the full run ends with 65 passed in a few seconds, most of it starting the server.

Step 9 · Clean up

The server stopped when the test run ended. Remove the demo project; Python and uv stay installed:

Bash
cd ~
rm -rf ~/negative-tests-demo

Check it worked

Bash
test ! -e ~/negative-tests-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.