Skip to content

Commit 57de5fa

Browse files
authored
Support HTTP response trailers in TestClient (#3563)
1 parent 03f12b7 commit 57de5fa

3 files changed

Lines changed: 146 additions & 3 deletions

File tree

‎docs/testclient.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,43 @@ case you should use `client = TestClient(app, raise_server_exceptions=False)`.
8383
not be triggered when the `TestClient` is instantiated. You can learn more about it
8484
[here](lifespan.md#running-lifespan-in-tests).
8585

86+
### HTTP trailers
87+
88+
The `TestClient` supports the ASGI HTTP trailer extension. Read trailing fields from
89+
`response.extensions["http.response.trailers"]` after the request completes.
90+
91+
```python
92+
from starlette.testclient import TestClient
93+
from starlette.types import Receive, Scope, Send
94+
95+
96+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
97+
await send({
98+
"type": "http.response.start", "status": 200,
99+
"headers": [(b"trailer", b"x-result")], "trailers": True,
100+
})
101+
await send({"type": "http.response.body", "body": b"hello"})
102+
await send({"type": "http.response.trailers", "headers": [(b"x-result", b"complete")]})
103+
104+
105+
def test_trailers() -> None:
106+
response = TestClient(app).get("/", headers={"TE": "trailers"})
107+
assert response.content == b"hello"
108+
assert response.extensions["http.response.trailers"] == [(b"x-result", b"complete")]
109+
```
110+
111+
The extension contains a list of raw byte pairs. It preserves field order and duplicates
112+
across multiple trailer messages. Trailers remain separate from `response.headers`.
113+
Responses that do not declare trailers have no trailer extension on the result.
114+
115+
With `raise_server_exceptions=True`, invalid trailer ordering or returning without final
116+
trailers raises an assertion error. With `raise_server_exceptions=False`, the result contains
117+
only the trailers received before the application failed or returned.
118+
119+
The test transport captures ASGI trailers regardless of `TE` negotiation. It does not emulate
120+
HTTP/2 framing or concurrent request and response streaming. Use a real server and client
121+
to verify those transport behaviors.
122+
86123
### Debug information
87124

88125
The `TestClient` supports the ASGI [`http.response.debug`](https://asgi.readthedocs.io/en/latest/extensions.html#debug)

‎starlette/testclient.py‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,12 +278,15 @@ def handle_request(self, request: httpx.Request) -> httpx.Response:
278278
"headers": headers,
279279
"client": self.client,
280280
"server": [host, port],
281-
"extensions": {"http.response.debug": {}},
281+
"extensions": {"http.response.debug": {}, "http.response.trailers": {}},
282282
"state": self.app_state.copy(),
283283
}
284284

285285
request_complete = False
286286
response_started = False
287+
body_complete = False
288+
trailers_expected = False
289+
trailers: list[tuple[bytes, bytes]] = []
287290
response_complete: anyio.Event
288291
raw_kwargs: dict[str, Any] = {"stream": io.BytesIO()}
289292
debug_info: dict[str, Any] | None = None
@@ -317,22 +320,33 @@ async def receive() -> Message:
317320
return {"type": "http.request", "body": body_bytes}
318321

319322
async def send(message: Message) -> None:
320-
nonlocal raw_kwargs, response_started, debug_info
323+
nonlocal raw_kwargs, response_started, debug_info, body_complete, trailers_expected
321324

322325
if message["type"] == "http.response.start":
323326
assert not response_started, 'Received multiple "http.response.start" messages.'
324327
raw_kwargs["status_code"] = message["status"]
325328
raw_kwargs["headers"] = [(key.decode(), value.decode()) for key, value in message.get("headers", [])]
326329
response_started = True
330+
trailers_expected = message.get("trailers", False)
327331
elif message["type"] == "http.response.body":
328332
assert response_started, 'Received "http.response.body" without "http.response.start".'
329333
assert not response_complete.is_set(), 'Received "http.response.body" after response completed.'
334+
assert not body_complete, 'Received "http.response.body" after body completed.'
330335
body = message.get("body", b"")
331336
more_body = message.get("more_body", False)
332337
if request.method != "HEAD":
333338
raw_kwargs["stream"].write(body)
334339
if not more_body:
335340
raw_kwargs["stream"].seek(0)
341+
body_complete = True
342+
if not trailers_expected:
343+
response_complete.set()
344+
elif message["type"] == "http.response.trailers":
345+
assert trailers_expected, 'Received "http.response.trailers" without declaring trailers.'
346+
assert body_complete, 'Received "http.response.trailers" before body completed.'
347+
assert not response_complete.is_set(), 'Received "http.response.trailers" after response completed.'
348+
trailers.extend(message.get("headers", []))
349+
if not message.get("more_trailers", False):
336350
response_complete.set()
337351
elif message["type"] == "http.response.debug":
338352
debug_info = message["info"]
@@ -357,6 +371,8 @@ async def send(message: Message) -> None:
357371
raw_kwargs["stream"] = httpx.ByteStream(raw_kwargs["stream"].read())
358372

359373
response = httpx.Response(**raw_kwargs, request=request)
374+
if trailers_expected:
375+
response.extensions["http.response.trailers"] = trailers
360376
if debug_info is not None:
361377
response.extensions["http.response.debug"] = debug_info
362378
if "template" in debug_info:

‎tests/test_testclient.py‎

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from starlette.responses import JSONResponse, RedirectResponse, Response
2121
from starlette.routing import Route
2222
from starlette.testclient import ASGIInstance, TestClient
23-
from starlette.types import ASGIApp, Receive, Scope, Send
23+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
2424
from starlette.websockets import WebSocket, WebSocketDisconnect
2525
from tests.types import TestClientFactory
2626

@@ -490,3 +490,93 @@ def test_timeout_deprecation() -> None:
490490
):
491491
client = TestClient(mock_service)
492492
client.get("/", timeout=1)
493+
494+
495+
@pytest.mark.parametrize(
496+
"messages, error",
497+
[
498+
([], "TestClient did not receive any response"),
499+
([{"type": "http.response.trailers"}], "without declaring trailers"),
500+
(
501+
[{"type": "http.response.start", "status": 200, "trailers": True}, {"type": "http.response.trailers"}],
502+
"before body completed",
503+
),
504+
(
505+
[
506+
{"type": "http.response.start", "status": 200, "trailers": True},
507+
{"type": "http.response.body"},
508+
{"type": "http.response.body"},
509+
],
510+
"after body completed",
511+
),
512+
(
513+
[
514+
{"type": "http.response.start", "status": 200, "trailers": True},
515+
{"type": "http.response.body"},
516+
{"type": "http.response.trailers"},
517+
{"type": "http.response.trailers"},
518+
],
519+
"after response completed",
520+
),
521+
],
522+
)
523+
def test_invalid_trailer_sequence(test_client_factory: TestClientFactory, messages: list[Message], error: str) -> None:
524+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
525+
for message in messages:
526+
await send(message)
527+
528+
with pytest.raises(AssertionError, match=error):
529+
test_client_factory(app).get("/")
530+
531+
532+
@pytest.mark.parametrize("empty", [True, False])
533+
def test_capture_trailers(test_client_factory: TestClientFactory, empty: bool) -> None:
534+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
535+
assert "http.response.trailers" in scope["extensions"]
536+
await send({"type": "http.response.start", "status": 200, "trailers": True})
537+
await send({"type": "http.response.body", "body": b"hello"})
538+
await anyio.lowlevel.checkpoint()
539+
headers = [] if empty else [(b"x-item", b"one")]
540+
await send({"type": "http.response.trailers", "headers": headers, "more_trailers": True})
541+
headers = [] if empty else [(b"x-item", b"two")]
542+
await send({"type": "http.response.trailers", "headers": headers})
543+
544+
response = test_client_factory(app).get("/", headers={"te": "trailers"})
545+
assert response.content == b"hello"
546+
assert response.extensions["http.response.trailers"] == (
547+
[] if empty else [(b"x-item", b"one"), (b"x-item", b"two")]
548+
)
549+
assert "x-item" not in response.headers
550+
551+
552+
@pytest.mark.parametrize("partial", [True, False])
553+
def test_incomplete_trailers(test_client_factory: TestClientFactory, partial: bool) -> None:
554+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
555+
await send({"type": "http.response.start", "status": 200, "trailers": True})
556+
await send({"type": "http.response.body", "body": b"hello"})
557+
if partial:
558+
await send({"type": "http.response.trailers", "headers": [(b"x-item", b"partial")], "more_trailers": True})
559+
560+
response = test_client_factory(app).get("/")
561+
assert response.content == b"hello"
562+
assert response.extensions["http.response.trailers"] == ([(b"x-item", b"partial")] if partial else [])
563+
564+
565+
@pytest.mark.parametrize("raise_server_exceptions", [True, False])
566+
def test_trailer_error_respects_raise_server_exceptions(
567+
test_client_factory: TestClientFactory, raise_server_exceptions: bool
568+
) -> None:
569+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
570+
await send({"type": "http.response.start", "status": 200, "trailers": True})
571+
await send({"type": "http.response.body", "body": b"hello"})
572+
await send({"type": "http.response.trailers", "headers": [(b"x-item", b"partial")], "more_trailers": True})
573+
raise ValueError("trailer production failed")
574+
575+
client = test_client_factory(app, raise_server_exceptions=raise_server_exceptions)
576+
if raise_server_exceptions:
577+
with pytest.raises(ValueError, match="trailer production failed"):
578+
client.get("/")
579+
else:
580+
response = client.get("/")
581+
assert response.content == b"hello"
582+
assert response.extensions["http.response.trailers"] == [(b"x-item", b"partial")]

0 commit comments

Comments
 (0)