-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_client_ws_functional.py
1214 lines (925 loc) · 35.5 KB
/
test_client_ws_functional.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 sys
from typing import NoReturn, Optional
from unittest import mock
import pytest
import aiohttp
from aiohttp import (
ClientConnectionResetError,
ServerTimeoutError,
WSMessageTypeError,
WSMsgType,
hdrs,
web,
)
from aiohttp._websocket.reader import WebSocketDataQueue
from aiohttp.client_ws import ClientWSTimeout
from aiohttp.http import WSCloseCode
from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer
if sys.version_info >= (3, 11):
import asyncio as async_timeout
else:
import async_timeout
class PatchableWebSocketDataQueue(WebSocketDataQueue):
"""A WebSocketDataQueue that can be patched."""
async def test_send_recv_text(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_str()
await ws.send_str(msg + "/answer")
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_str("ask")
assert resp.get_extra_info("socket") is not None
data = await resp.receive_str()
assert data == "ask/answer"
await resp.close()
assert resp.get_extra_info("socket") is None
async def test_send_recv_bytes_bad_type(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_str()
await ws.send_str(msg + "/answer")
await ws.close()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_str("ask")
with pytest.raises(WSMessageTypeError):
await resp.receive_bytes()
await resp.close()
async def test_recv_bytes_after_close(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.close()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
with pytest.raises(
WSMessageTypeError,
match=f"Received message {WSMsgType.CLOSE}:.+ is not WSMsgType.BINARY",
):
await resp.receive_bytes()
await resp.close()
async def test_send_recv_bytes(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_bytes()
await ws.send_bytes(msg + b"/answer")
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_bytes(b"ask")
data = await resp.receive_bytes()
assert data == b"ask/answer"
await resp.close()
async def test_send_recv_text_bad_type(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_bytes()
await ws.send_bytes(msg + b"/answer")
await ws.close()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_bytes(b"ask")
with pytest.raises(WSMessageTypeError):
await resp.receive_str()
await resp.close()
async def test_recv_text_after_close(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.close()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
with pytest.raises(
WSMessageTypeError,
match=f"Received message {WSMsgType.CLOSE}:.+ is not WSMsgType.TEXT",
):
await resp.receive_str()
await resp.close()
async def test_send_recv_json(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
data = await ws.receive_json()
await ws.send_json({"response": data["request"]})
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
payload = {"request": "test"}
await resp.send_json(payload)
data = await resp.receive_json()
assert data["response"] == payload["request"]
await resp.close()
async def test_send_recv_frame(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive()
assert msg.type is WSMsgType.BINARY
await ws.send_frame(msg.data, msg.type)
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_frame(b"test", WSMsgType.BINARY)
data = await resp.receive()
assert data.data == b"test"
assert data.type is WSMsgType.BINARY
await resp.close()
async def test_ping_pong(aiohttp_client: AiohttpClient) -> None:
loop = asyncio.get_event_loop()
closed = loop.create_future()
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_bytes()
await ws.ping()
await ws.send_bytes(msg + b"/answer")
try:
await ws.close()
finally:
closed.set_result(1)
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.ping()
await resp.send_bytes(b"ask")
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.BINARY
assert msg.data == b"ask/answer"
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.CLOSE
await resp.close()
await closed
async def test_ping_pong_manual(aiohttp_client: AiohttpClient) -> None:
loop = asyncio.get_event_loop()
closed = loop.create_future()
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_bytes()
await ws.ping()
await ws.send_bytes(msg + b"/answer")
try:
await ws.close()
finally:
closed.set_result(1)
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", autoping=False)
await resp.ping()
await resp.send_bytes(b"ask")
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.PONG
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.PING
await resp.pong()
msg = await resp.receive()
assert msg.data == b"ask/answer"
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.CLOSE
await closed
async def test_close(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_bytes()
await ws.send_str("test")
await ws.receive()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_bytes(b"ask")
closed = await resp.close()
assert closed
assert resp.closed
assert resp.close_code == 1000
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.CLOSED
async def test_concurrent_task_close(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.ws_connect("/") as resp:
# wait for the message in a separate task
task = asyncio.create_task(resp.receive())
# Make sure we start to wait on receiving message before closing the connection
await asyncio.sleep(0.1)
closed = await resp.close()
await task
assert closed
assert resp.closed
assert resp.close_code == 1000
async def test_concurrent_close(aiohttp_client: AiohttpClient) -> None:
client_ws: Optional[aiohttp.ClientWebSocketResponse] = None
async def handler(request: web.Request) -> web.WebSocketResponse:
nonlocal client_ws
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_bytes()
await ws.send_str("test")
assert client_ws is not None
await client_ws.close()
msg = await ws.receive()
assert msg.type is aiohttp.WSMsgType.CLOSE
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
ws = client_ws = await client.ws_connect("/")
await ws.send_bytes(b"ask")
msg = await ws.receive()
assert msg.type is aiohttp.WSMsgType.CLOSING
await asyncio.sleep(0.01)
msg = await ws.receive()
assert msg.type is aiohttp.WSMsgType.CLOSED
async def test_concurrent_close_multiple_tasks(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_bytes()
await ws.send_str("test")
msg = await ws.receive()
assert msg.type is aiohttp.WSMsgType.CLOSE
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
ws = await client.ws_connect("/")
await ws.send_bytes(b"ask")
task1 = asyncio.create_task(ws.close())
task2 = asyncio.create_task(ws.close())
msg = await ws.receive()
assert msg.type is aiohttp.WSMsgType.CLOSED
await task1
await task2
msg = await ws.receive()
assert msg.type is aiohttp.WSMsgType.CLOSED
async def test_close_from_server(aiohttp_client: AiohttpClient) -> None:
loop = asyncio.get_event_loop()
closed = loop.create_future()
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
try:
await ws.receive_bytes()
await ws.close()
finally:
closed.set_result(1)
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_bytes(b"ask")
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.CLOSE
assert resp.closed
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.CLOSED
await closed
async def test_close_manual(aiohttp_client: AiohttpClient) -> None:
loop = asyncio.get_event_loop()
closed = loop.create_future()
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_bytes()
await ws.send_str("test")
try:
await ws.close()
finally:
closed.set_result(1)
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", autoclose=False)
await resp.send_bytes(b"ask")
msg = await resp.receive()
assert msg.data == "test"
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.CLOSE
assert msg.data == 1000
assert msg.extra == ""
assert not resp.closed
await resp.close()
await closed
assert resp.closed
async def test_close_timeout_sock_close_read(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_bytes()
await ws.send_str("test")
await asyncio.sleep(1)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
timeout = ClientWSTimeout(ws_close=0.2)
resp = await client.ws_connect("/", timeout=timeout, autoclose=False)
await resp.send_bytes(b"ask")
msg = await resp.receive()
assert msg.data == "test"
assert msg.type == aiohttp.WSMsgType.TEXT
await resp.close()
assert resp.closed
assert isinstance(resp.exception(), asyncio.TimeoutError)
async def test_close_timeout_deprecated(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_bytes()
await ws.send_str("test")
await asyncio.sleep(1)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
with pytest.warns(
DeprecationWarning,
match="parameter 'timeout' of type 'float' "
"is deprecated, please use "
r"'timeout=ClientWSTimeout\(ws_close=...\)'",
):
resp = await client.ws_connect("/", timeout=0.2, autoclose=False)
await resp.send_bytes(b"ask")
msg = await resp.receive()
assert msg.data == "test"
assert msg.type == aiohttp.WSMsgType.TEXT
await resp.close()
assert resp.closed
assert isinstance(resp.exception(), asyncio.TimeoutError)
async def test_close_cancel(aiohttp_client: AiohttpClient) -> None:
loop = asyncio.get_event_loop()
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_bytes()
await ws.send_str("test")
await asyncio.sleep(10)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", autoclose=False)
await resp.send_bytes(b"ask")
text = await resp.receive()
assert text.data == "test"
t = loop.create_task(resp.close())
await asyncio.sleep(0.1)
t.cancel()
await asyncio.sleep(0.1)
assert resp.closed
assert resp.exception() is None
async def test_override_default_headers(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
assert request.headers[hdrs.SEC_WEBSOCKET_VERSION] == "8"
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.send_str("answer")
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
headers = {hdrs.SEC_WEBSOCKET_VERSION: "8"}
client = await aiohttp_client(app)
resp = await client.ws_connect("/", headers=headers)
msg = await resp.receive()
assert msg.data == "answer"
await resp.close()
async def test_additional_headers(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
assert request.headers["x-hdr"] == "xtra"
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.send_str("answer")
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", headers={"x-hdr": "xtra"})
msg = await resp.receive()
assert msg.data == "answer"
await resp.close()
async def test_recv_protocol_error(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_str()
assert ws._writer is not None
ws._writer.transport.write(b"01234" * 100)
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_str("ask")
msg = await resp.receive()
assert msg.type == aiohttp.WSMsgType.ERROR
assert type(msg.data) is aiohttp.WebSocketError
assert msg.data.code == aiohttp.WSCloseCode.PROTOCOL_ERROR
assert str(msg.data) == "Received frame with non-zero reserved bits"
assert msg.extra is None
await resp.close()
async def test_recv_timeout(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive_str()
await asyncio.sleep(0.1)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
await resp.send_str("ask")
with pytest.raises(asyncio.TimeoutError):
async with async_timeout.timeout(0.01):
await resp.receive()
await resp.close()
async def test_receive_timeout_sock_read(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive()
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
receive_timeout = ClientWSTimeout(ws_receive=0.1)
resp = await client.ws_connect("/", timeout=receive_timeout)
with pytest.raises(asyncio.TimeoutError):
await resp.receive(timeout=0.05)
await resp.close()
async def test_receive_timeout_deprecation(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive()
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
with pytest.warns(
DeprecationWarning,
match="float parameter 'receive_timeout' "
"is deprecated, please use parameter "
r"'timeout=ClientWSTimeout\(ws_receive=...\)'",
):
resp = await client.ws_connect("/", receive_timeout=0.1)
with pytest.raises(asyncio.TimeoutError):
await resp.receive(timeout=0.05)
await resp.close()
async def test_custom_receive_timeout(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.receive()
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/")
with pytest.raises(asyncio.TimeoutError):
await resp.receive(0.05)
await resp.close()
async def test_heartbeat(aiohttp_client: AiohttpClient) -> None:
ping_received = False
async def handler(request: web.Request) -> NoReturn:
nonlocal ping_received
ws = web.WebSocketResponse(autoping=False)
await ws.prepare(request)
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.PING
ping_received = True
await ws.close()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", heartbeat=0.01)
await asyncio.sleep(0.1)
await resp.receive()
await resp.close()
assert ping_received
async def test_heartbeat_connection_closed(aiohttp_client: AiohttpClient) -> None:
"""Test that the connection is closed while ping is in progress."""
async def handler(request: web.Request) -> NoReturn:
ws = web.WebSocketResponse(autoping=False)
await ws.prepare(request)
await ws.receive()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", heartbeat=0.1)
ping_count = 0
# We patch write here to simulate a connection reset error
# since if we closed the connection normally, the client would
# would cancel the heartbeat task and we wouldn't get a ping
assert resp._conn is not None
with mock.patch.object(
resp._conn.transport, "write", side_effect=ClientConnectionResetError
), mock.patch.object(
resp._writer, "send_frame", wraps=resp._writer.send_frame
) as send_frame:
await resp.receive()
ping_count = send_frame.call_args_list.count(mock.call(b"", WSMsgType.PING))
# Connection should be closed roughly after 1.5x heartbeat.
await asyncio.sleep(0.2)
assert ping_count == 1
assert resp.close_code is WSCloseCode.ABNORMAL_CLOSURE
async def test_heartbeat_no_pong(aiohttp_client: AiohttpClient) -> None:
"""Test that the connection is closed if no pong is received without sending messages."""
ping_received = False
async def handler(request: web.Request) -> NoReturn:
nonlocal ping_received
ws = web.WebSocketResponse(autoping=False)
await ws.prepare(request)
msg = await ws.receive()
assert msg.type == aiohttp.WSMsgType.PING
ping_received = True
await ws.receive()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", heartbeat=0.1)
# Connection should be closed roughly after 1.5x heartbeat.
await asyncio.sleep(0.2)
assert ping_received
assert resp.close_code is WSCloseCode.ABNORMAL_CLOSURE
async def test_heartbeat_no_pong_after_receive_many_messages(
aiohttp_client: AiohttpClient,
) -> None:
"""Test that the connection is closed if no pong is received after receiving many messages."""
ping_received = False
async def handler(request: web.Request) -> NoReturn:
nonlocal ping_received
ws = web.WebSocketResponse(autoping=False)
await ws.prepare(request)
for _ in range(5):
await ws.send_str("test")
await asyncio.sleep(0.05)
for _ in range(5):
await ws.send_str("test")
msg = await ws.receive()
ping_received = msg.type is aiohttp.WSMsgType.PING
await ws.receive()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", heartbeat=0.1)
for _ in range(10):
test_msg = await resp.receive()
assert test_msg.data == "test"
# Connection should be closed roughly after 1.5x heartbeat.
await asyncio.sleep(0.2)
assert ping_received
assert resp.close_code is WSCloseCode.ABNORMAL_CLOSURE
async def test_heartbeat_no_pong_after_send_many_messages(
aiohttp_client: AiohttpClient,
) -> None:
"""Test that the connection is closed if no pong is received after sending many messages."""
ping_received = False
async def handler(request: web.Request) -> NoReturn:
nonlocal ping_received
ws = web.WebSocketResponse(autoping=False)
await ws.prepare(request)
for _ in range(10):
msg = await ws.receive()
assert msg.data == "test"
assert msg.type is aiohttp.WSMsgType.TEXT
msg = await ws.receive()
ping_received = msg.type is aiohttp.WSMsgType.PING
await ws.receive()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", heartbeat=0.1)
for _ in range(5):
await resp.send_str("test")
await asyncio.sleep(0.05)
for _ in range(5):
await resp.send_str("test")
# Connection should be closed roughly after 1.5x heartbeat.
await asyncio.sleep(0.2)
assert ping_received
assert resp.close_code is WSCloseCode.ABNORMAL_CLOSURE
async def test_heartbeat_no_pong_concurrent_receive(
aiohttp_client: AiohttpClient,
) -> None:
ping_received = False
async def handler(request: web.Request) -> NoReturn:
nonlocal ping_received
ws = web.WebSocketResponse(autoping=False)
with mock.patch(
"aiohttp.web_ws.WebSocketDataQueue", PatchableWebSocketDataQueue
):
await ws.prepare(request)
msg = await ws.receive()
ping_received = msg.type is aiohttp.WSMsgType.PING
with mock.patch.object(
ws._reader, "feed_eof", autospec=True, spec_set=True, return_value=None
):
await asyncio.sleep(10.0)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
with mock.patch("aiohttp.client.WebSocketDataQueue", PatchableWebSocketDataQueue):
client = await aiohttp_client(app)
resp = await client.ws_connect("/", heartbeat=0.1)
with mock.patch.object(
resp._reader, "feed_eof", autospec=True, spec_set=True, return_value=None
):
# Connection should be closed roughly after 1.5x heartbeat.
msg = await resp.receive(5.0)
assert ping_received
assert resp.close_code is WSCloseCode.ABNORMAL_CLOSURE
assert msg.type is WSMsgType.ERROR
assert isinstance(msg.data, ServerTimeoutError)
async def test_close_websocket_while_ping_inflight(
aiohttp_client: AiohttpClient, loop: asyncio.AbstractEventLoop
) -> None:
"""Test closing the websocket while a ping is in-flight."""
ping_received = False
async def handler(request: web.Request) -> NoReturn:
nonlocal ping_received
ws = web.WebSocketResponse(autoping=False)
await ws.prepare(request)
msg = await ws.receive()
assert msg.type is aiohttp.WSMsgType.BINARY
msg = await ws.receive()
ping_received = msg.type is aiohttp.WSMsgType.PING
await ws.receive()
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", heartbeat=0.1)
await resp.send_bytes(b"ask")
cancelled = False
ping_started = loop.create_future()
async def delayed_send_frame(
message: bytes, opcode: int, compress: Optional[int] = None
) -> None:
assert opcode == WSMsgType.PING
nonlocal cancelled, ping_started
ping_started.set_result(None)
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
cancelled = True
raise
with mock.patch.object(resp._writer, "send_frame", delayed_send_frame):
async with async_timeout.timeout(1):
await ping_started
await resp.close()
await asyncio.sleep(0)
assert ping_started.result() is None
assert cancelled is True
async def test_send_recv_compress(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_str()
await ws.send_str(msg + "/answer")
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", compress=15)
await resp.send_str("ask")
assert resp.compress == 15
data = await resp.receive_str()
assert data == "ask/answer"
await resp.close()
assert resp.get_extra_info("socket") is None
async def test_send_recv_compress_wbits(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
msg = await ws.receive_str()
await ws.send_str(msg + "/answer")
await ws.close()
return ws
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.ws_connect("/", compress=9)
await resp.send_str("ask")
# Client indicates supports wbits 15
# Server supports wbit 15 for decode
assert resp.compress == 15