PageRenderTime 51ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/test/test_support.py

https://bitbucket.org/dac_io/pypy
Python | 1233 lines | 1102 code | 50 blank | 81 comment | 68 complexity | a35a210ca2312cba5b8c233a8ccc9c49 MD5 | raw file
  1. """Supporting definitions for the Python regression tests."""
  2. if __name__ != 'test.test_support':
  3. raise ImportError('test_support must be imported from the test package')
  4. import contextlib
  5. import errno
  6. import functools
  7. import gc
  8. import socket
  9. import sys
  10. import os
  11. import platform
  12. import shutil
  13. import warnings
  14. import unittest
  15. import importlib
  16. import UserDict
  17. import re
  18. import time
  19. try:
  20. import thread
  21. except ImportError:
  22. thread = None
  23. __all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
  24. "verbose", "use_resources", "max_memuse", "record_original_stdout",
  25. "get_original_stdout", "unload", "unlink", "rmtree", "forget",
  26. "is_resource_enabled", "requires", "find_unused_port", "bind_port",
  27. "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ",
  28. "SAVEDCWD", "temp_cwd", "findfile", "sortdict", "check_syntax_error",
  29. "open_urlresource", "check_warnings", "check_py3k_warnings",
  30. "CleanImport", "EnvironmentVarGuard", "captured_output",
  31. "captured_stdout", "TransientResource", "transient_internet",
  32. "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
  33. "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
  34. "threading_cleanup", "reap_children", "cpython_only",
  35. "check_impl_detail", "get_attribute", "py3k_bytes",
  36. "import_fresh_module"]
  37. class Error(Exception):
  38. """Base class for regression test exceptions."""
  39. class TestFailed(Error):
  40. """Test failed."""
  41. class ResourceDenied(unittest.SkipTest):
  42. """Test skipped because it requested a disallowed resource.
  43. This is raised when a test calls requires() for a resource that
  44. has not been enabled. It is used to distinguish between expected
  45. and unexpected skips.
  46. """
  47. @contextlib.contextmanager
  48. def _ignore_deprecated_imports(ignore=True):
  49. """Context manager to suppress package and module deprecation
  50. warnings when importing them.
  51. If ignore is False, this context manager has no effect."""
  52. if ignore:
  53. with warnings.catch_warnings():
  54. warnings.filterwarnings("ignore", ".+ (module|package)",
  55. DeprecationWarning)
  56. yield
  57. else:
  58. yield
  59. def import_module(name, deprecated=False):
  60. """Import and return the module to be tested, raising SkipTest if
  61. it is not available.
  62. If deprecated is True, any module or package deprecation messages
  63. will be suppressed."""
  64. with _ignore_deprecated_imports(deprecated):
  65. try:
  66. return importlib.import_module(name)
  67. except ImportError, msg:
  68. raise unittest.SkipTest(str(msg))
  69. def _save_and_remove_module(name, orig_modules):
  70. """Helper function to save and remove a module from sys.modules
  71. Raise ImportError if the module can't be imported."""
  72. # try to import the module and raise an error if it can't be imported
  73. if name not in sys.modules:
  74. __import__(name)
  75. del sys.modules[name]
  76. for modname in list(sys.modules):
  77. if modname == name or modname.startswith(name + '.'):
  78. orig_modules[modname] = sys.modules[modname]
  79. del sys.modules[modname]
  80. def _save_and_block_module(name, orig_modules):
  81. """Helper function to save and block a module in sys.modules
  82. Return True if the module was in sys.modules, False otherwise."""
  83. saved = True
  84. try:
  85. orig_modules[name] = sys.modules[name]
  86. except KeyError:
  87. saved = False
  88. sys.modules[name] = None
  89. return saved
  90. def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
  91. """Imports and returns a module, deliberately bypassing the sys.modules cache
  92. and importing a fresh copy of the module. Once the import is complete,
  93. the sys.modules cache is restored to its original state.
  94. Modules named in fresh are also imported anew if needed by the import.
  95. If one of these modules can't be imported, None is returned.
  96. Importing of modules named in blocked is prevented while the fresh import
  97. takes place.
  98. If deprecated is True, any module or package deprecation messages
  99. will be suppressed."""
  100. # NOTE: test_heapq, test_json, and test_warnings include extra sanity
  101. # checks to make sure that this utility function is working as expected
  102. with _ignore_deprecated_imports(deprecated):
  103. # Keep track of modules saved for later restoration as well
  104. # as those which just need a blocking entry removed
  105. orig_modules = {}
  106. names_to_remove = []
  107. _save_and_remove_module(name, orig_modules)
  108. try:
  109. for fresh_name in fresh:
  110. _save_and_remove_module(fresh_name, orig_modules)
  111. for blocked_name in blocked:
  112. if not _save_and_block_module(blocked_name, orig_modules):
  113. names_to_remove.append(blocked_name)
  114. fresh_module = importlib.import_module(name)
  115. except ImportError:
  116. fresh_module = None
  117. finally:
  118. for orig_name, module in orig_modules.items():
  119. sys.modules[orig_name] = module
  120. for name_to_remove in names_to_remove:
  121. del sys.modules[name_to_remove]
  122. return fresh_module
  123. def get_attribute(obj, name):
  124. """Get an attribute, raising SkipTest if AttributeError is raised."""
  125. try:
  126. attribute = getattr(obj, name)
  127. except AttributeError:
  128. raise unittest.SkipTest("module %s has no attribute %s" % (
  129. obj.__name__, name))
  130. else:
  131. return attribute
  132. verbose = 1 # Flag set to 0 by regrtest.py
  133. use_resources = None # Flag set to [] by regrtest.py
  134. max_memuse = 0 # Disable bigmem tests (they will still be run with
  135. # small sizes, to make sure they work.)
  136. real_max_memuse = 0
  137. # _original_stdout is meant to hold stdout at the time regrtest began.
  138. # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
  139. # The point is to have some flavor of stdout the user can actually see.
  140. _original_stdout = None
  141. def record_original_stdout(stdout):
  142. global _original_stdout
  143. _original_stdout = stdout
  144. def get_original_stdout():
  145. return _original_stdout or sys.stdout
  146. def unload(name):
  147. try:
  148. del sys.modules[name]
  149. except KeyError:
  150. pass
  151. def unlink(filename):
  152. try:
  153. os.unlink(filename)
  154. except OSError:
  155. pass
  156. def rmtree(path):
  157. try:
  158. shutil.rmtree(path)
  159. except OSError, e:
  160. # Unix returns ENOENT, Windows returns ESRCH.
  161. if e.errno not in (errno.ENOENT, errno.ESRCH):
  162. raise
  163. def forget(modname):
  164. '''"Forget" a module was ever imported by removing it from sys.modules and
  165. deleting any .pyc and .pyo files.'''
  166. unload(modname)
  167. for dirname in sys.path:
  168. unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
  169. # Deleting the .pyo file cannot be within the 'try' for the .pyc since
  170. # the chance exists that there is no .pyc (and thus the 'try' statement
  171. # is exited) but there is a .pyo file.
  172. unlink(os.path.join(dirname, modname + os.extsep + 'pyo'))
  173. def is_resource_enabled(resource):
  174. """Test whether a resource is enabled. Known resources are set by
  175. regrtest.py."""
  176. return use_resources is not None and resource in use_resources
  177. def requires(resource, msg=None):
  178. """Raise ResourceDenied if the specified resource is not available.
  179. If the caller's module is __main__ then automatically return True. The
  180. possibility of False being returned occurs when regrtest.py is executing."""
  181. # see if the caller's module is __main__ - if so, treat as if
  182. # the resource was set
  183. if sys._getframe(1).f_globals.get("__name__") == "__main__":
  184. return
  185. if not is_resource_enabled(resource):
  186. if msg is None:
  187. msg = "Use of the `%s' resource not enabled" % resource
  188. raise ResourceDenied(msg)
  189. HOST = 'localhost'
  190. def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
  191. """Returns an unused port that should be suitable for binding. This is
  192. achieved by creating a temporary socket with the same family and type as
  193. the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
  194. the specified host address (defaults to 0.0.0.0) with the port set to 0,
  195. eliciting an unused ephemeral port from the OS. The temporary socket is
  196. then closed and deleted, and the ephemeral port is returned.
  197. Either this method or bind_port() should be used for any tests where a
  198. server socket needs to be bound to a particular port for the duration of
  199. the test. Which one to use depends on whether the calling code is creating
  200. a python socket, or if an unused port needs to be provided in a constructor
  201. or passed to an external program (i.e. the -accept argument to openssl's
  202. s_server mode). Always prefer bind_port() over find_unused_port() where
  203. possible. Hard coded ports should *NEVER* be used. As soon as a server
  204. socket is bound to a hard coded port, the ability to run multiple instances
  205. of the test simultaneously on the same host is compromised, which makes the
  206. test a ticking time bomb in a buildbot environment. On Unix buildbots, this
  207. may simply manifest as a failed test, which can be recovered from without
  208. intervention in most cases, but on Windows, the entire python process can
  209. completely and utterly wedge, requiring someone to log in to the buildbot
  210. and manually kill the affected process.
  211. (This is easy to reproduce on Windows, unfortunately, and can be traced to
  212. the SO_REUSEADDR socket option having different semantics on Windows versus
  213. Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
  214. listen and then accept connections on identical host/ports. An EADDRINUSE
  215. socket.error will be raised at some point (depending on the platform and
  216. the order bind and listen were called on each socket).
  217. However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
  218. will ever be raised when attempting to bind two identical host/ports. When
  219. accept() is called on each socket, the second caller's process will steal
  220. the port from the first caller, leaving them both in an awkwardly wedged
  221. state where they'll no longer respond to any signals or graceful kills, and
  222. must be forcibly killed via OpenProcess()/TerminateProcess().
  223. The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
  224. instead of SO_REUSEADDR, which effectively affords the same semantics as
  225. SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
  226. Source world compared to Windows ones, this is a common mistake. A quick
  227. look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
  228. openssl.exe is called with the 's_server' option, for example. See
  229. http://bugs.python.org/issue2550 for more info. The following site also
  230. has a very thorough description about the implications of both REUSEADDR
  231. and EXCLUSIVEADDRUSE on Windows:
  232. http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
  233. XXX: although this approach is a vast improvement on previous attempts to
  234. elicit unused ports, it rests heavily on the assumption that the ephemeral
  235. port returned to us by the OS won't immediately be dished back out to some
  236. other process when we close and delete our temporary socket but before our
  237. calling code has a chance to bind the returned port. We can deal with this
  238. issue if/when we come across it."""
  239. tempsock = socket.socket(family, socktype)
  240. port = bind_port(tempsock)
  241. tempsock.close()
  242. del tempsock
  243. return port
  244. def bind_port(sock, host=HOST):
  245. """Bind the socket to a free port and return the port number. Relies on
  246. ephemeral ports in order to ensure we are using an unbound port. This is
  247. important as many tests may be running simultaneously, especially in a
  248. buildbot environment. This method raises an exception if the sock.family
  249. is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
  250. or SO_REUSEPORT set on it. Tests should *never* set these socket options
  251. for TCP/IP sockets. The only case for setting these options is testing
  252. multicasting via multiple UDP sockets.
  253. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
  254. on Windows), it will be set on the socket. This will prevent anyone else
  255. from bind()'ing to our host/port for the duration of the test.
  256. """
  257. if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
  258. if hasattr(socket, 'SO_REUSEADDR'):
  259. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
  260. raise TestFailed("tests should never set the SO_REUSEADDR " \
  261. "socket option on TCP/IP sockets!")
  262. if hasattr(socket, 'SO_REUSEPORT'):
  263. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
  264. raise TestFailed("tests should never set the SO_REUSEPORT " \
  265. "socket option on TCP/IP sockets!")
  266. if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
  267. sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  268. sock.bind((host, 0))
  269. port = sock.getsockname()[1]
  270. return port
  271. FUZZ = 1e-6
  272. def fcmp(x, y): # fuzzy comparison function
  273. if isinstance(x, float) or isinstance(y, float):
  274. try:
  275. fuzz = (abs(x) + abs(y)) * FUZZ
  276. if abs(x-y) <= fuzz:
  277. return 0
  278. except:
  279. pass
  280. elif type(x) == type(y) and isinstance(x, (tuple, list)):
  281. for i in range(min(len(x), len(y))):
  282. outcome = fcmp(x[i], y[i])
  283. if outcome != 0:
  284. return outcome
  285. return (len(x) > len(y)) - (len(x) < len(y))
  286. return (x > y) - (x < y)
  287. try:
  288. unicode
  289. have_unicode = True
  290. except NameError:
  291. have_unicode = False
  292. is_jython = sys.platform.startswith('java')
  293. # Filename used for testing
  294. if os.name == 'java':
  295. # Jython disallows @ in module names
  296. TESTFN = '$test'
  297. elif os.name == 'riscos':
  298. TESTFN = 'testfile'
  299. else:
  300. TESTFN = '@test'
  301. # Unicode name only used if TEST_FN_ENCODING exists for the platform.
  302. if have_unicode:
  303. # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
  304. # TESTFN_UNICODE is a filename that can be encoded using the
  305. # file system encoding, but *not* with the default (ascii) encoding
  306. if isinstance('', unicode):
  307. # python -U
  308. # XXX perhaps unicode() should accept Unicode strings?
  309. TESTFN_UNICODE = "@test-\xe0\xf2"
  310. else:
  311. # 2 latin characters.
  312. TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1")
  313. TESTFN_ENCODING = sys.getfilesystemencoding()
  314. # TESTFN_UNENCODABLE is a filename that should *not* be
  315. # able to be encoded by *either* the default or filesystem encoding.
  316. # This test really only makes sense on Windows NT platforms
  317. # which have special Unicode support in posixmodule.
  318. if (not hasattr(sys, "getwindowsversion") or
  319. sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
  320. TESTFN_UNENCODABLE = None
  321. else:
  322. # Japanese characters (I think - from bug 846133)
  323. TESTFN_UNENCODABLE = eval('u"@test-\u5171\u6709\u3055\u308c\u308b"')
  324. try:
  325. # XXX - Note - should be using TESTFN_ENCODING here - but for
  326. # Windows, "mbcs" currently always operates as if in
  327. # errors=ignore' mode - hence we get '?' characters rather than
  328. # the exception. 'Latin1' operates as we expect - ie, fails.
  329. # See [ 850997 ] mbcs encoding ignores errors
  330. TESTFN_UNENCODABLE.encode("Latin1")
  331. except UnicodeEncodeError:
  332. pass
  333. else:
  334. print \
  335. 'WARNING: The filename %r CAN be encoded by the filesystem. ' \
  336. 'Unicode filename tests may not be effective' \
  337. % TESTFN_UNENCODABLE
  338. # Disambiguate TESTFN for parallel testing, while letting it remain a valid
  339. # module name.
  340. TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
  341. # Save the initial cwd
  342. SAVEDCWD = os.getcwd()
  343. @contextlib.contextmanager
  344. def temp_cwd(name='tempcwd', quiet=False):
  345. """
  346. Context manager that creates a temporary directory and set it as CWD.
  347. The new CWD is created in the current directory and it's named *name*.
  348. If *quiet* is False (default) and it's not possible to create or change
  349. the CWD, an error is raised. If it's True, only a warning is raised
  350. and the original CWD is used.
  351. """
  352. if isinstance(name, unicode):
  353. try:
  354. name = name.encode(sys.getfilesystemencoding() or 'ascii')
  355. except UnicodeEncodeError:
  356. if not quiet:
  357. raise unittest.SkipTest('unable to encode the cwd name with '
  358. 'the filesystem encoding.')
  359. saved_dir = os.getcwd()
  360. is_temporary = False
  361. try:
  362. os.mkdir(name)
  363. os.chdir(name)
  364. is_temporary = True
  365. except OSError:
  366. if not quiet:
  367. raise
  368. warnings.warn('tests may fail, unable to change the CWD to ' + name,
  369. RuntimeWarning, stacklevel=3)
  370. try:
  371. yield os.getcwd()
  372. finally:
  373. os.chdir(saved_dir)
  374. if is_temporary:
  375. rmtree(name)
  376. def findfile(file, here=__file__, subdir=None):
  377. """Try to find a file on sys.path and the working directory. If it is not
  378. found the argument passed to the function is returned (this does not
  379. necessarily signal failure; could still be the legitimate path)."""
  380. if os.path.isabs(file):
  381. return file
  382. if subdir is not None:
  383. file = os.path.join(subdir, file)
  384. path = sys.path
  385. path = [os.path.dirname(here)] + path
  386. for dn in path:
  387. fn = os.path.join(dn, file)
  388. if os.path.exists(fn): return fn
  389. return file
  390. def sortdict(dict):
  391. "Like repr(dict), but in sorted order."
  392. items = dict.items()
  393. items.sort()
  394. reprpairs = ["%r: %r" % pair for pair in items]
  395. withcommas = ", ".join(reprpairs)
  396. return "{%s}" % withcommas
  397. def make_bad_fd():
  398. """
  399. Create an invalid file descriptor by opening and closing a file and return
  400. its fd.
  401. """
  402. file = open(TESTFN, "wb")
  403. try:
  404. return file.fileno()
  405. finally:
  406. file.close()
  407. unlink(TESTFN)
  408. def check_syntax_error(testcase, statement):
  409. testcase.assertRaises(SyntaxError, compile, statement,
  410. '<test string>', 'exec')
  411. def open_urlresource(url, check=None):
  412. import urlparse, urllib2
  413. filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
  414. fn = os.path.join(os.path.dirname(__file__), "data", filename)
  415. def check_valid_file(fn):
  416. f = open(fn)
  417. if check is None:
  418. return f
  419. elif check(f):
  420. f.seek(0)
  421. return f
  422. f.close()
  423. if os.path.exists(fn):
  424. f = check_valid_file(fn)
  425. if f is not None:
  426. return f
  427. unlink(fn)
  428. # Verify the requirement before downloading the file
  429. requires('urlfetch')
  430. print >> get_original_stdout(), '\tfetching %s ...' % url
  431. f = urllib2.urlopen(url, timeout=15)
  432. try:
  433. with open(fn, "wb") as out:
  434. s = f.read()
  435. while s:
  436. out.write(s)
  437. s = f.read()
  438. finally:
  439. f.close()
  440. f = check_valid_file(fn)
  441. if f is not None:
  442. return f
  443. raise TestFailed('invalid resource "%s"' % fn)
  444. class WarningsRecorder(object):
  445. """Convenience wrapper for the warnings list returned on
  446. entry to the warnings.catch_warnings() context manager.
  447. """
  448. def __init__(self, warnings_list):
  449. self._warnings = warnings_list
  450. self._last = 0
  451. def __getattr__(self, attr):
  452. if len(self._warnings) > self._last:
  453. return getattr(self._warnings[-1], attr)
  454. elif attr in warnings.WarningMessage._WARNING_DETAILS:
  455. return None
  456. raise AttributeError("%r has no attribute %r" % (self, attr))
  457. @property
  458. def warnings(self):
  459. return self._warnings[self._last:]
  460. def reset(self):
  461. self._last = len(self._warnings)
  462. def _filterwarnings(filters, quiet=False):
  463. """Catch the warnings, then check if all the expected
  464. warnings have been raised and re-raise unexpected warnings.
  465. If 'quiet' is True, only re-raise the unexpected warnings.
  466. """
  467. # Clear the warning registry of the calling module
  468. # in order to re-raise the warnings.
  469. frame = sys._getframe(2)
  470. registry = frame.f_globals.get('__warningregistry__')
  471. if registry:
  472. registry.clear()
  473. with warnings.catch_warnings(record=True) as w:
  474. # Set filter "always" to record all warnings. Because
  475. # test_warnings swap the module, we need to look up in
  476. # the sys.modules dictionary.
  477. sys.modules['warnings'].simplefilter("always")
  478. yield WarningsRecorder(w)
  479. # Filter the recorded warnings
  480. reraise = [warning.message for warning in w]
  481. missing = []
  482. for msg, cat in filters:
  483. seen = False
  484. for exc in reraise[:]:
  485. message = str(exc)
  486. # Filter out the matching messages
  487. if (re.match(msg, message, re.I) and
  488. issubclass(exc.__class__, cat)):
  489. seen = True
  490. reraise.remove(exc)
  491. if not seen and not quiet:
  492. # This filter caught nothing
  493. missing.append((msg, cat.__name__))
  494. if reraise:
  495. raise AssertionError("unhandled warning %r" % reraise[0])
  496. if missing:
  497. raise AssertionError("filter (%r, %s) did not catch any warning" %
  498. missing[0])
  499. @contextlib.contextmanager
  500. def check_warnings(*filters, **kwargs):
  501. """Context manager to silence warnings.
  502. Accept 2-tuples as positional arguments:
  503. ("message regexp", WarningCategory)
  504. Optional argument:
  505. - if 'quiet' is True, it does not fail if a filter catches nothing
  506. (default True without argument,
  507. default False if some filters are defined)
  508. Without argument, it defaults to:
  509. check_warnings(("", Warning), quiet=True)
  510. """
  511. quiet = kwargs.get('quiet')
  512. if not filters:
  513. filters = (("", Warning),)
  514. # Preserve backward compatibility
  515. if quiet is None:
  516. quiet = True
  517. return _filterwarnings(filters, quiet)
  518. @contextlib.contextmanager
  519. def check_py3k_warnings(*filters, **kwargs):
  520. """Context manager to silence py3k warnings.
  521. Accept 2-tuples as positional arguments:
  522. ("message regexp", WarningCategory)
  523. Optional argument:
  524. - if 'quiet' is True, it does not fail if a filter catches nothing
  525. (default False)
  526. Without argument, it defaults to:
  527. check_py3k_warnings(("", DeprecationWarning), quiet=False)
  528. """
  529. if sys.py3kwarning:
  530. if not filters:
  531. filters = (("", DeprecationWarning),)
  532. else:
  533. # It should not raise any py3k warning
  534. filters = ()
  535. return _filterwarnings(filters, kwargs.get('quiet'))
  536. class CleanImport(object):
  537. """Context manager to force import to return a new module reference.
  538. This is useful for testing module-level behaviours, such as
  539. the emission of a DeprecationWarning on import.
  540. Use like this:
  541. with CleanImport("foo"):
  542. importlib.import_module("foo") # new reference
  543. """
  544. def __init__(self, *module_names):
  545. self.original_modules = sys.modules.copy()
  546. for module_name in module_names:
  547. if module_name in sys.modules:
  548. module = sys.modules[module_name]
  549. # It is possible that module_name is just an alias for
  550. # another module (e.g. stub for modules renamed in 3.x).
  551. # In that case, we also need delete the real module to clear
  552. # the import cache.
  553. if module.__name__ != module_name:
  554. del sys.modules[module.__name__]
  555. del sys.modules[module_name]
  556. def __enter__(self):
  557. return self
  558. def __exit__(self, *ignore_exc):
  559. sys.modules.update(self.original_modules)
  560. class EnvironmentVarGuard(UserDict.DictMixin):
  561. """Class to help protect the environment variable properly. Can be used as
  562. a context manager."""
  563. def __init__(self):
  564. self._environ = os.environ
  565. self._changed = {}
  566. def __getitem__(self, envvar):
  567. return self._environ[envvar]
  568. def __setitem__(self, envvar, value):
  569. # Remember the initial value on the first access
  570. if envvar not in self._changed:
  571. self._changed[envvar] = self._environ.get(envvar)
  572. self._environ[envvar] = value
  573. def __delitem__(self, envvar):
  574. # Remember the initial value on the first access
  575. if envvar not in self._changed:
  576. self._changed[envvar] = self._environ.get(envvar)
  577. if envvar in self._environ:
  578. del self._environ[envvar]
  579. def keys(self):
  580. return self._environ.keys()
  581. def set(self, envvar, value):
  582. self[envvar] = value
  583. def unset(self, envvar):
  584. del self[envvar]
  585. def __enter__(self):
  586. return self
  587. def __exit__(self, *ignore_exc):
  588. for (k, v) in self._changed.items():
  589. if v is None:
  590. if k in self._environ:
  591. del self._environ[k]
  592. else:
  593. self._environ[k] = v
  594. os.environ = self._environ
  595. class DirsOnSysPath(object):
  596. """Context manager to temporarily add directories to sys.path.
  597. This makes a copy of sys.path, appends any directories given
  598. as positional arguments, then reverts sys.path to the copied
  599. settings when the context ends.
  600. Note that *all* sys.path modifications in the body of the
  601. context manager, including replacement of the object,
  602. will be reverted at the end of the block.
  603. """
  604. def __init__(self, *paths):
  605. self.original_value = sys.path[:]
  606. self.original_object = sys.path
  607. sys.path.extend(paths)
  608. def __enter__(self):
  609. return self
  610. def __exit__(self, *ignore_exc):
  611. sys.path = self.original_object
  612. sys.path[:] = self.original_value
  613. class TransientResource(object):
  614. """Raise ResourceDenied if an exception is raised while the context manager
  615. is in effect that matches the specified exception and attributes."""
  616. def __init__(self, exc, **kwargs):
  617. self.exc = exc
  618. self.attrs = kwargs
  619. def __enter__(self):
  620. return self
  621. def __exit__(self, type_=None, value=None, traceback=None):
  622. """If type_ is a subclass of self.exc and value has attributes matching
  623. self.attrs, raise ResourceDenied. Otherwise let the exception
  624. propagate (if any)."""
  625. if type_ is not None and issubclass(self.exc, type_):
  626. for attr, attr_value in self.attrs.iteritems():
  627. if not hasattr(value, attr):
  628. break
  629. if getattr(value, attr) != attr_value:
  630. break
  631. else:
  632. raise ResourceDenied("an optional resource is not available")
  633. @contextlib.contextmanager
  634. def transient_internet(resource_name, timeout=30.0, errnos=()):
  635. """Return a context manager that raises ResourceDenied when various issues
  636. with the Internet connection manifest themselves as exceptions."""
  637. default_errnos = [
  638. ('ECONNREFUSED', 111),
  639. ('ECONNRESET', 104),
  640. ('EHOSTUNREACH', 113),
  641. ('ENETUNREACH', 101),
  642. ('ETIMEDOUT', 110),
  643. ]
  644. default_gai_errnos = [
  645. ('EAI_NONAME', -2),
  646. ('EAI_NODATA', -5),
  647. ]
  648. denied = ResourceDenied("Resource '%s' is not available" % resource_name)
  649. captured_errnos = errnos
  650. gai_errnos = []
  651. if not captured_errnos:
  652. captured_errnos = [getattr(errno, name, num)
  653. for (name, num) in default_errnos]
  654. gai_errnos = [getattr(socket, name, num)
  655. for (name, num) in default_gai_errnos]
  656. def filter_error(err):
  657. n = getattr(err, 'errno', None)
  658. if (isinstance(err, socket.timeout) or
  659. (isinstance(err, socket.gaierror) and n in gai_errnos) or
  660. n in captured_errnos):
  661. if not verbose:
  662. sys.stderr.write(denied.args[0] + "\n")
  663. raise denied
  664. old_timeout = socket.getdefaulttimeout()
  665. try:
  666. if timeout is not None:
  667. socket.setdefaulttimeout(timeout)
  668. yield
  669. except IOError as err:
  670. # urllib can wrap original socket errors multiple times (!), we must
  671. # unwrap to get at the original error.
  672. while True:
  673. a = err.args
  674. if len(a) >= 1 and isinstance(a[0], IOError):
  675. err = a[0]
  676. # The error can also be wrapped as args[1]:
  677. # except socket.error as msg:
  678. # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
  679. elif len(a) >= 2 and isinstance(a[1], IOError):
  680. err = a[1]
  681. else:
  682. break
  683. filter_error(err)
  684. raise
  685. # XXX should we catch generic exceptions and look for their
  686. # __cause__ or __context__?
  687. finally:
  688. socket.setdefaulttimeout(old_timeout)
  689. @contextlib.contextmanager
  690. def captured_output(stream_name):
  691. """Return a context manager used by captured_stdout and captured_stdin
  692. that temporarily replaces the sys stream *stream_name* with a StringIO."""
  693. import StringIO
  694. orig_stdout = getattr(sys, stream_name)
  695. setattr(sys, stream_name, StringIO.StringIO())
  696. try:
  697. yield getattr(sys, stream_name)
  698. finally:
  699. setattr(sys, stream_name, orig_stdout)
  700. def captured_stdout():
  701. """Capture the output of sys.stdout:
  702. with captured_stdout() as s:
  703. print "hello"
  704. self.assertEqual(s.getvalue(), "hello")
  705. """
  706. return captured_output("stdout")
  707. def captured_stdin():
  708. return captured_output("stdin")
  709. def gc_collect():
  710. """Force as many objects as possible to be collected.
  711. In non-CPython implementations of Python, this is needed because timely
  712. deallocation is not guaranteed by the garbage collector. (Even in CPython
  713. this can be the case in case of reference cycles.) This means that __del__
  714. methods may be called later than expected and weakrefs may remain alive for
  715. longer than expected. This function tries its best to force all garbage
  716. objects to disappear.
  717. """
  718. gc.collect()
  719. if is_jython:
  720. time.sleep(0.1)
  721. gc.collect()
  722. gc.collect()
  723. #=======================================================================
  724. # Decorator for running a function in a different locale, correctly resetting
  725. # it afterwards.
  726. def run_with_locale(catstr, *locales):
  727. def decorator(func):
  728. def inner(*args, **kwds):
  729. try:
  730. import locale
  731. category = getattr(locale, catstr)
  732. orig_locale = locale.setlocale(category)
  733. except AttributeError:
  734. # if the test author gives us an invalid category string
  735. raise
  736. except:
  737. # cannot retrieve original locale, so do nothing
  738. locale = orig_locale = None
  739. else:
  740. for loc in locales:
  741. try:
  742. locale.setlocale(category, loc)
  743. break
  744. except:
  745. pass
  746. # now run the function, resetting the locale on exceptions
  747. try:
  748. return func(*args, **kwds)
  749. finally:
  750. if locale and orig_locale:
  751. locale.setlocale(category, orig_locale)
  752. inner.func_name = func.func_name
  753. inner.__doc__ = func.__doc__
  754. return inner
  755. return decorator
  756. #=======================================================================
  757. # Big-memory-test support. Separate from 'resources' because memory use should be configurable.
  758. # Some handy shorthands. Note that these are used for byte-limits as well
  759. # as size-limits, in the various bigmem tests
  760. _1M = 1024*1024
  761. _1G = 1024 * _1M
  762. _2G = 2 * _1G
  763. _4G = 4 * _1G
  764. MAX_Py_ssize_t = sys.maxsize
  765. def set_memlimit(limit):
  766. global max_memuse
  767. global real_max_memuse
  768. sizes = {
  769. 'k': 1024,
  770. 'm': _1M,
  771. 'g': _1G,
  772. 't': 1024*_1G,
  773. }
  774. m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
  775. re.IGNORECASE | re.VERBOSE)
  776. if m is None:
  777. raise ValueError('Invalid memory limit %r' % (limit,))
  778. memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
  779. real_max_memuse = memlimit
  780. if memlimit > MAX_Py_ssize_t:
  781. memlimit = MAX_Py_ssize_t
  782. if memlimit < _2G - 1:
  783. raise ValueError('Memory limit %r too low to be useful' % (limit,))
  784. max_memuse = memlimit
  785. def bigmemtest(minsize, memuse, overhead=5*_1M):
  786. """Decorator for bigmem tests.
  787. 'minsize' is the minimum useful size for the test (in arbitrary,
  788. test-interpreted units.) 'memuse' is the number of 'bytes per size' for
  789. the test, or a good estimate of it. 'overhead' specifies fixed overhead,
  790. independent of the testsize, and defaults to 5Mb.
  791. The decorator tries to guess a good value for 'size' and passes it to
  792. the decorated test function. If minsize * memuse is more than the
  793. allowed memory use (as defined by max_memuse), the test is skipped.
  794. Otherwise, minsize is adjusted upward to use up to max_memuse.
  795. """
  796. def decorator(f):
  797. def wrapper(self):
  798. if not max_memuse:
  799. # If max_memuse is 0 (the default),
  800. # we still want to run the tests with size set to a few kb,
  801. # to make sure they work. We still want to avoid using
  802. # too much memory, though, but we do that noisily.
  803. maxsize = 5147
  804. self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
  805. else:
  806. maxsize = int((max_memuse - overhead) / memuse)
  807. if maxsize < minsize:
  808. # Really ought to print 'test skipped' or something
  809. if verbose:
  810. sys.stderr.write("Skipping %s because of memory "
  811. "constraint\n" % (f.__name__,))
  812. return
  813. # Try to keep some breathing room in memory use
  814. maxsize = max(maxsize - 50 * _1M, minsize)
  815. return f(self, maxsize)
  816. wrapper.minsize = minsize
  817. wrapper.memuse = memuse
  818. wrapper.overhead = overhead
  819. return wrapper
  820. return decorator
  821. def precisionbigmemtest(size, memuse, overhead=5*_1M):
  822. def decorator(f):
  823. def wrapper(self):
  824. if not real_max_memuse:
  825. maxsize = 5147
  826. else:
  827. maxsize = size
  828. if real_max_memuse and real_max_memuse < maxsize * memuse:
  829. if verbose:
  830. sys.stderr.write("Skipping %s because of memory "
  831. "constraint\n" % (f.__name__,))
  832. return
  833. return f(self, maxsize)
  834. wrapper.size = size
  835. wrapper.memuse = memuse
  836. wrapper.overhead = overhead
  837. return wrapper
  838. return decorator
  839. def bigaddrspacetest(f):
  840. """Decorator for tests that fill the address space."""
  841. def wrapper(self):
  842. if max_memuse < MAX_Py_ssize_t:
  843. if verbose:
  844. sys.stderr.write("Skipping %s because of memory "
  845. "constraint\n" % (f.__name__,))
  846. else:
  847. return f(self)
  848. return wrapper
  849. #=======================================================================
  850. # unittest integration.
  851. class BasicTestRunner:
  852. def run(self, test):
  853. result = unittest.TestResult()
  854. test(result)
  855. return result
  856. def _id(obj):
  857. return obj
  858. def requires_resource(resource):
  859. if is_resource_enabled(resource):
  860. return _id
  861. else:
  862. return unittest.skip("resource {0!r} is not enabled".format(resource))
  863. def cpython_only(test):
  864. """
  865. Decorator for tests only applicable on CPython.
  866. """
  867. return impl_detail(cpython=True)(test)
  868. def impl_detail(msg=None, **guards):
  869. if check_impl_detail(**guards):
  870. return _id
  871. if msg is None:
  872. guardnames, default = _parse_guards(guards)
  873. if default:
  874. msg = "implementation detail not available on {0}"
  875. else:
  876. msg = "implementation detail specific to {0}"
  877. guardnames = sorted(guardnames.keys())
  878. msg = msg.format(' or '.join(guardnames))
  879. return unittest.skip(msg)
  880. def _parse_guards(guards):
  881. # Returns a tuple ({platform_name: run_me}, default_value)
  882. if not guards:
  883. return ({'cpython': True}, False)
  884. is_true = guards.values()[0]
  885. assert guards.values() == [is_true] * len(guards) # all True or all False
  886. return (guards, not is_true)
  887. # Use the following check to guard CPython's implementation-specific tests --
  888. # or to run them only on the implementation(s) guarded by the arguments.
  889. def check_impl_detail(**guards):
  890. """This function returns True or False depending on the host platform.
  891. Examples:
  892. if check_impl_detail(): # only on CPython (default)
  893. if check_impl_detail(jython=True): # only on Jython
  894. if check_impl_detail(cpython=False): # everywhere except on CPython
  895. """
  896. guards, default = _parse_guards(guards)
  897. return guards.get(platform.python_implementation().lower(), default)
  898. def _run_suite(suite):
  899. """Run tests from a unittest.TestSuite-derived class."""
  900. if verbose:
  901. runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
  902. else:
  903. runner = BasicTestRunner()
  904. result = runner.run(suite)
  905. if not result.wasSuccessful():
  906. if len(result.errors) == 1 and not result.failures:
  907. err = result.errors[0][1]
  908. elif len(result.failures) == 1 and not result.errors:
  909. err = result.failures[0][1]
  910. else:
  911. err = "multiple errors occurred"
  912. if not verbose:
  913. err += "; run in verbose mode for details"
  914. raise TestFailed(err)
  915. def run_unittest(*classes):
  916. """Run tests from unittest.TestCase-derived classes."""
  917. valid_types = (unittest.TestSuite, unittest.TestCase)
  918. suite = unittest.TestSuite()
  919. for cls in classes:
  920. if isinstance(cls, str):
  921. if cls in sys.modules:
  922. suite.addTest(unittest.findTestCases(sys.modules[cls]))
  923. else:
  924. raise ValueError("str arguments must be keys in sys.modules")
  925. elif isinstance(cls, valid_types):
  926. suite.addTest(cls)
  927. else:
  928. suite.addTest(unittest.makeSuite(cls))
  929. _run_suite(suite)
  930. #=======================================================================
  931. # doctest driver.
  932. def run_doctest(module, verbosity=None):
  933. """Run doctest on the given module. Return (#failures, #tests).
  934. If optional argument verbosity is not specified (or is None), pass
  935. test_support's belief about verbosity on to doctest. Else doctest's
  936. usual behavior is used (it searches sys.argv for -v).
  937. """
  938. import doctest
  939. if verbosity is None:
  940. verbosity = verbose
  941. else:
  942. verbosity = None
  943. # Direct doctest output (normally just errors) to real stdout; doctest
  944. # output shouldn't be compared by regrtest.
  945. save_stdout = sys.stdout
  946. sys.stdout = get_original_stdout()
  947. try:
  948. f, t = doctest.testmod(module, verbose=verbosity)
  949. if f:
  950. raise TestFailed("%d of %d doctests failed" % (f, t))
  951. finally:
  952. sys.stdout = save_stdout
  953. if verbose:
  954. print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
  955. return f, t
  956. #=======================================================================
  957. # Threading support to prevent reporting refleaks when running regrtest.py -R
  958. # NOTE: we use thread._count() rather than threading.enumerate() (or the
  959. # moral equivalent thereof) because a threading.Thread object is still alive
  960. # until its __bootstrap() method has returned, even after it has been
  961. # unregistered from the threading module.
  962. # thread._count(), on the other hand, only gets decremented *after* the
  963. # __bootstrap() method has returned, which gives us reliable reference counts
  964. # at the end of a test run.
  965. def threading_setup():
  966. if thread:
  967. return thread._count(),
  968. else:
  969. return 1,
  970. def threading_cleanup(nb_threads):
  971. if not thread:
  972. return
  973. _MAX_COUNT = 10
  974. for count in range(_MAX_COUNT):
  975. n = thread._count()
  976. if n == nb_threads:
  977. break
  978. time.sleep(0.1)
  979. # XXX print a warning in case of failure?
  980. def reap_threads(func):
  981. """Use this function when threads are being used. This will
  982. ensure that the threads are cleaned up even when the test fails.
  983. If threading is unavailable this function does nothing.
  984. """
  985. if not thread:
  986. return func
  987. @functools.wraps(func)
  988. def decorator(*args):
  989. key = threading_setup()
  990. try:
  991. return func(*args)
  992. finally:
  993. threading_cleanup(*key)
  994. return decorator
  995. def reap_children():
  996. """Use this function at the end of test_main() whenever sub-processes
  997. are started. This will help ensure that no extra children (zombies)
  998. stick around to hog resources and create problems when looking
  999. for refleaks.
  1000. """
  1001. # Reap all our dead child processes so we don't leave zombies around.
  1002. # These hog resources and might be causing some of the buildbots to die.
  1003. if hasattr(os, 'waitpid'):
  1004. any_process = -1
  1005. while True:
  1006. try:
  1007. # This will raise an exception on Windows. That's ok.
  1008. pid, status = os.waitpid(any_process, os.WNOHANG)
  1009. if pid == 0:
  1010. break
  1011. except:
  1012. break
  1013. def py3k_bytes(b):
  1014. """Emulate the py3k bytes() constructor.
  1015. NOTE: This is only a best effort function.
  1016. """
  1017. try:
  1018. # memoryview?
  1019. return b.tobytes()
  1020. except AttributeError:
  1021. try:
  1022. # iterable of ints?
  1023. return b"".join(chr(x) for x in b)
  1024. except TypeError:
  1025. return bytes(b)
  1026. def args_from_interpreter_flags():
  1027. """Return a list of command-line arguments reproducing the current
  1028. settings in sys.flags."""
  1029. flag_opt_map = {
  1030. 'bytes_warning': 'b',
  1031. 'dont_write_bytecode': 'B',
  1032. 'ignore_environment': 'E',
  1033. 'no_user_site': 's',
  1034. 'no_site': 'S',
  1035. 'optimize': 'O',
  1036. 'py3k_warning': '3',
  1037. 'verbose': 'v',
  1038. }
  1039. args = []
  1040. for flag, opt in flag_opt_map.items():
  1041. v = getattr(sys.flags, flag)
  1042. if v > 0:
  1043. args.append('-' + opt * v)
  1044. return args
  1045. def strip_python_stderr(stderr):
  1046. """Strip the stderr of a Python process from potential debug output
  1047. emitted by the interpreter.
  1048. This will typically be run on the result of the communicate() method
  1049. of a subprocess.Popen object.
  1050. """
  1051. stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
  1052. return stderr