blob: a05f420710c55aba182f58783cc392265f089343 [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
Fred Drakecd1b1dd2001-03-21 18:26:33 +000020
Benjamin Petersone549ead2009-03-28 21:42:05 +000021__all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
Benjamin Peterson744c2cd2008-05-26 16:26:37 +000022 "verbose", "use_resources", "max_memuse", "record_original_stdout",
23 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
24 "is_resource_enabled", "requires", "find_unused_port", "bind_port",
Ezio Melotti184bdfb2010-02-18 09:37:05 +000025 "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
26 "findfile", "sortdict", "check_syntax_error", "open_urlresource",
Benjamin Petersonfcf5d632008-10-16 23:24:44 +000027 "check_warnings", "CleanImport", "EnvironmentVarGuard",
Benjamin Peterson79e48032008-05-26 17:44:33 +000028 "TransientResource", "captured_output", "captured_stdout",
Raymond Hettingerd76b9f12009-06-04 00:35:30 +000029 "time_out", "socket_peer_reset", "ioerror_peer_reset",
30 "run_with_locale",
Benjamin Peterson79e48032008-05-26 17:44:33 +000031 "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
32 "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
R. David Murraya21e4ca2009-03-31 23:16:50 +000033 "reap_children", "cpython_only", "check_impl_detail", "get_attribute"]
Benjamin Peterson744c2cd2008-05-26 16:26:37 +000034
Fred Drake1790dd42000-07-24 06:55:00 +000035class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000036 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000037
38class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000039 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000040
Benjamin Petersone549ead2009-03-28 21:42:05 +000041class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +000042 """Test skipped because it requested a disallowed resource.
43
44 This is raised when a test calls requires() for a resource that
45 has not be enabled. It is used to distinguish between expected
46 and unexpected skips.
47 """
48
Nick Coghlanfce769e2009-04-11 14:30:59 +000049@contextlib.contextmanager
50def _ignore_deprecated_imports(ignore=True):
51 """Context manager to suppress package and module deprecation
52 warnings when importing them.
53
54 If ignore is False, this context manager has no effect."""
55 if ignore:
56 with warnings.catch_warnings():
57 warnings.filterwarnings("ignore", ".+ (module|package)",
58 DeprecationWarning)
59 yield
60 else:
61 yield
62
63
Benjamin Peterson699adb92008-05-08 22:27:58 +000064def import_module(name, deprecated=False):
R. David Murraya21e4ca2009-03-31 23:16:50 +000065 """Import and return the module to be tested, raising SkipTest if
66 it is not available.
67
68 If deprecated is True, any module or package deprecation messages
69 will be suppressed."""
Nick Coghlanfce769e2009-04-11 14:30:59 +000070 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +000071 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +000072 return importlib.import_module(name)
R. David Murraya21e4ca2009-03-31 23:16:50 +000073 except ImportError as msg:
74 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +000075
76
Nick Coghlan47384702009-04-22 16:13:36 +000077def _save_and_remove_module(name, orig_modules):
78 """Helper function to save and remove a module from sys.modules
79
80 Return value is True if the module was in sys.modules and
81 False otherwise."""
82 saved = True
83 try:
84 orig_modules[name] = sys.modules[name]
85 except KeyError:
86 saved = False
87 else:
88 del sys.modules[name]
89 return saved
90
91
92def _save_and_block_module(name, orig_modules):
93 """Helper function to save and block a module in sys.modules
94
95 Return value is True if the module was in sys.modules and
96 False otherwise."""
97 saved = True
98 try:
99 orig_modules[name] = sys.modules[name]
100 except KeyError:
101 saved = False
102 sys.modules[name] = 0
103 return saved
104
105
106def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Nick Coghlanfce769e2009-04-11 14:30:59 +0000107 """Imports and returns a module, deliberately bypassing the sys.modules cache
108 and importing a fresh copy of the module. Once the import is complete,
109 the sys.modules cache is restored to its original state.
110
Nick Coghlan47384702009-04-22 16:13:36 +0000111 Modules named in fresh are also imported anew if needed by the import.
112
113 Importing of modules named in blocked is prevented while the fresh import
Nick Coghlanfce769e2009-04-11 14:30:59 +0000114 takes place.
115
116 If deprecated is True, any module or package deprecation messages
117 will be suppressed."""
118 # NOTE: test_heapq and test_warnings include extra sanity checks to make
119 # sure that this utility function is working as expected
120 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000121 # Keep track of modules saved for later restoration as well
122 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000123 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000124 names_to_remove = []
125 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000126 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000127 for fresh_name in fresh:
128 _save_and_remove_module(fresh_name, orig_modules)
129 for blocked_name in blocked:
130 if not _save_and_block_module(blocked_name, orig_modules):
131 names_to_remove.append(blocked_name)
132 fresh_module = importlib.import_module(name)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000133 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000134 for orig_name, module in orig_modules.items():
135 sys.modules[orig_name] = module
136 for name_to_remove in names_to_remove:
137 del sys.modules[name_to_remove]
138 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000139
Benjamin Peterson699adb92008-05-08 22:27:58 +0000140
R. David Murraya21e4ca2009-03-31 23:16:50 +0000141def get_attribute(obj, name):
142 """Get an attribute, raising SkipTest if AttributeError is raised."""
143 try:
144 attribute = getattr(obj, name)
145 except AttributeError:
146 raise unittest.SkipTest("module %s has no attribute %s" % (
147 obj.__name__, name))
148 else:
149 return attribute
150
Barry Warsawc0fb6052001-08-20 22:29:23 +0000151verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000152use_resources = None # Flag set to [] by regrtest.py
153max_memuse = 0 # Disable bigmem tests (they will still be run with
154 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000155real_max_memuse = 0
Guido van Rossum531661c1996-12-20 02:58:22 +0000156
Tim Peters8dee8092001-09-25 20:05:11 +0000157# _original_stdout is meant to hold stdout at the time regrtest began.
158# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
159# The point is to have some flavor of stdout the user can actually see.
160_original_stdout = None
161def record_original_stdout(stdout):
162 global _original_stdout
163 _original_stdout = stdout
164
165def get_original_stdout():
166 return _original_stdout or sys.stdout
167
Guido van Rossum3bead091992-01-27 17:00:37 +0000168def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000169 try:
170 del sys.modules[name]
171 except KeyError:
172 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000173
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000174def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000175 try:
176 os.unlink(filename)
177 except OSError:
178 pass
179
Christian Heimes23daade02008-02-25 12:39:23 +0000180def rmtree(path):
181 try:
182 shutil.rmtree(path)
183 except OSError as e:
184 # Unix returns ENOENT, Windows returns ESRCH.
185 if e.errno not in (errno.ENOENT, errno.ESRCH):
186 raise
187
Guido van Rossum3bead091992-01-27 17:00:37 +0000188def forget(modname):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000189 '''"Forget" a module was ever imported by removing it from sys.modules and
190 deleting any .pyc and .pyo files.'''
Fred Drake004d5e62000-10-23 17:22:08 +0000191 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000192 for dirname in sys.path:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000193 unlink(os.path.join(dirname, modname + '.pyc'))
Brett Cannonf1cfb622003-05-04 21:15:27 +0000194 # Deleting the .pyo file cannot be within the 'try' for the .pyc since
195 # the chance exists that there is no .pyc (and thus the 'try' statement
196 # is exited) but there is a .pyo file.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000197 unlink(os.path.join(dirname, modname + '.pyo'))
Guido van Rossum3bead091992-01-27 17:00:37 +0000198
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000199def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000200 """Test whether a resource is enabled. Known resources are set by
201 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000202 return use_resources is not None and resource in use_resources
203
Barry Warsawc0fb6052001-08-20 22:29:23 +0000204def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000205 """Raise ResourceDenied if the specified resource is not available.
206
207 If the caller's module is __main__ then automatically return True. The
208 possibility of False being returned occurs when regrtest.py is executing."""
Skip Montanarod839ecd2003-04-24 19:06:57 +0000209 # see if the caller's module is __main__ - if so, treat as if
210 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000211 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000212 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000213 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000214 if msg is None:
215 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000216 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000217
Christian Heimes5e696852008-04-09 08:37:03 +0000218HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000219
Christian Heimes5e696852008-04-09 08:37:03 +0000220def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
221 """Returns an unused port that should be suitable for binding. This is
222 achieved by creating a temporary socket with the same family and type as
223 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
224 the specified host address (defaults to 0.0.0.0) with the port set to 0,
225 eliciting an unused ephemeral port from the OS. The temporary socket is
226 then closed and deleted, and the ephemeral port is returned.
227
228 Either this method or bind_port() should be used for any tests where a
229 server socket needs to be bound to a particular port for the duration of
230 the test. Which one to use depends on whether the calling code is creating
231 a python socket, or if an unused port needs to be provided in a constructor
232 or passed to an external program (i.e. the -accept argument to openssl's
233 s_server mode). Always prefer bind_port() over find_unused_port() where
234 possible. Hard coded ports should *NEVER* be used. As soon as a server
235 socket is bound to a hard coded port, the ability to run multiple instances
236 of the test simultaneously on the same host is compromised, which makes the
237 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
238 may simply manifest as a failed test, which can be recovered from without
239 intervention in most cases, but on Windows, the entire python process can
240 completely and utterly wedge, requiring someone to log in to the buildbot
241 and manually kill the affected process.
242
243 (This is easy to reproduce on Windows, unfortunately, and can be traced to
244 the SO_REUSEADDR socket option having different semantics on Windows versus
245 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
246 listen and then accept connections on identical host/ports. An EADDRINUSE
247 socket.error will be raised at some point (depending on the platform and
248 the order bind and listen were called on each socket).
249
250 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
251 will ever be raised when attempting to bind two identical host/ports. When
252 accept() is called on each socket, the second caller's process will steal
253 the port from the first caller, leaving them both in an awkwardly wedged
254 state where they'll no longer respond to any signals or graceful kills, and
255 must be forcibly killed via OpenProcess()/TerminateProcess().
256
257 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
258 instead of SO_REUSEADDR, which effectively affords the same semantics as
259 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
260 Source world compared to Windows ones, this is a common mistake. A quick
261 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
262 openssl.exe is called with the 's_server' option, for example. See
263 http://bugs.python.org/issue2550 for more info. The following site also
264 has a very thorough description about the implications of both REUSEADDR
265 and EXCLUSIVEADDRUSE on Windows:
266 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
267
268 XXX: although this approach is a vast improvement on previous attempts to
269 elicit unused ports, it rests heavily on the assumption that the ephemeral
270 port returned to us by the OS won't immediately be dished back out to some
271 other process when we close and delete our temporary socket but before our
272 calling code has a chance to bind the returned port. We can deal with this
273 issue if/when we come across it.
274 """
275
276 tempsock = socket.socket(family, socktype)
277 port = bind_port(tempsock)
278 tempsock.close()
279 del tempsock
280 return port
281
282def bind_port(sock, host=HOST):
283 """Bind the socket to a free port and return the port number. Relies on
284 ephemeral ports in order to ensure we are using an unbound port. This is
285 important as many tests may be running simultaneously, especially in a
286 buildbot environment. This method raises an exception if the sock.family
287 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
288 or SO_REUSEPORT set on it. Tests should *never* set these socket options
289 for TCP/IP sockets. The only case for setting these options is testing
290 multicasting via multiple UDP sockets.
291
292 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
293 on Windows), it will be set on the socket. This will prevent anyone else
294 from bind()'ing to our host/port for the duration of the test.
295 """
296
297 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
298 if hasattr(socket, 'SO_REUSEADDR'):
299 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
300 raise TestFailed("tests should never set the SO_REUSEADDR " \
301 "socket option on TCP/IP sockets!")
302 if hasattr(socket, 'SO_REUSEPORT'):
303 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
304 raise TestFailed("tests should never set the SO_REUSEPORT " \
305 "socket option on TCP/IP sockets!")
306 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
307 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
308
309 sock.bind((host, 0))
310 port = sock.getsockname()[1]
311 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000312
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000313FUZZ = 1e-6
314
315def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000316 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000317 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000318 fuzz = (abs(x) + abs(y)) * FUZZ
319 if abs(x-y) <= fuzz:
320 return 0
321 except:
322 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000323 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000324 for i in range(min(len(x), len(y))):
325 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000326 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000327 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000328 return (len(x) > len(y)) - (len(x) < len(y))
329 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000330
Finn Bock57bc5fa2002-11-01 18:02:03 +0000331is_jython = sys.platform.startswith('java')
332
Barry Warsaw559f6682001-03-23 18:04:02 +0000333# Filename used for testing
334if os.name == 'java':
335 # Jython disallows @ in module names
336 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000337else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000338 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000339
Antoine Pitrou88909542009-06-29 13:54:42 +0000340# Disambiguate TESTFN for parallel testing, while letting it remain a valid
341# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000342TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000343
344# Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
345# TESTFN_UNICODE is a filename that can be encoded using the
346# file system encoding, but *not* with the default (ascii) encoding
347TESTFN_UNICODE = TESTFN + "-\xe0\xf2"
348TESTFN_ENCODING = sys.getfilesystemencoding()
349# TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
350# able to be encoded by *either* the default or filesystem encoding.
351# This test really only makes sense on Windows NT platforms
352# which have special Unicode support in posixmodule.
353if (not hasattr(sys, "getwindowsversion") or
354 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
355 TESTFN_UNICODE_UNENCODEABLE = None
356else:
357 # Japanese characters (I think - from bug 846133)
358 TESTFN_UNICODE_UNENCODEABLE = TESTFN + "-\u5171\u6709\u3055\u308c\u308b"
359 try:
360 # XXX - Note - should be using TESTFN_ENCODING here - but for
361 # Windows, "mbcs" currently always operates as if in
362 # errors=ignore' mode - hence we get '?' characters rather than
363 # the exception. 'Latin1' operates as we expect - ie, fails.
364 # See [ 850997 ] mbcs encoding ignores errors
365 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
366 except UnicodeEncodeError:
367 pass
Walter Dörwald9b775532007-06-08 14:30:53 +0000368 else:
Antoine Pitrou88909542009-06-29 13:54:42 +0000369 print('WARNING: The filename %r CAN be encoded by the filesystem. '
370 'Unicode filename tests may not be effective'
371 % TESTFN_UNICODE_UNENCODEABLE)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000372
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000373# Save the initial cwd
374SAVEDCWD = os.getcwd()
375
376@contextlib.contextmanager
377def temp_cwd(name='tempcwd', quiet=False):
378 """
379 Context manager that creates a temporary directory and set it as CWD.
380
381 The new CWD is created in the current directory and it's named *name*.
382 If *quiet* is False (default) and it's not possible to create or change
383 the CWD, an error is raised. If it's True, only a warning is raised
384 and the original CWD is used.
385 """
386 saved_dir = os.getcwd()
387 is_temporary = False
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000388 try:
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000389 os.mkdir(name)
390 os.chdir(name)
391 is_temporary = True
392 except OSError:
393 if not quiet:
394 raise
395 warnings.warn('tests may fail, unable to change the CWD to ' + name,
396 RuntimeWarning, stacklevel=3)
397 try:
398 yield os.getcwd()
399 finally:
400 os.chdir(saved_dir)
401 if is_temporary:
402 rmtree(name)
403
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000404
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000405def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000406 """Try to find a file on sys.path and the working directory. If it is not
407 found the argument passed to the function is returned (this does not
408 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000409 if os.path.isabs(file):
410 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000411 if subdir is not None:
412 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000413 path = sys.path
414 path = [os.path.dirname(here)] + path
415 for dn in path:
416 fn = os.path.join(dn, file)
417 if os.path.exists(fn): return fn
418 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000419
Tim Peters2f228e72001-05-13 00:19:31 +0000420def sortdict(dict):
421 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000422 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000423 reprpairs = ["%r: %r" % pair for pair in items]
424 withcommas = ", ".join(reprpairs)
425 return "{%s}" % withcommas
426
Benjamin Peterson7522c742009-01-19 21:00:09 +0000427def make_bad_fd():
428 """
429 Create an invalid file descriptor by opening and closing a file and return
430 its fd.
431 """
432 file = open(TESTFN, "wb")
433 try:
434 return file.fileno()
435 finally:
436 file.close()
437 unlink(TESTFN)
438
Thomas Wouters89f507f2006-12-13 04:49:30 +0000439def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000440 testcase.assertRaises(SyntaxError, compile, statement,
441 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000442
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000443def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000444 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000445
Guido van Rossum360e4b82007-05-14 22:51:27 +0000446 requires('urlfetch')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000447 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000448
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000449 fn = os.path.join(os.path.dirname(__file__), "data", filename)
450 if os.path.exists(fn):
Alexandre Vassalottidf4ff082009-07-22 00:19:57 +0000451 return open(fn, *args, **kw)
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000452
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000453 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000454 f = urllib.request.urlopen(url, timeout=15)
455 try:
456 with open(fn, "wb") as out:
457 s = f.read()
458 while s:
459 out.write(s)
460 s = f.read()
461 finally:
462 f.close()
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000463 return open(fn, *args, **kw)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000464
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000465class WarningsRecorder(object):
466 """Convenience wrapper for the warnings list returned on
467 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000468 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000469 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000470 self._warnings = warnings_list
471 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000472
473 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000474 if len(self._warnings) > self._last:
475 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000476 elif attr in warnings.WarningMessage._WARNING_DETAILS:
477 return None
478 raise AttributeError("%r has no attribute %r" % (self, attr))
479
Florent Xiclunab14930c2010-03-13 15:26:44 +0000480 @property
481 def warnings(self):
482 return self._warnings[self._last:]
483
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000484 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000485 self._last = len(self._warnings)
486
487
488def _filterwarnings(filters, quiet=False):
489 """Catch the warnings, then check if all the expected
490 warnings have been raised and re-raise unexpected warnings.
491 If 'quiet' is True, only re-raise the unexpected warnings.
492 """
493 # Clear the warning registry of the calling module
494 # in order to re-raise the warnings.
495 frame = sys._getframe(2)
496 registry = frame.f_globals.get('__warningregistry__')
497 if registry:
498 registry.clear()
499 with warnings.catch_warnings(record=True) as w:
500 # Set filter "always" to record all warnings. Because
501 # test_warnings swap the module, we need to look up in
502 # the sys.modules dictionary.
503 sys.modules['warnings'].simplefilter("always")
504 yield WarningsRecorder(w)
505 # Filter the recorded warnings
506 reraise = [warning.message for warning in w]
507 missing = []
508 for msg, cat in filters:
509 seen = False
510 for exc in reraise[:]:
511 message = str(exc)
512 # Filter out the matching messages
513 if (re.match(msg, message, re.I) and
514 issubclass(exc.__class__, cat)):
515 seen = True
516 reraise.remove(exc)
517 if not seen and not quiet:
518 # This filter caught nothing
519 missing.append((msg, cat.__name__))
520 if reraise:
521 raise AssertionError("unhandled warning %r" % reraise[0])
522 if missing:
523 raise AssertionError("filter (%r, %s) did not catch any warning" %
524 missing[0])
525
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000526
527@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000528def check_warnings(*filters, **kwargs):
529 """Context manager to silence warnings.
530
531 Accept 2-tuples as positional arguments:
532 ("message regexp", WarningCategory)
533
534 Optional argument:
535 - if 'quiet' is True, it does not fail if a filter catches nothing
536 (default False)
537
538 Without argument, it defaults to:
539 check_warnings(("", Warning), quiet=False)
540 """
541 if not filters:
542 filters = (("", Warning),)
543 return _filterwarnings(filters, kwargs.get('quiet'))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000545
546class CleanImport(object):
547 """Context manager to force import to return a new module reference.
548
549 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000550 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000551
552 Use like this:
553
554 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000555 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000556 """
557
558 def __init__(self, *module_names):
559 self.original_modules = sys.modules.copy()
560 for module_name in module_names:
561 if module_name in sys.modules:
562 module = sys.modules[module_name]
563 # It is possible that module_name is just an alias for
564 # another module (e.g. stub for modules renamed in 3.x).
565 # In that case, we also need delete the real module to clear
566 # the import cache.
567 if module.__name__ != module_name:
568 del sys.modules[module.__name__]
569 del sys.modules[module_name]
570
571 def __enter__(self):
572 return self
573
574 def __exit__(self, *ignore_exc):
575 sys.modules.update(self.original_modules)
576
577
Walter Dörwald155374d2009-05-01 19:58:58 +0000578class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000579
580 """Class to help protect the environment variable properly. Can be used as
581 a context manager."""
582
583 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000584 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000585 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000586
Walter Dörwald155374d2009-05-01 19:58:58 +0000587 def __getitem__(self, envvar):
588 return self._environ[envvar]
589
590 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000591 # Remember the initial value on the first access
592 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000593 self._changed[envvar] = self._environ.get(envvar)
594 self._environ[envvar] = value
595
596 def __delitem__(self, envvar):
597 # Remember the initial value on the first access
598 if envvar not in self._changed:
599 self._changed[envvar] = self._environ.get(envvar)
600 if envvar in self._environ:
601 del self._environ[envvar]
602
603 def keys(self):
604 return self._environ.keys()
605
606 def __iter__(self):
607 return iter(self._environ)
608
609 def __len__(self):
610 return len(self._environ)
611
612 def set(self, envvar, value):
613 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000614
615 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000616 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000617
618 def __enter__(self):
619 return self
620
621 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000622 for (k, v) in self._changed.items():
623 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000624 if k in self._environ:
625 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000626 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000627 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000628 os.environ = self._environ
629
630
631class DirsOnSysPath(object):
632 """Context manager to temporarily add directories to sys.path.
633
634 This makes a copy of sys.path, appends any directories given
635 as positional arguments, then reverts sys.path to the copied
636 settings when the context ends.
637
638 Note that *all* sys.path modifications in the body of the
639 context manager, including replacement of the object,
640 will be reverted at the end of the block.
641 """
642
643 def __init__(self, *paths):
644 self.original_value = sys.path[:]
645 self.original_object = sys.path
646 sys.path.extend(paths)
647
648 def __enter__(self):
649 return self
650
651 def __exit__(self, *ignore_exc):
652 sys.path = self.original_object
653 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000654
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000655
Guido van Rossumd8faa362007-04-27 19:54:29 +0000656class TransientResource(object):
657
658 """Raise ResourceDenied if an exception is raised while the context manager
659 is in effect that matches the specified exception and attributes."""
660
661 def __init__(self, exc, **kwargs):
662 self.exc = exc
663 self.attrs = kwargs
664
665 def __enter__(self):
666 return self
667
668 def __exit__(self, type_=None, value=None, traceback=None):
669 """If type_ is a subclass of self.exc and value has attributes matching
670 self.attrs, raise ResourceDenied. Otherwise let the exception
671 propagate (if any)."""
672 if type_ is not None and issubclass(self.exc, type_):
673 for attr, attr_value in self.attrs.items():
674 if not hasattr(value, attr):
675 break
676 if getattr(value, attr) != attr_value:
677 break
678 else:
679 raise ResourceDenied("an optional resource is not available")
680
681
Raymond Hettinger686057b2009-06-04 00:11:54 +0000682# Context managers that raise ResourceDenied when various issues
683# with the Internet connection manifest themselves as exceptions.
684time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
685socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
686ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000687
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000688
Thomas Woutersed03b412007-08-28 21:37:11 +0000689@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000690def captured_output(stream_name):
691 """Run the 'with' statement body using a StringIO object in place of a
692 specific attribute on the sys module.
693 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000694
695 with captured_stdout() as s:
Neal Norwitz752abd02008-05-13 04:55:24 +0000696 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000697 assert s.getvalue() == "hello"
698 """
699 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000700 orig_stdout = getattr(sys, stream_name)
701 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000702 try:
703 yield getattr(sys, stream_name)
704 finally:
705 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000706
707def captured_stdout():
708 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000709
Nick Coghlan6ead5522009-10-18 13:19:33 +0000710def captured_stdin():
711 return captured_output("stdin")
712
Benjamin Petersone549ead2009-03-28 21:42:05 +0000713def gc_collect():
714 """Force as many objects as possible to be collected.
715
716 In non-CPython implementations of Python, this is needed because timely
717 deallocation is not guaranteed by the garbage collector. (Even in CPython
718 this can be the case in case of reference cycles.) This means that __del__
719 methods may be called later than expected and weakrefs may remain alive for
720 longer than expected. This function tries its best to force all garbage
721 objects to disappear.
722 """
Benjamin Petersone549ead2009-03-28 21:42:05 +0000723 gc.collect()
724 gc.collect()
725 gc.collect()
726
Thomas Woutersed03b412007-08-28 21:37:11 +0000727
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000728#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000729# Decorator for running a function in a different locale, correctly resetting
730# it afterwards.
731
732def run_with_locale(catstr, *locales):
733 def decorator(func):
734 def inner(*args, **kwds):
735 try:
736 import locale
737 category = getattr(locale, catstr)
738 orig_locale = locale.setlocale(category)
739 except AttributeError:
740 # if the test author gives us an invalid category string
741 raise
742 except:
743 # cannot retrieve original locale, so do nothing
744 locale = orig_locale = None
745 else:
746 for loc in locales:
747 try:
748 locale.setlocale(category, loc)
749 break
750 except:
751 pass
752
753 # now run the function, resetting the locale on exceptions
754 try:
755 return func(*args, **kwds)
756 finally:
757 if locale and orig_locale:
758 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000759 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000760 inner.__doc__ = func.__doc__
761 return inner
762 return decorator
763
764#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000765# Big-memory-test support. Separate from 'resources' because memory use
766# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000767
768# Some handy shorthands. Note that these are used for byte-limits as well
769# as size-limits, in the various bigmem tests
770_1M = 1024*1024
771_1G = 1024 * _1M
772_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000773_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +0000774
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000775MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000776
Thomas Wouters477c8d52006-05-27 19:21:47 +0000777def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000778 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000779 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +0000780 sizes = {
781 'k': 1024,
782 'm': _1M,
783 'g': _1G,
784 't': 1024*_1G,
785 }
786 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
787 re.IGNORECASE | re.VERBOSE)
788 if m is None:
789 raise ValueError('Invalid memory limit %r' % (limit,))
790 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000791 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000792 if memlimit > MAX_Py_ssize_t:
793 memlimit = MAX_Py_ssize_t
794 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000795 raise ValueError('Memory limit %r too low to be useful' % (limit,))
796 max_memuse = memlimit
797
798def bigmemtest(minsize, memuse, overhead=5*_1M):
799 """Decorator for bigmem tests.
800
801 'minsize' is the minimum useful size for the test (in arbitrary,
802 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
803 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
Christian Heimes33fe8092008-04-13 13:53:33 +0000804 independent of the testsize, and defaults to 5Mb.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805
806 The decorator tries to guess a good value for 'size' and passes it to
807 the decorated test function. If minsize * memuse is more than the
808 allowed memory use (as defined by max_memuse), the test is skipped.
809 Otherwise, minsize is adjusted upward to use up to max_memuse.
810 """
811 def decorator(f):
812 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000813 # Retrieve values in case someone decided to adjust them
814 minsize = wrapper.minsize
815 memuse = wrapper.memuse
816 overhead = wrapper.overhead
Thomas Wouters477c8d52006-05-27 19:21:47 +0000817 if not max_memuse:
818 # If max_memuse is 0 (the default),
819 # we still want to run the tests with size set to a few kb,
820 # to make sure they work. We still want to avoid using
821 # too much memory, though, but we do that noisily.
822 maxsize = 5147
Benjamin Peterson46d44402009-07-01 00:45:43 +0000823 self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824 else:
825 maxsize = int((max_memuse - overhead) / memuse)
826 if maxsize < minsize:
827 # Really ought to print 'test skipped' or something
828 if verbose:
829 sys.stderr.write("Skipping %s because of memory "
830 "constraint\n" % (f.__name__,))
831 return
832 # Try to keep some breathing room in memory use
833 maxsize = max(maxsize - 50 * _1M, minsize)
834 return f(self, maxsize)
835 wrapper.minsize = minsize
836 wrapper.memuse = memuse
837 wrapper.overhead = overhead
838 return wrapper
839 return decorator
840
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000841def precisionbigmemtest(size, memuse, overhead=5*_1M):
842 def decorator(f):
843 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000844 size = wrapper.size
845 memuse = wrapper.memuse
846 overhead = wrapper.overhead
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000847 if not real_max_memuse:
848 maxsize = 5147
849 else:
850 maxsize = size
851
852 if real_max_memuse and real_max_memuse < maxsize * memuse:
853 if verbose:
854 sys.stderr.write("Skipping %s because of memory "
855 "constraint\n" % (f.__name__,))
856 return
857
858 return f(self, maxsize)
859 wrapper.size = size
860 wrapper.memuse = memuse
861 wrapper.overhead = overhead
862 return wrapper
863 return decorator
864
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000865def bigaddrspacetest(f):
866 """Decorator for tests that fill the address space."""
867 def wrapper(self):
868 if max_memuse < MAX_Py_ssize_t:
869 if verbose:
870 sys.stderr.write("Skipping %s because of memory "
871 "constraint\n" % (f.__name__,))
872 else:
873 return f(self)
874 return wrapper
875
Thomas Wouters477c8d52006-05-27 19:21:47 +0000876#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +0000877# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000878
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000879class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000880 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000881 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000882 test(result)
883 return result
884
Benjamin Petersone549ead2009-03-28 21:42:05 +0000885def _id(obj):
886 return obj
887
888def requires_resource(resource):
889 if resource_is_enabled(resource):
890 return _id
891 else:
892 return unittest.skip("resource {0!r} is not enabled".format(resource))
893
894def cpython_only(test):
895 """
896 Decorator for tests only applicable on CPython.
897 """
898 return impl_detail(cpython=True)(test)
899
900def impl_detail(msg=None, **guards):
901 if check_impl_detail(**guards):
902 return _id
903 if msg is None:
904 guardnames, default = _parse_guards(guards)
905 if default:
906 msg = "implementation detail not available on {0}"
907 else:
908 msg = "implementation detail specific to {0}"
909 guardnames = sorted(guardnames.keys())
910 msg = msg.format(' or '.join(guardnames))
911 return unittest.skip(msg)
912
913def _parse_guards(guards):
914 # Returns a tuple ({platform_name: run_me}, default_value)
915 if not guards:
916 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +0000917 is_true = list(guards.values())[0]
918 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +0000919 return (guards, not is_true)
920
921# Use the following check to guard CPython's implementation-specific tests --
922# or to run them only on the implementation(s) guarded by the arguments.
923def check_impl_detail(**guards):
924 """This function returns True or False depending on the host platform.
925 Examples:
926 if check_impl_detail(): # only on CPython (default)
927 if check_impl_detail(jython=True): # only on Jython
928 if check_impl_detail(cpython=False): # everywhere except on CPython
929 """
930 guards, default = _parse_guards(guards)
931 return guards.get(platform.python_implementation().lower(), default)
932
933
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000934
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +0000936 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000937 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +0000938 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000939 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000940 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000941
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000942 result = runner.run(suite)
943 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +0000944 if len(result.errors) == 1 and not result.failures:
945 err = result.errors[0][1]
946 elif len(result.failures) == 1 and not result.errors:
947 err = result.failures[0][1]
948 else:
R. David Murray723357e2009-10-19 18:06:17 +0000949 err = "multiple errors occurred"
950 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +0000951 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +0000952
Barry Warsawc10d6902001-09-20 06:30:41 +0000953
Walter Dörwald21d3a322003-05-01 17:45:56 +0000954def run_unittest(*classes):
955 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000956 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000957 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000958 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000959 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960 if cls in sys.modules:
961 suite.addTest(unittest.findTestCases(sys.modules[cls]))
962 else:
963 raise ValueError("str arguments must be keys in sys.modules")
964 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +0000965 suite.addTest(cls)
966 else:
967 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000969
Barry Warsawc10d6902001-09-20 06:30:41 +0000970
Tim Petersa0a62222001-09-09 06:12:01 +0000971#=======================================================================
972# doctest driver.
973
974def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +0000975 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +0000976
977 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000978 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +0000979 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +0000980 """
981
982 import doctest
983
984 if verbosity is None:
985 verbosity = verbose
986 else:
987 verbosity = None
988
Tim Peters342ca752001-09-25 19:13:20 +0000989 # Direct doctest output (normally just errors) to real stdout; doctest
990 # output shouldn't be compared by regrtest.
991 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +0000992 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +0000993 try:
994 f, t = doctest.testmod(module, verbose=verbosity)
995 if f:
996 raise TestFailed("%d of %d doctests failed" % (f, t))
997 finally:
998 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000999 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001000 print('doctest (%s) ... %d tests with zero failures' %
1001 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001002 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001003
Antoine Pitrou060cee22009-11-13 16:29:04 +00001004
1005#=======================================================================
1006# Support for saving and restoring the imported modules.
1007
1008def modules_setup():
1009 return sys.modules.copy(),
1010
1011def modules_cleanup(oldmodules):
1012 # Encoders/decoders are registered permanently within the internal
1013 # codec cache. If we destroy the corresponding modules their
1014 # globals will be set to None which will trip up the cached functions.
1015 encodings = [(k, v) for k, v in sys.modules.items()
1016 if k.startswith('encodings.')]
1017 sys.modules.clear()
1018 sys.modules.update(encodings)
1019 sys.modules.update(oldmodules)
1020
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001021#=======================================================================
1022# Threading support to prevent reporting refleaks when running regrtest.py -R
1023
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001024# NOTE: we use thread._count() rather than threading.enumerate() (or the
1025# moral equivalent thereof) because a threading.Thread object is still alive
1026# until its __bootstrap() method has returned, even after it has been
1027# unregistered from the threading module.
1028# thread._count(), on the other hand, only gets decremented *after* the
1029# __bootstrap() method has returned, which gives us reliable reference counts
1030# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001031
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001032def threading_setup():
1033 import _thread
1034 return _thread._count(),
1035
1036def threading_cleanup(nb_threads):
1037 import _thread
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001038 import time
1039
1040 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001041 for count in range(_MAX_COUNT):
1042 n = _thread._count()
1043 if n == nb_threads:
1044 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001045 time.sleep(0.1)
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001046 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001047
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001048def reap_threads(func):
1049 @functools.wraps(func)
1050 def decorator(*args):
1051 key = threading_setup()
1052 try:
1053 return func(*args)
1054 finally:
1055 threading_cleanup(*key)
1056 return decorator
1057
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058def reap_children():
1059 """Use this function at the end of test_main() whenever sub-processes
1060 are started. This will help ensure that no extra children (zombies)
1061 stick around to hog resources and create problems when looking
1062 for refleaks.
1063 """
1064
1065 # Reap all our dead child processes so we don't leave zombies around.
1066 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001067 if hasattr(os, 'waitpid'):
1068 any_process = -1
1069 while True:
1070 try:
1071 # This will raise an exception on Windows. That's ok.
1072 pid, status = os.waitpid(any_process, os.WNOHANG)
1073 if pid == 0:
1074 break
1075 except:
1076 break