blob: 2827e8b84230e7209921afa16d6bfbaf1ad14fea [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
Vinay Sajip129fd042010-12-10 08:19:38 +000024import logging.handlers
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000025
Victor Stinner45df8202010-04-28 22:31:17 +000026try:
Antoine Pitrou707f2282011-07-15 22:29:44 +020027 import _thread, threading
Victor Stinner45df8202010-04-28 22:31:17 +000028except ImportError:
29 _thread = None
Antoine Pitrou707f2282011-07-15 22:29:44 +020030 threading = None
31try:
32 import multiprocessing.process
33except ImportError:
34 multiprocessing = None
35
Fred Drakecd1b1dd2001-03-21 18:26:33 +000036
Barry Warsaw28a691b2010-04-17 00:19:56 +000037__all__ = [
38 "Error", "TestFailed", "ResourceDenied", "import_module",
39 "verbose", "use_resources", "max_memuse", "record_original_stdout",
40 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
Victor Stinner88701e22011-06-01 13:13:04 +020041 "is_resource_enabled", "requires", "requires_mac_ver",
42 "find_unused_port", "bind_port",
Barry Warsaw28a691b2010-04-17 00:19:56 +000043 "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
44 "findfile", "sortdict", "check_syntax_error", "open_urlresource",
45 "check_warnings", "CleanImport", "EnvironmentVarGuard",
46 "TransientResource", "captured_output", "captured_stdout",
Ezio Melotti07352b02011-05-14 14:51:18 +030047 "captured_stdin", "captured_stderr",
Barry Warsaw28a691b2010-04-17 00:19:56 +000048 "time_out", "socket_peer_reset", "ioerror_peer_reset",
Antoine Pitroua88c83c2010-09-07 20:42:19 +000049 "run_with_locale", 'temp_umask', "transient_internet",
Barry Warsaw28a691b2010-04-17 00:19:56 +000050 "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
51 "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
52 "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
Vinay Sajip129fd042010-12-10 08:19:38 +000053 "swap_item", "swap_attr", "requires_IEEE_754",
Benjamin Peterson31dc3732011-05-08 15:34:24 -050054 "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink",
Benjamin Peterson262c5822011-05-08 15:32:46 -050055 "import_fresh_module"
Antoine Pitrou4d7979b2010-09-07 21:22:56 +000056 ]
Florent Xiclunaf089fd62010-03-19 14:25:03 +000057
Fred Drake1790dd42000-07-24 06:55:00 +000058class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000059 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000060
61class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000062 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000063
Benjamin Petersone549ead2009-03-28 21:42:05 +000064class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +000065 """Test skipped because it requested a disallowed resource.
66
67 This is raised when a test calls requires() for a resource that
68 has not be enabled. It is used to distinguish between expected
69 and unexpected skips.
70 """
71
Nick Coghlanfce769e2009-04-11 14:30:59 +000072@contextlib.contextmanager
73def _ignore_deprecated_imports(ignore=True):
74 """Context manager to suppress package and module deprecation
75 warnings when importing them.
76
77 If ignore is False, this context manager has no effect."""
78 if ignore:
79 with warnings.catch_warnings():
80 warnings.filterwarnings("ignore", ".+ (module|package)",
81 DeprecationWarning)
82 yield
83 else:
84 yield
85
86
Benjamin Peterson699adb92008-05-08 22:27:58 +000087def import_module(name, deprecated=False):
R. David Murraya21e4ca2009-03-31 23:16:50 +000088 """Import and return the module to be tested, raising SkipTest if
89 it is not available.
90
91 If deprecated is True, any module or package deprecation messages
92 will be suppressed."""
Nick Coghlanfce769e2009-04-11 14:30:59 +000093 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +000094 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +000095 return importlib.import_module(name)
R. David Murraya21e4ca2009-03-31 23:16:50 +000096 except ImportError as msg:
97 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +000098
99
Nick Coghlan47384702009-04-22 16:13:36 +0000100def _save_and_remove_module(name, orig_modules):
101 """Helper function to save and remove a module from sys.modules
102
Ezio Melotti199e0852011-05-09 06:41:55 +0300103 Raise ImportError if the module can't be imported."""
Ezio Melottifec3ad12011-05-14 06:02:25 +0300104 # try to import the module and raise an error if it can't be imported
105 if name not in sys.modules:
Ezio Melotti199e0852011-05-09 06:41:55 +0300106 __import__(name)
Nick Coghlan47384702009-04-22 16:13:36 +0000107 del sys.modules[name]
Ezio Melottifec3ad12011-05-14 06:02:25 +0300108 for modname in list(sys.modules):
109 if modname == name or modname.startswith(name + '.'):
110 orig_modules[modname] = sys.modules[modname]
111 del sys.modules[modname]
Nick Coghlan47384702009-04-22 16:13:36 +0000112
113def _save_and_block_module(name, orig_modules):
114 """Helper function to save and block a module in sys.modules
115
Ezio Melotti199e0852011-05-09 06:41:55 +0300116 Return True if the module was in sys.modules, False otherwise."""
Nick Coghlan47384702009-04-22 16:13:36 +0000117 saved = True
118 try:
119 orig_modules[name] = sys.modules[name]
120 except KeyError:
121 saved = False
Alexander Belopolsky903396e2010-07-13 14:50:16 +0000122 sys.modules[name] = None
Nick Coghlan47384702009-04-22 16:13:36 +0000123 return saved
124
125
126def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Nick Coghlanfce769e2009-04-11 14:30:59 +0000127 """Imports and returns a module, deliberately bypassing the sys.modules cache
128 and importing a fresh copy of the module. Once the import is complete,
129 the sys.modules cache is restored to its original state.
130
Nick Coghlan47384702009-04-22 16:13:36 +0000131 Modules named in fresh are also imported anew if needed by the import.
Ezio Melotti199e0852011-05-09 06:41:55 +0300132 If one of these modules can't be imported, None is returned.
Nick Coghlan47384702009-04-22 16:13:36 +0000133
134 Importing of modules named in blocked is prevented while the fresh import
Nick Coghlanfce769e2009-04-11 14:30:59 +0000135 takes place.
136
137 If deprecated is True, any module or package deprecation messages
138 will be suppressed."""
Ezio Melotti6b60fb92011-05-14 06:47:51 +0300139 # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
140 # to make sure that this utility function is working as expected
Nick Coghlanfce769e2009-04-11 14:30:59 +0000141 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000142 # Keep track of modules saved for later restoration as well
143 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000144 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000145 names_to_remove = []
146 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000147 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000148 for fresh_name in fresh:
149 _save_and_remove_module(fresh_name, orig_modules)
150 for blocked_name in blocked:
151 if not _save_and_block_module(blocked_name, orig_modules):
152 names_to_remove.append(blocked_name)
153 fresh_module = importlib.import_module(name)
Ezio Melotti199e0852011-05-09 06:41:55 +0300154 except ImportError:
155 fresh_module = None
Nick Coghlanfce769e2009-04-11 14:30:59 +0000156 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000157 for orig_name, module in orig_modules.items():
158 sys.modules[orig_name] = module
159 for name_to_remove in names_to_remove:
160 del sys.modules[name_to_remove]
161 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000162
Benjamin Peterson699adb92008-05-08 22:27:58 +0000163
R. David Murraya21e4ca2009-03-31 23:16:50 +0000164def get_attribute(obj, name):
165 """Get an attribute, raising SkipTest if AttributeError is raised."""
166 try:
167 attribute = getattr(obj, name)
168 except AttributeError:
169 raise unittest.SkipTest("module %s has no attribute %s" % (
170 obj.__name__, name))
171 else:
172 return attribute
173
Barry Warsawc0fb6052001-08-20 22:29:23 +0000174verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000175use_resources = None # Flag set to [] by regrtest.py
176max_memuse = 0 # Disable bigmem tests (they will still be run with
177 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000178real_max_memuse = 0
Guido van Rossum531661c1996-12-20 02:58:22 +0000179
Tim Peters8dee8092001-09-25 20:05:11 +0000180# _original_stdout is meant to hold stdout at the time regrtest began.
181# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
182# The point is to have some flavor of stdout the user can actually see.
183_original_stdout = None
184def record_original_stdout(stdout):
185 global _original_stdout
186 _original_stdout = stdout
187
188def get_original_stdout():
189 return _original_stdout or sys.stdout
190
Guido van Rossum3bead091992-01-27 17:00:37 +0000191def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000192 try:
193 del sys.modules[name]
194 except KeyError:
195 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000196
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000197def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000198 try:
199 os.unlink(filename)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000200 except OSError as error:
201 # The filename need not exist.
Michael Foord2d9c2d52010-05-04 22:29:10 +0000202 if error.errno not in (errno.ENOENT, errno.ENOTDIR):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000203 raise
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000204
Christian Heimes23daade02008-02-25 12:39:23 +0000205def rmtree(path):
206 try:
207 shutil.rmtree(path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000208 except OSError as error:
Christian Heimes23daade02008-02-25 12:39:23 +0000209 # Unix returns ENOENT, Windows returns ESRCH.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000210 if error.errno not in (errno.ENOENT, errno.ESRCH):
Christian Heimes23daade02008-02-25 12:39:23 +0000211 raise
212
Barry Warsaw28a691b2010-04-17 00:19:56 +0000213def make_legacy_pyc(source):
214 """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
215
216 The choice of .pyc or .pyo extension is done based on the __debug__ flag
217 value.
218
219 :param source: The file system path to the source file. The source file
220 does not need to exist, however the PEP 3147 pyc file must exist.
221 :return: The file system path to the legacy pyc file.
222 """
223 pyc_file = imp.cache_from_source(source)
224 up_one = os.path.dirname(os.path.abspath(source))
225 legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
226 os.rename(pyc_file, legacy_pyc)
227 return legacy_pyc
228
Guido van Rossum3bead091992-01-27 17:00:37 +0000229def forget(modname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000230 """'Forget' a module was ever imported.
231
232 This removes the module from sys.modules and deletes any PEP 3147 or
233 legacy .pyc and .pyo files.
234 """
Fred Drake004d5e62000-10-23 17:22:08 +0000235 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000236 for dirname in sys.path:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000237 source = os.path.join(dirname, modname + '.py')
238 # It doesn't matter if they exist or not, unlink all possible
239 # combinations of PEP 3147 and legacy pyc and pyo files.
240 unlink(source + 'c')
241 unlink(source + 'o')
242 unlink(imp.cache_from_source(source, debug_override=True))
243 unlink(imp.cache_from_source(source, debug_override=False))
Guido van Rossum3bead091992-01-27 17:00:37 +0000244
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000245# On some platforms, should not run gui test even if it is allowed
246# in `use_resources'.
247if sys.platform.startswith('win'):
248 import ctypes
249 import ctypes.wintypes
250 def _is_gui_available():
251 UOI_FLAGS = 1
252 WSF_VISIBLE = 0x0001
253 class USEROBJECTFLAGS(ctypes.Structure):
254 _fields_ = [("fInherit", ctypes.wintypes.BOOL),
255 ("fReserved", ctypes.wintypes.BOOL),
256 ("dwFlags", ctypes.wintypes.DWORD)]
257 dll = ctypes.windll.user32
258 h = dll.GetProcessWindowStation()
259 if not h:
260 raise ctypes.WinError()
261 uof = USEROBJECTFLAGS()
262 needed = ctypes.wintypes.DWORD()
263 res = dll.GetUserObjectInformationW(h,
264 UOI_FLAGS,
265 ctypes.byref(uof),
266 ctypes.sizeof(uof),
267 ctypes.byref(needed))
268 if not res:
269 raise ctypes.WinError()
270 return bool(uof.dwFlags & WSF_VISIBLE)
271else:
272 def _is_gui_available():
273 return True
274
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000275def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000276 """Test whether a resource is enabled. Known resources are set by
277 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000278 return use_resources is not None and resource in use_resources
279
Barry Warsawc0fb6052001-08-20 22:29:23 +0000280def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000281 """Raise ResourceDenied if the specified resource is not available.
282
283 If the caller's module is __main__ then automatically return True. The
Barry Warsaw28a691b2010-04-17 00:19:56 +0000284 possibility of False being returned occurs when regrtest.py is
285 executing.
286 """
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000287 if resource == 'gui' and not _is_gui_available():
288 raise unittest.SkipTest("Cannot use the 'gui' resource")
Skip Montanarod839ecd2003-04-24 19:06:57 +0000289 # see if the caller's module is __main__ - if so, treat as if
290 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000291 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000292 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000293 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000294 if msg is None:
295 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000296 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000297
Victor Stinner88701e22011-06-01 13:13:04 +0200298def requires_mac_ver(*min_version):
299 """Decorator raising SkipTest if the OS is Mac OS X and the OS X
300 version if less than min_version.
301
302 For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
303 is lesser than 10.5.
304 """
305 def decorator(func):
306 @functools.wraps(func)
307 def wrapper(*args, **kw):
308 if sys.platform == 'darwin':
309 version_txt = platform.mac_ver()[0]
310 try:
311 version = tuple(map(int, version_txt.split('.')))
312 except ValueError:
313 pass
314 else:
315 if version < min_version:
316 min_version_txt = '.'.join(map(str, min_version))
317 raise unittest.SkipTest(
318 "Mac OS X %s or higher required, not %s"
319 % (min_version_txt, version_txt))
320 return func(*args, **kw)
321 wrapper.min_version = min_version
322 return wrapper
323 return decorator
324
Christian Heimes5e696852008-04-09 08:37:03 +0000325HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000326
Christian Heimes5e696852008-04-09 08:37:03 +0000327def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
328 """Returns an unused port that should be suitable for binding. This is
329 achieved by creating a temporary socket with the same family and type as
330 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
331 the specified host address (defaults to 0.0.0.0) with the port set to 0,
332 eliciting an unused ephemeral port from the OS. The temporary socket is
333 then closed and deleted, and the ephemeral port is returned.
334
335 Either this method or bind_port() should be used for any tests where a
336 server socket needs to be bound to a particular port for the duration of
337 the test. Which one to use depends on whether the calling code is creating
338 a python socket, or if an unused port needs to be provided in a constructor
339 or passed to an external program (i.e. the -accept argument to openssl's
340 s_server mode). Always prefer bind_port() over find_unused_port() where
341 possible. Hard coded ports should *NEVER* be used. As soon as a server
342 socket is bound to a hard coded port, the ability to run multiple instances
343 of the test simultaneously on the same host is compromised, which makes the
344 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
345 may simply manifest as a failed test, which can be recovered from without
346 intervention in most cases, but on Windows, the entire python process can
347 completely and utterly wedge, requiring someone to log in to the buildbot
348 and manually kill the affected process.
349
350 (This is easy to reproduce on Windows, unfortunately, and can be traced to
351 the SO_REUSEADDR socket option having different semantics on Windows versus
352 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
353 listen and then accept connections on identical host/ports. An EADDRINUSE
354 socket.error will be raised at some point (depending on the platform and
355 the order bind and listen were called on each socket).
356
357 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
358 will ever be raised when attempting to bind two identical host/ports. When
359 accept() is called on each socket, the second caller's process will steal
360 the port from the first caller, leaving them both in an awkwardly wedged
361 state where they'll no longer respond to any signals or graceful kills, and
362 must be forcibly killed via OpenProcess()/TerminateProcess().
363
364 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
365 instead of SO_REUSEADDR, which effectively affords the same semantics as
366 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
367 Source world compared to Windows ones, this is a common mistake. A quick
368 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
369 openssl.exe is called with the 's_server' option, for example. See
370 http://bugs.python.org/issue2550 for more info. The following site also
371 has a very thorough description about the implications of both REUSEADDR
372 and EXCLUSIVEADDRUSE on Windows:
373 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
374
375 XXX: although this approach is a vast improvement on previous attempts to
376 elicit unused ports, it rests heavily on the assumption that the ephemeral
377 port returned to us by the OS won't immediately be dished back out to some
378 other process when we close and delete our temporary socket but before our
379 calling code has a chance to bind the returned port. We can deal with this
380 issue if/when we come across it.
381 """
382
383 tempsock = socket.socket(family, socktype)
384 port = bind_port(tempsock)
385 tempsock.close()
386 del tempsock
387 return port
388
389def bind_port(sock, host=HOST):
390 """Bind the socket to a free port and return the port number. Relies on
391 ephemeral ports in order to ensure we are using an unbound port. This is
392 important as many tests may be running simultaneously, especially in a
393 buildbot environment. This method raises an exception if the sock.family
394 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
395 or SO_REUSEPORT set on it. Tests should *never* set these socket options
396 for TCP/IP sockets. The only case for setting these options is testing
397 multicasting via multiple UDP sockets.
398
399 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
400 on Windows), it will be set on the socket. This will prevent anyone else
401 from bind()'ing to our host/port for the duration of the test.
402 """
403
404 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
405 if hasattr(socket, 'SO_REUSEADDR'):
406 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
407 raise TestFailed("tests should never set the SO_REUSEADDR " \
408 "socket option on TCP/IP sockets!")
409 if hasattr(socket, 'SO_REUSEPORT'):
410 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
411 raise TestFailed("tests should never set the SO_REUSEPORT " \
412 "socket option on TCP/IP sockets!")
413 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
414 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
415
416 sock.bind((host, 0))
417 port = sock.getsockname()[1]
418 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000419
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000420FUZZ = 1e-6
421
422def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000423 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000424 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000425 fuzz = (abs(x) + abs(y)) * FUZZ
426 if abs(x-y) <= fuzz:
427 return 0
428 except:
429 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000430 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000431 for i in range(min(len(x), len(y))):
432 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000433 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000434 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000435 return (len(x) > len(y)) - (len(x) < len(y))
436 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000437
Eric Smithf24a0d92010-12-04 13:32:18 +0000438# decorator for skipping tests on non-IEEE 754 platforms
439requires_IEEE_754 = unittest.skipUnless(
440 float.__getformat__("double").startswith("IEEE"),
441 "test requires IEEE 754 doubles")
442
Finn Bock57bc5fa2002-11-01 18:02:03 +0000443is_jython = sys.platform.startswith('java')
444
Barry Warsaw559f6682001-03-23 18:04:02 +0000445# Filename used for testing
446if os.name == 'java':
447 # Jython disallows @ in module names
448 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000449else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000450 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000451
Antoine Pitrou88909542009-06-29 13:54:42 +0000452# Disambiguate TESTFN for parallel testing, while letting it remain a valid
453# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000454TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000455
Michael Foord2d9c2d52010-05-04 22:29:10 +0000456
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000457# TESTFN_UNICODE is a non-ascii filename
458TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
Victor Stinner74a833f2010-08-18 21:06:23 +0000459if sys.platform == 'darwin':
460 # In Mac OS X's VFS API file names are, by definition, canonically
461 # decomposed Unicode, encoded using UTF-8. See QA1173:
462 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
463 import unicodedata
464 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
Antoine Pitrou88909542009-06-29 13:54:42 +0000465TESTFN_ENCODING = sys.getfilesystemencoding()
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000466
Victor Stinner09c449c2010-08-13 22:23:24 +0000467# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000468# encoded by the filesystem encoding (in strict mode). It can be None if we
469# cannot generate such filename.
Victor Stinnera0241c82010-08-15 19:28:21 +0000470TESTFN_UNENCODABLE = None
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000471if os.name in ('nt', 'ce'):
Victor Stinnera0241c82010-08-15 19:28:21 +0000472 # skip win32s (0) or Windows 9x/ME (1)
473 if sys.getwindowsversion().platform >= 2:
Victor Stinner8ce7df62010-09-10 11:19:59 +0000474 # Different kinds of characters from various languages to minimize the
475 # probability that the whole name is encodable to MBCS (issue #9819)
476 TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000477 try:
Victor Stinner09c449c2010-08-13 22:23:24 +0000478 TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000479 except UnicodeEncodeError:
480 pass
481 else:
482 print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
483 'Unicode filename tests may not be effective'
Victor Stinner09c449c2010-08-13 22:23:24 +0000484 % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
485 TESTFN_UNENCODABLE = None
Victor Stinnera0241c82010-08-15 19:28:21 +0000486# Mac OS X denies unencodable filenames (invalid utf-8)
Victor Stinner03c9e1d2010-08-14 17:35:20 +0000487elif sys.platform != 'darwin':
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000488 try:
489 # ascii and utf-8 cannot encode the byte 0xff
490 b'\xff'.decode(TESTFN_ENCODING)
491 except UnicodeDecodeError:
492 # 0xff will be encoded using the surrogate character u+DCFF
Victor Stinner09c449c2010-08-13 22:23:24 +0000493 TESTFN_UNENCODABLE = TESTFN \
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000494 + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
495 else:
496 # File system encoding (eg. ISO-8859-* encodings) can encode
497 # the byte 0xff. Skip some unicode filename tests.
Victor Stinnera0241c82010-08-15 19:28:21 +0000498 pass
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000499
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000500# Save the initial cwd
501SAVEDCWD = os.getcwd()
502
503@contextlib.contextmanager
Nick Coghland26c18a2010-08-17 13:06:11 +0000504def temp_cwd(name='tempcwd', quiet=False, path=None):
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000505 """
Nick Coghland26c18a2010-08-17 13:06:11 +0000506 Context manager that temporarily changes the CWD.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000507
Nick Coghland26c18a2010-08-17 13:06:11 +0000508 An existing path may be provided as *path*, in which case this
509 function makes no changes to the file system.
510
511 Otherwise, the new CWD is created in the current directory and it's
512 named *name*. If *quiet* is False (default) and it's not possible to
513 create or change the CWD, an error is raised. If it's True, only a
514 warning is raised and the original CWD is used.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000515 """
516 saved_dir = os.getcwd()
517 is_temporary = False
Nick Coghland26c18a2010-08-17 13:06:11 +0000518 if path is None:
519 path = name
520 try:
521 os.mkdir(name)
522 is_temporary = True
523 except OSError:
524 if not quiet:
525 raise
526 warnings.warn('tests may fail, unable to create temp CWD ' + name,
527 RuntimeWarning, stacklevel=3)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000528 try:
Nick Coghland26c18a2010-08-17 13:06:11 +0000529 os.chdir(path)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000530 except OSError:
531 if not quiet:
532 raise
533 warnings.warn('tests may fail, unable to change the CWD to ' + name,
534 RuntimeWarning, stacklevel=3)
535 try:
536 yield os.getcwd()
537 finally:
538 os.chdir(saved_dir)
539 if is_temporary:
540 rmtree(name)
541
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000542
Barry Warsaw28a691b2010-04-17 00:19:56 +0000543@contextlib.contextmanager
544def temp_umask(umask):
545 """Context manager that temporarily sets the process umask."""
546 oldmask = os.umask(umask)
547 try:
548 yield
549 finally:
550 os.umask(oldmask)
551
552
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000553def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000554 """Try to find a file on sys.path and the working directory. If it is not
555 found the argument passed to the function is returned (this does not
556 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000557 if os.path.isabs(file):
558 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000559 if subdir is not None:
560 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000561 path = sys.path
562 path = [os.path.dirname(here)] + path
563 for dn in path:
564 fn = os.path.join(dn, file)
565 if os.path.exists(fn): return fn
566 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000567
Tim Peters2f228e72001-05-13 00:19:31 +0000568def sortdict(dict):
569 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000570 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000571 reprpairs = ["%r: %r" % pair for pair in items]
572 withcommas = ", ".join(reprpairs)
573 return "{%s}" % withcommas
574
Benjamin Peterson7522c742009-01-19 21:00:09 +0000575def make_bad_fd():
576 """
577 Create an invalid file descriptor by opening and closing a file and return
578 its fd.
579 """
580 file = open(TESTFN, "wb")
581 try:
582 return file.fileno()
583 finally:
584 file.close()
585 unlink(TESTFN)
586
Thomas Wouters89f507f2006-12-13 04:49:30 +0000587def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000588 testcase.assertRaises(SyntaxError, compile, statement,
589 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000590
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000591def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000592 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000593
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000594 check = kw.pop('check', None)
595
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000596 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000597
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000598 fn = os.path.join(os.path.dirname(__file__), "data", filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000599
600 def check_valid_file(fn):
601 f = open(fn, *args, **kw)
602 if check is None:
603 return f
604 elif check(f):
605 f.seek(0)
606 return f
607 f.close()
608
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000609 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000610 f = check_valid_file(fn)
611 if f is not None:
612 return f
613 unlink(fn)
614
615 # Verify the requirement before downloading the file
616 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000617
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000618 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000619 f = urllib.request.urlopen(url, timeout=15)
620 try:
621 with open(fn, "wb") as out:
622 s = f.read()
623 while s:
624 out.write(s)
625 s = f.read()
626 finally:
627 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000628
629 f = check_valid_file(fn)
630 if f is not None:
631 return f
632 raise TestFailed('invalid resource "%s"' % fn)
633
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000634
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000635class WarningsRecorder(object):
636 """Convenience wrapper for the warnings list returned on
637 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000639 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000640 self._warnings = warnings_list
641 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000642
643 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000644 if len(self._warnings) > self._last:
645 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000646 elif attr in warnings.WarningMessage._WARNING_DETAILS:
647 return None
648 raise AttributeError("%r has no attribute %r" % (self, attr))
649
Florent Xiclunab14930c2010-03-13 15:26:44 +0000650 @property
651 def warnings(self):
652 return self._warnings[self._last:]
653
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000654 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000655 self._last = len(self._warnings)
656
657
658def _filterwarnings(filters, quiet=False):
659 """Catch the warnings, then check if all the expected
660 warnings have been raised and re-raise unexpected warnings.
661 If 'quiet' is True, only re-raise the unexpected warnings.
662 """
663 # Clear the warning registry of the calling module
664 # in order to re-raise the warnings.
665 frame = sys._getframe(2)
666 registry = frame.f_globals.get('__warningregistry__')
667 if registry:
668 registry.clear()
669 with warnings.catch_warnings(record=True) as w:
670 # Set filter "always" to record all warnings. Because
671 # test_warnings swap the module, we need to look up in
672 # the sys.modules dictionary.
673 sys.modules['warnings'].simplefilter("always")
674 yield WarningsRecorder(w)
675 # Filter the recorded warnings
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000676 reraise = list(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000677 missing = []
678 for msg, cat in filters:
679 seen = False
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000680 for w in reraise[:]:
681 warning = w.message
Florent Xiclunab14930c2010-03-13 15:26:44 +0000682 # Filter out the matching messages
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000683 if (re.match(msg, str(warning), re.I) and
684 issubclass(warning.__class__, cat)):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000685 seen = True
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000686 reraise.remove(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000687 if not seen and not quiet:
688 # This filter caught nothing
689 missing.append((msg, cat.__name__))
690 if reraise:
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000691 raise AssertionError("unhandled warning %s" % reraise[0])
Florent Xiclunab14930c2010-03-13 15:26:44 +0000692 if missing:
693 raise AssertionError("filter (%r, %s) did not catch any warning" %
694 missing[0])
695
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000696
697@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000698def check_warnings(*filters, **kwargs):
699 """Context manager to silence warnings.
700
701 Accept 2-tuples as positional arguments:
702 ("message regexp", WarningCategory)
703
704 Optional argument:
705 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506be2010-03-18 20:00:57 +0000706 (default True without argument,
707 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000708
709 Without argument, it defaults to:
Florent Xicluna53b506be2010-03-18 20:00:57 +0000710 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000711 """
Florent Xicluna53b506be2010-03-18 20:00:57 +0000712 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +0000713 if not filters:
714 filters = (("", Warning),)
Florent Xicluna53b506be2010-03-18 20:00:57 +0000715 # Preserve backward compatibility
716 if quiet is None:
717 quiet = True
718 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000719
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000720
721class CleanImport(object):
722 """Context manager to force import to return a new module reference.
723
724 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000725 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000726
727 Use like this:
728
729 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000730 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000731 """
732
733 def __init__(self, *module_names):
734 self.original_modules = sys.modules.copy()
735 for module_name in module_names:
736 if module_name in sys.modules:
737 module = sys.modules[module_name]
738 # It is possible that module_name is just an alias for
739 # another module (e.g. stub for modules renamed in 3.x).
740 # In that case, we also need delete the real module to clear
741 # the import cache.
742 if module.__name__ != module_name:
743 del sys.modules[module.__name__]
744 del sys.modules[module_name]
745
746 def __enter__(self):
747 return self
748
749 def __exit__(self, *ignore_exc):
750 sys.modules.update(self.original_modules)
751
752
Walter Dörwald155374d2009-05-01 19:58:58 +0000753class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000754
755 """Class to help protect the environment variable properly. Can be used as
756 a context manager."""
757
758 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000759 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000760 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000761
Walter Dörwald155374d2009-05-01 19:58:58 +0000762 def __getitem__(self, envvar):
763 return self._environ[envvar]
764
765 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000766 # Remember the initial value on the first access
767 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000768 self._changed[envvar] = self._environ.get(envvar)
769 self._environ[envvar] = value
770
771 def __delitem__(self, envvar):
772 # Remember the initial value on the first access
773 if envvar not in self._changed:
774 self._changed[envvar] = self._environ.get(envvar)
775 if envvar in self._environ:
776 del self._environ[envvar]
777
778 def keys(self):
779 return self._environ.keys()
780
781 def __iter__(self):
782 return iter(self._environ)
783
784 def __len__(self):
785 return len(self._environ)
786
787 def set(self, envvar, value):
788 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000789
790 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000791 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000792
793 def __enter__(self):
794 return self
795
796 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000797 for (k, v) in self._changed.items():
798 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000799 if k in self._environ:
800 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000801 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000802 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000803 os.environ = self._environ
804
805
806class DirsOnSysPath(object):
807 """Context manager to temporarily add directories to sys.path.
808
809 This makes a copy of sys.path, appends any directories given
810 as positional arguments, then reverts sys.path to the copied
811 settings when the context ends.
812
813 Note that *all* sys.path modifications in the body of the
814 context manager, including replacement of the object,
815 will be reverted at the end of the block.
816 """
817
818 def __init__(self, *paths):
819 self.original_value = sys.path[:]
820 self.original_object = sys.path
821 sys.path.extend(paths)
822
823 def __enter__(self):
824 return self
825
826 def __exit__(self, *ignore_exc):
827 sys.path = self.original_object
828 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000829
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000830
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831class TransientResource(object):
832
833 """Raise ResourceDenied if an exception is raised while the context manager
834 is in effect that matches the specified exception and attributes."""
835
836 def __init__(self, exc, **kwargs):
837 self.exc = exc
838 self.attrs = kwargs
839
840 def __enter__(self):
841 return self
842
843 def __exit__(self, type_=None, value=None, traceback=None):
844 """If type_ is a subclass of self.exc and value has attributes matching
845 self.attrs, raise ResourceDenied. Otherwise let the exception
846 propagate (if any)."""
847 if type_ is not None and issubclass(self.exc, type_):
848 for attr, attr_value in self.attrs.items():
849 if not hasattr(value, attr):
850 break
851 if getattr(value, attr) != attr_value:
852 break
853 else:
854 raise ResourceDenied("an optional resource is not available")
855
Raymond Hettinger686057b2009-06-04 00:11:54 +0000856# Context managers that raise ResourceDenied when various issues
857# with the Internet connection manifest themselves as exceptions.
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000858# XXX deprecate these and use transient_internet() instead
Raymond Hettinger686057b2009-06-04 00:11:54 +0000859time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
860socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
861ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000862
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000863
Thomas Woutersed03b412007-08-28 21:37:11 +0000864@contextlib.contextmanager
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000865def transient_internet(resource_name, *, timeout=30.0, errnos=()):
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000866 """Return a context manager that raises ResourceDenied when various issues
867 with the Internet connection manifest themselves as exceptions."""
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000868 default_errnos = [
869 ('ECONNREFUSED', 111),
870 ('ECONNRESET', 104),
Antoine Pitrou5d938cb2011-01-08 10:28:11 +0000871 ('EHOSTUNREACH', 113),
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000872 ('ENETUNREACH', 101),
873 ('ETIMEDOUT', 110),
874 ]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000875 default_gai_errnos = [
Antoine Pitrou4875c462011-07-09 02:31:24 +0200876 ('EAI_AGAIN', -3),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000877 ('EAI_NONAME', -2),
878 ('EAI_NODATA', -5),
Antoine Pitrou390ea0f2011-04-29 00:44:33 +0200879 # Encountered when trying to resolve IPv6-only hostnames
880 ('WSANO_DATA', 11004),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000881 ]
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000882
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000883 denied = ResourceDenied("Resource '%s' is not available" % resource_name)
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000884 captured_errnos = errnos
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000885 gai_errnos = []
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000886 if not captured_errnos:
887 captured_errnos = [getattr(errno, name, num)
888 for (name, num) in default_errnos]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000889 gai_errnos = [getattr(socket, name, num)
890 for (name, num) in default_gai_errnos]
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000891
892 def filter_error(err):
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000893 n = getattr(err, 'errno', None)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000894 if (isinstance(err, socket.timeout) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000895 (isinstance(err, socket.gaierror) and n in gai_errnos) or
896 n in captured_errnos):
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000897 if not verbose:
898 sys.stderr.write(denied.args[0] + "\n")
899 raise denied from err
900
901 old_timeout = socket.getdefaulttimeout()
902 try:
903 if timeout is not None:
904 socket.setdefaulttimeout(timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000905 yield
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000906 except IOError as err:
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000907 # urllib can wrap original socket errors multiple times (!), we must
908 # unwrap to get at the original error.
909 while True:
910 a = err.args
911 if len(a) >= 1 and isinstance(a[0], IOError):
912 err = a[0]
913 # The error can also be wrapped as args[1]:
914 # except socket.error as msg:
915 # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
916 elif len(a) >= 2 and isinstance(a[1], IOError):
917 err = a[1]
918 else:
919 break
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000920 filter_error(err)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000921 raise
922 # XXX should we catch generic exceptions and look for their
923 # __cause__ or __context__?
924 finally:
925 socket.setdefaulttimeout(old_timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000926
927
928@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000929def captured_output(stream_name):
Ezio Melotti07352b02011-05-14 14:51:18 +0300930 """Return a context manager used by captured_stdout/stdin/stderr
Ezio Melottifc778fd2011-05-14 08:22:47 +0300931 that temporarily replaces the sys stream *stream_name* with a StringIO."""
Thomas Woutersed03b412007-08-28 21:37:11 +0000932 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000933 orig_stdout = getattr(sys, stream_name)
934 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000935 try:
936 yield getattr(sys, stream_name)
937 finally:
938 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000939
940def captured_stdout():
Ezio Melottifc778fd2011-05-14 08:22:47 +0300941 """Capture the output of sys.stdout:
942
943 with captured_stdout() as s:
944 print("hello")
945 self.assertEqual(s.getvalue(), "hello")
946 """
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000947 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000948
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000949def captured_stderr():
950 return captured_output("stderr")
951
Nick Coghlan6ead5522009-10-18 13:19:33 +0000952def captured_stdin():
953 return captured_output("stdin")
954
Ezio Melotti07352b02011-05-14 14:51:18 +0300955
Benjamin Petersone549ead2009-03-28 21:42:05 +0000956def gc_collect():
957 """Force as many objects as possible to be collected.
958
959 In non-CPython implementations of Python, this is needed because timely
960 deallocation is not guaranteed by the garbage collector. (Even in CPython
961 this can be the case in case of reference cycles.) This means that __del__
962 methods may be called later than expected and weakrefs may remain alive for
963 longer than expected. This function tries its best to force all garbage
964 objects to disappear.
965 """
Benjamin Petersone549ead2009-03-28 21:42:05 +0000966 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +0000967 if is_jython:
968 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000969 gc.collect()
970 gc.collect()
971
Thomas Woutersed03b412007-08-28 21:37:11 +0000972
Benjamin Peterson65c66ab2010-10-29 21:31:35 +0000973def python_is_optimized():
974 """Find if Python was built with optimizations."""
Antoine Pitrou64474542010-10-31 11:34:47 +0000975 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
Benjamin Peterson65c66ab2010-10-29 21:31:35 +0000976 final_opt = ""
977 for opt in cflags.split():
978 if opt.startswith('-O'):
979 final_opt = opt
980 return final_opt and final_opt != '-O0'
981
982
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000983#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000984# Decorator for running a function in a different locale, correctly resetting
985# it afterwards.
986
987def run_with_locale(catstr, *locales):
988 def decorator(func):
989 def inner(*args, **kwds):
990 try:
991 import locale
992 category = getattr(locale, catstr)
993 orig_locale = locale.setlocale(category)
994 except AttributeError:
995 # if the test author gives us an invalid category string
996 raise
997 except:
998 # cannot retrieve original locale, so do nothing
999 locale = orig_locale = None
1000 else:
1001 for loc in locales:
1002 try:
1003 locale.setlocale(category, loc)
1004 break
1005 except:
1006 pass
1007
1008 # now run the function, resetting the locale on exceptions
1009 try:
1010 return func(*args, **kwds)
1011 finally:
1012 if locale and orig_locale:
1013 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +00001014 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015 inner.__doc__ = func.__doc__
1016 return inner
1017 return decorator
1018
1019#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +00001020# Big-memory-test support. Separate from 'resources' because memory use
1021# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001022
1023# Some handy shorthands. Note that these are used for byte-limits as well
1024# as size-limits, in the various bigmem tests
1025_1M = 1024*1024
1026_1G = 1024 * _1M
1027_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001028_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001030MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001031
Thomas Wouters477c8d52006-05-27 19:21:47 +00001032def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001034 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035 sizes = {
1036 'k': 1024,
1037 'm': _1M,
1038 'g': _1G,
1039 't': 1024*_1G,
1040 }
1041 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
1042 re.IGNORECASE | re.VERBOSE)
1043 if m is None:
1044 raise ValueError('Invalid memory limit %r' % (limit,))
1045 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001046 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001047 if memlimit > MAX_Py_ssize_t:
1048 memlimit = MAX_Py_ssize_t
1049 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001050 raise ValueError('Memory limit %r too low to be useful' % (limit,))
1051 max_memuse = memlimit
1052
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001053def bigmemtest(minsize, memuse):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054 """Decorator for bigmem tests.
1055
1056 'minsize' is the minimum useful size for the test (in arbitrary,
1057 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001058 the test, or a good estimate of it.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059
1060 The decorator tries to guess a good value for 'size' and passes it to
1061 the decorated test function. If minsize * memuse is more than the
1062 allowed memory use (as defined by max_memuse), the test is skipped.
1063 Otherwise, minsize is adjusted upward to use up to max_memuse.
1064 """
1065 def decorator(f):
1066 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001067 # Retrieve values in case someone decided to adjust them
1068 minsize = wrapper.minsize
1069 memuse = wrapper.memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001070 if not max_memuse:
1071 # If max_memuse is 0 (the default),
1072 # we still want to run the tests with size set to a few kb,
1073 # to make sure they work. We still want to avoid using
1074 # too much memory, though, but we do that noisily.
1075 maxsize = 5147
Antoine Pitrou9dd11712011-01-12 21:40:20 +00001076 self.assertFalse(maxsize * memuse > 20 * _1M)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077 else:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001078 maxsize = int(max_memuse / memuse)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 if maxsize < minsize:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001080 raise unittest.SkipTest(
1081 "not enough memory: %.1fG minimum needed"
1082 % (minsize * memuse / (1024 ** 3)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001083 return f(self, maxsize)
1084 wrapper.minsize = minsize
1085 wrapper.memuse = memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001086 return wrapper
1087 return decorator
1088
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001089def precisionbigmemtest(size, memuse):
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001090 def decorator(f):
1091 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001092 size = wrapper.size
1093 memuse = wrapper.memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001094 if not real_max_memuse:
1095 maxsize = 5147
1096 else:
1097 maxsize = size
1098
1099 if real_max_memuse and real_max_memuse < maxsize * memuse:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001100 raise unittest.SkipTest(
1101 "not enough memory: %.1fG minimum needed"
1102 % (size * memuse / (1024 ** 3)))
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001103
1104 return f(self, maxsize)
1105 wrapper.size = size
1106 wrapper.memuse = memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001107 return wrapper
1108 return decorator
1109
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001110def bigaddrspacetest(f):
1111 """Decorator for tests that fill the address space."""
1112 def wrapper(self):
1113 if max_memuse < MAX_Py_ssize_t:
Antoine Pitrou98c62bd2011-01-12 21:58:39 +00001114 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
Antoine Pitroue0d3f8a2011-01-12 21:50:44 +00001115 raise unittest.SkipTest(
1116 "not enough memory: try a 32-bit build instead")
1117 else:
1118 raise unittest.SkipTest(
1119 "not enough memory: %.1fG minimum needed"
1120 % (MAX_Py_ssize_t / (1024 ** 3)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001121 else:
1122 return f(self)
1123 return wrapper
1124
Thomas Wouters477c8d52006-05-27 19:21:47 +00001125#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +00001126# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001127
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001128class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001129 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001130 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001131 test(result)
1132 return result
1133
Benjamin Petersone549ead2009-03-28 21:42:05 +00001134def _id(obj):
1135 return obj
1136
1137def requires_resource(resource):
Antoine Pitrou4914f9e2011-02-26 16:49:08 +00001138 if resource == 'gui' and not _is_gui_available():
1139 return unittest.skip("resource 'gui' is not available")
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +00001140 if is_resource_enabled(resource):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001141 return _id
1142 else:
1143 return unittest.skip("resource {0!r} is not enabled".format(resource))
1144
1145def cpython_only(test):
1146 """
1147 Decorator for tests only applicable on CPython.
1148 """
1149 return impl_detail(cpython=True)(test)
1150
1151def impl_detail(msg=None, **guards):
1152 if check_impl_detail(**guards):
1153 return _id
1154 if msg is None:
1155 guardnames, default = _parse_guards(guards)
1156 if default:
1157 msg = "implementation detail not available on {0}"
1158 else:
1159 msg = "implementation detail specific to {0}"
1160 guardnames = sorted(guardnames.keys())
1161 msg = msg.format(' or '.join(guardnames))
1162 return unittest.skip(msg)
1163
1164def _parse_guards(guards):
1165 # Returns a tuple ({platform_name: run_me}, default_value)
1166 if not guards:
1167 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +00001168 is_true = list(guards.values())[0]
1169 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001170 return (guards, not is_true)
1171
1172# Use the following check to guard CPython's implementation-specific tests --
1173# or to run them only on the implementation(s) guarded by the arguments.
1174def check_impl_detail(**guards):
1175 """This function returns True or False depending on the host platform.
1176 Examples:
1177 if check_impl_detail(): # only on CPython (default)
1178 if check_impl_detail(jython=True): # only on Jython
1179 if check_impl_detail(cpython=False): # everywhere except on CPython
1180 """
1181 guards, default = _parse_guards(guards)
1182 return guards.get(platform.python_implementation().lower(), default)
1183
1184
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001185
Guido van Rossumd8faa362007-04-27 19:54:29 +00001186def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001187 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001188 if verbose:
Victor Stinnerf58087b2010-05-02 17:24:51 +00001189 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001190 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001191 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001192
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001193 result = runner.run(suite)
1194 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001195 if len(result.errors) == 1 and not result.failures:
1196 err = result.errors[0][1]
1197 elif len(result.failures) == 1 and not result.errors:
1198 err = result.failures[0][1]
1199 else:
R. David Murray723357e2009-10-19 18:06:17 +00001200 err = "multiple errors occurred"
1201 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001202 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001203
Barry Warsawc10d6902001-09-20 06:30:41 +00001204
Walter Dörwald21d3a322003-05-01 17:45:56 +00001205def run_unittest(*classes):
1206 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001208 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001209 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001210 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211 if cls in sys.modules:
1212 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1213 else:
1214 raise ValueError("str arguments must be keys in sys.modules")
1215 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001216 suite.addTest(cls)
1217 else:
1218 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001220
Barry Warsawc10d6902001-09-20 06:30:41 +00001221
Tim Petersa0a62222001-09-09 06:12:01 +00001222#=======================================================================
1223# doctest driver.
1224
1225def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +00001226 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001227
1228 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001229 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001230 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001231 """
1232
1233 import doctest
1234
1235 if verbosity is None:
1236 verbosity = verbose
1237 else:
1238 verbosity = None
1239
Victor Stinnerbddc4d42011-06-29 15:52:46 +02001240 f, t = doctest.testmod(module, verbose=verbosity)
1241 if f:
1242 raise TestFailed("%d of %d doctests failed" % (f, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001243 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001244 print('doctest (%s) ... %d tests with zero failures' %
1245 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001246 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001247
Antoine Pitrou060cee22009-11-13 16:29:04 +00001248
1249#=======================================================================
1250# Support for saving and restoring the imported modules.
1251
1252def modules_setup():
1253 return sys.modules.copy(),
1254
1255def modules_cleanup(oldmodules):
1256 # Encoders/decoders are registered permanently within the internal
1257 # codec cache. If we destroy the corresponding modules their
1258 # globals will be set to None which will trip up the cached functions.
1259 encodings = [(k, v) for k, v in sys.modules.items()
1260 if k.startswith('encodings.')]
1261 sys.modules.clear()
1262 sys.modules.update(encodings)
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001263 # XXX: This kind of problem can affect more than just encodings. In particular
Eric Smitha3e8f3d2011-01-11 10:24:34 +00001264 # extension modules (such as _ssl) don't cope with reloading properly.
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001265 # Really, test modules should be cleaning out the test specific modules they
1266 # know they added (ala test_runpy) rather than relying on this function (as
1267 # test_importhooks and test_pkg do currently).
1268 # Implicitly imported *real* modules should be left alone (see issue 10556).
Antoine Pitrou060cee22009-11-13 16:29:04 +00001269 sys.modules.update(oldmodules)
1270
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001271#=======================================================================
1272# Threading support to prevent reporting refleaks when running regrtest.py -R
1273
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001274# NOTE: we use thread._count() rather than threading.enumerate() (or the
1275# moral equivalent thereof) because a threading.Thread object is still alive
1276# until its __bootstrap() method has returned, even after it has been
1277# unregistered from the threading module.
1278# thread._count(), on the other hand, only gets decremented *after* the
1279# __bootstrap() method has returned, which gives us reliable reference counts
1280# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001281
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001282def threading_setup():
Victor Stinner45df8202010-04-28 22:31:17 +00001283 if _thread:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001284 return _thread._count(), threading._dangling.copy()
Victor Stinner45df8202010-04-28 22:31:17 +00001285 else:
Antoine Pitrou707f2282011-07-15 22:29:44 +02001286 return 1, ()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001287
Antoine Pitrou707f2282011-07-15 22:29:44 +02001288def threading_cleanup(*original_values):
Victor Stinner45df8202010-04-28 22:31:17 +00001289 if not _thread:
1290 return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001291 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001292 for count in range(_MAX_COUNT):
Antoine Pitrou707f2282011-07-15 22:29:44 +02001293 values = _thread._count(), threading._dangling
1294 if values == original_values:
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001295 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001296 time.sleep(0.1)
Antoine Pitrou707f2282011-07-15 22:29:44 +02001297 gc_collect()
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001298 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001299
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001300def reap_threads(func):
Victor Stinner45df8202010-04-28 22:31:17 +00001301 """Use this function when threads are being used. This will
1302 ensure that the threads are cleaned up even when the test fails.
1303 If threading is unavailable this function does nothing.
1304 """
1305 if not _thread:
1306 return func
1307
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001308 @functools.wraps(func)
1309 def decorator(*args):
1310 key = threading_setup()
1311 try:
1312 return func(*args)
1313 finally:
1314 threading_cleanup(*key)
1315 return decorator
1316
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001317def reap_children():
1318 """Use this function at the end of test_main() whenever sub-processes
1319 are started. This will help ensure that no extra children (zombies)
1320 stick around to hog resources and create problems when looking
1321 for refleaks.
1322 """
1323
1324 # Reap all our dead child processes so we don't leave zombies around.
1325 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001326 if hasattr(os, 'waitpid'):
1327 any_process = -1
1328 while True:
1329 try:
1330 # This will raise an exception on Windows. That's ok.
1331 pid, status = os.waitpid(any_process, os.WNOHANG)
1332 if pid == 0:
1333 break
1334 except:
1335 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001336
1337@contextlib.contextmanager
1338def swap_attr(obj, attr, new_val):
1339 """Temporary swap out an attribute with a new object.
1340
1341 Usage:
1342 with swap_attr(obj, "attr", 5):
1343 ...
1344
1345 This will set obj.attr to 5 for the duration of the with: block,
1346 restoring the old value at the end of the block. If `attr` doesn't
1347 exist on `obj`, it will be created and then deleted at the end of the
1348 block.
1349 """
1350 if hasattr(obj, attr):
1351 real_val = getattr(obj, attr)
1352 setattr(obj, attr, new_val)
1353 try:
1354 yield
1355 finally:
1356 setattr(obj, attr, real_val)
1357 else:
1358 setattr(obj, attr, new_val)
1359 try:
1360 yield
1361 finally:
1362 delattr(obj, attr)
1363
1364@contextlib.contextmanager
1365def swap_item(obj, item, new_val):
1366 """Temporary swap out an item with a new object.
1367
1368 Usage:
1369 with swap_item(obj, "item", 5):
1370 ...
1371
1372 This will set obj["item"] to 5 for the duration of the with: block,
1373 restoring the old value at the end of the block. If `item` doesn't
1374 exist on `obj`, it will be created and then deleted at the end of the
1375 block.
1376 """
1377 if item in obj:
1378 real_val = obj[item]
1379 obj[item] = new_val
1380 try:
1381 yield
1382 finally:
1383 obj[item] = real_val
1384 else:
1385 obj[item] = new_val
1386 try:
1387 yield
1388 finally:
1389 del obj[item]
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00001390
1391def strip_python_stderr(stderr):
1392 """Strip the stderr of a Python process from potential debug output
1393 emitted by the interpreter.
1394
1395 This will typically be run on the result of the communicate() method
1396 of a subprocess.Popen object.
1397 """
1398 stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
1399 return stderr
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00001400
1401def args_from_interpreter_flags():
1402 """Return a list of command-line arguments reproducing the current
1403 settings in sys.flags."""
1404 flag_opt_map = {
1405 'bytes_warning': 'b',
1406 'dont_write_bytecode': 'B',
1407 'ignore_environment': 'E',
1408 'no_user_site': 's',
1409 'no_site': 'S',
1410 'optimize': 'O',
1411 'verbose': 'v',
1412 }
1413 args = []
1414 for flag, opt in flag_opt_map.items():
1415 v = getattr(sys.flags, flag)
1416 if v > 0:
1417 args.append('-' + opt * v)
1418 return args
Vinay Sajip129fd042010-12-10 08:19:38 +00001419
1420#============================================================
1421# Support for assertions about logging.
1422#============================================================
1423
1424class TestHandler(logging.handlers.BufferingHandler):
1425 def __init__(self, matcher):
1426 # BufferingHandler takes a "capacity" argument
1427 # so as to know when to flush. As we're overriding
1428 # shouldFlush anyway, we can set a capacity of zero.
1429 # You can call flush() manually to clear out the
1430 # buffer.
1431 logging.handlers.BufferingHandler.__init__(self, 0)
1432 self.matcher = matcher
1433
1434 def shouldFlush(self):
1435 return False
1436
1437 def emit(self, record):
1438 self.format(record)
1439 self.buffer.append(record.__dict__)
1440
1441 def matches(self, **kwargs):
1442 """
1443 Look for a saved dict whose keys/values match the supplied arguments.
1444 """
1445 result = False
1446 for d in self.buffer:
1447 if self.matcher.matches(d, **kwargs):
1448 result = True
1449 break
1450 return result
1451
1452class Matcher(object):
1453
1454 _partial_matches = ('msg', 'message')
1455
1456 def matches(self, d, **kwargs):
1457 """
1458 Try to match a single dict with the supplied arguments.
1459
1460 Keys whose values are strings and which are in self._partial_matches
1461 will be checked for partial (i.e. substring) matches. You can extend
1462 this scheme to (for example) do regular expression matching, etc.
1463 """
1464 result = True
1465 for k in kwargs:
1466 v = kwargs[k]
1467 dv = d.get(k)
1468 if not self.match_value(k, dv, v):
1469 result = False
1470 break
1471 return result
1472
1473 def match_value(self, k, dv, v):
1474 """
1475 Try to match a single stored value (dv) with a supplied value (v).
1476 """
1477 if type(v) != type(dv):
1478 result = False
1479 elif type(dv) is not str or k not in self._partial_matches:
1480 result = (v == dv)
1481 else:
1482 result = dv.find(v) >= 0
1483 return result
Brian Curtin3b4499c2010-12-28 14:31:47 +00001484
1485
1486_can_symlink = None
1487def can_symlink():
1488 global _can_symlink
1489 if _can_symlink is not None:
1490 return _can_symlink
Victor Stinner62ec61f2011-06-07 12:17:15 +02001491 symlink_path = TESTFN + "can_symlink"
Brian Curtin3b4499c2010-12-28 14:31:47 +00001492 try:
Victor Stinner62ec61f2011-06-07 12:17:15 +02001493 os.symlink(TESTFN, symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00001494 can = True
Brian Curtind25aef52011-06-13 15:16:04 -05001495 except (OSError, NotImplementedError, AttributeError):
Brian Curtin3b4499c2010-12-28 14:31:47 +00001496 can = False
Victor Stinner62ec61f2011-06-07 12:17:15 +02001497 else:
1498 os.remove(symlink_path)
Brian Curtin3b4499c2010-12-28 14:31:47 +00001499 _can_symlink = can
1500 return can
1501
1502def skip_unless_symlink(test):
1503 """Skip decorator for tests that require functional symlink"""
1504 ok = can_symlink()
1505 msg = "Requires functional symlink implementation"
1506 return test if ok else unittest.skip(msg)(test)
Antoine Pitroue8706232011-03-15 21:05:36 +01001507
Antoine Pitrou2c50a092011-03-15 21:02:59 +01001508def patch(test_instance, object_to_patch, attr_name, new_value):
1509 """Override 'object_to_patch'.'attr_name' with 'new_value'.
1510
1511 Also, add a cleanup procedure to 'test_instance' to restore
1512 'object_to_patch' value for 'attr_name'.
1513 The 'attr_name' should be a valid attribute for 'object_to_patch'.
1514
1515 """
1516 # check that 'attr_name' is a real attribute for 'object_to_patch'
1517 # will raise AttributeError if it does not exist
1518 getattr(object_to_patch, attr_name)
1519
1520 # keep a copy of the old value
1521 attr_is_local = False
1522 try:
1523 old_value = object_to_patch.__dict__[attr_name]
1524 except (AttributeError, KeyError):
1525 old_value = getattr(object_to_patch, attr_name, None)
1526 else:
1527 attr_is_local = True
1528
1529 # restore the value when the test is done
1530 def cleanup():
1531 if attr_is_local:
1532 setattr(object_to_patch, attr_name, old_value)
1533 else:
1534 delattr(object_to_patch, attr_name)
1535
1536 test_instance.addCleanup(cleanup)
1537
1538 # actually override the attribute
1539 setattr(object_to_patch, attr_name, new_value)