PageRenderTime 65ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/dac_io/pypy
Python | 1284 lines | 1136 code | 57 blank | 91 comment | 77 complexity | 2a0b61f6f6c5e4ad6a0348bea8f85249 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=None, 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. import test
  381. if os.path.isabs(file):
  382. return file
  383. if subdir is not None:
  384. file = os.path.join(subdir, file)
  385. path = sys.path
  386. if here is None:
  387. path = test.__path__ + path
  388. else:
  389. path = [os.path.dirname(here)] + path
  390. for dn in path:
  391. fn = os.path.join(dn, file)
  392. if os.path.exists(fn): return fn
  393. return file
  394. def sortdict(dict):
  395. "Like repr(dict), but in sorted order."
  396. items = dict.items()
  397. items.sort()
  398. reprpairs = ["%r: %r" % pair for pair in items]
  399. withcommas = ", ".join(reprpairs)
  400. return "{%s}" % withcommas
  401. def make_bad_fd():
  402. """
  403. Create an invalid file descriptor by opening and closing a file and return
  404. its fd.
  405. """
  406. file = open(TESTFN, "wb")
  407. try:
  408. return file.fileno()
  409. finally:
  410. file.close()
  411. unlink(TESTFN)
  412. def check_syntax_error(testcase, statement):
  413. testcase.assertRaises(SyntaxError, compile, statement,
  414. '<test string>', 'exec')
  415. def open_urlresource(url, check=None):
  416. import urlparse, urllib2
  417. filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
  418. fn = os.path.join(os.path.dirname(__file__), "data", filename)
  419. def check_valid_file(fn):
  420. f = open(fn)
  421. if check is None:
  422. return f
  423. elif check(f):
  424. f.seek(0)
  425. return f
  426. f.close()
  427. if os.path.exists(fn):
  428. f = check_valid_file(fn)
  429. if f is not None:
  430. return f
  431. unlink(fn)
  432. # Verify the requirement before downloading the file
  433. requires('urlfetch')
  434. print >> get_original_stdout(), '\tfetching %s ...' % url
  435. f = urllib2.urlopen(url, timeout=15)
  436. try:
  437. with open(fn, "wb") as out:
  438. s = f.read()
  439. while s:
  440. out.write(s)
  441. s = f.read()
  442. finally:
  443. f.close()
  444. f = check_valid_file(fn)
  445. if f is not None:
  446. return f
  447. raise TestFailed('invalid resource "%s"' % fn)
  448. class WarningsRecorder(object):
  449. """Convenience wrapper for the warnings list returned on
  450. entry to the warnings.catch_warnings() context manager.
  451. """
  452. def __init__(self, warnings_list):
  453. self._warnings = warnings_list
  454. self._last = 0
  455. def __getattr__(self, attr):
  456. if len(self._warnings) > self._last:
  457. return getattr(self._warnings[-1], attr)
  458. elif attr in warnings.WarningMessage._WARNING_DETAILS:
  459. return None
  460. raise AttributeError("%r has no attribute %r" % (self, attr))
  461. @property
  462. def warnings(self):
  463. return self._warnings[self._last:]
  464. def reset(self):
  465. self._last = len(self._warnings)
  466. def _filterwarnings(filters, quiet=False):
  467. """Catch the warnings, then check if all the expected
  468. warnings have been raised and re-raise unexpected warnings.
  469. If 'quiet' is True, only re-raise the unexpected warnings.
  470. """
  471. # Clear the warning registry of the calling module
  472. # in order to re-raise the warnings.
  473. frame = sys._getframe(2)
  474. registry = frame.f_globals.get('__warningregistry__')
  475. if registry:
  476. registry.clear()
  477. with warnings.catch_warnings(record=True) as w:
  478. # Set filter "always" to record all warnings. Because
  479. # test_warnings swap the module, we need to look up in
  480. # the sys.modules dictionary.
  481. sys.modules['warnings'].simplefilter("always")
  482. yield WarningsRecorder(w)
  483. # Filter the recorded warnings
  484. reraise = [warning.message for warning in w]
  485. missing = []
  486. for msg, cat in filters:
  487. seen = False
  488. for exc in reraise[:]:
  489. message = str(exc)
  490. # Filter out the matching messages
  491. if (re.match(msg, message, re.I) and
  492. issubclass(exc.__class__, cat)):
  493. seen = True
  494. reraise.remove(exc)
  495. if not seen and not quiet:
  496. # This filter caught nothing
  497. missing.append((msg, cat.__name__))
  498. if reraise:
  499. raise AssertionError("unhandled warning %r" % reraise[0])
  500. if missing:
  501. raise AssertionError("filter (%r, %s) did not catch any warning" %
  502. missing[0])
  503. @contextlib.contextmanager
  504. def check_warnings(*filters, **kwargs):
  505. """Context manager to silence warnings.
  506. Accept 2-tuples as positional arguments:
  507. ("message regexp", WarningCategory)
  508. Optional argument:
  509. - if 'quiet' is True, it does not fail if a filter catches nothing
  510. (default True without argument,
  511. default False if some filters are defined)
  512. Without argument, it defaults to:
  513. check_warnings(("", Warning), quiet=True)
  514. """
  515. quiet = kwargs.get('quiet')
  516. if not filters:
  517. filters = (("", Warning),)
  518. # Preserve backward compatibility
  519. if quiet is None:
  520. quiet = True
  521. return _filterwarnings(filters, quiet)
  522. @contextlib.contextmanager
  523. def check_py3k_warnings(*filters, **kwargs):
  524. """Context manager to silence py3k warnings.
  525. Accept 2-tuples as positional arguments:
  526. ("message regexp", WarningCategory)
  527. Optional argument:
  528. - if 'quiet' is True, it does not fail if a filter catches nothing
  529. (default False)
  530. Without argument, it defaults to:
  531. check_py3k_warnings(("", DeprecationWarning), quiet=False)
  532. """
  533. if sys.py3kwarning:
  534. if not filters:
  535. filters = (("", DeprecationWarning),)
  536. else:
  537. # It should not raise any py3k warning
  538. filters = ()
  539. return _filterwarnings(filters, kwargs.get('quiet'))
  540. class CleanImport(object):
  541. """Context manager to force import to return a new module reference.
  542. This is useful for testing module-level behaviours, such as
  543. the emission of a DeprecationWarning on import.
  544. Use like this:
  545. with CleanImport("foo"):
  546. importlib.import_module("foo") # new reference
  547. """
  548. def __init__(self, *module_names):
  549. self.original_modules = sys.modules.copy()
  550. for module_name in module_names:
  551. if module_name in sys.modules:
  552. module = sys.modules[module_name]
  553. # It is possible that module_name is just an alias for
  554. # another module (e.g. stub for modules renamed in 3.x).
  555. # In that case, we also need delete the real module to clear
  556. # the import cache.
  557. if module.__name__ != module_name:
  558. del sys.modules[module.__name__]
  559. del sys.modules[module_name]
  560. def __enter__(self):
  561. return self
  562. def __exit__(self, *ignore_exc):
  563. sys.modules.update(self.original_modules)
  564. class EnvironmentVarGuard(UserDict.DictMixin):
  565. """Class to help protect the environment variable properly. Can be used as
  566. a context manager."""
  567. def __init__(self):
  568. self._environ = os.environ
  569. self._changed = {}
  570. def __getitem__(self, envvar):
  571. return self._environ[envvar]
  572. def __setitem__(self, envvar, value):
  573. # Remember the initial value on the first access
  574. if envvar not in self._changed:
  575. self._changed[envvar] = self._environ.get(envvar)
  576. self._environ[envvar] = value
  577. def __delitem__(self, envvar):
  578. # Remember the initial value on the first access
  579. if envvar not in self._changed:
  580. self._changed[envvar] = self._environ.get(envvar)
  581. if envvar in self._environ:
  582. del self._environ[envvar]
  583. def keys(self):
  584. return self._environ.keys()
  585. def set(self, envvar, value):
  586. self[envvar] = value
  587. def unset(self, envvar):
  588. del self[envvar]
  589. def __enter__(self):
  590. return self
  591. def __exit__(self, *ignore_exc):
  592. for (k, v) in self._changed.items():
  593. if v is None:
  594. if k in self._environ:
  595. del self._environ[k]
  596. else:
  597. self._environ[k] = v
  598. os.environ = self._environ
  599. class DirsOnSysPath(object):
  600. """Context manager to temporarily add directories to sys.path.
  601. This makes a copy of sys.path, appends any directories given
  602. as positional arguments, then reverts sys.path to the copied
  603. settings when the context ends.
  604. Note that *all* sys.path modifications in the body of the
  605. context manager, including replacement of the object,
  606. will be reverted at the end of the block.
  607. """
  608. def __init__(self, *paths):
  609. self.original_value = sys.path[:]
  610. self.original_object = sys.path
  611. sys.path.extend(paths)
  612. def __enter__(self):
  613. return self
  614. def __exit__(self, *ignore_exc):
  615. sys.path = self.original_object
  616. sys.path[:] = self.original_value
  617. class TransientResource(object):
  618. """Raise ResourceDenied if an exception is raised while the context manager
  619. is in effect that matches the specified exception and attributes."""
  620. def __init__(self, exc, **kwargs):
  621. self.exc = exc
  622. self.attrs = kwargs
  623. def __enter__(self):
  624. return self
  625. def __exit__(self, type_=None, value=None, traceback=None):
  626. """If type_ is a subclass of self.exc and value has attributes matching
  627. self.attrs, raise ResourceDenied. Otherwise let the exception
  628. propagate (if any)."""
  629. if type_ is not None and issubclass(self.exc, type_):
  630. for attr, attr_value in self.attrs.iteritems():
  631. if not hasattr(value, attr):
  632. break
  633. if getattr(value, attr) != attr_value:
  634. break
  635. else:
  636. raise ResourceDenied("an optional resource is not available")
  637. @contextlib.contextmanager
  638. def transient_internet(resource_name, timeout=30.0, errnos=()):
  639. """Return a context manager that raises ResourceDenied when various issues
  640. with the Internet connection manifest themselves as exceptions."""
  641. default_errnos = [
  642. ('ECONNREFUSED', 111),
  643. ('ECONNRESET', 104),
  644. ('EHOSTUNREACH', 113),
  645. ('ENETUNREACH', 101),
  646. ('ETIMEDOUT', 110),
  647. ]
  648. default_gai_errnos = [
  649. ('EAI_NONAME', -2),
  650. ('EAI_NODATA', -5),
  651. ]
  652. denied = ResourceDenied("Resource '%s' is not available" % resource_name)
  653. captured_errnos = errnos
  654. gai_errnos = []
  655. if not captured_errnos:
  656. captured_errnos = [getattr(errno, name, num)
  657. for (name, num) in default_errnos]
  658. gai_errnos = [getattr(socket, name, num)
  659. for (name, num) in default_gai_errnos]
  660. def filter_error(err):
  661. n = getattr(err, 'errno', None)
  662. if (isinstance(err, socket.timeout) or
  663. (isinstance(err, socket.gaierror) and n in gai_errnos) or
  664. n in captured_errnos):
  665. if not verbose:
  666. sys.stderr.write(denied.args[0] + "\n")
  667. raise denied
  668. old_timeout = socket.getdefaulttimeout()
  669. try:
  670. if timeout is not None:
  671. socket.setdefaulttimeout(timeout)
  672. yield
  673. except IOError as err:
  674. # urllib can wrap original socket errors multiple times (!), we must
  675. # unwrap to get at the original error.
  676. while True:
  677. a = err.args
  678. if len(a) >= 1 and isinstance(a[0], IOError):
  679. err = a[0]
  680. # The error can also be wrapped as args[1]:
  681. # except socket.error as msg:
  682. # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
  683. elif len(a) >= 2 and isinstance(a[1], IOError):
  684. err = a[1]
  685. else:
  686. break
  687. filter_error(err)
  688. raise
  689. # XXX should we catch generic exceptions and look for their
  690. # __cause__ or __context__?
  691. finally:
  692. socket.setdefaulttimeout(old_timeout)
  693. @contextlib.contextmanager
  694. def captured_output(stream_name):
  695. """Return a context manager used by captured_stdout and captured_stdin
  696. that temporarily replaces the sys stream *stream_name* with a StringIO."""
  697. import StringIO
  698. orig_stdout = getattr(sys, stream_name)
  699. setattr(sys, stream_name, StringIO.StringIO())
  700. try:
  701. yield getattr(sys, stream_name)
  702. finally:
  703. setattr(sys, stream_name, orig_stdout)
  704. def captured_stdout():
  705. """Capture the output of sys.stdout:
  706. with captured_stdout() as s:
  707. print "hello"
  708. self.assertEqual(s.getvalue(), "hello")
  709. """
  710. return captured_output("stdout")
  711. def captured_stdin():
  712. return captured_output("stdin")
  713. def gc_collect():
  714. """Force as many objects as possible to be collected.
  715. In non-CPython implementations of Python, this is needed because timely
  716. deallocation is not guaranteed by the garbage collector. (Even in CPython
  717. this can be the case in case of reference cycles.) This means that __del__
  718. methods may be called later than expected and weakrefs may remain alive for
  719. longer than expected. This function tries its best to force all garbage
  720. objects to disappear.
  721. """
  722. gc.collect()
  723. if is_jython:
  724. time.sleep(0.1)
  725. gc.collect()
  726. gc.collect()
  727. #=======================================================================
  728. # Decorator for running a function in a different locale, correctly resetting
  729. # it afterwards.
  730. def run_with_locale(catstr, *locales):
  731. def decorator(func):
  732. def inner(*args, **kwds):
  733. try:
  734. import locale
  735. category = getattr(locale, catstr)
  736. orig_locale = locale.setlocale(category)
  737. except AttributeError:
  738. # if the test author gives us an invalid category string
  739. raise
  740. except:
  741. # cannot retrieve original locale, so do nothing
  742. locale = orig_locale = None
  743. else:
  744. for loc in locales:
  745. try:
  746. locale.setlocale(category, loc)
  747. break
  748. except:
  749. pass
  750. # now run the function, resetting the locale on exceptions
  751. try:
  752. return func(*args, **kwds)
  753. finally:
  754. if locale and orig_locale:
  755. locale.setlocale(category, orig_locale)
  756. inner.func_name = func.func_name
  757. inner.__doc__ = func.__doc__
  758. return inner
  759. return decorator
  760. #=======================================================================
  761. # Big-memory-test support. Separate from 'resources' because memory use should be configurable.
  762. # Some handy shorthands. Note that these are used for byte-limits as well
  763. # as size-limits, in the various bigmem tests
  764. _1M = 1024*1024
  765. _1G = 1024 * _1M
  766. _2G = 2 * _1G
  767. _4G = 4 * _1G
  768. MAX_Py_ssize_t = sys.maxsize
  769. def set_memlimit(limit):
  770. global max_memuse
  771. global real_max_memuse
  772. sizes = {
  773. 'k': 1024,
  774. 'm': _1M,
  775. 'g': _1G,
  776. 't': 1024*_1G,
  777. }
  778. m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
  779. re.IGNORECASE | re.VERBOSE)
  780. if m is None:
  781. raise ValueError('Invalid memory limit %r' % (limit,))
  782. memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
  783. real_max_memuse = memlimit
  784. if memlimit > MAX_Py_ssize_t:
  785. memlimit = MAX_Py_ssize_t
  786. if memlimit < _2G - 1:
  787. raise ValueError('Memory limit %r too low to be useful' % (limit,))
  788. max_memuse = memlimit
  789. def bigmemtest(minsize, memuse, overhead=5*_1M):
  790. """Decorator for bigmem tests.
  791. 'minsize' is the minimum useful size for the test (in arbitrary,
  792. test-interpreted units.) 'memuse' is the number of 'bytes per size' for
  793. the test, or a good estimate of it. 'overhead' specifies fixed overhead,
  794. independent of the testsize, and defaults to 5Mb.
  795. The decorator tries to guess a good value for 'size' and passes it to
  796. the decorated test function. If minsize * memuse is more than the
  797. allowed memory use (as defined by max_memuse), the test is skipped.
  798. Otherwise, minsize is adjusted upward to use up to max_memuse.
  799. """
  800. def decorator(f):
  801. def wrapper(self):
  802. if not max_memuse:
  803. # If max_memuse is 0 (the default),
  804. # we still want to run the tests with size set to a few kb,
  805. # to make sure they work. We still want to avoid using
  806. # too much memory, though, but we do that noisily.
  807. maxsize = 5147
  808. self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
  809. else:
  810. maxsize = int((max_memuse - overhead) / memuse)
  811. if maxsize < minsize:
  812. # Really ought to print 'test skipped' or something
  813. if verbose:
  814. sys.stderr.write("Skipping %s because of memory "
  815. "constraint\n" % (f.__name__,))
  816. return
  817. # Try to keep some breathing room in memory use
  818. maxsize = max(maxsize - 50 * _1M, minsize)
  819. return f(self, maxsize)
  820. wrapper.minsize = minsize
  821. wrapper.memuse = memuse
  822. wrapper.overhead = overhead
  823. return wrapper
  824. return decorator
  825. def precisionbigmemtest(size, memuse, overhead=5*_1M):
  826. def decorator(f):
  827. def wrapper(self):
  828. if not real_max_memuse:
  829. maxsize = 5147
  830. else:
  831. maxsize = size
  832. if real_max_memuse and real_max_memuse < maxsize * memuse:
  833. if verbose:
  834. sys.stderr.write("Skipping %s because of memory "
  835. "constraint\n" % (f.__name__,))
  836. return
  837. return f(self, maxsize)
  838. wrapper.size = size
  839. wrapper.memuse = memuse
  840. wrapper.overhead = overhead
  841. return wrapper
  842. return decorator
  843. def bigaddrspacetest(f):
  844. """Decorator for tests that fill the address space."""
  845. def wrapper(self):
  846. if max_memuse < MAX_Py_ssize_t:
  847. if verbose:
  848. sys.stderr.write("Skipping %s because of memory "
  849. "constraint\n" % (f.__name__,))
  850. else:
  851. return f(self)
  852. return wrapper
  853. #=======================================================================
  854. # unittest integration.
  855. class BasicTestRunner:
  856. def run(self, test):
  857. result = unittest.TestResult()
  858. test(result)
  859. return result
  860. def _id(obj):
  861. return obj
  862. def requires_resource(resource):
  863. if is_resource_enabled(resource):
  864. return _id
  865. else:
  866. return unittest.skip("resource {0!r} is not enabled".format(resource))
  867. def cpython_only(test):
  868. """
  869. Decorator for tests only applicable on CPython.
  870. """
  871. return impl_detail(cpython=True)(test)
  872. def impl_detail(msg=None, **guards):
  873. if check_impl_detail(**guards):
  874. return _id
  875. if msg is None:
  876. guardnames, default = _parse_guards(guards)
  877. if default:
  878. msg = "implementation detail not available on {0}"
  879. else:
  880. msg = "implementation detail specific to {0}"
  881. guardnames = sorted(guardnames.keys())
  882. msg = msg.format(' or '.join(guardnames))
  883. return unittest.skip(msg)
  884. def _parse_guards(guards):
  885. # Returns a tuple ({platform_name: run_me}, default_value)
  886. if not guards:
  887. return ({'cpython': True}, False)
  888. is_true = guards.values()[0]
  889. assert guards.values() == [is_true] * len(guards) # all True or all False
  890. return (guards, not is_true)
  891. # Use the following check to guard CPython's implementation-specific tests --
  892. # or to run them only on the implementation(s) guarded by the arguments.
  893. def check_impl_detail(**guards):
  894. """This function returns True or False depending on the host platform.
  895. Examples:
  896. if check_impl_detail(): # only on CPython (default)
  897. if check_impl_detail(jython=True): # only on Jython
  898. if check_impl_detail(cpython=False): # everywhere except on CPython
  899. """
  900. guards, default = _parse_guards(guards)
  901. return guards.get(platform.python_implementation().lower(), default)
  902. # ----------------------------------
  903. # PyPy extension: you can run::
  904. # python ..../test_foo.py --pdb
  905. # to get a pdb prompt in case of exceptions
  906. ResultClass = unittest.TextTestRunner.resultclass
  907. class TestResultWithPdb(ResultClass):
  908. def addError(self, testcase, exc_info):
  909. ResultClass.addError(self, testcase, exc_info)
  910. if '--pdb' in sys.argv:
  911. import pdb, traceback
  912. traceback.print_tb(exc_info[2])
  913. pdb.post_mortem(exc_info[2])
  914. # ----------------------------------
  915. def _run_suite(suite):
  916. """Run tests from a unittest.TestSuite-derived class."""
  917. if verbose:
  918. runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
  919. resultclass=TestResultWithPdb)
  920. else:
  921. runner = BasicTestRunner()
  922. result = runner.run(suite)
  923. if not result.wasSuccessful():
  924. if len(result.errors) == 1 and not result.failures:
  925. err = result.errors[0][1]
  926. elif len(result.failures) == 1 and not result.errors:
  927. err = result.failures[0][1]
  928. else:
  929. err = "multiple errors occurred"
  930. if not verbose:
  931. err += "; run in verbose mode for details"
  932. raise TestFailed(err)
  933. # ----------------------------------
  934. # PyPy extension: you can run::
  935. # python ..../test_foo.py --filter bar
  936. # to run only the test cases whose name contains bar
  937. def filter_maybe(suite):
  938. try:
  939. i = sys.argv.index('--filter')
  940. filter = sys.argv[i+1]
  941. except (ValueError, IndexError):
  942. return suite
  943. tests = []
  944. for test in linearize_suite(suite):
  945. if filter in test._testMethodName:
  946. tests.append(test)
  947. return unittest.TestSuite(tests)
  948. def linearize_suite(suite_or_test):
  949. try:
  950. it = iter(suite_or_test)
  951. except TypeError:
  952. yield suite_or_test
  953. return
  954. for subsuite in it:
  955. for item in linearize_suite(subsuite):
  956. yield item
  957. # ----------------------------------
  958. def run_unittest(*classes):
  959. """Run tests from unittest.TestCase-derived classes."""
  960. valid_types = (unittest.TestSuite, unittest.TestCase)
  961. suite = unittest.TestSuite()
  962. for cls in classes:
  963. if isinstance(cls, str):
  964. if cls in sys.modules:
  965. suite.addTest(unittest.findTestCases(sys.modules[cls]))
  966. else:
  967. raise ValueError("str arguments must be keys in sys.modules")
  968. elif isinstance(cls, valid_types):
  969. suite.addTest(cls)
  970. else:
  971. suite.addTest(unittest.makeSuite(cls))
  972. suite = filter_maybe(suite)
  973. _run_suite(suite)
  974. #=======================================================================
  975. # doctest driver.
  976. def run_doctest(module, verbosity=None):
  977. """Run doctest on the given module. Return (#failures, #tests).
  978. If optional argument verbosity is not specified (or is None), pass
  979. test_support's belief about verbosity on to doctest. Else doctest's
  980. usual behavior is used (it searches sys.argv for -v).
  981. """
  982. import doctest
  983. if verbosity is None:
  984. verbosity = verbose
  985. else:
  986. verbosity = None
  987. # Direct doctest output (normally just errors) to real stdout; doctest
  988. # output shouldn't be compared by regrtest.
  989. save_stdout = sys.stdout
  990. sys.stdout = get_original_stdout()
  991. try:
  992. f, t = doctest.testmod(module, verbose=verbosity)
  993. if f:
  994. raise TestFailed("%d of %d doctests failed" % (f, t))
  995. finally:
  996. sys.stdout = save_stdout
  997. if verbose:
  998. print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
  999. return f, t
  1000. #=======================================================================
  1001. # Threading support to prevent reporting refleaks when running regrtest.py -R
  1002. # NOTE: we use thread._count() rather than threading.enumerate() (or the
  1003. # moral equivalent thereof) because a threading.Thread object is still alive
  1004. # until its __bootstrap() method has returned, even after it has been
  1005. # unregistered from the threading module.
  1006. # thread._count(), on the other hand, only gets decremented *after* the
  1007. # __bootstrap() method has returned, which gives us reliable reference counts
  1008. # at the end of a test run.
  1009. def threading_setup():
  1010. if thread:
  1011. return thread._count(),
  1012. else:
  1013. return 1,
  1014. def threading_cleanup(nb_threads):
  1015. if not thread:
  1016. return
  1017. _MAX_COUNT = 10
  1018. for count in range(_MAX_COUNT):
  1019. n = thread._count()
  1020. if n == nb_threads:
  1021. break
  1022. time.sleep(0.1)
  1023. # XXX print a warning in case of failure?
  1024. def reap_threads(func):
  1025. """Use this function when threads are being used. This will
  1026. ensure that the threads are cleaned up even when the test fails.
  1027. If threading is unavailable this function does nothing.
  1028. """
  1029. if not thread:
  1030. return func
  1031. @functools.wraps(func)
  1032. def decorator(*args):
  1033. key = threading_setup()
  1034. try:
  1035. return func(*args)
  1036. finally:
  1037. threading_cleanup(*key)
  1038. return decorator
  1039. def reap_children():
  1040. """Use this function at the end of test_main() whenever sub-processes
  1041. are started. This will help ensure that no extra children (zombies)
  1042. stick around to hog resources and create problems when looking
  1043. for refleaks.
  1044. """
  1045. # Reap all our dead child processes so we don't leave zombies around.
  1046. # These hog resources and might be causing some of the buildbots to die.
  1047. if hasattr(os, 'waitpid'):
  1048. any_process = -1
  1049. while True:
  1050. try:
  1051. # This will raise an exception on Windows. That's ok.
  1052. pid, status = os.waitpid(any_process, os.WNOHANG)
  1053. if pid == 0:
  1054. break
  1055. except:
  1056. break
  1057. def py3k_bytes(b):
  1058. """Emulate the py3k bytes() constructor.
  1059. NOTE: This is only a best effort function.
  1060. """
  1061. try:
  1062. # memoryview?
  1063. return b.tobytes()
  1064. except AttributeError:
  1065. try:
  1066. # iterable of ints?
  1067. return b"".join(chr(x) for x in b)
  1068. except TypeError:
  1069. return bytes(b)
  1070. def args_from_interpreter_flags():
  1071. """Return a list of command-line arguments reproducing the current
  1072. settings in sys.flags."""
  1073. flag_opt_map = {
  1074. 'bytes_warning': 'b',
  1075. 'dont_write_bytecode': 'B',
  1076. 'ignore_environment': 'E',
  1077. 'no_user_site': 's',
  1078. 'no_site': 'S',
  1079. 'optimize': 'O',
  1080. 'py3k_warning': '3',
  1081. 'verbose': 'v',
  1082. }
  1083. args = []
  1084. for flag, opt in flag_opt_map.items():
  1085. v = getattr(sys.flags, flag)
  1086. if v > 0:
  1087. args.append('-' + opt * v)
  1088. return args
  1089. def strip_python_stderr(stderr):
  1090. """Strip the stderr of a Python process from potential debug output
  1091. emitted by the interpreter.
  1092. This will typically be run on the result of the communicate() method
  1093. of a subprocess.Popen object.
  1094. """
  1095. stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
  1096. return stderr