blob: 9f9292d975fb450457ea1a757e8807c02449349c [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
Benjamin Petersona6590e82010-04-11 21:22:10 +000020import time
Fred Drakecd1b1dd2001-03-21 18:26:33 +000021
Benjamin Petersone549ead2009-03-28 21:42:05 +000022__all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
Benjamin Peterson744c2cd2008-05-26 16:26:37 +000023 "verbose", "use_resources", "max_memuse", "record_original_stdout",
24 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
25 "is_resource_enabled", "requires", "find_unused_port", "bind_port",
Ezio Melotti184bdfb2010-02-18 09:37:05 +000026 "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
27 "findfile", "sortdict", "check_syntax_error", "open_urlresource",
Benjamin Petersonfcf5d632008-10-16 23:24:44 +000028 "check_warnings", "CleanImport", "EnvironmentVarGuard",
Benjamin Peterson79e48032008-05-26 17:44:33 +000029 "TransientResource", "captured_output", "captured_stdout",
Raymond Hettingerd76b9f12009-06-04 00:35:30 +000030 "time_out", "socket_peer_reset", "ioerror_peer_reset",
31 "run_with_locale",
Benjamin Peterson79e48032008-05-26 17:44:33 +000032 "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
33 "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
Collin Winterf2bf2b32010-03-17 00:41:56 +000034 "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
35 "swap_item", "swap_attr"]
Benjamin Peterson744c2cd2008-05-26 16:26:37 +000036
Florent Xiclunaf089fd62010-03-19 14:25:03 +000037
Fred Drake1790dd42000-07-24 06:55:00 +000038class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000039 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000040
41class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000042 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000043
Benjamin Petersone549ead2009-03-28 21:42:05 +000044class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +000045 """Test skipped because it requested a disallowed resource.
46
47 This is raised when a test calls requires() for a resource that
48 has not be enabled. It is used to distinguish between expected
49 and unexpected skips.
50 """
51
Nick Coghlanfce769e2009-04-11 14:30:59 +000052@contextlib.contextmanager
53def _ignore_deprecated_imports(ignore=True):
54 """Context manager to suppress package and module deprecation
55 warnings when importing them.
56
57 If ignore is False, this context manager has no effect."""
58 if ignore:
59 with warnings.catch_warnings():
60 warnings.filterwarnings("ignore", ".+ (module|package)",
61 DeprecationWarning)
62 yield
63 else:
64 yield
65
66
Benjamin Peterson699adb92008-05-08 22:27:58 +000067def import_module(name, deprecated=False):
R. David Murraya21e4ca2009-03-31 23:16:50 +000068 """Import and return the module to be tested, raising SkipTest if
69 it is not available.
70
71 If deprecated is True, any module or package deprecation messages
72 will be suppressed."""
Nick Coghlanfce769e2009-04-11 14:30:59 +000073 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +000074 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +000075 return importlib.import_module(name)
R. David Murraya21e4ca2009-03-31 23:16:50 +000076 except ImportError as msg:
77 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +000078
79
Nick Coghlan47384702009-04-22 16:13:36 +000080def _save_and_remove_module(name, orig_modules):
81 """Helper function to save and remove a module from sys.modules
82
83 Return value is True if the module was in sys.modules and
84 False otherwise."""
85 saved = True
86 try:
87 orig_modules[name] = sys.modules[name]
88 except KeyError:
89 saved = False
90 else:
91 del sys.modules[name]
92 return saved
93
94
95def _save_and_block_module(name, orig_modules):
96 """Helper function to save and block a module in sys.modules
97
98 Return value is True if the module was in sys.modules and
99 False otherwise."""
100 saved = True
101 try:
102 orig_modules[name] = sys.modules[name]
103 except KeyError:
104 saved = False
105 sys.modules[name] = 0
106 return saved
107
108
109def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Nick Coghlanfce769e2009-04-11 14:30:59 +0000110 """Imports and returns a module, deliberately bypassing the sys.modules cache
111 and importing a fresh copy of the module. Once the import is complete,
112 the sys.modules cache is restored to its original state.
113
Nick Coghlan47384702009-04-22 16:13:36 +0000114 Modules named in fresh are also imported anew if needed by the import.
115
116 Importing of modules named in blocked is prevented while the fresh import
Nick Coghlanfce769e2009-04-11 14:30:59 +0000117 takes place.
118
119 If deprecated is True, any module or package deprecation messages
120 will be suppressed."""
121 # NOTE: test_heapq and test_warnings include extra sanity checks to make
122 # sure that this utility function is working as expected
123 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000124 # Keep track of modules saved for later restoration as well
125 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000126 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000127 names_to_remove = []
128 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000129 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000130 for fresh_name in fresh:
131 _save_and_remove_module(fresh_name, orig_modules)
132 for blocked_name in blocked:
133 if not _save_and_block_module(blocked_name, orig_modules):
134 names_to_remove.append(blocked_name)
135 fresh_module = importlib.import_module(name)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000136 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000137 for orig_name, module in orig_modules.items():
138 sys.modules[orig_name] = module
139 for name_to_remove in names_to_remove:
140 del sys.modules[name_to_remove]
141 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000142
Benjamin Peterson699adb92008-05-08 22:27:58 +0000143
R. David Murraya21e4ca2009-03-31 23:16:50 +0000144def get_attribute(obj, name):
145 """Get an attribute, raising SkipTest if AttributeError is raised."""
146 try:
147 attribute = getattr(obj, name)
148 except AttributeError:
149 raise unittest.SkipTest("module %s has no attribute %s" % (
150 obj.__name__, name))
151 else:
152 return attribute
153
Barry Warsawc0fb6052001-08-20 22:29:23 +0000154verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000155use_resources = None # Flag set to [] by regrtest.py
156max_memuse = 0 # Disable bigmem tests (they will still be run with
157 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000158real_max_memuse = 0
Guido van Rossum531661c1996-12-20 02:58:22 +0000159
Tim Peters8dee8092001-09-25 20:05:11 +0000160# _original_stdout is meant to hold stdout at the time regrtest began.
161# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
162# The point is to have some flavor of stdout the user can actually see.
163_original_stdout = None
164def record_original_stdout(stdout):
165 global _original_stdout
166 _original_stdout = stdout
167
168def get_original_stdout():
169 return _original_stdout or sys.stdout
170
Guido van Rossum3bead091992-01-27 17:00:37 +0000171def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000172 try:
173 del sys.modules[name]
174 except KeyError:
175 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000176
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000177def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000178 try:
179 os.unlink(filename)
180 except OSError:
181 pass
182
Christian Heimes23daade02008-02-25 12:39:23 +0000183def rmtree(path):
184 try:
185 shutil.rmtree(path)
186 except OSError as e:
187 # Unix returns ENOENT, Windows returns ESRCH.
188 if e.errno not in (errno.ENOENT, errno.ESRCH):
189 raise
190
Guido van Rossum3bead091992-01-27 17:00:37 +0000191def forget(modname):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000192 '''"Forget" a module was ever imported by removing it from sys.modules and
193 deleting any .pyc and .pyo files.'''
Fred Drake004d5e62000-10-23 17:22:08 +0000194 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000195 for dirname in sys.path:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000196 unlink(os.path.join(dirname, modname + '.pyc'))
Brett Cannonf1cfb622003-05-04 21:15:27 +0000197 # Deleting the .pyo file cannot be within the 'try' for the .pyc since
198 # the chance exists that there is no .pyc (and thus the 'try' statement
199 # is exited) but there is a .pyo file.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000200 unlink(os.path.join(dirname, modname + '.pyo'))
Guido van Rossum3bead091992-01-27 17:00:37 +0000201
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000202def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000203 """Test whether a resource is enabled. Known resources are set by
204 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000205 return use_resources is not None and resource in use_resources
206
Barry Warsawc0fb6052001-08-20 22:29:23 +0000207def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000208 """Raise ResourceDenied if the specified resource is not available.
209
210 If the caller's module is __main__ then automatically return True. The
211 possibility of False being returned occurs when regrtest.py is executing."""
Skip Montanarod839ecd2003-04-24 19:06:57 +0000212 # see if the caller's module is __main__ - if so, treat as if
213 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000214 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000215 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000216 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000217 if msg is None:
218 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000219 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000220
Christian Heimes5e696852008-04-09 08:37:03 +0000221HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000222
Christian Heimes5e696852008-04-09 08:37:03 +0000223def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
224 """Returns an unused port that should be suitable for binding. This is
225 achieved by creating a temporary socket with the same family and type as
226 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
227 the specified host address (defaults to 0.0.0.0) with the port set to 0,
228 eliciting an unused ephemeral port from the OS. The temporary socket is
229 then closed and deleted, and the ephemeral port is returned.
230
231 Either this method or bind_port() should be used for any tests where a
232 server socket needs to be bound to a particular port for the duration of
233 the test. Which one to use depends on whether the calling code is creating
234 a python socket, or if an unused port needs to be provided in a constructor
235 or passed to an external program (i.e. the -accept argument to openssl's
236 s_server mode). Always prefer bind_port() over find_unused_port() where
237 possible. Hard coded ports should *NEVER* be used. As soon as a server
238 socket is bound to a hard coded port, the ability to run multiple instances
239 of the test simultaneously on the same host is compromised, which makes the
240 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
241 may simply manifest as a failed test, which can be recovered from without
242 intervention in most cases, but on Windows, the entire python process can
243 completely and utterly wedge, requiring someone to log in to the buildbot
244 and manually kill the affected process.
245
246 (This is easy to reproduce on Windows, unfortunately, and can be traced to
247 the SO_REUSEADDR socket option having different semantics on Windows versus
248 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
249 listen and then accept connections on identical host/ports. An EADDRINUSE
250 socket.error will be raised at some point (depending on the platform and
251 the order bind and listen were called on each socket).
252
253 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
254 will ever be raised when attempting to bind two identical host/ports. When
255 accept() is called on each socket, the second caller's process will steal
256 the port from the first caller, leaving them both in an awkwardly wedged
257 state where they'll no longer respond to any signals or graceful kills, and
258 must be forcibly killed via OpenProcess()/TerminateProcess().
259
260 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
261 instead of SO_REUSEADDR, which effectively affords the same semantics as
262 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
263 Source world compared to Windows ones, this is a common mistake. A quick
264 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
265 openssl.exe is called with the 's_server' option, for example. See
266 http://bugs.python.org/issue2550 for more info. The following site also
267 has a very thorough description about the implications of both REUSEADDR
268 and EXCLUSIVEADDRUSE on Windows:
269 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
270
271 XXX: although this approach is a vast improvement on previous attempts to
272 elicit unused ports, it rests heavily on the assumption that the ephemeral
273 port returned to us by the OS won't immediately be dished back out to some
274 other process when we close and delete our temporary socket but before our
275 calling code has a chance to bind the returned port. We can deal with this
276 issue if/when we come across it.
277 """
278
279 tempsock = socket.socket(family, socktype)
280 port = bind_port(tempsock)
281 tempsock.close()
282 del tempsock
283 return port
284
285def bind_port(sock, host=HOST):
286 """Bind the socket to a free port and return the port number. Relies on
287 ephemeral ports in order to ensure we are using an unbound port. This is
288 important as many tests may be running simultaneously, especially in a
289 buildbot environment. This method raises an exception if the sock.family
290 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
291 or SO_REUSEPORT set on it. Tests should *never* set these socket options
292 for TCP/IP sockets. The only case for setting these options is testing
293 multicasting via multiple UDP sockets.
294
295 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
296 on Windows), it will be set on the socket. This will prevent anyone else
297 from bind()'ing to our host/port for the duration of the test.
298 """
299
300 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
301 if hasattr(socket, 'SO_REUSEADDR'):
302 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
303 raise TestFailed("tests should never set the SO_REUSEADDR " \
304 "socket option on TCP/IP sockets!")
305 if hasattr(socket, 'SO_REUSEPORT'):
306 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
307 raise TestFailed("tests should never set the SO_REUSEPORT " \
308 "socket option on TCP/IP sockets!")
309 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
310 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
311
312 sock.bind((host, 0))
313 port = sock.getsockname()[1]
314 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000315
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000316FUZZ = 1e-6
317
318def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000319 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000320 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000321 fuzz = (abs(x) + abs(y)) * FUZZ
322 if abs(x-y) <= fuzz:
323 return 0
324 except:
325 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000326 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000327 for i in range(min(len(x), len(y))):
328 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000329 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000330 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000331 return (len(x) > len(y)) - (len(x) < len(y))
332 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000333
Finn Bock57bc5fa2002-11-01 18:02:03 +0000334is_jython = sys.platform.startswith('java')
335
Barry Warsaw559f6682001-03-23 18:04:02 +0000336# Filename used for testing
337if os.name == 'java':
338 # Jython disallows @ in module names
339 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000340else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000341 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000342
Antoine Pitrou88909542009-06-29 13:54:42 +0000343# Disambiguate TESTFN for parallel testing, while letting it remain a valid
344# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000345TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000346
347# Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
348# TESTFN_UNICODE is a filename that can be encoded using the
349# file system encoding, but *not* with the default (ascii) encoding
350TESTFN_UNICODE = TESTFN + "-\xe0\xf2"
351TESTFN_ENCODING = sys.getfilesystemencoding()
352# TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
353# able to be encoded by *either* the default or filesystem encoding.
354# This test really only makes sense on Windows NT platforms
355# which have special Unicode support in posixmodule.
356if (not hasattr(sys, "getwindowsversion") or
357 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
358 TESTFN_UNICODE_UNENCODEABLE = None
359else:
360 # Japanese characters (I think - from bug 846133)
361 TESTFN_UNICODE_UNENCODEABLE = TESTFN + "-\u5171\u6709\u3055\u308c\u308b"
362 try:
363 # XXX - Note - should be using TESTFN_ENCODING here - but for
364 # Windows, "mbcs" currently always operates as if in
365 # errors=ignore' mode - hence we get '?' characters rather than
366 # the exception. 'Latin1' operates as we expect - ie, fails.
367 # See [ 850997 ] mbcs encoding ignores errors
368 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
369 except UnicodeEncodeError:
370 pass
Walter Dörwald9b775532007-06-08 14:30:53 +0000371 else:
Antoine Pitrou88909542009-06-29 13:54:42 +0000372 print('WARNING: The filename %r CAN be encoded by the filesystem. '
373 'Unicode filename tests may not be effective'
374 % TESTFN_UNICODE_UNENCODEABLE)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000375
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000376# Save the initial cwd
377SAVEDCWD = os.getcwd()
378
379@contextlib.contextmanager
380def temp_cwd(name='tempcwd', quiet=False):
381 """
382 Context manager that creates a temporary directory and set it as CWD.
383
384 The new CWD is created in the current directory and it's named *name*.
385 If *quiet* is False (default) and it's not possible to create or change
386 the CWD, an error is raised. If it's True, only a warning is raised
387 and the original CWD is used.
388 """
389 saved_dir = os.getcwd()
390 is_temporary = False
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000391 try:
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000392 os.mkdir(name)
393 os.chdir(name)
394 is_temporary = True
395 except OSError:
396 if not quiet:
397 raise
398 warnings.warn('tests may fail, unable to change the CWD to ' + name,
399 RuntimeWarning, stacklevel=3)
400 try:
401 yield os.getcwd()
402 finally:
403 os.chdir(saved_dir)
404 if is_temporary:
405 rmtree(name)
406
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000407
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000408def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000409 """Try to find a file on sys.path and the working directory. If it is not
410 found the argument passed to the function is returned (this does not
411 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000412 if os.path.isabs(file):
413 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000414 if subdir is not None:
415 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000416 path = sys.path
417 path = [os.path.dirname(here)] + path
418 for dn in path:
419 fn = os.path.join(dn, file)
420 if os.path.exists(fn): return fn
421 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000422
Tim Peters2f228e72001-05-13 00:19:31 +0000423def sortdict(dict):
424 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000425 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000426 reprpairs = ["%r: %r" % pair for pair in items]
427 withcommas = ", ".join(reprpairs)
428 return "{%s}" % withcommas
429
Benjamin Peterson7522c742009-01-19 21:00:09 +0000430def make_bad_fd():
431 """
432 Create an invalid file descriptor by opening and closing a file and return
433 its fd.
434 """
435 file = open(TESTFN, "wb")
436 try:
437 return file.fileno()
438 finally:
439 file.close()
440 unlink(TESTFN)
441
Thomas Wouters89f507f2006-12-13 04:49:30 +0000442def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000443 testcase.assertRaises(SyntaxError, compile, statement,
444 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000445
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000446def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000447 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000448
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000449 check = kw.pop('check', None)
450
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000451 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000452
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000453 fn = os.path.join(os.path.dirname(__file__), "data", filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000454
455 def check_valid_file(fn):
456 f = open(fn, *args, **kw)
457 if check is None:
458 return f
459 elif check(f):
460 f.seek(0)
461 return f
462 f.close()
463
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000464 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000465 f = check_valid_file(fn)
466 if f is not None:
467 return f
468 unlink(fn)
469
470 # Verify the requirement before downloading the file
471 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000472
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000473 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000474 f = urllib.request.urlopen(url, timeout=15)
475 try:
476 with open(fn, "wb") as out:
477 s = f.read()
478 while s:
479 out.write(s)
480 s = f.read()
481 finally:
482 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000483
484 f = check_valid_file(fn)
485 if f is not None:
486 return f
487 raise TestFailed('invalid resource "%s"' % fn)
488
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000489
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000490class WarningsRecorder(object):
491 """Convenience wrapper for the warnings list returned on
492 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000493 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000494 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000495 self._warnings = warnings_list
496 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000497
498 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000499 if len(self._warnings) > self._last:
500 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000501 elif attr in warnings.WarningMessage._WARNING_DETAILS:
502 return None
503 raise AttributeError("%r has no attribute %r" % (self, attr))
504
Florent Xiclunab14930c2010-03-13 15:26:44 +0000505 @property
506 def warnings(self):
507 return self._warnings[self._last:]
508
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000509 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000510 self._last = len(self._warnings)
511
512
513def _filterwarnings(filters, quiet=False):
514 """Catch the warnings, then check if all the expected
515 warnings have been raised and re-raise unexpected warnings.
516 If 'quiet' is True, only re-raise the unexpected warnings.
517 """
518 # Clear the warning registry of the calling module
519 # in order to re-raise the warnings.
520 frame = sys._getframe(2)
521 registry = frame.f_globals.get('__warningregistry__')
522 if registry:
523 registry.clear()
524 with warnings.catch_warnings(record=True) as w:
525 # Set filter "always" to record all warnings. Because
526 # test_warnings swap the module, we need to look up in
527 # the sys.modules dictionary.
528 sys.modules['warnings'].simplefilter("always")
529 yield WarningsRecorder(w)
530 # Filter the recorded warnings
531 reraise = [warning.message for warning in w]
532 missing = []
533 for msg, cat in filters:
534 seen = False
535 for exc in reraise[:]:
536 message = str(exc)
537 # Filter out the matching messages
538 if (re.match(msg, message, re.I) and
539 issubclass(exc.__class__, cat)):
540 seen = True
541 reraise.remove(exc)
542 if not seen and not quiet:
543 # This filter caught nothing
544 missing.append((msg, cat.__name__))
545 if reraise:
546 raise AssertionError("unhandled warning %r" % reraise[0])
547 if missing:
548 raise AssertionError("filter (%r, %s) did not catch any warning" %
549 missing[0])
550
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000551
552@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000553def check_warnings(*filters, **kwargs):
554 """Context manager to silence warnings.
555
556 Accept 2-tuples as positional arguments:
557 ("message regexp", WarningCategory)
558
559 Optional argument:
560 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506be2010-03-18 20:00:57 +0000561 (default True without argument,
562 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000563
564 Without argument, it defaults to:
Florent Xicluna53b506be2010-03-18 20:00:57 +0000565 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000566 """
Florent Xicluna53b506be2010-03-18 20:00:57 +0000567 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +0000568 if not filters:
569 filters = (("", Warning),)
Florent Xicluna53b506be2010-03-18 20:00:57 +0000570 # Preserve backward compatibility
571 if quiet is None:
572 quiet = True
573 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000574
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000575
576class CleanImport(object):
577 """Context manager to force import to return a new module reference.
578
579 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000580 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000581
582 Use like this:
583
584 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000585 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000586 """
587
588 def __init__(self, *module_names):
589 self.original_modules = sys.modules.copy()
590 for module_name in module_names:
591 if module_name in sys.modules:
592 module = sys.modules[module_name]
593 # It is possible that module_name is just an alias for
594 # another module (e.g. stub for modules renamed in 3.x).
595 # In that case, we also need delete the real module to clear
596 # the import cache.
597 if module.__name__ != module_name:
598 del sys.modules[module.__name__]
599 del sys.modules[module_name]
600
601 def __enter__(self):
602 return self
603
604 def __exit__(self, *ignore_exc):
605 sys.modules.update(self.original_modules)
606
607
Walter Dörwald155374d2009-05-01 19:58:58 +0000608class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000609
610 """Class to help protect the environment variable properly. Can be used as
611 a context manager."""
612
613 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000614 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000615 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000616
Walter Dörwald155374d2009-05-01 19:58:58 +0000617 def __getitem__(self, envvar):
618 return self._environ[envvar]
619
620 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000621 # Remember the initial value on the first access
622 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000623 self._changed[envvar] = self._environ.get(envvar)
624 self._environ[envvar] = value
625
626 def __delitem__(self, envvar):
627 # Remember the initial value on the first access
628 if envvar not in self._changed:
629 self._changed[envvar] = self._environ.get(envvar)
630 if envvar in self._environ:
631 del self._environ[envvar]
632
633 def keys(self):
634 return self._environ.keys()
635
636 def __iter__(self):
637 return iter(self._environ)
638
639 def __len__(self):
640 return len(self._environ)
641
642 def set(self, envvar, value):
643 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000644
645 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000646 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000647
648 def __enter__(self):
649 return self
650
651 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000652 for (k, v) in self._changed.items():
653 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000654 if k in self._environ:
655 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000656 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000657 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000658 os.environ = self._environ
659
660
661class DirsOnSysPath(object):
662 """Context manager to temporarily add directories to sys.path.
663
664 This makes a copy of sys.path, appends any directories given
665 as positional arguments, then reverts sys.path to the copied
666 settings when the context ends.
667
668 Note that *all* sys.path modifications in the body of the
669 context manager, including replacement of the object,
670 will be reverted at the end of the block.
671 """
672
673 def __init__(self, *paths):
674 self.original_value = sys.path[:]
675 self.original_object = sys.path
676 sys.path.extend(paths)
677
678 def __enter__(self):
679 return self
680
681 def __exit__(self, *ignore_exc):
682 sys.path = self.original_object
683 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000684
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000685
Guido van Rossumd8faa362007-04-27 19:54:29 +0000686class TransientResource(object):
687
688 """Raise ResourceDenied if an exception is raised while the context manager
689 is in effect that matches the specified exception and attributes."""
690
691 def __init__(self, exc, **kwargs):
692 self.exc = exc
693 self.attrs = kwargs
694
695 def __enter__(self):
696 return self
697
698 def __exit__(self, type_=None, value=None, traceback=None):
699 """If type_ is a subclass of self.exc and value has attributes matching
700 self.attrs, raise ResourceDenied. Otherwise let the exception
701 propagate (if any)."""
702 if type_ is not None and issubclass(self.exc, type_):
703 for attr, attr_value in self.attrs.items():
704 if not hasattr(value, attr):
705 break
706 if getattr(value, attr) != attr_value:
707 break
708 else:
709 raise ResourceDenied("an optional resource is not available")
710
711
Raymond Hettinger686057b2009-06-04 00:11:54 +0000712# Context managers that raise ResourceDenied when various issues
713# with the Internet connection manifest themselves as exceptions.
714time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
715socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
716ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000718
Thomas Woutersed03b412007-08-28 21:37:11 +0000719@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000720def captured_output(stream_name):
721 """Run the 'with' statement body using a StringIO object in place of a
722 specific attribute on the sys module.
723 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000724
725 with captured_stdout() as s:
Neal Norwitz752abd02008-05-13 04:55:24 +0000726 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000727 assert s.getvalue() == "hello"
728 """
729 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000730 orig_stdout = getattr(sys, stream_name)
731 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000732 try:
733 yield getattr(sys, stream_name)
734 finally:
735 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000736
737def captured_stdout():
738 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000739
Nick Coghlan6ead5522009-10-18 13:19:33 +0000740def captured_stdin():
741 return captured_output("stdin")
742
Benjamin Petersone549ead2009-03-28 21:42:05 +0000743def gc_collect():
744 """Force as many objects as possible to be collected.
745
746 In non-CPython implementations of Python, this is needed because timely
747 deallocation is not guaranteed by the garbage collector. (Even in CPython
748 this can be the case in case of reference cycles.) This means that __del__
749 methods may be called later than expected and weakrefs may remain alive for
750 longer than expected. This function tries its best to force all garbage
751 objects to disappear.
752 """
Benjamin Petersone549ead2009-03-28 21:42:05 +0000753 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +0000754 if is_jython:
755 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000756 gc.collect()
757 gc.collect()
758
Thomas Woutersed03b412007-08-28 21:37:11 +0000759
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000760#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761# Decorator for running a function in a different locale, correctly resetting
762# it afterwards.
763
764def run_with_locale(catstr, *locales):
765 def decorator(func):
766 def inner(*args, **kwds):
767 try:
768 import locale
769 category = getattr(locale, catstr)
770 orig_locale = locale.setlocale(category)
771 except AttributeError:
772 # if the test author gives us an invalid category string
773 raise
774 except:
775 # cannot retrieve original locale, so do nothing
776 locale = orig_locale = None
777 else:
778 for loc in locales:
779 try:
780 locale.setlocale(category, loc)
781 break
782 except:
783 pass
784
785 # now run the function, resetting the locale on exceptions
786 try:
787 return func(*args, **kwds)
788 finally:
789 if locale and orig_locale:
790 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000791 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000792 inner.__doc__ = func.__doc__
793 return inner
794 return decorator
795
796#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000797# Big-memory-test support. Separate from 'resources' because memory use
798# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000799
800# Some handy shorthands. Note that these are used for byte-limits as well
801# as size-limits, in the various bigmem tests
802_1M = 1024*1024
803_1G = 1024 * _1M
804_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000805_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +0000806
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000807MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000808
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000811 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +0000812 sizes = {
813 'k': 1024,
814 'm': _1M,
815 'g': _1G,
816 't': 1024*_1G,
817 }
818 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
819 re.IGNORECASE | re.VERBOSE)
820 if m is None:
821 raise ValueError('Invalid memory limit %r' % (limit,))
822 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000823 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000824 if memlimit > MAX_Py_ssize_t:
825 memlimit = MAX_Py_ssize_t
826 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000827 raise ValueError('Memory limit %r too low to be useful' % (limit,))
828 max_memuse = memlimit
829
830def bigmemtest(minsize, memuse, overhead=5*_1M):
831 """Decorator for bigmem tests.
832
833 'minsize' is the minimum useful size for the test (in arbitrary,
834 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
835 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
Christian Heimes33fe8092008-04-13 13:53:33 +0000836 independent of the testsize, and defaults to 5Mb.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000837
838 The decorator tries to guess a good value for 'size' and passes it to
839 the decorated test function. If minsize * memuse is more than the
840 allowed memory use (as defined by max_memuse), the test is skipped.
841 Otherwise, minsize is adjusted upward to use up to max_memuse.
842 """
843 def decorator(f):
844 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000845 # Retrieve values in case someone decided to adjust them
846 minsize = wrapper.minsize
847 memuse = wrapper.memuse
848 overhead = wrapper.overhead
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849 if not max_memuse:
850 # If max_memuse is 0 (the default),
851 # we still want to run the tests with size set to a few kb,
852 # to make sure they work. We still want to avoid using
853 # too much memory, though, but we do that noisily.
854 maxsize = 5147
Benjamin Peterson46d44402009-07-01 00:45:43 +0000855 self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000856 else:
857 maxsize = int((max_memuse - overhead) / memuse)
858 if maxsize < minsize:
859 # Really ought to print 'test skipped' or something
860 if verbose:
861 sys.stderr.write("Skipping %s because of memory "
862 "constraint\n" % (f.__name__,))
863 return
864 # Try to keep some breathing room in memory use
865 maxsize = max(maxsize - 50 * _1M, minsize)
866 return f(self, maxsize)
867 wrapper.minsize = minsize
868 wrapper.memuse = memuse
869 wrapper.overhead = overhead
870 return wrapper
871 return decorator
872
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000873def precisionbigmemtest(size, memuse, overhead=5*_1M):
874 def decorator(f):
875 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000876 size = wrapper.size
877 memuse = wrapper.memuse
878 overhead = wrapper.overhead
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000879 if not real_max_memuse:
880 maxsize = 5147
881 else:
882 maxsize = size
883
884 if real_max_memuse and real_max_memuse < maxsize * memuse:
885 if verbose:
886 sys.stderr.write("Skipping %s because of memory "
887 "constraint\n" % (f.__name__,))
888 return
889
890 return f(self, maxsize)
891 wrapper.size = size
892 wrapper.memuse = memuse
893 wrapper.overhead = overhead
894 return wrapper
895 return decorator
896
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000897def bigaddrspacetest(f):
898 """Decorator for tests that fill the address space."""
899 def wrapper(self):
900 if max_memuse < MAX_Py_ssize_t:
901 if verbose:
902 sys.stderr.write("Skipping %s because of memory "
903 "constraint\n" % (f.__name__,))
904 else:
905 return f(self)
906 return wrapper
907
Thomas Wouters477c8d52006-05-27 19:21:47 +0000908#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +0000909# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000910
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000911class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000912 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000913 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000914 test(result)
915 return result
916
Benjamin Petersone549ead2009-03-28 21:42:05 +0000917def _id(obj):
918 return obj
919
920def requires_resource(resource):
921 if resource_is_enabled(resource):
922 return _id
923 else:
924 return unittest.skip("resource {0!r} is not enabled".format(resource))
925
926def cpython_only(test):
927 """
928 Decorator for tests only applicable on CPython.
929 """
930 return impl_detail(cpython=True)(test)
931
932def impl_detail(msg=None, **guards):
933 if check_impl_detail(**guards):
934 return _id
935 if msg is None:
936 guardnames, default = _parse_guards(guards)
937 if default:
938 msg = "implementation detail not available on {0}"
939 else:
940 msg = "implementation detail specific to {0}"
941 guardnames = sorted(guardnames.keys())
942 msg = msg.format(' or '.join(guardnames))
943 return unittest.skip(msg)
944
945def _parse_guards(guards):
946 # Returns a tuple ({platform_name: run_me}, default_value)
947 if not guards:
948 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +0000949 is_true = list(guards.values())[0]
950 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +0000951 return (guards, not is_true)
952
953# Use the following check to guard CPython's implementation-specific tests --
954# or to run them only on the implementation(s) guarded by the arguments.
955def check_impl_detail(**guards):
956 """This function returns True or False depending on the host platform.
957 Examples:
958 if check_impl_detail(): # only on CPython (default)
959 if check_impl_detail(jython=True): # only on Jython
960 if check_impl_detail(cpython=False): # everywhere except on CPython
961 """
962 guards, default = _parse_guards(guards)
963 return guards.get(platform.python_implementation().lower(), default)
964
965
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000966
Guido van Rossumd8faa362007-04-27 19:54:29 +0000967def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +0000968 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000969 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +0000970 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000971 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000972 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000973
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000974 result = runner.run(suite)
975 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +0000976 if len(result.errors) == 1 and not result.failures:
977 err = result.errors[0][1]
978 elif len(result.failures) == 1 and not result.errors:
979 err = result.failures[0][1]
980 else:
R. David Murray723357e2009-10-19 18:06:17 +0000981 err = "multiple errors occurred"
982 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +0000983 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +0000984
Barry Warsawc10d6902001-09-20 06:30:41 +0000985
Walter Dörwald21d3a322003-05-01 17:45:56 +0000986def run_unittest(*classes):
987 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000988 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000989 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000990 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000991 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000992 if cls in sys.modules:
993 suite.addTest(unittest.findTestCases(sys.modules[cls]))
994 else:
995 raise ValueError("str arguments must be keys in sys.modules")
996 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +0000997 suite.addTest(cls)
998 else:
999 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001000 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001001
Barry Warsawc10d6902001-09-20 06:30:41 +00001002
Tim Petersa0a62222001-09-09 06:12:01 +00001003#=======================================================================
1004# doctest driver.
1005
1006def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +00001007 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001008
1009 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001010 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001011 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001012 """
1013
1014 import doctest
1015
1016 if verbosity is None:
1017 verbosity = verbose
1018 else:
1019 verbosity = None
1020
Tim Peters342ca752001-09-25 19:13:20 +00001021 # Direct doctest output (normally just errors) to real stdout; doctest
1022 # output shouldn't be compared by regrtest.
1023 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +00001024 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +00001025 try:
1026 f, t = doctest.testmod(module, verbose=verbosity)
1027 if f:
1028 raise TestFailed("%d of %d doctests failed" % (f, t))
1029 finally:
1030 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001031 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001032 print('doctest (%s) ... %d tests with zero failures' %
1033 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001034 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001035
Antoine Pitrou060cee22009-11-13 16:29:04 +00001036
1037#=======================================================================
1038# Support for saving and restoring the imported modules.
1039
1040def modules_setup():
1041 return sys.modules.copy(),
1042
1043def modules_cleanup(oldmodules):
1044 # Encoders/decoders are registered permanently within the internal
1045 # codec cache. If we destroy the corresponding modules their
1046 # globals will be set to None which will trip up the cached functions.
1047 encodings = [(k, v) for k, v in sys.modules.items()
1048 if k.startswith('encodings.')]
1049 sys.modules.clear()
1050 sys.modules.update(encodings)
1051 sys.modules.update(oldmodules)
1052
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001053#=======================================================================
1054# Threading support to prevent reporting refleaks when running regrtest.py -R
1055
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001056# NOTE: we use thread._count() rather than threading.enumerate() (or the
1057# moral equivalent thereof) because a threading.Thread object is still alive
1058# until its __bootstrap() method has returned, even after it has been
1059# unregistered from the threading module.
1060# thread._count(), on the other hand, only gets decremented *after* the
1061# __bootstrap() method has returned, which gives us reliable reference counts
1062# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001063
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001064def threading_setup():
1065 import _thread
1066 return _thread._count(),
1067
1068def threading_cleanup(nb_threads):
1069 import _thread
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001070
1071 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001072 for count in range(_MAX_COUNT):
1073 n = _thread._count()
1074 if n == nb_threads:
1075 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001076 time.sleep(0.1)
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001077 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001078
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001079def reap_threads(func):
1080 @functools.wraps(func)
1081 def decorator(*args):
1082 key = threading_setup()
1083 try:
1084 return func(*args)
1085 finally:
1086 threading_cleanup(*key)
1087 return decorator
1088
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001089def reap_children():
1090 """Use this function at the end of test_main() whenever sub-processes
1091 are started. This will help ensure that no extra children (zombies)
1092 stick around to hog resources and create problems when looking
1093 for refleaks.
1094 """
1095
1096 # Reap all our dead child processes so we don't leave zombies around.
1097 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001098 if hasattr(os, 'waitpid'):
1099 any_process = -1
1100 while True:
1101 try:
1102 # This will raise an exception on Windows. That's ok.
1103 pid, status = os.waitpid(any_process, os.WNOHANG)
1104 if pid == 0:
1105 break
1106 except:
1107 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001108
1109@contextlib.contextmanager
1110def swap_attr(obj, attr, new_val):
1111 """Temporary swap out an attribute with a new object.
1112
1113 Usage:
1114 with swap_attr(obj, "attr", 5):
1115 ...
1116
1117 This will set obj.attr to 5 for the duration of the with: block,
1118 restoring the old value at the end of the block. If `attr` doesn't
1119 exist on `obj`, it will be created and then deleted at the end of the
1120 block.
1121 """
1122 if hasattr(obj, attr):
1123 real_val = getattr(obj, attr)
1124 setattr(obj, attr, new_val)
1125 try:
1126 yield
1127 finally:
1128 setattr(obj, attr, real_val)
1129 else:
1130 setattr(obj, attr, new_val)
1131 try:
1132 yield
1133 finally:
1134 delattr(obj, attr)
1135
1136@contextlib.contextmanager
1137def swap_item(obj, item, new_val):
1138 """Temporary swap out an item with a new object.
1139
1140 Usage:
1141 with swap_item(obj, "item", 5):
1142 ...
1143
1144 This will set obj["item"] to 5 for the duration of the with: block,
1145 restoring the old value at the end of the block. If `item` doesn't
1146 exist on `obj`, it will be created and then deleted at the end of the
1147 block.
1148 """
1149 if item in obj:
1150 real_val = obj[item]
1151 obj[item] = new_val
1152 try:
1153 yield
1154 finally:
1155 obj[item] = real_val
1156 else:
1157 obj[item] = new_val
1158 try:
1159 yield
1160 finally:
1161 del obj[item]