forked from encode/uvicorn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_websocket.py
1210 lines (1043 loc) · 37.9 KB
/
test_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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import typing
from copy import deepcopy
import httpx
import pytest
import websockets
import websockets.client
import websockets.exceptions
from websockets.extensions.permessage_deflate import ClientPerMessageDeflateFactory
from websockets.typing import Subprotocol
from tests.protocols.test_http import HTTP_PROTOCOLS
from tests.utils import run_server
from uvicorn.config import Config
from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol
try:
from uvicorn.protocols.websockets.wsproto_impl import WSProtocol
skip_if_no_wsproto = pytest.mark.skipif(False, reason="wsproto is installed.")
except ModuleNotFoundError:
skip_if_no_wsproto = pytest.mark.skipif(True, reason="wsproto is not installed.")
class WebSocketResponse:
def __init__(self, scope, receive, send):
self.scope = scope
self.receive = receive
self.send = send
def __await__(self):
return self.asgi().__await__()
async def asgi(self):
while True:
message = await self.receive()
message_type = message["type"].replace(".", "_")
handler = getattr(self, message_type, None)
if handler is not None:
await handler(message)
if message_type == "websocket_disconnect":
break
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_invalid_upgrade(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
def app(scope):
return None
config = Config(
app=app, ws=ws_protocol_cls, http=http_protocol_cls, port=unused_tcp_port
)
async with run_server(config):
async with httpx.AsyncClient() as client:
response = await client.get(
f"http://127.0.0.1:{unused_tcp_port}",
headers={
"upgrade": "websocket",
"connection": "upgrade",
"sec-webSocket-version": "11",
},
)
if response.status_code == 426:
# response.text == ""
pass # ok, wsproto 0.13
else:
assert response.status_code == 400
assert response.text.lower().strip().rstrip(".") in [
"missing sec-websocket-key header",
"missing sec-websocket-version header", # websockets
"missing or empty sec-websocket-key header", # wsproto
"failed to open a websocket connection: missing "
"sec-websocket-key header",
"failed to open a websocket connection: missing or empty "
"sec-websocket-key header",
]
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_accept_connection(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
async def open_connection(url):
async with websockets.client.connect(url) as websocket:
return websocket.open
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
is_open = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}")
assert is_open
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_shutdown(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config) as server:
async with websockets.client.connect(f"ws://127.0.0.1:{unused_tcp_port}"):
# Attempt shutdown while connection is still open
await server.shutdown()
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_supports_permessage_deflate_extension(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
async def open_connection(url):
extension_factories = [ClientPerMessageDeflateFactory()]
async with websockets.client.connect(
url, extensions=extension_factories
) as websocket:
return [extension.name for extension in websocket.extensions]
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
extension_names = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}")
assert "permessage-deflate" in extension_names
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_can_disable_permessage_deflate_extension(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
async def open_connection(url):
# enable per-message deflate on the client, so that we can check the server
# won't support it when it's disabled.
extension_factories = [ClientPerMessageDeflateFactory()]
async with websockets.client.connect(
url, extensions=extension_factories
) as websocket:
return [extension.name for extension in websocket.extensions]
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
ws_per_message_deflate=False,
port=unused_tcp_port,
)
async with run_server(config):
extension_names = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}")
assert "permessage-deflate" not in extension_names
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_close_connection(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.close"})
async def open_connection(url):
try:
await websockets.client.connect(url)
except websockets.exceptions.InvalidHandshake:
return False
return True # pragma: no cover
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
is_open = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}")
assert not is_open
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_headers(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
headers = self.scope.get("headers")
headers = dict(headers)
assert headers[b"host"].startswith(b"127.0.0.1")
assert headers[b"username"] == bytes("abraão", "utf-8")
await self.send({"type": "websocket.accept"})
async def open_connection(url):
async with websockets.client.connect(
url, extra_headers=[("username", "abraão")]
) as websocket:
return websocket.open
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
is_open = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}")
assert is_open
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_extra_headers(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send(
{"type": "websocket.accept", "headers": [(b"extra", b"header")]}
)
async def open_connection(url):
async with websockets.client.connect(url) as websocket:
return websocket.response_headers
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
extra_headers = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}")
assert extra_headers.get("extra") == "header"
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_path_and_raw_path(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
path = self.scope.get("path")
raw_path = self.scope.get("raw_path")
assert path == "/one/two"
assert raw_path == b"/one%2Ftwo"
await self.send({"type": "websocket.accept"})
async def open_connection(url):
async with websockets.client.connect(url) as websocket:
return websocket.open
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
is_open = await open_connection(f"ws://127.0.0.1:{unused_tcp_port}/one%2Ftwo")
assert is_open
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_text_data_to_client(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
await self.send({"type": "websocket.send", "text": "123"})
async def get_data(url):
async with websockets.client.connect(url) as websocket:
return await websocket.recv()
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
data = await get_data(f"ws://127.0.0.1:{unused_tcp_port}")
assert data == "123"
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_binary_data_to_client(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
await self.send({"type": "websocket.send", "bytes": b"123"})
async def get_data(url):
async with websockets.client.connect(url) as websocket:
return await websocket.recv()
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
data = await get_data(f"ws://127.0.0.1:{unused_tcp_port}")
assert data == b"123"
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_and_close_connection(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
await self.send({"type": "websocket.send", "text": "123"})
await self.send({"type": "websocket.close"})
async def get_data(url):
async with websockets.client.connect(url) as websocket:
data = await websocket.recv()
is_open = True
try:
await websocket.recv()
except Exception:
is_open = False
return (data, is_open)
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
(data, is_open) = await get_data(f"ws://127.0.0.1:{unused_tcp_port}")
assert data == "123"
assert not is_open
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_text_data_to_server(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
async def websocket_receive(self, message):
_text = message.get("text")
await self.send({"type": "websocket.send", "text": _text})
async def send_text(url):
async with websockets.client.connect(url) as websocket:
await websocket.send("abc")
return await websocket.recv()
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
data = await send_text(f"ws://127.0.0.1:{unused_tcp_port}")
assert data == "abc"
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_binary_data_to_server(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
async def websocket_receive(self, message):
_bytes = message.get("bytes")
await self.send({"type": "websocket.send", "bytes": _bytes})
async def send_text(url):
async with websockets.client.connect(url) as websocket:
await websocket.send(b"abc")
return await websocket.recv()
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
data = await send_text(f"ws://127.0.0.1:{unused_tcp_port}")
assert data == b"abc"
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_after_protocol_close(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
await self.send({"type": "websocket.send", "text": "123"})
await self.send({"type": "websocket.close"})
with pytest.raises(Exception):
await self.send({"type": "websocket.send", "text": "123"})
async def get_data(url):
async with websockets.client.connect(url) as websocket:
data = await websocket.recv()
is_open = True
try:
await websocket.recv()
except Exception:
is_open = False
return (data, is_open)
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
(data, is_open) = await get_data(f"ws://127.0.0.1:{unused_tcp_port}")
assert data == "123"
assert not is_open
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_missing_handshake(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
async def app(app, receive, send):
pass
async def connect(url):
await websockets.client.connect(url)
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info:
await connect(f"ws://127.0.0.1:{unused_tcp_port}")
assert exc_info.value.status_code == 500
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_before_handshake(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
async def app(scope, receive, send):
await send({"type": "websocket.send", "text": "123"})
async def connect(url):
await websockets.client.connect(url)
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
with pytest.raises(websockets.exceptions.InvalidStatusCode) as exc_info:
await connect(f"ws://127.0.0.1:{unused_tcp_port}")
assert exc_info.value.status_code == 500
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_duplicate_handshake(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
async def app(scope, receive, send):
await send({"type": "websocket.accept"})
await send({"type": "websocket.accept"})
async def connect(url):
async with websockets.client.connect(url) as websocket:
_ = await websocket.recv()
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info:
await connect(f"ws://127.0.0.1:{unused_tcp_port}")
assert exc_info.value.code == 1006
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_asgi_return_value(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
"""
The ASGI callable should return 'None'. If it doesn't, make sure that
the connection is closed with an error condition.
"""
async def app(scope, receive, send):
await send({"type": "websocket.accept"})
return 123
async def connect(url):
async with websockets.client.connect(url) as websocket:
_ = await websocket.recv()
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info:
await connect(f"ws://127.0.0.1:{unused_tcp_port}")
assert exc_info.value.code == 1006
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
@pytest.mark.parametrize("code", [None, 1000, 1001])
@pytest.mark.parametrize(
"reason",
[None, "test", False],
ids=["none_as_reason", "normal_reason", "without_reason"],
)
async def test_app_close(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
code,
reason,
):
async def app(scope, receive, send):
while True:
message = await receive()
if message["type"] == "websocket.connect":
await send({"type": "websocket.accept"})
elif message["type"] == "websocket.receive":
reply = {"type": "websocket.close"}
if code is not None:
reply["code"] = code
if reason is not False:
reply["reason"] = reason
await send(reply)
elif message["type"] == "websocket.disconnect":
break
async def websocket_session(url):
async with websockets.client.connect(url) as websocket:
await websocket.ping()
await websocket.send("abc")
await websocket.recv()
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
with pytest.raises(websockets.exceptions.ConnectionClosed) as exc_info:
await websocket_session(f"ws://127.0.0.1:{unused_tcp_port}")
assert exc_info.value.code == (code or 1000)
assert exc_info.value.reason == (reason or "")
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_client_close(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
async def app(scope, receive, send):
while True:
message = await receive()
if message["type"] == "websocket.connect":
await send({"type": "websocket.accept"})
elif message["type"] == "websocket.receive":
pass
elif message["type"] == "websocket.disconnect":
break
async def websocket_session(url):
async with websockets.client.connect(url) as websocket:
await websocket.ping()
await websocket.send("abc")
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
await websocket_session(f"ws://127.0.0.1:{unused_tcp_port}")
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_client_connection_lost(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
got_disconnect_event = False
async def app(scope, receive, send):
nonlocal got_disconnect_event
while True:
message = await receive()
if message["type"] == "websocket.connect":
await send({"type": "websocket.accept"})
elif message["type"] == "websocket.disconnect":
break
got_disconnect_event = True
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
ws_ping_interval=0.0,
port=unused_tcp_port,
)
async with run_server(config):
async with websockets.client.connect(
f"ws://127.0.0.1:{unused_tcp_port}"
) as websocket:
websocket.transport.close()
await asyncio.sleep(0.1)
got_disconnect_event_before_shutdown = got_disconnect_event
assert got_disconnect_event_before_shutdown is True
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_connection_lost_before_handshake_complete(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
send_accept_task = asyncio.Event()
disconnect_message = {}
async def app(scope, receive, send):
nonlocal disconnect_message
message = await receive()
if message["type"] == "websocket.connect":
await send_accept_task.wait()
disconnect_message = await receive()
response: typing.Optional[httpx.Response] = None
async def websocket_session(uri):
nonlocal response
async with httpx.AsyncClient() as client:
response = await client.get(
f"http://127.0.0.1:{unused_tcp_port}",
headers={
"upgrade": "websocket",
"connection": "upgrade",
"sec-websocket-version": "13",
"sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==",
},
)
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
task = asyncio.create_task(
websocket_session(f"ws://127.0.0.1:{unused_tcp_port}")
)
await asyncio.sleep(0.1)
send_accept_task.set()
await asyncio.sleep(0.1)
assert response is not None
assert response.status_code == 500, response.text
assert response.text == "Internal Server Error"
assert disconnect_message == {"type": "websocket.disconnect", "code": 1006}
await task
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_send_close_on_server_shutdown(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
disconnect_message = {}
server_shutdown_event = asyncio.Event()
async def app(scope, receive, send):
nonlocal disconnect_message
while True:
message = await receive()
if message["type"] == "websocket.connect":
await send({"type": "websocket.accept"})
elif message["type"] == "websocket.disconnect":
disconnect_message = message
break
websocket: typing.Optional[websockets.client.WebSocketClientProtocol] = None
async def websocket_session(uri):
nonlocal websocket
async with websockets.client.connect(uri) as ws_connection:
websocket = ws_connection
await server_shutdown_event.wait()
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
task = asyncio.create_task(
websocket_session(f"ws://127.0.0.1:{unused_tcp_port}")
)
await asyncio.sleep(0.1)
disconnect_message_before_shutdown = disconnect_message
server_shutdown_event.set()
assert websocket is not None
assert websocket.close_code == 1012
assert disconnect_message_before_shutdown == {}
assert disconnect_message == {"type": "websocket.disconnect", "code": 1012}
task.cancel()
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
@pytest.mark.parametrize("subprotocol", ["proto1", "proto2"])
async def test_subprotocols(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
subprotocol,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept", "subprotocol": subprotocol})
async def get_subprotocol(url: str):
async with websockets.client.connect(
url, subprotocols=[Subprotocol("proto1"), Subprotocol("proto2")]
) as websocket:
return websocket.subprotocol
config = Config(
app=App,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
accepted_subprotocol = await get_subprotocol(
f"ws://127.0.0.1:{unused_tcp_port}"
)
assert accepted_subprotocol == subprotocol
MAX_WS_BYTES = 1024 * 1024 * 16
MAX_WS_BYTES_PLUS1 = MAX_WS_BYTES + 1
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
@pytest.mark.parametrize(
"client_size_sent, server_size_max, expected_result",
[
(MAX_WS_BYTES, MAX_WS_BYTES, 0),
(MAX_WS_BYTES_PLUS1, MAX_WS_BYTES, 1009),
(10, 10, 0),
(11, 10, 1009),
],
ids=[
"max=defaults sent=defaults",
"max=defaults sent=defaults+1",
"max=10 sent=10",
"max=10 sent=11",
],
)
async def test_send_binary_data_to_server_bigger_than_default_on_websockets(
http_protocol_cls,
client_size_sent: int,
server_size_max: int,
expected_result: int,
unused_tcp_port: int,
):
class App(WebSocketResponse):
async def websocket_connect(self, message):
await self.send({"type": "websocket.accept"})
async def websocket_receive(self, message):
_bytes = message.get("bytes")
await self.send({"type": "websocket.send", "bytes": _bytes})
async def send_text(url):
async with websockets.client.connect(
url, max_size=client_size_sent
) as websocket:
await websocket.send(b"\x01" * client_size_sent)
return await websocket.recv()
config = Config(
app=App,
ws=WebSocketProtocol,
http=http_protocol_cls,
lifespan="off",
ws_max_size=server_size_max,
port=unused_tcp_port,
)
async with run_server(config):
if expected_result == 0:
data = await send_text(f"ws://127.0.0.1:{unused_tcp_port}")
assert data == b"\x01" * client_size_sent
else:
with pytest.raises(websockets.exceptions.ConnectionClosedError) as e:
data = await send_text(f"ws://127.0.0.1:{unused_tcp_port}")
assert e.value.code == expected_result
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_server_reject_connection(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
async def app(scope, receive, send):
assert scope["type"] == "websocket"
# Pull up first recv message.
message = await receive()
assert message["type"] == "websocket.connect"
# Reject the connection.
await send({"type": "websocket.close"})
# -- At this point websockets' recv() is unusable. --
# This doesn't raise `TypeError`:
# See https://github.com/encode/uvicorn/issues/244
message = await receive()
assert message["type"] == "websocket.disconnect"
async def websocket_session(url):
try:
async with websockets.client.connect(url):
pass # pragma: no cover
except Exception:
pass
config = Config(
app=app,
ws=ws_protocol_cls,
http=http_protocol_cls,
lifespan="off",
port=unused_tcp_port,
)
async with run_server(config):
await websocket_session(f"ws://127.0.0.1:{unused_tcp_port}")
@pytest.mark.anyio
@pytest.mark.parametrize("http_protocol_cls", HTTP_PROTOCOLS)
async def test_server_can_read_messages_in_buffer_after_close(
ws_protocol_cls: "typing.Type[WSProtocol | WebSocketProtocol]",
http_protocol_cls,
unused_tcp_port: int,
):
frames = []