blob: 9d39de88761fa3f6470287d2f188a096408af5e0 [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
Barry Warsaw28a691b2010-04-17 00:19:56 +000020import imp
Benjamin Petersona6590e82010-04-11 21:22:10 +000021import time
Fred Drakecd1b1dd2001-03-21 18:26:33 +000022
Barry Warsaw28a691b2010-04-17 00:19:56 +000023__all__ = [
24 "Error", "TestFailed", "ResourceDenied", "import_module",
25 "verbose", "use_resources", "max_memuse", "record_original_stdout",
26 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
27 "is_resource_enabled", "requires", "find_unused_port", "bind_port",
28 "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
29 "findfile", "sortdict", "check_syntax_error", "open_urlresource",
30 "check_warnings", "CleanImport", "EnvironmentVarGuard",
31 "TransientResource", "captured_output", "captured_stdout",
32 "time_out", "socket_peer_reset", "ioerror_peer_reset",
33 "run_with_locale", 'temp_umask',
34 "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
35 "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
36 "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
37 "swap_item", "swap_attr",
38 ]
Benjamin Peterson744c2cd2008-05-26 16:26:37 +000039
Florent Xiclunaf089fd62010-03-19 14:25:03 +000040
Fred Drake1790dd42000-07-24 06:55:00 +000041class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000042 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000043
44class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000045 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000046
Benjamin Petersone549ead2009-03-28 21:42:05 +000047class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +000048 """Test skipped because it requested a disallowed resource.
49
50 This is raised when a test calls requires() for a resource that
51 has not be enabled. It is used to distinguish between expected
52 and unexpected skips.
53 """
54
Nick Coghlanfce769e2009-04-11 14:30:59 +000055@contextlib.contextmanager
56def _ignore_deprecated_imports(ignore=True):
57 """Context manager to suppress package and module deprecation
58 warnings when importing them.
59
60 If ignore is False, this context manager has no effect."""
61 if ignore:
62 with warnings.catch_warnings():
63 warnings.filterwarnings("ignore", ".+ (module|package)",
64 DeprecationWarning)
65 yield
66 else:
67 yield
68
69
Benjamin Peterson699adb92008-05-08 22:27:58 +000070def import_module(name, deprecated=False):
R. David Murraya21e4ca2009-03-31 23:16:50 +000071 """Import and return the module to be tested, raising SkipTest if
72 it is not available.
73
74 If deprecated is True, any module or package deprecation messages
75 will be suppressed."""
Nick Coghlanfce769e2009-04-11 14:30:59 +000076 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +000077 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +000078 return importlib.import_module(name)
R. David Murraya21e4ca2009-03-31 23:16:50 +000079 except ImportError as msg:
80 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +000081
82
Nick Coghlan47384702009-04-22 16:13:36 +000083def _save_and_remove_module(name, orig_modules):
84 """Helper function to save and remove a module from sys.modules
85
86 Return value is True if the module was in sys.modules and
87 False otherwise."""
88 saved = True
89 try:
90 orig_modules[name] = sys.modules[name]
91 except KeyError:
92 saved = False
93 else:
94 del sys.modules[name]
95 return saved
96
97
98def _save_and_block_module(name, orig_modules):
99 """Helper function to save and block a module in sys.modules
100
101 Return value is True if the module was in sys.modules and
102 False otherwise."""
103 saved = True
104 try:
105 orig_modules[name] = sys.modules[name]
106 except KeyError:
107 saved = False
108 sys.modules[name] = 0
109 return saved
110
111
112def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Nick Coghlanfce769e2009-04-11 14:30:59 +0000113 """Imports and returns a module, deliberately bypassing the sys.modules cache
114 and importing a fresh copy of the module. Once the import is complete,
115 the sys.modules cache is restored to its original state.
116
Nick Coghlan47384702009-04-22 16:13:36 +0000117 Modules named in fresh are also imported anew if needed by the import.
118
119 Importing of modules named in blocked is prevented while the fresh import
Nick Coghlanfce769e2009-04-11 14:30:59 +0000120 takes place.
121
122 If deprecated is True, any module or package deprecation messages
123 will be suppressed."""
124 # NOTE: test_heapq and test_warnings include extra sanity checks to make
125 # sure that this utility function is working as expected
126 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000127 # Keep track of modules saved for later restoration as well
128 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000129 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000130 names_to_remove = []
131 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000132 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000133 for fresh_name in fresh:
134 _save_and_remove_module(fresh_name, orig_modules)
135 for blocked_name in blocked:
136 if not _save_and_block_module(blocked_name, orig_modules):
137 names_to_remove.append(blocked_name)
138 fresh_module = importlib.import_module(name)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000139 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000140 for orig_name, module in orig_modules.items():
141 sys.modules[orig_name] = module
142 for name_to_remove in names_to_remove:
143 del sys.modules[name_to_remove]
144 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000145
Benjamin Peterson699adb92008-05-08 22:27:58 +0000146
R. David Murraya21e4ca2009-03-31 23:16:50 +0000147def get_attribute(obj, name):
148 """Get an attribute, raising SkipTest if AttributeError is raised."""
149 try:
150 attribute = getattr(obj, name)
151 except AttributeError:
152 raise unittest.SkipTest("module %s has no attribute %s" % (
153 obj.__name__, name))
154 else:
155 return attribute
156
Barry Warsawc0fb6052001-08-20 22:29:23 +0000157verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158use_resources = None # Flag set to [] by regrtest.py
159max_memuse = 0 # Disable bigmem tests (they will still be run with
160 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000161real_max_memuse = 0
Guido van Rossum531661c1996-12-20 02:58:22 +0000162
Tim Peters8dee8092001-09-25 20:05:11 +0000163# _original_stdout is meant to hold stdout at the time regrtest began.
164# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
165# The point is to have some flavor of stdout the user can actually see.
166_original_stdout = None
167def record_original_stdout(stdout):
168 global _original_stdout
169 _original_stdout = stdout
170
171def get_original_stdout():
172 return _original_stdout or sys.stdout
173
Guido van Rossum3bead091992-01-27 17:00:37 +0000174def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000175 try:
176 del sys.modules[name]
177 except KeyError:
178 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000179
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000180def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000181 try:
182 os.unlink(filename)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000183 except OSError as error:
184 # The filename need not exist.
185 if error.errno != errno.ENOENT:
186 raise
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000187
Christian Heimes23daade02008-02-25 12:39:23 +0000188def rmtree(path):
189 try:
190 shutil.rmtree(path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000191 except OSError as error:
Christian Heimes23daade02008-02-25 12:39:23 +0000192 # Unix returns ENOENT, Windows returns ESRCH.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000193 if error.errno not in (errno.ENOENT, errno.ESRCH):
Christian Heimes23daade02008-02-25 12:39:23 +0000194 raise
195
Barry Warsaw28a691b2010-04-17 00:19:56 +0000196def make_legacy_pyc(source):
197 """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
198
199 The choice of .pyc or .pyo extension is done based on the __debug__ flag
200 value.
201
202 :param source: The file system path to the source file. The source file
203 does not need to exist, however the PEP 3147 pyc file must exist.
204 :return: The file system path to the legacy pyc file.
205 """
206 pyc_file = imp.cache_from_source(source)
207 up_one = os.path.dirname(os.path.abspath(source))
208 legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
209 os.rename(pyc_file, legacy_pyc)
210 return legacy_pyc
211
Guido van Rossum3bead091992-01-27 17:00:37 +0000212def forget(modname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000213 """'Forget' a module was ever imported.
214
215 This removes the module from sys.modules and deletes any PEP 3147 or
216 legacy .pyc and .pyo files.
217 """
Fred Drake004d5e62000-10-23 17:22:08 +0000218 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000219 for dirname in sys.path:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000220 source = os.path.join(dirname, modname + '.py')
221 # It doesn't matter if they exist or not, unlink all possible
222 # combinations of PEP 3147 and legacy pyc and pyo files.
223 unlink(source + 'c')
224 unlink(source + 'o')
225 unlink(imp.cache_from_source(source, debug_override=True))
226 unlink(imp.cache_from_source(source, debug_override=False))
Guido van Rossum3bead091992-01-27 17:00:37 +0000227
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000228def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000229 """Test whether a resource is enabled. Known resources are set by
230 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000231 return use_resources is not None and resource in use_resources
232
Barry Warsawc0fb6052001-08-20 22:29:23 +0000233def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000234 """Raise ResourceDenied if the specified resource is not available.
235
236 If the caller's module is __main__ then automatically return True. The
Barry Warsaw28a691b2010-04-17 00:19:56 +0000237 possibility of False being returned occurs when regrtest.py is
238 executing.
239 """
Skip Montanarod839ecd2003-04-24 19:06:57 +0000240 # see if the caller's module is __main__ - if so, treat as if
241 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000242 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000243 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000244 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000245 if msg is None:
246 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000247 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000248
Christian Heimes5e696852008-04-09 08:37:03 +0000249HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000250
Christian Heimes5e696852008-04-09 08:37:03 +0000251def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
252 """Returns an unused port that should be suitable for binding. This is
253 achieved by creating a temporary socket with the same family and type as
254 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
255 the specified host address (defaults to 0.0.0.0) with the port set to 0,
256 eliciting an unused ephemeral port from the OS. The temporary socket is
257 then closed and deleted, and the ephemeral port is returned.
258
259 Either this method or bind_port() should be used for any tests where a
260 server socket needs to be bound to a particular port for the duration of
261 the test. Which one to use depends on whether the calling code is creating
262 a python socket, or if an unused port needs to be provided in a constructor
263 or passed to an external program (i.e. the -accept argument to openssl's
264 s_server mode). Always prefer bind_port() over find_unused_port() where
265 possible. Hard coded ports should *NEVER* be used. As soon as a server
266 socket is bound to a hard coded port, the ability to run multiple instances
267 of the test simultaneously on the same host is compromised, which makes the
268 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
269 may simply manifest as a failed test, which can be recovered from without
270 intervention in most cases, but on Windows, the entire python process can
271 completely and utterly wedge, requiring someone to log in to the buildbot
272 and manually kill the affected process.
273
274 (This is easy to reproduce on Windows, unfortunately, and can be traced to
275 the SO_REUSEADDR socket option having different semantics on Windows versus
276 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
277 listen and then accept connections on identical host/ports. An EADDRINUSE
278 socket.error will be raised at some point (depending on the platform and
279 the order bind and listen were called on each socket).
280
281 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
282 will ever be raised when attempting to bind two identical host/ports. When
283 accept() is called on each socket, the second caller's process will steal
284 the port from the first caller, leaving them both in an awkwardly wedged
285 state where they'll no longer respond to any signals or graceful kills, and
286 must be forcibly killed via OpenProcess()/TerminateProcess().
287
288 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
289 instead of SO_REUSEADDR, which effectively affords the same semantics as
290 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
291 Source world compared to Windows ones, this is a common mistake. A quick
292 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
293 openssl.exe is called with the 's_server' option, for example. See
294 http://bugs.python.org/issue2550 for more info. The following site also
295 has a very thorough description about the implications of both REUSEADDR
296 and EXCLUSIVEADDRUSE on Windows:
297 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
298
299 XXX: although this approach is a vast improvement on previous attempts to
300 elicit unused ports, it rests heavily on the assumption that the ephemeral
301 port returned to us by the OS won't immediately be dished back out to some
302 other process when we close and delete our temporary socket but before our
303 calling code has a chance to bind the returned port. We can deal with this
304 issue if/when we come across it.
305 """
306
307 tempsock = socket.socket(family, socktype)
308 port = bind_port(tempsock)
309 tempsock.close()
310 del tempsock
311 return port
312
313def bind_port(sock, host=HOST):
314 """Bind the socket to a free port and return the port number. Relies on
315 ephemeral ports in order to ensure we are using an unbound port. This is
316 important as many tests may be running simultaneously, especially in a
317 buildbot environment. This method raises an exception if the sock.family
318 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
319 or SO_REUSEPORT set on it. Tests should *never* set these socket options
320 for TCP/IP sockets. The only case for setting these options is testing
321 multicasting via multiple UDP sockets.
322
323 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
324 on Windows), it will be set on the socket. This will prevent anyone else
325 from bind()'ing to our host/port for the duration of the test.
326 """
327
328 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
329 if hasattr(socket, 'SO_REUSEADDR'):
330 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
331 raise TestFailed("tests should never set the SO_REUSEADDR " \
332 "socket option on TCP/IP sockets!")
333 if hasattr(socket, 'SO_REUSEPORT'):
334 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
335 raise TestFailed("tests should never set the SO_REUSEPORT " \
336 "socket option on TCP/IP sockets!")
337 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
338 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
339
340 sock.bind((host, 0))
341 port = sock.getsockname()[1]
342 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000343
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000344FUZZ = 1e-6
345
346def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000347 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000348 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000349 fuzz = (abs(x) + abs(y)) * FUZZ
350 if abs(x-y) <= fuzz:
351 return 0
352 except:
353 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000354 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000355 for i in range(min(len(x), len(y))):
356 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000357 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000358 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000359 return (len(x) > len(y)) - (len(x) < len(y))
360 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000361
Finn Bock57bc5fa2002-11-01 18:02:03 +0000362is_jython = sys.platform.startswith('java')
363
Barry Warsaw559f6682001-03-23 18:04:02 +0000364# Filename used for testing
365if os.name == 'java':
366 # Jython disallows @ in module names
367 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000368else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000369 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000370
Antoine Pitrou88909542009-06-29 13:54:42 +0000371# Disambiguate TESTFN for parallel testing, while letting it remain a valid
372# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000373TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000374
375# Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
376# TESTFN_UNICODE is a filename that can be encoded using the
377# file system encoding, but *not* with the default (ascii) encoding
378TESTFN_UNICODE = TESTFN + "-\xe0\xf2"
379TESTFN_ENCODING = sys.getfilesystemencoding()
380# TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
381# able to be encoded by *either* the default or filesystem encoding.
382# This test really only makes sense on Windows NT platforms
383# which have special Unicode support in posixmodule.
384if (not hasattr(sys, "getwindowsversion") or
385 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
386 TESTFN_UNICODE_UNENCODEABLE = None
387else:
388 # Japanese characters (I think - from bug 846133)
389 TESTFN_UNICODE_UNENCODEABLE = TESTFN + "-\u5171\u6709\u3055\u308c\u308b"
390 try:
391 # XXX - Note - should be using TESTFN_ENCODING here - but for
392 # Windows, "mbcs" currently always operates as if in
393 # errors=ignore' mode - hence we get '?' characters rather than
394 # the exception. 'Latin1' operates as we expect - ie, fails.
395 # See [ 850997 ] mbcs encoding ignores errors
396 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
397 except UnicodeEncodeError:
398 pass
Walter Dörwald9b775532007-06-08 14:30:53 +0000399 else:
Antoine Pitrou88909542009-06-29 13:54:42 +0000400 print('WARNING: The filename %r CAN be encoded by the filesystem. '
401 'Unicode filename tests may not be effective'
402 % TESTFN_UNICODE_UNENCODEABLE)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000403
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000404# Save the initial cwd
405SAVEDCWD = os.getcwd()
406
407@contextlib.contextmanager
408def temp_cwd(name='tempcwd', quiet=False):
409 """
410 Context manager that creates a temporary directory and set it as CWD.
411
412 The new CWD is created in the current directory and it's named *name*.
413 If *quiet* is False (default) and it's not possible to create or change
414 the CWD, an error is raised. If it's True, only a warning is raised
415 and the original CWD is used.
416 """
417 saved_dir = os.getcwd()
418 is_temporary = False
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000419 try:
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000420 os.mkdir(name)
421 os.chdir(name)
422 is_temporary = True
423 except OSError:
424 if not quiet:
425 raise
426 warnings.warn('tests may fail, unable to change the CWD to ' + name,
427 RuntimeWarning, stacklevel=3)
428 try:
429 yield os.getcwd()
430 finally:
431 os.chdir(saved_dir)
432 if is_temporary:
433 rmtree(name)
434
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000435
Barry Warsaw28a691b2010-04-17 00:19:56 +0000436@contextlib.contextmanager
437def temp_umask(umask):
438 """Context manager that temporarily sets the process umask."""
439 oldmask = os.umask(umask)
440 try:
441 yield
442 finally:
443 os.umask(oldmask)
444
445
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000446def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000447 """Try to find a file on sys.path and the working directory. If it is not
448 found the argument passed to the function is returned (this does not
449 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000450 if os.path.isabs(file):
451 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000452 if subdir is not None:
453 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000454 path = sys.path
455 path = [os.path.dirname(here)] + path
456 for dn in path:
457 fn = os.path.join(dn, file)
458 if os.path.exists(fn): return fn
459 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000460
Tim Peters2f228e72001-05-13 00:19:31 +0000461def sortdict(dict):
462 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000463 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000464 reprpairs = ["%r: %r" % pair for pair in items]
465 withcommas = ", ".join(reprpairs)
466 return "{%s}" % withcommas
467
Benjamin Peterson7522c742009-01-19 21:00:09 +0000468def make_bad_fd():
469 """
470 Create an invalid file descriptor by opening and closing a file and return
471 its fd.
472 """
473 file = open(TESTFN, "wb")
474 try:
475 return file.fileno()
476 finally:
477 file.close()
478 unlink(TESTFN)
479
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000481 testcase.assertRaises(SyntaxError, compile, statement,
482 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000483
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000484def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000485 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000486
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000487 check = kw.pop('check', None)
488
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000489 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000490
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000491 fn = os.path.join(os.path.dirname(__file__), "data", filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000492
493 def check_valid_file(fn):
494 f = open(fn, *args, **kw)
495 if check is None:
496 return f
497 elif check(f):
498 f.seek(0)
499 return f
500 f.close()
501
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000502 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000503 f = check_valid_file(fn)
504 if f is not None:
505 return f
506 unlink(fn)
507
508 # Verify the requirement before downloading the file
509 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000510
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000511 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000512 f = urllib.request.urlopen(url, timeout=15)
513 try:
514 with open(fn, "wb") as out:
515 s = f.read()
516 while s:
517 out.write(s)
518 s = f.read()
519 finally:
520 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000521
522 f = check_valid_file(fn)
523 if f is not None:
524 return f
525 raise TestFailed('invalid resource "%s"' % fn)
526
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000527
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000528class WarningsRecorder(object):
529 """Convenience wrapper for the warnings list returned on
530 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000531 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000532 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000533 self._warnings = warnings_list
534 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000535
536 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000537 if len(self._warnings) > self._last:
538 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000539 elif attr in warnings.WarningMessage._WARNING_DETAILS:
540 return None
541 raise AttributeError("%r has no attribute %r" % (self, attr))
542
Florent Xiclunab14930c2010-03-13 15:26:44 +0000543 @property
544 def warnings(self):
545 return self._warnings[self._last:]
546
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000547 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000548 self._last = len(self._warnings)
549
550
551def _filterwarnings(filters, quiet=False):
552 """Catch the warnings, then check if all the expected
553 warnings have been raised and re-raise unexpected warnings.
554 If 'quiet' is True, only re-raise the unexpected warnings.
555 """
556 # Clear the warning registry of the calling module
557 # in order to re-raise the warnings.
558 frame = sys._getframe(2)
559 registry = frame.f_globals.get('__warningregistry__')
560 if registry:
561 registry.clear()
562 with warnings.catch_warnings(record=True) as w:
563 # Set filter "always" to record all warnings. Because
564 # test_warnings swap the module, we need to look up in
565 # the sys.modules dictionary.
566 sys.modules['warnings'].simplefilter("always")
567 yield WarningsRecorder(w)
568 # Filter the recorded warnings
569 reraise = [warning.message for warning in w]
570 missing = []
571 for msg, cat in filters:
572 seen = False
573 for exc in reraise[:]:
574 message = str(exc)
575 # Filter out the matching messages
576 if (re.match(msg, message, re.I) and
577 issubclass(exc.__class__, cat)):
578 seen = True
579 reraise.remove(exc)
580 if not seen and not quiet:
581 # This filter caught nothing
582 missing.append((msg, cat.__name__))
583 if reraise:
584 raise AssertionError("unhandled warning %r" % reraise[0])
585 if missing:
586 raise AssertionError("filter (%r, %s) did not catch any warning" %
587 missing[0])
588
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000589
590@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000591def check_warnings(*filters, **kwargs):
592 """Context manager to silence warnings.
593
594 Accept 2-tuples as positional arguments:
595 ("message regexp", WarningCategory)
596
597 Optional argument:
598 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506be2010-03-18 20:00:57 +0000599 (default True without argument,
600 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000601
602 Without argument, it defaults to:
Florent Xicluna53b506be2010-03-18 20:00:57 +0000603 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000604 """
Florent Xicluna53b506be2010-03-18 20:00:57 +0000605 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +0000606 if not filters:
607 filters = (("", Warning),)
Florent Xicluna53b506be2010-03-18 20:00:57 +0000608 # Preserve backward compatibility
609 if quiet is None:
610 quiet = True
611 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000612
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000613
614class CleanImport(object):
615 """Context manager to force import to return a new module reference.
616
617 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000618 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000619
620 Use like this:
621
622 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000623 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000624 """
625
626 def __init__(self, *module_names):
627 self.original_modules = sys.modules.copy()
628 for module_name in module_names:
629 if module_name in sys.modules:
630 module = sys.modules[module_name]
631 # It is possible that module_name is just an alias for
632 # another module (e.g. stub for modules renamed in 3.x).
633 # In that case, we also need delete the real module to clear
634 # the import cache.
635 if module.__name__ != module_name:
636 del sys.modules[module.__name__]
637 del sys.modules[module_name]
638
639 def __enter__(self):
640 return self
641
642 def __exit__(self, *ignore_exc):
643 sys.modules.update(self.original_modules)
644
645
Walter Dörwald155374d2009-05-01 19:58:58 +0000646class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000647
648 """Class to help protect the environment variable properly. Can be used as
649 a context manager."""
650
651 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000652 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000653 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000654
Walter Dörwald155374d2009-05-01 19:58:58 +0000655 def __getitem__(self, envvar):
656 return self._environ[envvar]
657
658 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000659 # Remember the initial value on the first access
660 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000661 self._changed[envvar] = self._environ.get(envvar)
662 self._environ[envvar] = value
663
664 def __delitem__(self, envvar):
665 # Remember the initial value on the first access
666 if envvar not in self._changed:
667 self._changed[envvar] = self._environ.get(envvar)
668 if envvar in self._environ:
669 del self._environ[envvar]
670
671 def keys(self):
672 return self._environ.keys()
673
674 def __iter__(self):
675 return iter(self._environ)
676
677 def __len__(self):
678 return len(self._environ)
679
680 def set(self, envvar, value):
681 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000682
683 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000684 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000685
686 def __enter__(self):
687 return self
688
689 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000690 for (k, v) in self._changed.items():
691 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000692 if k in self._environ:
693 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000694 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000695 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000696 os.environ = self._environ
697
698
699class DirsOnSysPath(object):
700 """Context manager to temporarily add directories to sys.path.
701
702 This makes a copy of sys.path, appends any directories given
703 as positional arguments, then reverts sys.path to the copied
704 settings when the context ends.
705
706 Note that *all* sys.path modifications in the body of the
707 context manager, including replacement of the object,
708 will be reverted at the end of the block.
709 """
710
711 def __init__(self, *paths):
712 self.original_value = sys.path[:]
713 self.original_object = sys.path
714 sys.path.extend(paths)
715
716 def __enter__(self):
717 return self
718
719 def __exit__(self, *ignore_exc):
720 sys.path = self.original_object
721 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000722
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000723
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724class TransientResource(object):
725
726 """Raise ResourceDenied if an exception is raised while the context manager
727 is in effect that matches the specified exception and attributes."""
728
729 def __init__(self, exc, **kwargs):
730 self.exc = exc
731 self.attrs = kwargs
732
733 def __enter__(self):
734 return self
735
736 def __exit__(self, type_=None, value=None, traceback=None):
737 """If type_ is a subclass of self.exc and value has attributes matching
738 self.attrs, raise ResourceDenied. Otherwise let the exception
739 propagate (if any)."""
740 if type_ is not None and issubclass(self.exc, type_):
741 for attr, attr_value in self.attrs.items():
742 if not hasattr(value, attr):
743 break
744 if getattr(value, attr) != attr_value:
745 break
746 else:
747 raise ResourceDenied("an optional resource is not available")
748
749
Raymond Hettinger686057b2009-06-04 00:11:54 +0000750# Context managers that raise ResourceDenied when various issues
751# with the Internet connection manifest themselves as exceptions.
752time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
753socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
754ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000756
Thomas Woutersed03b412007-08-28 21:37:11 +0000757@contextlib.contextmanager
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000758def transient_internet():
759 """Return a context manager that raises ResourceDenied when various issues
760 with the Internet connection manifest themselves as exceptions."""
761 time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
762 socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
763 ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
764 with time_out, socket_peer_reset, ioerror_peer_reset:
765 yield
766
767
768@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000769def captured_output(stream_name):
770 """Run the 'with' statement body using a StringIO object in place of a
771 specific attribute on the sys module.
772 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000773
774 with captured_stdout() as s:
Neal Norwitz752abd02008-05-13 04:55:24 +0000775 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000776 assert s.getvalue() == "hello"
777 """
778 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000779 orig_stdout = getattr(sys, stream_name)
780 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000781 try:
782 yield getattr(sys, stream_name)
783 finally:
784 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000785
786def captured_stdout():
787 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000788
Nick Coghlan6ead5522009-10-18 13:19:33 +0000789def captured_stdin():
790 return captured_output("stdin")
791
Benjamin Petersone549ead2009-03-28 21:42:05 +0000792def gc_collect():
793 """Force as many objects as possible to be collected.
794
795 In non-CPython implementations of Python, this is needed because timely
796 deallocation is not guaranteed by the garbage collector. (Even in CPython
797 this can be the case in case of reference cycles.) This means that __del__
798 methods may be called later than expected and weakrefs may remain alive for
799 longer than expected. This function tries its best to force all garbage
800 objects to disappear.
801 """
Benjamin Petersone549ead2009-03-28 21:42:05 +0000802 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +0000803 if is_jython:
804 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000805 gc.collect()
806 gc.collect()
807
Thomas Woutersed03b412007-08-28 21:37:11 +0000808
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000809#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810# Decorator for running a function in a different locale, correctly resetting
811# it afterwards.
812
813def run_with_locale(catstr, *locales):
814 def decorator(func):
815 def inner(*args, **kwds):
816 try:
817 import locale
818 category = getattr(locale, catstr)
819 orig_locale = locale.setlocale(category)
820 except AttributeError:
821 # if the test author gives us an invalid category string
822 raise
823 except:
824 # cannot retrieve original locale, so do nothing
825 locale = orig_locale = None
826 else:
827 for loc in locales:
828 try:
829 locale.setlocale(category, loc)
830 break
831 except:
832 pass
833
834 # now run the function, resetting the locale on exceptions
835 try:
836 return func(*args, **kwds)
837 finally:
838 if locale and orig_locale:
839 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000840 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000841 inner.__doc__ = func.__doc__
842 return inner
843 return decorator
844
845#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000846# Big-memory-test support. Separate from 'resources' because memory use
847# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848
849# Some handy shorthands. Note that these are used for byte-limits as well
850# as size-limits, in the various bigmem tests
851_1M = 1024*1024
852_1G = 1024 * _1M
853_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000854_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +0000855
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000856MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000857
Thomas Wouters477c8d52006-05-27 19:21:47 +0000858def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000859 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000860 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +0000861 sizes = {
862 'k': 1024,
863 'm': _1M,
864 'g': _1G,
865 't': 1024*_1G,
866 }
867 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
868 re.IGNORECASE | re.VERBOSE)
869 if m is None:
870 raise ValueError('Invalid memory limit %r' % (limit,))
871 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000872 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000873 if memlimit > MAX_Py_ssize_t:
874 memlimit = MAX_Py_ssize_t
875 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000876 raise ValueError('Memory limit %r too low to be useful' % (limit,))
877 max_memuse = memlimit
878
879def bigmemtest(minsize, memuse, overhead=5*_1M):
880 """Decorator for bigmem tests.
881
882 'minsize' is the minimum useful size for the test (in arbitrary,
883 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
884 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
Christian Heimes33fe8092008-04-13 13:53:33 +0000885 independent of the testsize, and defaults to 5Mb.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000886
887 The decorator tries to guess a good value for 'size' and passes it to
888 the decorated test function. If minsize * memuse is more than the
889 allowed memory use (as defined by max_memuse), the test is skipped.
890 Otherwise, minsize is adjusted upward to use up to max_memuse.
891 """
892 def decorator(f):
893 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000894 # Retrieve values in case someone decided to adjust them
895 minsize = wrapper.minsize
896 memuse = wrapper.memuse
897 overhead = wrapper.overhead
Thomas Wouters477c8d52006-05-27 19:21:47 +0000898 if not max_memuse:
899 # If max_memuse is 0 (the default),
900 # we still want to run the tests with size set to a few kb,
901 # to make sure they work. We still want to avoid using
902 # too much memory, though, but we do that noisily.
903 maxsize = 5147
Benjamin Peterson46d44402009-07-01 00:45:43 +0000904 self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000905 else:
906 maxsize = int((max_memuse - overhead) / memuse)
907 if maxsize < minsize:
908 # Really ought to print 'test skipped' or something
909 if verbose:
910 sys.stderr.write("Skipping %s because of memory "
911 "constraint\n" % (f.__name__,))
912 return
913 # Try to keep some breathing room in memory use
914 maxsize = max(maxsize - 50 * _1M, minsize)
915 return f(self, maxsize)
916 wrapper.minsize = minsize
917 wrapper.memuse = memuse
918 wrapper.overhead = overhead
919 return wrapper
920 return decorator
921
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000922def precisionbigmemtest(size, memuse, overhead=5*_1M):
923 def decorator(f):
924 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000925 size = wrapper.size
926 memuse = wrapper.memuse
927 overhead = wrapper.overhead
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000928 if not real_max_memuse:
929 maxsize = 5147
930 else:
931 maxsize = size
932
933 if real_max_memuse and real_max_memuse < maxsize * memuse:
934 if verbose:
935 sys.stderr.write("Skipping %s because of memory "
936 "constraint\n" % (f.__name__,))
937 return
938
939 return f(self, maxsize)
940 wrapper.size = size
941 wrapper.memuse = memuse
942 wrapper.overhead = overhead
943 return wrapper
944 return decorator
945
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000946def bigaddrspacetest(f):
947 """Decorator for tests that fill the address space."""
948 def wrapper(self):
949 if max_memuse < MAX_Py_ssize_t:
950 if verbose:
951 sys.stderr.write("Skipping %s because of memory "
952 "constraint\n" % (f.__name__,))
953 else:
954 return f(self)
955 return wrapper
956
Thomas Wouters477c8d52006-05-27 19:21:47 +0000957#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +0000958# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000959
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000960class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000961 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000962 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000963 test(result)
964 return result
965
Benjamin Petersone549ead2009-03-28 21:42:05 +0000966def _id(obj):
967 return obj
968
969def requires_resource(resource):
970 if resource_is_enabled(resource):
971 return _id
972 else:
973 return unittest.skip("resource {0!r} is not enabled".format(resource))
974
975def cpython_only(test):
976 """
977 Decorator for tests only applicable on CPython.
978 """
979 return impl_detail(cpython=True)(test)
980
981def impl_detail(msg=None, **guards):
982 if check_impl_detail(**guards):
983 return _id
984 if msg is None:
985 guardnames, default = _parse_guards(guards)
986 if default:
987 msg = "implementation detail not available on {0}"
988 else:
989 msg = "implementation detail specific to {0}"
990 guardnames = sorted(guardnames.keys())
991 msg = msg.format(' or '.join(guardnames))
992 return unittest.skip(msg)
993
994def _parse_guards(guards):
995 # Returns a tuple ({platform_name: run_me}, default_value)
996 if not guards:
997 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +0000998 is_true = list(guards.values())[0]
999 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001000 return (guards, not is_true)
1001
1002# Use the following check to guard CPython's implementation-specific tests --
1003# or to run them only on the implementation(s) guarded by the arguments.
1004def check_impl_detail(**guards):
1005 """This function returns True or False depending on the host platform.
1006 Examples:
1007 if check_impl_detail(): # only on CPython (default)
1008 if check_impl_detail(jython=True): # only on Jython
1009 if check_impl_detail(cpython=False): # everywhere except on CPython
1010 """
1011 guards, default = _parse_guards(guards)
1012 return guards.get(platform.python_implementation().lower(), default)
1013
1014
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001015
Guido van Rossumd8faa362007-04-27 19:54:29 +00001016def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001017 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001018 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +00001019 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001020 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001021 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001022
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001023 result = runner.run(suite)
1024 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001025 if len(result.errors) == 1 and not result.failures:
1026 err = result.errors[0][1]
1027 elif len(result.failures) == 1 and not result.errors:
1028 err = result.failures[0][1]
1029 else:
R. David Murray723357e2009-10-19 18:06:17 +00001030 err = "multiple errors occurred"
1031 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001032 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001033
Barry Warsawc10d6902001-09-20 06:30:41 +00001034
Walter Dörwald21d3a322003-05-01 17:45:56 +00001035def run_unittest(*classes):
1036 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001037 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001038 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001039 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001040 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001041 if cls in sys.modules:
1042 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1043 else:
1044 raise ValueError("str arguments must be keys in sys.modules")
1045 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001046 suite.addTest(cls)
1047 else:
1048 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001050
Barry Warsawc10d6902001-09-20 06:30:41 +00001051
Tim Petersa0a62222001-09-09 06:12:01 +00001052#=======================================================================
1053# doctest driver.
1054
1055def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +00001056 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001057
1058 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001059 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001060 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001061 """
1062
1063 import doctest
1064
1065 if verbosity is None:
1066 verbosity = verbose
1067 else:
1068 verbosity = None
1069
Tim Peters342ca752001-09-25 19:13:20 +00001070 # Direct doctest output (normally just errors) to real stdout; doctest
1071 # output shouldn't be compared by regrtest.
1072 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +00001073 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +00001074 try:
1075 f, t = doctest.testmod(module, verbose=verbosity)
1076 if f:
1077 raise TestFailed("%d of %d doctests failed" % (f, t))
1078 finally:
1079 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001080 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001081 print('doctest (%s) ... %d tests with zero failures' %
1082 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001083 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001084
Antoine Pitrou060cee22009-11-13 16:29:04 +00001085
1086#=======================================================================
1087# Support for saving and restoring the imported modules.
1088
1089def modules_setup():
1090 return sys.modules.copy(),
1091
1092def modules_cleanup(oldmodules):
1093 # Encoders/decoders are registered permanently within the internal
1094 # codec cache. If we destroy the corresponding modules their
1095 # globals will be set to None which will trip up the cached functions.
1096 encodings = [(k, v) for k, v in sys.modules.items()
1097 if k.startswith('encodings.')]
1098 sys.modules.clear()
1099 sys.modules.update(encodings)
1100 sys.modules.update(oldmodules)
1101
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001102#=======================================================================
1103# Threading support to prevent reporting refleaks when running regrtest.py -R
1104
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001105# NOTE: we use thread._count() rather than threading.enumerate() (or the
1106# moral equivalent thereof) because a threading.Thread object is still alive
1107# until its __bootstrap() method has returned, even after it has been
1108# unregistered from the threading module.
1109# thread._count(), on the other hand, only gets decremented *after* the
1110# __bootstrap() method has returned, which gives us reliable reference counts
1111# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001112
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001113def threading_setup():
1114 import _thread
1115 return _thread._count(),
1116
1117def threading_cleanup(nb_threads):
1118 import _thread
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001119
1120 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001121 for count in range(_MAX_COUNT):
1122 n = _thread._count()
1123 if n == nb_threads:
1124 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001125 time.sleep(0.1)
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001126 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001127
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001128def reap_threads(func):
1129 @functools.wraps(func)
1130 def decorator(*args):
1131 key = threading_setup()
1132 try:
1133 return func(*args)
1134 finally:
1135 threading_cleanup(*key)
1136 return decorator
1137
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001138def reap_children():
1139 """Use this function at the end of test_main() whenever sub-processes
1140 are started. This will help ensure that no extra children (zombies)
1141 stick around to hog resources and create problems when looking
1142 for refleaks.
1143 """
1144
1145 # Reap all our dead child processes so we don't leave zombies around.
1146 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001147 if hasattr(os, 'waitpid'):
1148 any_process = -1
1149 while True:
1150 try:
1151 # This will raise an exception on Windows. That's ok.
1152 pid, status = os.waitpid(any_process, os.WNOHANG)
1153 if pid == 0:
1154 break
1155 except:
1156 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001157
1158@contextlib.contextmanager
1159def swap_attr(obj, attr, new_val):
1160 """Temporary swap out an attribute with a new object.
1161
1162 Usage:
1163 with swap_attr(obj, "attr", 5):
1164 ...
1165
1166 This will set obj.attr to 5 for the duration of the with: block,
1167 restoring the old value at the end of the block. If `attr` doesn't
1168 exist on `obj`, it will be created and then deleted at the end of the
1169 block.
1170 """
1171 if hasattr(obj, attr):
1172 real_val = getattr(obj, attr)
1173 setattr(obj, attr, new_val)
1174 try:
1175 yield
1176 finally:
1177 setattr(obj, attr, real_val)
1178 else:
1179 setattr(obj, attr, new_val)
1180 try:
1181 yield
1182 finally:
1183 delattr(obj, attr)
1184
1185@contextlib.contextmanager
1186def swap_item(obj, item, new_val):
1187 """Temporary swap out an item with a new object.
1188
1189 Usage:
1190 with swap_item(obj, "item", 5):
1191 ...
1192
1193 This will set obj["item"] to 5 for the duration of the with: block,
1194 restoring the old value at the end of the block. If `item` doesn't
1195 exist on `obj`, it will be created and then deleted at the end of the
1196 block.
1197 """
1198 if item in obj:
1199 real_val = obj[item]
1200 obj[item] = new_val
1201 try:
1202 yield
1203 finally:
1204 obj[item] = real_val
1205 else:
1206 obj[item] = new_val
1207 try:
1208 yield
1209 finally:
1210 del obj[item]