Debian Codegraph @

tests/legacy/test_protocol.py

raw
1 import asyncio
2 import contextlib
3 import logging
4 import unittest
5 import unittest.mock
6 import warnings
7
8 from websockets.exceptions import ConnectionClosed, InvalidState
9 from websockets.frames import (
10 BINARY as OP_BINARY,
11 CLOSE as OP_CLOSE,
12 CONT as OP_CONT,
13 PING as OP_PING,
14 PONG as OP_PONG,
15 TEXT as OP_TEXT,
16 Close,
17 CloseCode,
18 )
19 from websockets.legacy.framing import Frame
20 from websockets.legacy.protocol import WebSocketCommonProtocol, broadcast
21 from websockets.protocol import State
22
23 from ..utils import MS
24 from .utils import AsyncioTestCase
25
26
27 async def async_iterable(iterable):
28 for item in iterable:
29 yield item
30
31
32 class TransportMock(unittest.mock.Mock):
33 """
34 Transport mock to control the protocol's inputs and outputs in tests.
35
36 It calls the protocol's connection_made and connection_lost methods like
37 actual transports.
38
39 It also calls the protocol's connection_open method to bypass the
40 WebSocket handshake.
41
42 To simulate incoming data, tests call the protocol's data_received and
43 eof_received methods directly.
44
45 They could also pause_writing and resume_writing to test flow control.
46
47 """
48
49 # This should happen in __init__ but overriding Mock.__init__ is hard.
50 def setup_mock(self, loop, protocol):
51 self.loop = loop
52 self.protocol = protocol
53 self._eof = False
54 self._closing = False
55 # Simulate a successful TCP handshake.
56 self.protocol.connection_made(self)
57 # Simulate a successful WebSocket handshake.
58 self.protocol.connection_open()
59
60 def can_write_eof(self):
61 return True
62
63 def write_eof(self):
64 # When the protocol half-closes the TCP connection, it expects the
65 # other end to close it. Simulate that.
66 if not self._eof:
67 self.loop.call_soon(self.close)
68 self._eof = True
69
70 def close(self):
71 # Simulate how actual transports drop the connection.
72 if not self._closing:
73 self.loop.call_soon(self.protocol.connection_lost, None)
74 self._closing = True
75
76 def abort(self):
77 # Change this to an `if` if tests call abort() multiple times.
78 assert self.protocol.state is not State.CLOSED
79 self.loop.call_soon(self.protocol.connection_lost, None)
80
81
82 class CommonTests:
83 """
84 Mixin that defines most tests but doesn't inherit unittest.TestCase.
85
86 Tests are run by the ServerTests and ClientTests subclasses.
87
88 """
89
90 def setUp(self):
91 super().setUp()
92
93 # This logic is encapsulated in a coroutine to prevent it from executing
94 # before the event loop is running which causes asyncio.get_event_loop()
95 # to raise a DeprecationWarning on Python ≥ 3.10.
96
97 async def create_protocol():
98 # Disable pings to make it easier to test what frames are sent exactly.
99 return WebSocketCommonProtocol(ping_interval=None)
100
101 self.protocol = self.loop.run_until_complete(create_protocol())
102 self.transport = TransportMock()
103 self.transport.setup_mock(self.loop, self.protocol)
104
105 def tearDown(self):
106 self.transport.close()
107 self.loop.run_until_complete(self.protocol.close())
108 super().tearDown()
109
110 # Utilities for writing tests.
111
112 def make_drain_slow(self, delay=MS):
113 # Process connection_made in order to initialize self.protocol.transport.
114 self.run_loop_once()
115
116 original_drain = self.protocol._drain
117
118 async def delayed_drain():
119 await asyncio.sleep(delay)
120 await original_drain()
121
122 self.protocol._drain = delayed_drain
123
124 close_frame = Frame(
125 True,
126 OP_CLOSE,
127 Close(CloseCode.NORMAL_CLOSURE, "close").serialize(),
128 )
129 local_close = Frame(
130 True,
131 OP_CLOSE,
132 Close(CloseCode.NORMAL_CLOSURE, "local").serialize(),
133 )
134 remote_close = Frame(
135 True,
136 OP_CLOSE,
137 Close(CloseCode.NORMAL_CLOSURE, "remote").serialize(),
138 )
139
140 def receive_frame(self, frame):
141 """
142 Make the protocol receive a frame.
143
144 """
145 write = self.protocol.data_received
146 mask = not self.protocol.is_client
147 frame.write(write, mask=mask)
148
149 def receive_eof(self):
150 """
151 Make the protocol receive the end of the data stream.
152
153 Since ``WebSocketCommonProtocol.eof_received`` returns ``None``, an
154 actual transport would close itself after calling it. This function
155 emulates that behavior.
156
157 """
158 self.protocol.eof_received()
159 self.loop.call_soon(self.transport.close)
160
161 def receive_eof_if_client(self):
162 """
163 Like receive_eof, but only if this is the client side.
164
165 Since the server is supposed to initiate the termination of the TCP
166 connection, this method helps making tests work for both sides.
167
168 """
169 if self.protocol.is_client:
170 self.receive_eof()
171
172 def close_connection(self, code=CloseCode.NORMAL_CLOSURE, reason="close"):
173 """
174 Execute a closing handshake.
175
176 This puts the connection in the CLOSED state.
177
178 """
179 close_frame_data = Close(code, reason).serialize()
180 # Prepare the response to the closing handshake from the remote side.
181 self.receive_frame(Frame(True, OP_CLOSE, close_frame_data))
182 self.receive_eof_if_client()
183 # Trigger the closing handshake from the local side and complete it.
184 self.loop.run_until_complete(self.protocol.close(code, reason))
185 # Empty the outgoing data stream so we can make assertions later on.
186 self.assertOneFrameSent(True, OP_CLOSE, close_frame_data)
187
188 assert self.protocol.state is State.CLOSED
189
190 def half_close_connection_local(
191 self,
192 code=CloseCode.NORMAL_CLOSURE,
193 reason="close",
194 ):
195 """
196 Start a closing handshake but do not complete it.
197
198 The main difference with `close_connection` is that the connection is
199 left in the CLOSING state until the event loop runs again.
200
201 The current implementation returns a task that must be awaited or
202 canceled, else asyncio complains about destroying a pending task.
203
204 """
205 close_frame_data = Close(code, reason).serialize()
206 # Trigger the closing handshake from the local endpoint.
207 close_task = self.loop.create_task(self.protocol.close(code, reason))
208 self.run_loop_once() # write_frame executes
209 # Empty the outgoing data stream so we can make assertions later on.
210 self.assertOneFrameSent(True, OP_CLOSE, close_frame_data)
211
212 assert self.protocol.state is State.CLOSING
213
214 # Complete the closing sequence at 1ms intervals so the test can run
215 # at each point even it goes back to the event loop several times.
216 self.loop.call_later(
217 MS, self.receive_frame, Frame(True, OP_CLOSE, close_frame_data)
218 )
219 self.loop.call_later(2 * MS, self.receive_eof_if_client)
220
221 # This task must be awaited or canceled by the caller.
222 return close_task
223
224 def half_close_connection_remote(
225 self,
226 code=CloseCode.NORMAL_CLOSURE,
227 reason="close",
228 ):
229 """
230 Receive a closing handshake but do not complete it.
231
232 The main difference with `close_connection` is that the connection is
233 left in the CLOSING state until the event loop runs again.
234
235 """
236 # On the server side, websockets completes the closing handshake and
237 # closes the TCP connection immediately. Yield to the event loop after
238 # sending the close frame to run the test while the connection is in
239 # the CLOSING state.
240 if not self.protocol.is_client:
241 self.make_drain_slow()
242
243 close_frame_data = Close(code, reason).serialize()
244 # Trigger the closing handshake from the remote endpoint.
245 self.receive_frame(Frame(True, OP_CLOSE, close_frame_data))
246 self.run_loop_once() # read_frame executes
247 # Empty the outgoing data stream so we can make assertions later on.
248 self.assertOneFrameSent(True, OP_CLOSE, close_frame_data)
249
250 assert self.protocol.state is State.CLOSING
251
252 # Complete the closing sequence at 1ms intervals so the test can run
253 # at each point even it goes back to the event loop several times.
254 self.loop.call_later(2 * MS, self.receive_eof_if_client)
255
256 def process_invalid_frames(self):
257 """
258 Make the protocol fail quickly after simulating invalid data.
259
260 To achieve this, this function triggers the protocol's eof_received,
261 which interrupts pending reads waiting for more data.
262
263 """
264 self.run_loop_once()
265 self.receive_eof()
266 self.loop.run_until_complete(self.protocol.close_connection_task)
267
268 def sent_frames(self):
269 """
270 Read all frames sent to the transport.
271
272 """
273 stream = asyncio.StreamReader(loop=self.loop)
274
275 for (data,), kw in self.transport.write.call_args_list:
276 stream.feed_data(data)
277 self.transport.write.call_args_list = []
278 stream.feed_eof()
279
280 frames = []
281 while not stream.at_eof():
282 frames.append(
283 self.loop.run_until_complete(
284 Frame.read(stream.readexactly, mask=self.protocol.is_client)
285 )
286 )
287 return frames
288
289 def last_sent_frame(self):
290 """
291 Read the last frame sent to the transport.
292
293 This method assumes that at most one frame was sent. It raises an
294 AssertionError otherwise.
295
296 """
297 frames = self.sent_frames()
298 if frames:
299 assert len(frames) == 1
300 return frames[0]
301
302 def assertFramesSent(self, *frames):
303 self.assertEqual(self.sent_frames(), [Frame(*args) for args in frames])
304
305 def assertOneFrameSent(self, *args):
306 self.assertEqual(self.last_sent_frame(), Frame(*args))
307
308 def assertNoFrameSent(self):
309 self.assertIsNone(self.last_sent_frame())
310
311 def assertConnectionClosed(self, code, message):
312 # The following line guarantees that connection_lost was called.
313 self.assertEqual(self.protocol.state, State.CLOSED)
314 # A close frame was received.
315 self.assertEqual(self.protocol.close_code, code)
316 self.assertEqual(self.protocol.close_reason, message)
317
318 def assertConnectionFailed(self, code, message):
319 # The following line guarantees that connection_lost was called.
320 self.assertEqual(self.protocol.state, State.CLOSED)
321 # No close frame was received.
322 self.assertEqual(self.protocol.close_code, CloseCode.ABNORMAL_CLOSURE)
323 self.assertEqual(self.protocol.close_reason, "")
324 # A close frame was sent — unless the connection was already lost.
325 if code == CloseCode.ABNORMAL_CLOSURE:
326 self.assertNoFrameSent()
327 else:
328 self.assertOneFrameSent(True, OP_CLOSE, Close(code, message).serialize())
329
330 @contextlib.contextmanager
331 def assertCompletesWithin(self, min_time, max_time):
332 t0 = self.loop.time()
333 yield
334 t1 = self.loop.time()
335 dt = t1 - t0
336 self.assertGreaterEqual(dt, min_time, f"Too fast: {dt} < {min_time}")
337 self.assertLess(dt, max_time, f"Too slow: {dt} >= {max_time}")
338
339 # Test constructor.
340
341 def test_timeout_backwards_compatibility(self):
342 async def create_protocol():
343 return WebSocketCommonProtocol(ping_interval=None, timeout=5)
344
345 with warnings.catch_warnings(record=True) as recorded:
346 warnings.simplefilter("always")
347 protocol = self.loop.run_until_complete(create_protocol())
348
349 self.assertEqual(protocol.close_timeout, 5)
350 self.assertDeprecationWarnings(recorded, ["rename timeout to close_timeout"])
351
352 def test_loop_backwards_compatibility(self):
353 loop = asyncio.new_event_loop()
354 self.addCleanup(loop.close)
355
356 with warnings.catch_warnings(record=True) as recorded:
357 warnings.simplefilter("always")
358 protocol = WebSocketCommonProtocol(ping_interval=None, loop=loop)
359
360 self.assertEqual(protocol.loop, loop)
361 self.assertDeprecationWarnings(recorded, ["remove loop argument"])
362
363 # Test public attributes.
364
365 def test_local_address(self):
366 get_extra_info = unittest.mock.Mock(return_value=("host", 4312))
367 self.transport.get_extra_info = get_extra_info
368
369 self.assertEqual(self.protocol.local_address, ("host", 4312))
370 get_extra_info.assert_called_with("sockname")
371
372 def test_local_address_before_connection(self):
373 # Emulate the situation before connection_open() runs.
374 _transport = self.protocol.transport
375 del self.protocol.transport
376 try:
377 self.assertEqual(self.protocol.local_address, None)
378 finally:
379 self.protocol.transport = _transport
380
381 def test_remote_address(self):
382 get_extra_info = unittest.mock.Mock(return_value=("host", 4312))
383 self.transport.get_extra_info = get_extra_info
384
385 self.assertEqual(self.protocol.remote_address, ("host", 4312))
386 get_extra_info.assert_called_with("peername")
387
388 def test_remote_address_before_connection(self):
389 # Emulate the situation before connection_open() runs.
390 _transport = self.protocol.transport
391 del self.protocol.transport
392 try:
393 self.assertEqual(self.protocol.remote_address, None)
394 finally:
395 self.protocol.transport = _transport
396
397 def test_open(self):
398 self.assertTrue(self.protocol.open)
399 self.close_connection()
400 self.assertFalse(self.protocol.open)
401
402 def test_closed(self):
403 self.assertFalse(self.protocol.closed)
404 self.close_connection()
405 self.assertTrue(self.protocol.closed)
406
407 def test_wait_closed(self):
408 wait_closed = self.loop.create_task(self.protocol.wait_closed())
409 self.assertFalse(wait_closed.done())
410 self.close_connection()
411 self.assertTrue(wait_closed.done())
412
413 def test_close_code(self):
414 self.close_connection(CloseCode.GOING_AWAY, "Bye!")
415 self.assertEqual(self.protocol.close_code, CloseCode.GOING_AWAY)
416
417 def test_close_reason(self):
418 self.close_connection(CloseCode.GOING_AWAY, "Bye!")
419 self.assertEqual(self.protocol.close_reason, "Bye!")
420
421 def test_close_code_not_set(self):
422 self.assertIsNone(self.protocol.close_code)
423
424 def test_close_reason_not_set(self):
425 self.assertIsNone(self.protocol.close_reason)
426
427 # Test the recv coroutine.
428
429 def test_recv_text(self):
430 self.receive_frame(Frame(True, OP_TEXT, "café".encode()))
431 data = self.loop.run_until_complete(self.protocol.recv())
432 self.assertEqual(data, "café")
433
434 def test_recv_binary(self):
435 self.receive_frame(Frame(True, OP_BINARY, b"tea"))
436 data = self.loop.run_until_complete(self.protocol.recv())
437 self.assertEqual(data, b"tea")
438
439 def test_recv_on_closing_connection_local(self):
440 close_task = self.half_close_connection_local()
441
442 with self.assertRaises(ConnectionClosed):
443 self.loop.run_until_complete(self.protocol.recv())
444
445 self.loop.run_until_complete(close_task) # cleanup
446
447 def test_recv_on_closing_connection_remote(self):
448 self.half_close_connection_remote()
449
450 with self.assertRaises(ConnectionClosed):
451 self.loop.run_until_complete(self.protocol.recv())
452
453 def test_recv_on_closed_connection(self):
454 self.close_connection()
455
456 with self.assertRaises(ConnectionClosed):
457 self.loop.run_until_complete(self.protocol.recv())
458
459 def test_recv_protocol_error(self):
460 self.receive_frame(Frame(True, OP_CONT, "café".encode()))
461 self.process_invalid_frames()
462 self.assertConnectionFailed(CloseCode.PROTOCOL_ERROR, "")
463
464 def test_recv_unicode_error(self):
465 self.receive_frame(Frame(True, OP_TEXT, "café".encode("latin-1")))
466 self.process_invalid_frames()
467 self.assertConnectionFailed(CloseCode.INVALID_DATA, "")
468
469 def test_recv_text_payload_too_big(self):
470 self.protocol.max_size = 1024
471 self.receive_frame(Frame(True, OP_TEXT, "café".encode() * 205))
472 self.process_invalid_frames()
473 self.assertConnectionFailed(CloseCode.MESSAGE_TOO_BIG, "")
474
475 def test_recv_binary_payload_too_big(self):
476 self.protocol.max_size = 1024
477 self.receive_frame(Frame(True, OP_BINARY, b"tea" * 342))
478 self.process_invalid_frames()
479 self.assertConnectionFailed(CloseCode.MESSAGE_TOO_BIG, "")
480
481 def test_recv_text_no_max_size(self):
482 self.protocol.max_size = None # for test coverage
483 self.receive_frame(Frame(True, OP_TEXT, "café".encode() * 205))
484 data = self.loop.run_until_complete(self.protocol.recv())
485 self.assertEqual(data, "café" * 205)
486
487 def test_recv_binary_no_max_size(self):
488 self.protocol.max_size = None # for test coverage
489 self.receive_frame(Frame(True, OP_BINARY, b"tea" * 342))
490 data = self.loop.run_until_complete(self.protocol.recv())
491 self.assertEqual(data, b"tea" * 342)
492
493 def test_recv_queue_empty(self):
494 recv = self.loop.create_task(self.protocol.recv())
495 with self.assertRaises(asyncio.TimeoutError):
496 self.loop.run_until_complete(
497 asyncio.wait_for(asyncio.shield(recv), timeout=MS)
498 )
499
500 self.receive_frame(Frame(True, OP_TEXT, "café".encode()))
501 data = self.loop.run_until_complete(recv)
502 self.assertEqual(data, "café")
503
504 def test_recv_queue_full(self):
505 self.protocol.max_queue = 2
506 # Test internals because it's hard to verify buffers from the outside.
507 self.assertEqual(list(self.protocol.messages), [])
508
509 self.receive_frame(Frame(True, OP_TEXT, "café".encode()))
510 self.run_loop_once()
511 self.assertEqual(list(self.protocol.messages), ["café"])
512
513 self.receive_frame(Frame(True, OP_BINARY, b"tea"))
514 self.run_loop_once()
515 self.assertEqual(list(self.protocol.messages), ["café", b"tea"])
516
517 self.receive_frame(Frame(True, OP_BINARY, b"milk"))
518 self.run_loop_once()
519 self.assertEqual(list(self.protocol.messages), ["café", b"tea"])
520
521 self.loop.run_until_complete(self.protocol.recv())
522 self.run_loop_once()
523 self.assertEqual(list(self.protocol.messages), [b"tea", b"milk"])
524
525 self.loop.run_until_complete(self.protocol.recv())
526 self.run_loop_once()
527 self.assertEqual(list(self.protocol.messages), [b"milk"])
528
529 self.loop.run_until_complete(self.protocol.recv())
530 self.run_loop_once()
531 self.assertEqual(list(self.protocol.messages), [])
532
533 def test_recv_queue_no_limit(self):
534 self.protocol.max_queue = None
535
536 for _ in range(100):
537 self.receive_frame(Frame(True, OP_TEXT, "café".encode()))
538 self.run_loop_once()
539
540 # Incoming message queue can contain at least 100 messages.
541 self.assertEqual(list(self.protocol.messages), ["café"] * 100)
542
543 for _ in range(100):
544 self.loop.run_until_complete(self.protocol.recv())
545
546 self.assertEqual(list(self.protocol.messages), [])
547
548 def test_recv_other_error(self):
549 async def read_message():
550 raise Exception("BOOM")
551
552 self.protocol.read_message = read_message
553 self.process_invalid_frames()
554 self.assertConnectionFailed(CloseCode.INTERNAL_ERROR, "")
555
556 def test_recv_canceled(self):
557 recv = self.loop.create_task(self.protocol.recv())
558 self.loop.call_soon(recv.cancel)
559
560 with self.assertRaises(asyncio.CancelledError):
561 self.loop.run_until_complete(recv)
562
563 # The next frame doesn't disappear in a vacuum (it used to).
564 self.receive_frame(Frame(True, OP_TEXT, "café".encode()))
565 data = self.loop.run_until_complete(self.protocol.recv())
566 self.assertEqual(data, "café")
567
568 def test_recv_canceled_race_condition(self):
569 recv = self.loop.create_task(
570 asyncio.wait_for(self.protocol.recv(), timeout=0.000_001)
571 )
572 self.loop.call_soon(self.receive_frame, Frame(True, OP_TEXT, "café".encode()))
573
574 with self.assertRaises(asyncio.TimeoutError):
575 self.loop.run_until_complete(recv)
576
577 # The previous frame doesn't disappear in a vacuum (it used to).
578 self.receive_frame(Frame(True, OP_TEXT, "tea".encode()))
579 data = self.loop.run_until_complete(self.protocol.recv())
580 # If we're getting "tea" there, it means "café" was swallowed (ha, ha).
581 self.assertEqual(data, "café")
582
583 def test_recv_when_transfer_data_cancelled(self):
584 # Clog incoming queue.
585 self.protocol.max_queue = 1
586 self.receive_frame(Frame(True, OP_TEXT, "café".encode()))
587 self.receive_frame(Frame(True, OP_BINARY, b"tea"))
588 self.run_loop_once()
589
590 # Flow control kicks in (check with an implementation detail).
591 self.assertFalse(self.protocol._put_message_waiter.done())
592
593 # Schedule recv().
594 recv = self.loop.create_task(self.protocol.recv())
595
596 # Cancel transfer_data_task (again, implementation detail).
597 self.protocol.fail_connection()
598 self.run_loop_once()
599 self.assertTrue(self.protocol.transfer_data_task.cancelled())
600
601 # recv() completes properly.
602 self.assertEqual(self.loop.run_until_complete(recv), "café")
603
604 def test_recv_prevents_concurrent_calls(self):
605 recv = self.loop.create_task(self.protocol.recv())
606
607 with self.assertRaises(RuntimeError) as raised:
608 self.loop.run_until_complete(self.protocol.recv())
609 self.assertEqual(
610 str(raised.exception),
611 "cannot call recv while another coroutine "
612 "is already waiting for the next message",
613 )
614 recv.cancel()
615
616 # Test the send coroutine.
617
618 def test_send_text(self):
619 self.loop.run_until_complete(self.protocol.send("café"))
620 self.assertOneFrameSent(True, OP_TEXT, "café".encode())
621
622 def test_send_binary(self):
623 self.loop.run_until_complete(self.protocol.send(b"tea"))
624 self.assertOneFrameSent(True, OP_BINARY, b"tea")
625
626 def test_send_binary_from_bytearray(self):
627 self.loop.run_until_complete(self.protocol.send(bytearray(b"tea")))
628 self.assertOneFrameSent(True, OP_BINARY, b"tea")
629
630 def test_send_binary_from_memoryview(self):
631 self.loop.run_until_complete(self.protocol.send(memoryview(b"tea")))
632 self.assertOneFrameSent(True, OP_BINARY, b"tea")
633
634 def test_send_dict(self):
635 with self.assertRaises(TypeError):
636 self.loop.run_until_complete(self.protocol.send({"not": "encoded"}))
637 self.assertNoFrameSent()
638
639 def test_send_type_error(self):
640 with self.assertRaises(TypeError):
641 self.loop.run_until_complete(self.protocol.send(42))
642 self.assertNoFrameSent()
643
644 def test_send_iterable_text(self):
645 self.loop.run_until_complete(self.protocol.send(["ca", "fé"]))
646 self.assertFramesSent(
647 (False, OP_TEXT, "ca".encode()),
648 (False, OP_CONT, "fé".encode()),
649 (True, OP_CONT, "".encode()),
650 )
651
652 def test_send_iterable_binary(self):
653 self.loop.run_until_complete(self.protocol.send([b"te", b"a"]))
654 self.assertFramesSent(
655 (False, OP_BINARY, b"te"), (False, OP_CONT, b"a"), (True, OP_CONT, b"")
656 )
657
658 def test_send_iterable_binary_from_bytearray(self):
659 self.loop.run_until_complete(
660 self.protocol.send([bytearray(b"te"), bytearray(b"a")])
661 )
662 self.assertFramesSent(
663 (False, OP_BINARY, b"te"), (False, OP_CONT, b"a"), (True, OP_CONT, b"")
664 )
665
666 def test_send_iterable_binary_from_memoryview(self):
667 self.loop.run_until_complete(
668 self.protocol.send([memoryview(b"te"), memoryview(b"a")])
669 )
670 self.assertFramesSent(
671 (False, OP_BINARY, b"te"), (False, OP_CONT, b"a"), (True, OP_CONT, b"")
672 )
673
674 def test_send_empty_iterable(self):
675 self.loop.run_until_complete(self.protocol.send([]))
676 self.assertNoFrameSent()
677
678 def test_send_iterable_type_error(self):
679 with self.assertRaises(TypeError):
680 self.loop.run_until_complete(self.protocol.send([42]))
681 self.assertNoFrameSent()
682
683 def test_send_iterable_mixed_type_error(self):
684 with self.assertRaises(TypeError):
685 self.loop.run_until_complete(self.protocol.send(["café", b"tea"]))
686 self.assertFramesSent(
687 (False, OP_TEXT, "café".encode()),
688 (True, OP_CLOSE, Close(CloseCode.INTERNAL_ERROR, "").serialize()),
689 )
690
691 def test_send_iterable_prevents_concurrent_send(self):
692 self.make_drain_slow(2 * MS)
693
694 async def send_iterable():
695 await self.protocol.send(["ca", "fé"])
696
697 async def send_concurrent():
698 await asyncio.sleep(MS)
699 await self.protocol.send(b"tea")
700
701 async def run_concurrently():
702 await asyncio.gather(
703 send_iterable(),
704 send_concurrent(),
705 )
706
707 self.loop.run_until_complete(run_concurrently())
708
709 self.assertFramesSent(
710 (False, OP_TEXT, "ca".encode()),
711 (False, OP_CONT, "fé".encode()),
712 (True, OP_CONT, "".encode()),
713 (True, OP_BINARY, b"tea"),
714 )
715
716 def test_send_async_iterable_text(self):
717 self.loop.run_until_complete(self.protocol.send(async_iterable(["ca", "fé"])))
718 self.assertFramesSent(
719 (False, OP_TEXT, "ca".encode()),
720 (False, OP_CONT, "fé".encode()),
721 (True, OP_CONT, "".encode()),
722 )
723
724 def test_send_async_iterable_binary(self):
725 self.loop.run_until_complete(self.protocol.send(async_iterable([b"te", b"a"])))
726 self.assertFramesSent(
727 (False, OP_BINARY, b"te"), (False, OP_CONT, b"a"), (True, OP_CONT, b"")
728 )
729
730 def test_send_async_iterable_binary_from_bytearray(self):
731 self.loop.run_until_complete(
732 self.protocol.send(async_iterable([bytearray(b"te"), bytearray(b"a")]))
733 )
734 self.assertFramesSent(
735 (False, OP_BINARY, b"te"), (False, OP_CONT, b"a"), (True, OP_CONT, b"")
736 )
737
738 def test_send_async_iterable_binary_from_memoryview(self):
739 self.loop.run_until_complete(
740 self.protocol.send(async_iterable([memoryview(b"te"), memoryview(b"a")]))
741 )
742 self.assertFramesSent(
743 (False, OP_BINARY, b"te"), (False, OP_CONT, b"a"), (True, OP_CONT, b"")
744 )
745
746 def test_send_empty_async_iterable(self):
747 self.loop.run_until_complete(self.protocol.send(async_iterable([])))
748 self.assertNoFrameSent()
749
750 def test_send_async_iterable_type_error(self):
751 with self.assertRaises(TypeError):
752 self.loop.run_until_complete(self.protocol.send(async_iterable([42])))
753 self.assertNoFrameSent()
754
755 def test_send_async_iterable_mixed_type_error(self):
756 with self.assertRaises(TypeError):
757 self.loop.run_until_complete(
758 self.protocol.send(async_iterable(["café", b"tea"]))
759 )
760 self.assertFramesSent(
761 (False, OP_TEXT, "café".encode()),
762 (True, OP_CLOSE, Close(CloseCode.INTERNAL_ERROR, "").serialize()),
763 )
764
765 def test_send_async_iterable_prevents_concurrent_send(self):
766 self.make_drain_slow(2 * MS)
767
768 async def send_async_iterable():
769 await self.protocol.send(async_iterable(["ca", "fé"]))
770
771 async def send_concurrent():
772 await asyncio.sleep(MS)
773 await self.protocol.send(b"tea")
774
775 async def run_concurrently():
776 await asyncio.gather(
777 send_async_iterable(),
778 send_concurrent(),
779 )
780
781 self.loop.run_until_complete(run_concurrently())
782
783 self.assertFramesSent(
784 (False, OP_TEXT, "ca".encode()),
785 (False, OP_CONT, "fé".encode()),
786 (True, OP_CONT, "".encode()),
787 (True, OP_BINARY, b"tea"),
788 )
789
790 def test_send_on_closing_connection_local(self):
791 close_task = self.half_close_connection_local()
792
793 with self.assertRaises(ConnectionClosed):
794 self.loop.run_until_complete(self.protocol.send("foobar"))
795
796 self.assertNoFrameSent()
797
798 self.loop.run_until_complete(close_task) # cleanup
799
800 def test_send_on_closing_connection_remote(self):
801 self.half_close_connection_remote()
802
803 with self.assertRaises(ConnectionClosed):
804 self.loop.run_until_complete(self.protocol.send("foobar"))
805
806 self.assertNoFrameSent()
807
808 def test_send_on_closed_connection(self):
809 self.close_connection()
810
811 with self.assertRaises(ConnectionClosed):
812 self.loop.run_until_complete(self.protocol.send("foobar"))
813
814 self.assertNoFrameSent()
815
816 # Test the ping coroutine.
817
818 def test_ping_default(self):
819 self.loop.run_until_complete(self.protocol.ping())
820 # With our testing tools, it's more convenient to extract the expected
821 # ping data from the library's internals than from the frame sent.
822 ping_data = next(iter(self.protocol.pings))
823 self.assertIsInstance(ping_data, bytes)
824 self.assertEqual(len(ping_data), 4)
825 self.assertOneFrameSent(True, OP_PING, ping_data)
826
827 def test_ping_text(self):
828 self.loop.run_until_complete(self.protocol.ping("café"))
829 self.assertOneFrameSent(True, OP_PING, "café".encode())
830
831 def test_ping_binary(self):
832 self.loop.run_until_complete(self.protocol.ping(b"tea"))
833 self.assertOneFrameSent(True, OP_PING, b"tea")
834
835 def test_ping_binary_from_bytearray(self):
836 self.loop.run_until_complete(self.protocol.ping(bytearray(b"tea")))
837 self.assertOneFrameSent(True, OP_PING, b"tea")
838
839 def test_ping_binary_from_memoryview(self):
840 self.loop.run_until_complete(self.protocol.ping(memoryview(b"tea")))
841 self.assertOneFrameSent(True, OP_PING, b"tea")
842
843 def test_ping_type_error(self):
844 with self.assertRaises(TypeError):
845 self.loop.run_until_complete(self.protocol.ping(42))
846 self.assertNoFrameSent()
847
848 def test_ping_on_closing_connection_local(self):
849 close_task = self.half_close_connection_local()
850
851 with self.assertRaises(ConnectionClosed):
852 self.loop.run_until_complete(self.protocol.ping())
853
854 self.assertNoFrameSent()
855
856 self.loop.run_until_complete(close_task) # cleanup
857
858 def test_ping_on_closing_connection_remote(self):
859 self.half_close_connection_remote()
860
861 with self.assertRaises(ConnectionClosed):
862 self.loop.run_until_complete(self.protocol.ping())
863
864 self.assertNoFrameSent()
865
866 def test_ping_on_closed_connection(self):
867 self.close_connection()
868
869 with self.assertRaises(ConnectionClosed):
870 self.loop.run_until_complete(self.protocol.ping())
871
872 self.assertNoFrameSent()
873
874 # Test the pong coroutine.
875
876 def test_pong_default(self):
877 self.loop.run_until_complete(self.protocol.pong())
878 self.assertOneFrameSent(True, OP_PONG, b"")
879
880 def test_pong_text(self):
881 self.loop.run_until_complete(self.protocol.pong("café"))
882 self.assertOneFrameSent(True, OP_PONG, "café".encode())
883
884 def test_pong_binary(self):
885 self.loop.run_until_complete(self.protocol.pong(b"tea"))
886 self.assertOneFrameSent(True, OP_PONG, b"tea")
887
888 def test_pong_binary_from_bytearray(self):
889 self.loop.run_until_complete(self.protocol.pong(bytearray(b"tea")))
890 self.assertOneFrameSent(True, OP_PONG, b"tea")
891
892 def test_pong_binary_from_memoryview(self):
893 self.loop.run_until_complete(self.protocol.pong(memoryview(b"tea")))
894 self.assertOneFrameSent(True, OP_PONG, b"tea")
895
896 def test_pong_type_error(self):
897 with self.assertRaises(TypeError):
898 self.loop.run_until_complete(self.protocol.pong(42))
899 self.assertNoFrameSent()
900
901 def test_pong_on_closing_connection_local(self):
902 close_task = self.half_close_connection_local()
903
904 with self.assertRaises(ConnectionClosed):
905 self.loop.run_until_complete(self.protocol.pong())
906
907 self.assertNoFrameSent()
908
909 self.loop.run_until_complete(close_task) # cleanup
910
911 def test_pong_on_closing_connection_remote(self):
912 self.half_close_connection_remote()
913
914 with self.assertRaises(ConnectionClosed):
915 self.loop.run_until_complete(self.protocol.pong())
916
917 self.assertNoFrameSent()
918
919 def test_pong_on_closed_connection(self):
920 self.close_connection()
921
922 with self.assertRaises(ConnectionClosed):
923 self.loop.run_until_complete(self.protocol.pong())
924
925 self.assertNoFrameSent()
926
927 # Test the protocol's logic for acknowledging pings with pongs.
928
929 def test_answer_ping(self):
930 self.receive_frame(Frame(True, OP_PING, b"test"))
931 self.run_loop_once()
932 self.assertOneFrameSent(True, OP_PONG, b"test")
933
934 def test_answer_ping_does_not_crash_if_connection_closing(self):
935 close_task = self.half_close_connection_local()
936
937 self.receive_frame(Frame(True, OP_PING, b"test"))
938 self.run_loop_once()
939
940 with self.assertNoLogs("websockets", logging.ERROR):
941 self.loop.run_until_complete(self.protocol.close())
942
943 self.loop.run_until_complete(close_task) # cleanup
944
945 def test_answer_ping_does_not_crash_if_connection_closed(self):
946 self.make_drain_slow()
947 # Drop the connection right after receiving a ping frame,
948 # which prevents responding with a pong frame properly.
949 self.receive_frame(Frame(True, OP_PING, b"test"))
950 self.receive_eof()
951 self.run_loop_once()
952
953 with self.assertNoLogs("websockets", logging.ERROR):
954 self.loop.run_until_complete(self.protocol.close())
955
956 def test_ignore_pong(self):
957 self.receive_frame(Frame(True, OP_PONG, b"test"))
958 self.run_loop_once()
959 self.assertNoFrameSent()
960
961 def test_acknowledge_ping(self):
962 pong_waiter = self.loop.run_until_complete(self.protocol.ping())
963 self.assertFalse(pong_waiter.done())
964 ping_frame = self.last_sent_frame()
965 pong_frame = Frame(True, OP_PONG, ping_frame.data)
966 self.receive_frame(pong_frame)
967 self.run_loop_once()
968 self.run_loop_once()
969 self.assertTrue(pong_waiter.done())
970
971 def test_abort_ping(self):
972 pong_waiter = self.loop.run_until_complete(self.protocol.ping())
973 # Remove the frame from the buffer, else close_connection() complains.
974 self.last_sent_frame()
975 self.assertFalse(pong_waiter.done())
976 self.close_connection()
977 self.assertTrue(pong_waiter.done())
978 self.assertIsInstance(pong_waiter.exception(), ConnectionClosed)
979
980 def test_abort_ping_does_not_log_exception_if_not_retreived(self):
981 self.loop.run_until_complete(self.protocol.ping())
982 # Get the internal Future, which isn't directly returned by ping().
983 ((pong_waiter, _timestamp),) = self.protocol.pings.values()
984 # Remove the frame from the buffer, else close_connection() complains.
985 self.last_sent_frame()
986 self.close_connection()
987 # Check a private attribute, for lack of a better solution.
988 self.assertFalse(pong_waiter._log_traceback)
989
990 def test_acknowledge_previous_pings(self):
991 pings = [
992 (self.loop.run_until_complete(self.protocol.ping()), self.last_sent_frame())
993 for i in range(3)
994 ]
995 # Unsolicited pong doesn't acknowledge pings
996 self.receive_frame(Frame(True, OP_PONG, b""))
997 self.run_loop_once()
998 self.run_loop_once()
999 self.assertFalse(pings[0][0].done())
1000 self.assertFalse(pings[1][0].done())
1001 self.assertFalse(pings[2][0].done())
1002 # Pong acknowledges all previous pings
1003 self.receive_frame(Frame(True, OP_PONG, pings[1][1].data))
1004 self.run_loop_once()
1005 self.run_loop_once()
1006 self.assertTrue(pings[0][0].done())
1007 self.assertTrue(pings[1][0].done())
1008 self.assertFalse(pings[2][0].done())
1009
1010 def test_acknowledge_aborted_ping(self):
1011 pong_waiter = self.loop.run_until_complete(self.protocol.ping())
1012 ping_frame = self.last_sent_frame()
1013 # Clog incoming queue. This lets connection_lost() abort pending pings
1014 # with a ConnectionClosed exception before transfer_data_task
1015 # terminates and close_connection cancels keepalive_ping_task.
1016 self.protocol.max_queue = 1
1017 self.receive_frame(Frame(True, OP_TEXT, b"1"))
1018 self.receive_frame(Frame(True, OP_TEXT, b"2"))
1019 # Add pong frame to the queue.
1020 pong_frame = Frame(True, OP_PONG, ping_frame.data)
1021 self.receive_frame(pong_frame)
1022 # Connection drops.
1023 self.receive_eof()
1024 self.loop.run_until_complete(self.protocol.wait_closed())
1025 # Ping receives a ConnectionClosed exception.
1026 with self.assertRaises(ConnectionClosed):
1027 pong_waiter.result()
1028
1029 # transfer_data doesn't crash, which would be logged.
1030 with self.assertNoLogs("websockets", logging.ERROR):
1031 # Unclog incoming queue.
1032 self.loop.run_until_complete(self.protocol.recv())
1033 self.loop.run_until_complete(self.protocol.recv())
1034
1035 def test_canceled_ping(self):
1036 pong_waiter = self.loop.run_until_complete(self.protocol.ping())
1037 ping_frame = self.last_sent_frame()
1038 pong_waiter.cancel()
1039 pong_frame = Frame(True, OP_PONG, ping_frame.data)
1040 self.receive_frame(pong_frame)
1041 self.run_loop_once()
1042 self.run_loop_once()
1043 self.assertTrue(pong_waiter.cancelled())
1044
1045 def test_duplicate_ping(self):
1046 self.loop.run_until_complete(self.protocol.ping(b"foobar"))
1047 self.assertOneFrameSent(True, OP_PING, b"foobar")
1048 with self.assertRaises(RuntimeError):
1049 self.loop.run_until_complete(self.protocol.ping(b"foobar"))
1050 self.assertNoFrameSent()
1051
1052 # Test the protocol's logic for measuring latency
1053
1054 def test_record_latency_on_pong(self):
1055 self.assertEqual(self.protocol.latency, 0)
1056 self.loop.run_until_complete(self.protocol.ping(b"test"))
1057 self.receive_frame(Frame(True, OP_PONG, b"test"))
1058 self.run_loop_once()
1059 self.assertGreater(self.protocol.latency, 0)
1060
1061 def test_return_latency_on_pong(self):
1062 pong_waiter = self.loop.run_until_complete(self.protocol.ping())
1063 ping_frame = self.last_sent_frame()
1064 pong_frame = Frame(True, OP_PONG, ping_frame.data)
1065 self.receive_frame(pong_frame)
1066 latency = self.loop.run_until_complete(pong_waiter)
1067 self.assertGreater(latency, 0)
1068
1069 # Test the protocol's logic for rebuilding fragmented messages.
1070
1071 def test_fragmented_text(self):
1072 self.receive_frame(Frame(False, OP_TEXT, "ca".encode()))
1073 self.receive_frame(Frame(True, OP_CONT, "fé".encode()))
1074 data = self.loop.run_until_complete(self.protocol.recv())
1075 self.assertEqual(data, "café")
1076
1077 def test_fragmented_binary(self):
1078 self.receive_frame(Frame(False, OP_BINARY, b"t"))
1079 self.receive_frame(Frame(False, OP_CONT, b"e"))
1080 self.receive_frame(Frame(True, OP_CONT, b"a"))
1081 data = self.loop.run_until_complete(self.protocol.recv())
1082 self.assertEqual(data, b"tea")
1083
1084 def test_fragmented_text_payload_too_big(self):
1085 self.protocol.max_size = 1024
1086 self.receive_frame(Frame(False, OP_TEXT, "café".encode() * 100))
1087 self.receive_frame(Frame(True, OP_CONT, "café".encode() * 105))
1088 self.process_invalid_frames()
1089 self.assertConnectionFailed(CloseCode.MESSAGE_TOO_BIG, "")
1090
1091 def test_fragmented_binary_payload_too_big(self):
1092 self.protocol.max_size = 1024
1093 self.receive_frame(Frame(False, OP_BINARY, b"tea" * 171))
1094 self.receive_frame(Frame(True, OP_CONT, b"tea" * 171))
1095 self.process_invalid_frames()
1096 self.assertConnectionFailed(CloseCode.MESSAGE_TOO_BIG, "")
1097
1098 def test_fragmented_text_no_max_size(self):
1099 self.protocol.max_size = None # for test coverage
1100 self.receive_frame(Frame(False, OP_TEXT, "café".encode() * 100))
1101 self.receive_frame(Frame(True, OP_CONT, "café".encode() * 105))
1102 data = self.loop.run_until_complete(self.protocol.recv())
1103 self.assertEqual(data, "café" * 205)
1104
1105 def test_fragmented_binary_no_max_size(self):
1106 self.protocol.max_size = None # for test coverage
1107 self.receive_frame(Frame(False, OP_BINARY, b"tea" * 171))
1108 self.receive_frame(Frame(True, OP_CONT, b"tea" * 171))
1109 data = self.loop.run_until_complete(self.protocol.recv())
1110 self.assertEqual(data, b"tea" * 342)
1111
1112 def test_control_frame_within_fragmented_text(self):
1113 self.receive_frame(Frame(False, OP_TEXT, "ca".encode()))
1114 self.receive_frame(Frame(True, OP_PING, b""))
1115 self.receive_frame(Frame(True, OP_CONT, "fé".encode()))
1116 data = self.loop.run_until_complete(self.protocol.recv())
1117 self.assertEqual(data, "café")
1118 self.assertOneFrameSent(True, OP_PONG, b"")
1119
1120 def test_unterminated_fragmented_text(self):
1121 self.receive_frame(Frame(False, OP_TEXT, "ca".encode()))
1122 # Missing the second part of the fragmented frame.
1123 self.receive_frame(Frame(True, OP_BINARY, b"tea"))
1124 self.process_invalid_frames()
1125 self.assertConnectionFailed(CloseCode.PROTOCOL_ERROR, "")
1126
1127 def test_close_handshake_in_fragmented_text(self):
1128 self.receive_frame(Frame(False, OP_TEXT, "ca".encode()))
1129 self.receive_frame(Frame(True, OP_CLOSE, b""))
1130 self.process_invalid_frames()
1131 # The RFC may have overlooked this case: it says that control frames
1132 # can be interjected in the middle of a fragmented message and that a
1133 # close frame must be echoed. Even though there's an unterminated
1134 # message, technically, the closing handshake was successful.
1135 self.assertConnectionClosed(CloseCode.NO_STATUS_RCVD, "")
1136
1137 def test_connection_close_in_fragmented_text(self):
1138 self.receive_frame(Frame(False, OP_TEXT, "ca".encode()))
1139 self.process_invalid_frames()
1140 self.assertConnectionFailed(CloseCode.ABNORMAL_CLOSURE, "")
1141
1142 # Test miscellaneous code paths to ensure full coverage.
1143
1144 def test_connection_lost(self):
1145 # Test calling connection_lost without going through close_connection.
1146 self.protocol.connection_lost(None)
1147
1148 self.assertConnectionFailed(CloseCode.ABNORMAL_CLOSURE, "")
1149
1150 def test_ensure_open_before_opening_handshake(self):
1151 # Simulate a bug by forcibly reverting the protocol state.
1152 self.protocol.state = State.CONNECTING
1153
1154 with self.assertRaises(InvalidState):
1155 self.loop.run_until_complete(self.protocol.ensure_open())
1156
1157 def test_ensure_open_during_unclean_close(self):
1158 # Process connection_made in order to start transfer_data_task.
1159 self.run_loop_once()
1160
1161 # Ensure the test terminates quickly.
1162 self.loop.call_later(MS, self.receive_eof_if_client)
1163
1164 # Simulate the case when close() times out sending a close frame.
1165 self.protocol.fail_connection()
1166
1167 with self.assertRaises(ConnectionClosed):
1168 self.loop.run_until_complete(self.protocol.ensure_open())
1169
1170 def test_legacy_recv(self):
1171 # By default legacy_recv in disabled.
1172 self.assertEqual(self.protocol.legacy_recv, False)
1173
1174 self.close_connection()
1175
1176 # Enable legacy_recv.
1177 self.protocol.legacy_recv = True
1178
1179 # Now recv() returns None instead of raising ConnectionClosed.
1180 self.assertIsNone(self.loop.run_until_complete(self.protocol.recv()))
1181
1182 # Test the protocol logic for sending keepalive pings.
1183
1184 def restart_protocol_with_keepalive_ping(
1185 self,
1186 ping_interval=3 * MS,
1187 ping_timeout=3 * MS,
1188 ):
1189 initial_protocol = self.protocol
1190
1191 # copied from tearDown
1192
1193 self.transport.close()
1194 self.loop.run_until_complete(self.protocol.close())
1195
1196 # copied from setUp, but enables keepalive pings
1197
1198 async def create_protocol():
1199 return WebSocketCommonProtocol(
1200 ping_interval=ping_interval,
1201 ping_timeout=ping_timeout,
1202 )
1203
1204 self.protocol = self.loop.run_until_complete(create_protocol())
1205
1206 self.transport = TransportMock()
1207 self.transport.setup_mock(self.loop, self.protocol)
1208 self.protocol.is_client = initial_protocol.is_client
1209 self.protocol.side = initial_protocol.side
1210
1211 self.keepalive_ping_task = self.protocol.keepalive_ping_task
1212
1213 def test_keepalive_ping(self):
1214 self.restart_protocol_with_keepalive_ping()
1215
1216 # Ping is sent at 3ms and acknowledged at 4ms.
1217 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1218 (ping_1,) = tuple(self.protocol.pings)
1219 self.assertOneFrameSent(True, OP_PING, ping_1)
1220 self.receive_frame(Frame(True, OP_PONG, ping_1))
1221
1222 # Next ping is sent at 7ms.
1223 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1224 (ping_2,) = tuple(self.protocol.pings)
1225 self.assertOneFrameSent(True, OP_PING, ping_2)
1226
1227 # The keepalive ping task goes on.
1228 self.assertFalse(self.keepalive_ping_task.done())
1229
1230 def test_keepalive_ping_not_acknowledged_closes_connection(self):
1231 self.restart_protocol_with_keepalive_ping()
1232
1233 # Ping is sent at 3ms and not acknowledged.
1234 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1235 (ping_1,) = tuple(self.protocol.pings)
1236 self.assertOneFrameSent(True, OP_PING, ping_1)
1237
1238 # Connection is closed at 6ms.
1239 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1240 self.assertOneFrameSent(
1241 True,
1242 OP_CLOSE,
1243 Close(CloseCode.INTERNAL_ERROR, "keepalive ping timeout").serialize(),
1244 )
1245
1246 # The keepalive ping task is complete.
1247 self.assertEqual(self.keepalive_ping_task.result(), None)
1248
1249 def test_keepalive_ping_stops_when_connection_closing(self):
1250 self.restart_protocol_with_keepalive_ping()
1251 close_task = self.half_close_connection_local()
1252
1253 # No ping sent at 3ms because the closing handshake is in progress.
1254 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1255 self.assertNoFrameSent()
1256
1257 # The keepalive ping task terminated.
1258 self.assertTrue(self.keepalive_ping_task.cancelled())
1259
1260 self.loop.run_until_complete(close_task) # cleanup
1261
1262 def test_keepalive_ping_stops_when_connection_closed(self):
1263 self.restart_protocol_with_keepalive_ping()
1264 self.close_connection()
1265
1266 # The keepalive ping task terminated.
1267 self.assertTrue(self.keepalive_ping_task.cancelled())
1268
1269 def test_keepalive_ping_does_not_crash_when_connection_lost(self):
1270 self.restart_protocol_with_keepalive_ping()
1271 # Clog incoming queue. This lets connection_lost() abort pending pings
1272 # with a ConnectionClosed exception before transfer_data_task
1273 # terminates and close_connection cancels keepalive_ping_task.
1274 self.protocol.max_queue = 1
1275 self.receive_frame(Frame(True, OP_TEXT, b"1"))
1276 self.receive_frame(Frame(True, OP_TEXT, b"2"))
1277 # Ping is sent at 3ms.
1278 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1279 ((pong_waiter, _timestamp),) = self.protocol.pings.values()
1280 # Connection drops.
1281 self.receive_eof()
1282 self.loop.run_until_complete(self.protocol.wait_closed())
1283
1284 # The ping waiter receives a ConnectionClosed exception.
1285 with self.assertRaises(ConnectionClosed):
1286 pong_waiter.result()
1287 # The keepalive ping task terminated properly.
1288 self.assertIsNone(self.keepalive_ping_task.result())
1289
1290 # Unclog incoming queue to terminate the test quickly.
1291 self.loop.run_until_complete(self.protocol.recv())
1292 self.loop.run_until_complete(self.protocol.recv())
1293
1294 def test_keepalive_ping_with_no_ping_interval(self):
1295 self.restart_protocol_with_keepalive_ping(ping_interval=None)
1296
1297 # No ping is sent at 3ms.
1298 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1299 self.assertNoFrameSent()
1300
1301 def test_keepalive_ping_with_no_ping_timeout(self):
1302 self.restart_protocol_with_keepalive_ping(ping_timeout=None)
1303
1304 # Ping is sent at 3ms and not acknowledged.
1305 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1306 (ping_1,) = tuple(self.protocol.pings)
1307 self.assertOneFrameSent(True, OP_PING, ping_1)
1308
1309 # Next ping is sent at 7ms anyway.
1310 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1311 ping_1_again, ping_2 = tuple(self.protocol.pings)
1312 self.assertEqual(ping_1, ping_1_again)
1313 self.assertOneFrameSent(True, OP_PING, ping_2)
1314
1315 # The keepalive ping task goes on.
1316 self.assertFalse(self.keepalive_ping_task.done())
1317
1318 def test_keepalive_ping_unexpected_error(self):
1319 self.restart_protocol_with_keepalive_ping()
1320
1321 async def ping():
1322 raise Exception("BOOM")
1323
1324 self.protocol.ping = ping
1325
1326 # The keepalive ping task fails when sending a ping at 3ms.
1327 self.loop.run_until_complete(asyncio.sleep(4 * MS))
1328
1329 # The keepalive ping task is complete.
1330 # It logs and swallows the exception.
1331 self.assertEqual(self.keepalive_ping_task.result(), None)
1332
1333 # Test the protocol logic for closing the connection.
1334
1335 def test_local_close(self):
1336 # Emulate how the remote endpoint answers the closing handshake.
1337 self.loop.call_later(MS, self.receive_frame, self.close_frame)
1338 self.loop.call_later(MS, self.receive_eof_if_client)
1339
1340 # Run the closing handshake.
1341 self.loop.run_until_complete(self.protocol.close(reason="close"))
1342
1343 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1344 self.assertOneFrameSent(*self.close_frame)
1345
1346 # Closing the connection again is a no-op.
1347 self.loop.run_until_complete(self.protocol.close(reason="oh no!"))
1348
1349 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1350 self.assertNoFrameSent()
1351
1352 def test_remote_close(self):
1353 # Emulate how the remote endpoint initiates the closing handshake.
1354 self.loop.call_later(MS, self.receive_frame, self.close_frame)
1355 self.loop.call_later(MS, self.receive_eof_if_client)
1356
1357 # Wait for some data in order to process the handshake.
1358 # After recv() raises ConnectionClosed, the connection is closed.
1359 with self.assertRaises(ConnectionClosed):
1360 self.loop.run_until_complete(self.protocol.recv())
1361
1362 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1363 self.assertOneFrameSent(*self.close_frame)
1364
1365 # Closing the connection again is a no-op.
1366 self.loop.run_until_complete(self.protocol.close(reason="oh no!"))
1367
1368 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1369 self.assertNoFrameSent()
1370
1371 def test_remote_close_and_connection_lost(self):
1372 self.make_drain_slow()
1373 # Drop the connection right after receiving a close frame,
1374 # which prevents echoing the close frame properly.
1375 self.receive_frame(self.close_frame)
1376 self.receive_eof()
1377 self.run_loop_once()
1378
1379 with self.assertNoLogs("websockets", logging.ERROR):
1380 self.loop.run_until_complete(self.protocol.close(reason="oh no!"))
1381
1382 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1383 self.assertOneFrameSent(*self.close_frame)
1384
1385 def test_simultaneous_close(self):
1386 # Receive the incoming close frame right after self.protocol.close()
1387 # starts executing. This reproduces the error described in:
1388 # https://github.com/python-websockets/websockets/issues/339
1389 self.loop.call_soon(self.receive_frame, self.remote_close)
1390 self.loop.call_soon(self.receive_eof_if_client)
1391 self.run_loop_once()
1392
1393 self.loop.run_until_complete(self.protocol.close(reason="local"))
1394
1395 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "remote")
1396 # The current implementation sends a close frame in response to the
1397 # close frame received from the remote end. It skips the close frame
1398 # that should be sent as a result of calling close().
1399 self.assertOneFrameSent(*self.remote_close)
1400
1401 def test_close_preserves_incoming_frames(self):
1402 self.receive_frame(Frame(True, OP_TEXT, b"hello"))
1403 self.run_loop_once()
1404
1405 self.loop.call_later(MS, self.receive_frame, self.close_frame)
1406 self.loop.call_later(MS, self.receive_eof_if_client)
1407 self.loop.run_until_complete(self.protocol.close(reason="close"))
1408
1409 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1410 self.assertOneFrameSent(*self.close_frame)
1411
1412 next_message = self.loop.run_until_complete(self.protocol.recv())
1413 self.assertEqual(next_message, "hello")
1414
1415 def test_close_protocol_error(self):
1416 invalid_close_frame = Frame(True, OP_CLOSE, b"\x00")
1417 self.receive_frame(invalid_close_frame)
1418 self.receive_eof_if_client()
1419 self.run_loop_once()
1420 self.loop.run_until_complete(self.protocol.close(reason="close"))
1421
1422 self.assertConnectionFailed(CloseCode.PROTOCOL_ERROR, "")
1423
1424 def test_close_connection_lost(self):
1425 self.receive_eof()
1426 self.run_loop_once()
1427 self.loop.run_until_complete(self.protocol.close(reason="close"))
1428
1429 self.assertConnectionFailed(CloseCode.ABNORMAL_CLOSURE, "")
1430
1431 def test_local_close_during_recv(self):
1432 recv = self.loop.create_task(self.protocol.recv())
1433
1434 self.loop.call_later(MS, self.receive_frame, self.close_frame)
1435 self.loop.call_later(MS, self.receive_eof_if_client)
1436
1437 self.loop.run_until_complete(self.protocol.close(reason="close"))
1438
1439 with self.assertRaises(ConnectionClosed):
1440 self.loop.run_until_complete(recv)
1441
1442 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1443
1444 # There is no test_remote_close_during_recv because it would be identical
1445 # to test_remote_close.
1446
1447 def test_remote_close_during_send(self):
1448 self.make_drain_slow()
1449 send = self.loop.create_task(self.protocol.send("hello"))
1450
1451 self.receive_frame(self.close_frame)
1452 self.receive_eof()
1453
1454 with self.assertRaises(ConnectionClosed):
1455 self.loop.run_until_complete(send)
1456
1457 self.assertConnectionClosed(CloseCode.NORMAL_CLOSURE, "close")
1458
1459 # There is no test_local_close_during_send because this cannot really
1460 # happen, considering that writes are serialized.
1461
1462 def test_broadcast_text(self):
1463 broadcast([self.protocol], "café")
1464 self.assertOneFrameSent(True, OP_TEXT, "café".encode())
1465
1466 def test_broadcast_text_reports_no_errors(self):
1467 broadcast([self.protocol], "café", raise_exceptions=True)
1468 self.assertOneFrameSent(True, OP_TEXT, "café".encode())
1469
1470 def test_broadcast_binary(self):
1471 broadcast([self.protocol], b"tea")
1472 self.assertOneFrameSent(True, OP_BINARY, b"tea")
1473
1474 def test_broadcast_binary_reports_no_errors(self):
1475 broadcast([self.protocol], b"tea", raise_exceptions=True)
1476 self.assertOneFrameSent(True, OP_BINARY, b"tea")
1477
1478 def test_broadcast_type_error(self):
1479 with self.assertRaises(TypeError):
1480 broadcast([self.protocol], ["ca", "fé"])
1481
1482 def test_broadcast_no_clients(self):
1483 broadcast([], "café")
1484 self.assertNoFrameSent()
1485
1486 def test_broadcast_two_clients(self):
1487 broadcast([self.protocol, self.protocol], "café")
1488 self.assertFramesSent(
1489 (True, OP_TEXT, "café".encode()),
1490 (True, OP_TEXT, "café".encode()),
1491 )
1492
1493 def test_broadcast_skips_closed_connection(self):
1494 self.close_connection()
1495
1496 with self.assertNoLogs("websockets", logging.ERROR):
1497 broadcast([self.protocol], "café")
1498 self.assertNoFrameSent()
1499
1500 def test_broadcast_skips_closing_connection(self):
1501 close_task = self.half_close_connection_local()
1502
1503 with self.assertNoLogs("websockets", logging.ERROR):
1504 broadcast([self.protocol], "café")
1505 self.assertNoFrameSent()
1506
1507 self.loop.run_until_complete(close_task) # cleanup
1508
1509 def test_broadcast_skips_connection_sending_fragmented_text(self):
1510 self.make_drain_slow()
1511 self.loop.create_task(self.protocol.send(["ca", "fé"]))
1512 self.run_loop_once()
1513 self.assertOneFrameSent(False, OP_TEXT, "ca".encode())
1514
1515 with self.assertLogs("websockets", logging.WARNING) as logs:
1516 broadcast([self.protocol], "café")
1517
1518 self.assertEqual(
1519 [record.getMessage() for record in logs.records],
1520 ["skipped broadcast: sending a fragmented message"],
1521 )
1522
1523 def test_broadcast_reports_connection_sending_fragmented_text(self):
1524 self.make_drain_slow()
1525 self.loop.create_task(self.protocol.send(["ca", "fé"]))
1526 self.run_loop_once()
1527 self.assertOneFrameSent(False, OP_TEXT, "ca".encode())
1528
1529 with self.assertRaises(ExceptionGroup) as raised:
1530 broadcast([self.protocol], "café", raise_exceptions=True)
1531
1532 self.assertEqual(str(raised.exception), "skipped broadcast (1 sub-exception)")
1533 self.assertEqual(
1534 str(raised.exception.exceptions[0]), "sending a fragmented message"
1535 )
1536
1537 def test_broadcast_skips_connection_failing_to_send(self):
1538 # Configure mock to raise an exception when writing to the network.
1539 self.protocol.transport.write.side_effect = RuntimeError("BOOM")
1540
1541 with self.assertLogs("websockets", logging.WARNING) as logs:
1542 broadcast([self.protocol], "café")
1543
1544 self.assertEqual(
1545 [record.getMessage() for record in logs.records],
1546 ["skipped broadcast: failed to write message: RuntimeError: BOOM"],
1547 )
1548
1549 def test_broadcast_reports_connection_failing_to_send(self):
1550 # Configure mock to raise an exception when writing to the network.
1551 self.protocol.transport.write.side_effect = RuntimeError("BOOM")
1552
1553 with self.assertRaises(ExceptionGroup) as raised:
1554 broadcast([self.protocol], "café", raise_exceptions=True)
1555
1556 self.assertEqual(str(raised.exception), "skipped broadcast (1 sub-exception)")
1557 self.assertEqual(str(raised.exception.exceptions[0]), "failed to write message")
1558 self.assertEqual(str(raised.exception.exceptions[0].__cause__), "BOOM")
1559
1560
1561 class ServerTests(CommonTests, AsyncioTestCase):
1562 def setUp(self):
1563 super().setUp()
1564 self.protocol.is_client = False
1565 self.protocol.side = "server"
1566
1567 def test_local_close_send_close_frame_timeout(self):
1568 self.protocol.close_timeout = 10 * MS
1569 self.make_drain_slow(50 * MS)
1570 # If we can't send a close frame, time out in 10ms.
1571 # Check the timing within -1/+9ms for robustness.
1572 with self.assertCompletesWithin(9 * MS, 19 * MS):
1573 self.loop.run_until_complete(self.protocol.close(reason="close"))
1574 self.assertConnectionClosed(CloseCode.ABNORMAL_CLOSURE, "")
1575
1576 def test_local_close_receive_close_frame_timeout(self):
1577 self.protocol.close_timeout = 10 * MS
1578 # If the client doesn't send a close frame, time out in 10ms.
1579 # Check the timing within -1/+9ms for robustness.
1580 with self.assertCompletesWithin(9 * MS, 19 * MS):
1581 self.loop.run_until_complete(self.protocol.close(reason="close"))
1582 self.assertConnectionClosed(CloseCode.ABNORMAL_CLOSURE, "")
1583
1584 def test_local_close_connection_lost_timeout_after_write_eof(self):
1585 self.protocol.close_timeout = 10 * MS
1586 # If the client doesn't close its side of the TCP connection after we
1587 # half-close our side with write_eof(), time out in 10ms.
1588 # Check the timing within -1/+9ms for robustness.
1589 with self.assertCompletesWithin(9 * MS, 19 * MS):
1590 # HACK: disable write_eof => other end drops connection emulation.
1591 self.transport._eof = True
1592 self.receive_frame(self.close_frame)
1593 self.run_loop_once()
1594 self.loop.run_until_complete(self.protocol.close(reason="close"))
1595 self.assertConnectionClosed(
1596 CloseCode.NORMAL_CLOSURE,
1597 "close",
1598 )
1599
1600 def test_local_close_connection_lost_timeout_after_close(self):
1601 self.protocol.close_timeout = 10 * MS
1602 # If the client doesn't close its side of the TCP connection after we
1603 # half-close our side with write_eof() and close it with close(), time
1604 # out in 20ms.
1605 # Check the timing within -1/+9ms for robustness.
1606 # Add another 10ms because this test is flaky and I don't understand.
1607 with self.assertCompletesWithin(19 * MS, 39 * MS):
1608 # HACK: disable write_eof => other end drops connection emulation.
1609 self.transport._eof = True
1610 # HACK: disable close => other end drops connection emulation.
1611 self.transport._closing = True
1612 self.receive_frame(self.close_frame)
1613 self.run_loop_once()
1614 self.loop.run_until_complete(self.protocol.close(reason="close"))
1615 self.assertConnectionClosed(
1616 CloseCode.NORMAL_CLOSURE,
1617 "close",
1618 )
1619
1620
1621 class ClientTests(CommonTests, AsyncioTestCase):
1622 def setUp(self):
1623 super().setUp()
1624 self.protocol.is_client = True
1625 self.protocol.side = "client"
1626
1627 def test_local_close_send_close_frame_timeout(self):
1628 self.protocol.close_timeout = 10 * MS
1629 self.make_drain_slow(50 * MS)
1630 # If we can't send a close frame, time out in 20ms.
1631 # - 10ms waiting for sending a close frame
1632 # - 10ms waiting for receiving a half-close
1633 # Check the timing within -1/+9ms for robustness.
1634 with self.assertCompletesWithin(19 * MS, 29 * MS):
1635 self.loop.run_until_complete(self.protocol.close(reason="close"))
1636 self.assertConnectionClosed(
1637 CloseCode.ABNORMAL_CLOSURE,
1638 "",
1639 )
1640
1641 def test_local_close_receive_close_frame_timeout(self):
1642 self.protocol.close_timeout = 10 * MS
1643 # If the server doesn't send a close frame, time out in 20ms:
1644 # - 10ms waiting for receiving a close frame
1645 # - 10ms waiting for receiving a half-close
1646 # Check the timing within -1/+9ms for robustness.
1647 with self.assertCompletesWithin(19 * MS, 29 * MS):
1648 self.loop.run_until_complete(self.protocol.close(reason="close"))
1649 self.assertConnectionClosed(
1650 CloseCode.ABNORMAL_CLOSURE,
1651 "",
1652 )
1653
1654 def test_local_close_connection_lost_timeout_after_write_eof(self):
1655 self.protocol.close_timeout = 10 * MS
1656 # If the server doesn't half-close its side of the TCP connection
1657 # after we send a close frame, time out in 20ms:
1658 # - 10ms waiting for receiving a half-close
1659 # - 10ms waiting for receiving a close after write_eof
1660 # Check the timing within -1/+9ms for robustness.
1661 with self.assertCompletesWithin(19 * MS, 29 * MS):
1662 # HACK: disable write_eof => other end drops connection emulation.
1663 self.transport._eof = True
1664 self.receive_frame(self.close_frame)
1665 self.run_loop_once()
1666 self.loop.run_until_complete(self.protocol.close(reason="close"))
1667 self.assertConnectionClosed(
1668 CloseCode.NORMAL_CLOSURE,
1669 "close",
1670 )
1671
1672 def test_local_close_connection_lost_timeout_after_close(self):
1673 self.protocol.close_timeout = 10 * MS
1674 # If the client doesn't close its side of the TCP connection after we
1675 # half-close our side with write_eof() and close it with close(), time
1676 # out in 30ms.
1677 # - 10ms waiting for receiving a half-close
1678 # - 10ms waiting for receiving a close after write_eof
1679 # - 10ms waiting for receiving a close after close
1680 # Check the timing within -1/+9ms for robustness.
1681 # Add another 10ms because this test is flaky and I don't understand.
1682 with self.assertCompletesWithin(29 * MS, 49 * MS):
1683 # HACK: disable write_eof => other end drops connection emulation.
1684 self.transport._eof = True
1685 # HACK: disable close => other end drops connection emulation.
1686 self.transport._closing = True
1687 self.receive_frame(self.close_frame)
1688 self.run_loop_once()
1689 self.loop.run_until_complete(self.protocol.close(reason="close"))
1690 self.assertConnectionClosed(
1691 CloseCode.NORMAL_CLOSURE,
1692 "close",
1693 )