CodeSampleX

サンプル

fastapi 0.141.1: Test a FastAPI app with TestClient and no network, and assert the validation error bodies it returns

検証済みサンプル — pypi fastapi 0.141.1: Test a FastAPI app with TestClient and no network, and assert the validation error bodies it returns. python 3.12 · linux…

sha256:8bcaa6f98cea6edf681d2b0f76a18856106de62aab70009b1d22a5a50abb1257

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
2
宣言された環境 python 3.12 linux x64 python 3.12 python pip

検証実行環境

環境 コントラクト ステージ 実行日
python 3.12 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-14
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

ケース

HOW
ゴール
Test a FastAPI app with TestClient and no network, and assert the validation error bodies it returns
パッケージ
シンボル
  • fastapi.testclient.TestClient
  • fastapi.HTTPException
  • response_model
  • lifespan
  • pydantic.BaseModel
  • httpx2.HTTPStatusError
  • starlette.exceptions.StarletteDeprecationWarning
環境
python 3.12
作成日
2026-08-14T08:53:22Z

コントラクト

  1. assert TestClient targets http://testserver, so the run needs no socket, no port and no DNS
  2. assert TestClient drives the real ASGI pipeline, so pure ASGI middleware runs and stamps a header on the response
  3. assert calling the endpoint function directly does no coercion, so it returns nonsense instead of a 422
  4. assert an int path parameter given text answers 422 with detail[0].type int_parsing and loc path/item_id
  5. assert every 422 entry carries exactly type, loc, msg and input, and input echoes the submitted body back to the caller
  6. assert a missing body field answers 422 with type missing and loc body/age
  7. assert a valid body answers the declared 201 and response_model removes the extra field the handler returned
  8. assert an unexpected field in the request body is ignored by the model rather than rejected
  9. assert HTTPException(404) serialises to a single detail string
  10. assert the lifespan runs only when TestClient is entered as a context manager, so a plain client leaves startup unrun
  11. assert starlette 1.6 binds httpx2 for TestClient when both httpx2 and httpx are installed, so the response is not an httpx.Response
  12. assert raise_for_status on a TestClient response raises httpx2.HTTPStatusError, which except httpx.HTTPStatusError does not catch
  13. assert fastapi.testclient.TestClient is starlette's class re-exported unchanged
  14. assert hiding httpx2 makes the import fall back to httpx with a StarletteDeprecationWarning, which is a UserWarning and not a DeprecationWarning

ファイル

  • csx.json
  • requirements.txt
  • src/__init__.py
  • src/app.py
  • test/contract.py

ソースアーティファクトをダウンロード (tar.gz)

ソース

