Debian Codegraph @

tests/sync/connection.py

raw
1 import contextlib
2 import time
3
4 from websockets.sync.connection import Connection
5
6
7 class InterceptingConnection(Connection):
8 """
9 Connection subclass that can intercept outgoing packets.
10
11 By interfacing with this connection, we simulate network conditions
12 affecting what the component being tested receives during a test.
13
14 """
15
16 def __init__(self, *args, **kwargs):
17 super().__init__(*args, **kwargs)
18 self.socket = InterceptingSocket(self.socket)
19
20 @contextlib.contextmanager
21 def delay_frames_sent(self, delay):
22 """
23 Add a delay before sending frames.
24
25 Delays cumulate: they're added before every frame or before EOF.
26
27 """
28 assert self.socket.delay_sendall is None
29 self.socket.delay_sendall = delay
30 try:
31 yield
32 finally:
33 self.socket.delay_sendall = None
34
35 @contextlib.contextmanager
36 def delay_eof_sent(self, delay):
37 """
38 Add a delay before sending EOF.
39
40 Delays cumulate: they're added before every frame or before EOF.
41
42 """
43 assert self.socket.delay_shutdown is None
44 self.socket.delay_shutdown = delay
45 try:
46 yield
47 finally:
48 self.socket.delay_shutdown = None
49
50 @contextlib.contextmanager
51 def drop_frames_sent(self):
52 """
53 Prevent frames from being sent.
54
55 Since TCP is reliable, sending frames or EOF afterwards is unrealistic.
56
57 """
58 assert not self.socket.drop_sendall
59 self.socket.drop_sendall = True
60 try:
61 yield
62 finally:
63 self.socket.drop_sendall = False
64
65 @contextlib.contextmanager
66 def drop_eof_sent(self):
67 """
68 Prevent EOF from being sent.
69
70 Since TCP is reliable, sending frames or EOF afterwards is unrealistic.
71
72 """
73 assert not self.socket.drop_shutdown
74 self.socket.drop_shutdown = True
75 try:
76 yield
77 finally:
78 self.socket.drop_shutdown = False
79
80
81 class InterceptingSocket:
82 """
83 Socket wrapper that intercepts calls to ``sendall()`` and ``shutdown()``.
84
85 This is coupled to the implementation, which relies on these two methods.
86
87 """
88
89 def __init__(self, socket):
90 self.socket = socket
91 self.delay_sendall = None
92 self.delay_shutdown = None
93 self.drop_sendall = False
94 self.drop_shutdown = False
95
96 def __getattr__(self, name):
97 return getattr(self.socket, name)
98
99 def sendall(self, bytes, flags=0):
100 if self.delay_sendall is not None:
101 time.sleep(self.delay_sendall)
102 if not self.drop_sendall:
103 self.socket.sendall(bytes, flags)
104
105 def shutdown(self, how):
106 if self.delay_shutdown is not None:
107 time.sleep(self.delay_shutdown)
108 if not self.drop_shutdown:
109 self.socket.shutdown(how)