Skip to content

Commit 9eea41a

Browse files
y2kbuggerKludex
andauthored
Expose http.response.debug info via response extensions (#3130)
Co-authored-by: Marcelo Trylesinski <[email protected]>
1 parent 38f8999 commit 9eea41a

3 files changed

Lines changed: 94 additions & 8 deletions

File tree

‎docs/testclient.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,52 @@ 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+
### Debug information
87+
88+
The `TestClient` supports the ASGI [`http.response.debug`](https://asgi.readthedocs.io/en/latest/extensions.html#debug)
89+
extension. The `info` dictionary sent by the application is available as
90+
`response.extensions["http.response.debug"]`, which allows custom response classes to
91+
expose additional debug information to tests.
92+
93+
This is useful when asserting on the response body would mean parsing it back. Consider
94+
a response class that renders rows into a CSV file. By sending the rows through the
95+
debug extension, tests can assert on the original data instead of the serialized body:
96+
97+
```python
98+
import csv
99+
import io
100+
101+
from starlette.responses import Response
102+
103+
104+
class CSVResponse(Response):
105+
media_type = "text/csv"
106+
107+
def __init__(self, rows):
108+
self.rows = rows
109+
buffer = io.StringIO()
110+
csv.writer(buffer).writerows(rows)
111+
super().__init__(buffer.getvalue())
112+
113+
async def __call__(self, scope, receive, send):
114+
if "http.response.debug" in scope.get("extensions", {}):
115+
await send({"type": "http.response.debug", "info": {"rows": self.rows}})
116+
await super().__call__(scope, receive, send)
117+
118+
119+
def test_export():
120+
client = TestClient(app)
121+
response = client.get("/export")
122+
rows = response.extensions["http.response.debug"]["rows"]
123+
assert rows[0] == ("id", "username", "joined")
124+
assert len(rows) == 101
125+
```
126+
127+
Template responses use the same extension to expose the `.template` and `.context`
128+
response attributes - see [testing template responses](templates.md#testing-template-responses).
129+
The `info` dictionary is always available as `response.extensions["http.response.debug"]`,
130+
even when it carries `template`/`context` keys.
131+
86132
### Change client address
87133

88134
By default, the TestClient will set the client host to `"testclient"` and the port to `50000`.

‎starlette/testclient.py‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -294,8 +294,7 @@ def handle_request(self, request: httpx.Request) -> httpx.Response:
294294
response_started = False
295295
response_complete: anyio.Event
296296
raw_kwargs: dict[str, Any] = {"stream": io.BytesIO()}
297-
template = None
298-
context = None
297+
debug_info: dict[str, Any] | None = None
299298

300299
async def receive() -> Message:
301300
nonlocal request_complete
@@ -326,7 +325,7 @@ async def receive() -> Message:
326325
return {"type": "http.request", "body": body_bytes}
327326

328327
async def send(message: Message) -> None:
329-
nonlocal raw_kwargs, response_started, template, context
328+
nonlocal raw_kwargs, response_started, debug_info
330329

331330
if message["type"] == "http.response.start":
332331
assert not response_started, 'Received multiple "http.response.start" messages.'
@@ -344,8 +343,7 @@ async def send(message: Message) -> None:
344343
raw_kwargs["stream"].seek(0)
345344
response_complete.set()
346345
elif message["type"] == "http.response.debug":
347-
template = message["info"]["template"]
348-
context = message["info"]["context"]
346+
debug_info = message["info"]
349347

350348
try:
351349
with self.portal_factory() as portal:
@@ -367,9 +365,12 @@ async def send(message: Message) -> None:
367365
raw_kwargs["stream"] = httpx.ByteStream(raw_kwargs["stream"].read())
368366

369367
response = httpx.Response(**raw_kwargs, request=request)
370-
if template is not None:
371-
response.template = template # type: ignore[attr-defined]
372-
response.context = context # type: ignore[attr-defined]
368+
if debug_info is not None:
369+
response.extensions["http.response.debug"] = debug_info
370+
if "template" in debug_info:
371+
response.template = debug_info["template"] # type: ignore[attr-defined]
372+
if "context" in debug_info:
373+
response.context = debug_info["context"] # type: ignore[attr-defined]
373374
return response
374375

375376

‎tests/test_testclient.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,45 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
230230
assert response.text == "Hello, world!"
231231

232232

233+
def test_debug_info_in_response_extensions(test_client_factory: TestClientFactory) -> None:
234+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
235+
await send(
236+
{
237+
"type": "http.response.start",
238+
"status": 200,
239+
"headers": [[b"content-type", b"text/plain"]],
240+
}
241+
)
242+
await send({"type": "http.response.debug", "info": {"fragment": "header", "blocks": ["nav", "title"]}})
243+
await send({"type": "http.response.body", "body": b"Hello, world!"})
244+
245+
client = test_client_factory(app)
246+
response = client.get("/")
247+
assert response.extensions["http.response.debug"] == {"fragment": "header", "blocks": ["nav", "title"]}
248+
assert not hasattr(response, "template")
249+
250+
251+
def test_debug_info_in_response_extensions_with_template(test_client_factory: TestClientFactory) -> None:
252+
info = {"template": "index.html", "context": {"name": "world"}, "blocks": ["nav"]}
253+
254+
async def app(scope: Scope, receive: Receive, send: Send) -> None:
255+
await send(
256+
{
257+
"type": "http.response.start",
258+
"status": 200,
259+
"headers": [[b"content-type", b"text/plain"]],
260+
}
261+
)
262+
await send({"type": "http.response.debug", "info": info})
263+
await send({"type": "http.response.body", "body": b"Hello, world!"})
264+
265+
client = test_client_factory(app)
266+
response = client.get("/")
267+
assert response.extensions["http.response.debug"] == info
268+
assert response.template == "index.html" # type: ignore[attr-defined]
269+
assert response.context == {"name": "world"} # type: ignore[attr-defined]
270+
271+
233272
def test_websocket_blocking_receive(test_client_factory: TestClientFactory) -> None:
234273
def app(scope: Scope) -> ASGIInstance:
235274
async def respond(websocket: WebSocket) -> None:

0 commit comments

Comments
 (0)