Debian Codegraph @

tests/asyncio/test_connection.py

raw
1 import asyncio
2 import contextlib
3 import itertools
4 import logging
5 import socket
6 import sys
7 import unittest
8 import uuid
9 import weakref
10 from unittest.mock import Mock, patch
11
12 from websockets.asyncio.connection import *
13 from websockets.asyncio.connection import broadcast
14 from websockets.exceptions import (
15 ConcurrencyError,
16 ConnectionClosedError,
17 ConnectionClosedOK,
18 )
19 from websockets.frames import BINARY, CLOSE, CONT, PING, PONG, TEXT, CloseCode, Frame
20 from websockets.protocol import CLIENT, CLOSED, OPEN, SERVER, Protocol
21
22 from ..protocol import RecordingProtocol
23 from ..utils import MS, LoggingTestCase, alist
24 from .connection import InterceptingConnection
25
26
27 # Connection implements symmetrical behavior between clients and servers.
28 # All tests run on the client side and the server side to validate this.
29
30
31 class ClientConnectionTests(LoggingTestCase, unittest.IsolatedAsyncioTestCase):
32 LOCAL = CLIENT
33 REMOTE = SERVER
34
35 async def asyncSetUp(self):
36 self.loop = asyncio.get_running_loop()
37 socket_, remote_socket = socket.socketpair()
38 protocol = Protocol(self.LOCAL)
39 remote_protocol = RecordingProtocol(self.REMOTE)
40 self.transport, self.connection = await self.loop.create_connection(
41 lambda: Connection(protocol, close_timeout=2 * MS),
42 sock=socket_,
43 )
44 _remote_transport, self.remote_connection = await self.loop.create_connection(
45 lambda: InterceptingConnection(remote_protocol),
46 sock=remote_socket,
47 )
48
49 async def asyncTearDown(self):
50 await self.remote_connection.close()
51 if hasattr(self, "connection"):
52 await self.connection.close()
53
54 # Test helpers built upon RecordingProtocol and InterceptingConnection.
55
56 async def wait_for_remote_side(self):
57 """Wait for the remote side to process messages."""
58 # Two runs of the event loop are required for answering pings.
59 await asyncio.sleep(0)
60 await asyncio.sleep(0)
61
62 async def assertFrameSent(self, frame):
63 """Check that a single frame was sent."""
64 await self.wait_for_remote_side()
65 self.assertEqual(self.remote_connection.protocol.get_frames_rcvd(), [frame])
66
67 async def assertFramesSent(self, frames):
68 """Check that several frames were sent."""
69 await self.wait_for_remote_side()
70 self.assertEqual(self.remote_connection.protocol.get_frames_rcvd(), frames)
71
72 async def assertNoFrameSent(self):
73 """Check that no frame was sent."""
74 await self.wait_for_remote_side()
75 self.assertEqual(self.remote_connection.protocol.get_frames_rcvd(), [])
76
77 @contextlib.asynccontextmanager
78 async def delay_frames_rcvd(self, delay):
79 """Delay frames before they're received by the connection."""
80 with self.remote_connection.delay_frames_sent(delay):
81 yield
82 await self.wait_for_remote_side()
83
84 @contextlib.asynccontextmanager
85 async def delay_eof_rcvd(self, delay):
86 """Delay EOF before it's received by the connection."""
87 with self.remote_connection.delay_eof_sent(delay):
88 yield
89 await self.wait_for_remote_side()
90
91 @contextlib.asynccontextmanager
92 async def drop_frames_rcvd(self):
93 """Drop frames before they're received by the connection."""
94 with self.remote_connection.drop_frames_sent():
95 yield
96 await self.wait_for_remote_side()
97
98 @contextlib.asynccontextmanager
99 async def drop_eof_rcvd(self):
100 """Drop EOF before it's received by the connection."""
101 with self.remote_connection.drop_eof_sent():
102 yield
103 await self.wait_for_remote_side()
104
105 # Test __aenter__ and __aexit__.
106
107 async def test_aenter(self):
108 """__aenter__ returns the connection itself."""
109 async with self.connection as connection:
110 self.assertIs(connection, self.connection)
111
112 async def test_aexit(self):
113 """__aexit__ closes the connection with code 1000."""
114 async with self.connection:
115 await self.assertNoFrameSent()
116 await self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
117
118 async def test_aexit_with_exception(self):
119 """__aexit__ with an exception closes the connection with code 1011."""
120 with self.assertRaises(RuntimeError):
121 async with self.connection:
122 raise RuntimeError
123 await self.assertFrameSent(Frame(CLOSE, b"\x03\xf3"))
124
125 # Test __aiter__.
126
127 async def test_aiter_text(self):
128 """__aiter__ yields text messages."""
129 iterator = aiter(self.connection)
130 async with contextlib.aclosing(iterator):
131 await self.remote_connection.send("😀")
132 self.assertEqual(await anext(iterator), "😀")
133 await self.remote_connection.send("😀")
134 self.assertEqual(await anext(iterator), "😀")
135
136 async def test_aiter_binary(self):
137 """__aiter__ yields binary messages."""
138 iterator = aiter(self.connection)
139 async with contextlib.aclosing(iterator):
140 await self.remote_connection.send(b"\x01\x02\xfe\xff")
141 self.assertEqual(await anext(iterator), b"\x01\x02\xfe\xff")
142 await self.remote_connection.send(b"\x01\x02\xfe\xff")
143 self.assertEqual(await anext(iterator), b"\x01\x02\xfe\xff")
144
145 async def test_aiter_mixed(self):
146 """__aiter__ yields a mix of text and binary messages."""
147 iterator = aiter(self.connection)
148 async with contextlib.aclosing(iterator):
149 await self.remote_connection.send("😀")
150 self.assertEqual(await anext(iterator), "😀")
151 await self.remote_connection.send(b"\x01\x02\xfe\xff")
152 self.assertEqual(await anext(iterator), b"\x01\x02\xfe\xff")
153
154 async def test_aiter_connection_closed_ok(self):
155 """__aiter__ terminates after a normal closure."""
156 iterator = aiter(self.connection)
157 async with contextlib.aclosing(iterator):
158 await self.remote_connection.close()
159 with self.assertRaises(StopAsyncIteration):
160 await anext(iterator)
161
162 async def test_aiter_connection_closed_error(self):
163 """__aiter__ raises ConnectionClosedError after an error."""
164 iterator = aiter(self.connection)
165 async with contextlib.aclosing(iterator):
166 await self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
167 with self.assertRaises(ConnectionClosedError):
168 await anext(iterator)
169
170 # Test recv.
171
172 async def test_recv_text(self):
173 """recv receives a text message."""
174 await self.remote_connection.send("😀")
175 self.assertEqual(await self.connection.recv(), "😀")
176
177 async def test_recv_binary(self):
178 """recv receives a binary message."""
179 await self.remote_connection.send(b"\x01\x02\xfe\xff")
180 self.assertEqual(await self.connection.recv(), b"\x01\x02\xfe\xff")
181
182 async def test_recv_text_as_bytes(self):
183 """recv receives a text message as bytes."""
184 await self.remote_connection.send("😀")
185 self.assertEqual(await self.connection.recv(decode=False), "😀".encode())
186
187 async def test_recv_binary_as_text(self):
188 """recv receives a binary message as a str."""
189 await self.remote_connection.send("😀".encode())
190 self.assertEqual(await self.connection.recv(decode=True), "😀")
191
192 async def test_recv_fragmented_text(self):
193 """recv receives a fragmented text message."""
194 await self.remote_connection.send(["😀", "😀"])
195 self.assertEqual(await self.connection.recv(), "😀😀")
196
197 async def test_recv_fragmented_binary(self):
198 """recv receives a fragmented binary message."""
199 await self.remote_connection.send([b"\x01\x02", b"\xfe\xff"])
200 self.assertEqual(await self.connection.recv(), b"\x01\x02\xfe\xff")
201
202 async def test_recv_connection_closed_ok(self):
203 """recv raises ConnectionClosedOK after a normal closure."""
204 await self.remote_connection.close()
205 with self.assertRaises(ConnectionClosedOK):
206 await self.connection.recv()
207
208 async def test_recv_connection_closed_error(self):
209 """recv raises ConnectionClosedError after an error."""
210 await self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
211 with self.assertRaises(ConnectionClosedError):
212 await self.connection.recv()
213
214 async def test_recv_non_utf8_text(self):
215 """recv receives a non-UTF-8 text message."""
216 await self.remote_connection.send(b"\x01\x02\xfe\xff", text=True)
217 with self.assertRaises(ConnectionClosedError) as raised:
218 await self.connection.recv()
219 self.assertEqual(raised.exception.sent.code, CloseCode.INVALID_DATA)
220
221 async def test_recv_during_recv(self):
222 """recv raises ConcurrencyError when called concurrently."""
223 recv_task = asyncio.create_task(self.connection.recv())
224 await asyncio.sleep(0) # let the event loop start recv_task
225 try:
226 with self.assertRaises(ConcurrencyError) as raised:
227 await self.connection.recv()
228 finally:
229 recv_task.cancel()
230 self.assertEqual(
231 str(raised.exception),
232 "cannot call recv while another coroutine "
233 "is already running recv or recv_streaming",
234 )
235
236 async def test_recv_during_recv_streaming(self):
237 """recv raises ConcurrencyError when called concurrently with recv_streaming."""
238 recv_streaming_task = asyncio.create_task(
239 alist(self.connection.recv_streaming())
240 )
241 await asyncio.sleep(0) # let the event loop start recv_streaming_task
242 try:
243 with self.assertRaises(ConcurrencyError) as raised:
244 await self.connection.recv()
245 finally:
246 recv_streaming_task.cancel()
247 self.assertEqual(
248 str(raised.exception),
249 "cannot call recv while another coroutine "
250 "is already running recv or recv_streaming",
251 )
252
253 async def test_recv_cancellation_before_receiving(self):
254 """recv can be canceled before receiving a message."""
255 recv_task = asyncio.create_task(self.connection.recv())
256 await asyncio.sleep(0) # let the event loop start recv_task
257 recv_task.cancel()
258 await asyncio.sleep(0) # let the event loop cancel recv_task
259
260 # Running recv again receives the next message.
261 await self.remote_connection.send("😀")
262 self.assertEqual(await self.connection.recv(), "😀")
263
264 async def test_recv_cancellation_while_receiving(self):
265 """recv can be canceled while receiving a fragmented message."""
266 gate = asyncio.Event()
267
268 async def fragments():
269 yield "⏳"
270 await gate.wait()
271 yield "⌛️"
272
273 asyncio.create_task(self.remote_connection.send(fragments()))
274 await asyncio.sleep(0)
275
276 recv_task = asyncio.create_task(self.connection.recv())
277 await asyncio.sleep(0) # let the event loop start recv_task
278 recv_task.cancel()
279 await asyncio.sleep(0) # let the event loop cancel recv_task
280
281 gate.set()
282
283 # Running recv again receives the complete message.
284 self.assertEqual(await self.connection.recv(), "⏳⌛️")
285
286 # Test recv_streaming.
287
288 async def test_recv_streaming_text(self):
289 """recv_streaming receives a text message."""
290 await self.remote_connection.send("😀")
291 self.assertEqual(
292 await alist(self.connection.recv_streaming()),
293 ["😀"],
294 )
295
296 async def test_recv_streaming_binary(self):
297 """recv_streaming receives a binary message."""
298 await self.remote_connection.send(b"\x01\x02\xfe\xff")
299 self.assertEqual(
300 await alist(self.connection.recv_streaming()),
301 [b"\x01\x02\xfe\xff"],
302 )
303
304 async def test_recv_streaming_text_as_bytes(self):
305 """recv_streaming receives a text message as bytes."""
306 await self.remote_connection.send("😀")
307 self.assertEqual(
308 await alist(self.connection.recv_streaming(decode=False)),
309 ["😀".encode()],
310 )
311
312 async def test_recv_streaming_binary_as_str(self):
313 """recv_streaming receives a binary message as a str."""
314 await self.remote_connection.send("😀".encode())
315 self.assertEqual(
316 await alist(self.connection.recv_streaming(decode=True)),
317 ["😀"],
318 )
319
320 async def test_recv_streaming_fragmented_text(self):
321 """recv_streaming receives a fragmented text message."""
322 await self.remote_connection.send(["😀", "😀"])
323 # websockets sends an trailing empty fragment. That's an implementation detail.
324 self.assertEqual(
325 await alist(self.connection.recv_streaming()),
326 ["😀", "😀", ""],
327 )
328
329 async def test_recv_streaming_fragmented_binary(self):
330 """recv_streaming receives a fragmented binary message."""
331 await self.remote_connection.send([b"\x01\x02", b"\xfe\xff"])
332 # websockets sends an trailing empty fragment. That's an implementation detail.
333 self.assertEqual(
334 await alist(self.connection.recv_streaming()),
335 [b"\x01\x02", b"\xfe\xff", b""],
336 )
337
338 async def test_recv_streaming_connection_closed_ok(self):
339 """recv_streaming raises ConnectionClosedOK after a normal closure."""
340 await self.remote_connection.close()
341 with self.assertRaises(ConnectionClosedOK):
342 async for _ in self.connection.recv_streaming():
343 self.fail("did not raise")
344
345 async def test_recv_streaming_connection_closed_error(self):
346 """recv_streaming raises ConnectionClosedError after an error."""
347 await self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
348 with self.assertRaises(ConnectionClosedError):
349 async for _ in self.connection.recv_streaming():
350 self.fail("did not raise")
351
352 async def test_recv_streaming_non_utf8_text(self):
353 """recv_streaming receives a non-UTF-8 text message."""
354 await self.remote_connection.send(b"\x01\x02\xfe\xff", text=True)
355 with self.assertRaises(ConnectionClosedError) as raised:
356 await alist(self.connection.recv_streaming())
357 self.assertEqual(raised.exception.sent.code, CloseCode.INVALID_DATA)
358
359 async def test_recv_streaming_during_recv(self):
360 """recv_streaming raises ConcurrencyError when called concurrently with recv."""
361 recv_task = asyncio.create_task(self.connection.recv())
362 await asyncio.sleep(0) # let the event loop start recv_task
363 try:
364 with self.assertRaises(ConcurrencyError) as raised:
365 async for _ in self.connection.recv_streaming():
366 self.fail("did not raise")
367 finally:
368 recv_task.cancel()
369 self.assertEqual(
370 str(raised.exception),
371 "cannot call recv_streaming while another coroutine "
372 "is already running recv or recv_streaming",
373 )
374
375 async def test_recv_streaming_during_recv_streaming(self):
376 """recv_streaming raises ConcurrencyError when called concurrently."""
377 recv_streaming_task = asyncio.create_task(
378 alist(self.connection.recv_streaming())
379 )
380 await asyncio.sleep(0) # let the event loop start recv_streaming_task
381 try:
382 with self.assertRaises(ConcurrencyError) as raised:
383 async for _ in self.connection.recv_streaming():
384 self.fail("did not raise")
385 finally:
386 recv_streaming_task.cancel()
387 self.assertEqual(
388 str(raised.exception),
389 "cannot call recv_streaming while another coroutine "
390 "is already running recv or recv_streaming",
391 )
392
393 async def test_recv_streaming_cancellation_before_receiving(self):
394 """recv_streaming can be canceled before receiving a message."""
395 recv_streaming_task = asyncio.create_task(
396 alist(self.connection.recv_streaming())
397 )
398 await asyncio.sleep(0) # let the event loop start recv_streaming_task
399 recv_streaming_task.cancel()
400 await asyncio.sleep(0) # let the event loop cancel recv_streaming_task
401
402 # Running recv_streaming again receives the next message.
403 await self.remote_connection.send(["😀", "😀"])
404 self.assertEqual(
405 await alist(self.connection.recv_streaming()),
406 ["😀", "😀", ""],
407 )
408
409 async def test_recv_streaming_cancellation_while_receiving(self):
410 """recv_streaming cannot be canceled while receiving a fragmented message."""
411 gate = asyncio.Event()
412
413 async def fragments():
414 yield "⏳"
415 await gate.wait()
416 yield "⌛️"
417
418 asyncio.create_task(self.remote_connection.send(fragments()))
419 await asyncio.sleep(0)
420
421 recv_streaming_task = asyncio.create_task(
422 alist(self.connection.recv_streaming())
423 )
424 await asyncio.sleep(0) # let the event loop start recv_streaming_task
425 await asyncio.sleep(0) # experimentally, two runs of the event loop
426 await asyncio.sleep(0) # are needed to receive the first fragment
427 recv_streaming_task.cancel()
428 await asyncio.sleep(0) # let the event loop cancel recv_streaming_task
429
430 gate.set()
431 await asyncio.sleep(0)
432
433 # Running recv_streaming again fails.
434 with self.assertRaises(ConcurrencyError):
435 async for _ in self.connection.recv_streaming():
436 self.fail("did not raise")
437
438 # Test send.
439
440 async def test_send_text(self):
441 """send sends a text message."""
442 await self.connection.send("😀")
443 self.assertEqual(await self.remote_connection.recv(), "😀")
444
445 async def test_send_binary(self):
446 """send sends a binary message."""
447 await self.connection.send(b"\x01\x02\xfe\xff")
448 self.assertEqual(await self.remote_connection.recv(), b"\x01\x02\xfe\xff")
449
450 async def test_send_binary_from_str(self):
451 """send sends a binary message from a str."""
452 await self.connection.send("😀", text=False)
453 self.assertEqual(await self.remote_connection.recv(), "😀".encode())
454
455 async def test_send_text_from_bytes(self):
456 """send sends a text message from bytes."""
457 await self.connection.send("😀".encode(), text=True)
458 self.assertEqual(await self.remote_connection.recv(), "😀")
459
460 async def test_send_fragmented_text(self):
461 """send sends a fragmented text message."""
462 await self.connection.send(["😀", "😀"])
463 # websockets sends an trailing empty fragment. That's an implementation detail.
464 self.assertEqual(
465 await alist(self.remote_connection.recv_streaming()),
466 ["😀", "😀", ""],
467 )
468
469 async def test_send_fragmented_binary(self):
470 """send sends a fragmented binary message."""
471 await self.connection.send([b"\x01\x02", b"\xfe\xff"])
472 # websockets sends an trailing empty fragment. That's an implementation detail.
473 self.assertEqual(
474 await alist(self.remote_connection.recv_streaming()),
475 [b"\x01\x02", b"\xfe\xff", b""],
476 )
477
478 async def test_send_fragmented_binary_from_str(self):
479 """send sends a fragmented binary message from a str."""
480 await self.connection.send(["😀", "😀"], text=False)
481 # websockets sends an trailing empty fragment. That's an implementation detail.
482 self.assertEqual(
483 await alist(self.remote_connection.recv_streaming()),
484 ["😀".encode(), "😀".encode(), b""],
485 )
486
487 async def test_send_fragmented_text_from_bytes(self):
488 """send sends a fragmented text message from bytes."""
489 await self.connection.send(["😀".encode(), "😀".encode()], text=True)
490 # websockets sends an trailing empty fragment. That's an implementation detail.
491 self.assertEqual(
492 await alist(self.remote_connection.recv_streaming()),
493 ["😀", "😀", ""],
494 )
495
496 async def test_send_async_fragmented_text(self):
497 """send sends a fragmented text message asynchronously."""
498
499 async def fragments():
500 yield "😀"
501 yield "😀"
502
503 await self.connection.send(fragments())
504 # websockets sends an trailing empty fragment. That's an implementation detail.
505 self.assertEqual(
506 await alist(self.remote_connection.recv_streaming()),
507 ["😀", "😀", ""],
508 )
509
510 async def test_send_async_fragmented_binary(self):
511 """send sends a fragmented binary message asynchronously."""
512
513 async def fragments():
514 yield b"\x01\x02"
515 yield b"\xfe\xff"
516
517 await self.connection.send(fragments())
518 # websockets sends an trailing empty fragment. That's an implementation detail.
519 self.assertEqual(
520 await alist(self.remote_connection.recv_streaming()),
521 [b"\x01\x02", b"\xfe\xff", b""],
522 )
523
524 async def test_send_async_fragmented_binary_from_str(self):
525 """send sends a fragmented binary message from a str asynchronously."""
526
527 async def fragments():
528 yield "😀"
529 yield "😀"
530
531 await self.connection.send(fragments(), text=False)
532 # websockets sends an trailing empty fragment. That's an implementation detail.
533 self.assertEqual(
534 await alist(self.remote_connection.recv_streaming()),
535 ["😀".encode(), "😀".encode(), b""],
536 )
537
538 async def test_send_async_fragmented_text_from_bytes(self):
539 """send sends a fragmented text message from bytes asynchronously."""
540
541 async def fragments():
542 yield "😀".encode()
543 yield "😀".encode()
544
545 await self.connection.send(fragments(), text=True)
546 # websockets sends an trailing empty fragment. That's an implementation detail.
547 self.assertEqual(
548 await alist(self.remote_connection.recv_streaming()),
549 ["😀", "😀", ""],
550 )
551
552 async def test_send_connection_closed_ok(self):
553 """send raises ConnectionClosedOK after a normal closure."""
554 await self.remote_connection.close()
555 with self.assertRaises(ConnectionClosedOK):
556 await self.connection.send("😀")
557
558 async def test_send_connection_closed_error(self):
559 """send raises ConnectionClosedError after an error."""
560 await self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
561 with self.assertRaises(ConnectionClosedError):
562 await self.connection.send("😀")
563
564 async def test_send_during_send(self):
565 """send waits for a previous call to send to complete."""
566 # This test fails if the guard with send_in_progress is removed
567 # from send() in the case when message is an AsyncIterable.
568 gate = asyncio.Event()
569
570 async def fragments():
571 yield "⏳"
572 await gate.wait()
573 yield "⌛️"
574
575 asyncio.create_task(self.connection.send(fragments()))
576 await asyncio.sleep(0) # let the event loop start the task
577 await self.assertFrameSent(
578 Frame(TEXT, "⏳".encode(), fin=False),
579 )
580
581 asyncio.create_task(self.connection.send("✅"))
582 await asyncio.sleep(0) # let the event loop start the task
583 await self.assertNoFrameSent()
584
585 gate.set()
586 await asyncio.sleep(0) # run the event loop
587 await asyncio.sleep(0) # three times in order
588 await asyncio.sleep(0) # to send three frames
589 await self.assertFramesSent(
590 [
591 Frame(CONT, "⌛️".encode(), fin=False),
592 Frame(CONT, b"", fin=True),
593 Frame(TEXT, "✅".encode()),
594 ]
595 )
596
597 async def test_send_while_send_blocked(self):
598 """send waits for a blocked call to send to complete."""
599 # This test fails if the guard with send_in_progress is removed
600 # from send() in the case when message is an Iterable.
601 self.connection.pause_writing()
602
603 asyncio.create_task(self.connection.send(["⏳", "⌛️"]))
604 await asyncio.sleep(0) # let the event loop start the task
605 await self.assertFrameSent(
606 Frame(TEXT, "⏳".encode(), fin=False),
607 )
608
609 asyncio.create_task(self.connection.send("✅"))
610 await asyncio.sleep(0) # let the event loop start the task
611 await self.assertNoFrameSent()
612
613 self.connection.resume_writing()
614 await asyncio.sleep(0) # run the event loop
615 await asyncio.sleep(0) # three times in order
616 await asyncio.sleep(0) # to send three frames
617 await self.assertFramesSent(
618 [
619 Frame(CONT, "⌛️".encode(), fin=False),
620 Frame(CONT, b"", fin=True),
621 Frame(TEXT, "✅".encode()),
622 ]
623 )
624
625 async def test_send_while_send_async_blocked(self):
626 """send waits for a blocked call to send to complete."""
627 # This test fails if the guard with send_in_progress is removed
628 # from send() in the case when message is an AsyncIterable.
629 self.connection.pause_writing()
630
631 async def fragments():
632 yield "⏳"
633 yield "⌛️"
634
635 asyncio.create_task(self.connection.send(fragments()))
636 await asyncio.sleep(0) # let the event loop start the task
637 await self.assertFrameSent(
638 Frame(TEXT, "⏳".encode(), fin=False),
639 )
640
641 asyncio.create_task(self.connection.send("✅"))
642 await asyncio.sleep(0) # let the event loop start the task
643 await self.assertNoFrameSent()
644
645 self.connection.resume_writing()
646 await asyncio.sleep(0) # run the event loop
647 await asyncio.sleep(0) # three times in order
648 await asyncio.sleep(0) # to send three frames
649 await self.assertFramesSent(
650 [
651 Frame(CONT, "⌛️".encode(), fin=False),
652 Frame(CONT, b"", fin=True),
653 Frame(TEXT, "✅".encode()),
654 ]
655 )
656
657 async def test_send_empty_iterable(self):
658 """send does nothing when called with an empty iterable."""
659 await self.connection.send([])
660 await self.connection.close()
661 self.assertEqual(await alist(self.remote_connection), [])
662
663 async def test_send_mixed_iterable(self):
664 """send raises TypeError when called with an iterable of inconsistent types."""
665 with self.assertRaises(TypeError):
666 await self.connection.send(["😀", b"\xfe\xff"])
667
668 async def test_send_unsupported_iterable(self):
669 """send raises TypeError when called with an iterable of unsupported type."""
670 with self.assertRaises(TypeError):
671 await self.connection.send([None])
672
673 async def test_send_empty_async_iterable(self):
674 """send does nothing when called with an empty async iterable."""
675
676 async def fragments():
677 return
678 yield # pragma: no cover
679
680 await self.connection.send(fragments())
681 await self.connection.close()
682 self.assertEqual(await alist(self.remote_connection), [])
683
684 async def test_send_mixed_async_iterable(self):
685 """send raises TypeError when called with an iterable of inconsistent types."""
686
687 async def fragments():
688 yield "😀"
689 yield b"\xfe\xff"
690
691 iterator = fragments()
692 async with contextlib.aclosing(iterator):
693 with self.assertRaises(TypeError):
694 await self.connection.send(iterator)
695
696 async def test_send_unsupported_async_iterable(self):
697 """send raises TypeError when called with an iterable of unsupported type."""
698
699 async def fragments():
700 yield None
701
702 iterator = fragments()
703 async with contextlib.aclosing(iterator):
704 with self.assertRaises(TypeError):
705 await self.connection.send(iterator)
706
707 async def test_send_dict(self):
708 """send raises TypeError when called with a dict."""
709 with self.assertRaises(TypeError):
710 await self.connection.send({"type": "object"})
711
712 async def test_send_unsupported_type(self):
713 """send raises TypeError when called with an unsupported type."""
714 with self.assertRaises(TypeError):
715 await self.connection.send(None)
716
717 # Test close.
718
719 async def test_close(self):
720 """close sends a close frame."""
721 await self.connection.close()
722 await self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
723
724 async def test_close_explicit_code_reason(self):
725 """close sends a close frame with a given code and reason."""
726 await self.connection.close(CloseCode.GOING_AWAY, "bye!")
727 await self.assertFrameSent(Frame(CLOSE, b"\x03\xe9bye!"))
728
729 async def test_close_waits_for_close_frame(self):
730 """close waits for a close frame then EOF before returning."""
731 t0 = self.loop.time()
732 async with self.delay_frames_rcvd(MS), self.delay_eof_rcvd(MS):
733 await self.connection.close()
734 t1 = self.loop.time()
735
736 self.assertEqual(self.connection.state, CLOSED)
737 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
738 self.assertGreater(t1 - t0, MS)
739
740 with self.assertRaises(ConnectionClosedOK) as raised:
741 await self.connection.recv()
742
743 exc = raised.exception
744 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
745 self.assertIsNone(exc.__cause__)
746
747 async def test_close_waits_for_connection_closed(self):
748 """close waits for EOF before returning."""
749 if self.LOCAL is SERVER:
750 self.skipTest("only relevant on the client-side")
751
752 t0 = self.loop.time()
753 async with self.delay_eof_rcvd(MS):
754 await self.connection.close()
755 t1 = self.loop.time()
756
757 self.assertEqual(self.connection.state, CLOSED)
758 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
759 self.assertGreater(t1 - t0, MS)
760
761 with self.assertRaises(ConnectionClosedOK) as raised:
762 await self.connection.recv()
763
764 exc = raised.exception
765 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
766 self.assertIsNone(exc.__cause__)
767
768 async def test_close_no_timeout_waits_for_close_frame(self):
769 """close without timeout waits for a close frame then EOF before returning."""
770 self.connection.close_timeout = None
771
772 t0 = self.loop.time()
773 async with self.delay_frames_rcvd(MS), self.delay_eof_rcvd(MS):
774 await self.connection.close()
775 t1 = self.loop.time()
776
777 self.assertEqual(self.connection.state, CLOSED)
778 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
779 self.assertGreater(t1 - t0, MS)
780
781 with self.assertRaises(ConnectionClosedOK) as raised:
782 await self.connection.recv()
783
784 exc = raised.exception
785 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
786 self.assertIsNone(exc.__cause__)
787
788 async def test_close_no_timeout_waits_for_connection_closed(self):
789 """close without timeout waits for EOF before returning."""
790 if self.LOCAL is SERVER:
791 self.skipTest("only relevant on the client-side")
792
793 self.connection.close_timeout = None
794
795 t0 = self.loop.time()
796 async with self.delay_eof_rcvd(MS):
797 await self.connection.close()
798 t1 = self.loop.time()
799
800 self.assertEqual(self.connection.state, CLOSED)
801 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
802 self.assertGreater(t1 - t0, MS)
803
804 with self.assertRaises(ConnectionClosedOK) as raised:
805 await self.connection.recv()
806
807 exc = raised.exception
808 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
809 self.assertIsNone(exc.__cause__)
810
811 async def test_close_timeout_waiting_for_close_frame(self):
812 """close times out if no close frame is received."""
813 t0 = self.loop.time()
814 async with self.drop_eof_rcvd(), self.drop_frames_rcvd():
815 await self.connection.close()
816 t1 = self.loop.time()
817
818 self.assertEqual(self.connection.state, CLOSED)
819 self.assertEqual(self.connection.close_code, CloseCode.ABNORMAL_CLOSURE)
820 self.assertGreater(t1 - t0, 2 * MS)
821
822 with self.assertRaises(ConnectionClosedError) as raised:
823 await self.connection.recv()
824
825 exc = raised.exception
826 self.assertEqual(str(exc), "sent 1000 (OK); no close frame received")
827 self.assertIsInstance(exc.__cause__, TimeoutError)
828
829 async def test_close_timeout_waiting_for_connection_closed(self):
830 """close times out if EOF isn't received."""
831 if self.LOCAL is SERVER:
832 self.skipTest("only relevant on the client-side")
833
834 t0 = self.loop.time()
835 async with self.drop_eof_rcvd():
836 await self.connection.close()
837 t1 = self.loop.time()
838
839 self.assertEqual(self.connection.state, CLOSED)
840 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
841 self.assertGreater(t1 - t0, 2 * MS)
842
843 with self.assertRaises(ConnectionClosedOK) as raised:
844 await self.connection.recv()
845
846 exc = raised.exception
847 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
848 self.assertIsInstance(exc.__cause__, TimeoutError)
849
850 async def test_close_preserves_queued_messages(self):
851 """close preserves messages buffered in the assembler."""
852 await self.remote_connection.send("😀")
853 await self.connection.close()
854
855 self.assertEqual(await self.connection.recv(), "😀")
856 with self.assertRaises(ConnectionClosedOK):
857 await self.connection.recv()
858
859 async def test_close_idempotency(self):
860 """close does nothing if the connection is already closed."""
861 await self.connection.close()
862 await self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
863
864 await self.connection.close()
865 await self.assertNoFrameSent()
866
867 async def test_close_during_recv(self):
868 """close aborts recv when called concurrently with recv."""
869
870 async def closer():
871 await asyncio.sleep(MS)
872 await self.connection.close()
873
874 asyncio.create_task(closer())
875 with self.assertRaises(ConnectionClosedOK) as raised:
876 await self.connection.recv()
877
878 exc = raised.exception
879 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
880 self.assertIsNone(exc.__cause__)
881
882 async def test_close_during_recv_streaming(self):
883 """close aborts recv_streaming when called concurrently with recv_streaming."""
884
885 async def closer():
886 await asyncio.sleep(MS)
887 await self.connection.close()
888
889 asyncio.create_task(closer())
890 with self.assertRaises(ConnectionClosedOK) as raised:
891 async for _ in self.connection.recv_streaming():
892 self.fail("did not raise")
893
894 exc = raised.exception
895 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
896 self.assertIsNone(exc.__cause__)
897
898 async def test_close_during_send(self):
899 """close fails the connection when called concurrently with send."""
900 close_gate = asyncio.Event()
901 exit_gate = asyncio.Event()
902
903 async def closer():
904 await close_gate.wait()
905 await self.connection.close()
906 exit_gate.set()
907
908 async def fragments():
909 yield "⏳"
910 close_gate.set()
911 await exit_gate.wait()
912 yield "⌛️"
913
914 asyncio.create_task(closer())
915 iterator = fragments()
916 async with contextlib.aclosing(iterator):
917 with self.assertRaises(ConnectionClosedError) as raised:
918 await self.connection.send(iterator)
919
920 exc = raised.exception
921 self.assertEqual(
922 str(exc),
923 "sent 1011 (internal error) close during fragmented message; "
924 "no close frame received",
925 )
926 self.assertIsNone(exc.__cause__)
927
928 # Test wait_closed.
929
930 async def test_wait_closed(self):
931 """wait_closed waits for the connection to close."""
932 wait_closed_task = asyncio.create_task(self.connection.wait_closed())
933 await asyncio.sleep(0) # let the event loop start wait_closed_task
934 self.assertFalse(wait_closed_task.done())
935 await self.connection.close()
936 self.assertTrue(wait_closed_task.done())
937
938 # Test ping.
939
940 @patch("random.getrandbits")
941 async def test_ping(self, getrandbits):
942 """ping sends a ping frame with a random payload."""
943 getrandbits.side_effect = itertools.count(1918987876)
944 await self.connection.ping()
945 getrandbits.assert_called_once_with(32)
946 await self.assertFrameSent(Frame(PING, b"rand"))
947
948 async def test_ping_explicit_text(self):
949 """ping sends a ping frame with a payload provided as text."""
950 await self.connection.ping("ping")
951 await self.assertFrameSent(Frame(PING, b"ping"))
952
953 async def test_ping_explicit_binary(self):
954 """ping sends a ping frame with a payload provided as binary."""
955 await self.connection.ping(b"ping")
956 await self.assertFrameSent(Frame(PING, b"ping"))
957
958 async def test_acknowledge_ping(self):
959 """ping is acknowledged by a pong with the same payload."""
960 async with self.drop_frames_rcvd(): # drop automatic response to ping
961 pong_received = await self.connection.ping("this")
962 await self.remote_connection.pong("this")
963 async with asyncio.timeout(MS):
964 await pong_received
965
966 async def test_acknowledge_canceled_ping(self):
967 """ping is acknowledged by a pong with the same payload after being canceled."""
968 async with self.drop_frames_rcvd(): # drop automatic response to ping
969 pong_received = await self.connection.ping("this")
970 pong_received.cancel()
971 await self.remote_connection.pong("this")
972 with self.assertRaises(asyncio.CancelledError):
973 await pong_received
974
975 async def test_acknowledge_ping_non_matching_pong(self):
976 """ping isn't acknowledged by a pong with a different payload."""
977 async with self.drop_frames_rcvd(): # drop automatic response to ping
978 pong_received = await self.connection.ping("this")
979 await self.remote_connection.pong("that")
980 with self.assertRaises(TimeoutError):
981 async with asyncio.timeout(MS):
982 await pong_received
983
984 async def test_acknowledge_previous_ping(self):
985 """ping is acknowledged by a pong for a later ping."""
986 async with self.drop_frames_rcvd(): # drop automatic response to ping
987 pong_received = await self.connection.ping("this")
988 await self.connection.ping("that")
989 await self.remote_connection.pong("that")
990 async with asyncio.timeout(MS):
991 await pong_received
992
993 async def test_acknowledge_previous_canceled_ping(self):
994 """ping is acknowledged by a pong for a later ping after being canceled."""
995 async with self.drop_frames_rcvd(): # drop automatic response to ping
996 pong_received = await self.connection.ping("this")
997 pong_received_2 = await self.connection.ping("that")
998 pong_received.cancel()
999 await self.remote_connection.pong("that")
1000 async with asyncio.timeout(MS):
1001 await pong_received_2
1002 with self.assertRaises(asyncio.CancelledError):
1003 await pong_received
1004
1005 async def test_terminate_ping_on_close(self):
1006 """ping is done with an exception when the connection is closed."""
1007 async with self.drop_frames_rcvd(): # drop automatic response to ping
1008 pong_received = await self.connection.ping("this")
1009 await self.connection.close()
1010 with self.assertRaises(ConnectionClosedOK):
1011 await pong_received
1012
1013 async def test_ping_duplicate_payload(self):
1014 """ping rejects the same payload until receiving the pong."""
1015 async with self.drop_frames_rcvd(): # drop automatic response to ping
1016 pong_received = await self.connection.ping("idem")
1017
1018 with self.assertRaises(ConcurrencyError) as raised:
1019 await self.connection.ping("idem")
1020 self.assertEqual(
1021 str(raised.exception),
1022 "already waiting for a pong with the same data",
1023 )
1024
1025 await self.remote_connection.pong("idem")
1026 async with asyncio.timeout(MS):
1027 await pong_received
1028
1029 await self.connection.ping("idem") # doesn't raise an exception
1030
1031 async def test_ping_unsupported_type(self):
1032 """ping raises TypeError when called with an unsupported type."""
1033 with self.assertRaises(TypeError):
1034 await self.connection.ping([])
1035
1036 # Test pong.
1037
1038 async def test_pong(self):
1039 """pong sends a pong frame."""
1040 await self.connection.pong()
1041 await self.assertFrameSent(Frame(PONG, b""))
1042
1043 async def test_pong_explicit_text(self):
1044 """pong sends a pong frame with a payload provided as text."""
1045 await self.connection.pong("pong")
1046 await self.assertFrameSent(Frame(PONG, b"pong"))
1047
1048 async def test_pong_explicit_binary(self):
1049 """pong sends a pong frame with a payload provided as binary."""
1050 await self.connection.pong(b"pong")
1051 await self.assertFrameSent(Frame(PONG, b"pong"))
1052
1053 async def test_pong_unsupported_type(self):
1054 """pong raises TypeError when called with an unsupported type."""
1055 with self.assertRaises(TypeError):
1056 await self.connection.pong([])
1057
1058 # Test keepalive.
1059
1060 @patch("random.getrandbits")
1061 async def test_keepalive(self, getrandbits):
1062 """keepalive sends pings at ping_interval and measures latency."""
1063 getrandbits.side_effect = itertools.count(1918987876)
1064 self.connection.ping_interval = 3 * MS
1065 self.connection.start_keepalive()
1066 self.assertIsNotNone(self.connection.keepalive_task)
1067 self.assertEqual(self.connection.latency, 0)
1068 # 3 ms: keepalive() sends a ping frame.
1069 # 3.x ms: a pong frame is received.
1070 await asyncio.sleep(4 * MS)
1071 # 4 ms: check that the ping frame was sent.
1072 await self.assertFrameSent(Frame(PING, b"rand"))
1073 self.assertGreater(self.connection.latency, 0)
1074 self.assertLess(self.connection.latency, MS)
1075
1076 async def test_disable_keepalive(self):
1077 """keepalive is disabled when ping_interval is None."""
1078 self.connection.ping_interval = None
1079 self.connection.start_keepalive()
1080 self.assertIsNone(self.connection.keepalive_task)
1081
1082 @patch("random.getrandbits")
1083 async def test_keepalive_times_out(self, getrandbits):
1084 """keepalive closes the connection if ping_timeout elapses."""
1085 getrandbits.side_effect = itertools.count(1918987876)
1086 self.connection.ping_interval = 4 * MS
1087 self.connection.ping_timeout = 2 * MS
1088 async with self.drop_frames_rcvd():
1089 self.connection.start_keepalive()
1090 # 4 ms: keepalive() sends a ping frame.
1091 # 4.x ms: a pong frame is dropped.
1092 await asyncio.sleep(5 * MS)
1093 # 6 ms: no pong frame is received; the connection is closed.
1094 await asyncio.sleep(3 * MS)
1095 # 8 ms: check that the connection is closed.
1096 self.assertEqual(self.connection.state, CLOSED)
1097
1098 @patch("random.getrandbits")
1099 async def test_keepalive_ignores_timeout(self, getrandbits):
1100 """keepalive ignores timeouts if ping_timeout isn't set."""
1101 getrandbits.side_effect = itertools.count(1918987876)
1102 self.connection.ping_interval = 4 * MS
1103 self.connection.ping_timeout = None
1104 async with self.drop_frames_rcvd():
1105 self.connection.start_keepalive()
1106 # 4 ms: keepalive() sends a ping frame.
1107 # 4.x ms: a pong frame is dropped.
1108 await asyncio.sleep(5 * MS)
1109 # 6 ms: no pong frame is received; the connection remains open.
1110 await asyncio.sleep(3 * MS)
1111 # 8 ms: check that the connection is still open.
1112 self.assertEqual(self.connection.state, OPEN)
1113
1114 async def test_keepalive_terminates_while_sleeping(self):
1115 """keepalive task terminates while waiting to send a ping."""
1116 self.connection.ping_interval = 3 * MS
1117 self.connection.start_keepalive()
1118 # Keep a reference to self.connection.keepalive_task
1119 # because it's set to None once cancelled.
1120 keepalive_task = self.connection.keepalive_task
1121 await asyncio.sleep(MS)
1122 self.assertFalse(keepalive_task.done())
1123 await self.connection.close()
1124 self.assertTrue(keepalive_task.done())
1125
1126 # test_keepalive_terminates_when_sending_ping_fails is not implemented
1127 # because sending a ping cannot fail in the asyncio implementation.
1128
1129 async def test_keepalive_terminates_while_waiting_for_pong(self):
1130 """keepalive task terminates while waiting to receive a pong."""
1131 self.connection.ping_interval = MS
1132 self.connection.ping_timeout = 4 * MS
1133 async with self.drop_frames_rcvd():
1134 self.connection.start_keepalive()
1135 # Keep a reference to self.connection.keepalive_task
1136 # because it's set to None once cancelled.
1137 keepalive_task = self.connection.keepalive_task
1138 # 1 ms: keepalive() sends a ping frame.
1139 # 1.x ms: a pong frame is dropped.
1140 await asyncio.sleep(2 * MS)
1141 # 2 ms: close the connection before ping_timeout elapses.
1142 await self.connection.close()
1143 self.assertTrue(keepalive_task.done())
1144
1145 async def test_keepalive_reports_errors(self):
1146 """keepalive reports unexpected errors in logs."""
1147 self.connection.ping_interval = 2 * MS
1148 self.connection.start_keepalive()
1149 async with self.drop_frames_rcvd():
1150 # 2 ms: keepalive() sends a ping frame.
1151 # 2.x ms: a pong frame is dropped.
1152 await asyncio.sleep(3 * MS)
1153 # 3 ms: inject a fault: raise an exception in the pending pong waiter.
1154 pong_received = next(iter(self.connection.pending_pings.values()))[0]
1155 with self.assertLogs("websockets", logging.ERROR) as logs:
1156 pong_received.set_exception(Exception("BOOM"))
1157 await asyncio.sleep(0)
1158 self.assertExceptionLogged(logs, "keepalive ping failed", "BOOM")
1159
1160 # Test parameters.
1161
1162 async def test_close_timeout(self):
1163 """close_timeout parameter configures close timeout."""
1164 connection = Connection(
1165 Protocol(self.LOCAL),
1166 close_timeout=42 * MS,
1167 )
1168 self.assertEqual(connection.close_timeout, 42 * MS)
1169
1170 async def test_max_queue(self):
1171 """max_queue configures high-water mark of frames buffer."""
1172 connection = Connection(
1173 Protocol(self.LOCAL),
1174 max_queue=4,
1175 )
1176 connection.connection_made(Mock(spec=asyncio.Transport))
1177 self.assertEqual(connection.recv_messages.high, 4)
1178
1179 async def test_max_queue_none(self):
1180 """max_queue disables high-water mark of frames buffer."""
1181 connection = Connection(
1182 Protocol(self.LOCAL),
1183 max_queue=None,
1184 )
1185 connection.connection_made(Mock(spec=asyncio.Transport))
1186 self.assertEqual(connection.recv_messages.high, None)
1187 self.assertEqual(connection.recv_messages.low, None)
1188
1189 async def test_max_queue_tuple(self):
1190 """max_queue configures high-water and low-water marks of frames buffer."""
1191 connection = Connection(
1192 Protocol(self.LOCAL),
1193 max_queue=(4, 2),
1194 )
1195 connection.connection_made(Mock(spec=asyncio.Transport))
1196 self.assertEqual(connection.recv_messages.high, 4)
1197 self.assertEqual(connection.recv_messages.low, 2)
1198
1199 async def test_write_limit(self):
1200 """write_limit parameter configures high-water mark of write buffer."""
1201 connection = Connection(
1202 Protocol(self.LOCAL),
1203 write_limit=4096,
1204 )
1205 transport = Mock(spec=asyncio.Transport)
1206 connection.connection_made(transport)
1207 transport.set_write_buffer_limits.assert_called_once_with(4096, None)
1208
1209 async def test_write_limits(self):
1210 """write_limit parameter configures high and low-water marks of write buffer."""
1211 connection = Connection(
1212 Protocol(self.LOCAL),
1213 write_limit=(4096, 2048),
1214 )
1215 transport = Mock(spec=asyncio.Transport)
1216 connection.connection_made(transport)
1217 transport.set_write_buffer_limits.assert_called_once_with(4096, 2048)
1218
1219 # Test attributes.
1220
1221 async def test_id(self):
1222 """Connection has an id attribute."""
1223 self.assertIsInstance(self.connection.id, uuid.UUID)
1224
1225 async def test_logger(self):
1226 """Connection has a logger attribute."""
1227 self.assertIsInstance(self.connection.logger, logging.LoggerAdapter)
1228
1229 @patch("asyncio.Transport.get_extra_info")
1230 async def test_local_address(self, get_extra_info):
1231 """Connection has a local_address attribute."""
1232 get_extra_info.return_value = ("sock", 1234)
1233 self.assertEqual(self.connection.local_address, ("sock", 1234))
1234 get_extra_info.assert_called_with("sockname")
1235
1236 @patch("asyncio.Transport.get_extra_info")
1237 async def test_remote_address(self, get_extra_info):
1238 """Connection has a remote_address attribute."""
1239 get_extra_info.return_value = ("peer", 1234)
1240 self.assertEqual(self.connection.remote_address, ("peer", 1234))
1241 get_extra_info.assert_called_with("peername")
1242
1243 async def test_state(self):
1244 """Connection has a state attribute."""
1245 self.assertIs(self.connection.state, OPEN)
1246
1247 async def test_request(self):
1248 """Connection has a request attribute."""
1249 self.assertIsNone(self.connection.request)
1250
1251 async def test_response(self):
1252 """Connection has a response attribute."""
1253 self.assertIsNone(self.connection.response)
1254
1255 async def test_subprotocol(self):
1256 """Connection has a subprotocol attribute."""
1257 self.assertIsNone(self.connection.subprotocol)
1258
1259 async def test_close_code(self):
1260 """Connection has a close_code attribute."""
1261 self.assertIsNone(self.connection.close_code)
1262
1263 async def test_close_reason(self):
1264 """Connection has a close_reason attribute."""
1265 self.assertIsNone(self.connection.close_reason)
1266
1267 # Test backpressure.
1268
1269 async def test_backpressure(self):
1270 """Connection stops reading from the network when the buffer fills up."""
1271 self.connection.recv_messages.high = 1
1272 self.connection.recv_messages.low = 0
1273 frames_buffer = self.connection.recv_messages.frames
1274
1275 await self.remote_connection.send("A")
1276 await self.remote_connection.send("B")
1277
1278 # Assembler buffer is above the high water mark. Backpressure kicks in.
1279 await self.wait_for_remote_side()
1280 self.assertFalse(self.transport.is_reading())
1281 self.assertEqual(len(frames_buffer), 2)
1282
1283 await self.remote_connection.send("C")
1284
1285 # A third frame is sent by the peer but the connection doesn't read it.
1286 await self.wait_for_remote_side()
1287 self.assertEqual(len(frames_buffer), 2)
1288
1289 self.assertEqual(await self.connection.recv(), "A")
1290 self.assertEqual(await self.connection.recv(), "B")
1291
1292 # Draining the assembler buffer below the low water mark resumes reading.
1293 await self.wait_for_remote_side()
1294 self.assertTrue(self.transport.is_reading())
1295 self.assertEqual(len(frames_buffer), 1)
1296
1297 self.assertEqual(await self.connection.recv(), "C")
1298
1299 # Test reporting of network errors.
1300
1301 async def test_writing_in_data_received_fails(self):
1302 """Error when responding to incoming frames is correctly reported."""
1303 # Inject a fault by shutting down the transport for writing.
1304 # Don't close it because that would terminate the connection.
1305 self.transport.write_eof()
1306 # Receive a ping. Responding with a pong will fail.
1307 await self.remote_connection.ping()
1308 with self.assertRaises(ConnectionClosedError) as raised:
1309 await self.connection.recv()
1310 self.assertIsInstance(raised.exception.__cause__, RuntimeError)
1311
1312 async def test_writing_in_send_context_fails(self):
1313 """Error when sending outgoing frame is correctly reported."""
1314 # Inject a fault by shutting down the transport for writing.
1315 # Don't close it because that would terminate the connection.
1316 self.transport.write_eof()
1317 # Sending a pong will fail.
1318 with self.assertRaises(ConnectionClosedError) as raised:
1319 await self.connection.pong()
1320 self.assertIsInstance(raised.exception.__cause__, RuntimeError)
1321
1322 # Test safety nets — catching all exceptions in case of bugs.
1323
1324 @patch("websockets.protocol.Protocol.events_received", side_effect=AssertionError)
1325 async def test_unexpected_failure_in_data_received(self, events_received):
1326 """Unexpected internal error in data_received() is correctly reported."""
1327 await self.remote_connection.send("😀")
1328 # Reading the message will trigger the injected fault.
1329 with self.assertRaises(ConnectionClosedError) as raised:
1330 await self.connection.recv()
1331 self.assertIsInstance(raised.exception.__cause__, AssertionError)
1332
1333 @patch("websockets.protocol.Protocol.send_text", side_effect=AssertionError)
1334 async def test_unexpected_failure_in_send_context(self, send_text):
1335 """Unexpected internal error in send_context() is correctly reported."""
1336 # Sending a message will trigger the injected fault.
1337 with self.assertRaises(ConnectionClosedError) as raised:
1338 await self.connection.send("😀")
1339 self.assertIsInstance(raised.exception.__cause__, AssertionError)
1340
1341 # Test garbage collection.
1342
1343 @unittest.skipUnless(
1344 sys.implementation.name == "cpython",
1345 "this test checks the behavior of CPython's garbage collector",
1346 )
1347 async def test_no_reference_cycle(self):
1348 """Connection is garbage collected immediately after deletion."""
1349 self.connection.start_keepalive()
1350 await asyncio.sleep(0) # let the event loop start the keepalive task
1351 await self.connection.close()
1352
1353 connection_ref = weakref.ref(self.connection)
1354 del self.connection
1355 self.assertIsNone(connection_ref(), "still alive after deletion")
1356
1357 # Test broadcast.
1358
1359 async def test_broadcast_text(self):
1360 """broadcast broadcasts a text message."""
1361 broadcast([self.connection], "😀")
1362 await self.assertFrameSent(Frame(TEXT, "😀".encode()))
1363
1364 async def test_broadcast_text_reports_no_errors(self):
1365 """broadcast broadcasts a text message without raising exceptions."""
1366 broadcast([self.connection], "😀", raise_exceptions=True)
1367 await self.assertFrameSent(Frame(TEXT, "😀".encode()))
1368
1369 async def test_broadcast_binary(self):
1370 """broadcast broadcasts a binary message."""
1371 broadcast([self.connection], b"\x01\x02\xfe\xff")
1372 await self.assertFrameSent(Frame(BINARY, b"\x01\x02\xfe\xff"))
1373
1374 async def test_broadcast_binary_reports_no_errors(self):
1375 """broadcast broadcasts a binary message without raising exceptions."""
1376 broadcast([self.connection], b"\x01\x02\xfe\xff", raise_exceptions=True)
1377 await self.assertFrameSent(Frame(BINARY, b"\x01\x02\xfe\xff"))
1378
1379 async def test_broadcast_text_from_bytes(self):
1380 """broadcast broadcasts a text message from bytes."""
1381 broadcast([self.connection], "😀".encode(), text=True)
1382 await self.assertFrameSent(Frame(TEXT, "😀".encode()))
1383
1384 async def test_broadcast_binary_from_str(self):
1385 """broadcast broadcasts a binary message from a str."""
1386 broadcast([self.connection], "😀", text=False)
1387 await self.assertFrameSent(Frame(BINARY, "😀".encode()))
1388
1389 async def test_broadcast_no_clients(self):
1390 """broadcast does nothing when called with an empty list of clients."""
1391 broadcast([], "😀")
1392 await self.assertNoFrameSent()
1393
1394 async def test_broadcast_two_clients(self):
1395 """broadcast broadcasts a message to several clients."""
1396 broadcast([self.connection, self.connection], "😀")
1397 await self.assertFramesSent(
1398 [
1399 Frame(TEXT, "😀".encode()),
1400 Frame(TEXT, "😀".encode()),
1401 ]
1402 )
1403
1404 async def test_broadcast_skips_closed_connection(self):
1405 """broadcast ignores closed connections."""
1406 await self.connection.close()
1407 await self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
1408
1409 with self.assertNoLogs("websockets", logging.WARNING):
1410 broadcast([self.connection], "😀")
1411 await self.assertNoFrameSent()
1412
1413 async def test_broadcast_skips_closing_connection(self):
1414 """broadcast ignores closing connections."""
1415 async with self.delay_frames_rcvd(MS):
1416 close_task = asyncio.create_task(self.connection.close())
1417 await asyncio.sleep(0)
1418 await self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
1419
1420 with self.assertNoLogs("websockets", logging.WARNING):
1421 broadcast([self.connection], "😀")
1422 await self.assertNoFrameSent()
1423
1424 await close_task
1425
1426 async def test_broadcast_skips_connection_with_send_blocked(self):
1427 """broadcast logs a warning when a connection is blocked in send."""
1428 gate = asyncio.Event()
1429
1430 async def fragments():
1431 yield "⏳"
1432 await gate.wait()
1433
1434 send_task = asyncio.create_task(self.connection.send(fragments()))
1435 await asyncio.sleep(MS)
1436 await self.assertFrameSent(Frame(TEXT, "⏳".encode(), fin=False))
1437
1438 with self.assertLogs("websockets", logging.WARNING) as logs:
1439 broadcast([self.connection], "😀")
1440
1441 self.assertEqual(
1442 [record.getMessage() for record in logs.records],
1443 ["skipped broadcast: sending a fragmented message"],
1444 )
1445
1446 gate.set()
1447 await send_task
1448
1449 async def test_broadcast_reports_connection_with_send_blocked(self):
1450 """broadcast raises exceptions for connections blocked in send."""
1451 gate = asyncio.Event()
1452
1453 async def fragments():
1454 yield "⏳"
1455 await gate.wait()
1456
1457 send_task = asyncio.create_task(self.connection.send(fragments()))
1458 await asyncio.sleep(MS)
1459 await self.assertFrameSent(Frame(TEXT, "⏳".encode(), fin=False))
1460
1461 with self.assertRaises(ExceptionGroup) as raised:
1462 broadcast([self.connection], "😀", raise_exceptions=True)
1463
1464 self.assertEqual(str(raised.exception), "skipped broadcast (1 sub-exception)")
1465 exc = raised.exception.exceptions[0]
1466 self.assertEqual(str(exc), "sending a fragmented message")
1467 self.assertIsInstance(exc, ConcurrencyError)
1468
1469 gate.set()
1470 await send_task
1471
1472 async def test_broadcast_skips_connection_failing_to_send(self):
1473 """broadcast logs a warning when a connection fails to send."""
1474 # Inject a fault by shutting down the transport for writing.
1475 # Don't close it because that would terminate the connection.
1476 self.transport.write_eof()
1477
1478 with self.assertLogs("websockets", logging.WARNING) as logs:
1479 broadcast([self.connection], "😀")
1480
1481 self.assertEqual(
1482 [record.getMessage() for record in logs.records],
1483 [
1484 "skipped broadcast: failed to write message: "
1485 "RuntimeError: Cannot call write() after write_eof()"
1486 ],
1487 )
1488
1489 async def test_broadcast_reports_connection_failing_to_send(self):
1490 """broadcast raises exceptions for connections failing to send."""
1491 # Inject a fault by shutting down the transport for writing.
1492 # Don't close it because that would terminate the connection.
1493 self.transport.write_eof()
1494
1495 with self.assertRaises(ExceptionGroup) as raised:
1496 broadcast([self.connection], "😀", raise_exceptions=True)
1497
1498 self.assertEqual(str(raised.exception), "skipped broadcast (1 sub-exception)")
1499 exc = raised.exception.exceptions[0]
1500 self.assertEqual(str(exc), "failed to write message")
1501 self.assertIsInstance(exc, RuntimeError)
1502 cause = exc.__cause__
1503 self.assertEqual(str(cause), "Cannot call write() after write_eof()")
1504 self.assertIsInstance(cause, RuntimeError)
1505
1506 async def test_broadcast_type_error(self):
1507 """broadcast raises TypeError when called with an unsupported type."""
1508 with self.assertRaises(TypeError):
1509 broadcast([self.connection], ["⏳", "⌛️"])
1510
1511
1512 class ServerConnectionTests(ClientConnectionTests):
1513 LOCAL = SERVER
1514 REMOTE = CLIENT