Debian Codegraph @

tests/trio/test_connection.py

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