blob: e1ec9e2d1f7084beca003a177013fee6496cf27c [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 Heimes23daade02008-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 Heimes23daade02008-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 Heimes23daade02008-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 Heimes23daade02008-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
Michael Foord2d9c2d52010-05-04 22:29:10 +0000526
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000527# TESTFN_UNICODE is a non-ascii filename
528TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
Victor Stinner74a833f2010-08-18 21:06:23 +0000529if sys.platform == 'darwin':
530 # In Mac OS X's VFS API file names are, by definition, canonically
531 # decomposed Unicode, encoded using UTF-8. See QA1173:
532 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
533 import unicodedata
534 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
Antoine Pitrou88909542009-06-29 13:54:42 +0000535TESTFN_ENCODING = sys.getfilesystemencoding()
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000536
Victor Stinner09c449c2010-08-13 22:23:24 +0000537# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000538# encoded by the filesystem encoding (in strict mode). It can be None if we
539# cannot generate such filename.
Victor Stinnera0241c82010-08-15 19:28:21 +0000540TESTFN_UNENCODABLE = None
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000541if os.name in ('nt', 'ce'):
Victor Stinnera0241c82010-08-15 19:28:21 +0000542 # skip win32s (0) or Windows 9x/ME (1)
543 if sys.getwindowsversion().platform >= 2:
Victor Stinner8ce7df62010-09-10 11:19:59 +0000544 # Different kinds of characters from various languages to minimize the
545 # probability that the whole name is encodable to MBCS (issue #9819)
546 TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000547 try:
Victor Stinner09c449c2010-08-13 22:23:24 +0000548 TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000549 except UnicodeEncodeError:
550 pass
551 else:
552 print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
553 'Unicode filename tests may not be effective'
Victor Stinner09c449c2010-08-13 22:23:24 +0000554 % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
555 TESTFN_UNENCODABLE = None
Victor Stinnera0241c82010-08-15 19:28:21 +0000556# Mac OS X denies unencodable filenames (invalid utf-8)
Victor Stinner03c9e1d2010-08-14 17:35:20 +0000557elif sys.platform != 'darwin':
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000558 try:
559 # ascii and utf-8 cannot encode the byte 0xff
560 b'\xff'.decode(TESTFN_ENCODING)
561 except UnicodeDecodeError:
562 # 0xff will be encoded using the surrogate character u+DCFF
Victor Stinner09c449c2010-08-13 22:23:24 +0000563 TESTFN_UNENCODABLE = TESTFN \
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000564 + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
565 else:
566 # File system encoding (eg. ISO-8859-* encodings) can encode
567 # the byte 0xff. Skip some unicode filename tests.
Victor Stinnera0241c82010-08-15 19:28:21 +0000568 pass
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000569
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000570# Save the initial cwd
571SAVEDCWD = os.getcwd()
572
573@contextlib.contextmanager
Nick Coghland26c18a2010-08-17 13:06:11 +0000574def temp_cwd(name='tempcwd', quiet=False, path=None):
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000575 """
Nick Coghland26c18a2010-08-17 13:06:11 +0000576 Context manager that temporarily changes the CWD.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000577
Nick Coghland26c18a2010-08-17 13:06:11 +0000578 An existing path may be provided as *path*, in which case this
579 function makes no changes to the file system.
580
581 Otherwise, the new CWD is created in the current directory and it's
582 named *name*. If *quiet* is False (default) and it's not possible to
583 create or change the CWD, an error is raised. If it's True, only a
584 warning is raised and the original CWD is used.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000585 """
586 saved_dir = os.getcwd()
587 is_temporary = False
Nick Coghland26c18a2010-08-17 13:06:11 +0000588 if path is None:
589 path = name
590 try:
591 os.mkdir(name)
592 is_temporary = True
593 except OSError:
594 if not quiet:
595 raise
596 warnings.warn('tests may fail, unable to create temp CWD ' + name,
597 RuntimeWarning, stacklevel=3)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000598 try:
Nick Coghland26c18a2010-08-17 13:06:11 +0000599 os.chdir(path)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000600 except OSError:
601 if not quiet:
602 raise
Ezio Melottie418d762012-09-21 16:48:12 +0300603 warnings.warn('tests may fail, unable to change the CWD to ' + path,
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000604 RuntimeWarning, stacklevel=3)
605 try:
606 yield os.getcwd()
607 finally:
608 os.chdir(saved_dir)
609 if is_temporary:
610 rmtree(name)
611
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000612
Barry Warsaw28a691b2010-04-17 00:19:56 +0000613@contextlib.contextmanager
614def temp_umask(umask):
615 """Context manager that temporarily sets the process umask."""
616 oldmask = os.umask(umask)
617 try:
618 yield
619 finally:
620 os.umask(oldmask)
621
622
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000623def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000624 """Try to find a file on sys.path and the working directory. If it is not
625 found the argument passed to the function is returned (this does not
626 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000627 if os.path.isabs(file):
628 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000629 if subdir is not None:
630 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000631 path = sys.path
632 path = [os.path.dirname(here)] + path
633 for dn in path:
634 fn = os.path.join(dn, file)
635 if os.path.exists(fn): return fn
636 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000637
Tim Peters2f228e72001-05-13 00:19:31 +0000638def sortdict(dict):
639 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000640 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000641 reprpairs = ["%r: %r" % pair for pair in items]
642 withcommas = ", ".join(reprpairs)
643 return "{%s}" % withcommas
644
Benjamin Peterson7522c742009-01-19 21:00:09 +0000645def make_bad_fd():
646 """
647 Create an invalid file descriptor by opening and closing a file and return
648 its fd.
649 """
650 file = open(TESTFN, "wb")
651 try:
652 return file.fileno()
653 finally:
654 file.close()
655 unlink(TESTFN)
656
Thomas Wouters89f507f2006-12-13 04:49:30 +0000657def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000658 testcase.assertRaises(SyntaxError, compile, statement,
659 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000660
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000661def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000662 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000663
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000664 check = kw.pop('check', None)
665
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000666 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000667
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000668 fn = os.path.join(os.path.dirname(__file__), "data", filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000669
670 def check_valid_file(fn):
671 f = open(fn, *args, **kw)
672 if check is None:
673 return f
674 elif check(f):
675 f.seek(0)
676 return f
677 f.close()
678
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000679 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000680 f = check_valid_file(fn)
681 if f is not None:
682 return f
683 unlink(fn)
684
685 # Verify the requirement before downloading the file
686 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000687
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000688 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000689 f = urllib.request.urlopen(url, timeout=15)
690 try:
691 with open(fn, "wb") as out:
692 s = f.read()
693 while s:
694 out.write(s)
695 s = f.read()
696 finally:
697 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000698
699 f = check_valid_file(fn)
700 if f is not None:
701 return f
702 raise TestFailed('invalid resource "%s"' % fn)
703
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000704
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000705class WarningsRecorder(object):
706 """Convenience wrapper for the warnings list returned on
707 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000709 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000710 self._warnings = warnings_list
711 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000712
713 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000714 if len(self._warnings) > self._last:
715 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000716 elif attr in warnings.WarningMessage._WARNING_DETAILS:
717 return None
718 raise AttributeError("%r has no attribute %r" % (self, attr))
719
Florent Xiclunab14930c2010-03-13 15:26:44 +0000720 @property
721 def warnings(self):
722 return self._warnings[self._last:]
723
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000724 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000725 self._last = len(self._warnings)
726
727
728def _filterwarnings(filters, quiet=False):
729 """Catch the warnings, then check if all the expected
730 warnings have been raised and re-raise unexpected warnings.
731 If 'quiet' is True, only re-raise the unexpected warnings.
732 """
733 # Clear the warning registry of the calling module
734 # in order to re-raise the warnings.
735 frame = sys._getframe(2)
736 registry = frame.f_globals.get('__warningregistry__')
737 if registry:
738 registry.clear()
739 with warnings.catch_warnings(record=True) as w:
740 # Set filter "always" to record all warnings. Because
741 # test_warnings swap the module, we need to look up in
742 # the sys.modules dictionary.
743 sys.modules['warnings'].simplefilter("always")
744 yield WarningsRecorder(w)
745 # Filter the recorded warnings
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000746 reraise = list(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000747 missing = []
748 for msg, cat in filters:
749 seen = False
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000750 for w in reraise[:]:
751 warning = w.message
Florent Xiclunab14930c2010-03-13 15:26:44 +0000752 # Filter out the matching messages
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000753 if (re.match(msg, str(warning), re.I) and
754 issubclass(warning.__class__, cat)):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000755 seen = True
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000756 reraise.remove(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000757 if not seen and not quiet:
758 # This filter caught nothing
759 missing.append((msg, cat.__name__))
760 if reraise:
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000761 raise AssertionError("unhandled warning %s" % reraise[0])
Florent Xiclunab14930c2010-03-13 15:26:44 +0000762 if missing:
763 raise AssertionError("filter (%r, %s) did not catch any warning" %
764 missing[0])
765
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000766
767@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000768def check_warnings(*filters, **kwargs):
769 """Context manager to silence warnings.
770
771 Accept 2-tuples as positional arguments:
772 ("message regexp", WarningCategory)
773
774 Optional argument:
775 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506be2010-03-18 20:00:57 +0000776 (default True without argument,
777 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000778
779 Without argument, it defaults to:
Florent Xicluna53b506be2010-03-18 20:00:57 +0000780 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000781 """
Florent Xicluna53b506be2010-03-18 20:00:57 +0000782 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +0000783 if not filters:
784 filters = (("", Warning),)
Florent Xicluna53b506be2010-03-18 20:00:57 +0000785 # Preserve backward compatibility
786 if quiet is None:
787 quiet = True
788 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000789
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000790
791class CleanImport(object):
792 """Context manager to force import to return a new module reference.
793
794 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000795 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000796
797 Use like this:
798
799 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000800 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000801 """
802
803 def __init__(self, *module_names):
804 self.original_modules = sys.modules.copy()
805 for module_name in module_names:
806 if module_name in sys.modules:
807 module = sys.modules[module_name]
808 # It is possible that module_name is just an alias for
809 # another module (e.g. stub for modules renamed in 3.x).
810 # In that case, we also need delete the real module to clear
811 # the import cache.
812 if module.__name__ != module_name:
813 del sys.modules[module.__name__]
814 del sys.modules[module_name]
815
816 def __enter__(self):
817 return self
818
819 def __exit__(self, *ignore_exc):
820 sys.modules.update(self.original_modules)
821
822
Walter Dörwald155374d2009-05-01 19:58:58 +0000823class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000824
825 """Class to help protect the environment variable properly. Can be used as
826 a context manager."""
827
828 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000829 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000830 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000831
Walter Dörwald155374d2009-05-01 19:58:58 +0000832 def __getitem__(self, envvar):
833 return self._environ[envvar]
834
835 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000836 # Remember the initial value on the first access
837 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000838 self._changed[envvar] = self._environ.get(envvar)
839 self._environ[envvar] = value
840
841 def __delitem__(self, envvar):
842 # Remember the initial value on the first access
843 if envvar not in self._changed:
844 self._changed[envvar] = self._environ.get(envvar)
845 if envvar in self._environ:
846 del self._environ[envvar]
847
848 def keys(self):
849 return self._environ.keys()
850
851 def __iter__(self):
852 return iter(self._environ)
853
854 def __len__(self):
855 return len(self._environ)
856
857 def set(self, envvar, value):
858 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000859
860 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000861 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000862
863 def __enter__(self):
864 return self
865
866 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000867 for (k, v) in self._changed.items():
868 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000869 if k in self._environ:
870 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000871 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000872 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000873 os.environ = self._environ
874
875
876class DirsOnSysPath(object):
877 """Context manager to temporarily add directories to sys.path.
878
879 This makes a copy of sys.path, appends any directories given
880 as positional arguments, then reverts sys.path to the copied
881 settings when the context ends.
882
883 Note that *all* sys.path modifications in the body of the
884 context manager, including replacement of the object,
885 will be reverted at the end of the block.
886 """
887
888 def __init__(self, *paths):
889 self.original_value = sys.path[:]
890 self.original_object = sys.path
891 sys.path.extend(paths)
892
893 def __enter__(self):
894 return self
895
896 def __exit__(self, *ignore_exc):
897 sys.path = self.original_object
898 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000899
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000900
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901class TransientResource(object):
902
903 """Raise ResourceDenied if an exception is raised while the context manager
904 is in effect that matches the specified exception and attributes."""
905
906 def __init__(self, exc, **kwargs):
907 self.exc = exc
908 self.attrs = kwargs
909
910 def __enter__(self):
911 return self
912
913 def __exit__(self, type_=None, value=None, traceback=None):
914 """If type_ is a subclass of self.exc and value has attributes matching
915 self.attrs, raise ResourceDenied. Otherwise let the exception
916 propagate (if any)."""
917 if type_ is not None and issubclass(self.exc, type_):
918 for attr, attr_value in self.attrs.items():
919 if not hasattr(value, attr):
920 break
921 if getattr(value, attr) != attr_value:
922 break
923 else:
924 raise ResourceDenied("an optional resource is not available")
925
Raymond Hettinger686057b2009-06-04 00:11:54 +0000926# Context managers that raise ResourceDenied when various issues
927# with the Internet connection manifest themselves as exceptions.
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000928# XXX deprecate these and use transient_internet() instead
Raymond Hettinger686057b2009-06-04 00:11:54 +0000929time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
930socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
931ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000932
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000933
Thomas Woutersed03b412007-08-28 21:37:11 +0000934@contextlib.contextmanager
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000935def transient_internet(resource_name, *, timeout=30.0, errnos=()):
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000936 """Return a context manager that raises ResourceDenied when various issues
937 with the Internet connection manifest themselves as exceptions."""
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000938 default_errnos = [
939 ('ECONNREFUSED', 111),
940 ('ECONNRESET', 104),
Antoine Pitrou5d938cb2011-01-08 10:28:11 +0000941 ('EHOSTUNREACH', 113),
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000942 ('ENETUNREACH', 101),
943 ('ETIMEDOUT', 110),
944 ]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000945 default_gai_errnos = [
Antoine Pitrou4875c462011-07-09 02:31:24 +0200946 ('EAI_AGAIN', -3),
Charles-François Natali13859bf2011-12-10 13:16:44 +0100947 ('EAI_FAIL', -4),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000948 ('EAI_NONAME', -2),
949 ('EAI_NODATA', -5),
Antoine Pitrou390ea0f2011-04-29 00:44:33 +0200950 # Encountered when trying to resolve IPv6-only hostnames
951 ('WSANO_DATA', 11004),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000952 ]
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000953
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000954 denied = ResourceDenied("Resource '%s' is not available" % resource_name)
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000955 captured_errnos = errnos
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000956 gai_errnos = []
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000957 if not captured_errnos:
958 captured_errnos = [getattr(errno, name, num)
959 for (name, num) in default_errnos]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000960 gai_errnos = [getattr(socket, name, num)
961 for (name, num) in default_gai_errnos]
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000962
963 def filter_error(err):
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000964 n = getattr(err, 'errno', None)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000965 if (isinstance(err, socket.timeout) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000966 (isinstance(err, socket.gaierror) and n in gai_errnos) or
967 n in captured_errnos):
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000968 if not verbose:
969 sys.stderr.write(denied.args[0] + "\n")
970 raise denied from err
971
972 old_timeout = socket.getdefaulttimeout()
973 try:
974 if timeout is not None:
975 socket.setdefaulttimeout(timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000976 yield
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000977 except IOError as err:
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000978 # urllib can wrap original socket errors multiple times (!), we must
979 # unwrap to get at the original error.
980 while True:
981 a = err.args
982 if len(a) >= 1 and isinstance(a[0], IOError):
983 err = a[0]
984 # The error can also be wrapped as args[1]:
985 # except socket.error as msg:
986 # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
987 elif len(a) >= 2 and isinstance(a[1], IOError):
988 err = a[1]
989 else:
990 break
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000991 filter_error(err)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000992 raise
993 # XXX should we catch generic exceptions and look for their
994 # __cause__ or __context__?
995 finally:
996 socket.setdefaulttimeout(old_timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000997
998
999@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001000def captured_output(stream_name):
Ezio Melotti07352b02011-05-14 14:51:18 +03001001 """Return a context manager used by captured_stdout/stdin/stderr
Ezio Melottifc778fd2011-05-14 08:22:47 +03001002 that temporarily replaces the sys stream *stream_name* with a StringIO."""
Thomas Woutersed03b412007-08-28 21:37:11 +00001003 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001004 orig_stdout = getattr(sys, stream_name)
1005 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001006 try:
1007 yield getattr(sys, stream_name)
1008 finally:
1009 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001010
1011def captured_stdout():
Ezio Melottifc778fd2011-05-14 08:22:47 +03001012 """Capture the output of sys.stdout:
1013
1014 with captured_stdout() as s:
1015 print("hello")
1016 self.assertEqual(s.getvalue(), "hello")
1017 """
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00001018 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +00001019
Nick Coghlan6b22f3f2010-12-12 15:24:21 +00001020def captured_stderr():
1021 return captured_output("stderr")
1022
Nick Coghlan6ead5522009-10-18 13:19:33 +00001023def captured_stdin():
1024 return captured_output("stdin")
1025
Ezio Melotti07352b02011-05-14 14:51:18 +03001026
Benjamin Petersone549ead2009-03-28 21:42:05 +00001027def gc_collect():
1028 """Force as many objects as possible to be collected.
1029
1030 In non-CPython implementations of Python, this is needed because timely
1031 deallocation is not guaranteed by the garbage collector. (Even in CPython
1032 this can be the case in case of reference cycles.) This means that __del__
1033 methods may be called later than expected and weakrefs may remain alive for
1034 longer than expected. This function tries its best to force all garbage
1035 objects to disappear.
1036 """
Benjamin Petersone549ead2009-03-28 21:42:05 +00001037 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +00001038 if is_jython:
1039 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00001040 gc.collect()
1041 gc.collect()
1042
Thomas Woutersed03b412007-08-28 21:37:11 +00001043
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001044def python_is_optimized():
1045 """Find if Python was built with optimizations."""
Antoine Pitrou64474542010-10-31 11:34:47 +00001046 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
Benjamin Peterson65c66ab2010-10-29 21:31:35 +00001047 final_opt = ""
1048 for opt in cflags.split():
1049 if opt.startswith('-O'):
1050 final_opt = opt
1051 return final_opt and final_opt != '-O0'
1052
1053
Martin v. Löwis33f79972012-07-29 16:33:05 +02001054_header = '2P'
1055if hasattr(sys, "gettotalrefcount"):
1056 _header = '2P' + _header
1057_vheader = _header + 'P'
1058
1059def calcobjsize(fmt):
1060 return struct.calcsize(_header + fmt + '0P')
1061
1062def calcvobjsize(fmt):
1063 return struct.calcsize(_vheader + fmt + '0P')
1064
1065
1066_TPFLAGS_HAVE_GC = 1<<14
1067_TPFLAGS_HEAPTYPE = 1<<9
1068
1069def check_sizeof(test, o, size):
1070 result = sys.getsizeof(o)
1071 # add GC header size
1072 if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
1073 ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
1074 size += _testcapi.SIZEOF_PYGC_HEAD
1075 msg = 'wrong size for %s: got %d, expected %d' \
1076 % (type(o), result, size)
1077 test.assertEqual(result, size, msg)
1078
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001079#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080# Decorator for running a function in a different locale, correctly resetting
1081# it afterwards.
1082
1083def run_with_locale(catstr, *locales):
1084 def decorator(func):
1085 def inner(*args, **kwds):
1086 try:
1087 import locale
1088 category = getattr(locale, catstr)
1089 orig_locale = locale.setlocale(category)
1090 except AttributeError:
1091 # if the test author gives us an invalid category string
1092 raise
1093 except:
1094 # cannot retrieve original locale, so do nothing
1095 locale = orig_locale = None
1096 else:
1097 for loc in locales:
1098 try:
1099 locale.setlocale(category, loc)
1100 break
1101 except:
1102 pass
1103
1104 # now run the function, resetting the locale on exceptions
1105 try:
1106 return func(*args, **kwds)
1107 finally:
1108 if locale and orig_locale:
1109 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +00001110 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +00001111 inner.__doc__ = func.__doc__
1112 return inner
1113 return decorator
1114
1115#=======================================================================
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001116# Decorator for running a function in a specific timezone, correctly
1117# resetting it afterwards.
1118
1119def run_with_tz(tz):
1120 def decorator(func):
1121 def inner(*args, **kwds):
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001122 try:
1123 tzset = time.tzset
1124 except AttributeError:
1125 raise unittest.SkipTest("tzset required")
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001126 if 'TZ' in os.environ:
1127 orig_tz = os.environ['TZ']
1128 else:
1129 orig_tz = None
1130 os.environ['TZ'] = tz
Alexander Belopolskyb8f02b52012-04-29 18:16:46 -04001131 tzset()
Alexander Belopolsky2420d832012-04-29 15:56:49 -04001132
1133 # now run the function, resetting the tz on exceptions
1134 try:
1135 return func(*args, **kwds)
1136 finally:
1137 if orig_tz == None:
1138 del os.environ['TZ']
1139 else:
1140 os.environ['TZ'] = orig_tz
1141 time.tzset()
1142
1143 inner.__name__ = func.__name__
1144 inner.__doc__ = func.__doc__
1145 return inner
1146 return decorator
1147
1148#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +00001149# Big-memory-test support. Separate from 'resources' because memory use
1150# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001151
1152# Some handy shorthands. Note that these are used for byte-limits as well
1153# as size-limits, in the various bigmem tests
1154_1M = 1024*1024
1155_1G = 1024 * _1M
1156_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001157_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +00001158
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001159MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001160
Thomas Wouters477c8d52006-05-27 19:21:47 +00001161def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001162 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001163 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001164 sizes = {
1165 'k': 1024,
1166 'm': _1M,
1167 'g': _1G,
1168 't': 1024*_1G,
1169 }
1170 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
1171 re.IGNORECASE | re.VERBOSE)
1172 if m is None:
1173 raise ValueError('Invalid memory limit %r' % (limit,))
1174 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001175 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001176 if memlimit > MAX_Py_ssize_t:
1177 memlimit = MAX_Py_ssize_t
1178 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001179 raise ValueError('Memory limit %r too low to be useful' % (limit,))
1180 max_memuse = memlimit
1181
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001182def _memory_watchdog(start_evt, finish_evt, period=10.0):
1183 """A function which periodically watches the process' memory consumption
1184 and prints it out.
1185 """
1186 # XXX: because of the GIL, and because the very long operations tested
1187 # in most bigmem tests are uninterruptible, the loop below gets woken up
1188 # much less often than expected.
1189 # The polling code should be rewritten in raw C, without holding the GIL,
1190 # and push results onto an anonymous pipe.
1191 try:
1192 page_size = os.sysconf('SC_PAGESIZE')
1193 except (ValueError, AttributeError):
1194 try:
1195 page_size = os.sysconf('SC_PAGE_SIZE')
1196 except (ValueError, AttributeError):
1197 page_size = 4096
1198 procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
1199 try:
1200 f = open(procfile, 'rb')
1201 except IOError as e:
1202 warnings.warn('/proc not available for stats: {}'.format(e),
1203 RuntimeWarning)
1204 sys.stderr.flush()
1205 return
1206 with f:
1207 start_evt.set()
1208 old_data = -1
1209 while not finish_evt.wait(period):
1210 f.seek(0)
1211 statm = f.read().decode('ascii')
1212 data = int(statm.split()[5])
1213 if data != old_data:
1214 old_data = data
1215 print(" ... process data size: {data:.1f}G"
1216 .format(data=data * page_size / (1024 ** 3)))
1217
1218def bigmemtest(size, memuse, dry_run=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219 """Decorator for bigmem tests.
1220
1221 'minsize' is the minimum useful size for the test (in arbitrary,
1222 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001223 the test, or a good estimate of it.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001224
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001225 if 'dry_run' is False, it means the test doesn't support dummy runs
1226 when -M is not specified.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001227 """
1228 def decorator(f):
1229 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001230 size = wrapper.size
1231 memuse = wrapper.memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001232 if not real_max_memuse:
1233 maxsize = 5147
1234 else:
1235 maxsize = size
1236
Antoine Pitrou82be19f2011-08-29 23:09:33 +02001237 if ((real_max_memuse or not dry_run)
1238 and real_max_memuse < maxsize * memuse):
1239 raise unittest.SkipTest(
1240 "not enough memory: %.1fG minimum needed"
1241 % (size * memuse / (1024 ** 3)))
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001242
Antoine Pitrou94190bb2011-10-04 10:22:36 +02001243 if real_max_memuse and verbose and threading:
1244 print()
1245 print(" ... expected peak memory use: {peak:.1f}G"
1246 .format(peak=size * memuse / (1024 ** 3)))
1247 sys.stdout.flush()
1248 start_evt = threading.Event()
1249 finish_evt = threading.Event()
1250 t = threading.Thread(target=_memory_watchdog,
1251 args=(start_evt, finish_evt, 0.5))
1252 t.daemon = True
1253 t.start()
1254 start_evt.set()
1255 else:
1256 t = None
1257
1258 try:
1259 return f(self, maxsize)
1260 finally:
1261 if t:
1262 finish_evt.set()
1263 t.join()
1264
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001265 wrapper.size = size
1266 wrapper.memuse = memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001267 return wrapper
1268 return decorator
1269
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001270def bigaddrspacetest(f):
1271 """Decorator for tests that fill the address space."""
1272 def wrapper(self):
1273 if max_memuse < MAX_Py_ssize_t:
Antoine Pitrou98c62bd2011-01-12 21:58:39 +00001274 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
Antoine Pitroue0d3f8a2011-01-12 21:50:44 +00001275 raise unittest.SkipTest(
1276 "not enough memory: try a 32-bit build instead")
1277 else:
1278 raise unittest.SkipTest(
1279 "not enough memory: %.1fG minimum needed"
1280 % (MAX_Py_ssize_t / (1024 ** 3)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001281 else:
1282 return f(self)
1283 return wrapper
1284
Thomas Wouters477c8d52006-05-27 19:21:47 +00001285#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +00001286# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001287
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001288class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001289 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001290 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001291 test(result)
1292 return result
1293
Benjamin Petersone549ead2009-03-28 21:42:05 +00001294def _id(obj):
1295 return obj
1296
1297def requires_resource(resource):
Antoine Pitrou4914f9e2011-02-26 16:49:08 +00001298 if resource == 'gui' and not _is_gui_available():
1299 return unittest.skip("resource 'gui' is not available")
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +00001300 if is_resource_enabled(resource):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001301 return _id
1302 else:
1303 return unittest.skip("resource {0!r} is not enabled".format(resource))
1304
1305def cpython_only(test):
1306 """
1307 Decorator for tests only applicable on CPython.
1308 """
1309 return impl_detail(cpython=True)(test)
1310
1311def impl_detail(msg=None, **guards):
1312 if check_impl_detail(**guards):
1313 return _id
1314 if msg is None:
1315 guardnames, default = _parse_guards(guards)
1316 if default:
1317 msg = "implementation detail not available on {0}"
1318 else:
1319 msg = "implementation detail specific to {0}"
1320 guardnames = sorted(guardnames.keys())
1321 msg = msg.format(' or '.join(guardnames))
1322 return unittest.skip(msg)
1323
1324def _parse_guards(guards):
1325 # Returns a tuple ({platform_name: run_me}, default_value)
1326 if not guards:
1327 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +00001328 is_true = list(guards.values())[0]
1329 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001330 return (guards, not is_true)
1331
1332# Use the following check to guard CPython's implementation-specific tests --
1333# or to run them only on the implementation(s) guarded by the arguments.
1334def check_impl_detail(**guards):
1335 """This function returns True or False depending on the host platform.
1336 Examples:
1337 if check_impl_detail(): # only on CPython (default)
1338 if check_impl_detail(jython=True): # only on Jython
1339 if check_impl_detail(cpython=False): # everywhere except on CPython
1340 """
1341 guards, default = _parse_guards(guards)
1342 return guards.get(platform.python_implementation().lower(), default)
1343
1344
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001345def _filter_suite(suite, pred):
1346 """Recursively filter test cases in a suite based on a predicate."""
1347 newtests = []
1348 for test in suite._tests:
1349 if isinstance(test, unittest.TestSuite):
1350 _filter_suite(test, pred)
1351 newtests.append(test)
1352 else:
1353 if pred(test):
1354 newtests.append(test)
1355 suite._tests = newtests
1356
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001357
Guido van Rossumd8faa362007-04-27 19:54:29 +00001358def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001359 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001360 if verbose:
Antoine Pitrou216a3bc2011-07-23 22:33:39 +02001361 runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
1362 failfast=failfast)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001363 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001364 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001365
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001366 result = runner.run(suite)
1367 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001368 if len(result.errors) == 1 and not result.failures:
1369 err = result.errors[0][1]
1370 elif len(result.failures) == 1 and not result.errors:
1371 err = result.failures[0][1]
1372 else:
R. David Murray723357e2009-10-19 18:06:17 +00001373 err = "multiple errors occurred"
1374 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001375 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001376
Barry Warsawc10d6902001-09-20 06:30:41 +00001377
Walter Dörwald21d3a322003-05-01 17:45:56 +00001378def run_unittest(*classes):
1379 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001380 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001381 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001382 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001383 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001384 if cls in sys.modules:
1385 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1386 else:
1387 raise ValueError("str arguments must be keys in sys.modules")
1388 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001389 suite.addTest(cls)
1390 else:
1391 suite.addTest(unittest.makeSuite(cls))
Antoine Pitroub9c73e82011-07-29 23:53:38 +02001392 def case_pred(test):
1393 if match_tests is None:
1394 return True
1395 for name in test.id().split("."):
1396 if fnmatch.fnmatchcase(name, match_tests):
1397 return True
1398 return False
1399 _filter_suite(suite, case_pred)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001400 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001401
Barry Warsawc10d6902001-09-20 06:30:41 +00001402
Tim Petersa0a62222001-09-09 06:12:01 +00001403#=======================================================================
1404# doctest driver.
1405
1406def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +00001407 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001408
1409 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001410 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001411 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001412 """
1413
1414 import doctest
1415
1416 if verbosity is None:
1417 verbosity = verbose
1418 else:
1419 verbosity = None
1420
Victor Stinnerbddc4d42011-06-29 15:52:46 +02001421 f, t = doctest.testmod(module, verbose=verbosity)
1422 if f:
1423 raise TestFailed("%d of %d doctests failed" % (f, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001424 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001425 print('doctest (%s) ... %d tests with zero failures' %
1426 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001427 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001428
Antoine Pitrou060cee22009-11-13 16:29:04 +00001429
1430#=======================================================================
1431# Support for saving and restoring the imported modules.
1432
1433def modules_setup():
1434 return sys.modules.copy(),
1435
1436def modules_cleanup(oldmodules):
1437 # Encoders/decoders are registered permanently within the internal
1438 # codec cache. If we destroy the corresponding modules their
1439 # globals will be set to None which will trip up the cached functions.
1440 encodings = [(k, v) for k, v in sys.modules.items()
1441 if k.startswith('encodings.')]
1442 sys.modules.clear()
1443 sys.modules.update(encodings)
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001444 # XXX: This kind of problem can affect more than just encodings. In particular
Eric Smitha3e8f3d2011-01-11 10:24:34 +00001445 # extension modules (such as _ssl) don't cope with reloading properly.
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001446 # Really, test modules should be cleaning out the test specific modules they
1447 # know they added (ala test_runpy) rather than relying on this function (as
1448 # test_importhooks and test_pkg do currently).
1449 # Implicitly imported *real* modules should be left alone (see issue 10556).
Antoine Pitrou060cee22009-11-13 16:29:04 +00001450 sys.modules.update(oldmodules)
1451
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001452#=======================================================================
1453# Threading support to prevent reporting refleaks when running regrtest.py -R
1454
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001455# NOTE: we use thread._count() rather than threading.enumerate() (or the
1456# moral equivalent thereof) because a threading.Thread object is still alive
1457# until its __bootstrap() method has returned, even after it has been
1458# unregistered from the threading module.
1459# thread._count(), on the other hand, only gets decremented *after* the
1460# __bootstrap() method has returned, which gives us reliable reference counts
1461# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001462
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001463def threading_setup():
Victor Stinner45df8202010-04-28 22:31:17 +00001464 if _thread:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001465 return _thread._count(), threading._dangling.copy()
Victor Stinner45df8202010-04-28 22:31:17 +00001466 else:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001467 return 1, ()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001468
Antoine Pitrou707f2282011-07-15 22:29:44 +02001469def threading_cleanup(*original_values):
Victor Stinner45df8202010-04-28 22:31:17 +00001470 if not _thread:
1471 return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001472 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001473 for count in range(_MAX_COUNT):
Antoine Pitrou707f2282011-07-15 22:29:44 +02001474 values = _thread._count(), threading._dangling
1475 if values == original_values:
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001476 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001477 time.sleep(0.1)
Antoine Pitrou707f2282011-07-15 22:29:44 +02001478 gc_collect()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001479 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001480
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001481def reap_threads(func):
Victor Stinner45df8202010-04-28 22:31:17 +00001482 """Use this function when threads are being used. This will
1483 ensure that the threads are cleaned up even when the test fails.
1484 If threading is unavailable this function does nothing.
1485 """
1486 if not _thread:
1487 return func
1488
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001489 @functools.wraps(func)
1490 def decorator(*args):
1491 key = threading_setup()
1492 try:
1493 return func(*args)
1494 finally:
1495 threading_cleanup(*key)
1496 return decorator
1497
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001498def reap_children():
1499 """Use this function at the end of test_main() whenever sub-processes
1500 are started. This will help ensure that no extra children (zombies)
1501 stick around to hog resources and create problems when looking
1502 for refleaks.
1503 """
1504
1505 # Reap all our dead child processes so we don't leave zombies around.
1506 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001507 if hasattr(os, 'waitpid'):
1508 any_process = -1
1509 while True:
1510 try:
1511 # This will raise an exception on Windows. That's ok.
1512 pid, status = os.waitpid(any_process, os.WNOHANG)
1513 if pid == 0:
1514 break
1515 except:
1516 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001517
1518@contextlib.contextmanager
1519def swap_attr(obj, attr, new_val):
1520 """Temporary swap out an attribute with a new object.
1521
1522 Usage:
1523 with swap_attr(obj, "attr", 5):
1524 ...
1525
1526 This will set obj.attr to 5 for the duration of the with: block,
1527 restoring the old value at the end of the block. If `attr` doesn't
1528 exist on `obj`, it will be created and then deleted at the end of the
1529 block.
1530 """
1531 if hasattr(obj, attr):
1532 real_val = getattr(obj, attr)
1533 setattr(obj, attr, new_val)
1534 try:
1535 yield
1536 finally:
1537 setattr(obj, attr, real_val)
1538 else:
1539 setattr(obj, attr, new_val)
1540 try:
1541 yield
1542 finally:
1543 delattr(obj, attr)
1544
1545@contextlib.contextmanager
1546def swap_item(obj, item, new_val):
1547 """Temporary swap out an item with a new object.
1548
1549 Usage:
1550 with swap_item(obj, "item", 5):
1551 ...
1552
1553 This will set obj["item"] to 5 for the duration of the with: block,
1554 restoring the old value at the end of the block. If `item` doesn't
1555 exist on `obj`, it will be created and then deleted at the end of the
1556 block.
1557 """
1558 if item in obj:
1559 real_val = obj[item]
1560 obj[item] = new_val
1561 try:
1562 yield
1563 finally:
1564 obj[item] = real_val
1565 else:
1566 obj[item] = new_val
1567 try:
1568 yield
1569 finally:
1570 del obj[item]
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00001571
1572def strip_python_stderr(stderr):
1573 """Strip the stderr of a Python process from potential debug output
1574 emitted by the interpreter.
1575
1576 This will typically be run on the result of the communicate() method
1577 of a subprocess.Popen object.
1578 """
1579 stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
1580 return stderr
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00001581
1582def args_from_interpreter_flags():
1583 """Return a list of command-line arguments reproducing the current
1584 settings in sys.flags."""
1585 flag_opt_map = {
1586 'bytes_warning': 'b',
1587 'dont_write_bytecode': 'B',
Antoine Pitroue9f637b2012-02-20 23:49:07 +01001588 'hash_randomization': 'R',
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00001589 'ignore_environment': 'E',
1590 'no_user_site': 's',
1591 'no_site': 'S',
1592 'optimize': 'O',
1593 'verbose': 'v',
1594 }
1595 args = []
1596 for flag, opt in flag_opt_map.items():
1597 v = getattr(sys.flags, flag)
1598 if v > 0:
1599 args.append('-' + opt * v)
1600 return args
Vinay Sajip129fd042010-12-10 08:19:38 +00001601
1602#============================================================
1603# Support for assertions about logging.
1604#============================================================
1605
1606class TestHandler(logging.handlers.BufferingHandler):
1607 def __init__(self, matcher):
1608 # BufferingHandler takes a "capacity" argument
1609 # so as to know when to flush. As we're overriding
1610 # shouldFlush anyway, we can set a capacity of zero.
1611 # You can call flush() manually to clear out the
1612 # buffer.
1613 logging.handlers.BufferingHandler.__init__(self, 0)
1614 self.matcher = matcher
1615
1616 def shouldFlush(self):
1617 return False
1618
1619 def emit(self, record):
1620 self.format(record)
1621 self.buffer.append(record.__dict__)
1622
1623 def matches(self, **kwargs):
1624 """
1625 Look for a saved dict whose keys/values match the supplied arguments.
1626 """
1627 result = False
1628 for d in self.buffer:
1629 if self.matcher.matches(d, **kwargs):
1630 result = True
1631 break
1632 return result
1633
1634class Matcher(object):
1635
1636 _partial_matches = ('msg', 'message')
1637
1638 def matches(self, d, **kwargs):
1639 """
1640 Try to match a single dict with the supplied arguments.
1641
1642 Keys whose values are strings and which are in self._partial_matches
1643 will be checked for partial (i.e. substring) matches. You can extend
1644 this scheme to (for example) do regular expression matching, etc.
1645 """
1646 result = True
1647 for k in kwargs:
1648 v = kwargs[k]
1649 dv = d.get(k)
1650 if not self.match_value(k, dv, v):
1651 result = False
1652 break
1653 return result
1654
1655 def match_value(self, k, dv, v):
1656 """
1657 Try to match a single stored value (dv) with a supplied value (v).
1658 """
1659 if type(v) != type(dv):
1660 result = False
1661 elif type(dv) is not str or k not in self._partial_matches:
1662 result = (v == dv)
1663 else:
1664 result = dv.find(v) >= 0
1665 return result
Brian Curtin3b4499c2010-12-28 14:31:47 +00001666
1667
1668_can_symlink = None
1669def can_symlink():
1670 global _can_symlink
1671 if _can_symlink is not None:
1672 return _can_symlink
Victor Stinner62ec61f2011-06-07 12:17:15 +02001673 symlink_path = TESTFN + "can_symlink"
Brian Curtin3b4499c2010-12-28 14:31:47 +00001674 try:
Victor Stinner62ec61f2011-06-07 12:17:15 +02001675 os.symlink(TESTFN, symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00001676 can = True
Brian Curtind25aef52011-06-13 15:16:04 -05001677 except (OSError, NotImplementedError, AttributeError):
Brian Curtin3b4499c2010-12-28 14:31:47 +00001678 can = False
Victor Stinner62ec61f2011-06-07 12:17:15 +02001679 else:
1680 os.remove(symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00001681 _can_symlink = can
1682 return can
1683
1684def skip_unless_symlink(test):
1685 """Skip decorator for tests that require functional symlink"""
1686 ok = can_symlink()
1687 msg = "Requires functional symlink implementation"
1688 return test if ok else unittest.skip(msg)(test)
Antoine Pitroue8706232011-03-15 21:05:36 +01001689
Antoine Pitrou2c50a092011-03-15 21:02:59 +01001690def patch(test_instance, object_to_patch, attr_name, new_value):
1691 """Override 'object_to_patch'.'attr_name' with 'new_value'.
1692
1693 Also, add a cleanup procedure to 'test_instance' to restore
1694 'object_to_patch' value for 'attr_name'.
1695 The 'attr_name' should be a valid attribute for 'object_to_patch'.
1696
1697 """
1698 # check that 'attr_name' is a real attribute for 'object_to_patch'
1699 # will raise AttributeError if it does not exist
1700 getattr(object_to_patch, attr_name)
1701
1702 # keep a copy of the old value
1703 attr_is_local = False
1704 try:
1705 old_value = object_to_patch.__dict__[attr_name]
1706 except (AttributeError, KeyError):
1707 old_value = getattr(object_to_patch, attr_name, None)
1708 else:
1709 attr_is_local = True
1710
1711 # restore the value when the test is done
1712 def cleanup():
1713 if attr_is_local:
1714 setattr(object_to_patch, attr_name, old_value)
1715 else:
1716 delattr(object_to_patch, attr_name)
1717
1718 test_instance.addCleanup(cleanup)
1719
1720 # actually override the attribute
1721 setattr(object_to_patch, attr_name, new_value)