Debian Codegraph @

Lib/test/test_timeout.py

raw
1 """Unit tests for socket timeout feature."""
2
3 import functools
4 import unittest
5 from test import support
6 from test.support import socket_helper
7
8 import time
9 import errno
10 import socket
11
12
13 @functools.lru_cache()
14 def resolve_address(host, port):
15 """Resolve an (host, port) to an address.
16
17 We must perform name resolution before timeout tests, otherwise it will be
18 performed by connect().
19 """
20 with socket_helper.transient_internet(host):
21 return socket.getaddrinfo(host, port, socket.AF_INET,
22 socket.SOCK_STREAM)[0][4]
23
24
25 class CreationTestCase(unittest.TestCase):
26 """Test case for socket.gettimeout() and socket.settimeout()"""
27
28 def setUp(self):
29 self.sock = self.enterContext(
30 socket.socket(socket.AF_INET, socket.SOCK_STREAM))
31
32 def testObjectCreation(self):
33 # Test Socket creation
34 self.assertEqual(self.sock.gettimeout(), None,
35 "timeout not disabled by default")
36
37 def testFloatReturnValue(self):
38 # Test return value of gettimeout()
39 self.sock.settimeout(7.345)
40 self.assertEqual(self.sock.gettimeout(), 7.345)
41
42 self.sock.settimeout(3)
43 self.assertEqual(self.sock.gettimeout(), 3)
44
45 self.sock.settimeout(None)
46 self.assertEqual(self.sock.gettimeout(), None)
47
48 def testReturnType(self):
49 # Test return type of gettimeout()
50 self.sock.settimeout(1)
51 self.assertIs(type(self.sock.gettimeout()), float)
52
53 self.sock.settimeout(3.9)
54 self.assertIs(type(self.sock.gettimeout()), float)
55
56 def testTypeCheck(self):
57 # Test type checking by settimeout()
58 self.sock.settimeout(0)
59 self.sock.settimeout(0)
60 self.sock.settimeout(0.0)
61 self.sock.settimeout(None)
62 self.assertRaises(TypeError, self.sock.settimeout, "")
63 self.assertRaises(TypeError, self.sock.settimeout, "")
64 self.assertRaises(TypeError, self.sock.settimeout, ())
65 self.assertRaises(TypeError, self.sock.settimeout, [])
66 self.assertRaises(TypeError, self.sock.settimeout, {})
67 self.assertRaises(TypeError, self.sock.settimeout, 0j)
68
69 def testRangeCheck(self):
70 # Test range checking by settimeout()
71 self.assertRaises(ValueError, self.sock.settimeout, -1)
72 self.assertRaises(ValueError, self.sock.settimeout, -1)
73 self.assertRaises(ValueError, self.sock.settimeout, -1.0)
74
75 def testTimeoutThenBlocking(self):
76 # Test settimeout() followed by setblocking()
77 self.sock.settimeout(10)
78 self.sock.setblocking(True)
79 self.assertEqual(self.sock.gettimeout(), None)
80 self.sock.setblocking(False)
81 self.assertEqual(self.sock.gettimeout(), 0.0)
82
83 self.sock.settimeout(10)
84 self.sock.setblocking(False)
85 self.assertEqual(self.sock.gettimeout(), 0.0)
86 self.sock.setblocking(True)
87 self.assertEqual(self.sock.gettimeout(), None)
88
89 def testBlockingThenTimeout(self):
90 # Test setblocking() followed by settimeout()
91 self.sock.setblocking(False)
92 self.sock.settimeout(1)
93 self.assertEqual(self.sock.gettimeout(), 1)
94
95 self.sock.setblocking(True)
96 self.sock.settimeout(1)
97 self.assertEqual(self.sock.gettimeout(), 1)
98
99
100 class TimeoutTestCase(unittest.TestCase):
101 # There are a number of tests here trying to make sure that an operation
102 # doesn't take too much longer than expected. But competing machine
103 # activity makes it inevitable that such tests will fail at times.
104 # When fuzz was at 1.0, I (tim) routinely saw bogus failures on Win2K
105 # and Win98SE. Boosting it to 2.0 helped a lot, but isn't a real
106 # solution.
107 fuzz = 2.0
108
109 localhost = socket_helper.HOST
110
111 def setUp(self):
112 raise NotImplementedError()
113
114 def _sock_operation(self, count, timeout, method, *args):
115 """
116 Test the specified socket method.
117
118 The method is run at most `count` times and must raise a TimeoutError
119 within `timeout` + self.fuzz seconds.
120 """
121 self.sock.settimeout(timeout)
122 method = getattr(self.sock, method)
123 for i in range(count):
124 t1 = time.monotonic()
125 try:
126 method(*args)
127 except TimeoutError as e:
128 delta = time.monotonic() - t1
129 break
130 else:
131 self.fail('TimeoutError was not raised')
132 # These checks should account for timing unprecision
133 self.assertLess(delta, timeout + self.fuzz)
134 self.assertGreater(delta, timeout - 1.0)
135
136
137 class TCPTimeoutTestCase(TimeoutTestCase):
138 """TCP test case for socket.socket() timeout functions"""
139
140 def setUp(self):
141 self.sock = self.enterContext(
142 socket.socket(socket.AF_INET, socket.SOCK_STREAM))
143 self.addr_remote = resolve_address('www.python.org.', 80)
144
145 def testConnectTimeout(self):
146 # Testing connect timeout is tricky: we need to have IP connectivity
147 # to a host that silently drops our packets. We can't simulate this
148 # from Python because it's a function of the underlying TCP/IP stack.
149 # So, the following port on the pythontest.net host has been defined:
150 blackhole = resolve_address('pythontest.net', 56666)
151
152 # Blackhole has been configured to silently drop any incoming packets.
153 # No RSTs (for TCP) or ICMP UNREACH (for UDP/ICMP) will be sent back
154 # to hosts that attempt to connect to this address: which is exactly
155 # what we need to confidently test connect timeout.
156
157 # However, we want to prevent false positives. It's not unreasonable
158 # to expect certain hosts may not be able to reach the blackhole, due
159 # to firewalling or general network configuration. In order to improve
160 # our confidence in testing the blackhole, a corresponding 'whitehole'
161 # has also been set up using one port higher:
162 whitehole = resolve_address('pythontest.net', 56667)
163
164 # This address has been configured to immediately drop any incoming
165 # packets as well, but it does it respectfully with regards to the
166 # incoming protocol. RSTs are sent for TCP packets, and ICMP UNREACH
167 # is sent for UDP/ICMP packets. This means our attempts to connect to
168 # it should be met immediately with ECONNREFUSED. The test case has
169 # been structured around this premise: if we get an ECONNREFUSED from
170 # the whitehole, we proceed with testing connect timeout against the
171 # blackhole. If we don't, we skip the test (with a message about not
172 # getting the required RST from the whitehole within the required
173 # timeframe).
174
175 # For the records, the whitehole/blackhole configuration has been set
176 # up using the 'iptables' firewall, using the following rules:
177 #
178 # -A INPUT -p tcp --destination-port 56666 -j DROP
179 # -A INPUT -p udp --destination-port 56666 -j DROP
180 # -A INPUT -p tcp --destination-port 56667 -j REJECT
181 # -A INPUT -p udp --destination-port 56667 -j REJECT
182 #
183 # See https://github.com/python/psf-salt/blob/main/pillar/base/firewall/snakebite.sls
184 # for the current configuration.
185
186 skip = True
187 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
188 try:
189 timeout = support.LOOPBACK_TIMEOUT
190 sock.settimeout(timeout)
191 sock.connect((whitehole))
192 except TimeoutError:
193 pass
194 except OSError as err:
195 if err.errno == errno.ECONNREFUSED:
196 skip = False
197
198 if skip:
199 self.skipTest(
200 "We didn't receive a connection reset (RST) packet from "
201 "{}:{} within {} seconds, so we're unable to test connect "
202 "timeout against the corresponding {}:{} (which is "
203 "configured to silently drop packets)."
204 .format(
205 whitehole[0],
206 whitehole[1],
207 timeout,
208 blackhole[0],
209 blackhole[1],
210 )
211 )
212
213 # All that hard work just to test if connect times out in 0.001s ;-)
214 self.addr_remote = blackhole
215 with socket_helper.transient_internet(self.addr_remote[0]):
216 self._sock_operation(1, 0.001, 'connect', self.addr_remote)
217
218 def testRecvTimeout(self):
219 # Test recv() timeout
220 with socket_helper.transient_internet(self.addr_remote[0]):
221 self.sock.connect(self.addr_remote)
222 self._sock_operation(1, 1.5, 'recv', 1024)
223
224 def testAcceptTimeout(self):
225 # Test accept() timeout
226 socket_helper.bind_port(self.sock, self.localhost)
227 self.sock.listen()
228 self._sock_operation(1, 1.5, 'accept')
229
230 def testSend(self):
231 # Test send() timeout
232 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
233 socket_helper.bind_port(serv, self.localhost)
234 serv.listen()
235 self.sock.connect(serv.getsockname())
236 # Send a lot of data in order to bypass buffering in the TCP stack.
237 self._sock_operation(100, 1.5, 'send', b"X" * 200000)
238
239 def testSendto(self):
240 # Test sendto() timeout
241 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
242 socket_helper.bind_port(serv, self.localhost)
243 serv.listen()
244 self.sock.connect(serv.getsockname())
245 # The address argument is ignored since we already connected.
246 self._sock_operation(100, 1.5, 'sendto', b"X" * 200000,
247 serv.getsockname())
248
249 def testSendall(self):
250 # Test sendall() timeout
251 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
252 socket_helper.bind_port(serv, self.localhost)
253 serv.listen()
254 self.sock.connect(serv.getsockname())
255 # Send a lot of data in order to bypass buffering in the TCP stack.
256 self._sock_operation(100, 1.5, 'sendall', b"X" * 200000)
257
258
259 class UDPTimeoutTestCase(TimeoutTestCase):
260 """UDP test case for socket.socket() timeout functions"""
261
262 def setUp(self):
263 self.sock = self.enterContext(
264 socket.socket(socket.AF_INET, socket.SOCK_DGRAM))
265
266 def testRecvfromTimeout(self):
267 # Test recvfrom() timeout
268 # Prevent "Address already in use" socket exceptions
269 socket_helper.bind_port(self.sock, self.localhost)
270 self._sock_operation(1, 1.5, 'recvfrom', 1024)
271
272
273 def setUpModule():
274 support.requires('network')
275 support.requires_working_socket(module=True)
276
277
278 if __name__ == "__main__":
279 unittest.main()