From: Jean Hominal Date: Sat, 2 Jul 2022 18:11:46 +0000 (+0200) Subject: Test StreamingResponse behavior on receiving http.disconnect (#1727) X-Git-Tag: 0.21.0~38 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=25a52fe52a1fa4f55da4096fb0c7e6f6de0ae980;p=thirdparty%2Fstarlette.git Test StreamingResponse behavior on receiving http.disconnect (#1727) --- diff --git a/tests/test_responses.py b/tests/test_responses.py index a272559e..2030a738 100644 --- a/tests/test_responses.py +++ b/tests/test_responses.py @@ -391,3 +391,34 @@ def test_streaming_response_known_size(test_client_factory): client: TestClient = test_client_factory(app) response = client.get("/") assert response.headers["content-length"] == "10" + + +@pytest.mark.anyio +async def test_streaming_response_stops_if_receiving_http_disconnect(): + streamed = 0 + + disconnected = anyio.Event() + + async def receive_disconnect(): + await disconnected.wait() + return {"type": "http.disconnect"} + + async def send(message): + nonlocal streamed + if message["type"] == "http.response.body": + streamed += len(message.get("body", b"")) + # Simulate disconnection after download has started + if streamed >= 16: + disconnected.set() + + async def stream_indefinitely(): + while True: + # Need a sleep for the event loop to switch to another task + await anyio.sleep(0) + yield b"chunk " + + response = StreamingResponse(content=stream_indefinitely()) + + with anyio.move_on_after(1) as cancel_scope: + await response({}, receive_disconnect, send) + assert not cancel_scope.cancel_called, "Content streaming should stop itself."