blob: bd35fded3567d0b176b4134030ab8654b00bc27b [file] [log] [blame]
Brett Cannonf1cfb622003-05-04 21:15:27 +00001"""Supporting definitions for the Python regression tests."""
Guido van Rossum3bead091992-01-27 17:00:37 +00002
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003if __name__ != 'test.support':
4 raise ImportError('support must be imported from the test package')
Barry Warsaw408b6d32002-07-30 23:27:12 +00005
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import contextlib
7import errno
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00008import functools
Benjamin Peterson8cc7d882009-06-01 23:14:51 +00009import gc
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import socket
Fred Drakecd1b1dd2001-03-21 18:26:33 +000011import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000012import os
Benjamin Petersone549ead2009-03-28 21:42:05 +000013import platform
Christian Heimes23daade02008-02-25 12:39:23 +000014import shutil
Thomas Wouters902d6eb2007-01-09 23:18:33 +000015import warnings
Guido van Rossumd8faa362007-04-27 19:54:29 +000016import unittest
R. David Murraya21e4ca2009-03-31 23:16:50 +000017import importlib
Walter Dörwald155374d2009-05-01 19:58:58 +000018import collections
Florent Xiclunab14930c2010-03-13 15:26:44 +000019import re
Brian Curtind40e6f72010-07-08 21:39:08 +000020import subprocess
Barry Warsaw28a691b2010-04-17 00:19:56 +000021import imp
Benjamin Petersona6590e82010-04-11 21:22:10 +000022import time
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000023import sysconfig
Vinay Sajip129fd042010-12-10 08:19:38 +000024import logging.handlers
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000025
Victor Stinner45df8202010-04-28 22:31:17 +000026try:
27 import _thread
28except ImportError:
29 _thread = None
Fred Drakecd1b1dd2001-03-21 18:26:33 +000030
Barry Warsaw28a691b2010-04-17 00:19:56 +000031__all__ = [
32 "Error", "TestFailed", "ResourceDenied", "import_module",
33 "verbose", "use_resources", "max_memuse", "record_original_stdout",
34 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
35 "is_resource_enabled", "requires", "find_unused_port", "bind_port",
36 "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
37 "findfile", "sortdict", "check_syntax_error", "open_urlresource",
38 "check_warnings", "CleanImport", "EnvironmentVarGuard",
39 "TransientResource", "captured_output", "captured_stdout",
40 "time_out", "socket_peer_reset", "ioerror_peer_reset",
Antoine Pitroua88c83c2010-09-07 20:42:19 +000041 "run_with_locale", 'temp_umask', "transient_internet",
Barry Warsaw28a691b2010-04-17 00:19:56 +000042 "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
43 "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
44 "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
Vinay Sajip129fd042010-12-10 08:19:38 +000045 "swap_item", "swap_attr", "requires_IEEE_754",
Benjamin Peterson31dc3732011-05-08 15:34:24 -050046 "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink",
Benjamin Peterson262c5822011-05-08 15:32:46 -050047 "import_fresh_module"
Antoine Pitrou4d7979b2010-09-07 21:22:56 +000048 ]
Florent Xiclunaf089fd62010-03-19 14:25:03 +000049
Fred Drake1790dd42000-07-24 06:55:00 +000050class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000051 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000052
53class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000054 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000055
Benjamin Petersone549ead2009-03-28 21:42:05 +000056class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +000057 """Test skipped because it requested a disallowed resource.
58
59 This is raised when a test calls requires() for a resource that
60 has not be enabled. It is used to distinguish between expected
61 and unexpected skips.
62 """
63
Nick Coghlanfce769e2009-04-11 14:30:59 +000064@contextlib.contextmanager
65def _ignore_deprecated_imports(ignore=True):
66 """Context manager to suppress package and module deprecation
67 warnings when importing them.
68
69 If ignore is False, this context manager has no effect."""
70 if ignore:
71 with warnings.catch_warnings():
72 warnings.filterwarnings("ignore", ".+ (module|package)",
73 DeprecationWarning)
74 yield
75 else:
76 yield
77
78
Benjamin Peterson699adb92008-05-08 22:27:58 +000079def import_module(name, deprecated=False):
R. David Murraya21e4ca2009-03-31 23:16:50 +000080 """Import and return the module to be tested, raising SkipTest if
81 it is not available.
82
83 If deprecated is True, any module or package deprecation messages
84 will be suppressed."""
Nick Coghlanfce769e2009-04-11 14:30:59 +000085 with _ignore_deprecated_imports(deprecated):
Benjamin Peterson699adb92008-05-08 22:27:58 +000086 try:
Nick Coghlanfce769e2009-04-11 14:30:59 +000087 return importlib.import_module(name)
R. David Murraya21e4ca2009-03-31 23:16:50 +000088 except ImportError as msg:
89 raise unittest.SkipTest(str(msg))
Nick Coghlanfce769e2009-04-11 14:30:59 +000090
91
Nick Coghlan47384702009-04-22 16:13:36 +000092def _save_and_remove_module(name, orig_modules):
93 """Helper function to save and remove a module from sys.modules
94
Ezio Melotti199e0852011-05-09 06:41:55 +030095 Raise ImportError if the module can't be imported."""
Ezio Melottifec3ad12011-05-14 06:02:25 +030096 # try to import the module and raise an error if it can't be imported
97 if name not in sys.modules:
Ezio Melotti199e0852011-05-09 06:41:55 +030098 __import__(name)
Nick Coghlan47384702009-04-22 16:13:36 +000099 del sys.modules[name]
Ezio Melottifec3ad12011-05-14 06:02:25 +0300100 for modname in list(sys.modules):
101 if modname == name or modname.startswith(name + '.'):
102 orig_modules[modname] = sys.modules[modname]
103 del sys.modules[modname]
Nick Coghlan47384702009-04-22 16:13:36 +0000104
105def _save_and_block_module(name, orig_modules):
106 """Helper function to save and block a module in sys.modules
107
Ezio Melotti199e0852011-05-09 06:41:55 +0300108 Return True if the module was in sys.modules, False otherwise."""
Nick Coghlan47384702009-04-22 16:13:36 +0000109 saved = True
110 try:
111 orig_modules[name] = sys.modules[name]
112 except KeyError:
113 saved = False
Alexander Belopolsky903396e2010-07-13 14:50:16 +0000114 sys.modules[name] = None
Nick Coghlan47384702009-04-22 16:13:36 +0000115 return saved
116
117
118def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Nick Coghlanfce769e2009-04-11 14:30:59 +0000119 """Imports and returns a module, deliberately bypassing the sys.modules cache
120 and importing a fresh copy of the module. Once the import is complete,
121 the sys.modules cache is restored to its original state.
122
Nick Coghlan47384702009-04-22 16:13:36 +0000123 Modules named in fresh are also imported anew if needed by the import.
Ezio Melotti199e0852011-05-09 06:41:55 +0300124 If one of these modules can't be imported, None is returned.
Nick Coghlan47384702009-04-22 16:13:36 +0000125
126 Importing of modules named in blocked is prevented while the fresh import
Nick Coghlanfce769e2009-04-11 14:30:59 +0000127 takes place.
128
129 If deprecated is True, any module or package deprecation messages
130 will be suppressed."""
Ezio Melotti6b60fb92011-05-14 06:47:51 +0300131 # NOTE: test_heapq, test_json and test_warnings include extra sanity checks
132 # to make sure that this utility function is working as expected
Nick Coghlanfce769e2009-04-11 14:30:59 +0000133 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000134 # Keep track of modules saved for later restoration as well
135 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000136 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000137 names_to_remove = []
138 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000139 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000140 for fresh_name in fresh:
141 _save_and_remove_module(fresh_name, orig_modules)
142 for blocked_name in blocked:
143 if not _save_and_block_module(blocked_name, orig_modules):
144 names_to_remove.append(blocked_name)
145 fresh_module = importlib.import_module(name)
Ezio Melotti199e0852011-05-09 06:41:55 +0300146 except ImportError:
147 fresh_module = None
Nick Coghlanfce769e2009-04-11 14:30:59 +0000148 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000149 for orig_name, module in orig_modules.items():
150 sys.modules[orig_name] = module
151 for name_to_remove in names_to_remove:
152 del sys.modules[name_to_remove]
153 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000154
Benjamin Peterson699adb92008-05-08 22:27:58 +0000155
R. David Murraya21e4ca2009-03-31 23:16:50 +0000156def get_attribute(obj, name):
157 """Get an attribute, raising SkipTest if AttributeError is raised."""
158 try:
159 attribute = getattr(obj, name)
160 except AttributeError:
161 raise unittest.SkipTest("module %s has no attribute %s" % (
162 obj.__name__, name))
163 else:
164 return attribute
165
Barry Warsawc0fb6052001-08-20 22:29:23 +0000166verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000167use_resources = None # Flag set to [] by regrtest.py
168max_memuse = 0 # Disable bigmem tests (they will still be run with
169 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000170real_max_memuse = 0
Guido van Rossum531661c1996-12-20 02:58:22 +0000171
Tim Peters8dee8092001-09-25 20:05:11 +0000172# _original_stdout is meant to hold stdout at the time regrtest began.
173# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
174# The point is to have some flavor of stdout the user can actually see.
175_original_stdout = None
176def record_original_stdout(stdout):
177 global _original_stdout
178 _original_stdout = stdout
179
180def get_original_stdout():
181 return _original_stdout or sys.stdout
182
Guido van Rossum3bead091992-01-27 17:00:37 +0000183def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000184 try:
185 del sys.modules[name]
186 except KeyError:
187 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000188
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000189def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000190 try:
191 os.unlink(filename)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000192 except OSError as error:
193 # The filename need not exist.
Michael Foord2d9c2d52010-05-04 22:29:10 +0000194 if error.errno not in (errno.ENOENT, errno.ENOTDIR):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000195 raise
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000196
Christian Heimes23daade02008-02-25 12:39:23 +0000197def rmtree(path):
198 try:
199 shutil.rmtree(path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000200 except OSError as error:
Christian Heimes23daade02008-02-25 12:39:23 +0000201 # Unix returns ENOENT, Windows returns ESRCH.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000202 if error.errno not in (errno.ENOENT, errno.ESRCH):
Christian Heimes23daade02008-02-25 12:39:23 +0000203 raise
204
Barry Warsaw28a691b2010-04-17 00:19:56 +0000205def make_legacy_pyc(source):
206 """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
207
208 The choice of .pyc or .pyo extension is done based on the __debug__ flag
209 value.
210
211 :param source: The file system path to the source file. The source file
212 does not need to exist, however the PEP 3147 pyc file must exist.
213 :return: The file system path to the legacy pyc file.
214 """
215 pyc_file = imp.cache_from_source(source)
216 up_one = os.path.dirname(os.path.abspath(source))
217 legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
218 os.rename(pyc_file, legacy_pyc)
219 return legacy_pyc
220
Guido van Rossum3bead091992-01-27 17:00:37 +0000221def forget(modname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000222 """'Forget' a module was ever imported.
223
224 This removes the module from sys.modules and deletes any PEP 3147 or
225 legacy .pyc and .pyo files.
226 """
Fred Drake004d5e62000-10-23 17:22:08 +0000227 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000228 for dirname in sys.path:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000229 source = os.path.join(dirname, modname + '.py')
230 # It doesn't matter if they exist or not, unlink all possible
231 # combinations of PEP 3147 and legacy pyc and pyo files.
232 unlink(source + 'c')
233 unlink(source + 'o')
234 unlink(imp.cache_from_source(source, debug_override=True))
235 unlink(imp.cache_from_source(source, debug_override=False))
Guido van Rossum3bead091992-01-27 17:00:37 +0000236
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000237# On some platforms, should not run gui test even if it is allowed
238# in `use_resources'.
239if sys.platform.startswith('win'):
240 import ctypes
241 import ctypes.wintypes
242 def _is_gui_available():
243 UOI_FLAGS = 1
244 WSF_VISIBLE = 0x0001
245 class USEROBJECTFLAGS(ctypes.Structure):
246 _fields_ = [("fInherit", ctypes.wintypes.BOOL),
247 ("fReserved", ctypes.wintypes.BOOL),
248 ("dwFlags", ctypes.wintypes.DWORD)]
249 dll = ctypes.windll.user32
250 h = dll.GetProcessWindowStation()
251 if not h:
252 raise ctypes.WinError()
253 uof = USEROBJECTFLAGS()
254 needed = ctypes.wintypes.DWORD()
255 res = dll.GetUserObjectInformationW(h,
256 UOI_FLAGS,
257 ctypes.byref(uof),
258 ctypes.sizeof(uof),
259 ctypes.byref(needed))
260 if not res:
261 raise ctypes.WinError()
262 return bool(uof.dwFlags & WSF_VISIBLE)
263else:
264 def _is_gui_available():
265 return True
266
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000267def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000268 """Test whether a resource is enabled. Known resources are set by
269 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000270 return use_resources is not None and resource in use_resources
271
Barry Warsawc0fb6052001-08-20 22:29:23 +0000272def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000273 """Raise ResourceDenied if the specified resource is not available.
274
275 If the caller's module is __main__ then automatically return True. The
Barry Warsaw28a691b2010-04-17 00:19:56 +0000276 possibility of False being returned occurs when regrtest.py is
277 executing.
278 """
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000279 if resource == 'gui' and not _is_gui_available():
280 raise unittest.SkipTest("Cannot use the 'gui' resource")
Skip Montanarod839ecd2003-04-24 19:06:57 +0000281 # see if the caller's module is __main__ - if so, treat as if
282 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000283 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000284 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000285 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000286 if msg is None:
287 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000288 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000289
Christian Heimes5e696852008-04-09 08:37:03 +0000290HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000291
Christian Heimes5e696852008-04-09 08:37:03 +0000292def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
293 """Returns an unused port that should be suitable for binding. This is
294 achieved by creating a temporary socket with the same family and type as
295 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
296 the specified host address (defaults to 0.0.0.0) with the port set to 0,
297 eliciting an unused ephemeral port from the OS. The temporary socket is
298 then closed and deleted, and the ephemeral port is returned.
299
300 Either this method or bind_port() should be used for any tests where a
301 server socket needs to be bound to a particular port for the duration of
302 the test. Which one to use depends on whether the calling code is creating
303 a python socket, or if an unused port needs to be provided in a constructor
304 or passed to an external program (i.e. the -accept argument to openssl's
305 s_server mode). Always prefer bind_port() over find_unused_port() where
306 possible. Hard coded ports should *NEVER* be used. As soon as a server
307 socket is bound to a hard coded port, the ability to run multiple instances
308 of the test simultaneously on the same host is compromised, which makes the
309 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
310 may simply manifest as a failed test, which can be recovered from without
311 intervention in most cases, but on Windows, the entire python process can
312 completely and utterly wedge, requiring someone to log in to the buildbot
313 and manually kill the affected process.
314
315 (This is easy to reproduce on Windows, unfortunately, and can be traced to
316 the SO_REUSEADDR socket option having different semantics on Windows versus
317 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
318 listen and then accept connections on identical host/ports. An EADDRINUSE
319 socket.error will be raised at some point (depending on the platform and
320 the order bind and listen were called on each socket).
321
322 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
323 will ever be raised when attempting to bind two identical host/ports. When
324 accept() is called on each socket, the second caller's process will steal
325 the port from the first caller, leaving them both in an awkwardly wedged
326 state where they'll no longer respond to any signals or graceful kills, and
327 must be forcibly killed via OpenProcess()/TerminateProcess().
328
329 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
330 instead of SO_REUSEADDR, which effectively affords the same semantics as
331 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
332 Source world compared to Windows ones, this is a common mistake. A quick
333 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
334 openssl.exe is called with the 's_server' option, for example. See
335 http://bugs.python.org/issue2550 for more info. The following site also
336 has a very thorough description about the implications of both REUSEADDR
337 and EXCLUSIVEADDRUSE on Windows:
338 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
339
340 XXX: although this approach is a vast improvement on previous attempts to
341 elicit unused ports, it rests heavily on the assumption that the ephemeral
342 port returned to us by the OS won't immediately be dished back out to some
343 other process when we close and delete our temporary socket but before our
344 calling code has a chance to bind the returned port. We can deal with this
345 issue if/when we come across it.
346 """
347
348 tempsock = socket.socket(family, socktype)
349 port = bind_port(tempsock)
350 tempsock.close()
351 del tempsock
352 return port
353
354def bind_port(sock, host=HOST):
355 """Bind the socket to a free port and return the port number. Relies on
356 ephemeral ports in order to ensure we are using an unbound port. This is
357 important as many tests may be running simultaneously, especially in a
358 buildbot environment. This method raises an exception if the sock.family
359 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
360 or SO_REUSEPORT set on it. Tests should *never* set these socket options
361 for TCP/IP sockets. The only case for setting these options is testing
362 multicasting via multiple UDP sockets.
363
364 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
365 on Windows), it will be set on the socket. This will prevent anyone else
366 from bind()'ing to our host/port for the duration of the test.
367 """
368
369 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
370 if hasattr(socket, 'SO_REUSEADDR'):
371 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
372 raise TestFailed("tests should never set the SO_REUSEADDR " \
373 "socket option on TCP/IP sockets!")
374 if hasattr(socket, 'SO_REUSEPORT'):
375 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
376 raise TestFailed("tests should never set the SO_REUSEPORT " \
377 "socket option on TCP/IP sockets!")
378 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
379 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
380
381 sock.bind((host, 0))
382 port = sock.getsockname()[1]
383 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000384
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000385FUZZ = 1e-6
386
387def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000388 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000389 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000390 fuzz = (abs(x) + abs(y)) * FUZZ
391 if abs(x-y) <= fuzz:
392 return 0
393 except:
394 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000395 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000396 for i in range(min(len(x), len(y))):
397 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000398 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000399 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000400 return (len(x) > len(y)) - (len(x) < len(y))
401 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000402
Eric Smithf24a0d92010-12-04 13:32:18 +0000403# decorator for skipping tests on non-IEEE 754 platforms
404requires_IEEE_754 = unittest.skipUnless(
405 float.__getformat__("double").startswith("IEEE"),
406 "test requires IEEE 754 doubles")
407
Finn Bock57bc5fa2002-11-01 18:02:03 +0000408is_jython = sys.platform.startswith('java')
409
Barry Warsaw559f6682001-03-23 18:04:02 +0000410# Filename used for testing
411if os.name == 'java':
412 # Jython disallows @ in module names
413 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000414else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000415 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000416
Antoine Pitrou88909542009-06-29 13:54:42 +0000417# Disambiguate TESTFN for parallel testing, while letting it remain a valid
418# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000419TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000420
Michael Foord2d9c2d52010-05-04 22:29:10 +0000421
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000422# TESTFN_UNICODE is a non-ascii filename
423TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
Victor Stinner74a833f2010-08-18 21:06:23 +0000424if sys.platform == 'darwin':
425 # In Mac OS X's VFS API file names are, by definition, canonically
426 # decomposed Unicode, encoded using UTF-8. See QA1173:
427 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
428 import unicodedata
429 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
Antoine Pitrou88909542009-06-29 13:54:42 +0000430TESTFN_ENCODING = sys.getfilesystemencoding()
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000431
Victor Stinner09c449c2010-08-13 22:23:24 +0000432# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000433# encoded by the filesystem encoding (in strict mode). It can be None if we
434# cannot generate such filename.
Victor Stinnera0241c82010-08-15 19:28:21 +0000435TESTFN_UNENCODABLE = None
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000436if os.name in ('nt', 'ce'):
Victor Stinnera0241c82010-08-15 19:28:21 +0000437 # skip win32s (0) or Windows 9x/ME (1)
438 if sys.getwindowsversion().platform >= 2:
Victor Stinner8ce7df62010-09-10 11:19:59 +0000439 # Different kinds of characters from various languages to minimize the
440 # probability that the whole name is encodable to MBCS (issue #9819)
441 TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000442 try:
Victor Stinner09c449c2010-08-13 22:23:24 +0000443 TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000444 except UnicodeEncodeError:
445 pass
446 else:
447 print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
448 'Unicode filename tests may not be effective'
Victor Stinner09c449c2010-08-13 22:23:24 +0000449 % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
450 TESTFN_UNENCODABLE = None
Victor Stinnera0241c82010-08-15 19:28:21 +0000451# Mac OS X denies unencodable filenames (invalid utf-8)
Victor Stinner03c9e1d2010-08-14 17:35:20 +0000452elif sys.platform != 'darwin':
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000453 try:
454 # ascii and utf-8 cannot encode the byte 0xff
455 b'\xff'.decode(TESTFN_ENCODING)
456 except UnicodeDecodeError:
457 # 0xff will be encoded using the surrogate character u+DCFF
Victor Stinner09c449c2010-08-13 22:23:24 +0000458 TESTFN_UNENCODABLE = TESTFN \
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000459 + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
460 else:
461 # File system encoding (eg. ISO-8859-* encodings) can encode
462 # the byte 0xff. Skip some unicode filename tests.
Victor Stinnera0241c82010-08-15 19:28:21 +0000463 pass
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000464
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000465# Save the initial cwd
466SAVEDCWD = os.getcwd()
467
468@contextlib.contextmanager
Nick Coghland26c18a2010-08-17 13:06:11 +0000469def temp_cwd(name='tempcwd', quiet=False, path=None):
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000470 """
Nick Coghland26c18a2010-08-17 13:06:11 +0000471 Context manager that temporarily changes the CWD.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000472
Nick Coghland26c18a2010-08-17 13:06:11 +0000473 An existing path may be provided as *path*, in which case this
474 function makes no changes to the file system.
475
476 Otherwise, the new CWD is created in the current directory and it's
477 named *name*. If *quiet* is False (default) and it's not possible to
478 create or change the CWD, an error is raised. If it's True, only a
479 warning is raised and the original CWD is used.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000480 """
481 saved_dir = os.getcwd()
482 is_temporary = False
Nick Coghland26c18a2010-08-17 13:06:11 +0000483 if path is None:
484 path = name
485 try:
486 os.mkdir(name)
487 is_temporary = True
488 except OSError:
489 if not quiet:
490 raise
491 warnings.warn('tests may fail, unable to create temp CWD ' + name,
492 RuntimeWarning, stacklevel=3)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000493 try:
Nick Coghland26c18a2010-08-17 13:06:11 +0000494 os.chdir(path)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000495 except OSError:
496 if not quiet:
497 raise
498 warnings.warn('tests may fail, unable to change the CWD to ' + name,
499 RuntimeWarning, stacklevel=3)
500 try:
501 yield os.getcwd()
502 finally:
503 os.chdir(saved_dir)
504 if is_temporary:
505 rmtree(name)
506
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000507
Barry Warsaw28a691b2010-04-17 00:19:56 +0000508@contextlib.contextmanager
509def temp_umask(umask):
510 """Context manager that temporarily sets the process umask."""
511 oldmask = os.umask(umask)
512 try:
513 yield
514 finally:
515 os.umask(oldmask)
516
517
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000518def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000519 """Try to find a file on sys.path and the working directory. If it is not
520 found the argument passed to the function is returned (this does not
521 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000522 if os.path.isabs(file):
523 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000524 if subdir is not None:
525 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000526 path = sys.path
527 path = [os.path.dirname(here)] + path
528 for dn in path:
529 fn = os.path.join(dn, file)
530 if os.path.exists(fn): return fn
531 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000532
Tim Peters2f228e72001-05-13 00:19:31 +0000533def sortdict(dict):
534 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000535 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000536 reprpairs = ["%r: %r" % pair for pair in items]
537 withcommas = ", ".join(reprpairs)
538 return "{%s}" % withcommas
539
Benjamin Peterson7522c742009-01-19 21:00:09 +0000540def make_bad_fd():
541 """
542 Create an invalid file descriptor by opening and closing a file and return
543 its fd.
544 """
545 file = open(TESTFN, "wb")
546 try:
547 return file.fileno()
548 finally:
549 file.close()
550 unlink(TESTFN)
551
Thomas Wouters89f507f2006-12-13 04:49:30 +0000552def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000553 testcase.assertRaises(SyntaxError, compile, statement,
554 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000555
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000556def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000557 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000558
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000559 check = kw.pop('check', None)
560
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000561 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000562
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000563 fn = os.path.join(os.path.dirname(__file__), "data", filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000564
565 def check_valid_file(fn):
566 f = open(fn, *args, **kw)
567 if check is None:
568 return f
569 elif check(f):
570 f.seek(0)
571 return f
572 f.close()
573
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000574 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000575 f = check_valid_file(fn)
576 if f is not None:
577 return f
578 unlink(fn)
579
580 # Verify the requirement before downloading the file
581 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000582
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000583 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000584 f = urllib.request.urlopen(url, timeout=15)
585 try:
586 with open(fn, "wb") as out:
587 s = f.read()
588 while s:
589 out.write(s)
590 s = f.read()
591 finally:
592 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000593
594 f = check_valid_file(fn)
595 if f is not None:
596 return f
597 raise TestFailed('invalid resource "%s"' % fn)
598
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000599
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000600class WarningsRecorder(object):
601 """Convenience wrapper for the warnings list returned on
602 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000603 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000604 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000605 self._warnings = warnings_list
606 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000607
608 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000609 if len(self._warnings) > self._last:
610 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000611 elif attr in warnings.WarningMessage._WARNING_DETAILS:
612 return None
613 raise AttributeError("%r has no attribute %r" % (self, attr))
614
Florent Xiclunab14930c2010-03-13 15:26:44 +0000615 @property
616 def warnings(self):
617 return self._warnings[self._last:]
618
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000619 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000620 self._last = len(self._warnings)
621
622
623def _filterwarnings(filters, quiet=False):
624 """Catch the warnings, then check if all the expected
625 warnings have been raised and re-raise unexpected warnings.
626 If 'quiet' is True, only re-raise the unexpected warnings.
627 """
628 # Clear the warning registry of the calling module
629 # in order to re-raise the warnings.
630 frame = sys._getframe(2)
631 registry = frame.f_globals.get('__warningregistry__')
632 if registry:
633 registry.clear()
634 with warnings.catch_warnings(record=True) as w:
635 # Set filter "always" to record all warnings. Because
636 # test_warnings swap the module, we need to look up in
637 # the sys.modules dictionary.
638 sys.modules['warnings'].simplefilter("always")
639 yield WarningsRecorder(w)
640 # Filter the recorded warnings
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000641 reraise = list(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000642 missing = []
643 for msg, cat in filters:
644 seen = False
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000645 for w in reraise[:]:
646 warning = w.message
Florent Xiclunab14930c2010-03-13 15:26:44 +0000647 # Filter out the matching messages
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000648 if (re.match(msg, str(warning), re.I) and
649 issubclass(warning.__class__, cat)):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000650 seen = True
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000651 reraise.remove(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000652 if not seen and not quiet:
653 # This filter caught nothing
654 missing.append((msg, cat.__name__))
655 if reraise:
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000656 raise AssertionError("unhandled warning %s" % reraise[0])
Florent Xiclunab14930c2010-03-13 15:26:44 +0000657 if missing:
658 raise AssertionError("filter (%r, %s) did not catch any warning" %
659 missing[0])
660
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000661
662@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000663def check_warnings(*filters, **kwargs):
664 """Context manager to silence warnings.
665
666 Accept 2-tuples as positional arguments:
667 ("message regexp", WarningCategory)
668
669 Optional argument:
670 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506be2010-03-18 20:00:57 +0000671 (default True without argument,
672 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000673
674 Without argument, it defaults to:
Florent Xicluna53b506be2010-03-18 20:00:57 +0000675 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000676 """
Florent Xicluna53b506be2010-03-18 20:00:57 +0000677 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +0000678 if not filters:
679 filters = (("", Warning),)
Florent Xicluna53b506be2010-03-18 20:00:57 +0000680 # Preserve backward compatibility
681 if quiet is None:
682 quiet = True
683 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000684
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000685
686class CleanImport(object):
687 """Context manager to force import to return a new module reference.
688
689 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000690 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000691
692 Use like this:
693
694 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000695 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000696 """
697
698 def __init__(self, *module_names):
699 self.original_modules = sys.modules.copy()
700 for module_name in module_names:
701 if module_name in sys.modules:
702 module = sys.modules[module_name]
703 # It is possible that module_name is just an alias for
704 # another module (e.g. stub for modules renamed in 3.x).
705 # In that case, we also need delete the real module to clear
706 # the import cache.
707 if module.__name__ != module_name:
708 del sys.modules[module.__name__]
709 del sys.modules[module_name]
710
711 def __enter__(self):
712 return self
713
714 def __exit__(self, *ignore_exc):
715 sys.modules.update(self.original_modules)
716
717
Walter Dörwald155374d2009-05-01 19:58:58 +0000718class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000719
720 """Class to help protect the environment variable properly. Can be used as
721 a context manager."""
722
723 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000724 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000725 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000726
Walter Dörwald155374d2009-05-01 19:58:58 +0000727 def __getitem__(self, envvar):
728 return self._environ[envvar]
729
730 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000731 # Remember the initial value on the first access
732 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000733 self._changed[envvar] = self._environ.get(envvar)
734 self._environ[envvar] = value
735
736 def __delitem__(self, envvar):
737 # Remember the initial value on the first access
738 if envvar not in self._changed:
739 self._changed[envvar] = self._environ.get(envvar)
740 if envvar in self._environ:
741 del self._environ[envvar]
742
743 def keys(self):
744 return self._environ.keys()
745
746 def __iter__(self):
747 return iter(self._environ)
748
749 def __len__(self):
750 return len(self._environ)
751
752 def set(self, envvar, value):
753 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000754
755 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000756 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000757
758 def __enter__(self):
759 return self
760
761 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000762 for (k, v) in self._changed.items():
763 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000764 if k in self._environ:
765 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000766 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000767 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000768 os.environ = self._environ
769
770
771class DirsOnSysPath(object):
772 """Context manager to temporarily add directories to sys.path.
773
774 This makes a copy of sys.path, appends any directories given
775 as positional arguments, then reverts sys.path to the copied
776 settings when the context ends.
777
778 Note that *all* sys.path modifications in the body of the
779 context manager, including replacement of the object,
780 will be reverted at the end of the block.
781 """
782
783 def __init__(self, *paths):
784 self.original_value = sys.path[:]
785 self.original_object = sys.path
786 sys.path.extend(paths)
787
788 def __enter__(self):
789 return self
790
791 def __exit__(self, *ignore_exc):
792 sys.path = self.original_object
793 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000794
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000795
Guido van Rossumd8faa362007-04-27 19:54:29 +0000796class TransientResource(object):
797
798 """Raise ResourceDenied if an exception is raised while the context manager
799 is in effect that matches the specified exception and attributes."""
800
801 def __init__(self, exc, **kwargs):
802 self.exc = exc
803 self.attrs = kwargs
804
805 def __enter__(self):
806 return self
807
808 def __exit__(self, type_=None, value=None, traceback=None):
809 """If type_ is a subclass of self.exc and value has attributes matching
810 self.attrs, raise ResourceDenied. Otherwise let the exception
811 propagate (if any)."""
812 if type_ is not None and issubclass(self.exc, type_):
813 for attr, attr_value in self.attrs.items():
814 if not hasattr(value, attr):
815 break
816 if getattr(value, attr) != attr_value:
817 break
818 else:
819 raise ResourceDenied("an optional resource is not available")
820
Raymond Hettinger686057b2009-06-04 00:11:54 +0000821# Context managers that raise ResourceDenied when various issues
822# with the Internet connection manifest themselves as exceptions.
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000823# XXX deprecate these and use transient_internet() instead
Raymond Hettinger686057b2009-06-04 00:11:54 +0000824time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
825socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
826ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000827
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000828
Thomas Woutersed03b412007-08-28 21:37:11 +0000829@contextlib.contextmanager
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000830def transient_internet(resource_name, *, timeout=30.0, errnos=()):
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000831 """Return a context manager that raises ResourceDenied when various issues
832 with the Internet connection manifest themselves as exceptions."""
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000833 default_errnos = [
834 ('ECONNREFUSED', 111),
835 ('ECONNRESET', 104),
Antoine Pitrou5d938cb2011-01-08 10:28:11 +0000836 ('EHOSTUNREACH', 113),
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000837 ('ENETUNREACH', 101),
838 ('ETIMEDOUT', 110),
839 ]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000840 default_gai_errnos = [
841 ('EAI_NONAME', -2),
842 ('EAI_NODATA', -5),
Antoine Pitrou390ea0f2011-04-29 00:44:33 +0200843 # Encountered when trying to resolve IPv6-only hostnames
844 ('WSANO_DATA', 11004),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000845 ]
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000846
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000847 denied = ResourceDenied("Resource '%s' is not available" % resource_name)
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000848 captured_errnos = errnos
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000849 gai_errnos = []
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000850 if not captured_errnos:
851 captured_errnos = [getattr(errno, name, num)
852 for (name, num) in default_errnos]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000853 gai_errnos = [getattr(socket, name, num)
854 for (name, num) in default_gai_errnos]
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000855
856 def filter_error(err):
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000857 n = getattr(err, 'errno', None)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000858 if (isinstance(err, socket.timeout) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000859 (isinstance(err, socket.gaierror) and n in gai_errnos) or
860 n in captured_errnos):
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000861 if not verbose:
862 sys.stderr.write(denied.args[0] + "\n")
863 raise denied from err
864
865 old_timeout = socket.getdefaulttimeout()
866 try:
867 if timeout is not None:
868 socket.setdefaulttimeout(timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000869 yield
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000870 except IOError as err:
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000871 # urllib can wrap original socket errors multiple times (!), we must
872 # unwrap to get at the original error.
873 while True:
874 a = err.args
875 if len(a) >= 1 and isinstance(a[0], IOError):
876 err = a[0]
877 # The error can also be wrapped as args[1]:
878 # except socket.error as msg:
879 # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
880 elif len(a) >= 2 and isinstance(a[1], IOError):
881 err = a[1]
882 else:
883 break
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000884 filter_error(err)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000885 raise
886 # XXX should we catch generic exceptions and look for their
887 # __cause__ or __context__?
888 finally:
889 socket.setdefaulttimeout(old_timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000890
891
892@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000893def captured_output(stream_name):
894 """Run the 'with' statement body using a StringIO object in place of a
895 specific attribute on the sys module.
896 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000897
898 with captured_stdout() as s:
Neal Norwitz752abd02008-05-13 04:55:24 +0000899 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000900 assert s.getvalue() == "hello"
901 """
902 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000903 orig_stdout = getattr(sys, stream_name)
904 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000905 try:
906 yield getattr(sys, stream_name)
907 finally:
908 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000909
910def captured_stdout():
911 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000912
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000913def captured_stderr():
914 return captured_output("stderr")
915
Nick Coghlan6ead5522009-10-18 13:19:33 +0000916def captured_stdin():
917 return captured_output("stdin")
918
Benjamin Petersone549ead2009-03-28 21:42:05 +0000919def gc_collect():
920 """Force as many objects as possible to be collected.
921
922 In non-CPython implementations of Python, this is needed because timely
923 deallocation is not guaranteed by the garbage collector. (Even in CPython
924 this can be the case in case of reference cycles.) This means that __del__
925 methods may be called later than expected and weakrefs may remain alive for
926 longer than expected. This function tries its best to force all garbage
927 objects to disappear.
928 """
Benjamin Petersone549ead2009-03-28 21:42:05 +0000929 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +0000930 if is_jython:
931 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000932 gc.collect()
933 gc.collect()
934
Thomas Woutersed03b412007-08-28 21:37:11 +0000935
Benjamin Peterson65c66ab2010-10-29 21:31:35 +0000936def python_is_optimized():
937 """Find if Python was built with optimizations."""
Antoine Pitrou64474542010-10-31 11:34:47 +0000938 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
Benjamin Peterson65c66ab2010-10-29 21:31:35 +0000939 final_opt = ""
940 for opt in cflags.split():
941 if opt.startswith('-O'):
942 final_opt = opt
943 return final_opt and final_opt != '-O0'
944
945
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000946#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000947# Decorator for running a function in a different locale, correctly resetting
948# it afterwards.
949
950def run_with_locale(catstr, *locales):
951 def decorator(func):
952 def inner(*args, **kwds):
953 try:
954 import locale
955 category = getattr(locale, catstr)
956 orig_locale = locale.setlocale(category)
957 except AttributeError:
958 # if the test author gives us an invalid category string
959 raise
960 except:
961 # cannot retrieve original locale, so do nothing
962 locale = orig_locale = None
963 else:
964 for loc in locales:
965 try:
966 locale.setlocale(category, loc)
967 break
968 except:
969 pass
970
971 # now run the function, resetting the locale on exceptions
972 try:
973 return func(*args, **kwds)
974 finally:
975 if locale and orig_locale:
976 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000977 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000978 inner.__doc__ = func.__doc__
979 return inner
980 return decorator
981
982#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000983# Big-memory-test support. Separate from 'resources' because memory use
984# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985
986# Some handy shorthands. Note that these are used for byte-limits as well
987# as size-limits, in the various bigmem tests
988_1M = 1024*1024
989_1G = 1024 * _1M
990_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000991_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000993MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994
Thomas Wouters477c8d52006-05-27 19:21:47 +0000995def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000997 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +0000998 sizes = {
999 'k': 1024,
1000 'm': _1M,
1001 'g': _1G,
1002 't': 1024*_1G,
1003 }
1004 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
1005 re.IGNORECASE | re.VERBOSE)
1006 if m is None:
1007 raise ValueError('Invalid memory limit %r' % (limit,))
1008 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001009 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001010 if memlimit > MAX_Py_ssize_t:
1011 memlimit = MAX_Py_ssize_t
1012 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013 raise ValueError('Memory limit %r too low to be useful' % (limit,))
1014 max_memuse = memlimit
1015
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001016def bigmemtest(minsize, memuse):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001017 """Decorator for bigmem tests.
1018
1019 'minsize' is the minimum useful size for the test (in arbitrary,
1020 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001021 the test, or a good estimate of it.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001022
1023 The decorator tries to guess a good value for 'size' and passes it to
1024 the decorated test function. If minsize * memuse is more than the
1025 allowed memory use (as defined by max_memuse), the test is skipped.
1026 Otherwise, minsize is adjusted upward to use up to max_memuse.
1027 """
1028 def decorator(f):
1029 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001030 # Retrieve values in case someone decided to adjust them
1031 minsize = wrapper.minsize
1032 memuse = wrapper.memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 if not max_memuse:
1034 # If max_memuse is 0 (the default),
1035 # we still want to run the tests with size set to a few kb,
1036 # to make sure they work. We still want to avoid using
1037 # too much memory, though, but we do that noisily.
1038 maxsize = 5147
Antoine Pitrou9dd11712011-01-12 21:40:20 +00001039 self.assertFalse(maxsize * memuse > 20 * _1M)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001040 else:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001041 maxsize = int(max_memuse / memuse)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001042 if maxsize < minsize:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001043 raise unittest.SkipTest(
1044 "not enough memory: %.1fG minimum needed"
1045 % (minsize * memuse / (1024 ** 3)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001046 return f(self, maxsize)
1047 wrapper.minsize = minsize
1048 wrapper.memuse = memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049 return wrapper
1050 return decorator
1051
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001052def precisionbigmemtest(size, memuse):
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001053 def decorator(f):
1054 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001055 size = wrapper.size
1056 memuse = wrapper.memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001057 if not real_max_memuse:
1058 maxsize = 5147
1059 else:
1060 maxsize = size
1061
1062 if real_max_memuse and real_max_memuse < maxsize * memuse:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001063 raise unittest.SkipTest(
1064 "not enough memory: %.1fG minimum needed"
1065 % (size * memuse / (1024 ** 3)))
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001066
1067 return f(self, maxsize)
1068 wrapper.size = size
1069 wrapper.memuse = memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001070 return wrapper
1071 return decorator
1072
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001073def bigaddrspacetest(f):
1074 """Decorator for tests that fill the address space."""
1075 def wrapper(self):
1076 if max_memuse < MAX_Py_ssize_t:
Antoine Pitrou98c62bd2011-01-12 21:58:39 +00001077 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
Antoine Pitroue0d3f8a2011-01-12 21:50:44 +00001078 raise unittest.SkipTest(
1079 "not enough memory: try a 32-bit build instead")
1080 else:
1081 raise unittest.SkipTest(
1082 "not enough memory: %.1fG minimum needed"
1083 % (MAX_Py_ssize_t / (1024 ** 3)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001084 else:
1085 return f(self)
1086 return wrapper
1087
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +00001089# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001090
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001091class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001092 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001093 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001094 test(result)
1095 return result
1096
Benjamin Petersone549ead2009-03-28 21:42:05 +00001097def _id(obj):
1098 return obj
1099
1100def requires_resource(resource):
Antoine Pitrou4914f9e2011-02-26 16:49:08 +00001101 if resource == 'gui' and not _is_gui_available():
1102 return unittest.skip("resource 'gui' is not available")
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +00001103 if is_resource_enabled(resource):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001104 return _id
1105 else:
1106 return unittest.skip("resource {0!r} is not enabled".format(resource))
1107
1108def cpython_only(test):
1109 """
1110 Decorator for tests only applicable on CPython.
1111 """
1112 return impl_detail(cpython=True)(test)
1113
1114def impl_detail(msg=None, **guards):
1115 if check_impl_detail(**guards):
1116 return _id
1117 if msg is None:
1118 guardnames, default = _parse_guards(guards)
1119 if default:
1120 msg = "implementation detail not available on {0}"
1121 else:
1122 msg = "implementation detail specific to {0}"
1123 guardnames = sorted(guardnames.keys())
1124 msg = msg.format(' or '.join(guardnames))
1125 return unittest.skip(msg)
1126
1127def _parse_guards(guards):
1128 # Returns a tuple ({platform_name: run_me}, default_value)
1129 if not guards:
1130 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +00001131 is_true = list(guards.values())[0]
1132 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001133 return (guards, not is_true)
1134
1135# Use the following check to guard CPython's implementation-specific tests --
1136# or to run them only on the implementation(s) guarded by the arguments.
1137def check_impl_detail(**guards):
1138 """This function returns True or False depending on the host platform.
1139 Examples:
1140 if check_impl_detail(): # only on CPython (default)
1141 if check_impl_detail(jython=True): # only on Jython
1142 if check_impl_detail(cpython=False): # everywhere except on CPython
1143 """
1144 guards, default = _parse_guards(guards)
1145 return guards.get(platform.python_implementation().lower(), default)
1146
1147
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001148
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001150 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001151 if verbose:
Victor Stinnerf58087b2010-05-02 17:24:51 +00001152 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001153 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001154 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001155
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001156 result = runner.run(suite)
1157 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001158 if len(result.errors) == 1 and not result.failures:
1159 err = result.errors[0][1]
1160 elif len(result.failures) == 1 and not result.errors:
1161 err = result.failures[0][1]
1162 else:
R. David Murray723357e2009-10-19 18:06:17 +00001163 err = "multiple errors occurred"
1164 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001165 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001166
Barry Warsawc10d6902001-09-20 06:30:41 +00001167
Walter Dörwald21d3a322003-05-01 17:45:56 +00001168def run_unittest(*classes):
1169 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001171 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001172 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001173 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174 if cls in sys.modules:
1175 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1176 else:
1177 raise ValueError("str arguments must be keys in sys.modules")
1178 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001179 suite.addTest(cls)
1180 else:
1181 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001182 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001183
Barry Warsawc10d6902001-09-20 06:30:41 +00001184
Tim Petersa0a62222001-09-09 06:12:01 +00001185#=======================================================================
1186# doctest driver.
1187
1188def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +00001189 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001190
1191 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001192 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001193 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001194 """
1195
1196 import doctest
1197
1198 if verbosity is None:
1199 verbosity = verbose
1200 else:
1201 verbosity = None
1202
Tim Peters342ca752001-09-25 19:13:20 +00001203 # Direct doctest output (normally just errors) to real stdout; doctest
1204 # output shouldn't be compared by regrtest.
1205 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +00001206 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +00001207 try:
1208 f, t = doctest.testmod(module, verbose=verbosity)
1209 if f:
1210 raise TestFailed("%d of %d doctests failed" % (f, t))
1211 finally:
1212 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001213 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001214 print('doctest (%s) ... %d tests with zero failures' %
1215 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001216 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001217
Antoine Pitrou060cee22009-11-13 16:29:04 +00001218
1219#=======================================================================
1220# Support for saving and restoring the imported modules.
1221
1222def modules_setup():
1223 return sys.modules.copy(),
1224
1225def modules_cleanup(oldmodules):
1226 # Encoders/decoders are registered permanently within the internal
1227 # codec cache. If we destroy the corresponding modules their
1228 # globals will be set to None which will trip up the cached functions.
1229 encodings = [(k, v) for k, v in sys.modules.items()
1230 if k.startswith('encodings.')]
1231 sys.modules.clear()
1232 sys.modules.update(encodings)
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001233 # XXX: This kind of problem can affect more than just encodings. In particular
Eric Smitha3e8f3d2011-01-11 10:24:34 +00001234 # extension modules (such as _ssl) don't cope with reloading properly.
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001235 # Really, test modules should be cleaning out the test specific modules they
1236 # know they added (ala test_runpy) rather than relying on this function (as
1237 # test_importhooks and test_pkg do currently).
1238 # Implicitly imported *real* modules should be left alone (see issue 10556).
Antoine Pitrou060cee22009-11-13 16:29:04 +00001239 sys.modules.update(oldmodules)
1240
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001241#=======================================================================
1242# Threading support to prevent reporting refleaks when running regrtest.py -R
1243
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001244# NOTE: we use thread._count() rather than threading.enumerate() (or the
1245# moral equivalent thereof) because a threading.Thread object is still alive
1246# until its __bootstrap() method has returned, even after it has been
1247# unregistered from the threading module.
1248# thread._count(), on the other hand, only gets decremented *after* the
1249# __bootstrap() method has returned, which gives us reliable reference counts
1250# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001251
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001252def threading_setup():
Victor Stinner45df8202010-04-28 22:31:17 +00001253 if _thread:
1254 return _thread._count(),
1255 else:
1256 return 1,
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001257
1258def threading_cleanup(nb_threads):
Victor Stinner45df8202010-04-28 22:31:17 +00001259 if not _thread:
1260 return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001261 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001262 for count in range(_MAX_COUNT):
1263 n = _thread._count()
1264 if n == nb_threads:
1265 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001266 time.sleep(0.1)
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001267 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001268
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001269def reap_threads(func):
Victor Stinner45df8202010-04-28 22:31:17 +00001270 """Use this function when threads are being used. This will
1271 ensure that the threads are cleaned up even when the test fails.
1272 If threading is unavailable this function does nothing.
1273 """
1274 if not _thread:
1275 return func
1276
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001277 @functools.wraps(func)
1278 def decorator(*args):
1279 key = threading_setup()
1280 try:
1281 return func(*args)
1282 finally:
1283 threading_cleanup(*key)
1284 return decorator
1285
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001286def reap_children():
1287 """Use this function at the end of test_main() whenever sub-processes
1288 are started. This will help ensure that no extra children (zombies)
1289 stick around to hog resources and create problems when looking
1290 for refleaks.
1291 """
1292
1293 # Reap all our dead child processes so we don't leave zombies around.
1294 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001295 if hasattr(os, 'waitpid'):
1296 any_process = -1
1297 while True:
1298 try:
1299 # This will raise an exception on Windows. That's ok.
1300 pid, status = os.waitpid(any_process, os.WNOHANG)
1301 if pid == 0:
1302 break
1303 except:
1304 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001305
1306@contextlib.contextmanager
1307def swap_attr(obj, attr, new_val):
1308 """Temporary swap out an attribute with a new object.
1309
1310 Usage:
1311 with swap_attr(obj, "attr", 5):
1312 ...
1313
1314 This will set obj.attr to 5 for the duration of the with: block,
1315 restoring the old value at the end of the block. If `attr` doesn't
1316 exist on `obj`, it will be created and then deleted at the end of the
1317 block.
1318 """
1319 if hasattr(obj, attr):
1320 real_val = getattr(obj, attr)
1321 setattr(obj, attr, new_val)
1322 try:
1323 yield
1324 finally:
1325 setattr(obj, attr, real_val)
1326 else:
1327 setattr(obj, attr, new_val)
1328 try:
1329 yield
1330 finally:
1331 delattr(obj, attr)
1332
1333@contextlib.contextmanager
1334def swap_item(obj, item, new_val):
1335 """Temporary swap out an item with a new object.
1336
1337 Usage:
1338 with swap_item(obj, "item", 5):
1339 ...
1340
1341 This will set obj["item"] to 5 for the duration of the with: block,
1342 restoring the old value at the end of the block. If `item` doesn't
1343 exist on `obj`, it will be created and then deleted at the end of the
1344 block.
1345 """
1346 if item in obj:
1347 real_val = obj[item]
1348 obj[item] = new_val
1349 try:
1350 yield
1351 finally:
1352 obj[item] = real_val
1353 else:
1354 obj[item] = new_val
1355 try:
1356 yield
1357 finally:
1358 del obj[item]
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00001359
1360def strip_python_stderr(stderr):
1361 """Strip the stderr of a Python process from potential debug output
1362 emitted by the interpreter.
1363
1364 This will typically be run on the result of the communicate() method
1365 of a subprocess.Popen object.
1366 """
1367 stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
1368 return stderr
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00001369
1370def args_from_interpreter_flags():
1371 """Return a list of command-line arguments reproducing the current
1372 settings in sys.flags."""
1373 flag_opt_map = {
1374 'bytes_warning': 'b',
1375 'dont_write_bytecode': 'B',
1376 'ignore_environment': 'E',
1377 'no_user_site': 's',
1378 'no_site': 'S',
1379 'optimize': 'O',
1380 'verbose': 'v',
1381 }
1382 args = []
1383 for flag, opt in flag_opt_map.items():
1384 v = getattr(sys.flags, flag)
1385 if v > 0:
1386 args.append('-' + opt * v)
1387 return args
Vinay Sajip129fd042010-12-10 08:19:38 +00001388
1389#============================================================
1390# Support for assertions about logging.
1391#============================================================
1392
1393class TestHandler(logging.handlers.BufferingHandler):
1394 def __init__(self, matcher):
1395 # BufferingHandler takes a "capacity" argument
1396 # so as to know when to flush. As we're overriding
1397 # shouldFlush anyway, we can set a capacity of zero.
1398 # You can call flush() manually to clear out the
1399 # buffer.
1400 logging.handlers.BufferingHandler.__init__(self, 0)
1401 self.matcher = matcher
1402
1403 def shouldFlush(self):
1404 return False
1405
1406 def emit(self, record):
1407 self.format(record)
1408 self.buffer.append(record.__dict__)
1409
1410 def matches(self, **kwargs):
1411 """
1412 Look for a saved dict whose keys/values match the supplied arguments.
1413 """
1414 result = False
1415 for d in self.buffer:
1416 if self.matcher.matches(d, **kwargs):
1417 result = True
1418 break
1419 return result
1420
1421class Matcher(object):
1422
1423 _partial_matches = ('msg', 'message')
1424
1425 def matches(self, d, **kwargs):
1426 """
1427 Try to match a single dict with the supplied arguments.
1428
1429 Keys whose values are strings and which are in self._partial_matches
1430 will be checked for partial (i.e. substring) matches. You can extend
1431 this scheme to (for example) do regular expression matching, etc.
1432 """
1433 result = True
1434 for k in kwargs:
1435 v = kwargs[k]
1436 dv = d.get(k)
1437 if not self.match_value(k, dv, v):
1438 result = False
1439 break
1440 return result
1441
1442 def match_value(self, k, dv, v):
1443 """
1444 Try to match a single stored value (dv) with a supplied value (v).
1445 """
1446 if type(v) != type(dv):
1447 result = False
1448 elif type(dv) is not str or k not in self._partial_matches:
1449 result = (v == dv)
1450 else:
1451 result = dv.find(v) >= 0
1452 return result
Brian Curtin3b4499c2010-12-28 14:31:47 +00001453
1454
1455_can_symlink = None
1456def can_symlink():
1457 global _can_symlink
1458 if _can_symlink is not None:
1459 return _can_symlink
1460 try:
1461 os.symlink(TESTFN, TESTFN + "can_symlink")
1462 can = True
Brian Curtin57160d72010-12-29 02:04:28 +00001463 except (OSError, NotImplementedError):
Brian Curtin3b4499c2010-12-28 14:31:47 +00001464 can = False
1465 _can_symlink = can
1466 return can
1467
1468def skip_unless_symlink(test):
1469 """Skip decorator for tests that require functional symlink"""
1470 ok = can_symlink()
1471 msg = "Requires functional symlink implementation"
1472 return test if ok else unittest.skip(msg)(test)
Antoine Pitroue8706232011-03-15 21:05:36 +01001473
Antoine Pitrou2c50a092011-03-15 21:02:59 +01001474def patch(test_instance, object_to_patch, attr_name, new_value):
1475 """Override 'object_to_patch'.'attr_name' with 'new_value'.
1476
1477 Also, add a cleanup procedure to 'test_instance' to restore
1478 'object_to_patch' value for 'attr_name'.
1479 The 'attr_name' should be a valid attribute for 'object_to_patch'.
1480
1481 """
1482 # check that 'attr_name' is a real attribute for 'object_to_patch'
1483 # will raise AttributeError if it does not exist
1484 getattr(object_to_patch, attr_name)
1485
1486 # keep a copy of the old value
1487 attr_is_local = False
1488 try:
1489 old_value = object_to_patch.__dict__[attr_name]
1490 except (AttributeError, KeyError):
1491 old_value = getattr(object_to_patch, attr_name, None)
1492 else:
1493 attr_is_local = True
1494
1495 # restore the value when the test is done
1496 def cleanup():
1497 if attr_is_local:
1498 setattr(object_to_patch, attr_name, old_value)
1499 else:
1500 delattr(object_to_patch, attr_name)
1501
1502 test_instance.addCleanup(cleanup)
1503
1504 # actually override the attribute
1505 setattr(object_to_patch, attr_name, new_value)