PageRenderTime 61ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_support.py

http://github.com/IronLanguages/main
Python | 1679 lines | 1470 code | 75 blank | 134 comment | 115 complexity | 42e4969c136555ea23ef916bfe2f7545 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full 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. import struct
  20. import sysconfig
  21. try:
  22. import thread
  23. except ImportError:
  24. thread = None
  25. __all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
  26. "verbose", "use_resources", "max_memuse", "record_original_stdout",
  27. "get_original_stdout", "unload", "unlink", "rmtree", "forget",
  28. "is_resource_enabled", "requires", "requires_mac_ver",
  29. "find_unused_port", "bind_port",
  30. "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ",
  31. "SAVEDCWD", "temp_cwd", "findfile", "sortdict", "check_syntax_error",
  32. "open_urlresource", "check_warnings", "check_py3k_warnings",
  33. "CleanImport", "EnvironmentVarGuard", "captured_output",
  34. "captured_stdout", "TransientResource", "transient_internet",
  35. "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
  36. "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
  37. "threading_cleanup", "reap_threads", "start_threads", "cpython_only",
  38. "check_impl_detail", "get_attribute", "py3k_bytes",
  39. "import_fresh_module", "threading_cleanup", "reap_children",
  40. "strip_python_stderr", "IPV6_ENABLED", "run_with_tz"]
  41. class Error(Exception):
  42. """Base class for regression test exceptions."""
  43. class TestFailed(Error):
  44. """Test failed."""
  45. class ResourceDenied(unittest.SkipTest):
  46. """Test skipped because it requested a disallowed resource.
  47. This is raised when a test calls requires() for a resource that
  48. has not been enabled. It is used to distinguish between expected
  49. and unexpected skips.
  50. """
  51. @contextlib.contextmanager
  52. def _ignore_deprecated_imports(ignore=True):
  53. """Context manager to suppress package and module deprecation
  54. warnings when importing them.
  55. If ignore is False, this context manager has no effect."""
  56. if ignore:
  57. with warnings.catch_warnings():
  58. warnings.filterwarnings("ignore", ".+ (module|package)",
  59. DeprecationWarning)
  60. yield
  61. else:
  62. yield
  63. def import_module(name, deprecated=False):
  64. """Import and return the module to be tested, raising SkipTest if
  65. it is not available.
  66. If deprecated is True, any module or package deprecation messages
  67. will be suppressed."""
  68. with _ignore_deprecated_imports(deprecated):
  69. try:
  70. return importlib.import_module(name)
  71. except ImportError, msg:
  72. raise unittest.SkipTest(str(msg))
  73. def _save_and_remove_module(name, orig_modules):
  74. """Helper function to save and remove a module from sys.modules
  75. Raise ImportError if the module can't be imported."""
  76. # try to import the module and raise an error if it can't be imported
  77. if name not in sys.modules:
  78. __import__(name)
  79. del sys.modules[name]
  80. for modname in list(sys.modules):
  81. if modname == name or modname.startswith(name + '.'):
  82. orig_modules[modname] = sys.modules[modname]
  83. del sys.modules[modname]
  84. def _save_and_block_module(name, orig_modules):
  85. """Helper function to save and block a module in sys.modules
  86. Return True if the module was in sys.modules, False otherwise."""
  87. saved = True
  88. try:
  89. orig_modules[name] = sys.modules[name]
  90. except KeyError:
  91. saved = False
  92. sys.modules[name] = None
  93. return saved
  94. def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
  95. """Imports and returns a module, deliberately bypassing the sys.modules cache
  96. and importing a fresh copy of the module. Once the import is complete,
  97. the sys.modules cache is restored to its original state.
  98. Modules named in fresh are also imported anew if needed by the import.
  99. If one of these modules can't be imported, None is returned.
  100. Importing of modules named in blocked is prevented while the fresh import
  101. takes place.
  102. If deprecated is True, any module or package deprecation messages
  103. will be suppressed."""
  104. # NOTE: test_heapq, test_json, and test_warnings include extra sanity
  105. # checks to make sure that this utility function is working as expected
  106. with _ignore_deprecated_imports(deprecated):
  107. # Keep track of modules saved for later restoration as well
  108. # as those which just need a blocking entry removed
  109. orig_modules = {}
  110. names_to_remove = []
  111. _save_and_remove_module(name, orig_modules)
  112. try:
  113. for fresh_name in fresh:
  114. _save_and_remove_module(fresh_name, orig_modules)
  115. for blocked_name in blocked:
  116. if not _save_and_block_module(blocked_name, orig_modules):
  117. names_to_remove.append(blocked_name)
  118. fresh_module = importlib.import_module(name)
  119. except ImportError:
  120. fresh_module = None
  121. finally:
  122. for orig_name, module in orig_modules.items():
  123. sys.modules[orig_name] = module
  124. for name_to_remove in names_to_remove:
  125. del sys.modules[name_to_remove]
  126. return fresh_module
  127. def get_attribute(obj, name):
  128. """Get an attribute, raising SkipTest if AttributeError is raised."""
  129. try:
  130. attribute = getattr(obj, name)
  131. except AttributeError:
  132. raise unittest.SkipTest("module %s has no attribute %s" % (
  133. obj.__name__, name))
  134. else:
  135. return attribute
  136. verbose = 1 # Flag set to 0 by regrtest.py
  137. use_resources = None # Flag set to [] by regrtest.py
  138. max_memuse = 0 # Disable bigmem tests (they will still be run with
  139. # small sizes, to make sure they work.)
  140. real_max_memuse = 0
  141. # _original_stdout is meant to hold stdout at the time regrtest began.
  142. # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
  143. # The point is to have some flavor of stdout the user can actually see.
  144. _original_stdout = None
  145. def record_original_stdout(stdout):
  146. global _original_stdout
  147. _original_stdout = stdout
  148. def get_original_stdout():
  149. return _original_stdout or sys.stdout
  150. def unload(name):
  151. try:
  152. del sys.modules[name]
  153. except KeyError:
  154. pass
  155. if sys.platform.startswith("win"):
  156. def _waitfor(func, pathname, waitall=False):
  157. # Perform the operation
  158. func(pathname)
  159. # Now setup the wait loop
  160. if waitall:
  161. dirname = pathname
  162. else:
  163. dirname, name = os.path.split(pathname)
  164. dirname = dirname or '.'
  165. # Check for `pathname` to be removed from the filesystem.
  166. # The exponential backoff of the timeout amounts to a total
  167. # of ~1 second after which the deletion is probably an error
  168. # anyway.
  169. # Testing on a i7@4.3GHz shows that usually only 1 iteration is
  170. # required when contention occurs.
  171. timeout = 0.001
  172. while timeout < 1.0:
  173. # Note we are only testing for the existence of the file(s) in
  174. # the contents of the directory regardless of any security or
  175. # access rights. If we have made it this far, we have sufficient
  176. # permissions to do that much using Python's equivalent of the
  177. # Windows API FindFirstFile.
  178. # Other Windows APIs can fail or give incorrect results when
  179. # dealing with files that are pending deletion.
  180. L = os.listdir(dirname)
  181. if not (L if waitall else name in L):
  182. return
  183. # Increase the timeout and try again
  184. time.sleep(timeout)
  185. timeout *= 2
  186. warnings.warn('tests may fail, delete still pending for ' + pathname,
  187. RuntimeWarning, stacklevel=4)
  188. def _unlink(filename):
  189. _waitfor(os.unlink, filename)
  190. def _rmdir(dirname):
  191. _waitfor(os.rmdir, dirname)
  192. def _rmtree(path):
  193. def _rmtree_inner(path):
  194. for name in os.listdir(path):
  195. fullname = os.path.join(path, name)
  196. if os.path.isdir(fullname):
  197. _waitfor(_rmtree_inner, fullname, waitall=True)
  198. os.rmdir(fullname)
  199. else:
  200. os.unlink(fullname)
  201. _waitfor(_rmtree_inner, path, waitall=True)
  202. _waitfor(os.rmdir, path)
  203. else:
  204. _unlink = os.unlink
  205. _rmdir = os.rmdir
  206. _rmtree = shutil.rmtree
  207. def unlink(filename):
  208. try:
  209. _unlink(filename)
  210. except OSError:
  211. pass
  212. def rmdir(dirname):
  213. try:
  214. _rmdir(dirname)
  215. except OSError as error:
  216. # The directory need not exist.
  217. if error.errno != errno.ENOENT:
  218. raise
  219. def rmtree(path):
  220. try:
  221. _rmtree(path)
  222. except OSError, e:
  223. # Unix returns ENOENT, Windows returns ESRCH.
  224. if e.errno not in (errno.ENOENT, errno.ESRCH):
  225. raise
  226. def forget(modname):
  227. '''"Forget" a module was ever imported by removing it from sys.modules and
  228. deleting any .pyc and .pyo files.'''
  229. unload(modname)
  230. for dirname in sys.path:
  231. unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
  232. # Deleting the .pyo file cannot be within the 'try' for the .pyc since
  233. # the chance exists that there is no .pyc (and thus the 'try' statement
  234. # is exited) but there is a .pyo file.
  235. unlink(os.path.join(dirname, modname + os.extsep + 'pyo'))
  236. # Check whether a gui is actually available
  237. def _is_gui_available():
  238. if hasattr(_is_gui_available, 'result'):
  239. return _is_gui_available.result
  240. reason = None
  241. if sys.platform.startswith('win'):
  242. # if Python is running as a service (such as the buildbot service),
  243. # gui interaction may be disallowed
  244. import ctypes
  245. import ctypes.wintypes
  246. UOI_FLAGS = 1
  247. WSF_VISIBLE = 0x0001
  248. class USEROBJECTFLAGS(ctypes.Structure):
  249. _fields_ = [("fInherit", ctypes.wintypes.BOOL),
  250. ("fReserved", ctypes.wintypes.BOOL),
  251. ("dwFlags", ctypes.wintypes.DWORD)]
  252. dll = ctypes.windll.user32
  253. h = dll.GetProcessWindowStation()
  254. if not h:
  255. raise ctypes.WinError()
  256. uof = USEROBJECTFLAGS()
  257. needed = ctypes.wintypes.DWORD()
  258. res = dll.GetUserObjectInformationW(h,
  259. UOI_FLAGS,
  260. ctypes.byref(uof),
  261. ctypes.sizeof(uof),
  262. ctypes.byref(needed))
  263. if not res:
  264. raise ctypes.WinError()
  265. if not bool(uof.dwFlags & WSF_VISIBLE):
  266. reason = "gui not available (WSF_VISIBLE flag not set)"
  267. elif sys.platform == 'darwin':
  268. # The Aqua Tk implementations on OS X can abort the process if
  269. # being called in an environment where a window server connection
  270. # cannot be made, for instance when invoked by a buildbot or ssh
  271. # process not running under the same user id as the current console
  272. # user. To avoid that, raise an exception if the window manager
  273. # connection is not available.
  274. from ctypes import cdll, c_int, pointer, Structure
  275. from ctypes.util import find_library
  276. app_services = cdll.LoadLibrary(find_library("ApplicationServices"))
  277. if app_services.CGMainDisplayID() == 0:
  278. reason = "gui tests cannot run without OS X window manager"
  279. else:
  280. class ProcessSerialNumber(Structure):
  281. _fields_ = [("highLongOfPSN", c_int),
  282. ("lowLongOfPSN", c_int)]
  283. psn = ProcessSerialNumber()
  284. psn_p = pointer(psn)
  285. if ( (app_services.GetCurrentProcess(psn_p) < 0) or
  286. (app_services.SetFrontProcess(psn_p) < 0) ):
  287. reason = "cannot run without OS X gui process"
  288. # check on every platform whether tkinter can actually do anything
  289. if not reason:
  290. try:
  291. from Tkinter import Tk
  292. root = Tk()
  293. root.update()
  294. root.destroy()
  295. except Exception as e:
  296. err_string = str(e)
  297. if len(err_string) > 50:
  298. err_string = err_string[:50] + ' [...]'
  299. reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__,
  300. err_string)
  301. _is_gui_available.reason = reason
  302. _is_gui_available.result = not reason
  303. return _is_gui_available.result
  304. def is_resource_enabled(resource):
  305. """Test whether a resource is enabled.
  306. Known resources are set by regrtest.py. If not running under regrtest.py,
  307. all resources are assumed enabled unless use_resources has been set.
  308. """
  309. return use_resources is None or resource in use_resources
  310. def requires(resource, msg=None):
  311. """Raise ResourceDenied if the specified resource is not available."""
  312. if resource == 'gui' and not _is_gui_available():
  313. raise ResourceDenied(_is_gui_available.reason)
  314. if not is_resource_enabled(resource):
  315. if msg is None:
  316. msg = "Use of the `%s' resource not enabled" % resource
  317. raise ResourceDenied(msg)
  318. def requires_mac_ver(*min_version):
  319. """Decorator raising SkipTest if the OS is Mac OS X and the OS X
  320. version if less than min_version.
  321. For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
  322. is lesser than 10.5.
  323. """
  324. def decorator(func):
  325. @functools.wraps(func)
  326. def wrapper(*args, **kw):
  327. if sys.platform == 'darwin':
  328. version_txt = platform.mac_ver()[0]
  329. try:
  330. version = tuple(map(int, version_txt.split('.')))
  331. except ValueError:
  332. pass
  333. else:
  334. if version < min_version:
  335. min_version_txt = '.'.join(map(str, min_version))
  336. raise unittest.SkipTest(
  337. "Mac OS X %s or higher required, not %s"
  338. % (min_version_txt, version_txt))
  339. return func(*args, **kw)
  340. wrapper.min_version = min_version
  341. return wrapper
  342. return decorator
  343. # Don't use "localhost", since resolving it uses the DNS under recent
  344. # Windows versions (see issue #18792).
  345. HOST = "127.0.0.1"
  346. HOSTv6 = "::1"
  347. def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
  348. """Returns an unused port that should be suitable for binding. This is
  349. achieved by creating a temporary socket with the same family and type as
  350. the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
  351. the specified host address (defaults to 0.0.0.0) with the port set to 0,
  352. eliciting an unused ephemeral port from the OS. The temporary socket is
  353. then closed and deleted, and the ephemeral port is returned.
  354. Either this method or bind_port() should be used for any tests where a
  355. server socket needs to be bound to a particular port for the duration of
  356. the test. Which one to use depends on whether the calling code is creating
  357. a python socket, or if an unused port needs to be provided in a constructor
  358. or passed to an external program (i.e. the -accept argument to openssl's
  359. s_server mode). Always prefer bind_port() over find_unused_port() where
  360. possible. Hard coded ports should *NEVER* be used. As soon as a server
  361. socket is bound to a hard coded port, the ability to run multiple instances
  362. of the test simultaneously on the same host is compromised, which makes the
  363. test a ticking time bomb in a buildbot environment. On Unix buildbots, this
  364. may simply manifest as a failed test, which can be recovered from without
  365. intervention in most cases, but on Windows, the entire python process can
  366. completely and utterly wedge, requiring someone to log in to the buildbot
  367. and manually kill the affected process.
  368. (This is easy to reproduce on Windows, unfortunately, and can be traced to
  369. the SO_REUSEADDR socket option having different semantics on Windows versus
  370. Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
  371. listen and then accept connections on identical host/ports. An EADDRINUSE
  372. socket.error will be raised at some point (depending on the platform and
  373. the order bind and listen were called on each socket).
  374. However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
  375. will ever be raised when attempting to bind two identical host/ports. When
  376. accept() is called on each socket, the second caller's process will steal
  377. the port from the first caller, leaving them both in an awkwardly wedged
  378. state where they'll no longer respond to any signals or graceful kills, and
  379. must be forcibly killed via OpenProcess()/TerminateProcess().
  380. The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
  381. instead of SO_REUSEADDR, which effectively affords the same semantics as
  382. SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
  383. Source world compared to Windows ones, this is a common mistake. A quick
  384. look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
  385. openssl.exe is called with the 's_server' option, for example. See
  386. http://bugs.python.org/issue2550 for more info. The following site also
  387. has a very thorough description about the implications of both REUSEADDR
  388. and EXCLUSIVEADDRUSE on Windows:
  389. http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
  390. XXX: although this approach is a vast improvement on previous attempts to
  391. elicit unused ports, it rests heavily on the assumption that the ephemeral
  392. port returned to us by the OS won't immediately be dished back out to some
  393. other process when we close and delete our temporary socket but before our
  394. calling code has a chance to bind the returned port. We can deal with this
  395. issue if/when we come across it."""
  396. tempsock = socket.socket(family, socktype)
  397. port = bind_port(tempsock)
  398. tempsock.close()
  399. del tempsock
  400. return port
  401. def bind_port(sock, host=HOST):
  402. """Bind the socket to a free port and return the port number. Relies on
  403. ephemeral ports in order to ensure we are using an unbound port. This is
  404. important as many tests may be running simultaneously, especially in a
  405. buildbot environment. This method raises an exception if the sock.family
  406. is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
  407. or SO_REUSEPORT set on it. Tests should *never* set these socket options
  408. for TCP/IP sockets. The only case for setting these options is testing
  409. multicasting via multiple UDP sockets.
  410. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
  411. on Windows), it will be set on the socket. This will prevent anyone else
  412. from bind()'ing to our host/port for the duration of the test.
  413. """
  414. if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
  415. if hasattr(socket, 'SO_REUSEADDR'):
  416. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
  417. raise TestFailed("tests should never set the SO_REUSEADDR " \
  418. "socket option on TCP/IP sockets!")
  419. if hasattr(socket, 'SO_REUSEPORT'):
  420. try:
  421. if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
  422. raise TestFailed("tests should never set the SO_REUSEPORT " \
  423. "socket option on TCP/IP sockets!")
  424. except EnvironmentError:
  425. # Python's socket module was compiled using modern headers
  426. # thus defining SO_REUSEPORT but this process is running
  427. # under an older kernel that does not support SO_REUSEPORT.
  428. pass
  429. if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
  430. sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  431. sock.bind((host, 0))
  432. port = sock.getsockname()[1]
  433. return port
  434. def _is_ipv6_enabled():
  435. """Check whether IPv6 is enabled on this host."""
  436. if socket.has_ipv6:
  437. sock = None
  438. try:
  439. sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  440. sock.bind((HOSTv6, 0))
  441. return True
  442. except socket.error:
  443. pass
  444. finally:
  445. if sock:
  446. sock.close()
  447. return False
  448. IPV6_ENABLED = _is_ipv6_enabled()
  449. def system_must_validate_cert(f):
  450. """Skip the test on TLS certificate validation failures."""
  451. @functools.wraps(f)
  452. def dec(*args, **kwargs):
  453. try:
  454. f(*args, **kwargs)
  455. except IOError as e:
  456. if "CERTIFICATE_VERIFY_FAILED" in str(e):
  457. raise unittest.SkipTest("system does not contain "
  458. "necessary certificates")
  459. raise
  460. return dec
  461. FUZZ = 1e-6
  462. def fcmp(x, y): # fuzzy comparison function
  463. if isinstance(x, float) or isinstance(y, float):
  464. try:
  465. fuzz = (abs(x) + abs(y)) * FUZZ
  466. if abs(x-y) <= fuzz:
  467. return 0
  468. except:
  469. pass
  470. elif type(x) == type(y) and isinstance(x, (tuple, list)):
  471. for i in range(min(len(x), len(y))):
  472. outcome = fcmp(x[i], y[i])
  473. if outcome != 0:
  474. return outcome
  475. return (len(x) > len(y)) - (len(x) < len(y))
  476. return (x > y) - (x < y)
  477. # A constant likely larger than the underlying OS pipe buffer size, to
  478. # make writes blocking.
  479. # Windows limit seems to be around 512 B, and many Unix kernels have a
  480. # 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
  481. # (see issue #17835 for a discussion of this number).
  482. PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
  483. # A constant likely larger than the underlying OS socket buffer size, to make
  484. # writes blocking.
  485. # The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
  486. # on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
  487. # for a discussion of this number).
  488. SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1
  489. is_jython = sys.platform.startswith('java')
  490. try:
  491. unicode
  492. have_unicode = True
  493. except NameError:
  494. have_unicode = False
  495. requires_unicode = unittest.skipUnless(have_unicode, 'no unicode support')
  496. def u(s):
  497. return unicode(s, 'unicode-escape')
  498. # FS_NONASCII: non-ASCII Unicode character encodable by
  499. # sys.getfilesystemencoding(), or None if there is no such character.
  500. FS_NONASCII = None
  501. if have_unicode:
  502. for character in (
  503. # First try printable and common characters to have a readable filename.
  504. # For each character, the encoding list are just example of encodings able
  505. # to encode the character (the list is not exhaustive).
  506. # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
  507. unichr(0x00E6),
  508. # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
  509. unichr(0x0130),
  510. # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
  511. unichr(0x0141),
  512. # U+03C6 (Greek Small Letter Phi): cp1253
  513. unichr(0x03C6),
  514. # U+041A (Cyrillic Capital Letter Ka): cp1251
  515. unichr(0x041A),
  516. # U+05D0 (Hebrew Letter Alef): Encodable to cp424
  517. unichr(0x05D0),
  518. # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
  519. unichr(0x060C),
  520. # U+062A (Arabic Letter Teh): cp720
  521. unichr(0x062A),
  522. # U+0E01 (Thai Character Ko Kai): cp874
  523. unichr(0x0E01),
  524. # Then try more "special" characters. "special" because they may be
  525. # interpreted or displayed differently depending on the exact locale
  526. # encoding and the font.
  527. # U+00A0 (No-Break Space)
  528. unichr(0x00A0),
  529. # U+20AC (Euro Sign)
  530. unichr(0x20AC),
  531. ):
  532. try:
  533. character.encode(sys.getfilesystemencoding())\
  534. .decode(sys.getfilesystemencoding())
  535. except UnicodeError:
  536. pass
  537. else:
  538. FS_NONASCII = character
  539. break
  540. # Filename used for testing
  541. if os.name == 'java':
  542. # Jython disallows @ in module names
  543. TESTFN = '$test'
  544. elif os.name == 'riscos':
  545. TESTFN = 'testfile'
  546. else:
  547. TESTFN = '@test'
  548. # Unicode name only used if TEST_FN_ENCODING exists for the platform.
  549. if have_unicode:
  550. # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
  551. # TESTFN_UNICODE is a filename that can be encoded using the
  552. # file system encoding, but *not* with the default (ascii) encoding
  553. if isinstance('', unicode):
  554. # python -U
  555. # XXX perhaps unicode() should accept Unicode strings?
  556. TESTFN_UNICODE = "@test-\xe0\xf2"
  557. else:
  558. # 2 latin characters.
  559. TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1")
  560. TESTFN_ENCODING = sys.getfilesystemencoding()
  561. # TESTFN_UNENCODABLE is a filename that should *not* be
  562. # able to be encoded by *either* the default or filesystem encoding.
  563. # This test really only makes sense on Windows NT platforms
  564. # which have special Unicode support in posixmodule.
  565. if (not hasattr(sys, "getwindowsversion") or
  566. sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
  567. TESTFN_UNENCODABLE = None
  568. else:
  569. # Japanese characters (I think - from bug 846133)
  570. TESTFN_UNENCODABLE = eval('u"@test-\u5171\u6709\u3055\u308c\u308b"')
  571. try:
  572. # XXX - Note - should be using TESTFN_ENCODING here - but for
  573. # Windows, "mbcs" currently always operates as if in
  574. # errors=ignore' mode - hence we get '?' characters rather than
  575. # the exception. 'Latin1' operates as we expect - ie, fails.
  576. # See [ 850997 ] mbcs encoding ignores errors
  577. TESTFN_UNENCODABLE.encode("Latin1")
  578. except UnicodeEncodeError:
  579. pass
  580. else:
  581. print \
  582. 'WARNING: The filename %r CAN be encoded by the filesystem. ' \
  583. 'Unicode filename tests may not be effective' \
  584. % TESTFN_UNENCODABLE
  585. # Disambiguate TESTFN for parallel testing, while letting it remain a valid
  586. # module name.
  587. TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
  588. # Save the initial cwd
  589. SAVEDCWD = os.getcwd()
  590. @contextlib.contextmanager
  591. def change_cwd(path, quiet=False):
  592. """Return a context manager that changes the current working directory.
  593. Arguments:
  594. path: the directory to use as the temporary current working directory.
  595. quiet: if False (the default), the context manager raises an exception
  596. on error. Otherwise, it issues only a warning and keeps the current
  597. working directory the same.
  598. """
  599. saved_dir = os.getcwd()
  600. try:
  601. os.chdir(path)
  602. except OSError:
  603. if not quiet:
  604. raise
  605. warnings.warn('tests may fail, unable to change CWD to: ' + path,
  606. RuntimeWarning, stacklevel=3)
  607. try:
  608. yield os.getcwd()
  609. finally:
  610. os.chdir(saved_dir)
  611. @contextlib.contextmanager
  612. def temp_cwd(name='tempcwd', quiet=False):
  613. """
  614. Context manager that creates a temporary directory and set it as CWD.
  615. The new CWD is created in the current directory and it's named *name*.
  616. If *quiet* is False (default) and it's not possible to create or change
  617. the CWD, an error is raised. If it's True, only a warning is raised
  618. and the original CWD is used.
  619. """
  620. if (have_unicode and isinstance(name, unicode) and
  621. not os.path.supports_unicode_filenames):
  622. try:
  623. name = name.encode(sys.getfilesystemencoding() or 'ascii')
  624. except UnicodeEncodeError:
  625. if not quiet:
  626. raise unittest.SkipTest('unable to encode the cwd name with '
  627. 'the filesystem encoding.')
  628. saved_dir = os.getcwd()
  629. is_temporary = False
  630. try:
  631. os.mkdir(name)
  632. os.chdir(name)
  633. is_temporary = True
  634. except OSError:
  635. if not quiet:
  636. raise
  637. warnings.warn('tests may fail, unable to change the CWD to ' + name,
  638. RuntimeWarning, stacklevel=3)
  639. try:
  640. yield os.getcwd()
  641. finally:
  642. os.chdir(saved_dir)
  643. if is_temporary:
  644. rmtree(name)
  645. def findfile(file, here=__file__, subdir=None):
  646. """Try to find a file on sys.path and the working directory. If it is not
  647. found the argument passed to the function is returned (this does not
  648. necessarily signal failure; could still be the legitimate path)."""
  649. if os.path.isabs(file):
  650. return file
  651. if subdir is not None:
  652. file = os.path.join(subdir, file)
  653. path = sys.path
  654. path = [os.path.dirname(here)] + path
  655. for dn in path:
  656. fn = os.path.join(dn, file)
  657. if os.path.exists(fn): return fn
  658. return file
  659. def sortdict(dict):
  660. "Like repr(dict), but in sorted order."
  661. items = dict.items()
  662. items.sort()
  663. reprpairs = ["%r: %r" % pair for pair in items]
  664. withcommas = ", ".join(reprpairs)
  665. return "{%s}" % withcommas
  666. def make_bad_fd():
  667. """
  668. Create an invalid file descriptor by opening and closing a file and return
  669. its fd.
  670. """
  671. file = open(TESTFN, "wb")
  672. try:
  673. return file.fileno()
  674. finally:
  675. file.close()
  676. unlink(TESTFN)
  677. def check_syntax_error(testcase, statement):
  678. testcase.assertRaises(SyntaxError, compile, statement,
  679. '<test string>', 'exec')
  680. def open_urlresource(url, check=None):
  681. import urlparse, urllib2
  682. filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
  683. fn = os.path.join(os.path.dirname(__file__), "data", filename)
  684. def check_valid_file(fn):
  685. f = open(fn)
  686. if check is None:
  687. return f
  688. elif check(f):
  689. f.seek(0)
  690. return f
  691. f.close()
  692. if os.path.exists(fn):
  693. f = check_valid_file(fn)
  694. if f is not None:
  695. return f
  696. unlink(fn)
  697. # Verify the requirement before downloading the file
  698. requires('urlfetch')
  699. print >> get_original_stdout(), '\tfetching %s ...' % url
  700. f = urllib2.urlopen(url, timeout=15)
  701. try:
  702. with open(fn, "wb") as out:
  703. s = f.read()
  704. while s:
  705. out.write(s)
  706. s = f.read()
  707. finally:
  708. f.close()
  709. f = check_valid_file(fn)
  710. if f is not None:
  711. return f
  712. raise TestFailed('invalid resource "%s"' % fn)
  713. class WarningsRecorder(object):
  714. """Convenience wrapper for the warnings list returned on
  715. entry to the warnings.catch_warnings() context manager.
  716. """
  717. def __init__(self, warnings_list):
  718. self._warnings = warnings_list
  719. self._last = 0
  720. def __getattr__(self, attr):
  721. if len(self._warnings) > self._last:
  722. return getattr(self._warnings[-1], attr)
  723. elif attr in warnings.WarningMessage._WARNING_DETAILS:
  724. return None
  725. raise AttributeError("%r has no attribute %r" % (self, attr))
  726. @property
  727. def warnings(self):
  728. return self._warnings[self._last:]
  729. def reset(self):
  730. self._last = len(self._warnings)
  731. def _filterwarnings(filters, quiet=False):
  732. """Catch the warnings, then check if all the expected
  733. warnings have been raised and re-raise unexpected warnings.
  734. If 'quiet' is True, only re-raise the unexpected warnings.
  735. """
  736. # Clear the warning registry of the calling module
  737. # in order to re-raise the warnings.
  738. frame = sys._getframe(2)
  739. registry = frame.f_globals.get('__warningregistry__')
  740. if registry:
  741. registry.clear()
  742. with warnings.catch_warnings(record=True) as w:
  743. # Set filter "always" to record all warnings. Because
  744. # test_warnings swap the module, we need to look up in
  745. # the sys.modules dictionary.
  746. sys.modules['warnings'].simplefilter("always")
  747. yield WarningsRecorder(w)
  748. # Filter the recorded warnings
  749. reraise = [warning.message for warning in w]
  750. missing = []
  751. for msg, cat in filters:
  752. seen = False
  753. for exc in reraise[:]:
  754. message = str(exc)
  755. # Filter out the matching messages
  756. if (re.match(msg, message, re.I) and
  757. issubclass(exc.__class__, cat)):
  758. seen = True
  759. reraise.remove(exc)
  760. if not seen and not quiet:
  761. # This filter caught nothing
  762. missing.append((msg, cat.__name__))
  763. if reraise:
  764. raise AssertionError("unhandled warning %r" % reraise[0])
  765. if missing:
  766. raise AssertionError("filter (%r, %s) did not catch any warning" %
  767. missing[0])
  768. @contextlib.contextmanager
  769. def check_warnings(*filters, **kwargs):
  770. """Context manager to silence warnings.
  771. Accept 2-tuples as positional arguments:
  772. ("message regexp", WarningCategory)
  773. Optional argument:
  774. - if 'quiet' is True, it does not fail if a filter catches nothing
  775. (default True without argument,
  776. default False if some filters are defined)
  777. Without argument, it defaults to:
  778. check_warnings(("", Warning), quiet=True)
  779. """
  780. quiet = kwargs.get('quiet')
  781. if not filters:
  782. filters = (("", Warning),)
  783. # Preserve backward compatibility
  784. if quiet is None:
  785. quiet = True
  786. return _filterwarnings(filters, quiet)
  787. @contextlib.contextmanager
  788. def check_py3k_warnings(*filters, **kwargs):
  789. """Context manager to silence py3k warnings.
  790. Accept 2-tuples as positional arguments:
  791. ("message regexp", WarningCategory)
  792. Optional argument:
  793. - if 'quiet' is True, it does not fail if a filter catches nothing
  794. (default False)
  795. Without argument, it defaults to:
  796. check_py3k_warnings(("", DeprecationWarning), quiet=False)
  797. """
  798. if sys.py3kwarning:
  799. if not filters:
  800. filters = (("", DeprecationWarning),)
  801. else:
  802. # It should not raise any py3k warning
  803. filters = ()
  804. return _filterwarnings(filters, kwargs.get('quiet'))
  805. class CleanImport(object):
  806. """Context manager to force import to return a new module reference.
  807. This is useful for testing module-level behaviours, such as
  808. the emission of a DeprecationWarning on import.
  809. Use like this:
  810. with CleanImport("foo"):
  811. importlib.import_module("foo") # new reference
  812. """
  813. def __init__(self, *module_names):
  814. self.original_modules = sys.modules.copy()
  815. for module_name in module_names:
  816. if module_name in sys.modules:
  817. module = sys.modules[module_name]
  818. # It is possible that module_name is just an alias for
  819. # another module (e.g. stub for modules renamed in 3.x).
  820. # In that case, we also need delete the real module to clear
  821. # the import cache.
  822. if module.__name__ != module_name:
  823. del sys.modules[module.__name__]
  824. del sys.modules[module_name]
  825. def __enter__(self):
  826. return self
  827. def __exit__(self, *ignore_exc):
  828. sys.modules.update(self.original_modules)
  829. class EnvironmentVarGuard(UserDict.DictMixin):
  830. """Class to help protect the environment variable properly. Can be used as
  831. a context manager."""
  832. def __init__(self):
  833. self._environ = os.environ
  834. self._changed = {}
  835. def __getitem__(self, envvar):
  836. return self._environ[envvar]
  837. def __setitem__(self, envvar, value):
  838. # Remember the initial value on the first access
  839. if envvar not in self._changed:
  840. self._changed[envvar] = self._environ.get(envvar)
  841. self._environ[envvar] = value
  842. def __delitem__(self, envvar):
  843. # Remember the initial value on the first access
  844. if envvar not in self._changed:
  845. self._changed[envvar] = self._environ.get(envvar)
  846. if envvar in self._environ:
  847. del self._environ[envvar]
  848. def keys(self):
  849. return self._environ.keys()
  850. def set(self, envvar, value):
  851. self[envvar] = value
  852. def unset(self, envvar):
  853. del self[envvar]
  854. def __enter__(self):
  855. return self
  856. def __exit__(self, *ignore_exc):
  857. for (k, v) in self._changed.items():
  858. if v is None:
  859. if k in self._environ:
  860. del self._environ[k]
  861. else:
  862. self._environ[k] = v
  863. os.environ = self._environ
  864. class DirsOnSysPath(object):
  865. """Context manager to temporarily add directories to sys.path.
  866. This makes a copy of sys.path, appends any directories given
  867. as positional arguments, then reverts sys.path to the copied
  868. settings when the context ends.
  869. Note that *all* sys.path modifications in the body of the
  870. context manager, including replacement of the object,
  871. will be reverted at the end of the block.
  872. """
  873. def __init__(self, *paths):
  874. self.original_value = sys.path[:]
  875. self.original_object = sys.path
  876. sys.path.extend(paths)
  877. def __enter__(self):
  878. return self
  879. def __exit__(self, *ignore_exc):
  880. sys.path = self.original_object
  881. sys.path[:] = self.original_value
  882. class TransientResource(object):
  883. """Raise ResourceDenied if an exception is raised while the context manager
  884. is in effect that matches the specified exception and attributes."""
  885. def __init__(self, exc, **kwargs):
  886. self.exc = exc
  887. self.attrs = kwargs
  888. def __enter__(self):
  889. return self
  890. def __exit__(self, type_=None, value=None, traceback=None):
  891. """If type_ is a subclass of self.exc and value has attributes matching
  892. self.attrs, raise ResourceDenied. Otherwise let the exception
  893. propagate (if any)."""
  894. if type_ is not None and issubclass(self.exc, type_):
  895. for attr, attr_value in self.attrs.iteritems():
  896. if not hasattr(value, attr):
  897. break
  898. if getattr(value, attr) != attr_value:
  899. break
  900. else:
  901. raise ResourceDenied("an optional resource is not available")
  902. @contextlib.contextmanager
  903. def transient_internet(resource_name, timeout=30.0, errnos=()):
  904. """Return a context manager that raises ResourceDenied when various issues
  905. with the Internet connection manifest themselves as exceptions."""
  906. default_errnos = [
  907. ('ECONNREFUSED', 111),
  908. ('ECONNRESET', 104),
  909. ('EHOSTUNREACH', 113),
  910. ('ENETUNREACH', 101),
  911. ('ETIMEDOUT', 110),
  912. ]
  913. default_gai_errnos = [
  914. ('EAI_AGAIN', -3),
  915. ('EAI_FAIL', -4),
  916. ('EAI_NONAME', -2),
  917. ('EAI_NODATA', -5),
  918. # Windows defines EAI_NODATA as 11001 but idiotic getaddrinfo()
  919. # implementation actually returns WSANO_DATA i.e. 11004.
  920. ('WSANO_DATA', 11004),
  921. ]
  922. denied = ResourceDenied("Resource '%s' is not available" % resource_name)
  923. captured_errnos = errnos
  924. gai_errnos = []
  925. if not captured_errnos:
  926. captured_errnos = [getattr(errno, name, num)
  927. for (name, num) in default_errnos]
  928. gai_errnos = [getattr(socket, name, num)
  929. for (name, num) in default_gai_errnos]
  930. def filter_error(err):
  931. n = getattr(err, 'errno', None)
  932. if (isinstance(err, socket.timeout) or
  933. (isinstance(err, socket.gaierror) and n in gai_errnos) or
  934. n in captured_errnos):
  935. if not verbose:
  936. sys.stderr.write(denied.args[0] + "\n")
  937. raise denied
  938. old_timeout = socket.getdefaulttimeout()
  939. try:
  940. if timeout is not None:
  941. socket.setdefaulttimeout(timeout)
  942. yield
  943. except IOError as err:
  944. # urllib can wrap original socket errors multiple times (!), we must
  945. # unwrap to get at the original error.
  946. while True:
  947. a = err.args
  948. if len(a) >= 1 and isinstance(a[0], IOError):
  949. err = a[0]
  950. # The error can also be wrapped as args[1]:
  951. # except socket.error as msg:
  952. # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
  953. elif len(a) >= 2 and isinstance(a[1], IOError):
  954. err = a[1]
  955. else:
  956. break
  957. filter_error(err)
  958. raise
  959. # XXX should we catch generic exceptions and look for their
  960. # __cause__ or __context__?
  961. finally:
  962. socket.setdefaulttimeout(old_timeout)
  963. @contextlib.contextmanager
  964. def captured_output(stream_name):
  965. """Return a context manager used by captured_stdout and captured_stdin
  966. that temporarily replaces the sys stream *stream_name* with a StringIO."""
  967. import StringIO
  968. orig_stdout = getattr(sys, stream_name)
  969. setattr(sys, stream_name, StringIO.StringIO())
  970. try:
  971. yield getattr(sys, stream_name)
  972. finally:
  973. setattr(sys, stream_name, orig_stdout)
  974. def captured_stdout():
  975. """Capture the output of sys.stdout:
  976. with captured_stdout() as s:
  977. print "hello"
  978. self.assertEqual(s.getvalue(), "hello")
  979. """
  980. return captured_output("stdout")
  981. def captured_stderr():
  982. return captured_output("stderr")
  983. def captured_stdin():
  984. return captured_output("stdin")
  985. def gc_collect():
  986. """Force as many objects as possible to be collected.
  987. In non-CPython implementations of Python, this is needed because timely
  988. deallocation is not guaranteed by the garbage collector. (Even in CPython
  989. this can be the case in case of reference cycles.) This means that __del__
  990. methods may be called later than expected and weakrefs may remain alive for
  991. longer than expected. This function tries its best to force all garbage
  992. objects to disappear.
  993. """
  994. gc.collect()
  995. if is_jython:
  996. time.sleep(0.1)
  997. gc.collect()
  998. gc.collect()
  999. _header = '2P'
  1000. if hasattr(sys, "gettotalrefcount"):
  1001. _header = '2P' + _header
  1002. _vheader = _header + 'P'
  1003. def calcobjsize(fmt):
  1004. return struct.calcsize(_header + fmt + '0P')
  1005. def calcvobjsize(fmt):
  1006. return struct.calcsize(_vheader + fmt + '0P')
  1007. _TPFLAGS_HAVE_GC = 1<<14
  1008. _TPFLAGS_HEAPTYPE = 1<<9
  1009. def check_sizeof(test, o, size):
  1010. import _testcapi
  1011. result = sys.getsizeof(o)
  1012. # add GC header size
  1013. if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
  1014. ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
  1015. size += _testcapi.SIZEOF_PYGC_HEAD
  1016. msg = 'wrong size for %s: got %d, expected %d' \
  1017. % (type(o), result, size)
  1018. test.assertEqual(result, size, msg)
  1019. #=======================================================================
  1020. # Decorator for running a function in a different locale, correctly resetting
  1021. # it afterwards.
  1022. def run_with_locale(catstr, *locales):
  1023. def decorator(func):
  1024. def inner(*args, **kwds):
  1025. try:
  1026. import locale
  1027. category = getattr(locale, catstr)
  1028. orig_locale = locale.setlocale(category)
  1029. except AttributeError:
  1030. # if the test author gives us an invalid category string
  1031. raise
  1032. except:
  1033. # cannot retrieve original locale, so do nothing
  1034. locale = orig_locale = None
  1035. else:
  1036. for loc in locales:
  1037. try:
  1038. locale.setlocale(category, loc)
  1039. break
  1040. except:
  1041. pass
  1042. # now run the function, resetting the locale on exceptions
  1043. try:
  1044. return func(*args, **kwds)
  1045. finally:
  1046. if locale and orig_locale:
  1047. locale.setlocale(category, orig_locale)
  1048. inner.func_name = func.func_name
  1049. inner.__doc__ = func.__doc__
  1050. return inner
  1051. return decorator
  1052. #=======================================================================
  1053. # Decorator for running a function in a specific timezone, correctly
  1054. # resetting it afterwards.
  1055. def run_with_tz(tz):
  1056. def decorator(func):
  1057. def inner(*args, **kwds):
  1058. try:
  1059. tzset = time.tzset
  1060. except AttributeError:
  1061. raise unittest.SkipTest("tzset required")
  1062. if 'TZ' in os.environ:
  1063. orig_tz = os.environ['TZ']
  1064. else:
  1065. orig_tz = None
  1066. os.environ['TZ'] = tz
  1067. tzset()
  1068. # now run the function, resetting the tz on exceptions
  1069. try:
  1070. return func(*args, **kwds)
  1071. finally:
  1072. if orig_tz is None:
  1073. del os.environ['TZ']
  1074. else:
  1075. os.environ['TZ'] = orig_tz
  1076. time.tzset()
  1077. inner.__name__ = func.__name__
  1078. inner.__doc__ = func.__doc__
  1079. return inner
  1080. return decorator
  1081. #=======================================================================
  1082. # Big-memory-test support. Separate from 'resources' because memory use should be configurable.
  1083. # Some handy shorthands. Note that these are used for byte-limits as well
  1084. # as size-limits, in the various bigmem tests
  1085. _1M = 1024*1024
  1086. _1G = 1024 * _1M
  1087. _2G = 2 * _1G
  1088. _4G = 4 * _1G
  1089. MAX_Py_ssize_t = sys.maxsize
  1090. def set_memlimit(limit):
  1091. global max_memuse
  1092. global real_max_memuse
  1093. sizes = {
  1094. 'k': 1024,
  1095. 'm': _1M,
  1096. 'g': _1G,
  1097. 't': 1024*_1G,
  1098. }
  1099. m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
  1100. re.IGNORECASE | re.VERBOSE)
  1101. if m is None:
  1102. raise ValueError('Invalid memory limit %r' % (limit,))
  1103. memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
  1104. real_max_memuse = memlimit
  1105. if memlimit > MAX_Py_ssize_t:
  1106. memlimit = MAX_Py_ssize_t
  1107. if memlimit < _2G - 1:
  1108. raise ValueError('Memory limit %r too low to be useful' % (limit,))
  1109. max_memuse = memlimit
  1110. def bigmemtest(minsize, memuse, overhead=5*_1M):
  1111. """Decorator for bigmem tests.
  1112. 'minsize' is the minimum useful size for the test (in arbitrary,
  1113. test-interpreted units.) 'memuse' is the number of 'bytes per size' for
  1114. the test, or a good estimate of it. 'overhead' specifies fixed overhead,
  1115. independent of the testsize, and defaults to 5Mb.
  1116. The decorator tries to guess a good value for 'size' and passes it to
  1117. the decorated test function. If minsize * memuse is more than the
  1118. allowed memory use (as defined by max_memuse), the test is skipped.
  1119. Otherwise, minsize is adjusted upward to use up to max_memuse.
  1120. """
  1121. def decorator(f):
  1122. def wrapper(self):
  1123. if not max_memuse:
  1124. # If max_memuse is 0 (the default),
  1125. # we still want to run the tests with size set to a few kb,
  1126. # to make sure they work. We still want to avoid using
  1127. # too much memory, though, but we do that noisily.
  1128. maxsize = 5147
  1129. self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
  1130. else:
  1131. maxsize = int((max_memuse - overhead) / memuse)
  1132. if maxsize < minsize:
  1133. # Really ought to print 'test skipped' or something
  1134. if verbose:
  1135. sys.stderr.write("Skipping %s because of memory "
  1136. "constraint\n" % (f.__name__,))
  1137. return
  1138. # Try to keep some breathing room in memory use
  1139. maxsize = max(maxsize - 50 * _1M, minsize)
  1140. return f(self, maxsize)
  1141. wrapper.minsize = minsize
  1142. wrapper.memuse = memuse
  1143. wrapper.overhead = overhead
  1144. return wrapper
  1145. return decorator
  1146. def precisionbigmemtest(size, memuse, overhead=5*_1M, dry_run=True):
  1147. def decorator(f):
  1148. def wrapper(self):
  1149. if not real_max_memuse:
  1150. maxsize = 5147
  1151. else:
  1152. maxsize = size
  1153. if ((real_max_memuse or not dry_run)
  1154. and real_max_memuse < maxsize * memuse):
  1155. if verbose:
  1156. sys.stderr.write("Skipping %s because of memory "
  1157. "constraint\n" % (f.__name__,))
  1158. return
  1159. return f(self, maxsize)
  1160. wrapper.size = size
  1161. wrapper.memuse = memuse
  1162. wrapper.overhead = overhead
  1163. return wrapper
  1164. return decorator
  1165. def bigaddrspacetest(f):
  1166. """Decorator for tests that fill the address space."""
  1167. def wrapper(self):
  1168. if max_memuse < MAX_Py_ssize_t:
  1169. if verbose:
  1170. sys.stderr.write("Skipping %s because of memory "
  1171. "constraint\n" % (f.__name__,))
  1172. else:
  1173. return f(self)
  1174. return wrapper
  1175. #=======================================================================
  1176. # unittest integration.
  1177. class BasicTestRunner:
  1178. def run(self, test):
  1179. result = unittest.TestResult()
  1180. test(result)
  1181. return result
  1182. def _id(obj):
  1183. return obj
  1184. def requires_resource(resource):
  1185. if resource == 'gui' and not _is_gui_available():
  1186. return unittest.skip(_is_gui_available.reason)
  1187. if is_resource_enabled(resource):
  1188. return _id

Large files files are truncated, but you can click here to view the full file