|
| 1 | +import json |
| 2 | +import asyncio |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from channels.generic.http import AsyncHttpConsumer |
| 7 | +from channels.testing import HttpCommunicator |
| 8 | + |
| 9 | + |
| 10 | +@pytest.mark.asyncio |
| 11 | +async def test_async_http_consumer(): |
| 12 | + """ |
| 13 | + Tests that AsyncHttpConsumer is implemented correctly. |
| 14 | + """ |
| 15 | + |
| 16 | + class TestConsumer(AsyncHttpConsumer): |
| 17 | + async def handle(self, body): |
| 18 | + self.is_streaming = True |
| 19 | + await self.send_headers(headers=[ |
| 20 | + (b"Cache-Control", b"no-cache"), |
| 21 | + (b"Content-Type", b"text/event-stream"), |
| 22 | + (b"Transfer-Encoding", b"chunked"), |
| 23 | + ]) |
| 24 | + asyncio.get_event_loop().create_task(self.stream()) |
| 25 | + |
| 26 | + async def stream(self): |
| 27 | + for n in range(0, 3): |
| 28 | + if not self.is_streaming: |
| 29 | + break |
| 30 | + payload = "data: %d\n\n" % (n + 1) |
| 31 | + await self.send_body(payload.encode("utf-8"), more_body=True) |
| 32 | + await asyncio.sleep(0.2) |
| 33 | + await self.send_body(b"") |
| 34 | + |
| 35 | + async def disconnect(self): |
| 36 | + self.is_streaming = False |
| 37 | + |
| 38 | + # Open a connection |
| 39 | + communicator = HttpCommunicator( |
| 40 | + TestConsumer, |
| 41 | + method="GET", |
| 42 | + path="/test/", |
| 43 | + body=b"", |
| 44 | + ) |
| 45 | + response = await communicator.get_response() |
| 46 | + assert response["body"] == b'data: 1\n\ndata: 2\n\ndata: 3\n\n' |
| 47 | + assert response["status"] == 200 |
0 commit comments