blob: 2130fd639c9f49add256e7f3e722b1e6d70b53d9 [file] [log] [blame]
Brett Cannonf1cfb622003-05-04 21:15:27 +00001"""Supporting definitions for the Python regression tests."""
Guido van Rossum3bead091992-01-27 17:00:37 +00002
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003if __name__ != 'test.support':
4 raise ImportError('support must be imported from the test package')
Barry Warsaw408b6d32002-07-30 23:27:12 +00005
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import contextlib
7import errno
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00008import functools
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00009import gc
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import socket
Fred Drakecd1b1dd2001-03-21 18:26:33 +000011import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000012import os
Benjamin Petersone549ead2009-03-28 21:42:05 +000013import platform
Christian Heimes23daade2008-02-25 12:39:23 +000014import shutil
Thomas Wouters902d6eb2007-01-09 23:18:33 +000015import warnings
Guido van Rossumd8faa362007-04-27 19:54:29 +000016import unittest
R. David Murraya21e4ca2009-03-31 23:16:50 +000017import importlib
Walter Dörwald155374d2009-05-01 19:58:58 +000018import collections
Florent Xiclunab14930c2010-03-13 15:26:44 +000019import re
Brian Curtind40e6f72010-07-08 21:39:08 +000020import subprocess
Barry Warsaw28a691b2010-04-17 00:19:56 +000021import imp
Benjamin Petersona6590e82010-04-11 21:22:10 +000022import time
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000023import sysconfig
Antoine Pitroub9c73e82011-07-29 23:53:38 +020024import fnmatch
Vinay Sajip129fd042010-12-10 08:19:38 +000025import logging.handlers
Martin v. Löwis33f79972012-07-29 16:33:05 +020026import struct
27import tempfile
28import _testcapi
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000029
Victor Stinner45df8202010-04-28 22:31:17 +000030try:
Antoine Pitrou707f2282011-07-15 22:29:44 +020031 import _thread, threading
Victor Stinner45df8202010-04-28 22:31:17 +000032except ImportError:
33 _thread = None
Antoine Pitrou707f2282011-07-15 22:29:44 +020034 threading = None
35try:
36 import multiprocessing.process
37except ImportError:
38 multiprocessing = None
39
Fred Drakecd1b1dd2001-03-21 18:26:33 +000040
Barry Warsaw28a691b2010-04-17 00:19:56 +000041__all__ = [
42 "Error", "TestFailed", "ResourceDenied", "import_module",
43 "verbose", "use_resources", "max_memuse", "record_original_stdout",
44 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
Victor Stinner88701e22011-06-01 13:13:04 +020045 "is_resource_enabled", "requires", "requires_mac_ver",
46 "find_unused_port", "bind_port",
Barry Warsaw28a691b2010-04-17 00:19:56 +000047 "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
48 "findfile", "sortdict", "check_syntax_error", "open_urlresource",
49 "check_warnings", "CleanImport", "EnvironmentVarGuard",
50 "TransientResource", "captured_output", "captured_stdout",
Ezio Melotti07352b02011-05-14 14:51:18 +030051 "captured_stdin", "captured_stderr",
Barry Warsaw28a691b2010-04-17 00:19:56 +000052 "time_out", "socket_peer_reset", "ioerror_peer_reset",
Antoine Pitroua88c83c2010-09-07 20:42:19 +000053 "run_with_locale", 'temp_umask', "transient_internet",
Barry Warsaw28a691b2010-04-17 00:19:56 +000054 "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
55 "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
56 "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
Vinay Sajip129fd042010-12-10 08:19:38 +000057 "swap_item", "swap_attr", "requires_IEEE_754",
Benjamin Peterson31dc3732011-05-08 15:34:24 -050058 "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink",
Alexander Belopolsky2420d832012-04-29 15:56:49 -040059 "import_fresh_module", "failfast", "run_with_tz"
Antoine Pitrou4d7979b2010-09-07 21:22:56 +000060 ]
Florent Xiclunaf089fd62010-03-19 14:25:03 +000061
Fred Drake1790dd42000-07-24 06:55:00 +000062class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000063 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000064
65class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000066 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000067
Benjamin Petersone549ead2009-03-28 21:42:05 +000068class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +000069 """Test skipped because it requested a disallowed resource.
70
71 This is raised when a test calls requires() for a resource that
72 has not be enabled. It is used to distinguish between expected
73 and unexpected skips.
74 """
75
Nick Coghlanfce769e2009-04-11 14:30:59 +000076@contextlib.contextmanager
77def _ignore_deprecated_imports(ignore=True):
78 """Context manager to suppress package and module deprecation
79 warnings when importing them.
80
81 If ignore is False, this context manager has no effect."""
82 if ignore:
83 with warnings.catch_warnings():
84 warnings.filterwarnings("ignore", ".+ (module|package)",
85 DeprecationWarning)
86 yield
87 else:
88 yield
89
90
Benjamin Peterson699adb92008-05-08 22:27:58 +000091def import_module(name, deprecated=False):
R. David Murraya21e4ca2009-03-31 23:16:50 +000092 """Import and return the module to be tested, raising SkipTest if
93 it is not available.
94
95 If deprecated is True, any module or package deprecation messages
96 will be suppressed."""
Nick Coghlanfce769e2009-04-11 14:30:59 +000097 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +000098 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +000099 return importlib.import_module(name)
R. David Murraya21e4ca2009-03-31 23:16:50 +0000100 except ImportError as msg:
101 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +0000102
103
Nick Coghlan47384702009-04-22 16:13:36 +0000104def _save_and_remove_module(name, orig_modules):
105 """Helper function to save and remove a module from sys.modules
106
Ezio Melotti199e0852011-05-09 06:41:55 +0300107 Raise ImportError if the module can't be imported."""
Ezio Melottifec3ad12011-05-14 06:02:25 +0300108 # try to import the module and raise an error if it can't be imported
109 if name not in sys.modules:
Ezio Melotti199e0852011-05-09 06:41:55 +0300110 __import__(name)
Nick Coghlan47384702009-04-22 16:13:36 +0000111 del sys.modules[name]
Ezio Melottifec3ad12011-05-14 06:02:25 +0300112 for modname in list(sys.modules):
113 if modname == name or modname.startswith(name + '.'):
114 orig_modules[modname] = sys.modules[modname]
115 del sys.modules[modname]
Nick Coghlan47384702009-04-22 16:13:36 +0000116
117def _save_and_block_module(name, orig_modules):
118 """Helper function to save and block a module in sys.modules
119
Ezio Melotti199e0852011-05-09 06:41:55 +0300120 Return True if the module was in sys.modules, False otherwise."""
Nick Coghlan47384702009-04-22 16:13:36 +0000121 saved = True
122 try:
123 orig_modules[name] = sys.modules[name]
124 except KeyError:
125 saved = False
Alexander Belopolsky903396e2010-07-13 14:50:16 +0000126 sys.modules[name] = None
Nick Coghlan47384702009-04-22 16:13:36 +0000127 return saved
128
129
130def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Nick Coghlanfce769e2009-04-11 14:30:59 +0000131 """Imports and returns a module, deliberately bypassing the sys.modules cache
132 and importing a fresh copy of the module. Once the import is complete,
133 the sys.modules cache is restored to its original state.
134
Nick Coghlan47384702009-04-22 16:13:36 +0000135 Modules named in fresh are also imported anew if needed by the import.
Ezio Melotti199e0852011-05-09 06:41:55 +0300136 If one of these modules can't be imported, None is returned.
Nick Coghlan47384702009-04-22 16:13:36 +0000137
138 Importing of modules named in blocked is prevented while the fresh import
Nick Coghlanfce769e2009-04-11 14:30:59 +0000139 takes place.
140
141 If deprecated is True, any module or package deprecation messages
142 will be suppressed."""
Ezio Melotti6b60fb92011-05-14 06:47:51 +0300143 # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
144 # to make sure that this utility function is working as expected
Nick Coghlanfce769e2009-04-11 14:30:59 +0000145 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000146 # Keep track of modules saved for later restoration as well
147 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000148 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000149 names_to_remove = []
150 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000151 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000152 for fresh_name in fresh:
153 _save_and_remove_module(fresh_name, orig_modules)
154 for blocked_name in blocked:
155 if not _save_and_block_module(blocked_name, orig_modules):
156 names_to_remove.append(blocked_name)
157 fresh_module = importlib.import_module(name)
Ezio Melotti199e0852011-05-09 06:41:55 +0300158 except ImportError:
159 fresh_module = None
Nick Coghlanfce769e2009-04-11 14:30:59 +0000160 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000161 for orig_name, module in orig_modules.items():
162 sys.modules[orig_name] = module
163 for name_to_remove in names_to_remove:
164 del sys.modules[name_to_remove]
165 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000166
Benjamin Peterson699adb92008-05-08 22:27:58 +0000167
R. David Murraya21e4ca2009-03-31 23:16:50 +0000168def get_attribute(obj, name):
169 """Get an attribute, raising SkipTest if AttributeError is raised."""
170 try:
171 attribute = getattr(obj, name)
172 except AttributeError:
173 raise unittest.SkipTest("module %s has no attribute %s" % (
174 obj.__name__, name))
175 else:
176 return attribute
177
Barry Warsawc0fb6052001-08-20 22:29:23 +0000178verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000179use_resources = None # Flag set to [] by regrtest.py
180max_memuse = 0 # Disable bigmem tests (they will still be run with
181 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000182real_max_memuse = 0
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200183failfast = False
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200184match_tests = None
Guido van Rossum531661c1996-12-20 02:58:22 +0000185
Tim Peters8dee8092001-09-25 20:05:11 +0000186# _original_stdout is meant to hold stdout at the time regrtest began.
187# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
188# The point is to have some flavor of stdout the user can actually see.
189_original_stdout = None
190def record_original_stdout(stdout):
191 global _original_stdout
192 _original_stdout = stdout
193
194def get_original_stdout():
195 return _original_stdout or sys.stdout
196
Guido van Rossum3bead091992-01-27 17:00:37 +0000197def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000198 try:
199 del sys.modules[name]
200 except KeyError:
201 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000202
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500203if sys.platform.startswith("win"):
204 def _waitfor(func, pathname, waitall=False):
205 # Peform the operation
206 func(pathname)
207 # Now setup the wait loop
208 if waitall:
209 dirname = pathname
210 else:
211 dirname, name = os.path.split(pathname)
212 dirname = dirname or '.'
213 # Check for `pathname` to be removed from the filesystem.
214 # The exponential backoff of the timeout amounts to a total
215 # of ~1 second after which the deletion is probably an error
216 # anyway.
217 # Testing on a i7@4.3GHz shows that usually only 1 iteration is
218 # required when contention occurs.
219 timeout = 0.001
220 while timeout < 1.0:
221 # Note we are only testing for the existance of the file(s) in
222 # the contents of the directory regardless of any security or
223 # access rights. If we have made it this far, we have sufficient
224 # permissions to do that much using Python's equivalent of the
225 # Windows API FindFirstFile.
226 # Other Windows APIs can fail or give incorrect results when
227 # dealing with files that are pending deletion.
228 L = os.listdir(dirname)
229 if not (L if waitall else name in L):
230 return
231 # Increase the timeout and try again
232 time.sleep(timeout)
233 timeout *= 2
234 warnings.warn('tests may fail, delete still pending for ' + pathname,
235 RuntimeWarning, stacklevel=4)
236
237 def _unlink(filename):
238 _waitfor(os.unlink, filename)
239
240 def _rmdir(dirname):
241 _waitfor(os.rmdir, dirname)
242
243 def _rmtree(path):
244 def _rmtree_inner(path):
245 for name in os.listdir(path):
246 fullname = os.path.join(path, name)
247 if os.path.isdir(fullname):
248 _waitfor(_rmtree_inner, fullname, waitall=True)
249 os.rmdir(fullname)
250 else:
251 os.unlink(fullname)
252 _waitfor(_rmtree_inner, path, waitall=True)
253 _waitfor(os.rmdir, path)
254else:
255 _unlink = os.unlink
256 _rmdir = os.rmdir
257 _rmtree = shutil.rmtree
258
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000259def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000260 try:
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500261 _unlink(filename)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000262 except OSError as error:
263 # The filename need not exist.
Michael Foord2d9c2d52010-05-04 22:29:10 +0000264 if error.errno not in (errno.ENOENT, errno.ENOTDIR):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000265 raise
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000266
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500267def rmdir(dirname):
268 try:
269 _rmdir(dirname)
270 except OSError as error:
271 # The directory need not exist.
272 if error.errno != errno.ENOENT:
273 raise
274
Christian Heimes23daade2008-02-25 12:39:23 +0000275def rmtree(path):
276 try:
Brian Curtin6f5c5cb2012-08-13 17:05:57 -0500277 _rmtree(path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000278 except OSError as error:
Christian Heimes23daade2008-02-25 12:39:23 +0000279 # Unix returns ENOENT, Windows returns ESRCH.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000280 if error.errno not in (errno.ENOENT, errno.ESRCH):
Christian Heimes23daade2008-02-25 12:39:23 +0000281 raise
282
Barry Warsaw28a691b2010-04-17 00:19:56 +0000283def make_legacy_pyc(source):
284 """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
285
286 The choice of .pyc or .pyo extension is done based on the __debug__ flag
287 value.
288
289 :param source: The file system path to the source file. The source file
290 does not need to exist, however the PEP 3147 pyc file must exist.
291 :return: The file system path to the legacy pyc file.
292 """
293 pyc_file = imp.cache_from_source(source)
294 up_one = os.path.dirname(os.path.abspath(source))
295 legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
296 os.rename(pyc_file, legacy_pyc)
297 return legacy_pyc
298
Guido van Rossum3bead091992-01-27 17:00:37 +0000299def forget(modname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000300 """'Forget' a module was ever imported.
301
302 This removes the module from sys.modules and deletes any PEP 3147 or
303 legacy .pyc and .pyo files.
304 """
Fred Drake004d5e62000-10-23 17:22:08 +0000305 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000306 for dirname in sys.path:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000307 source = os.path.join(dirname, modname + '.py')
308 # It doesn't matter if they exist or not, unlink all possible
309 # combinations of PEP 3147 and legacy pyc and pyo files.
310 unlink(source + 'c')
311 unlink(source + 'o')
312 unlink(imp.cache_from_source(source, debug_override=True))
313 unlink(imp.cache_from_source(source, debug_override=False))
Guido van Rossum3bead091992-01-27 17:00:37 +0000314
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000315# On some platforms, should not run gui test even if it is allowed
316# in `use_resources'.
317if sys.platform.startswith('win'):
318 import ctypes
319 import ctypes.wintypes
320 def _is_gui_available():
321 UOI_FLAGS = 1
322 WSF_VISIBLE = 0x0001
323 class USEROBJECTFLAGS(ctypes.Structure):
324 _fields_ = [("fInherit", ctypes.wintypes.BOOL),
325 ("fReserved", ctypes.wintypes.BOOL),
326 ("dwFlags", ctypes.wintypes.DWORD)]
327 dll = ctypes.windll.user32
328 h = dll.GetProcessWindowStation()
329 if not h:
330 raise ctypes.WinError()
331 uof = USEROBJECTFLAGS()
332 needed = ctypes.wintypes.DWORD()
333 res = dll.GetUserObjectInformationW(h,
334 UOI_FLAGS,
335 ctypes.byref(uof),
336 ctypes.sizeof(uof),
337 ctypes.byref(needed))
338 if not res:
339 raise ctypes.WinError()
340 return bool(uof.dwFlags & WSF_VISIBLE)
341else:
342 def _is_gui_available():
343 return True
344
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000345def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000346 """Test whether a resource is enabled. Known resources are set by
347 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000348 return use_resources is not None and resource in use_resources
349
Barry Warsawc0fb6052001-08-20 22:29:23 +0000350def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000351 """Raise ResourceDenied if the specified resource is not available.
352
353 If the caller's module is __main__ then automatically return True. The
Barry Warsaw28a691b2010-04-17 00:19:56 +0000354 possibility of False being returned occurs when regrtest.py is
355 executing.
356 """
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000357 if resource == 'gui' and not _is_gui_available():
358 raise unittest.SkipTest("Cannot use the 'gui' resource")
Skip Montanarod839ecd2003-04-24 19:06:57 +0000359 # see if the caller's module is __main__ - if so, treat as if
360 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000361 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000362 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000363 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000364 if msg is None:
365 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000366 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000367
Victor Stinner88701e22011-06-01 13:13:04 +0200368def requires_mac_ver(*min_version):
369 """Decorator raising SkipTest if the OS is Mac OS X and the OS X
370 version if less than min_version.
371
372 For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
373 is lesser than 10.5.
374 """
375 def decorator(func):
376 @functools.wraps(func)
377 def wrapper(*args, **kw):
378 if sys.platform == 'darwin':
379 version_txt = platform.mac_ver()[0]
380 try:
381 version = tuple(map(int, version_txt.split('.')))
382 except ValueError:
383 pass
384 else:
385 if version < min_version:
386 min_version_txt = '.'.join(map(str, min_version))
387 raise unittest.SkipTest(
388 "Mac OS X %s or higher required, not %s"
389 % (min_version_txt, version_txt))
390 return func(*args, **kw)
391 wrapper.min_version = min_version
392 return wrapper
393 return decorator
394
Christian Heimes5e696852008-04-09 08:37:03 +0000395HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000396
Christian Heimes5e696852008-04-09 08:37:03 +0000397def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
398 """Returns an unused port that should be suitable for binding. This is
399 achieved by creating a temporary socket with the same family and type as
400 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
401 the specified host address (defaults to 0.0.0.0) with the port set to 0,
402 eliciting an unused ephemeral port from the OS. The temporary socket is
403 then closed and deleted, and the ephemeral port is returned.
404
405 Either this method or bind_port() should be used for any tests where a
406 server socket needs to be bound to a particular port for the duration of
407 the test. Which one to use depends on whether the calling code is creating
408 a python socket, or if an unused port needs to be provided in a constructor
409 or passed to an external program (i.e. the -accept argument to openssl's
410 s_server mode). Always prefer bind_port() over find_unused_port() where
411 possible. Hard coded ports should *NEVER* be used. As soon as a server
412 socket is bound to a hard coded port, the ability to run multiple instances
413 of the test simultaneously on the same host is compromised, which makes the
414 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
415 may simply manifest as a failed test, which can be recovered from without
416 intervention in most cases, but on Windows, the entire python process can
417 completely and utterly wedge, requiring someone to log in to the buildbot
418 and manually kill the affected process.
419
420 (This is easy to reproduce on Windows, unfortunately, and can be traced to
421 the SO_REUSEADDR socket option having different semantics on Windows versus
422 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
423 listen and then accept connections on identical host/ports. An EADDRINUSE
424 socket.error will be raised at some point (depending on the platform and
425 the order bind and listen were called on each socket).
426
427 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
428 will ever be raised when attempting to bind two identical host/ports. When
429 accept() is called on each socket, the second caller's process will steal
430 the port from the first caller, leaving them both in an awkwardly wedged
431 state where they'll no longer respond to any signals or graceful kills, and
432 must be forcibly killed via OpenProcess()/TerminateProcess().
433
434 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
435 instead of SO_REUSEADDR, which effectively affords the same semantics as
436 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
437 Source world compared to Windows ones, this is a common mistake. A quick
438 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
439 openssl.exe is called with the 's_server' option, for example. See
440 http://bugs.python.org/issue2550 for more info. The following site also
441 has a very thorough description about the implications of both REUSEADDR
442 and EXCLUSIVEADDRUSE on Windows:
443 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
444
445 XXX: although this approach is a vast improvement on previous attempts to
446 elicit unused ports, it rests heavily on the assumption that the ephemeral
447 port returned to us by the OS won't immediately be dished back out to some
448 other process when we close and delete our temporary socket but before our
449 calling code has a chance to bind the returned port. We can deal with this
450 issue if/when we come across it.
451 """
452
453 tempsock = socket.socket(family, socktype)
454 port = bind_port(tempsock)
455 tempsock.close()
456 del tempsock
457 return port
458
459def bind_port(sock, host=HOST):
460 """Bind the socket to a free port and return the port number. Relies on
461 ephemeral ports in order to ensure we are using an unbound port. This is
462 important as many tests may be running simultaneously, especially in a
463 buildbot environment. This method raises an exception if the sock.family
464 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
465 or SO_REUSEPORT set on it. Tests should *never* set these socket options
466 for TCP/IP sockets. The only case for setting these options is testing
467 multicasting via multiple UDP sockets.
468
469 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
470 on Windows), it will be set on the socket. This will prevent anyone else
471 from bind()'ing to our host/port for the duration of the test.
472 """
473
474 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
475 if hasattr(socket, 'SO_REUSEADDR'):
476 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
477 raise TestFailed("tests should never set the SO_REUSEADDR " \
478 "socket option on TCP/IP sockets!")
479 if hasattr(socket, 'SO_REUSEPORT'):
480 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
481 raise TestFailed("tests should never set the SO_REUSEPORT " \
482 "socket option on TCP/IP sockets!")
483 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
484 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
485
486 sock.bind((host, 0))
487 port = sock.getsockname()[1]
488 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000489
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000490FUZZ = 1e-6
491
492def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000493 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000494 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000495 fuzz = (abs(x) + abs(y)) * FUZZ
496 if abs(x-y) <= fuzz:
497 return 0
498 except:
499 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000500 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000501 for i in range(min(len(x), len(y))):
502 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000503 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000504 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000505 return (len(x) > len(y)) - (len(x) < len(y))
506 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000507
Eric Smithf24a0d92010-12-04 13:32:18 +0000508# decorator for skipping tests on non-IEEE 754 platforms
509requires_IEEE_754 = unittest.skipUnless(
510 float.__getformat__("double").startswith("IEEE"),
511 "test requires IEEE 754 doubles")
512
Finn Bock57bc5fa2002-11-01 18:02:03 +0000513is_jython = sys.platform.startswith('java')
514
Barry Warsaw559f6682001-03-23 18:04:02 +0000515# Filename used for testing
516if os.name == 'java':
517 # Jython disallows @ in module names
518 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000519else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000520 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000521
Antoine Pitrou88909542009-06-29 13:54:42 +0000522# Disambiguate TESTFN for parallel testing, while letting it remain a valid
523# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000524TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000525
Victor Stinner0af71aa2013-01-03 01:50:30 +0100526# FS_NONASCII: non-ASCII character encodable by os.fsencode(),
527# or None if there is no such character.
528FS_NONASCII = None
529for character in (
530 # First try printable and common characters to have a readable filename.
531 # For each character, the encoding list are just example of encodings able
532 # to encode the character (the list is not exhaustive).
533
534 # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
535 '\u00E6',
536 # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
537 '\u0130',
538 # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
539 '\u0141',
540 # U+03C6 (Greek Small Letter Phi): cp1253
541 '\u03C6',
542 # U+041A (Cyrillic Capital Letter Ka): cp1251
543 '\u041A',
544 # U+05D0 (Hebrew Letter Alef): Encodable to cp424
545 '\u05D0',
546 # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
547 '\u060C',
548 # U+062A (Arabic Letter Teh): cp720
549 '\u062A',
550 # U+0E01 (Thai Character Ko Kai): cp874
551 '\u0E01',
552
553 # Then try more "special" characters. "special" because they may be
554 # interpreted or displayed differently depending on the exact locale
555 # encoding and the font.
556
557 # U+00A0 (No-Break Space)
558 '\u00A0',
559 # U+20AC (Euro Sign)
560 '\u20AC',
561):
562 try:
563 os.fsdecode(os.fsencode(character))
564 except UnicodeError:
565 pass
566 else:
567 FS_NONASCII = character
568 break
Michael Foord2d9c2d52010-05-04 22:29:10 +0000569
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000570# TESTFN_UNICODE is a non-ascii filename
571TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
Victor Stinner74a833f2010-08-18 21:06:23 +0000572if sys.platform == 'darwin':
573 # In Mac OS X's VFS API file names are, by definition, canonically
574 # decomposed Unicode, encoded using UTF-8. See QA1173:
575 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
576 import unicodedata
577 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
Antoine Pitrou88909542009-06-29 13:54:42 +0000578TESTFN_ENCODING = sys.getfilesystemencoding()
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000579
Victor Stinner09c449c2010-08-13 22:23:24 +0000580# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000581# encoded by the filesystem encoding (in strict mode). It can be None if we
582# cannot generate such filename.
Victor Stinnera0241c82010-08-15 19:28:21 +0000583TESTFN_UNENCODABLE = None
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000584if os.name in ('nt', 'ce'):
Victor Stinnera0241c82010-08-15 19:28:21 +0000585 # skip win32s (0) or Windows 9x/ME (1)
586 if sys.getwindowsversion().platform >= 2:
Victor Stinner8ce7df62010-09-10 11:19:59 +0000587 # Different kinds of characters from various languages to minimize the
588 # probability that the whole name is encodable to MBCS (issue #9819)
589 TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000590 try:
Victor Stinner09c449c2010-08-13 22:23:24 +0000591 TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000592 except UnicodeEncodeError:
593 pass
594 else:
595 print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
596 'Unicode filename tests may not be effective'
Victor Stinner09c449c2010-08-13 22:23:24 +0000597 % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
598 TESTFN_UNENCODABLE = None
Victor Stinnera0241c82010-08-15 19:28:21 +0000599# Mac OS X denies unencodable filenames (invalid utf-8)
Victor Stinner03c9e1d2010-08-14 17:35:20 +0000600elif sys.platform != 'darwin':
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000601 try:
602 # ascii and utf-8 cannot encode the byte 0xff
603 b'\xff'.decode(TESTFN_ENCODING)
604 except UnicodeDecodeError:
605 # 0xff will be encoded using the surrogate character u+DCFF
Victor Stinner09c449c2010-08-13 22:23:24 +0000606 TESTFN_UNENCODABLE = TESTFN \
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000607 + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
608 else:
609 # File system encoding (eg. ISO-8859-* encodings) can encode
610 # the byte 0xff. Skip some unicode filename tests.
Victor Stinnera0241c82010-08-15 19:28:21 +0000611 pass
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000612
Victor Stinner0af71aa2013-01-03 01:50:30 +0100613# TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be
614# decoded from the filesystem encoding (in strict mode). It can be None if we
615# cannot generate such filename (ex: the latin1 encoding can decode any byte
616# sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks
617# to the surrogateescape error handler (PEP 383), but not from the filesystem
618# encoding in strict mode.
619TESTFN_UNDECODABLE = None
620for name in (
621 # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows
622 # accepts it to create a file or a directory, or don't accept to enter to
623 # such directory (when the bytes name is used). So test b'\xe7' first: it is
624 # not decodable from cp932.
625 b'\xe7w\xf0',
626 # undecodable from ASCII, UTF-8
627 b'\xff',
628 # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856
629 # and cp857
630 b'\xae\xd5'
631 # undecodable from UTF-8 (UNIX and Mac OS X)
632 b'\xed\xb2\x80', b'\xed\xb4\x80',
633 # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252,
634 # cp1253, cp1254, cp1255, cp1257, cp1258
635 b'\x81\x98',
636):
637 try:
638 name.decode(TESTFN_ENCODING)
639 except UnicodeDecodeError:
640 TESTFN_UNDECODABLE = os.fsencode(TESTFN) + name
641 break
642
643if FS_NONASCII:
644 TESTFN_NONASCII = TESTFN + '-' + FS_NONASCII
645else:
646 TESTFN_NONASCII = None
647
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000648# Save the initial cwd
649SAVEDCWD = os.getcwd()
650
651@contextlib.contextmanager
Nick Coghland26c18a2010-08-17 13:06:11 +0000652def temp_cwd(name='tempcwd', quiet=False, path=None):
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000653 """
Nick Coghland26c18a2010-08-17 13:06:11 +0000654 Context manager that temporarily changes the CWD.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000655
Nick Coghland26c18a2010-08-17 13:06:11 +0000656 An existing path may be provided as *path*, in which case this
657 function makes no changes to the file system.
658
659 Otherwise, the new CWD is created in the current directory and it's
660 named *name*. If *quiet* is False (default) and it's not possible to
661 create or change the CWD, an error is raised. If it's True, only a
662 warning is raised and the original CWD is used.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000663 """
664 saved_dir = os.getcwd()
665 is_temporary = False
Nick Coghland26c18a2010-08-17 13:06:11 +0000666 if path is None:
667 path = name
668 try:
669 os.mkdir(name)
670 is_temporary = True
671 except OSError:
672 if not quiet:
673 raise
674 warnings.warn('tests may fail, unable to create temp CWD ' + name,
675 RuntimeWarning, stacklevel=3)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000676 try:
Nick Coghland26c18a2010-08-17 13:06:11 +0000677 os.chdir(path)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000678 except OSError:
679 if not quiet:
680 raise
Ezio Melottie418d762012-09-21 16:48:12 +0300681 warnings.warn('tests may fail, unable to change the CWD to ' + path,
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000682 RuntimeWarning, stacklevel=3)
683 try:
684 yield os.getcwd()
685 finally:
686 os.chdir(saved_dir)
687 if is_temporary:
688 rmtree(name)
689
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000690
Barry Warsaw28a691b2010-04-17 00:19:56 +0000691@contextlib.contextmanager
692def temp_umask(umask):
693 """Context manager that temporarily sets the process umask."""
694 oldmask = os.umask(umask)
695 try:
696 yield
697 finally:
698 os.umask(oldmask)
699
700
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000701def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000702 """Try to find a file on sys.path and the working directory. If it is not
703 found the argument passed to the function is returned (this does not
704 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000705 if os.path.isabs(file):
706 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000707 if subdir is not None:
708 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000709 path = sys.path
710 path = [os.path.dirname(here)] + path
711 for dn in path:
712 fn = os.path.join(dn, file)
713 if os.path.exists(fn): return fn
714 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000715
Tim Peters2f228e72001-05-13 00:19:31 +0000716def sortdict(dict):
717 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000718 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000719 reprpairs = ["%r: %r" % pair for pair in items]
720 withcommas = ", ".join(reprpairs)
721 return "{%s}" % withcommas
722
Benjamin Peterson7522c742009-01-19 21:00:09 +0000723def make_bad_fd():
724 """
725 Create an invalid file descriptor by opening and closing a file and return
726 its fd.
727 """
728 file = open(TESTFN, "wb")
729 try:
730 return file.fileno()
731 finally:
732 file.close()
733 unlink(TESTFN)
734
Thomas Wouters89f507f2006-12-13 04:49:30 +0000735def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000736 testcase.assertRaises(SyntaxError, compile, statement,
737 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000738
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000739def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000740 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000741
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000742 check = kw.pop('check', None)
743
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000744 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000745
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000746 fn = os.path.join(os.path.dirname(__file__), "data", filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000747
748 def check_valid_file(fn):
749 f = open(fn, *args, **kw)
750 if check is None:
751 return f
752 elif check(f):
753 f.seek(0)
754 return f
755 f.close()
756
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000757 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000758 f = check_valid_file(fn)
759 if f is not None:
760 return f
761 unlink(fn)
762
763 # Verify the requirement before downloading the file
764 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000765
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000766 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000767 f = urllib.request.urlopen(url, timeout=15)
768 try:
769 with open(fn, "wb") as out:
770 s = f.read()
771 while s:
772 out.write(s)
773 s = f.read()
774 finally:
775 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000776
777 f = check_valid_file(fn)
778 if f is not None:
779 return f
780 raise TestFailed('invalid resource "%s"' % fn)
781
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000782
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000783class WarningsRecorder(object):
784 """Convenience wrapper for the warnings list returned on
785 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000786 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000787 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000788 self._warnings = warnings_list
789 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000790
791 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000792 if len(self._warnings) > self._last:
793 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000794 elif attr in warnings.WarningMessage._WARNING_DETAILS:
795 return None
796 raise AttributeError("%r has no attribute %r" % (self, attr))
797
Florent Xiclunab14930c2010-03-13 15:26:44 +0000798 @property
799 def warnings(self):
800 return self._warnings[self._last:]
801
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000802 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000803 self._last = len(self._warnings)
804
805
806def _filterwarnings(filters, quiet=False):
807 """Catch the warnings, then check if all the expected
808 warnings have been raised and re-raise unexpected warnings.
809 If 'quiet' is True, only re-raise the unexpected warnings.
810 """
811 # Clear the warning registry of the calling module
812 # in order to re-raise the warnings.
813 frame = sys._getframe(2)
814 registry = frame.f_globals.get('__warningregistry__')
815 if registry:
816 registry.clear()
817 with warnings.catch_warnings(record=True) as w:
818 # Set filter "always" to record all warnings. Because
819 # test_warnings swap the module, we need to look up in
820 # the sys.modules dictionary.
821 sys.modules['warnings'].simplefilter("always")
822 yield WarningsRecorder(w)
823 # Filter the recorded warnings
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000824 reraise = list(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000825 missing = []
826 for msg, cat in filters:
827 seen = False
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000828 for w in reraise[:]:
829 warning = w.message
Florent Xiclunab14930c2010-03-13 15:26:44 +0000830 # Filter out the matching messages
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000831 if (re.match(msg, str(warning), re.I) and
832 issubclass(warning.__class__, cat)):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000833 seen = True
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000834 reraise.remove(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000835 if not seen and not quiet:
836 # This filter caught nothing
837 missing.append((msg, cat.__name__))
838 if reraise:
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000839 raise AssertionError("unhandled warning %s" % reraise[0])
Florent Xiclunab14930c2010-03-13 15:26:44 +0000840 if missing:
841 raise AssertionError("filter (%r, %s) did not catch any warning" %
842 missing[0])
843
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000844
845@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000846def check_warnings(*filters, **kwargs):
847 """Context manager to silence warnings.
848
849 Accept 2-tuples as positional arguments:
850 ("message regexp", WarningCategory)
851
852 Optional argument:
853 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506b2010-03-18 20:00:57 +0000854 (default True without argument,
855 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000856
857 Without argument, it defaults to:
Florent Xicluna53b506b2010-03-18 20:00:57 +0000858 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000859 """
Florent Xicluna53b506b2010-03-18 20:00:57 +0000860 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +0000861 if not filters:
862 filters = (("", Warning),)
Florent Xicluna53b506b2010-03-18 20:00:57 +0000863 # Preserve backward compatibility
864 if quiet is None:
865 quiet = True
866 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000867
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000868
869class CleanImport(object):
870 """Context manager to force import to return a new module reference.
871
872 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000873 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000874
875 Use like this:
876
877 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000878 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000879 """
880
881 def __init__(self, *module_names):
882 self.original_modules = sys.modules.copy()
883 for module_name in module_names:
884 if module_name in sys.modules:
885 module = sys.modules[module_name]
886 # It is possible that module_name is just an alias for
887 # another module (e.g. stub for modules renamed in 3.x).
888 # In that case, we also need delete the real module to clear
889 # the import cache.
890 if module.__name__ != module_name:
891 del sys.modules[module.__name__]
892 del sys.modules[module_name]
893
894 def __enter__(self):
895 return self
896
897 def __exit__(self, *ignore_exc):
898 sys.modules.update(self.original_modules)
899
900
Walter Dörwald155374d2009-05-01 19:58:58 +0000901class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000902
903 """Class to help protect the environment variable properly. Can be used as
904 a context manager."""
905
906 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000907 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000908 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000909
Walter Dörwald155374d2009-05-01 19:58:58 +0000910 def __getitem__(self, envvar):
911 return self._environ[envvar]
912
913 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000914 # Remember the initial value on the first access
915 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000916 self._changed[envvar] = self._environ.get(envvar)
917 self._environ[envvar] = value
918
919 def __delitem__(self, envvar):
920 # Remember the initial value on the first access
921 if envvar not in self._changed:
922 self._changed[envvar] = self._environ.get(envvar)
923 if envvar in self._environ:
924 del self._environ[envvar]
925
926 def keys(self):
927 return self._environ.keys()
928
929 def __iter__(self):
930 return iter(self._environ)
931
932 def __len__(self):
933 return len(self._environ)
934
935 def set(self, envvar, value):
936 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000937
938 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000939 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000940
941 def __enter__(self):
942 return self
943
944 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000945 for (k, v) in self._changed.items():
946 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000947 if k in self._environ:
948 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000949 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000950 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000951 os.environ = self._environ
952
953
954class DirsOnSysPath(object):
955 """Context manager to temporarily add directories to sys.path.
956
957 This makes a copy of sys.path, appends any directories given
958 as positional arguments, then reverts sys.path to the copied
959 settings when the context ends.
960
961 Note that *all* sys.path modifications in the body of the
962 context manager, including replacement of the object,
963 will be reverted at the end of the block.
964 """
965
966 def __init__(self, *paths):
967 self.original_value = sys.path[:]
968 self.original_object = sys.path
969 sys.path.extend(paths)
970
971 def __enter__(self):
972 return self
973
974 def __exit__(self, *ignore_exc):
975 sys.path = self.original_object
976 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000977
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000978
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979class TransientResource(object):
980
981 """Raise ResourceDenied if an exception is raised while the context manager
982 is in effect that matches the specified exception and attributes."""
983
984 def __init__(self, exc, **kwargs):
985 self.exc = exc
986 self.attrs = kwargs
987
988 def __enter__(self):
989 return self
990
991 def __exit__(self, type_=None, value=None, traceback=None):
992 """If type_ is a subclass of self.exc and value has attributes matching
993 self.attrs, raise ResourceDenied. Otherwise let the exception
994 propagate (if any)."""
995 if type_ is not None and issubclass(self.exc, type_):
996 for attr, attr_value in self.attrs.items():
997 if not hasattr(value, attr):
998 break
999 if getattr(value, attr) != attr_value:
1000 break
1001 else:
1002 raise ResourceDenied("an optional resource is not available")
1003
Raymond Hettinger686057b2009-06-04 00:11:54 +00001004# Context managers that raise ResourceDenied when various issues
1005# with the Internet connection manifest themselves as exceptions.
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001006# XXX deprecate these and use transient_internet() instead
Raymond Hettinger686057b2009-06-04 00:11:54 +00001007time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
1008socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
1009ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001010
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001011
Thomas Woutersed03b412007-08-28 21:37:11 +00001012@contextlib.contextmanager
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001013def transient_internet(resource_name, *, timeout=30.0, errnos=()):
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001014 """Return a context manager that raises ResourceDenied when various issues
1015 with the Internet connection manifest themselves as exceptions."""
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001016 default_errnos = [
1017 ('ECONNREFUSED', 111),
1018 ('ECONNRESET', 104),
Antoine Pitrou5d938cb2011-01-08 10:28:11 +00001019 ('EHOSTUNREACH', 113),
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001020 ('ENETUNREACH', 101),
1021 ('ETIMEDOUT', 110),
1022 ]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001023 default_gai_errnos = [
Antoine Pitrou4875c462011-07-09 02:31:24 +02001024 ('EAI_AGAIN', -3),
Charles-François Natali13859bf2011-12-10 13:16:44 +01001025 ('EAI_FAIL', -4),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001026 ('EAI_NONAME', -2),
1027 ('EAI_NODATA', -5),
Antoine Pitrou390ea0f2011-04-29 00:44:33 +02001028 # Encountered when trying to resolve IPv6-only hostnames
1029 ('WSANO_DATA', 11004),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001030 ]
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001031
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001032 denied = ResourceDenied("Resource '%s' is not available" % resource_name)
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001033 captured_errnos = errnos
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001034 gai_errnos = []
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001035 if not captured_errnos:
1036 captured_errnos = [getattr(errno, name, num)
1037 for (name, num) in default_errnos]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001038 gai_errnos = [getattr(socket, name, num)
1039 for (name, num) in default_gai_errnos]
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001040
1041 def filter_error(err):
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001042 n = getattr(err, 'errno', None)
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001043 if (isinstance(err, socket.timeout) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +00001044 (isinstance(err, socket.gaierror) and n in gai_errnos) or
1045 n in captured_errnos):
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001046 if not verbose:
1047 sys.stderr.write(denied.args[0] + "\n")
1048 raise denied from err
1049
1050 old_timeout = socket.getdefaulttimeout()
1051 try:
1052 if timeout is not None:
1053 socket.setdefaulttimeout(timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001054 yield
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001055 except IOError as err:
Antoine Pitrou8bc09032010-09-07 21:09:09 +00001056 # urllib can wrap original socket errors multiple times (!), we must
1057 # unwrap to get at the original error.
1058 while True:
1059 a = err.args
1060 if len(a) >= 1 and isinstance(a[0], IOError):
1061 err = a[0]
1062 # The error can also be wrapped as args[1]:
1063 # except socket.error as msg:
1064 # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
1065 elif len(a) >= 2 and isinstance(a[1], IOError):
1066 err = a[1]
1067 else:
1068 break
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001069 filter_error(err)
Antoine Pitroua88c83c2010-09-07 20:42:19 +00001070 raise
1071 # XXX should we catch generic exceptions and look for their
1072 # __cause__ or __context__?
1073 finally:
1074 socket.setdefaulttimeout(old_timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001075
1076
1077@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001078def captured_output(stream_name):
Ezio Melotti07352b02011-05-14 14:51:18 +03001079 """Return a context manager used by captured_stdout/stdin/stderr
Ezio Melottifc778fd2011-05-14 08:22:47 +03001080 that temporarily replaces the sys stream *stream_name* with a StringIO."""
Thomas Woutersed03b412007-08-28 21:37:11 +00001081 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001082 orig_stdout = getattr(sys, stream_name)
1083 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001084 try:
1085 yield getattr(sys, stream_name)
1086 finally:
1087 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001088
1089def captured_stdout():
Ezio Melottifc778fd2011-05-14 08:22:47 +03001090 """Capture the output of sys.stdout:
1091
1092 with captured_stdout() as s:
1093 print("hello")
1094 self.assertEqual(s.getvalue(), "hello")
1095 """
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001096 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +00001097
Nick Coghlan6b22f3f2010-12-12 15:24:21 +00001098def captured_stderr():
1099 return captured_output("stderr")
1100
Nick Coghlan6ead5522009-10-18 13:19:33 +00001101def captured_stdin():
1102 return captured_output("stdin")
1103
Ezio Melotti07352b02011-05-14 14:51:18 +03001104
Benjamin Petersone549ead2009-03-28 21:42:05 +00001105def gc_collect():
1106 """Force as many objects as possible to be collected.
1107
1108 In non-CPython implementations of Python, this is needed because timely
1109 deallocation is not guaranteed by the garbage collector. (Even in CPython
1110 this can be the case in case of reference cycles.) This means that __del__
1111 methods may be called later than expected and weakrefs may remain alive for
1112 longer than expected. This function tries its best to force all garbage
1113 objects to disappear.
1114 """
Benjamin Petersone549ead2009-03-28 21:42:05 +00001115 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +00001116 if is_jython:
1117 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00001118 gc.collect()
1119 gc.collect()
1120
Thomas Woutersed03b412007-08-28 21:37:11 +00001121
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001122def python_is_optimized():
1123 """Find if Python was built with optimizations."""
Antoine Pitrou64474542010-10-31 11:34:47 +00001124 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001125 final_opt = ""
1126 for opt in cflags.split():
1127 if opt.startswith('-O'):
1128 final_opt = opt
1129 return final_opt and final_opt != '-O0'
1130
1131
Martin v. Löwis33f79972012-07-29 16:33:05 +02001132_header = '2P'
1133if hasattr(sys, "gettotalrefcount"):
1134 _header = '2P' + _header
1135_vheader = _header + 'P'
1136
1137def calcobjsize(fmt):
1138 return struct.calcsize(_header + fmt + '0P')
1139
1140def calcvobjsize(fmt):
1141 return struct.calcsize(_vheader + fmt + '0P')
1142
1143
1144_TPFLAGS_HAVE_GC = 1<<14
1145_TPFLAGS_HEAPTYPE = 1<<9
1146
1147def check_sizeof(test, o, size):
1148 result = sys.getsizeof(o)
1149 # add GC header size
1150 if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
1151 ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
1152 size += _testcapi.SIZEOF_PYGC_HEAD
1153 msg = 'wrong size for %s: got %d, expected %d' \
1154 % (type(o), result, size)
1155 test.assertEqual(result, size, msg)
1156
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001157#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001158# Decorator for running a function in a different locale, correctly resetting
1159# it afterwards.
1160
1161def run_with_locale(catstr, *locales):
1162 def decorator(func):
1163 def inner(*args, **kwds):
1164 try:
1165 import locale
1166 category = getattr(locale, catstr)
1167 orig_locale = locale.setlocale(category)
1168 except AttributeError:
1169 # if the test author gives us an invalid category string
1170 raise
1171 except:
1172 # cannot retrieve original locale, so do nothing
1173 locale = orig_locale = None
1174 else:
1175 for loc in locales:
1176 try:
1177 locale.setlocale(category, loc)
1178 break
1179 except:
1180 pass
1181
1182 # now run the function, resetting the locale on exceptions
1183 try:
1184 return func(*args, **kwds)
1185 finally:
1186 if locale and orig_locale:
1187 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +00001188 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +00001189 inner.__doc__ = func.__doc__
1190 return inner
1191 return decorator
1192
1193#=======================================================================
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001194# Decorator for running a function in a specific timezone, correctly
1195# resetting it afterwards.
1196
1197def run_with_tz(tz):
1198 def decorator(func):
1199 def inner(*args, **kwds):
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001200 try:
1201 tzset = time.tzset
1202 except AttributeError:
1203 raise unittest.SkipTest("tzset required")
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001204 if 'TZ' in os.environ:
1205 orig_tz = os.environ['TZ']
1206 else:
1207 orig_tz = None
1208 os.environ['TZ'] = tz
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001209 tzset()
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001210
1211 # now run the function, resetting the tz on exceptions
1212 try:
1213 return func(*args, **kwds)
1214 finally:
1215 if orig_tz == None:
1216 del os.environ['TZ']
1217 else:
1218 os.environ['TZ'] = orig_tz
1219 time.tzset()
1220
1221 inner.__name__ = func.__name__
1222 inner.__doc__ = func.__doc__
1223 return inner
1224 return decorator
1225
1226#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +00001227# Big-memory-test support. Separate from 'resources' because memory use
1228# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001229
1230# Some handy shorthands. Note that these are used for byte-limits as well
1231# as size-limits, in the various bigmem tests
1232_1M = 1024*1024
1233_1G = 1024 * _1M
1234_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001235_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001237MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001238
Thomas Wouters477c8d52006-05-27 19:21:47 +00001239def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001241 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001242 sizes = {
1243 'k': 1024,
1244 'm': _1M,
1245 'g': _1G,
1246 't': 1024*_1G,
1247 }
1248 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
1249 re.IGNORECASE | re.VERBOSE)
1250 if m is None:
1251 raise ValueError('Invalid memory limit %r' % (limit,))
1252 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001253 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001254 if memlimit > MAX_Py_ssize_t:
1255 memlimit = MAX_Py_ssize_t
1256 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 raise ValueError('Memory limit %r too low to be useful' % (limit,))
1258 max_memuse = memlimit
1259
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001260def _memory_watchdog(start_evt, finish_evt, period=10.0):
1261 """A function which periodically watches the process' memory consumption
1262 and prints it out.
1263 """
1264 # XXX: because of the GIL, and because the very long operations tested
1265 # in most bigmem tests are uninterruptible, the loop below gets woken up
1266 # much less often than expected.
1267 # The polling code should be rewritten in raw C, without holding the GIL,
1268 # and push results onto an anonymous pipe.
1269 try:
1270 page_size = os.sysconf('SC_PAGESIZE')
1271 except (ValueError, AttributeError):
1272 try:
1273 page_size = os.sysconf('SC_PAGE_SIZE')
1274 except (ValueError, AttributeError):
1275 page_size = 4096
1276 procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
1277 try:
1278 f = open(procfile, 'rb')
1279 except IOError as e:
1280 warnings.warn('/proc not available for stats: {}'.format(e),
1281 RuntimeWarning)
1282 sys.stderr.flush()
1283 return
1284 with f:
1285 start_evt.set()
1286 old_data = -1
1287 while not finish_evt.wait(period):
1288 f.seek(0)
1289 statm = f.read().decode('ascii')
1290 data = int(statm.split()[5])
1291 if data != old_data:
1292 old_data = data
1293 print(" ... process data size: {data:.1f}G"
1294 .format(data=data * page_size / (1024 ** 3)))
1295
1296def bigmemtest(size, memuse, dry_run=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001297 """Decorator for bigmem tests.
1298
1299 'minsize' is the minimum useful size for the test (in arbitrary,
1300 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001301 the test, or a good estimate of it.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001302
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001303 if 'dry_run' is False, it means the test doesn't support dummy runs
1304 when -M is not specified.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001305 """
1306 def decorator(f):
1307 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001308 size = wrapper.size
1309 memuse = wrapper.memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001310 if not real_max_memuse:
1311 maxsize = 5147
1312 else:
1313 maxsize = size
1314
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001315 if ((real_max_memuse or not dry_run)
1316 and real_max_memuse < maxsize * memuse):
1317 raise unittest.SkipTest(
1318 "not enough memory: %.1fG minimum needed"
1319 % (size * memuse / (1024 ** 3)))
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001320
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001321 if real_max_memuse and verbose and threading:
1322 print()
1323 print(" ... expected peak memory use: {peak:.1f}G"
1324 .format(peak=size * memuse / (1024 ** 3)))
1325 sys.stdout.flush()
1326 start_evt = threading.Event()
1327 finish_evt = threading.Event()
1328 t = threading.Thread(target=_memory_watchdog,
1329 args=(start_evt, finish_evt, 0.5))
1330 t.daemon = True
1331 t.start()
1332 start_evt.set()
1333 else:
1334 t = None
1335
1336 try:
1337 return f(self, maxsize)
1338 finally:
1339 if t:
1340 finish_evt.set()
1341 t.join()
1342
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001343 wrapper.size = size
1344 wrapper.memuse = memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001345 return wrapper
1346 return decorator
1347
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001348def bigaddrspacetest(f):
1349 """Decorator for tests that fill the address space."""
1350 def wrapper(self):
1351 if max_memuse < MAX_Py_ssize_t:
Antoine Pitrou98c62bd2011-01-12 21:58:39 +00001352 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
Antoine Pitroue0d3f8a2011-01-12 21:50:44 +00001353 raise unittest.SkipTest(
1354 "not enough memory: try a 32-bit build instead")
1355 else:
1356 raise unittest.SkipTest(
1357 "not enough memory: %.1fG minimum needed"
1358 % (MAX_Py_ssize_t / (1024 ** 3)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001359 else:
1360 return f(self)
1361 return wrapper
1362
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +00001364# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001365
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001366class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001367 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001368 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001369 test(result)
1370 return result
1371
Benjamin Petersone549ead2009-03-28 21:42:05 +00001372def _id(obj):
1373 return obj
1374
1375def requires_resource(resource):
Antoine Pitrou4914f9e2011-02-26 16:49:08 +00001376 if resource == 'gui' and not _is_gui_available():
1377 return unittest.skip("resource 'gui' is not available")
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +00001378 if is_resource_enabled(resource):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001379 return _id
1380 else:
1381 return unittest.skip("resource {0!r} is not enabled".format(resource))
1382
1383def cpython_only(test):
1384 """
1385 Decorator for tests only applicable on CPython.
1386 """
1387 return impl_detail(cpython=True)(test)
1388
1389def impl_detail(msg=None, **guards):
1390 if check_impl_detail(**guards):
1391 return _id
1392 if msg is None:
1393 guardnames, default = _parse_guards(guards)
1394 if default:
1395 msg = "implementation detail not available on {0}"
1396 else:
1397 msg = "implementation detail specific to {0}"
1398 guardnames = sorted(guardnames.keys())
1399 msg = msg.format(' or '.join(guardnames))
1400 return unittest.skip(msg)
1401
1402def _parse_guards(guards):
1403 # Returns a tuple ({platform_name: run_me}, default_value)
1404 if not guards:
1405 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +00001406 is_true = list(guards.values())[0]
1407 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001408 return (guards, not is_true)
1409
1410# Use the following check to guard CPython's implementation-specific tests --
1411# or to run them only on the implementation(s) guarded by the arguments.
1412def check_impl_detail(**guards):
1413 """This function returns True or False depending on the host platform.
1414 Examples:
1415 if check_impl_detail(): # only on CPython (default)
1416 if check_impl_detail(jython=True): # only on Jython
1417 if check_impl_detail(cpython=False): # everywhere except on CPython
1418 """
1419 guards, default = _parse_guards(guards)
1420 return guards.get(platform.python_implementation().lower(), default)
1421
1422
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001423def _filter_suite(suite, pred):
1424 """Recursively filter test cases in a suite based on a predicate."""
1425 newtests = []
1426 for test in suite._tests:
1427 if isinstance(test, unittest.TestSuite):
1428 _filter_suite(test, pred)
1429 newtests.append(test)
1430 else:
1431 if pred(test):
1432 newtests.append(test)
1433 suite._tests = newtests
1434
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001435
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001437 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001438 if verbose:
Antoine Pitrou216a3bc2011-07-23 22:33:39 +02001439 runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
1440 failfast=failfast)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001441 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001442 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001443
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001444 result = runner.run(suite)
1445 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001446 if len(result.errors) == 1 and not result.failures:
1447 err = result.errors[0][1]
1448 elif len(result.failures) == 1 and not result.errors:
1449 err = result.failures[0][1]
1450 else:
R. David Murray723357e2009-10-19 18:06:17 +00001451 err = "multiple errors occurred"
1452 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001453 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001454
Barry Warsawc10d6902001-09-20 06:30:41 +00001455
Walter Dörwald21d3a322003-05-01 17:45:56 +00001456def run_unittest(*classes):
1457 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001459 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001460 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001461 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001462 if cls in sys.modules:
1463 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1464 else:
1465 raise ValueError("str arguments must be keys in sys.modules")
1466 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001467 suite.addTest(cls)
1468 else:
1469 suite.addTest(unittest.makeSuite(cls))
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001470 def case_pred(test):
1471 if match_tests is None:
1472 return True
1473 for name in test.id().split("."):
1474 if fnmatch.fnmatchcase(name, match_tests):
1475 return True
1476 return False
1477 _filter_suite(suite, case_pred)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001478 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001479
Barry Warsawc10d6902001-09-20 06:30:41 +00001480
Tim Petersa0a62222001-09-09 06:12:01 +00001481#=======================================================================
1482# doctest driver.
1483
1484def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +00001485 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001486
1487 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001488 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001489 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001490 """
1491
1492 import doctest
1493
1494 if verbosity is None:
1495 verbosity = verbose
1496 else:
1497 verbosity = None
1498
Victor Stinnerbddc4d42011-06-29 15:52:46 +02001499 f, t = doctest.testmod(module, verbose=verbosity)
1500 if f:
1501 raise TestFailed("%d of %d doctests failed" % (f, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001502 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001503 print('doctest (%s) ... %d tests with zero failures' %
1504 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001505 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001506
Antoine Pitrou060cee22009-11-13 16:29:04 +00001507
1508#=======================================================================
1509# Support for saving and restoring the imported modules.
1510
1511def modules_setup():
1512 return sys.modules.copy(),
1513
1514def modules_cleanup(oldmodules):
1515 # Encoders/decoders are registered permanently within the internal
1516 # codec cache. If we destroy the corresponding modules their
1517 # globals will be set to None which will trip up the cached functions.
1518 encodings = [(k, v) for k, v in sys.modules.items()
1519 if k.startswith('encodings.')]
1520 sys.modules.clear()
1521 sys.modules.update(encodings)
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001522 # XXX: This kind of problem can affect more than just encodings. In particular
Eric Smitha3e8f3d2011-01-11 10:24:34 +00001523 # extension modules (such as _ssl) don't cope with reloading properly.
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001524 # Really, test modules should be cleaning out the test specific modules they
1525 # know they added (ala test_runpy) rather than relying on this function (as
1526 # test_importhooks and test_pkg do currently).
1527 # Implicitly imported *real* modules should be left alone (see issue 10556).
Antoine Pitrou060cee22009-11-13 16:29:04 +00001528 sys.modules.update(oldmodules)
1529
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001530#=======================================================================
1531# Threading support to prevent reporting refleaks when running regrtest.py -R
1532
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001533# NOTE: we use thread._count() rather than threading.enumerate() (or the
1534# moral equivalent thereof) because a threading.Thread object is still alive
1535# until its __bootstrap() method has returned, even after it has been
1536# unregistered from the threading module.
1537# thread._count(), on the other hand, only gets decremented *after* the
1538# __bootstrap() method has returned, which gives us reliable reference counts
1539# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001540
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001541def threading_setup():
Victor Stinner45df8202010-04-28 22:31:17 +00001542 if _thread:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001543 return _thread._count(), threading._dangling.copy()
Victor Stinner45df8202010-04-28 22:31:17 +00001544 else:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001545 return 1, ()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001546
Antoine Pitrou707f2282011-07-15 22:29:44 +02001547def threading_cleanup(*original_values):
Victor Stinner45df8202010-04-28 22:31:17 +00001548 if not _thread:
1549 return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001550 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001551 for count in range(_MAX_COUNT):
Antoine Pitrou707f2282011-07-15 22:29:44 +02001552 values = _thread._count(), threading._dangling
1553 if values == original_values:
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001554 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001555 time.sleep(0.1)
Antoine Pitrou707f2282011-07-15 22:29:44 +02001556 gc_collect()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001557 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001558
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001559def reap_threads(func):
Victor Stinner45df8202010-04-28 22:31:17 +00001560 """Use this function when threads are being used. This will
1561 ensure that the threads are cleaned up even when the test fails.
1562 If threading is unavailable this function does nothing.
1563 """
1564 if not _thread:
1565 return func
1566
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001567 @functools.wraps(func)
1568 def decorator(*args):
1569 key = threading_setup()
1570 try:
1571 return func(*args)
1572 finally:
1573 threading_cleanup(*key)
1574 return decorator
1575
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001576def reap_children():
1577 """Use this function at the end of test_main() whenever sub-processes
1578 are started. This will help ensure that no extra children (zombies)
1579 stick around to hog resources and create problems when looking
1580 for refleaks.
1581 """
1582
1583 # Reap all our dead child processes so we don't leave zombies around.
1584 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001585 if hasattr(os, 'waitpid'):
1586 any_process = -1
1587 while True:
1588 try:
1589 # This will raise an exception on Windows. That's ok.
1590 pid, status = os.waitpid(any_process, os.WNOHANG)
1591 if pid == 0:
1592 break
1593 except:
1594 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001595
1596@contextlib.contextmanager
1597def swap_attr(obj, attr, new_val):
1598 """Temporary swap out an attribute with a new object.
1599
1600 Usage:
1601 with swap_attr(obj, "attr", 5):
1602 ...
1603
1604 This will set obj.attr to 5 for the duration of the with: block,
1605 restoring the old value at the end of the block. If `attr` doesn't
1606 exist on `obj`, it will be created and then deleted at the end of the
1607 block.
1608 """
1609 if hasattr(obj, attr):
1610 real_val = getattr(obj, attr)
1611 setattr(obj, attr, new_val)
1612 try:
1613 yield
1614 finally:
1615 setattr(obj, attr, real_val)
1616 else:
1617 setattr(obj, attr, new_val)
1618 try:
1619 yield
1620 finally:
1621 delattr(obj, attr)
1622
1623@contextlib.contextmanager
1624def swap_item(obj, item, new_val):
1625 """Temporary swap out an item with a new object.
1626
1627 Usage:
1628 with swap_item(obj, "item", 5):
1629 ...
1630
1631 This will set obj["item"] to 5 for the duration of the with: block,
1632 restoring the old value at the end of the block. If `item` doesn't
1633 exist on `obj`, it will be created and then deleted at the end of the
1634 block.
1635 """
1636 if item in obj:
1637 real_val = obj[item]
1638 obj[item] = new_val
1639 try:
1640 yield
1641 finally:
1642 obj[item] = real_val
1643 else:
1644 obj[item] = new_val
1645 try:
1646 yield
1647 finally:
1648 del obj[item]
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00001649
1650def strip_python_stderr(stderr):
1651 """Strip the stderr of a Python process from potential debug output
1652 emitted by the interpreter.
1653
1654 This will typically be run on the result of the communicate() method
1655 of a subprocess.Popen object.
1656 """
1657 stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
1658 return stderr
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00001659
1660def args_from_interpreter_flags():
1661 """Return a list of command-line arguments reproducing the current
1662 settings in sys.flags."""
1663 flag_opt_map = {
1664 'bytes_warning': 'b',
1665 'dont_write_bytecode': 'B',
Antoine Pitroue9f637b2012-02-20 23:49:07 +01001666 'hash_randomization': 'R',
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00001667 'ignore_environment': 'E',
1668 'no_user_site': 's',
1669 'no_site': 'S',
1670 'optimize': 'O',
1671 'verbose': 'v',
1672 }
1673 args = []
1674 for flag, opt in flag_opt_map.items():
1675 v = getattr(sys.flags, flag)
1676 if v > 0:
1677 args.append('-' + opt * v)
1678 return args
Vinay Sajip129fd042010-12-10 08:19:38 +00001679
1680#============================================================
1681# Support for assertions about logging.
1682#============================================================
1683
1684class TestHandler(logging.handlers.BufferingHandler):
1685 def __init__(self, matcher):
1686 # BufferingHandler takes a "capacity" argument
1687 # so as to know when to flush. As we're overriding
1688 # shouldFlush anyway, we can set a capacity of zero.
1689 # You can call flush() manually to clear out the
1690 # buffer.
1691 logging.handlers.BufferingHandler.__init__(self, 0)
1692 self.matcher = matcher
1693
1694 def shouldFlush(self):
1695 return False
1696
1697 def emit(self, record):
1698 self.format(record)
1699 self.buffer.append(record.__dict__)
1700
1701 def matches(self, **kwargs):
1702 """
1703 Look for a saved dict whose keys/values match the supplied arguments.
1704 """
1705 result = False
1706 for d in self.buffer:
1707 if self.matcher.matches(d, **kwargs):
1708 result = True
1709 break
1710 return result
1711
1712class Matcher(object):
1713
1714 _partial_matches = ('msg', 'message')
1715
1716 def matches(self, d, **kwargs):
1717 """
1718 Try to match a single dict with the supplied arguments.
1719
1720 Keys whose values are strings and which are in self._partial_matches
1721 will be checked for partial (i.e. substring) matches. You can extend
1722 this scheme to (for example) do regular expression matching, etc.
1723 """
1724 result = True
1725 for k in kwargs:
1726 v = kwargs[k]
1727 dv = d.get(k)
1728 if not self.match_value(k, dv, v):
1729 result = False
1730 break
1731 return result
1732
1733 def match_value(self, k, dv, v):
1734 """
1735 Try to match a single stored value (dv) with a supplied value (v).
1736 """
1737 if type(v) != type(dv):
1738 result = False
1739 elif type(dv) is not str or k not in self._partial_matches:
1740 result = (v == dv)
1741 else:
1742 result = dv.find(v) >= 0
1743 return result
Brian Curtin3b4499c2010-12-28 14:31:47 +00001744
1745
1746_can_symlink = None
1747def can_symlink():
1748 global _can_symlink
1749 if _can_symlink is not None:
1750 return _can_symlink
Victor Stinner62ec61f2011-06-07 12:17:15 +02001751 symlink_path = TESTFN + "can_symlink"
Brian Curtin3b4499c2010-12-28 14:31:47 +00001752 try:
Victor Stinner62ec61f2011-06-07 12:17:15 +02001753 os.symlink(TESTFN, symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00001754 can = True
Brian Curtind25aef52011-06-13 15:16:04 -05001755 except (OSError, NotImplementedError, AttributeError):
Brian Curtin3b4499c2010-12-28 14:31:47 +00001756 can = False
Victor Stinner62ec61f2011-06-07 12:17:15 +02001757 else:
1758 os.remove(symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00001759 _can_symlink = can
1760 return can
1761
1762def skip_unless_symlink(test):
1763 """Skip decorator for tests that require functional symlink"""
1764 ok = can_symlink()
1765 msg = "Requires functional symlink implementation"
1766 return test if ok else unittest.skip(msg)(test)
Antoine Pitroue8706232011-03-15 21:05:36 +01001767
Antoine Pitrou2c50a092011-03-15 21:02:59 +01001768def patch(test_instance, object_to_patch, attr_name, new_value):
1769 """Override 'object_to_patch'.'attr_name' with 'new_value'.
1770
1771 Also, add a cleanup procedure to 'test_instance' to restore
1772 'object_to_patch' value for 'attr_name'.
1773 The 'attr_name' should be a valid attribute for 'object_to_patch'.
1774
1775 """
1776 # check that 'attr_name' is a real attribute for 'object_to_patch'
1777 # will raise AttributeError if it does not exist
1778 getattr(object_to_patch, attr_name)
1779
1780 # keep a copy of the old value
1781 attr_is_local = False
1782 try:
1783 old_value = object_to_patch.__dict__[attr_name]
1784 except (AttributeError, KeyError):
1785 old_value = getattr(object_to_patch, attr_name, None)
1786 else:
1787 attr_is_local = True
1788
1789 # restore the value when the test is done
1790 def cleanup():
1791 if attr_is_local:
1792 setattr(object_to_patch, attr_name, old_value)
1793 else:
1794 delattr(object_to_patch, attr_name)
1795
1796 test_instance.addCleanup(cleanup)
1797
1798 # actually override the attribute
1799 setattr(object_to_patch, attr_name, new_value)