test_timeout.py 11 KB

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