Testing¶
The in-memory test clients, and the live-socket server that drives the native HTTP/1.1 transport.
TestClient
¶
Sync test client - drives the app through its ASGI surface.
Usage::
client = TestClient(app)
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "ok"}
cookies
property
¶
Live view of the client's cookie jar.
Dict-like access, assignment, deletion, iteration and clear(). Cookies
the server sends are merged in, and the state persists across calls until
the client is closed.
set_cookie
¶
Add or update a cookie sent on every subsequent request.
wait_for_background_tasks
¶
Wait for the app's background tasks to finish, on this client's loop.
A background task runs after the response is returned, so a test
asserting its effect would otherwise drive client._loop by hand.
Returns True when everything finished, False on timeout.
Usage::
client.post("/subscribe")
client.wait_for_background_tasks()
assert sent == ["welcome@example.com"]
session_transaction
¶
session_transaction() -> Generator[Session, None, None]
Mutate the session outside a request.
Yields a Session dict pre-loaded from the current session cookie. On
exit it is re-signed with the app's SessionMiddleware secret and stored
in the cookie jar, so the next request carries it::
with client.session_transaction() as sess:
sess["user_id"] = 7
Raises RuntimeError if the app has no SessionMiddleware.
get
¶
get(path: str, headers: _HeadersArg = None, params: dict[str, str] | Sequence[tuple[str, str]] | None = None, follow_redirects: bool | None = None) -> TestResponse
Send a GET request and return the response.
post
¶
post(path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Send a POST.
stream feeds the body as multiple http.request chunks (a sync
Iterable or AsyncIterable of bytes/str); when given it takes
precedence over and excludes json/data/content/files.
put
¶
put(path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Send a PUT. See post for the stream chunked-body parameter.
patch
¶
patch(path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Send a PATCH. See post for the stream chunked-body parameter.
delete
¶
delete(path: str, headers: _HeadersArg = None, follow_redirects: bool | None = None) -> TestResponse
Send a DELETE request and return the response.
head
¶
head(path: str, headers: _HeadersArg = None, follow_redirects: bool | None = None) -> TestResponse
Send a HEAD request and return the response.
options
¶
options(path: str, headers: _HeadersArg = None, follow_redirects: bool | None = None) -> TestResponse
Send an OPTIONS request and return the response.
request
¶
request(method: str, path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, params: dict[str, str] | Sequence[tuple[str, str]] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Dispatch a request of any verb - httpx/test-client shape.
The verb-agnostic form of client.get / client.post / .... Bodies and
params are handled exactly as the per-verb methods do, and stream
excludes the buffered body forms.
websocket_connect
¶
websocket_connect(path: str, subprotocols: list[str] | None = None, headers: _HeadersArg = None) -> _WebSocketSession
Open an in-memory WebSocket against the app - context manager.
Synthesises the scope, sends websocket.connect, routes to the handler,
then forwards calls to it through a pair of asyncio queues.
AsyncTestClient
¶
Async in-memory test client - drives the app through its ASGI surface.
Used as an async context manager inside an async test, so each request is awaited on the test's own running loop rather than a private one.
Usage::
async with AsyncTestClient(app) as client:
resp = await client.get("/")
Cookie persistence, redirect following and the body shapes match TestClient
exactly. WebSocket testing and session_transaction stay on TestClient.
cookies
property
¶
Live view of the client's cookie jar (see TestClient.cookies).
wait_for_background_tasks
async
¶
Wait for the app's background tasks to finish. See TestClient.
set_cookie
¶
Add or update a cookie sent on every subsequent request.
get
async
¶
get(path: str, headers: _HeadersArg = None, params: dict[str, str] | Sequence[tuple[str, str]] | None = None, follow_redirects: bool | None = None) -> TestResponse
Send a GET request and return the response.
post
async
¶
post(path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Send a POST.
stream feeds the body as multiple http.request chunks (a sync
Iterable or AsyncIterable of bytes/str); when given it takes
precedence over and excludes json/data/content/files.
put
async
¶
put(path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Send a PUT. See post for the stream chunked-body parameter.
patch
async
¶
patch(path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Send a PATCH. See post for the stream chunked-body parameter.
delete
async
¶
delete(path: str, headers: _HeadersArg = None, follow_redirects: bool | None = None) -> TestResponse
Send a DELETE request and return the response.
head
async
¶
head(path: str, headers: _HeadersArg = None, follow_redirects: bool | None = None) -> TestResponse
Send a HEAD request and return the response.
options
async
¶
options(path: str, headers: _HeadersArg = None, follow_redirects: bool | None = None) -> TestResponse
Send an OPTIONS request and return the response.
request
async
¶
request(method: str, path: str, json: Any = None, data: dict[str, str] | None = None, headers: _HeadersArg = None, content: bytes | None = None, files: dict[str, Any] | None = None, params: dict[str, str] | Sequence[tuple[str, str]] | None = None, follow_redirects: bool | None = None, stream: StreamBody | None = None) -> TestResponse
Dispatch a request of any verb (see TestClient.request).
TestResponse
¶
What every TestClient / AsyncTestClient call returns.
A read-only view of one ASGI response cycle: status_code, the decoded
text and parsed json(), a case-insensitive headers mapping, the parsed
cookies, and raw_headers for what the mapping flattens (several
Set-Cookie lines join into one headers value). The clients build it.
Usage::
with TestClient(app) as client:
response = client.get("/items/1")
assert response.status_code == 200
assert response.json() == {"id": 1}
assert response.headers["content-type"].startswith("application/json")
LiveServer
¶
Serve an app on a real loopback socket for the duration of a test.
The app runs on the native HttpProtocol transport, so keep-alive reuse,
chunked bodies and response framing are exercised rather than simulated.
Port 0 asks the OS for a free port; port and base_url report it.
Usage::
async with LiveServer(app) as server:
response = await server.get("/items")
assert response.status_code == 200
Each get / post / request call on the server itself uses a fresh
connection. To send several requests down one connection - the thing the
in-memory clients cannot do - use connect()::
async with LiveServer(app) as server, server.connect() as conn:
first = await conn.get("/items")
second = await conn.get("/items")
authority
property
¶
host:port as a URL and a Host: header must spell it.
An IPv6 literal is bracketed (RFC 3986 Sec. 3.2.2), or its colons run
into the port and ::1:8080 names no host.
connect
¶
Return an unopened connection to this server - an async context manager.
Several requests sent through one _LiveConnection share one TCP
connection, which is how a test reaches keep-alive reuse and pipelining.
request
async
¶
request(method: str, path: str, headers: dict[str, str] | None = None, json: Any = None, data: dict[str, str] | None = None, content: bytes | None = None, files: dict[str, Any] | None = None, params: dict[str, str] | Sequence[tuple[str, str]] | None = None, stream: StreamBody | None = None) -> TestResponse
Send one request over a fresh connection and return the response.
The body forms match TestClient: json, data, content and files
are buffered, and stream sends the body with Transfer-Encoding:
chunked instead (it excludes the other four).
The connection closes after the answer, so this sends
Connection: close and a Connection header passed here is replaced.
Hold a connection open with connect() to decide that yourself.
get
async
¶
get(path: str, headers: dict[str, str] | None = None, params: dict[str, str] | Sequence[tuple[str, str]] | None = None) -> TestResponse
Send a GET request over a fresh connection.
post
async
¶
post(path: str, json: Any = None, data: dict[str, str] | None = None, headers: dict[str, str] | None = None, content: bytes | None = None, files: dict[str, Any] | None = None, params: dict[str, str] | Sequence[tuple[str, str]] | None = None, stream: StreamBody | None = None) -> TestResponse
Send a POST request over a fresh connection. See request for the body forms.