test_support.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # Subset of test.support from CPython 3.5, just what we need to run asyncio
  2. # test suite. The code is copied from CPython 3.5 to not depend on the test
  3. # module because it is rarely installed.
  4. # Ignore symbol TEST_HOME_DIR: test_events works without it
  5. import functools
  6. import gc
  7. import os
  8. import platform
  9. import re
  10. import socket
  11. import subprocess
  12. import sys
  13. import time
  14. # A constant likely larger than the underlying OS pipe buffer size, to
  15. # make writes blocking.
  16. # Windows limit seems to be around 512 B, and many Unix kernels have a
  17. # 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
  18. # (see issue #17835 for a discussion of this number).
  19. PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
  20. def strip_python_stderr(stderr):
  21. """Strip the stderr of a Python process from potential debug output
  22. emitted by the interpreter.
  23. This will typically be run on the result of the communicate() method
  24. of a subprocess.Popen object.
  25. """
  26. stderr = re.sub(br"\[\d+ refs, \d+ blocks\]\r?\n?", b"", stderr).strip()
  27. return stderr
  28. # Executing the interpreter in a subprocess
  29. def _assert_python(expected_success, *args, **env_vars):
  30. if '__isolated' in env_vars:
  31. isolated = env_vars.pop('__isolated')
  32. else:
  33. isolated = not env_vars
  34. cmd_line = [sys.executable, '-X', 'faulthandler']
  35. if isolated and sys.version_info >= (3, 4):
  36. # isolated mode: ignore Python environment variables, ignore user
  37. # site-packages, and don't add the current directory to sys.path
  38. cmd_line.append('-I')
  39. elif not env_vars:
  40. # ignore Python environment variables
  41. cmd_line.append('-E')
  42. # Need to preserve the original environment, for in-place testing of
  43. # shared library builds.
  44. env = os.environ.copy()
  45. # But a special flag that can be set to override -- in this case, the
  46. # caller is responsible to pass the full environment.
  47. if env_vars.pop('__cleanenv', None):
  48. env = {}
  49. env.update(env_vars)
  50. cmd_line.extend(args)
  51. p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
  52. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  53. env=env)
  54. try:
  55. out, err = p.communicate()
  56. finally:
  57. subprocess._cleanup()
  58. p.stdout.close()
  59. p.stderr.close()
  60. rc = p.returncode
  61. err = strip_python_stderr(err)
  62. if (rc and expected_success) or (not rc and not expected_success):
  63. raise AssertionError(
  64. "Process return code is %d, "
  65. "stderr follows:\n%s" % (rc, err.decode('ascii', 'ignore')))
  66. return rc, out, err
  67. def assert_python_ok(*args, **env_vars):
  68. """
  69. Assert that running the interpreter with `args` and optional environment
  70. variables `env_vars` succeeds (rc == 0) and return a (return code, stdout,
  71. stderr) tuple.
  72. If the __cleanenv keyword is set, env_vars is used a fresh environment.
  73. Python is started in isolated mode (command line option -I),
  74. except if the __isolated keyword is set to False.
  75. """
  76. return _assert_python(True, *args, **env_vars)
  77. is_jython = sys.platform.startswith('java')
  78. def gc_collect():
  79. """Force as many objects as possible to be collected.
  80. In non-CPython implementations of Python, this is needed because timely
  81. deallocation is not guaranteed by the garbage collector. (Even in CPython
  82. this can be the case in case of reference cycles.) This means that __del__
  83. methods may be called later than expected and weakrefs may remain alive for
  84. longer than expected. This function tries its best to force all garbage
  85. objects to disappear.
  86. """
  87. gc.collect()
  88. if is_jython:
  89. time.sleep(0.1)
  90. gc.collect()
  91. gc.collect()
  92. HOST = "127.0.0.1"
  93. HOSTv6 = "::1"
  94. def _is_ipv6_enabled():
  95. """Check whether IPv6 is enabled on this host."""
  96. if socket.has_ipv6:
  97. sock = None
  98. try:
  99. sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  100. sock.bind((HOSTv6, 0))
  101. return True
  102. except OSError:
  103. pass
  104. finally:
  105. if sock:
  106. sock.close()
  107. return False
  108. IPV6_ENABLED = _is_ipv6_enabled()
  109. def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
  110. """Returns an unused port that should be suitable for binding. This is
  111. achieved by creating a temporary socket with the same family and type as
  112. the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
  113. the specified host address (defaults to 0.0.0.0) with the port set to 0,
  114. eliciting an unused ephemeral port from the OS. The temporary socket is
  115. then closed and deleted, and the ephemeral port is returned.
  116. Either this method or bind_port() should be used for any tests where a
  117. server socket needs to be bound to a particular port for the duration of
  118. the test. Which one to use depends on whether the calling code is creating
  119. a python socket, or if an unused port needs to be provided in a constructor
  120. or passed to an external program (i.e. the -accept argument to openssl's
  121. s_server mode). Always prefer bind_port() over find_unused_port() where
  122. possible. Hard coded ports should *NEVER* be used. As soon as a server
  123. socket is bound to a hard coded port, the ability to run multiple instances
  124. of the test simultaneously on the same host is compromised, which makes the
  125. test a ticking time bomb in a buildbot environment. On Unix buildbots, this
  126. may simply manifest as a failed test, which can be recovered from without
  127. intervention in most cases, but on Windows, the entire python process can
  128. completely and utterly wedge, requiring someone to log in to the buildbot
  129. and manually kill the affected process.
  130. (This is easy to reproduce on Windows, unfortunately, and can be traced to
  131. the SO_REUSEADDR socket option having different semantics on Windows versus
  132. Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
  133. listen and then accept connections on identical host/ports. An EADDRINUSE
  134. OSError will be raised at some point (depending on the platform and
  135. the order bind and listen were called on each socket).
  136. However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
  137. will ever be raised when attempting to bind two identical host/ports. When
  138. accept() is called on each socket, the second caller's process will steal
  139. the port from the first caller, leaving them both in an awkwardly wedged
  140. state where they'll no longer respond to any signals or graceful kills, and
  141. must be forcibly killed via OpenProcess()/TerminateProcess().
  142. The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
  143. instead of SO_REUSEADDR, which effectively affords the same semantics as
  144. SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
  145. Source world compared to Windows ones, this is a common mistake. A quick
  146. look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
  147. openssl.exe is called with the 's_server' option, for example. See
  148. http://bugs.python.org/issue2550 for more info. The following site also
  149. has a very thorough description about the implications of both REUSEADDR
  150. and EXCLUSIVEADDRUSE on Windows:
  151. http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
  152. XXX: although this approach is a vast improvement on previous attempts to
  153. elicit unused ports, it rests heavily on the assumption that the ephemeral
  154. port returned to us by the OS won't immediately be dished back out to some
  155. other process when we close and delete our temporary socket but before our
  156. calling code has a chance to bind the returned port. We can deal with this
  157. issue if/when we come across it.
  158. """
  159. tempsock = socket.socket(family, socktype)
  160. port = bind_port(tempsock)
  161. tempsock.close()
  162. del tempsock
  163. return port
  164. def bind_port(sock, host=HOST):
  165. """Bind the socket to a free port and return the port number. Relies on
  166. ephemeral ports in order to ensure we are using an unbound port. This is
  167. important as many tests may be running simultaneously, especially in a
  168. buildbot environment. This method raises an exception if the sock.family
  169. is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
  170. or SO_REUSEPORT set on it. Tests should *never* set these socket options
  171. for TCP/IP sockets. The only case for setting these options is testing
  172. multicasting via multiple UDP sockets.
  173. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
  174. on Windows), it will be set on the socket. This will prevent anyone else
  175. from bind()'ing to our host/port for the duration of the test.
  176. """
  177. if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
  178. if hasattr(socket, 'SO_REUSEADDR'):
  179. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
  180. raise TestFailed("tests should never set the SO_REUSEADDR "
  181. "socket option on TCP/IP sockets!")
  182. if hasattr(socket, 'SO_REUSEPORT'):
  183. try:
  184. reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT)
  185. if reuse == 1:
  186. raise TestFailed("tests should never set the SO_REUSEPORT "
  187. "socket option on TCP/IP sockets!")
  188. except OSError:
  189. # Python's socket module was compiled using modern headers
  190. # thus defining SO_REUSEPORT but this process is running
  191. # under an older kernel that does not support SO_REUSEPORT.
  192. pass
  193. if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
  194. sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  195. sock.bind((host, 0))
  196. port = sock.getsockname()[1]
  197. return port
  198. def requires_mac_ver(*min_version):
  199. """Decorator raising SkipTest if the OS is Mac OS X and the OS X
  200. version if less than min_version.
  201. For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
  202. is lesser than 10.5.
  203. """
  204. def decorator(func):
  205. @functools.wraps(func)
  206. def wrapper(*args, **kw):
  207. if sys.platform == 'darwin':
  208. version_txt = platform.mac_ver()[0]
  209. try:
  210. version = tuple(map(int, version_txt.split('.')))
  211. except ValueError:
  212. pass
  213. else:
  214. if version < min_version:
  215. min_version_txt = '.'.join(map(str, min_version))
  216. raise unittest.SkipTest(
  217. "Mac OS X %s or higher required, not %s"
  218. % (min_version_txt, version_txt))
  219. return func(*args, **kw)
  220. wrapper.min_version = min_version
  221. return wrapper
  222. return decorator
  223. def _requires_unix_version(sysname, min_version):
  224. """Decorator raising SkipTest if the OS is `sysname` and the version is
  225. less than `min_version`.
  226. For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
  227. the FreeBSD version is less than 7.2.
  228. """
  229. def decorator(func):
  230. @functools.wraps(func)
  231. def wrapper(*args, **kw):
  232. if platform.system() == sysname:
  233. version_txt = platform.release().split('-', 1)[0]
  234. try:
  235. version = tuple(map(int, version_txt.split('.')))
  236. except ValueError:
  237. pass
  238. else:
  239. if version < min_version:
  240. min_version_txt = '.'.join(map(str, min_version))
  241. raise unittest.SkipTest(
  242. "%s version %s or higher required, not %s"
  243. % (sysname, min_version_txt, version_txt))
  244. return func(*args, **kw)
  245. wrapper.min_version = min_version
  246. return wrapper
  247. return decorator
  248. def requires_freebsd_version(*min_version):
  249. """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version
  250. is less than `min_version`.
  251. For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
  252. version is less than 7.2.
  253. """
  254. return _requires_unix_version('FreeBSD', min_version)
  255. # Use test.support if available
  256. try:
  257. from test.support import *
  258. except ImportError:
  259. pass
  260. # Use test.script_helper if available
  261. try:
  262. from test.script_helper import assert_python_ok
  263. except ImportError:
  264. pass