forked from django/channels
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_generic_websocket.py
357 lines (291 loc) · 12.1 KB
/
test_generic_websocket.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import pytest
from django.test import override_settings
from channels.generic.websocket import (
AsyncJsonWebsocketConsumer,
AsyncWebsocketConsumer,
JsonWebsocketConsumer,
WebsocketConsumer,
)
from channels.layers import get_channel_layer
from channels.testing import WebsocketCommunicator
@pytest.mark.asyncio
async def test_websocket_consumer():
"""
Tests that WebsocketConsumer is implemented correctly.
"""
results = {}
class TestConsumer(WebsocketConsumer):
def connect(self):
results["connected"] = True
self.accept()
def receive(self, text_data=None, bytes_data=None):
results["received"] = (text_data, bytes_data)
self.send(text_data=text_data, bytes_data=bytes_data)
def disconnect(self, code):
results["disconnected"] = code
# Test a normal connection
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
connected, _ = await communicator.connect()
assert connected
assert "connected" in results
# Test sending text
await communicator.send_to(text_data="hello")
response = await communicator.receive_from()
assert response == "hello"
assert results["received"] == ("hello", None)
# Test sending bytes
await communicator.send_to(bytes_data=b"w\0\0\0")
response = await communicator.receive_from()
assert response == b"w\0\0\0"
assert results["received"] == (None, b"w\0\0\0")
# Close out
await communicator.disconnect()
assert "disconnected" in results
@pytest.mark.asyncio
async def test_websocket_consumer_subprotocol():
"""
Tests that WebsocketConsumer correctly handles subprotocols.
"""
class TestConsumer(WebsocketConsumer):
def connect(self):
assert self.scope["subprotocols"] == ["subprotocol1", "subprotocol2"]
self.accept("subprotocol2")
# Test a normal connection with subprotocols
communicator = WebsocketCommunicator(
TestConsumer, "/testws/", subprotocols=["subprotocol1", "subprotocol2"]
)
connected, subprotocol = await communicator.connect()
assert connected
assert subprotocol == "subprotocol2"
@pytest.mark.asyncio
async def test_websocket_consumer_groups():
"""
Tests that WebsocketConsumer adds and removes channels from groups.
"""
results = {}
class TestConsumer(WebsocketConsumer):
groups = ["chat"]
def receive(self, text_data=None, bytes_data=None):
results["received"] = (text_data, bytes_data)
self.send(text_data=text_data, bytes_data=bytes_data)
channel_layers_setting = {
"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}
}
with override_settings(CHANNEL_LAYERS=channel_layers_setting):
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
await communicator.connect()
channel_layer = get_channel_layer()
# Test that the websocket channel was added to the group on connect
message = {"type": "websocket.receive", "text": "hello"}
await channel_layer.group_send("chat", message)
response = await communicator.receive_from()
assert response == "hello"
assert results["received"] == ("hello", None)
# Test that the websocket channel was discarded from the group on disconnect
await communicator.disconnect()
assert channel_layer.groups == {}
@pytest.mark.asyncio
async def test_async_websocket_consumer():
"""
Tests that AsyncWebsocketConsumer is implemented correctly.
"""
results = {}
class TestConsumer(AsyncWebsocketConsumer):
async def connect(self):
results["connected"] = True
await self.accept()
async def receive(self, text_data=None, bytes_data=None):
results["received"] = (text_data, bytes_data)
await self.send(text_data=text_data, bytes_data=bytes_data)
async def disconnect(self, code):
results["disconnected"] = code
# Test a normal connection
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
connected, _ = await communicator.connect()
assert connected
assert "connected" in results
# Test sending text
await communicator.send_to(text_data="hello")
response = await communicator.receive_from()
assert response == "hello"
assert results["received"] == ("hello", None)
# Test sending bytes
await communicator.send_to(bytes_data=b"w\0\0\0")
response = await communicator.receive_from()
assert response == b"w\0\0\0"
assert results["received"] == (None, b"w\0\0\0")
# Close out
await communicator.disconnect()
assert "disconnected" in results
@pytest.mark.asyncio
async def test_async_websocket_consumer_subprotocol():
"""
Tests that AsyncWebsocketConsumer correctly handles subprotocols.
"""
class TestConsumer(AsyncWebsocketConsumer):
async def connect(self):
assert self.scope["subprotocols"] == ["subprotocol1", "subprotocol2"]
await self.accept("subprotocol2")
# Test a normal connection with subprotocols
communicator = WebsocketCommunicator(
TestConsumer, "/testws/", subprotocols=["subprotocol1", "subprotocol2"]
)
connected, subprotocol = await communicator.connect()
assert connected
assert subprotocol == "subprotocol2"
@pytest.mark.asyncio
async def test_async_websocket_consumer_groups():
"""
Tests that AsyncWebsocketConsumer adds and removes channels from groups.
"""
results = {}
class TestConsumer(AsyncWebsocketConsumer):
groups = ["chat"]
async def receive(self, text_data=None, bytes_data=None):
results["received"] = (text_data, bytes_data)
await self.send(text_data=text_data, bytes_data=bytes_data)
channel_layers_setting = {
"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}
}
with override_settings(CHANNEL_LAYERS=channel_layers_setting):
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
await communicator.connect()
channel_layer = get_channel_layer()
# Test that the websocket channel was added to the group on connect
message = {"type": "websocket.receive", "text": "hello"}
await channel_layer.group_send("chat", message)
response = await communicator.receive_from()
assert response == "hello"
assert results["received"] == ("hello", None)
# Test that the websocket channel was discarded from the group on disconnect
await communicator.disconnect()
assert channel_layer.groups == {}
@pytest.mark.asyncio
async def test_async_websocket_consumer_specific_channel_layer():
"""
Tests that AsyncWebsocketConsumer uses the specified channel layer.
"""
results = {}
class TestConsumer(AsyncWebsocketConsumer):
channel_layer_alias = "testlayer"
async def receive(self, text_data=None, bytes_data=None):
results["received"] = (text_data, bytes_data)
await self.send(text_data=text_data, bytes_data=bytes_data)
channel_layers_setting = {
"testlayer": {"BACKEND": "channels.layers.InMemoryChannelLayer"}
}
with override_settings(CHANNEL_LAYERS=channel_layers_setting):
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
await communicator.connect()
channel_layer = get_channel_layer("testlayer")
# Test that the specific channel layer is retrieved
assert channel_layer != None
channel_name = list(channel_layer.channels.keys())[0]
message = {"type": "websocket.receive", "text": "hello"}
await channel_layer.send(channel_name, message)
response = await communicator.receive_from()
assert response == "hello"
assert results["received"] == ("hello", None)
await communicator.disconnect()
@pytest.mark.asyncio
async def test_json_websocket_consumer():
"""
Tests that JsonWebsocketConsumer is implemented correctly.
"""
results = {}
class TestConsumer(JsonWebsocketConsumer):
def connect(self):
self.accept()
def receive_json(self, data=None):
results["received"] = data
self.send_json(data)
# Open a connection
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
connected, _ = await communicator.connect()
assert connected
# Test sending
await communicator.send_json_to({"hello": "world"})
response = await communicator.receive_json_from()
assert response == {"hello": "world"}
assert results["received"] == {"hello": "world"}
# Test sending bytes breaks it
await communicator.send_to(bytes_data=b"w\0\0\0")
with pytest.raises(ValueError):
await communicator.wait()
@pytest.mark.asyncio
async def test_async_json_websocket_consumer():
"""
Tests that AsyncJsonWebsocketConsumer is implemented correctly.
"""
results = {}
class TestConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
async def receive_json(self, data=None):
results["received"] = data
await self.send_json(data)
# Open a connection
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
connected, _ = await communicator.connect()
assert connected
# Test sending
await communicator.send_json_to({"hello": "world"})
response = await communicator.receive_json_from()
assert response == {"hello": "world"}
assert results["received"] == {"hello": "world"}
# Test sending bytes breaks it
await communicator.send_to(bytes_data=b"w\0\0\0")
with pytest.raises(ValueError):
await communicator.wait()
@pytest.mark.asyncio
async def test_block_underscored_type_function_call():
"""
Test that consumer prevent calling private functions as handler
"""
class TestConsumer(AsyncWebsocketConsumer):
channel_layer_alias = "testlayer"
async def _my_private_handler(self, _):
await self.send(text_data="should never be called")
channel_layers_setting = {
"testlayer": {"BACKEND": "channels.layers.InMemoryChannelLayer"}
}
with override_settings(CHANNEL_LAYERS=channel_layers_setting):
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
await communicator.connect()
channel_layer = get_channel_layer("testlayer")
# Test that the specific channel layer is retrieved
assert channel_layer != None
channel_name = list(channel_layer.channels.keys())[0]
# Should block call to private functions handler and raise ValueError
message = {"type": "_my_private_handler", "text": "hello"}
await channel_layer.send(channel_name, message)
with pytest.raises(
ValueError, match=r"Malformed type in message \(leading underscore\)"
):
await communicator.receive_from()
@pytest.mark.asyncio
async def test_block_leading_dot_type_function_call():
"""
Test that consumer prevent calling private functions as handler
"""
class TestConsumer(AsyncWebsocketConsumer):
channel_layer_alias = "testlayer"
async def _my_private_handler(self, _):
await self.send(text_data="should never be called")
channel_layers_setting = {
"testlayer": {"BACKEND": "channels.layers.InMemoryChannelLayer"}
}
with override_settings(CHANNEL_LAYERS=channel_layers_setting):
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
await communicator.connect()
channel_layer = get_channel_layer("testlayer")
# Test that the specific channel layer is retrieved
assert channel_layer != None
channel_name = list(channel_layer.channels.keys())[0]
# Should not replace dot by underscore and call private function (see issue: #1430)
message = {"type": ".my_private_handler", "text": "hello"}
await channel_layer.send(channel_name, message)
with pytest.raises(
ValueError, match=r"Malformed type in message \(leading underscore\)"
):
await communicator.receive_from()