Skip to content

Commit

Permalink
Test StreamingResponse behavior on receiving http.disconnect (#1727)
Browse files Browse the repository at this point in the history
  • Loading branch information
jhominal authored Jul 2, 2022
1 parent a3b43f0 commit 25a52fe
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."

0 comments on commit 25a52fe

Please sign in to comment.