Debian Codegraph @

tests/sync/test_connection.py

raw
1 import contextlib
2 import itertools
3 import logging
4 import socket
5 import sys
6 import threading
7 import time
8 import unittest
9 import uuid
10 import weakref
11 from unittest.mock import Mock, patch
12
13 from websockets.exceptions import (
14 ConcurrencyError,
15 ConnectionClosedError,
16 ConnectionClosedOK,
17 )
18 from websockets.frames import BINARY, CLOSE, PING, PONG, TEXT, CloseCode, Frame
19 from websockets.protocol import CLIENT, CLOSED, CONNECTING, OPEN, SERVER, Protocol
20 from websockets.sync.connection import *
21 from websockets.sync.connection import broadcast
22
23 from ..protocol import RecordingProtocol
24 from ..utils import MS, LoggingTestCase
25 from .connection import InterceptingConnection
26 from .utils import ThreadTestCase
27
28
29 # Connection implements symmetrical behavior between clients and servers.
30 # All tests run on the client side and the server side to validate this.
31
32
33 class ClientConnectionTests(LoggingTestCase, ThreadTestCase):
34 LOCAL = CLIENT
35 REMOTE = SERVER
36
37 def setUp(self):
38 socket_, remote_socket = socket.socketpair()
39 protocol = Protocol(self.LOCAL)
40 remote_protocol = RecordingProtocol(self.REMOTE)
41 self.connection = Connection(socket_, protocol, close_timeout=2 * MS)
42 self.remote_connection = InterceptingConnection(remote_socket, remote_protocol)
43
44 def tearDown(self):
45 self.remote_connection.close()
46 if hasattr(self, "connection"):
47 self.connection.close()
48
49 # Test helpers built upon RecordingProtocol and InterceptingConnection.
50
51 def wait_for_remote_side(self):
52 """Wait for the remote side to process messages."""
53 # We don't have a way to tell if the remote side is blocked on I/O.
54 # The sync tests still run faster than the asyncio and trio tests :-)
55 time.sleep(MS)
56
57 def assertFrameSent(self, frame):
58 """Check that a single frame was sent."""
59 self.wait_for_remote_side()
60 self.assertEqual(self.remote_connection.protocol.get_frames_rcvd(), [frame])
61
62 def assertFramesSent(self, frames):
63 """Check that several frames were sent."""
64 self.wait_for_remote_side()
65 self.assertEqual(self.remote_connection.protocol.get_frames_rcvd(), frames)
66
67 def assertNoFrameSent(self):
68 """Check that no frame was sent."""
69 self.wait_for_remote_side()
70 self.assertEqual(self.remote_connection.protocol.get_frames_rcvd(), [])
71
72 @contextlib.contextmanager
73 def delay_frames_rcvd(self, delay):
74 """Delay frames before they're received by the connection."""
75 with self.remote_connection.delay_frames_sent(delay):
76 yield
77 self.wait_for_remote_side()
78
79 @contextlib.contextmanager
80 def delay_eof_rcvd(self, delay):
81 """Delay EOF before it's received by the connection."""
82 with self.remote_connection.delay_eof_sent(delay):
83 yield
84 self.wait_for_remote_side()
85
86 @contextlib.contextmanager
87 def drop_frames_rcvd(self):
88 """Drop frames before they're received by the connection."""
89 with self.remote_connection.drop_frames_sent():
90 yield
91 self.wait_for_remote_side()
92
93 @contextlib.contextmanager
94 def drop_eof_rcvd(self):
95 """Drop EOF before it's received by the connection."""
96 with self.remote_connection.drop_eof_sent():
97 yield
98 self.wait_for_remote_side()
99
100 # Test __enter__ and __exit__.
101
102 def test_enter(self):
103 """__enter__ returns the connection itself."""
104 with self.connection as connection:
105 self.assertIs(connection, self.connection)
106
107 def test_exit(self):
108 """__exit__ closes the connection with code 1000."""
109 with self.connection:
110 self.assertNoFrameSent()
111 self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
112
113 def test_exit_with_exception(self):
114 """__exit__ with an exception closes the connection with code 1011."""
115 with self.assertRaises(RuntimeError):
116 with self.connection:
117 raise RuntimeError
118 self.assertFrameSent(Frame(CLOSE, b"\x03\xf3"))
119
120 # Test __iter__.
121
122 def test_iter_text(self):
123 """__iter__ yields text messages."""
124 iterator = iter(self.connection)
125 with contextlib.closing(iterator):
126 self.remote_connection.send("😀")
127 self.assertEqual(next(iterator), "😀")
128 self.remote_connection.send("😀")
129 self.assertEqual(next(iterator), "😀")
130
131 def test_iter_binary(self):
132 """__iter__ yields binary messages."""
133 iterator = iter(self.connection)
134 with contextlib.closing(iterator):
135 self.remote_connection.send(b"\x01\x02\xfe\xff")
136 self.assertEqual(next(iterator), b"\x01\x02\xfe\xff")
137 self.remote_connection.send(b"\x01\x02\xfe\xff")
138 self.assertEqual(next(iterator), b"\x01\x02\xfe\xff")
139
140 def test_iter_mixed(self):
141 """__iter__ yields a mix of text and binary messages."""
142 iterator = iter(self.connection)
143 with contextlib.closing(iterator):
144 self.remote_connection.send("😀")
145 self.assertEqual(next(iterator), "😀")
146 self.remote_connection.send(b"\x01\x02\xfe\xff")
147 self.assertEqual(next(iterator), b"\x01\x02\xfe\xff")
148
149 def test_iter_connection_closed_ok(self):
150 """__iter__ terminates after a normal closure."""
151 iterator = iter(self.connection)
152 with contextlib.closing(iterator):
153 self.remote_connection.close()
154 with self.assertRaises(StopIteration):
155 next(iterator)
156
157 def test_iter_connection_closed_error(self):
158 """__iter__ raises ConnectionClosedError after an error."""
159 iterator = iter(self.connection)
160 with contextlib.closing(iterator):
161 self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
162 with self.assertRaises(ConnectionClosedError):
163 next(iterator)
164
165 # Test recv.
166
167 def test_recv_text(self):
168 """recv receives a text message."""
169 self.remote_connection.send("😀")
170 self.assertEqual(self.connection.recv(), "😀")
171
172 def test_recv_binary(self):
173 """recv receives a binary message."""
174 self.remote_connection.send(b"\x01\x02\xfe\xff")
175 self.assertEqual(self.connection.recv(), b"\x01\x02\xfe\xff")
176
177 def test_recv_text_as_bytes(self):
178 """recv receives a text message as bytes."""
179 self.remote_connection.send("😀")
180 self.assertEqual(self.connection.recv(decode=False), "😀".encode())
181
182 def test_recv_binary_as_text(self):
183 """recv receives a binary message as a str."""
184 self.remote_connection.send("😀".encode())
185 self.assertEqual(self.connection.recv(decode=True), "😀")
186
187 def test_recv_fragmented_text(self):
188 """recv receives a fragmented text message."""
189 self.remote_connection.send(["😀", "😀"])
190 self.assertEqual(self.connection.recv(), "😀😀")
191
192 def test_recv_fragmented_binary(self):
193 """recv receives a fragmented binary message."""
194 self.remote_connection.send([b"\x01\x02", b"\xfe\xff"])
195 self.assertEqual(self.connection.recv(), b"\x01\x02\xfe\xff")
196
197 def test_recv_connection_closed_ok(self):
198 """recv raises ConnectionClosedOK after a normal closure."""
199 self.remote_connection.close()
200 with self.assertRaises(ConnectionClosedOK):
201 self.connection.recv()
202
203 def test_recv_connection_closed_error(self):
204 """recv raises ConnectionClosedError after an error."""
205 self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
206 with self.assertRaises(ConnectionClosedError):
207 self.connection.recv()
208
209 def test_recv_non_utf8_text(self):
210 """recv receives a non-UTF-8 text message."""
211 self.remote_connection.send(b"\x01\x02\xfe\xff", text=True)
212 with self.assertRaises(ConnectionClosedError) as raised:
213 self.connection.recv()
214 self.assertEqual(raised.exception.sent.code, CloseCode.INVALID_DATA)
215
216 def test_recv_during_recv(self):
217 """recv raises ConcurrencyError when called concurrently."""
218 with self.run_in_thread(self.connection.recv):
219 try:
220 with self.assertRaises(ConcurrencyError) as raised:
221 self.connection.recv()
222 finally:
223 self.remote_connection.send("")
224 self.assertEqual(
225 str(raised.exception),
226 "cannot call recv while another thread "
227 "is already running recv or recv_streaming",
228 )
229
230 def test_recv_during_recv_streaming(self):
231 """recv raises ConcurrencyError when called concurrently with recv_streaming."""
232 with self.run_in_thread(lambda: list(self.connection.recv_streaming())):
233 try:
234 with self.assertRaises(ConcurrencyError) as raised:
235 self.connection.recv()
236 finally:
237 self.remote_connection.send("")
238 self.assertEqual(
239 str(raised.exception),
240 "cannot call recv while another thread "
241 "is already running recv or recv_streaming",
242 )
243
244 # Test recv_streaming.
245
246 def test_recv_streaming_text(self):
247 """recv_streaming receives a text message."""
248 self.remote_connection.send("😀")
249 self.assertEqual(
250 list(self.connection.recv_streaming()),
251 ["😀"],
252 )
253
254 def test_recv_streaming_binary(self):
255 """recv_streaming receives a binary message."""
256 self.remote_connection.send(b"\x01\x02\xfe\xff")
257 self.assertEqual(
258 list(self.connection.recv_streaming()),
259 [b"\x01\x02\xfe\xff"],
260 )
261
262 def test_recv_streaming_text_as_bytes(self):
263 """recv_streaming receives a text message as bytes."""
264 self.remote_connection.send("😀")
265 self.assertEqual(
266 list(self.connection.recv_streaming(decode=False)),
267 ["😀".encode()],
268 )
269
270 def test_recv_streaming_binary_as_str(self):
271 """recv_streaming receives a binary message as a str."""
272 self.remote_connection.send("😀".encode())
273 self.assertEqual(
274 list(self.connection.recv_streaming(decode=True)),
275 ["😀"],
276 )
277
278 def test_recv_streaming_fragmented_text(self):
279 """recv_streaming receives a fragmented text message."""
280 self.remote_connection.send(["😀", "😀"])
281 # websockets sends an trailing empty fragment. That's an implementation detail.
282 self.assertEqual(
283 list(self.connection.recv_streaming()),
284 ["😀", "😀", ""],
285 )
286
287 def test_recv_streaming_fragmented_binary(self):
288 """recv_streaming receives a fragmented binary message."""
289 self.remote_connection.send([b"\x01\x02", b"\xfe\xff"])
290 # websockets sends an trailing empty fragment. That's an implementation detail.
291 self.assertEqual(
292 list(self.connection.recv_streaming()),
293 [b"\x01\x02", b"\xfe\xff", b""],
294 )
295
296 def test_recv_streaming_connection_closed_ok(self):
297 """recv_streaming raises ConnectionClosedOK after a normal closure."""
298 self.remote_connection.close()
299 with self.assertRaises(ConnectionClosedOK):
300 for _ in self.connection.recv_streaming():
301 self.fail("did not raise")
302
303 def test_recv_streaming_connection_closed_error(self):
304 """recv_streaming raises ConnectionClosedError after an error."""
305 self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
306 with self.assertRaises(ConnectionClosedError):
307 for _ in self.connection.recv_streaming():
308 self.fail("did not raise")
309
310 def test_recv_streaming_non_utf8_text(self):
311 """recv_streaming receives a non-UTF-8 text message."""
312 self.remote_connection.send(b"\x01\x02\xfe\xff", text=True)
313 with self.assertRaises(ConnectionClosedError) as raised:
314 list(self.connection.recv_streaming())
315 self.assertEqual(raised.exception.sent.code, CloseCode.INVALID_DATA)
316
317 def test_recv_streaming_during_recv(self):
318 """recv_streaming raises ConcurrencyError when called concurrently with recv."""
319 with self.run_in_thread(self.connection.recv):
320 try:
321 with self.assertRaises(ConcurrencyError) as raised:
322 for _ in self.connection.recv_streaming():
323 self.fail("did not raise")
324 finally:
325 self.remote_connection.send("")
326 self.assertEqual(
327 str(raised.exception),
328 "cannot call recv_streaming while another thread "
329 "is already running recv or recv_streaming",
330 )
331
332 def test_recv_streaming_during_recv_streaming(self):
333 """recv_streaming raises ConcurrencyError when called concurrently."""
334 with self.run_in_thread(lambda: list(self.connection.recv_streaming())):
335 try:
336 with self.assertRaises(ConcurrencyError) as raised:
337 for _ in self.connection.recv_streaming():
338 self.fail("did not raise")
339 finally:
340 self.remote_connection.send("")
341 self.assertEqual(
342 str(raised.exception),
343 "cannot call recv_streaming while another thread "
344 "is already running recv or recv_streaming",
345 )
346
347 # Test send.
348
349 def test_send_text(self):
350 """send sends a text message."""
351 self.connection.send("😀")
352 self.assertEqual(self.remote_connection.recv(), "😀")
353
354 def test_send_binary(self):
355 """send sends a binary message."""
356 self.connection.send(b"\x01\x02\xfe\xff")
357 self.assertEqual(self.remote_connection.recv(), b"\x01\x02\xfe\xff")
358
359 def test_send_binary_from_str(self):
360 """send sends a binary message from a str."""
361 self.connection.send("😀", text=False)
362 self.assertEqual(self.remote_connection.recv(), "😀".encode())
363
364 def test_send_text_from_bytes(self):
365 """send sends a text message from bytes."""
366 self.connection.send("😀".encode(), text=True)
367 self.assertEqual(self.remote_connection.recv(), "😀")
368
369 def test_send_fragmented_text(self):
370 """send sends a fragmented text message."""
371 self.connection.send(["😀", "😀"])
372 # websockets sends an trailing empty fragment. That's an implementation detail.
373 self.assertEqual(
374 list(self.remote_connection.recv_streaming()),
375 ["😀", "😀", ""],
376 )
377
378 def test_send_fragmented_binary(self):
379 """send sends a fragmented binary message."""
380 self.connection.send([b"\x01\x02", b"\xfe\xff"])
381 # websockets sends an trailing empty fragment. That's an implementation detail.
382 self.assertEqual(
383 list(self.remote_connection.recv_streaming()),
384 [b"\x01\x02", b"\xfe\xff", b""],
385 )
386
387 def test_send_fragmented_binary_from_str(self):
388 """send sends a fragmented binary message from a str."""
389 self.connection.send(["😀", "😀"], text=False)
390 # websockets sends an trailing empty fragment. That's an implementation detail.
391 self.assertEqual(
392 list(self.remote_connection.recv_streaming()),
393 ["😀".encode(), "😀".encode(), b""],
394 )
395
396 def test_send_fragmented_text_from_bytes(self):
397 """send sends a fragmented text message from bytes."""
398 self.connection.send(["😀".encode(), "😀".encode()], text=True)
399 # websockets sends an trailing empty fragment. That's an implementation detail.
400 self.assertEqual(
401 list(self.remote_connection.recv_streaming()),
402 ["😀", "😀", ""],
403 )
404
405 def test_send_connection_closed_ok(self):
406 """send raises ConnectionClosedOK after a normal closure."""
407 self.remote_connection.close()
408 with self.assertRaises(ConnectionClosedOK):
409 self.connection.send("😀")
410
411 def test_send_connection_closed_error(self):
412 """send raises ConnectionClosedError after an error."""
413 self.remote_connection.close(code=CloseCode.INTERNAL_ERROR)
414 with self.assertRaises(ConnectionClosedError):
415 self.connection.send("😀")
416
417 def test_send_during_send(self):
418 """send raises ConcurrencyError when called concurrently."""
419 with self.run_in_thread(self.remote_connection.recv):
420 send_gate = threading.Event()
421 exit_gate = threading.Event()
422
423 def fragments():
424 yield "😀"
425 send_gate.set()
426 exit_gate.wait()
427 yield "😀"
428
429 with self.run_in_thread(self.connection.send, args=(fragments(),)):
430 send_gate.wait()
431 # The check happens in four code paths, depending on the argument.
432 for message in [
433 "😀",
434 b"\x01\x02\xfe\xff",
435 ["😀", "😀"],
436 [b"\x01\x02", b"\xfe\xff"],
437 ]:
438 with self.subTest(message=message):
439 with self.assertRaises(ConcurrencyError) as raised:
440 self.connection.send(message)
441 self.assertEqual(
442 str(raised.exception),
443 "cannot call send while another thread "
444 "is already running send",
445 )
446
447 exit_gate.set()
448
449 def test_send_empty_iterable(self):
450 """send does nothing when called with an empty iterable."""
451 self.connection.send([])
452 self.connection.close()
453 self.assertEqual(list(self.remote_connection), [])
454
455 def test_send_mixed_iterable(self):
456 """send raises TypeError when called with an iterable of inconsistent types."""
457 with self.assertRaises(TypeError):
458 self.connection.send(["😀", b"\xfe\xff"])
459
460 def test_send_unsupported_iterable(self):
461 """send raises TypeError when called with an iterable of unsupported type."""
462 with self.assertRaises(TypeError):
463 self.connection.send([None])
464
465 def test_send_dict(self):
466 """send raises TypeError when called with a dict."""
467 with self.assertRaises(TypeError):
468 self.connection.send({"type": "object"})
469
470 def test_send_unsupported_type(self):
471 """send raises TypeError when called with an unsupported type."""
472 with self.assertRaises(TypeError):
473 self.connection.send(None)
474
475 # Test close.
476
477 def test_close(self):
478 """close sends a close frame."""
479 self.connection.close()
480 self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
481
482 def test_close_explicit_code_reason(self):
483 """close sends a close frame with a given code and reason."""
484 self.connection.close(CloseCode.GOING_AWAY, "bye!")
485 self.assertFrameSent(Frame(CLOSE, b"\x03\xe9bye!"))
486
487 def test_close_waits_for_close_frame(self):
488 """close waits for a close frame then EOF before returning."""
489 t0 = time.time()
490 with self.delay_frames_rcvd(MS):
491 self.connection.close()
492 t1 = time.time()
493
494 self.assertEqual(self.connection.state, CLOSED)
495 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
496 self.assertGreater(t1 - t0, MS)
497
498 with self.assertRaises(ConnectionClosedOK) as raised:
499 self.connection.recv()
500
501 exc = raised.exception
502 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
503 self.assertIsNone(exc.__cause__)
504
505 def test_close_waits_for_connection_closed(self):
506 """close waits for EOF before returning."""
507 if self.LOCAL is SERVER:
508 self.skipTest("only relevant on the client-side")
509
510 t0 = time.time()
511 with self.delay_eof_rcvd(MS):
512 self.connection.close()
513 t1 = time.time()
514
515 self.assertEqual(self.connection.state, CLOSED)
516 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
517 self.assertGreater(t1 - t0, MS)
518
519 with self.assertRaises(ConnectionClosedOK) as raised:
520 self.connection.recv()
521
522 exc = raised.exception
523 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
524 self.assertIsNone(exc.__cause__)
525
526 def test_close_timeout_waiting_for_close_frame(self):
527 """close times out if no close frame is received."""
528 t0 = time.time()
529 with self.drop_frames_rcvd(), self.drop_eof_rcvd():
530 self.connection.close()
531 t1 = time.time()
532
533 self.assertEqual(self.connection.state, CLOSED)
534 self.assertEqual(self.connection.close_code, CloseCode.ABNORMAL_CLOSURE)
535 self.assertGreater(t1 - t0, 2 * MS)
536
537 with self.assertRaises(ConnectionClosedError) as raised:
538 self.connection.recv()
539
540 exc = raised.exception
541 self.assertEqual(str(exc), "sent 1000 (OK); no close frame received")
542 self.assertIsInstance(exc.__cause__, TimeoutError)
543
544 def test_close_timeout_waiting_for_connection_closed(self):
545 """close times out if EOF isn't received."""
546 if self.LOCAL is SERVER:
547 self.skipTest("only relevant on the client-side")
548
549 t0 = time.time()
550 with self.drop_eof_rcvd():
551 self.connection.close()
552 t1 = time.time()
553
554 self.assertEqual(self.connection.state, CLOSED)
555 self.assertEqual(self.connection.close_code, CloseCode.NORMAL_CLOSURE)
556 self.assertGreater(t1 - t0, 2 * MS)
557
558 with self.assertRaises(ConnectionClosedOK) as raised:
559 self.connection.recv()
560
561 exc = raised.exception
562 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
563 self.assertIsInstance(exc.__cause__, TimeoutError)
564
565 def test_close_preserves_queued_messages(self):
566 """close preserves messages buffered in the assembler."""
567 self.remote_connection.send("😀")
568 self.connection.close()
569
570 self.assertEqual(self.connection.recv(), "😀")
571 with self.assertRaises(ConnectionClosedOK):
572 self.connection.recv()
573
574 def test_close_idempotency(self):
575 """close does nothing if the connection is already closed."""
576 self.connection.close()
577 self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
578
579 self.connection.close()
580 self.assertNoFrameSent()
581
582 def test_close_idempotency_race_condition(self):
583 """close waits if the connection is already closing."""
584 self.connection.close_timeout = 6 * MS
585
586 def closer():
587 with self.delay_frames_rcvd(4 * MS):
588 self.connection.close()
589
590 with self.run_in_thread(closer):
591 # run_in_thread() waits for MS, which lets closer() send a close frame.
592 self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
593
594 # Connection isn't closed yet.
595 with self.assertRaises(TimeoutError):
596 self.connection.recv(timeout=MS)
597
598 self.connection.close()
599 self.assertNoFrameSent()
600
601 # Connection is closed now.
602 with self.assertRaises(ConnectionClosedOK):
603 self.connection.recv(timeout=MS)
604
605 def test_close_during_recv(self):
606 """close aborts recv when called concurrently with recv."""
607
608 def closer():
609 # Wait 2 * MS because run_in_thread() waits for MS.
610 time.sleep(2 * MS)
611 self.connection.close()
612
613 with self.run_in_thread(closer):
614 with self.assertRaises(ConnectionClosedOK) as raised:
615 self.connection.recv()
616
617 exc = raised.exception
618 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
619 self.assertIsNone(exc.__cause__)
620
621 def test_close_during_recv_streaming(self):
622 """close aborts recv_streaming when called concurrently with recv_streaming."""
623
624 def closer():
625 # Wait 2 * MS because run_in_thread() waits for MS.
626 time.sleep(2 * MS)
627 self.connection.close()
628
629 with self.run_in_thread(closer):
630 with self.assertRaises(ConnectionClosedOK) as raised:
631 for _ in self.connection.recv_streaming():
632 self.fail("did not raise")
633
634 exc = raised.exception
635 self.assertEqual(str(exc), "sent 1000 (OK); then received 1000 (OK)")
636 self.assertIsNone(exc.__cause__)
637
638 def test_close_during_send(self):
639 """close fails the connection when called concurrently with send."""
640 close_gate = threading.Event()
641 exit_gate = threading.Event()
642
643 def closer():
644 close_gate.wait()
645 self.connection.close()
646 exit_gate.set()
647
648 def fragments():
649 yield "⏳"
650 close_gate.set()
651 exit_gate.wait()
652 yield "⌛️"
653
654 with self.run_in_thread(closer):
655 iterator = fragments()
656 with contextlib.closing(iterator):
657 with self.assertRaises(ConnectionClosedError) as raised:
658 self.connection.send(iterator)
659
660 exc = raised.exception
661 self.assertEqual(
662 str(exc),
663 "sent 1011 (internal error) close during fragmented message; "
664 "no close frame received",
665 )
666 self.assertIsNone(exc.__cause__)
667
668 # Test ping.
669
670 @patch("random.getrandbits")
671 def test_ping(self, getrandbits):
672 """ping sends a ping frame with a random payload."""
673 getrandbits.side_effect = itertools.count(1918987876)
674 self.connection.ping()
675 getrandbits.assert_called_once_with(32)
676 self.assertFrameSent(Frame(PING, b"rand"))
677
678 def test_ping_explicit_text(self):
679 """ping sends a ping frame with a payload provided as text."""
680 self.connection.ping("ping")
681 self.assertFrameSent(Frame(PING, b"ping"))
682
683 def test_ping_explicit_binary(self):
684 """ping sends a ping frame with a payload provided as binary."""
685 self.connection.ping(b"ping")
686 self.assertFrameSent(Frame(PING, b"ping"))
687
688 def test_acknowledge_ping(self):
689 """ping is acknowledged by a pong with the same payload."""
690 with self.drop_frames_rcvd(): # drop automatic response to ping
691 pong_received = self.connection.ping("this")
692 self.remote_connection.pong("this")
693 self.assertTrue(pong_received.wait(MS))
694
695 def test_acknowledge_ping_non_matching_pong(self):
696 """ping isn't acknowledged by a pong with a different payload."""
697 with self.drop_frames_rcvd(): # drop automatic response to ping
698 pong_received = self.connection.ping("this")
699 self.remote_connection.pong("that")
700 self.assertFalse(pong_received.wait(MS))
701
702 def test_acknowledge_previous_ping(self):
703 """ping is acknowledged by a pong for as a later ping."""
704 with self.drop_frames_rcvd(): # drop automatic response to ping
705 pong_received = self.connection.ping("this")
706 self.connection.ping("that")
707 self.remote_connection.pong("that")
708 self.assertTrue(pong_received.wait(MS))
709
710 def test_acknowledge_ping_on_close(self):
711 """ping with ack_on_close is acknowledged when the connection is closed."""
712 with self.drop_frames_rcvd(): # drop automatic response to ping
713 pong_received_aoc = self.connection.ping("this", ack_on_close=True)
714 pong_received = self.connection.ping("that")
715 self.connection.close()
716 self.assertTrue(pong_received_aoc.wait(MS))
717 self.assertFalse(pong_received.wait(MS))
718
719 def test_ping_duplicate_payload(self):
720 """ping rejects the same payload until receiving the pong."""
721 with self.drop_frames_rcvd(): # drop automatic response to ping
722 pong_received = self.connection.ping("idem")
723
724 with self.assertRaises(ConcurrencyError) as raised:
725 self.connection.ping("idem")
726 self.assertEqual(
727 str(raised.exception),
728 "already waiting for a pong with the same data",
729 )
730
731 self.remote_connection.pong("idem")
732 self.assertTrue(pong_received.wait(MS))
733
734 self.connection.ping("idem") # doesn't raise an exception
735
736 def test_ping_unsupported_type(self):
737 """ping raises TypeError when called with an unsupported type."""
738 with self.assertRaises(TypeError):
739 self.connection.ping([])
740
741 # Test pong.
742
743 def test_pong(self):
744 """pong sends a pong frame."""
745 self.connection.pong()
746 self.assertFrameSent(Frame(PONG, b""))
747
748 def test_pong_explicit_text(self):
749 """pong sends a pong frame with a payload provided as text."""
750 self.connection.pong("pong")
751 self.assertFrameSent(Frame(PONG, b"pong"))
752
753 def test_pong_explicit_binary(self):
754 """pong sends a pong frame with a payload provided as binary."""
755 self.connection.pong(b"pong")
756 self.assertFrameSent(Frame(PONG, b"pong"))
757
758 def test_pong_unsupported_type(self):
759 """pong raises TypeError when called with an unsupported type."""
760 with self.assertRaises(TypeError):
761 self.connection.pong([])
762
763 # Test keepalive.
764
765 @patch("random.getrandbits")
766 def test_keepalive(self, getrandbits):
767 """keepalive sends pings at ping_interval and measures latency."""
768 getrandbits.side_effect = itertools.count(1918987876)
769 self.connection.ping_interval = 3 * MS
770 self.connection.start_keepalive()
771 self.assertIsNotNone(self.connection.keepalive_thread)
772 self.assertEqual(self.connection.latency, 0)
773 # 3 ms: keepalive() sends a ping frame.
774 # 3.x ms: a pong frame is received.
775 time.sleep(4 * MS)
776 # 4 ms: check that the ping frame was sent.
777 self.assertFrameSent(Frame(PING, b"rand"))
778 self.assertGreater(self.connection.latency, 0)
779 self.assertLess(self.connection.latency, MS)
780
781 def test_disable_keepalive(self):
782 """keepalive is disabled when ping_interval is None."""
783 self.connection.ping_interval = None
784 self.connection.start_keepalive()
785 self.assertIsNone(self.connection.keepalive_thread)
786
787 @patch("random.getrandbits")
788 def test_keepalive_times_out(self, getrandbits):
789 """keepalive closes the connection if ping_timeout elapses."""
790 getrandbits.side_effect = itertools.count(1918987876)
791 self.connection.ping_interval = 4 * MS
792 self.connection.ping_timeout = 2 * MS
793 with self.drop_frames_rcvd():
794 self.connection.start_keepalive()
795 # 4 ms: keepalive() sends a ping frame.
796 # 4.x ms: a pong frame is dropped.
797 time.sleep(4 * MS)
798 # Exiting the context manager sleeps for 1 ms.
799 # 6 ms: no pong frame is received; the connection is closed.
800 time.sleep(3 * MS)
801 # 8 ms: check that the connection is closed.
802 self.assertEqual(self.connection.state, CLOSED)
803
804 @patch("random.getrandbits")
805 def test_keepalive_ignores_timeout(self, getrandbits):
806 """keepalive ignores timeouts if ping_timeout isn't set."""
807 getrandbits.side_effect = itertools.count(1918987876)
808 self.connection.ping_interval = 4 * MS
809 self.connection.ping_timeout = None
810 with self.drop_frames_rcvd():
811 self.connection.start_keepalive()
812 # 4 ms: keepalive() sends a ping frame.
813 # 4.x ms: a pong frame is dropped.
814 time.sleep(4 * MS)
815 # Exiting the context manager sleeps for 1 ms.
816 # 6 ms: no pong frame is received; the connection remains open.
817 time.sleep(3 * MS)
818 # 8 ms: check that the connection is still open.
819 self.assertEqual(self.connection.state, OPEN)
820
821 def test_keepalive_terminates_while_sleeping(self):
822 """keepalive task terminates while waiting to send a ping."""
823 self.connection.ping_interval = 3 * MS
824 self.connection.start_keepalive()
825 self.connection.keepalive_thread.join(MS)
826 self.assertTrue(self.connection.keepalive_thread.is_alive())
827 self.connection.close()
828 self.connection.keepalive_thread.join(MS)
829 self.assertFalse(self.connection.keepalive_thread.is_alive())
830
831 def test_keepalive_terminates_when_sending_ping_fails(self):
832 """keepalive task terminates when sending a ping fails."""
833 self.connection.ping_interval = MS
834 self.connection.start_keepalive()
835 self.assertTrue(self.connection.keepalive_thread.is_alive())
836 with self.drop_eof_rcvd(), self.drop_frames_rcvd():
837 self.connection.close()
838 # Exiting the context managers sleeps for 2 ms.
839 self.assertFalse(self.connection.keepalive_thread.is_alive())
840
841 def test_keepalive_terminates_while_waiting_for_pong(self):
842 """keepalive task terminates while waiting to receive a pong."""
843 self.connection.ping_interval = MS
844 self.connection.ping_timeout = 4 * MS
845 with self.drop_frames_rcvd():
846 self.connection.start_keepalive()
847 # 1 ms: keepalive() sends a ping frame.
848 # 1.x ms: a pong frame is dropped.
849 time.sleep(MS)
850 # Exiting the context manager sleeps for 1 ms.
851 # 2 ms: close the connection before ping_timeout elapses.
852 self.connection.close()
853 self.connection.keepalive_thread.join(MS)
854 self.assertFalse(self.connection.keepalive_thread.is_alive())
855
856 def test_keepalive_reports_errors(self):
857 """keepalive reports unexpected errors in logs."""
858 self.connection.ping_interval = 2 * MS
859 self.connection.start_keepalive()
860 # Inject a fault when waiting to receive a pong.
861 with self.assertLogs("websockets", logging.ERROR) as logs:
862 with patch("threading.Event.wait", side_effect=Exception("BOOM")):
863 # 2 ms: keepalive() sends a ping frame.
864 # 2.x ms: a pong frame is dropped.
865 time.sleep(3 * MS)
866 self.assertExceptionLogged(logs, "keepalive ping failed", "BOOM")
867
868 # Test parameters.
869
870 def test_close_timeout(self):
871 """close_timeout parameter configures close timeout."""
872 connection = Connection(
873 Mock(spec=socket.socket),
874 Protocol(self.LOCAL),
875 close_timeout=42 * MS,
876 )
877 self.assertEqual(connection.close_timeout, 42 * MS)
878
879 def test_max_queue(self):
880 """max_queue configures high-water mark of frames buffer."""
881 connection = Connection(
882 Mock(spec=socket.socket),
883 Protocol(self.LOCAL),
884 max_queue=4,
885 )
886 self.assertEqual(connection.recv_messages.high, 4)
887
888 def test_max_queue_none(self):
889 """max_queue disables high-water mark of frames buffer."""
890 connection = Connection(
891 Mock(spec=socket.socket),
892 Protocol(self.LOCAL),
893 max_queue=None,
894 )
895 self.assertEqual(connection.recv_messages.high, None)
896 self.assertEqual(connection.recv_messages.high, None)
897
898 def test_max_queue_tuple(self):
899 """max_queue configures high-water and low-water marks of frames buffer."""
900 connection = Connection(
901 Mock(spec=socket.socket),
902 Protocol(self.LOCAL),
903 max_queue=(4, 2),
904 )
905 self.assertEqual(connection.recv_messages.high, 4)
906 self.assertEqual(connection.recv_messages.low, 2)
907
908 # Test attributes.
909
910 def test_id(self):
911 """Connection has an id attribute."""
912 self.assertIsInstance(self.connection.id, uuid.UUID)
913
914 def test_logger(self):
915 """Connection has a logger attribute."""
916 self.assertIsInstance(self.connection.logger, logging.LoggerAdapter)
917
918 @patch("socket.socket.getsockname")
919 def test_local_address(self, getsockname):
920 """Connection has a local_address attribute."""
921 getsockname.return_value = ("sock", 1234)
922 self.assertEqual(self.connection.local_address, ("sock", 1234))
923 getsockname.assert_called_with()
924
925 @patch("socket.socket.getpeername")
926 def test_remote_address(self, getpeername):
927 """Connection has a remote_address attribute."""
928 getpeername.return_value = ("peer", 1234)
929 self.assertEqual(self.connection.remote_address, ("peer", 1234))
930 getpeername.assert_called_with()
931
932 def test_state(self):
933 """Connection has a state attribute."""
934 self.assertIs(self.connection.state, OPEN)
935
936 def test_request(self):
937 """Connection has a request attribute."""
938 self.assertIsNone(self.connection.request)
939
940 def test_response(self):
941 """Connection has a response attribute."""
942 self.assertIsNone(self.connection.response)
943
944 def test_subprotocol(self):
945 """Connection has a subprotocol attribute."""
946 self.assertIsNone(self.connection.subprotocol)
947
948 def test_close_code(self):
949 """Connection has a close_code attribute."""
950 self.assertIsNone(self.connection.close_code)
951
952 def test_close_reason(self):
953 """Connection has a close_reason attribute."""
954 self.assertIsNone(self.connection.close_reason)
955
956 # Test backpressure.
957
958 def test_backpressure(self):
959 """Connection stops reading from the network when the buffer fills up."""
960 self.connection.recv_messages.high = 1
961 self.connection.recv_messages.low = 0
962 frames_buffer = self.connection.recv_messages.frames
963
964 self.remote_connection.send("A")
965 self.remote_connection.send("B")
966
967 # Assembler buffer is above the high water mark. Backpressure kicks in.
968 self.wait_for_remote_side()
969 self.assertTrue(self.connection.recv_flow_control.locked())
970 self.assertEqual(frames_buffer.qsize(), 2)
971
972 self.remote_connection.send("C")
973
974 # A third frame is sent by the peer but the connection doesn't read it.
975 self.wait_for_remote_side()
976 self.assertEqual(frames_buffer.qsize(), 2)
977
978 self.assertEqual(self.connection.recv(), "A")
979 self.assertEqual(self.connection.recv(), "B")
980
981 # Draining the assembler buffer below the low water mark resumes reading.
982 self.wait_for_remote_side()
983 self.assertFalse(self.connection.recv_flow_control.locked())
984 self.assertEqual(frames_buffer.qsize(), 1)
985
986 self.assertEqual(self.connection.recv(), "C")
987
988 # Test reporting of network errors.
989
990 def test_writing_in_recv_events_fails(self):
991 """Error when responding to incoming frames is correctly reported."""
992 # Inject a fault by making sendall() fail. Use a mock rather than a real
993 # shutdown(SHUT_WR) so the remote side doesn't terminate the connection.
994 self.connection.socket = Mock(wraps=self.connection.socket)
995 self.connection.socket.sendall.side_effect = BrokenPipeError
996 # Receive a ping. Responding with a pong will fail.
997 self.remote_connection.ping()
998 with self.assertRaises(ConnectionClosedError) as raised:
999 self.connection.recv()
1000 self.assertIsInstance(raised.exception.__cause__, BrokenPipeError)
1001
1002 def test_writing_in_send_context_fails(self):
1003 """Error when sending outgoing frame is correctly reported."""
1004 # Inject a fault by making sendall() fail. Use a mock rather than a real
1005 # shutdown(SHUT_WR) so the remote side doesn't terminate the connection.
1006 self.connection.socket = Mock(wraps=self.connection.socket)
1007 self.connection.socket.sendall.side_effect = BrokenPipeError
1008 # Sending a pong will fail.
1009 with self.assertRaises(ConnectionClosedError) as raised:
1010 self.connection.pong()
1011 self.assertIsInstance(raised.exception.__cause__, BrokenPipeError)
1012
1013 # Test safety nets — catching all exceptions in case of bugs.
1014
1015 @patch("websockets.protocol.Protocol.events_received", side_effect=AssertionError)
1016 def test_unexpected_failure_in_recv_events(self, events_received):
1017 """Unexpected internal error in recv_events() is correctly reported."""
1018 self.remote_connection.send("😀")
1019 # Reading the message will trigger the injected fault.
1020 with self.assertRaises(ConnectionClosedError) as raised:
1021 self.connection.recv()
1022 self.assertIsInstance(raised.exception.__cause__, AssertionError)
1023
1024 @patch("websockets.protocol.Protocol.send_text", side_effect=AssertionError)
1025 def test_unexpected_failure_in_send_context(self, send_text):
1026 """Unexpected internal error in send_context() is correctly reported."""
1027 # Sending a message will trigger the injected fault.
1028 with self.assertRaises(ConnectionClosedError) as raised:
1029 self.connection.send("😀")
1030 self.assertIsInstance(raised.exception.__cause__, AssertionError)
1031
1032 # Test recv_events().
1033
1034 def test_close_expected_during_connecting(self):
1035 """recv_events() terminates without waiting for close_timeout."""
1036 # See https://github.com/python-websockets/websockets/issues/1596.
1037 socket_, remote_socket = socket.socketpair()
1038 protocol = Protocol(self.LOCAL, state=CONNECTING)
1039 # Simulate ClientProtocol / ServerProtocol deciding that the TCP
1040 # connection must close because the opening handshake failed.
1041 protocol.send_eof()
1042 connection = Connection(socket_, protocol, close_timeout=5 * MS)
1043 try:
1044 t0 = time.time()
1045 remote_socket.sendall(b"\x00")
1046 connection.recv_events_thread.join(3 * MS)
1047 t1 = time.time()
1048
1049 self.assertFalse(connection.recv_events_thread.is_alive())
1050 self.assertLess(t1 - t0, 3 * MS)
1051 finally:
1052 remote_socket.close()
1053 connection.close_socket()
1054 connection.recv_events_thread.join()
1055
1056 # Test garbage collection.
1057
1058 @unittest.skipUnless(
1059 sys.implementation.name == "cpython",
1060 "this test checks the behavior of CPython's garbage collector",
1061 )
1062 def test_no_reference_cycle(self):
1063 """Connection is garbage collected immediately after deletion."""
1064 self.connection.start_keepalive()
1065 time.sleep(0) # let the keepalive thread start
1066 self.connection.close()
1067 time.sleep(MS) # let the recv_events thread terminate
1068
1069 connection_ref = weakref.ref(self.connection)
1070 del self.connection
1071 self.assertIsNone(connection_ref(), "still alive after deletion")
1072
1073 # Test broadcast.
1074
1075 def test_broadcast_text(self):
1076 """broadcast broadcasts a text message."""
1077 broadcast([self.connection], "😀")
1078 self.assertFrameSent(Frame(TEXT, "😀".encode()))
1079
1080 def test_broadcast_text_reports_no_errors(self):
1081 """broadcast broadcasts a text message without raising exceptions."""
1082 broadcast([self.connection], "😀", raise_exceptions=True)
1083 self.assertFrameSent(Frame(TEXT, "😀".encode()))
1084
1085 def test_broadcast_binary(self):
1086 """broadcast broadcasts a binary message."""
1087 broadcast([self.connection], b"\x01\x02\xfe\xff")
1088 self.assertFrameSent(Frame(BINARY, b"\x01\x02\xfe\xff"))
1089
1090 def test_broadcast_binary_reports_no_errors(self):
1091 """broadcast broadcasts a binary message without raising exceptions."""
1092 broadcast([self.connection], b"\x01\x02\xfe\xff", raise_exceptions=True)
1093 self.assertFrameSent(Frame(BINARY, b"\x01\x02\xfe\xff"))
1094
1095 def test_broadcast_text_from_bytes(self):
1096 """broadcast broadcasts a text message from bytes."""
1097 broadcast([self.connection], "😀".encode(), text=True)
1098 self.assertFrameSent(Frame(TEXT, "😀".encode()))
1099
1100 def test_broadcast_binary_from_str(self):
1101 """broadcast broadcasts a binary message from a str."""
1102 broadcast([self.connection], "😀", text=False)
1103 self.assertFrameSent(Frame(BINARY, "😀".encode()))
1104
1105 def test_broadcast_no_clients(self):
1106 """broadcast does nothing when called with an empty list of clients."""
1107 broadcast([], "😀")
1108 self.assertNoFrameSent()
1109
1110 def test_broadcast_two_clients(self):
1111 """broadcast broadcasts a message to several clients."""
1112 broadcast([self.connection, self.connection], "😀")
1113 self.assertFramesSent(
1114 [
1115 Frame(TEXT, "😀".encode()),
1116 Frame(TEXT, "😀".encode()),
1117 ]
1118 )
1119
1120 def test_broadcast_skips_closed_connection(self):
1121 """broadcast ignores closed connections."""
1122 self.connection.close()
1123 self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
1124
1125 with self.assertNoLogs("websockets", logging.WARNING):
1126 broadcast([self.connection], "😀")
1127 self.assertNoFrameSent()
1128
1129 def test_broadcast_skips_closing_connection(self):
1130 """broadcast ignores closing connections."""
1131
1132 def closer():
1133 with self.delay_frames_rcvd(MS):
1134 self.connection.close()
1135
1136 with self.run_in_thread(closer):
1137 self.assertFrameSent(Frame(CLOSE, b"\x03\xe8"))
1138
1139 with self.assertNoLogs("websockets", logging.WARNING):
1140 broadcast([self.connection], "😀")
1141 self.assertNoFrameSent()
1142
1143 def test_broadcast_skips_connection_with_send_blocked(self):
1144 """broadcast logs a warning when a connection is blocked in send."""
1145 gate = threading.Event()
1146
1147 def fragments():
1148 yield "⏳"
1149 gate.wait()
1150
1151 with self.run_in_thread(self.connection.send, args=(fragments(),)):
1152 self.assertFrameSent(Frame(TEXT, "⏳".encode(), fin=False))
1153
1154 with self.assertLogs("websockets", logging.WARNING) as logs:
1155 broadcast([self.connection], "😀")
1156
1157 self.assertEqual(
1158 [record.getMessage() for record in logs.records],
1159 ["skipped broadcast: sending a fragmented message"],
1160 )
1161
1162 gate.set()
1163
1164 def test_broadcast_reports_connection_with_send_blocked(self):
1165 """broadcast raises exceptions for connections blocked in send."""
1166 gate = threading.Event()
1167
1168 def fragments():
1169 yield "⏳"
1170 gate.wait()
1171
1172 with self.run_in_thread(self.connection.send, args=(fragments(),)):
1173 self.assertFrameSent(Frame(TEXT, "⏳".encode(), fin=False))
1174
1175 with self.assertRaises(ExceptionGroup) as raised:
1176 broadcast([self.connection], "😀", raise_exceptions=True)
1177
1178 self.assertEqual(
1179 str(raised.exception), "skipped broadcast (1 sub-exception)"
1180 )
1181 exc = raised.exception.exceptions[0]
1182 self.assertEqual(str(exc), "sending a fragmented message")
1183 self.assertIsInstance(exc, ConcurrencyError)
1184
1185 gate.set()
1186
1187 def test_broadcast_skips_connection_failing_to_send(self):
1188 """broadcast logs a warning when a connection fails to send."""
1189 # Inject a fault by making sendall() fail. Use a mock rather than a real
1190 # shutdown(SHUT_WR) so the remote side doesn't terminate the connection.
1191 self.connection.socket = Mock(wraps=self.connection.socket)
1192 self.connection.socket.sendall.side_effect = BrokenPipeError(32, "Broken pipe")
1193
1194 with self.assertLogs("websockets", logging.WARNING) as logs:
1195 broadcast([self.connection], "😀")
1196
1197 self.assertEqual(
1198 [record.getMessage() for record in logs.records],
1199 [
1200 "skipped broadcast: failed to write message: "
1201 "BrokenPipeError: [Errno 32] Broken pipe"
1202 ],
1203 )
1204
1205 def test_broadcast_reports_connection_failing_to_send(self):
1206 """broadcast raises exceptions for connections failing to send."""
1207 # Inject a fault by making sendall() fail. Use a mock rather than a real
1208 # shutdown(SHUT_WR) so the remote side doesn't terminate the connection.
1209 self.connection.socket = Mock(wraps=self.connection.socket)
1210 self.connection.socket.sendall.side_effect = BrokenPipeError(32, "Broken pipe")
1211
1212 with self.assertRaises(ExceptionGroup) as raised:
1213 broadcast([self.connection], "😀", raise_exceptions=True)
1214
1215 self.assertEqual(str(raised.exception), "skipped broadcast (1 sub-exception)")
1216 exc = raised.exception.exceptions[0]
1217 self.assertEqual(str(exc), "failed to write message")
1218 self.assertIsInstance(exc, RuntimeError)
1219 cause = exc.__cause__
1220 self.assertEqual(str(cause), "[Errno 32] Broken pipe")
1221 self.assertIsInstance(cause, BrokenPipeError)
1222
1223 def test_broadcast_type_error(self):
1224 """broadcast raises TypeError when called with an unsupported type."""
1225 with self.assertRaises(TypeError):
1226 broadcast([self.connection], ["⏳", "⌛️"])
1227
1228
1229 class ServerConnectionTests(ClientConnectionTests):
1230 LOCAL = SERVER
1231 REMOTE = CLIENT