blob: c3c4acfb47941129d2b2dabd841db8576efe7007 [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
3import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Guido van Rossum67f7a382002-06-06 21:08:16 +00005
Neal Norwitz55b61d22003-02-28 19:57:03 +00006# This requires the 'network' resource as given on the regrtest command line.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007skip_expected = not support.is_resource_enabled('network')
Neal Norwitz55b61d22003-02-28 19:57:03 +00008
Guido van Rossum67f7a382002-06-06 21:08:16 +00009import time
Antoine Pitrouca023ca2011-01-06 09:05:22 +000010import errno
Guido van Rossum67f7a382002-06-06 21:08:16 +000011import socket
12
Guido van Rossumaa6a6642002-06-12 19:57:18 +000013
Guido van Rossum24e4af82002-06-12 19:18:08 +000014class CreationTestCase(unittest.TestCase):
Guido van Rossum28774da2002-06-12 20:22:49 +000015 """Test case for socket.gettimeout() and socket.settimeout()"""
Guido van Rossumaa6a6642002-06-12 19:57:18 +000016
Guido van Rossum67f7a382002-06-06 21:08:16 +000017 def setUp(self):
Guido van Rossum28774da2002-06-12 20:22:49 +000018 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum67f7a382002-06-06 21:08:16 +000019
20 def tearDown(self):
Guido van Rossum28774da2002-06-12 20:22:49 +000021 self.sock.close()
Guido van Rossum67f7a382002-06-06 21:08:16 +000022
23 def testObjectCreation(self):
Guido van Rossumae469312002-08-22 20:22:16 +000024 # Test Socket creation
Guido van Rossum28774da2002-06-12 20:22:49 +000025 self.assertEqual(self.sock.gettimeout(), None,
26 "timeout not disabled by default")
Guido van Rossum67f7a382002-06-06 21:08:16 +000027
28 def testFloatReturnValue(self):
Guido van Rossumae469312002-08-22 20:22:16 +000029 # Test return value of gettimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000030 self.sock.settimeout(7.345)
31 self.assertEqual(self.sock.gettimeout(), 7.345)
Guido van Rossum67f7a382002-06-06 21:08:16 +000032
Guido van Rossum28774da2002-06-12 20:22:49 +000033 self.sock.settimeout(3)
34 self.assertEqual(self.sock.gettimeout(), 3)
35
36 self.sock.settimeout(None)
37 self.assertEqual(self.sock.gettimeout(), None)
Guido van Rossum67f7a382002-06-06 21:08:16 +000038
39 def testReturnType(self):
Guido van Rossumae469312002-08-22 20:22:16 +000040 # Test return type of gettimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000041 self.sock.settimeout(1)
42 self.assertEqual(type(self.sock.gettimeout()), type(1.0))
Guido van Rossum67f7a382002-06-06 21:08:16 +000043
Guido van Rossum28774da2002-06-12 20:22:49 +000044 self.sock.settimeout(3.9)
45 self.assertEqual(type(self.sock.gettimeout()), type(1.0))
Guido van Rossumaa6a6642002-06-12 19:57:18 +000046
47 def testTypeCheck(self):
Guido van Rossumae469312002-08-22 20:22:16 +000048 # Test type checking by settimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000049 self.sock.settimeout(0)
Guido van Rossume2a383d2007-01-15 16:59:06 +000050 self.sock.settimeout(0)
Guido van Rossum28774da2002-06-12 20:22:49 +000051 self.sock.settimeout(0.0)
52 self.sock.settimeout(None)
53 self.assertRaises(TypeError, self.sock.settimeout, "")
Guido van Rossumef87d6e2007-05-02 19:09:54 +000054 self.assertRaises(TypeError, self.sock.settimeout, "")
Guido van Rossum28774da2002-06-12 20:22:49 +000055 self.assertRaises(TypeError, self.sock.settimeout, ())
56 self.assertRaises(TypeError, self.sock.settimeout, [])
57 self.assertRaises(TypeError, self.sock.settimeout, {})
58 self.assertRaises(TypeError, self.sock.settimeout, 0j)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000059
60 def testRangeCheck(self):
Guido van Rossumae469312002-08-22 20:22:16 +000061 # Test range checking by settimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000062 self.assertRaises(ValueError, self.sock.settimeout, -1)
Guido van Rossume2a383d2007-01-15 16:59:06 +000063 self.assertRaises(ValueError, self.sock.settimeout, -1)
Guido van Rossum28774da2002-06-12 20:22:49 +000064 self.assertRaises(ValueError, self.sock.settimeout, -1.0)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000065
Guido van Rossum11ba0942002-06-13 15:07:44 +000066 def testTimeoutThenBlocking(self):
Guido van Rossumae469312002-08-22 20:22:16 +000067 # Test settimeout() followed by setblocking()
Guido van Rossum28774da2002-06-12 20:22:49 +000068 self.sock.settimeout(10)
69 self.sock.setblocking(1)
70 self.assertEqual(self.sock.gettimeout(), None)
71 self.sock.setblocking(0)
Guido van Rossum11ba0942002-06-13 15:07:44 +000072 self.assertEqual(self.sock.gettimeout(), 0.0)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000073
Guido van Rossum28774da2002-06-12 20:22:49 +000074 self.sock.settimeout(10)
75 self.sock.setblocking(0)
Guido van Rossum11ba0942002-06-13 15:07:44 +000076 self.assertEqual(self.sock.gettimeout(), 0.0)
Guido van Rossum28774da2002-06-12 20:22:49 +000077 self.sock.setblocking(1)
78 self.assertEqual(self.sock.gettimeout(), None)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000079
80 def testBlockingThenTimeout(self):
Guido van Rossumae469312002-08-22 20:22:16 +000081 # Test setblocking() followed by settimeout()
Guido van Rossum28774da2002-06-12 20:22:49 +000082 self.sock.setblocking(0)
83 self.sock.settimeout(1)
84 self.assertEqual(self.sock.gettimeout(), 1)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000085
Guido van Rossum28774da2002-06-12 20:22:49 +000086 self.sock.setblocking(1)
87 self.sock.settimeout(1)
88 self.assertEqual(self.sock.gettimeout(), 1)
Guido van Rossumaa6a6642002-06-12 19:57:18 +000089
Guido van Rossum67f7a382002-06-06 21:08:16 +000090
Guido van Rossum24e4af82002-06-12 19:18:08 +000091class TimeoutTestCase(unittest.TestCase):
Tim Peters14821c52003-02-21 16:45:41 +000092 # There are a number of tests here trying to make sure that an operation
93 # doesn't take too much longer than expected. But competing machine
94 # activity makes it inevitable that such tests will fail at times.
95 # When fuzz was at 1.0, I (tim) routinely saw bogus failures on Win2K
96 # and Win98SE. Boosting it to 2.0 helped a lot, but isn't a real
97 # solution.
98 fuzz = 2.0
Guido van Rossumaa6a6642002-06-12 19:57:18 +000099
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000100 localhost = '127.0.0.1'
101
Guido van Rossum67f7a382002-06-06 21:08:16 +0000102 def setUp(self):
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000103 raise NotImplementedError()
Guido van Rossum67f7a382002-06-06 21:08:16 +0000104
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000105 tearDown = setUp
106
107 def _sock_operation(self, count, timeout, method, *args):
108 """
109 Test the specified socket method.
110
111 The method is run at most `count` times and must raise a socket.timeout
112 within `timeout` + self.fuzz seconds.
113 """
114 self.sock.settimeout(timeout)
115 method = getattr(self.sock, method)
116 for i in range(count):
117 t1 = time.time()
118 try:
119 method(*args)
120 except socket.timeout as e:
121 delta = time.time() - t1
122 break
123 else:
124 self.fail('socket.timeout was not raised')
125 # These checks should account for timing unprecision
126 self.assertLess(delta, timeout + self.fuzz)
127 self.assertGreater(delta, timeout - 1.0)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000128
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000129
130class TCPTimeoutTestCase(TimeoutTestCase):
131 """TCP test case for socket.socket() timeout functions"""
132
133 def setUp(self):
134 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
135 self.addr_remote = ('www.python.org.', 80)
136
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000137 def tearDown(self):
138 self.sock.close()
139
Guido van Rossum67f7a382002-06-06 21:08:16 +0000140 def testConnectTimeout(self):
Trent Nelson514dbb02012-08-20 21:22:59 -0400141 # Testing connect timeout is tricky: we need to have IP connectivity
142 # to a host that silently drops our packets. We can't simulate this
143 # from Python because it's a function of the underlying TCP/IP stack.
144 # So, the following Snakebite host has been defined:
145 blackhole = ('blackhole.snakebite.net', 56666)
146
147 # Blackhole has been configured to silently drop any incoming packets.
148 # No RSTs (for TCP) or ICMP UNREACH (for UDP/ICMP) will be sent back
149 # to hosts that attempt to connect to this address: which is exactly
150 # what we need to confidently test connect timeout.
151
152 # However, we want to prevent false positives. It's not unreasonable
153 # to expect certain hosts may not be able to reach the blackhole, due
154 # to firewalling or general network configuration. In order to improve
155 # our confidence in testing the blackhole, a corresponding 'whitehole'
156 # has also been set up using one port higher:
157 whitehole = ('whitehole.snakebite.net', 56667)
158
159 # This address has been configured to immediately drop any incoming
160 # packets as well, but it does it respectfully with regards to the
161 # incoming protocol. RSTs are sent for TCP packets, and ICMP UNREACH
162 # is sent for UDP/ICMP packets. This means our attempts to connect to
163 # it should be met immediately with ECONNREFUSED. The test case has
164 # been structured around this premise: if we get an ECONNREFUSED from
165 # the whitehole, we proceed with testing connect timeout against the
166 # blackhole. If we don't, we skip the test (with a message about not
167 # getting the required RST from the whitehole within the required
168 # timeframe).
169
170 # For the records, the whitehole/blackhole configuration has been set
171 # up using the 'pf' firewall (available on BSDs), using the following:
172 #
173 # ext_if="bge0"
174 #
175 # blackhole_ip="35.8.247.6"
176 # whitehole_ip="35.8.247.6"
177 # blackhole_port="56666"
178 # whitehole_port="56667"
179 #
180 # block return in log quick on $ext_if proto { tcp udp } \
181 # from any to $whitehole_ip port $whitehole_port
182 # block drop in log quick on $ext_if proto { tcp udp } \
183 # from any to $blackhole_ip port $blackhole_port
184 #
185
186 skip = True
187 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
188 # Use a timeout of 3 seconds. Why 3? Because it's more than 1, and
189 # less than 5. i.e. no particular reason. Feel free to tweak it if
190 # you feel a different value would be more appropriate.
191 timeout = 3
192 sock.settimeout(timeout)
193 try:
194 sock.connect((whitehole))
195 except socket.timeout:
196 pass
197 except IOError as err:
198 if err.errno == errno.ECONNREFUSED:
199 skip = False
200 finally:
201 sock.close()
202 del sock
203
204 if skip:
205 self.skipTest(
206 "We didn't receive a connection reset (RST) packet from "
207 "{}:{} within {} seconds, so we're unable to test connect "
208 "timeout against the corresponding {}:{} (which is "
209 "configured to silently drop packets)."
210 .format(
211 whitehole[0],
212 whitehole[1],
213 timeout,
214 blackhole[0],
215 blackhole[1],
216 )
217 )
218
219 # All that hard work just to test if connect times out in 0.001s ;-)
220 self.addr_remote = blackhole
221 with support.transient_internet(self.addr_remote[0]):
222 self._sock_operation(1, 0.001, 'connect', self.addr_remote)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000223
224 def testRecvTimeout(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000225 # Test recv() timeout
Antoine Pitrou83432ba2010-10-29 18:15:33 +0000226 with support.transient_internet(self.addr_remote[0]):
227 self.sock.connect(self.addr_remote)
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000228 self._sock_operation(1, 1.5, 'recv', 1024)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000229
230 def testAcceptTimeout(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000231 # Test accept() timeout
R. David Murraye9e95932010-02-06 05:00:15 +0000232 support.bind_port(self.sock, self.localhost)
Guido van Rossum28774da2002-06-12 20:22:49 +0000233 self.sock.listen(5)
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000234 self._sock_operation(1, 1.5, 'accept')
Guido van Rossum67f7a382002-06-06 21:08:16 +0000235
Guido van Rossum67f7a382002-06-06 21:08:16 +0000236 def testSend(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000237 # Test send() timeout
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000238 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
239 support.bind_port(serv, self.localhost)
240 serv.listen(5)
241 self.sock.connect(serv.getsockname())
242 # Send a lot of data in order to bypass buffering in the TCP stack.
243 self._sock_operation(100, 1.5, 'send', b"X" * 200000)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000244
245 def testSendto(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000246 # Test sendto() timeout
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000247 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
248 support.bind_port(serv, self.localhost)
249 serv.listen(5)
250 self.sock.connect(serv.getsockname())
251 # The address argument is ignored since we already connected.
252 self._sock_operation(100, 1.5, 'sendto', b"X" * 200000,
253 serv.getsockname())
Guido van Rossum67f7a382002-06-06 21:08:16 +0000254
255 def testSendall(self):
Guido van Rossumae469312002-08-22 20:22:16 +0000256 # Test sendall() timeout
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000257 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
258 support.bind_port(serv, self.localhost)
259 serv.listen(5)
260 self.sock.connect(serv.getsockname())
261 # Send a lot of data in order to bypass buffering in the TCP stack.
262 self._sock_operation(100, 1.5, 'sendall', b"X" * 200000)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000263
264
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000265class UDPTimeoutTestCase(TimeoutTestCase):
266 """UDP test case for socket.socket() timeout functions"""
267
268 def setUp(self):
269 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
270
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000271 def tearDown(self):
272 self.sock.close()
273
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000274 def testRecvfromTimeout(self):
275 # Test recvfrom() timeout
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000276 # Prevent "Address already in use" socket exceptions
277 support.bind_port(self.sock, self.localhost)
Antoine Pitrouca023ca2011-01-06 09:05:22 +0000278 self._sock_operation(1, 1.5, 'recvfrom', 1024)
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000279
280
Neal Norwitz996acf12003-02-17 14:51:41 +0000281def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000282 support.requires('network')
Victor Stinner5c85e3f2011-01-03 14:30:41 +0000283 support.run_unittest(
284 CreationTestCase,
285 TCPTimeoutTestCase,
286 UDPTimeoutTestCase,
287 )
Guido van Rossum67f7a382002-06-06 21:08:16 +0000288
289if __name__ == "__main__":
Neal Norwitz996acf12003-02-17 14:51:41 +0000290 test_main()