csx.json
{"case":{"caseId":"case:sha256:c48ef4a6a65425c73261b977bc5bf581c1606f8cc644e73a3f2c08c5fbc5c359","constraints":{"runtime":"python"},"contract":["assert TestClient targets http://testserver, so the run needs no socket, no port and no DNS","assert TestClient drives the real ASGI pipeline, so pure ASGI middleware runs and stamps a header on the response","assert calling the endpoint function directly does no coercion, so it returns nonsense instead of a 422","assert an int path parameter given text answers 422 with detail[0].type int_parsing and loc path/item_id","assert every 422 entry carries exactly type, loc, msg and input, and input echoes the submitted body back to the caller","assert a missing body field answers 422 with type missing and loc body/age","assert a valid body answers the declared 201 and response_model removes the extra field the handler returned","assert an unexpected field in the request body is ignored by the model rather than rejected","assert HTTPException(404) serialises to a single detail string","assert the lifespan runs only when TestClient is entered as a context manager, so a plain client leaves startup unrun","assert starlette 1.6 binds httpx2 for TestClient when both httpx2 and httpx are installed, so the response is not an httpx.Response","assert raise_for_status on a TestClient response raises httpx2.HTTPStatusError, which except httpx.HTTPStatusError does not catch","assert fastapi.testclient.TestClient is starlette's class re-exported unchanged","assert hiding httpx2 makes the import fall back to httpx with a StarletteDeprecationWarning, which is a UserWarning and not a DeprecationWarning"],"goal":"Test a FastAPI app with TestClient and no network, and assert the validation error bodies it returns","kind":"HOW","packages":["pkg:pypi/fastapi@0.141.1","pkg:pypi/starlette@1.6.0","pkg:pypi/httpx2@2.10.0","pkg:pypi/httpx@0.28.1","pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["fastapi.testclient.TestClient","fastapi.HTTPException","response_model","lifespan","pydantic.BaseModel","httpx2.HTTPStatusError","starlette.exceptions.StarletteDeprecationWarning"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/fastapi@0.141.1","pkg:pypi/starlette@1.6.0","pkg:pypi/httpx2@2.10.0","pkg:pypi/httpx@0.28.1","pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["fastapi.testclient.TestClient","fastapi.HTTPException","response_model","lifespan","pydantic.BaseModel","httpx2.HTTPStatusError","starlette.exceptions.StarletteDeprecationWarning"],"verifierAdapter":"python@1"}
requirements.txt
# The full closure, because it is installed with --no-deps. Three entries
# that a list copied from an older project gets wrong: fastapi now pulls
# annotated-doc, anyio 4.14 no longer requires sniffio, and TestClient's
# http client is httpx2 (with httpcore2 and truststore, not h11/certifi).
# httpx is here only so the contract can show which one starlette picks.
fastapi==0.141.1
starlette==1.6.0
annotated-doc==0.0.5
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.16.0
typing-inspection==0.4.4
annotated-types==0.8.0
anyio==4.14.2
idna==3.18
httpx2==2.10.0
httpcore2==2.10.0
truststore==0.10.4
httpx==0.28.1
httpcore==1.0.9
h11==0.16.0
certifi==2026.7.22
src/__init__.py
src/app.py
"""A FastAPI app shaped so a test can prove what TestClient actually does.

TestClient is not a shortcut around the app. It runs the app on a
background event loop (anyio's blocking portal) behind a transport that
hands the ASGI scope straight to the app, so middleware, path-parameter
coercion, request validation and response serialisation all run the same
code they run behind a real server. Nothing binds a port and nothing
resolves a host name, which is why this whole sample runs with the network
switched off.

That distinction is the trap. Calling an endpoint function directly is a
different operation: no coercion, no validation, no response_model. It can
never return 422 and it cannot strip a field, so a "unit test" that calls
the function tests none of the behaviour people actually rely on.
read_item("abc") happily doubles the string — see test/contract.py.

Three deliberate shapes below: read_item takes an int the caller can only
send as text, create_user returns one field more than it declares so
response_model has something to remove, and the app has a lifespan, which
plain TestClient(app) never runs.
"""

from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send


class UserIn(BaseModel):
    name: str
    age: int


class UserOut(BaseModel):
    name: str
    age: int


LIFECYCLE = []


@asynccontextmanager
async def lifespan(_: FastAPI):
    # Whatever a real app opens here — a pool, a cache, a client — stays
    # closed under a bare TestClient(app), because the lifespan scope is
    # only sent when the client is entered as a context manager. A suite
    # that never writes `with TestClient(app) as client` tests an app whose
    # startup never ran.
    LIFECYCLE.append("startup")
    yield
    LIFECYCLE.append("shutdown")


api = FastAPI(lifespan=lifespan)

USERS = {1: {"name": "ada", "age": 36}}


@api.get("/items/{item_id}")
def read_item(item_id: int):
    # item_id arrives as text on the wire. FastAPI converts it, or answers
    # 422 before this body runs. Called as a function, the annotation is
    # inert and item_id is whatever you passed.
    return {"item_id": item_id, "doubled": item_id * 2}


@api.post("/users", response_model=UserOut, status_code=201)
def create_user(payload: UserIn):
    # The extra key is the point: response_model is a filter on the way
    # out, not a description of the return value. Nothing here prevents a
    # handler from returning a secret; the declared model is what stops it
    # reaching the client.
    return {"name": payload.name, "age": payload.age,
            "password_hash": "sha256:0ddba11"}


@api.get("/users/{user_id}")
def read_user(user_id: int):
    if user_id not in USERS:
        raise HTTPException(status_code=404, detail="user not found")
    return USERS[user_id]


class AsgiMarker:
    """Pure ASGI middleware that can only run if a real request happens.

    It counts http scopes and stamps a header on every response. A test
    that called the endpoint function would leave the counter at zero, so
    the counter is the evidence that TestClient went through the app.
    """

    def __init__(self, app: ASGIApp) -> None:
        self.app = app
        self.http_calls = 0

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            # A lifespan or websocket scope has no http.response.start to
            # stamp, so it is forwarded untouched. Swallowing it here is the
            # classic way a hand-written middleware silently disables an
            # app's startup; the contract checks the lifespan still fires.
            await self.app(scope, receive, send)
            return
        self.http_calls += 1
        seen = self.http_calls

        async def send_marked(message: Message) -> None:
            if message["type"] == "http.response.start":
                MutableHeaders(scope=message)["x-asgi-marker"] = str(seen)
            await send(message)

        await self.app(scope, receive, send_marked)


app = AsgiMarker(api)
test/contract.py
import importlib
import sys
import warnings
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import httpx
import httpx2
import starlette
import starlette.testclient
from fastapi import __version__ as fastapi_version
from fastapi.testclient import TestClient
from starlette.exceptions import StarletteDeprecationWarning

from src.app import LIFECYCLE, UserIn, api, app, create_user, read_item

client = TestClient(app)

# TestClient talks to a host name that exists nowhere. No socket, no port,
# no DNS: this file runs with the network disabled.
assert str(client.base_url) == "http://testserver"

# --- a real request went through the app, not into the function ----------
before = app.http_calls
ok = client.get("/items/7")
assert ok.status_code == 200
assert ok.json() == {"item_id": 7, "doubled": 14}
assert app.http_calls == before + 1
assert ok.headers["x-asgi-marker"] == str(app.http_calls)

# Calling the same endpoint as a plain function skips every layer. The int
# annotation does nothing, so "abc" * 2 is the answer instead of a 422.
assert read_item("abc") == {"item_id": "abc", "doubled": "abcabc"}
assert app.http_calls == before + 1

# --- an int path parameter rejects text with 422 -------------------------
# 422, not 400 and not 404: FastAPI treats an unparseable path parameter as
# a validation failure. The body is a list under "detail", and each entry
# carries exactly these four keys — a client that reads exc["detail"]["msg"]
# is indexing a list with a string.
bad = client.get("/items/abc")
assert bad.status_code == 422
detail = bad.json()["detail"]
assert len(detail) == 1
assert set(detail[0]) == {"type", "loc", "msg", "input"}
assert detail[0]["type"] == "int_parsing"
assert detail[0]["loc"] == ["path", "item_id"]
assert detail[0]["input"] == "abc"
assert detail[0]["msg"] == (
    "Input should be a valid integer, unable to parse string as an integer")

# --- a missing body field is 422, and the loc says where ----------------
missing = client.post("/users", json={"name": "ada"})
assert missing.status_code == 422
assert set(missing.json()["detail"][0]) == {"type", "loc", "msg", "input"}
assert missing.json()["detail"][0]["type"] == "missing"
assert missing.json()["detail"][0]["loc"] == ["body", "age"]
assert missing.json()["detail"][0]["msg"] == "Field required"

# The 422 echoes the offending input straight back to the caller. For a
# body error that is the whole submitted object, so a route that validates
# a payload containing a password answers with the password in it. Replace
# the default handler for RequestValidationError if that matters.
assert missing.json()["detail"][0]["input"] == {"name": "ada"}

# --- a valid body is accepted, and response_model filters the reply -----
created = client.post("/users", json={"name": "ada", "age": 36})
assert created.status_code == 201
assert created.json() == {"name": "ada", "age": 36}

# The handler really did return the extra field. response_model removed it
# on the way out; the function is untouched by the declaration.
leaked = create_user(UserIn(name="ada", age=36))
assert leaked["password_hash"] == "sha256:0ddba11"

# An unexpected field in the request body is ignored, not rejected:
# pydantic v2 models default to extra="ignore". The 201 on its own does not
# show that the field was dropped, since response_model would have hidden a
# carried-through field either way, so the model is checked directly too.
extra = client.post("/users", json={"name": "ada", "age": 36, "role": "admin"})
assert extra.status_code == 201
assert extra.json() == {"name": "ada", "age": 36}
loaded = UserIn.model_validate({"name": "ada", "age": 36, "role": "admin"})
assert loaded.model_dump() == {"name": "ada", "age": 36}
assert loaded.model_extra is None

# --- HTTPException is a JSON object with one key ------------------------
absent = client.get("/users/999")
assert absent.status_code == 404
assert absent.json() == {"detail": "user not found"}
assert client.get("/users/1").json() == {"name": "ada", "age": 36}

# --- the lifespan only runs inside a with block -------------------------
# Every request above went through the app, and startup still has not run.
# TestClient sends the lifespan scope from __enter__, so a suite that keeps
# a module-level client tests an app whose pools were never opened.
assert LIFECYCLE == []
with TestClient(app) as started:
    assert LIFECYCLE == ["startup"]
    assert started.get("/items/2").json() == {"item_id": 2, "doubled": 4}
assert LIFECYCLE == ["startup", "shutdown"]

# --- which httpx TestClient is holding ---------------------------------
# starlette 1.6 imports httpx2 for TestClient and only falls back to httpx
# with a StarletteDeprecationWarning. With both installed httpx2 wins, so
# the response is an httpx2.Response: annotating a test helper with
# httpx.Response, or catching httpx.HTTPStatusError around a TestClient
# call, is wrong in a way no import error will tell you about.
assert starlette.testclient.httpx is httpx2
assert isinstance(ok, httpx2.Response)
assert not isinstance(ok, httpx.Response)

# The exception classes are separate hierarchies, so the except clause a
# 2024 test suite already has does not catch what raise_for_status raises.
try:
    absent.raise_for_status()
except httpx2.HTTPStatusError as exc:
    assert not isinstance(exc, httpx.HTTPStatusError)
else:
    raise AssertionError("404 did not raise")

# TestClient is starlette's, re-exported. FastAPI adds nothing to it.
assert TestClient is starlette.testclient.TestClient

# Prove the fallback rather than describing it: hide httpx2 from the import
# machinery and load the module again. It warns and binds plain httpx, at
# which point every response is an httpx.Response instead — the same test
# suite, different response class, no error anywhere.


class BlockHttpx2:
    def find_spec(self, name, path=None, target=None):
        if name == "httpx2":
            raise ModuleNotFoundError("No module named 'httpx2'", name="httpx2")
        return None


sys.meta_path.insert(0, BlockHttpx2())
del sys.modules["httpx2"], sys.modules["starlette.testclient"]
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    legacy = importlib.import_module("starlette.testclient")
sys.meta_path.pop(0)
sys.modules["httpx2"] = httpx2

assert [type(w.message) for w in caught] == [StarletteDeprecationWarning]
assert "httpx2" in str(caught[0].message)
assert legacy.httpx is httpx

# And the warning is a UserWarning, not a DeprecationWarning. Test suites
# that turn DeprecationWarning into an error to catch exactly this kind of
# drift will not see it.
assert issubclass(StarletteDeprecationWarning, UserWarning)
assert not issubclass(StarletteDeprecationWarning, DeprecationWarning)

print("contract ok:", fastapi_version, "starlette", starlette.__version__,
      "testclient on httpx2", httpx2.__version__)

オリジンシーダー

anonymous