|
3 | 3 | import async_timeout
|
4 | 4 | import pytest
|
5 | 5 |
|
| 6 | +from django.test import override_settings |
6 | 7 | from channels.exceptions import ChannelFull
|
7 |
| -from channels.layers import InMemoryChannelLayer |
| 8 | +from channels.generic.websocket import AsyncWebsocketConsumer |
| 9 | +from channels.layers import InMemoryChannelLayer, get_channel_layer |
| 10 | +from channels.testing import WebsocketCommunicator |
8 | 11 |
|
9 | 12 |
|
10 | 13 | @pytest.fixture()
|
@@ -92,6 +95,56 @@ async def test_groups_basic(channel_layer):
|
92 | 95 | await channel_layer.receive("test-gr-chan-2")
|
93 | 96 |
|
94 | 97 |
|
| 98 | +@pytest.mark.asyncio |
| 99 | +async def test_async_group_self(): |
| 100 | + """ |
| 101 | + Tests that AsyncWebsocketConsumer receives messages from a group while processing a previous message |
| 102 | + """ |
| 103 | + results = {} |
| 104 | + |
| 105 | + class TestConsumer(AsyncWebsocketConsumer): |
| 106 | + groups = ["chat"] |
| 107 | + |
| 108 | + async def receive(self, text_data=None, bytes_data=None): |
| 109 | + results["received"] = (text_data, bytes_data) |
| 110 | + assert text_data == "hello" |
| 111 | + await self.channel_layer.group_send("chat", {"type": "chat.message", "message": "message1"}) |
| 112 | + await self.channel_layer.group_send("chat", {"type": "chat.message", "message": "message2"}) |
| 113 | + await asyncio.sleep(0.1) |
| 114 | + await self.send(text_data="message3") |
| 115 | + |
| 116 | + async def chat_message(self, event): |
| 117 | + await self.send(text_data=event["message"]) |
| 118 | + |
| 119 | + app = TestConsumer() |
| 120 | + |
| 121 | + channel_layers_setting = { |
| 122 | + "default": {"BACKEND": "channels.layers.InMemoryChannelLayer"} |
| 123 | + } |
| 124 | + with override_settings(CHANNEL_LAYERS=channel_layers_setting): |
| 125 | + communicator = WebsocketCommunicator(app, "/testws/") |
| 126 | + await communicator.connect() |
| 127 | + |
| 128 | + channel_layer = get_channel_layer() |
| 129 | + |
| 130 | + message = {"type": "websocket.receive", "text": "hello"} |
| 131 | + await channel_layer.group_send("chat", message) |
| 132 | + |
| 133 | + responses = [] |
| 134 | + response = await communicator.receive_from() |
| 135 | + responses.append(response) |
| 136 | + |
| 137 | + response = await communicator.receive_from() |
| 138 | + responses.append(response) |
| 139 | + |
| 140 | + response = await communicator.receive_from() |
| 141 | + responses.append(response) |
| 142 | + |
| 143 | + await communicator.disconnect() |
| 144 | + |
| 145 | + assert responses == ["message1", "message2", "message3"] |
| 146 | + |
| 147 | + |
95 | 148 | @pytest.mark.asyncio
|
96 | 149 | async def test_groups_channel_full(channel_layer):
|
97 | 150 | """
|
|
0 commit comments