blob: 3c75dcc6f922cc12b4dd58989355f272273d1749 [file] [log] [blame]
Guido van Rossumaa6a6642002-06-12 19:57:18 +00001"""Unit tests for socket timeout feature."""
Guido van Rossum67f7a382002-06-06 21:08:16 +00002
Charles-François Natali7bf11252013-08-16 23:19:22 +02003import functools
Guido van Rossum67f7a382002-06-06 21:08:16 +00004import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Guido van Rossum67f7a382002-06-06 21:08:16 +00006
Neal Norwitz55b61d22003-02-28 19:57:03 +00007# This requires the 'network' resource as given on the regrtest command line.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008skip_expected = not support.is_resource_enabled('network')
Neal Norwitz55b61d22003-02-28 19:57:03 +00009
Guido van Rossum67f7a382002-06-06 21:08:16 +000010import time
Antoine Pitrouca023ca2011-01-06 09:05:22 +000011import errno
Guido van Rossum67f7a382002-06-06 21:08:16 +000012import socket
13
Guido van Rossumaa6a6642002-06-12 19:57:18 +000014
Charles-François Natali7bf11252013-08-16 23:19:22 +020015@functools.lru_cache()
16def resolve_address(host, port):
17 """Resolve an (host, port) to an address.
18
19 We must perform name resolution before timeout tests, otherwise it will be
20 performed by connect().
21 """
22 with support.transient_internet(host):
23 return socket.getaddrinfo(host, port, socket.AF_INET,
24 socket.SOCK_STREAM)[0][4]
25
26
Guido van Rossum24e4af82002-06-12 19:18:08 +000027class CreationTestCase(unittest.TestCase):
Guido van Rossum28774da2002-06-12 20:22:49 +000028 """Test case for socket.gettimeout() and socket.settimeout()"""
Guido van Rossumaa6a6642002-06-12 19:57:18 +000029
Guido van Rossum67f7a382002-06-06 21:08:16 +000030 def setUp(self):
Guido van Rossum28774da2002-06-12 20:22:49 +000031 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum67f7a382002-06-06 21:08:16 +000032
33 def tearDown(self):
Guido van Rossum28774da2002-06-12 20:22:49 +000034 self.sock.close()
Guido van Rossum67f7a382002-06-06 21:08:16 +000035
36 def testObjectCreation(self):
Guido van Rossumae469312002-08-22 20:22:16 +000037 # Test Socket creation
Guido van Rossum28774da2002-06-12 20:22:49 +000038 self.assertEqual(self.sock.gettimeout(), None,
39 "timeout not disabled by default")
Guido van Rossum67f7a382002-06-06 21:08:16 +000040
41 def testFloatReturnValue(self):
Guido van Rossumae469312002-08-22 20:22:16 +000042 # Test return value of gettimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000043 self.sock.settimeout(7.345)
44 self.assertEqual(self.sock.gettimeout(), 7.345)
Guido van Rossum67f7a382002-06-06 21:08:16 +000045
Guido van Rossum28774da2002-06-12 20:22:49 +000046 self.sock.settimeout(3)
47 self.assertEqual(self.sock.gettimeout(), 3)
48
49 self.sock.settimeout(None)
50 self.assertEqual(self.sock.gettimeout(), None)
Guido van Rossum67f7a382002-06-06 21:08:16 +000051
52 def testReturnType(self):
Guido van Rossumae469312002-08-22 20:22:16 +000053 # Test return type of gettimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000054 self.sock.settimeout(1)
55 self.assertEqual(type(self.sock.gettimeout()), type(1.0))
Guido van Rossum67f7a382002-06-06 21:08:16 +000056
Guido van Rossum28774da2002-06-12 20:22:49 +000057 self.sock.settimeout(3.9)
58 self.assertEqual(type(self.sock.gettimeout()), type(1.0))
Guido van Rossumaa6a6642002-06-12 19:57:18 +000059
60 def testTypeCheck(self):
Guido van Rossumae469312002-08-22 20:22:16 +000061 # Test type checking by settimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000062 self.sock.settimeout(0)
Guido van Rossume2a383d2007-01-15 16:59:06 +000063 self.sock.settimeout(0)
Guido van Rossum28774da2002-06-12 20:22:49 +000064 self.sock.settimeout(0.0)
65 self.sock.settimeout(None)
66 self.assertRaises(TypeError, self.sock.settimeout, "")
Guido van Rossumef87d6e2007-05-02 19:09:54 +000067 self.assertRaises(TypeError, self.sock.settimeout, "")
Guido van Rossum28774da2002-06-12 20:22:49 +000068 self.assertRaises(TypeError, self.sock.settimeout, ())
69 self.assertRaises(TypeError, self.sock.settimeout, [])
70 self.assertRaises(TypeError, self.sock.settimeout, {})
71 self.assertRaises(TypeError, self.sock.settimeout, 0j)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000072
73 def testRangeCheck(self):
Guido van Rossumae469312002-08-22 20:22:16 +000074 # Test range checking by settimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000075 self.assertRaises(ValueError, self.sock.settimeout, -1)
Guido van Rossume2a383d2007-01-15 16:59:06 +000076 self.assertRaises(ValueError, self.sock.settimeout, -1)
Guido van Rossum28774da2002-06-12 20:22:49 +000077 self.assertRaises(ValueError, self.sock.settimeout, -1.0)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000078
Guido van Rossum11ba0942002-06-13 15:07:44 +000079 def testTimeoutThenBlocking(self):
Guido van Rossumae469312002-08-22 20:22:16 +000080 # Test settimeout() followed by setblocking()
Guido van Rossum28774da2002-06-12 20:22:49 +000081 self.sock.settimeout(10)
82 self.sock.setblocking(1)
83 self.assertEqual(self.sock.gettimeout(), None)
84 self.sock.setblocking(0)
Guido van Rossum11ba0942002-06-13 15:07:44 +000085 self.assertEqual(self.sock.gettimeout(), 0.0)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000086
Guido van Rossum28774da2002-06-12 20:22:49 +000087 self.sock.settimeout(10)
88 self.sock.setblocking(0)
Guido van Rossum11ba0942002-06-13 15:07:44 +000089 self.assertEqual(self.sock.gettimeout(), 0.0)
Guido van Rossum28774da2002-06-12 20:22:49 +000090 self.sock.setblocking(1)
91 self.assertEqual(self.sock.gettimeout(), None)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000092
93 def testBlockingThenTimeout(self):
Guido van Rossumae469312002-08-22 20:22:16 +000094 # Test setblocking() followed by settimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000095 self.sock.setblocking(0)
96 self.sock.settimeout(1)
97 self.assertEqual(self.sock.gettimeout(), 1)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000098
Guido van Rossum28774da2002-06-12 20:22:49 +000099 self.sock.setblocking(1)
100 self.sock.settimeout(1)
101 self.assertEqual(self.sock.gettimeout(), 1)
Guido van Rossumaa6a6642002-06-12 19:57:18 +0000102
Guido van Rossum67f7a382002-06-06 21:08:16 +0000103
Guido van Rossum24e4af82002-06-12 19:18:08 +0000104class TimeoutTestCase(unittest.TestCase):
Tim Peters14821c52003-02-21 16:45:41 +0000105 # There are a number of tests here trying to make sure that an operation
106 # doesn't take too much longer than expected. But competing machine
107 # activity makes it inevitable that such tests will fail at times.
108 # When fuzz was at 1.0, I (tim) routinely saw bogus failures on Win2K
109 # and Win98SE. Boosting it to 2.0 helped a lot, but isn't a real
110 # solution.
111 fuzz = 2.0
Guido van Rossumaa6a6642002-06-12 19:57:18 +0000112
Antoine Pitrouf6fbf562013-08-22 00:39:46 +0200113 localhost = support.HOST
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000114
Guido van Rossum67f7a382002-06-06 21:08:16 +0000115 def setUp(self):
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000116 raise NotImplementedError()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000117
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000118 tearDown = setUp
119
120 def _sock_operation(self, count, timeout, method, *args):
121 """
122 Test the specified socket method.
123
124 The method is run at most `count` times and must raise a socket.timeout
125 within `timeout` + self.fuzz seconds.
126 """
127 self.sock.settimeout(timeout)
128 method = getattr(self.sock, method)
129 for i in range(count):
130 t1 = time.time()
131 try:
132 method(*args)
133 except socket.timeout as e:
134 delta = time.time() - t1
135 break
136 else:
137 self.fail('socket.timeout was not raised')
138 # These checks should account for timing unprecision
139 self.assertLess(delta, timeout + self.fuzz)
140 self.assertGreater(delta, timeout - 1.0)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000141
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000142
143class TCPTimeoutTestCase(TimeoutTestCase):
144 """TCP test case for socket.socket() timeout functions"""
145
146 def setUp(self):
147 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Charles-François Natali7bf11252013-08-16 23:19:22 +0200148 self.addr_remote = resolve_address('www.python.org.', 80)
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000149
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000150 def tearDown(self):
151 self.sock.close()
152
Guido van Rossum67f7a382002-06-06 21:08:16 +0000153 def testConnectTimeout(self):
Trent Nelson514dbb02012-08-20 21:22:59 -0400154 # Testing connect timeout is tricky: we need to have IP connectivity
155 # to a host that silently drops our packets. We can't simulate this
156 # from Python because it's a function of the underlying TCP/IP stack.
157 # So, the following Snakebite host has been defined:
Charles-François Natali7bf11252013-08-16 23:19:22 +0200158 blackhole = resolve_address('blackhole.snakebite.net', 56666)
Trent Nelson514dbb02012-08-20 21:22:59 -0400159
160 # Blackhole has been configured to silently drop any incoming packets.
161 # No RSTs (for TCP) or ICMP UNREACH (for UDP/ICMP) will be sent back
162 # to hosts that attempt to connect to this address: which is exactly
163 # what we need to confidently test connect timeout.
164
165 # However, we want to prevent false positives. It's not unreasonable
166 # to expect certain hosts may not be able to reach the blackhole, due
167 # to firewalling or general network configuration. In order to improve
168 # our confidence in testing the blackhole, a corresponding 'whitehole'
169 # has also been set up using one port higher:
Charles-François Natali7bf11252013-08-16 23:19:22 +0200170 whitehole = resolve_address('whitehole.snakebite.net', 56667)
Trent Nelson514dbb02012-08-20 21:22:59 -0400171
172 # This address has been configured to immediately drop any incoming
173 # packets as well, but it does it respectfully with regards to the
174 # incoming protocol. RSTs are sent for TCP packets, and ICMP UNREACH
175 # is sent for UDP/ICMP packets. This means our attempts to connect to
176 # it should be met immediately with ECONNREFUSED. The test case has
177 # been structured around this premise: if we get an ECONNREFUSED from
178 # the whitehole, we proceed with testing connect timeout against the
179 # blackhole. If we don't, we skip the test (with a message about not
180 # getting the required RST from the whitehole within the required
181 # timeframe).
182
183 # For the records, the whitehole/blackhole configuration has been set
184 # up using the 'pf' firewall (available on BSDs), using the following:
185 #
186 # ext_if="bge0"
187 #
188 # blackhole_ip="35.8.247.6"
189 # whitehole_ip="35.8.247.6"
190 # blackhole_port="56666"
191 # whitehole_port="56667"
192 #
193 # block return in log quick on $ext_if proto { tcp udp } \
194 # from any to $whitehole_ip port $whitehole_port
195 # block drop in log quick on $ext_if proto { tcp udp } \
196 # from any to $blackhole_ip port $blackhole_port
197 #
198
199 skip = True
200 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
201 # Use a timeout of 3 seconds. Why 3? Because it's more than 1, and
202 # less than 5. i.e. no particular reason. Feel free to tweak it if
203 # you feel a different value would be more appropriate.
204 timeout = 3
205 sock.settimeout(timeout)
206 try:
207 sock.connect((whitehole))
208 except socket.timeout:
209 pass
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200210 except OSError as err:
Trent Nelson514dbb02012-08-20 21:22:59 -0400211 if err.errno == errno.ECONNREFUSED:
212 skip = False
213 finally:
214 sock.close()
215 del sock
216
217 if skip:
218 self.skipTest(
219 "We didn't receive a connection reset (RST) packet from "
220 "{}:{} within {} seconds, so we're unable to test connect "
221 "timeout against the corresponding {}:{} (which is "
222 "configured to silently drop packets)."
223 .format(
224 whitehole[0],
225 whitehole[1],
226 timeout,
227 blackhole[0],
228 blackhole[1],
229 )
230 )
231
232 # All that hard work just to test if connect times out in 0.001s ;-)
233 self.addr_remote = blackhole
234 with support.transient_internet(self.addr_remote[0]):
235 self._sock_operation(1, 0.001, 'connect', self.addr_remote)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000236
237 def testRecvTimeout(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000238 # Test recv() timeout
Antoine Pitrou83432ba2010-10-29 18:15:33 +0000239 with support.transient_internet(self.addr_remote[0]):
240 self.sock.connect(self.addr_remote)
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000241 self._sock_operation(1, 1.5, 'recv', 1024)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000242
243 def testAcceptTimeout(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000244 # Test accept() timeout
R. David Murraye9e95932010-02-06 05:00:15 +0000245 support.bind_port(self.sock, self.localhost)
Charles-François Natali6e204602014-07-23 19:28:13 +0100246 self.sock.listen()
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000247 self._sock_operation(1, 1.5, 'accept')
Guido van Rossum67f7a382002-06-06 21:08:16 +0000248
Guido van Rossum67f7a382002-06-06 21:08:16 +0000249 def testSend(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000250 # Test send() timeout
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000251 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
252 support.bind_port(serv, self.localhost)
Charles-François Natali6e204602014-07-23 19:28:13 +0100253 serv.listen()
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000254 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, 'send', b"X" * 200000)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000257
258 def testSendto(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000259 # Test sendto() timeout
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000260 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
261 support.bind_port(serv, self.localhost)
Charles-François Natali6e204602014-07-23 19:28:13 +0100262 serv.listen()
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000263 self.sock.connect(serv.getsockname())
264 # The address argument is ignored since we already connected.
265 self._sock_operation(100, 1.5, 'sendto', b"X" * 200000,
266 serv.getsockname())
Guido van Rossum67f7a382002-06-06 21:08:16 +0000267
268 def testSendall(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000269 # Test sendall() timeout
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000270 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
271 support.bind_port(serv, self.localhost)
Charles-François Natali6e204602014-07-23 19:28:13 +0100272 serv.listen()
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000273 self.sock.connect(serv.getsockname())
274 # Send a lot of data in order to bypass buffering in the TCP stack.
275 self._sock_operation(100, 1.5, 'sendall', b"X" * 200000)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000276
277
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000278class UDPTimeoutTestCase(TimeoutTestCase):
279 """UDP test case for socket.socket() timeout functions"""
280
281 def setUp(self):
282 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
283
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000284 def tearDown(self):
285 self.sock.close()
286
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000287 def testRecvfromTimeout(self):
288 # Test recvfrom() timeout
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000289 # Prevent "Address already in use" socket exceptions
290 support.bind_port(self.sock, self.localhost)
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000291 self._sock_operation(1, 1.5, 'recvfrom', 1024)
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000292
293
Neal Norwitz996acf12003-02-17 14:51:41 +0000294def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000295 support.requires('network')
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000296 support.run_unittest(
297 CreationTestCase,
298 TCPTimeoutTestCase,
299 UDPTimeoutTestCase,
300 )
Guido van Rossum67f7a382002-06-06 21:08:16 +0000301
302if __name__ == "__main__":
Neal Norwitz996acf12003-02-17 14:51:41 +0000303 test_main()