blob: cab366b09bdd46322340f33ee0072f22a6aa7fba [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 Heimes23daade2008-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 Return True if the module was in sys.modules, False otherwise.
96 Raise ImportError if the module can't be imported."""
Nick Coghlan47384702009-04-22 16:13:36 +000097 saved = True
98 try:
99 orig_modules[name] = sys.modules[name]
100 except KeyError:
Ezio Melotti199e0852011-05-09 06:41:55 +0300101 # try to import the module and raise an error if it can't be imported
102 __import__(name)
Nick Coghlan47384702009-04-22 16:13:36 +0000103 saved = False
104 else:
105 del sys.modules[name]
106 return saved
107
108
109def _save_and_block_module(name, orig_modules):
110 """Helper function to save and block a module in sys.modules
111
Ezio Melotti199e0852011-05-09 06:41:55 +0300112 Return True if the module was in sys.modules, False otherwise."""
Nick Coghlan47384702009-04-22 16:13:36 +0000113 saved = True
114 try:
115 orig_modules[name] = sys.modules[name]
116 except KeyError:
117 saved = False
Alexander Belopolsky903396e2010-07-13 14:50:16 +0000118 sys.modules[name] = None
Nick Coghlan47384702009-04-22 16:13:36 +0000119 return saved
120
121
122def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
Nick Coghlanfce769e2009-04-11 14:30:59 +0000123 """Imports and returns a module, deliberately bypassing the sys.modules cache
124 and importing a fresh copy of the module. Once the import is complete,
125 the sys.modules cache is restored to its original state.
126
Nick Coghlan47384702009-04-22 16:13:36 +0000127 Modules named in fresh are also imported anew if needed by the import.
Ezio Melotti199e0852011-05-09 06:41:55 +0300128 If one of these modules can't be imported, None is returned.
Nick Coghlan47384702009-04-22 16:13:36 +0000129
130 Importing of modules named in blocked is prevented while the fresh import
Nick Coghlanfce769e2009-04-11 14:30:59 +0000131 takes place.
132
133 If deprecated is True, any module or package deprecation messages
134 will be suppressed."""
135 # NOTE: test_heapq and test_warnings include extra sanity checks to make
136 # sure that this utility function is working as expected
137 with _ignore_deprecated_imports(deprecated):
Nick Coghlan47384702009-04-22 16:13:36 +0000138 # Keep track of modules saved for later restoration as well
139 # as those which just need a blocking entry removed
Nick Coghlanfce769e2009-04-11 14:30:59 +0000140 orig_modules = {}
Nick Coghlan47384702009-04-22 16:13:36 +0000141 names_to_remove = []
142 _save_and_remove_module(name, orig_modules)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000143 try:
Nick Coghlan47384702009-04-22 16:13:36 +0000144 for fresh_name in fresh:
145 _save_and_remove_module(fresh_name, orig_modules)
146 for blocked_name in blocked:
147 if not _save_and_block_module(blocked_name, orig_modules):
148 names_to_remove.append(blocked_name)
149 fresh_module = importlib.import_module(name)
Ezio Melotti199e0852011-05-09 06:41:55 +0300150 except ImportError:
151 fresh_module = None
Nick Coghlanfce769e2009-04-11 14:30:59 +0000152 finally:
Nick Coghlan47384702009-04-22 16:13:36 +0000153 for orig_name, module in orig_modules.items():
154 sys.modules[orig_name] = module
155 for name_to_remove in names_to_remove:
156 del sys.modules[name_to_remove]
157 return fresh_module
Nick Coghlanfce769e2009-04-11 14:30:59 +0000158
Benjamin Peterson699adb92008-05-08 22:27:58 +0000159
R. David Murraya21e4ca2009-03-31 23:16:50 +0000160def get_attribute(obj, name):
161 """Get an attribute, raising SkipTest if AttributeError is raised."""
162 try:
163 attribute = getattr(obj, name)
164 except AttributeError:
165 raise unittest.SkipTest("module %s has no attribute %s" % (
166 obj.__name__, name))
167 else:
168 return attribute
169
Barry Warsawc0fb6052001-08-20 22:29:23 +0000170verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +0000171use_resources = None # Flag set to [] by regrtest.py
172max_memuse = 0 # Disable bigmem tests (they will still be run with
173 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000174real_max_memuse = 0
Guido van Rossum531661c1996-12-20 02:58:22 +0000175
Tim Peters8dee8092001-09-25 20:05:11 +0000176# _original_stdout is meant to hold stdout at the time regrtest began.
177# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
178# The point is to have some flavor of stdout the user can actually see.
179_original_stdout = None
180def record_original_stdout(stdout):
181 global _original_stdout
182 _original_stdout = stdout
183
184def get_original_stdout():
185 return _original_stdout or sys.stdout
186
Guido van Rossum3bead091992-01-27 17:00:37 +0000187def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +0000188 try:
189 del sys.modules[name]
190 except KeyError:
191 pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000192
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000193def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000194 try:
195 os.unlink(filename)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000196 except OSError as error:
197 # The filename need not exist.
Michael Foord2d9c2d52010-05-04 22:29:10 +0000198 if error.errno not in (errno.ENOENT, errno.ENOTDIR):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000199 raise
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000200
Christian Heimes23daade2008-02-25 12:39:23 +0000201def rmtree(path):
202 try:
203 shutil.rmtree(path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000204 except OSError as error:
Christian Heimes23daade2008-02-25 12:39:23 +0000205 # Unix returns ENOENT, Windows returns ESRCH.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000206 if error.errno not in (errno.ENOENT, errno.ESRCH):
Christian Heimes23daade2008-02-25 12:39:23 +0000207 raise
208
Barry Warsaw28a691b2010-04-17 00:19:56 +0000209def make_legacy_pyc(source):
210 """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.
211
212 The choice of .pyc or .pyo extension is done based on the __debug__ flag
213 value.
214
215 :param source: The file system path to the source file. The source file
216 does not need to exist, however the PEP 3147 pyc file must exist.
217 :return: The file system path to the legacy pyc file.
218 """
219 pyc_file = imp.cache_from_source(source)
220 up_one = os.path.dirname(os.path.abspath(source))
221 legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
222 os.rename(pyc_file, legacy_pyc)
223 return legacy_pyc
224
Guido van Rossum3bead091992-01-27 17:00:37 +0000225def forget(modname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000226 """'Forget' a module was ever imported.
227
228 This removes the module from sys.modules and deletes any PEP 3147 or
229 legacy .pyc and .pyo files.
230 """
Fred Drake004d5e62000-10-23 17:22:08 +0000231 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000232 for dirname in sys.path:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000233 source = os.path.join(dirname, modname + '.py')
234 # It doesn't matter if they exist or not, unlink all possible
235 # combinations of PEP 3147 and legacy pyc and pyo files.
236 unlink(source + 'c')
237 unlink(source + 'o')
238 unlink(imp.cache_from_source(source, debug_override=True))
239 unlink(imp.cache_from_source(source, debug_override=False))
Guido van Rossum3bead091992-01-27 17:00:37 +0000240
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000241# On some platforms, should not run gui test even if it is allowed
242# in `use_resources'.
243if sys.platform.startswith('win'):
244 import ctypes
245 import ctypes.wintypes
246 def _is_gui_available():
247 UOI_FLAGS = 1
248 WSF_VISIBLE = 0x0001
249 class USEROBJECTFLAGS(ctypes.Structure):
250 _fields_ = [("fInherit", ctypes.wintypes.BOOL),
251 ("fReserved", ctypes.wintypes.BOOL),
252 ("dwFlags", ctypes.wintypes.DWORD)]
253 dll = ctypes.windll.user32
254 h = dll.GetProcessWindowStation()
255 if not h:
256 raise ctypes.WinError()
257 uof = USEROBJECTFLAGS()
258 needed = ctypes.wintypes.DWORD()
259 res = dll.GetUserObjectInformationW(h,
260 UOI_FLAGS,
261 ctypes.byref(uof),
262 ctypes.sizeof(uof),
263 ctypes.byref(needed))
264 if not res:
265 raise ctypes.WinError()
266 return bool(uof.dwFlags & WSF_VISIBLE)
267else:
268 def _is_gui_available():
269 return True
270
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000271def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000272 """Test whether a resource is enabled. Known resources are set by
273 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000274 return use_resources is not None and resource in use_resources
275
Barry Warsawc0fb6052001-08-20 22:29:23 +0000276def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000277 """Raise ResourceDenied if the specified resource is not available.
278
279 If the caller's module is __main__ then automatically return True. The
Barry Warsaw28a691b2010-04-17 00:19:56 +0000280 possibility of False being returned occurs when regrtest.py is
281 executing.
282 """
Antoine Pitrou4914f9e2011-02-26 16:49:08 +0000283 if resource == 'gui' and not _is_gui_available():
284 raise unittest.SkipTest("Cannot use the 'gui' resource")
Skip Montanarod839ecd2003-04-24 19:06:57 +0000285 # see if the caller's module is __main__ - if so, treat as if
286 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000287 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000288 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000289 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000290 if msg is None:
291 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000292 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000293
Christian Heimes5e696852008-04-09 08:37:03 +0000294HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000295
Christian Heimes5e696852008-04-09 08:37:03 +0000296def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
297 """Returns an unused port that should be suitable for binding. This is
298 achieved by creating a temporary socket with the same family and type as
299 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
300 the specified host address (defaults to 0.0.0.0) with the port set to 0,
301 eliciting an unused ephemeral port from the OS. The temporary socket is
302 then closed and deleted, and the ephemeral port is returned.
303
304 Either this method or bind_port() should be used for any tests where a
305 server socket needs to be bound to a particular port for the duration of
306 the test. Which one to use depends on whether the calling code is creating
307 a python socket, or if an unused port needs to be provided in a constructor
308 or passed to an external program (i.e. the -accept argument to openssl's
309 s_server mode). Always prefer bind_port() over find_unused_port() where
310 possible. Hard coded ports should *NEVER* be used. As soon as a server
311 socket is bound to a hard coded port, the ability to run multiple instances
312 of the test simultaneously on the same host is compromised, which makes the
313 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
314 may simply manifest as a failed test, which can be recovered from without
315 intervention in most cases, but on Windows, the entire python process can
316 completely and utterly wedge, requiring someone to log in to the buildbot
317 and manually kill the affected process.
318
319 (This is easy to reproduce on Windows, unfortunately, and can be traced to
320 the SO_REUSEADDR socket option having different semantics on Windows versus
321 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
322 listen and then accept connections on identical host/ports. An EADDRINUSE
323 socket.error will be raised at some point (depending on the platform and
324 the order bind and listen were called on each socket).
325
326 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
327 will ever be raised when attempting to bind two identical host/ports. When
328 accept() is called on each socket, the second caller's process will steal
329 the port from the first caller, leaving them both in an awkwardly wedged
330 state where they'll no longer respond to any signals or graceful kills, and
331 must be forcibly killed via OpenProcess()/TerminateProcess().
332
333 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
334 instead of SO_REUSEADDR, which effectively affords the same semantics as
335 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
336 Source world compared to Windows ones, this is a common mistake. A quick
337 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
338 openssl.exe is called with the 's_server' option, for example. See
339 http://bugs.python.org/issue2550 for more info. The following site also
340 has a very thorough description about the implications of both REUSEADDR
341 and EXCLUSIVEADDRUSE on Windows:
342 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
343
344 XXX: although this approach is a vast improvement on previous attempts to
345 elicit unused ports, it rests heavily on the assumption that the ephemeral
346 port returned to us by the OS won't immediately be dished back out to some
347 other process when we close and delete our temporary socket but before our
348 calling code has a chance to bind the returned port. We can deal with this
349 issue if/when we come across it.
350 """
351
352 tempsock = socket.socket(family, socktype)
353 port = bind_port(tempsock)
354 tempsock.close()
355 del tempsock
356 return port
357
358def bind_port(sock, host=HOST):
359 """Bind the socket to a free port and return the port number. Relies on
360 ephemeral ports in order to ensure we are using an unbound port. This is
361 important as many tests may be running simultaneously, especially in a
362 buildbot environment. This method raises an exception if the sock.family
363 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
364 or SO_REUSEPORT set on it. Tests should *never* set these socket options
365 for TCP/IP sockets. The only case for setting these options is testing
366 multicasting via multiple UDP sockets.
367
368 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
369 on Windows), it will be set on the socket. This will prevent anyone else
370 from bind()'ing to our host/port for the duration of the test.
371 """
372
373 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
374 if hasattr(socket, 'SO_REUSEADDR'):
375 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
376 raise TestFailed("tests should never set the SO_REUSEADDR " \
377 "socket option on TCP/IP sockets!")
378 if hasattr(socket, 'SO_REUSEPORT'):
379 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
380 raise TestFailed("tests should never set the SO_REUSEPORT " \
381 "socket option on TCP/IP sockets!")
382 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
383 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
384
385 sock.bind((host, 0))
386 port = sock.getsockname()[1]
387 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000388
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000389FUZZ = 1e-6
390
391def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000392 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000393 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000394 fuzz = (abs(x) + abs(y)) * FUZZ
395 if abs(x-y) <= fuzz:
396 return 0
397 except:
398 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000399 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000400 for i in range(min(len(x), len(y))):
401 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000402 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000403 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000404 return (len(x) > len(y)) - (len(x) < len(y))
405 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000406
Eric Smithf24a0d92010-12-04 13:32:18 +0000407# decorator for skipping tests on non-IEEE 754 platforms
408requires_IEEE_754 = unittest.skipUnless(
409 float.__getformat__("double").startswith("IEEE"),
410 "test requires IEEE 754 doubles")
411
Finn Bock57bc5fa2002-11-01 18:02:03 +0000412is_jython = sys.platform.startswith('java')
413
Barry Warsaw559f6682001-03-23 18:04:02 +0000414# Filename used for testing
415if os.name == 'java':
416 # Jython disallows @ in module names
417 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000418else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000419 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000420
Antoine Pitrou88909542009-06-29 13:54:42 +0000421# Disambiguate TESTFN for parallel testing, while letting it remain a valid
422# module name.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000423TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
Antoine Pitrou88909542009-06-29 13:54:42 +0000424
Michael Foord2d9c2d52010-05-04 22:29:10 +0000425
Victor Stinnerd91df1a2010-08-18 10:56:19 +0000426# TESTFN_UNICODE is a non-ascii filename
427TESTFN_UNICODE = TESTFN + "-\xe0\xf2\u0258\u0141\u011f"
Victor Stinner74a833f2010-08-18 21:06:23 +0000428if sys.platform == 'darwin':
429 # In Mac OS X's VFS API file names are, by definition, canonically
430 # decomposed Unicode, encoded using UTF-8. See QA1173:
431 # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
432 import unicodedata
433 TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE)
Antoine Pitrou88909542009-06-29 13:54:42 +0000434TESTFN_ENCODING = sys.getfilesystemencoding()
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000435
Victor Stinner09c449c2010-08-13 22:23:24 +0000436# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000437# encoded by the filesystem encoding (in strict mode). It can be None if we
438# cannot generate such filename.
Victor Stinnera0241c82010-08-15 19:28:21 +0000439TESTFN_UNENCODABLE = None
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000440if os.name in ('nt', 'ce'):
Victor Stinnera0241c82010-08-15 19:28:21 +0000441 # skip win32s (0) or Windows 9x/ME (1)
442 if sys.getwindowsversion().platform >= 2:
Victor Stinner8ce7df62010-09-10 11:19:59 +0000443 # Different kinds of characters from various languages to minimize the
444 # probability that the whole name is encodable to MBCS (issue #9819)
445 TESTFN_UNENCODABLE = TESTFN + "-\u5171\u0141\u2661\u0363\uDC80"
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000446 try:
Victor Stinner09c449c2010-08-13 22:23:24 +0000447 TESTFN_UNENCODABLE.encode(TESTFN_ENCODING)
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000448 except UnicodeEncodeError:
449 pass
450 else:
451 print('WARNING: The filename %r CAN be encoded by the filesystem encoding (%s). '
452 'Unicode filename tests may not be effective'
Victor Stinner09c449c2010-08-13 22:23:24 +0000453 % (TESTFN_UNENCODABLE, TESTFN_ENCODING))
454 TESTFN_UNENCODABLE = None
Victor Stinnera0241c82010-08-15 19:28:21 +0000455# Mac OS X denies unencodable filenames (invalid utf-8)
Victor Stinner03c9e1d2010-08-14 17:35:20 +0000456elif sys.platform != 'darwin':
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000457 try:
458 # ascii and utf-8 cannot encode the byte 0xff
459 b'\xff'.decode(TESTFN_ENCODING)
460 except UnicodeDecodeError:
461 # 0xff will be encoded using the surrogate character u+DCFF
Victor Stinner09c449c2010-08-13 22:23:24 +0000462 TESTFN_UNENCODABLE = TESTFN \
Victor Stinner3d85a6f2010-08-13 13:02:04 +0000463 + b'-\xff'.decode(TESTFN_ENCODING, 'surrogateescape')
464 else:
465 # File system encoding (eg. ISO-8859-* encodings) can encode
466 # the byte 0xff. Skip some unicode filename tests.
Victor Stinnera0241c82010-08-15 19:28:21 +0000467 pass
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000468
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000469# Save the initial cwd
470SAVEDCWD = os.getcwd()
471
472@contextlib.contextmanager
Nick Coghland26c18a2010-08-17 13:06:11 +0000473def temp_cwd(name='tempcwd', quiet=False, path=None):
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000474 """
Nick Coghland26c18a2010-08-17 13:06:11 +0000475 Context manager that temporarily changes the CWD.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000476
Nick Coghland26c18a2010-08-17 13:06:11 +0000477 An existing path may be provided as *path*, in which case this
478 function makes no changes to the file system.
479
480 Otherwise, the new CWD is created in the current directory and it's
481 named *name*. If *quiet* is False (default) and it's not possible to
482 create or change the CWD, an error is raised. If it's True, only a
483 warning is raised and the original CWD is used.
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000484 """
485 saved_dir = os.getcwd()
486 is_temporary = False
Nick Coghland26c18a2010-08-17 13:06:11 +0000487 if path is None:
488 path = name
489 try:
490 os.mkdir(name)
491 is_temporary = True
492 except OSError:
493 if not quiet:
494 raise
495 warnings.warn('tests may fail, unable to create temp CWD ' + name,
496 RuntimeWarning, stacklevel=3)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000497 try:
Nick Coghland26c18a2010-08-17 13:06:11 +0000498 os.chdir(path)
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000499 except OSError:
500 if not quiet:
501 raise
502 warnings.warn('tests may fail, unable to change the CWD to ' + name,
503 RuntimeWarning, stacklevel=3)
504 try:
505 yield os.getcwd()
506 finally:
507 os.chdir(saved_dir)
508 if is_temporary:
509 rmtree(name)
510
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000511
Barry Warsaw28a691b2010-04-17 00:19:56 +0000512@contextlib.contextmanager
513def temp_umask(umask):
514 """Context manager that temporarily sets the process umask."""
515 oldmask = os.umask(umask)
516 try:
517 yield
518 finally:
519 os.umask(oldmask)
520
521
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000522def findfile(file, here=__file__, subdir=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000523 """Try to find a file on sys.path and the working directory. If it is not
524 found the argument passed to the function is returned (this does not
525 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000526 if os.path.isabs(file):
527 return file
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000528 if subdir is not None:
529 file = os.path.join(subdir, file)
Fred Drake004d5e62000-10-23 17:22:08 +0000530 path = sys.path
531 path = [os.path.dirname(here)] + path
532 for dn in path:
533 fn = os.path.join(dn, file)
534 if os.path.exists(fn): return fn
535 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000536
Tim Peters2f228e72001-05-13 00:19:31 +0000537def sortdict(dict):
538 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000539 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000540 reprpairs = ["%r: %r" % pair for pair in items]
541 withcommas = ", ".join(reprpairs)
542 return "{%s}" % withcommas
543
Benjamin Peterson7522c742009-01-19 21:00:09 +0000544def make_bad_fd():
545 """
546 Create an invalid file descriptor by opening and closing a file and return
547 its fd.
548 """
549 file = open(TESTFN, "wb")
550 try:
551 return file.fileno()
552 finally:
553 file.close()
554 unlink(TESTFN)
555
Thomas Wouters89f507f2006-12-13 04:49:30 +0000556def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000557 testcase.assertRaises(SyntaxError, compile, statement,
558 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000559
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000560def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000561 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000562
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000563 check = kw.pop('check', None)
564
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000565 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000566
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000567 fn = os.path.join(os.path.dirname(__file__), "data", filename)
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000568
569 def check_valid_file(fn):
570 f = open(fn, *args, **kw)
571 if check is None:
572 return f
573 elif check(f):
574 f.seek(0)
575 return f
576 f.close()
577
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +0000578 if os.path.exists(fn):
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000579 f = check_valid_file(fn)
580 if f is not None:
581 return f
582 unlink(fn)
583
584 # Verify the requirement before downloading the file
585 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000586
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000587 print('\tfetching %s ...' % url, file=get_original_stdout())
Antoine Pitroufd0680b2009-11-01 22:13:48 +0000588 f = urllib.request.urlopen(url, timeout=15)
589 try:
590 with open(fn, "wb") as out:
591 s = f.read()
592 while s:
593 out.write(s)
594 s = f.read()
595 finally:
596 f.close()
Florent Xiclunaf089fd62010-03-19 14:25:03 +0000597
598 f = check_valid_file(fn)
599 if f is not None:
600 return f
601 raise TestFailed('invalid resource "%s"' % fn)
602
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000603
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000604class WarningsRecorder(object):
605 """Convenience wrapper for the warnings list returned on
606 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000608 def __init__(self, warnings_list):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000609 self._warnings = warnings_list
610 self._last = 0
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000611
612 def __getattr__(self, attr):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000613 if len(self._warnings) > self._last:
614 return getattr(self._warnings[-1], attr)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000615 elif attr in warnings.WarningMessage._WARNING_DETAILS:
616 return None
617 raise AttributeError("%r has no attribute %r" % (self, attr))
618
Florent Xiclunab14930c2010-03-13 15:26:44 +0000619 @property
620 def warnings(self):
621 return self._warnings[self._last:]
622
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000623 def reset(self):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000624 self._last = len(self._warnings)
625
626
627def _filterwarnings(filters, quiet=False):
628 """Catch the warnings, then check if all the expected
629 warnings have been raised and re-raise unexpected warnings.
630 If 'quiet' is True, only re-raise the unexpected warnings.
631 """
632 # Clear the warning registry of the calling module
633 # in order to re-raise the warnings.
634 frame = sys._getframe(2)
635 registry = frame.f_globals.get('__warningregistry__')
636 if registry:
637 registry.clear()
638 with warnings.catch_warnings(record=True) as w:
639 # Set filter "always" to record all warnings. Because
640 # test_warnings swap the module, we need to look up in
641 # the sys.modules dictionary.
642 sys.modules['warnings'].simplefilter("always")
643 yield WarningsRecorder(w)
644 # Filter the recorded warnings
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000645 reraise = list(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000646 missing = []
647 for msg, cat in filters:
648 seen = False
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000649 for w in reraise[:]:
650 warning = w.message
Florent Xiclunab14930c2010-03-13 15:26:44 +0000651 # Filter out the matching messages
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000652 if (re.match(msg, str(warning), re.I) and
653 issubclass(warning.__class__, cat)):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000654 seen = True
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000655 reraise.remove(w)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000656 if not seen and not quiet:
657 # This filter caught nothing
658 missing.append((msg, cat.__name__))
659 if reraise:
Antoine Pitrou31e08a42010-10-29 11:54:03 +0000660 raise AssertionError("unhandled warning %s" % reraise[0])
Florent Xiclunab14930c2010-03-13 15:26:44 +0000661 if missing:
662 raise AssertionError("filter (%r, %s) did not catch any warning" %
663 missing[0])
664
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000665
666@contextlib.contextmanager
Florent Xiclunab14930c2010-03-13 15:26:44 +0000667def check_warnings(*filters, **kwargs):
668 """Context manager to silence warnings.
669
670 Accept 2-tuples as positional arguments:
671 ("message regexp", WarningCategory)
672
673 Optional argument:
674 - if 'quiet' is True, it does not fail if a filter catches nothing
Florent Xicluna53b506b2010-03-18 20:00:57 +0000675 (default True without argument,
676 default False if some filters are defined)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000677
678 Without argument, it defaults to:
Florent Xicluna53b506b2010-03-18 20:00:57 +0000679 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000680 """
Florent Xicluna53b506b2010-03-18 20:00:57 +0000681 quiet = kwargs.get('quiet')
Florent Xiclunab14930c2010-03-13 15:26:44 +0000682 if not filters:
683 filters = (("", Warning),)
Florent Xicluna53b506b2010-03-18 20:00:57 +0000684 # Preserve backward compatibility
685 if quiet is None:
686 quiet = True
687 return _filterwarnings(filters, quiet)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000688
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000689
690class CleanImport(object):
691 """Context manager to force import to return a new module reference.
692
693 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000694 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000695
696 Use like this:
697
698 with CleanImport("foo"):
Brett Cannonddb5e702010-02-03 22:16:11 +0000699 importlib.import_module("foo") # new reference
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000700 """
701
702 def __init__(self, *module_names):
703 self.original_modules = sys.modules.copy()
704 for module_name in module_names:
705 if module_name in sys.modules:
706 module = sys.modules[module_name]
707 # It is possible that module_name is just an alias for
708 # another module (e.g. stub for modules renamed in 3.x).
709 # In that case, we also need delete the real module to clear
710 # the import cache.
711 if module.__name__ != module_name:
712 del sys.modules[module.__name__]
713 del sys.modules[module_name]
714
715 def __enter__(self):
716 return self
717
718 def __exit__(self, *ignore_exc):
719 sys.modules.update(self.original_modules)
720
721
Walter Dörwald155374d2009-05-01 19:58:58 +0000722class EnvironmentVarGuard(collections.MutableMapping):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000723
724 """Class to help protect the environment variable properly. Can be used as
725 a context manager."""
726
727 def __init__(self):
Walter Dörwald155374d2009-05-01 19:58:58 +0000728 self._environ = os.environ
Walter Dörwald4ba80132009-04-25 12:48:43 +0000729 self._changed = {}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000730
Walter Dörwald155374d2009-05-01 19:58:58 +0000731 def __getitem__(self, envvar):
732 return self._environ[envvar]
733
734 def __setitem__(self, envvar, value):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000735 # Remember the initial value on the first access
736 if envvar not in self._changed:
Walter Dörwald155374d2009-05-01 19:58:58 +0000737 self._changed[envvar] = self._environ.get(envvar)
738 self._environ[envvar] = value
739
740 def __delitem__(self, envvar):
741 # Remember the initial value on the first access
742 if envvar not in self._changed:
743 self._changed[envvar] = self._environ.get(envvar)
744 if envvar in self._environ:
745 del self._environ[envvar]
746
747 def keys(self):
748 return self._environ.keys()
749
750 def __iter__(self):
751 return iter(self._environ)
752
753 def __len__(self):
754 return len(self._environ)
755
756 def set(self, envvar, value):
757 self[envvar] = value
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000758
759 def unset(self, envvar):
Walter Dörwald155374d2009-05-01 19:58:58 +0000760 del self[envvar]
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000761
762 def __enter__(self):
763 return self
764
765 def __exit__(self, *ignore_exc):
Walter Dörwald4ba80132009-04-25 12:48:43 +0000766 for (k, v) in self._changed.items():
767 if v is None:
Walter Dörwald155374d2009-05-01 19:58:58 +0000768 if k in self._environ:
769 del self._environ[k]
Walter Dörwald4ba80132009-04-25 12:48:43 +0000770 else:
Walter Dörwald155374d2009-05-01 19:58:58 +0000771 self._environ[k] = v
Nick Coghlan6ead5522009-10-18 13:19:33 +0000772 os.environ = self._environ
773
774
775class DirsOnSysPath(object):
776 """Context manager to temporarily add directories to sys.path.
777
778 This makes a copy of sys.path, appends any directories given
779 as positional arguments, then reverts sys.path to the copied
780 settings when the context ends.
781
782 Note that *all* sys.path modifications in the body of the
783 context manager, including replacement of the object,
784 will be reverted at the end of the block.
785 """
786
787 def __init__(self, *paths):
788 self.original_value = sys.path[:]
789 self.original_object = sys.path
790 sys.path.extend(paths)
791
792 def __enter__(self):
793 return self
794
795 def __exit__(self, *ignore_exc):
796 sys.path = self.original_object
797 sys.path[:] = self.original_value
Walter Dörwald155374d2009-05-01 19:58:58 +0000798
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000799
Guido van Rossumd8faa362007-04-27 19:54:29 +0000800class TransientResource(object):
801
802 """Raise ResourceDenied if an exception is raised while the context manager
803 is in effect that matches the specified exception and attributes."""
804
805 def __init__(self, exc, **kwargs):
806 self.exc = exc
807 self.attrs = kwargs
808
809 def __enter__(self):
810 return self
811
812 def __exit__(self, type_=None, value=None, traceback=None):
813 """If type_ is a subclass of self.exc and value has attributes matching
814 self.attrs, raise ResourceDenied. Otherwise let the exception
815 propagate (if any)."""
816 if type_ is not None and issubclass(self.exc, type_):
817 for attr, attr_value in self.attrs.items():
818 if not hasattr(value, attr):
819 break
820 if getattr(value, attr) != attr_value:
821 break
822 else:
823 raise ResourceDenied("an optional resource is not available")
824
Raymond Hettinger686057b2009-06-04 00:11:54 +0000825# Context managers that raise ResourceDenied when various issues
826# with the Internet connection manifest themselves as exceptions.
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000827# XXX deprecate these and use transient_internet() instead
Raymond Hettinger686057b2009-06-04 00:11:54 +0000828time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
829socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
830ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000832
Thomas Woutersed03b412007-08-28 21:37:11 +0000833@contextlib.contextmanager
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000834def transient_internet(resource_name, *, timeout=30.0, errnos=()):
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000835 """Return a context manager that raises ResourceDenied when various issues
836 with the Internet connection manifest themselves as exceptions."""
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000837 default_errnos = [
838 ('ECONNREFUSED', 111),
839 ('ECONNRESET', 104),
Antoine Pitrou5d938cb2011-01-08 10:28:11 +0000840 ('EHOSTUNREACH', 113),
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000841 ('ENETUNREACH', 101),
842 ('ETIMEDOUT', 110),
843 ]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000844 default_gai_errnos = [
845 ('EAI_NONAME', -2),
846 ('EAI_NODATA', -5),
Antoine Pitrou390ea0f2011-04-29 00:44:33 +0200847 # Encountered when trying to resolve IPv6-only hostnames
848 ('WSANO_DATA', 11004),
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000849 ]
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000850
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000851 denied = ResourceDenied("Resource '%s' is not available" % resource_name)
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000852 captured_errnos = errnos
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000853 gai_errnos = []
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000854 if not captured_errnos:
855 captured_errnos = [getattr(errno, name, num)
856 for (name, num) in default_errnos]
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000857 gai_errnos = [getattr(socket, name, num)
858 for (name, num) in default_gai_errnos]
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000859
860 def filter_error(err):
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000861 n = getattr(err, 'errno', None)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000862 if (isinstance(err, socket.timeout) or
Antoine Pitrou2673c5b2010-09-07 21:43:31 +0000863 (isinstance(err, socket.gaierror) and n in gai_errnos) or
864 n in captured_errnos):
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000865 if not verbose:
866 sys.stderr.write(denied.args[0] + "\n")
867 raise denied from err
868
869 old_timeout = socket.getdefaulttimeout()
870 try:
871 if timeout is not None:
872 socket.setdefaulttimeout(timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000873 yield
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000874 except IOError as err:
Antoine Pitrou8bc09032010-09-07 21:09:09 +0000875 # urllib can wrap original socket errors multiple times (!), we must
876 # unwrap to get at the original error.
877 while True:
878 a = err.args
879 if len(a) >= 1 and isinstance(a[0], IOError):
880 err = a[0]
881 # The error can also be wrapped as args[1]:
882 # except socket.error as msg:
883 # raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
884 elif len(a) >= 2 and isinstance(a[1], IOError):
885 err = a[1]
886 else:
887 break
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000888 filter_error(err)
Antoine Pitroua88c83c2010-09-07 20:42:19 +0000889 raise
890 # XXX should we catch generic exceptions and look for their
891 # __cause__ or __context__?
892 finally:
893 socket.setdefaulttimeout(old_timeout)
Antoine Pitroufec12ff2010-04-21 19:46:23 +0000894
895
896@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000897def captured_output(stream_name):
898 """Run the 'with' statement body using a StringIO object in place of a
899 specific attribute on the sys module.
900 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000901
902 with captured_stdout() as s:
Neal Norwitz752abd02008-05-13 04:55:24 +0000903 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000904 assert s.getvalue() == "hello"
905 """
906 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000907 orig_stdout = getattr(sys, stream_name)
908 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000909 try:
910 yield getattr(sys, stream_name)
911 finally:
912 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000913
914def captured_stdout():
915 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000916
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000917def captured_stderr():
918 return captured_output("stderr")
919
Nick Coghlan6ead5522009-10-18 13:19:33 +0000920def captured_stdin():
921 return captured_output("stdin")
922
Benjamin Petersone549ead2009-03-28 21:42:05 +0000923def gc_collect():
924 """Force as many objects as possible to be collected.
925
926 In non-CPython implementations of Python, this is needed because timely
927 deallocation is not guaranteed by the garbage collector. (Even in CPython
928 this can be the case in case of reference cycles.) This means that __del__
929 methods may be called later than expected and weakrefs may remain alive for
930 longer than expected. This function tries its best to force all garbage
931 objects to disappear.
932 """
Benjamin Petersone549ead2009-03-28 21:42:05 +0000933 gc.collect()
Benjamin Petersona6590e82010-04-11 21:22:10 +0000934 if is_jython:
935 time.sleep(0.1)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000936 gc.collect()
937 gc.collect()
938
Thomas Woutersed03b412007-08-28 21:37:11 +0000939
Benjamin Peterson65c66ab2010-10-29 21:31:35 +0000940def python_is_optimized():
941 """Find if Python was built with optimizations."""
Antoine Pitrou64474542010-10-31 11:34:47 +0000942 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
Benjamin Peterson65c66ab2010-10-29 21:31:35 +0000943 final_opt = ""
944 for opt in cflags.split():
945 if opt.startswith('-O'):
946 final_opt = opt
947 return final_opt and final_opt != '-O0'
948
949
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000950#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000951# Decorator for running a function in a different locale, correctly resetting
952# it afterwards.
953
954def run_with_locale(catstr, *locales):
955 def decorator(func):
956 def inner(*args, **kwds):
957 try:
958 import locale
959 category = getattr(locale, catstr)
960 orig_locale = locale.setlocale(category)
961 except AttributeError:
962 # if the test author gives us an invalid category string
963 raise
964 except:
965 # cannot retrieve original locale, so do nothing
966 locale = orig_locale = None
967 else:
968 for loc in locales:
969 try:
970 locale.setlocale(category, loc)
971 break
972 except:
973 pass
974
975 # now run the function, resetting the locale on exceptions
976 try:
977 return func(*args, **kwds)
978 finally:
979 if locale and orig_locale:
980 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000981 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000982 inner.__doc__ = func.__doc__
983 return inner
984 return decorator
985
986#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000987# Big-memory-test support. Separate from 'resources' because memory use
988# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000989
990# Some handy shorthands. Note that these are used for byte-limits as well
991# as size-limits, in the various bigmem tests
992_1M = 1024*1024
993_1G = 1024 * _1M
994_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000995_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000997MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000998
Thomas Wouters477c8d52006-05-27 19:21:47 +0000999def set_memlimit(limit):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001000 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001001 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002 sizes = {
1003 'k': 1024,
1004 'm': _1M,
1005 'g': _1G,
1006 't': 1024*_1G,
1007 }
1008 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
1009 re.IGNORECASE | re.VERBOSE)
1010 if m is None:
1011 raise ValueError('Invalid memory limit %r' % (limit,))
1012 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001013 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001014 if memlimit > MAX_Py_ssize_t:
1015 memlimit = MAX_Py_ssize_t
1016 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001017 raise ValueError('Memory limit %r too low to be useful' % (limit,))
1018 max_memuse = memlimit
1019
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001020def bigmemtest(minsize, memuse):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001021 """Decorator for bigmem tests.
1022
1023 'minsize' is the minimum useful size for the test (in arbitrary,
1024 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001025 the test, or a good estimate of it.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001026
1027 The decorator tries to guess a good value for 'size' and passes it to
1028 the decorated test function. If minsize * memuse is more than the
1029 allowed memory use (as defined by max_memuse), the test is skipped.
1030 Otherwise, minsize is adjusted upward to use up to max_memuse.
1031 """
1032 def decorator(f):
1033 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001034 # Retrieve values in case someone decided to adjust them
1035 minsize = wrapper.minsize
1036 memuse = wrapper.memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001037 if not max_memuse:
1038 # If max_memuse is 0 (the default),
1039 # we still want to run the tests with size set to a few kb,
1040 # to make sure they work. We still want to avoid using
1041 # too much memory, though, but we do that noisily.
1042 maxsize = 5147
Antoine Pitrou9dd11712011-01-12 21:40:20 +00001043 self.assertFalse(maxsize * memuse > 20 * _1M)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044 else:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001045 maxsize = int(max_memuse / memuse)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001046 if maxsize < minsize:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001047 raise unittest.SkipTest(
1048 "not enough memory: %.1fG minimum needed"
1049 % (minsize * memuse / (1024 ** 3)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001050 return f(self, maxsize)
1051 wrapper.minsize = minsize
1052 wrapper.memuse = memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +00001053 return wrapper
1054 return decorator
1055
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001056def precisionbigmemtest(size, memuse):
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001057 def decorator(f):
1058 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +00001059 size = wrapper.size
1060 memuse = wrapper.memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001061 if not real_max_memuse:
1062 maxsize = 5147
1063 else:
1064 maxsize = size
1065
1066 if real_max_memuse and real_max_memuse < maxsize * memuse:
Antoine Pitrouaca5fa72011-01-12 21:19:59 +00001067 raise unittest.SkipTest(
1068 "not enough memory: %.1fG minimum needed"
1069 % (size * memuse / (1024 ** 3)))
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001070
1071 return f(self, maxsize)
1072 wrapper.size = size
1073 wrapper.memuse = memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001074 return wrapper
1075 return decorator
1076
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001077def bigaddrspacetest(f):
1078 """Decorator for tests that fill the address space."""
1079 def wrapper(self):
1080 if max_memuse < MAX_Py_ssize_t:
Antoine Pitrou98c62bd2011-01-12 21:58:39 +00001081 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
Antoine Pitroue0d3f8a2011-01-12 21:50:44 +00001082 raise unittest.SkipTest(
1083 "not enough memory: try a 32-bit build instead")
1084 else:
1085 raise unittest.SkipTest(
1086 "not enough memory: %.1fG minimum needed"
1087 % (MAX_Py_ssize_t / (1024 ** 3)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001088 else:
1089 return f(self)
1090 return wrapper
1091
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001094
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001095class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001096 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001097 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001098 test(result)
1099 return result
1100
Benjamin Petersone549ead2009-03-28 21:42:05 +00001101def _id(obj):
1102 return obj
1103
1104def requires_resource(resource):
Antoine Pitrou4914f9e2011-02-26 16:49:08 +00001105 if resource == 'gui' and not _is_gui_available():
1106 return unittest.skip("resource 'gui' is not available")
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +00001107 if is_resource_enabled(resource):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001108 return _id
1109 else:
1110 return unittest.skip("resource {0!r} is not enabled".format(resource))
1111
1112def cpython_only(test):
1113 """
1114 Decorator for tests only applicable on CPython.
1115 """
1116 return impl_detail(cpython=True)(test)
1117
1118def impl_detail(msg=None, **guards):
1119 if check_impl_detail(**guards):
1120 return _id
1121 if msg is None:
1122 guardnames, default = _parse_guards(guards)
1123 if default:
1124 msg = "implementation detail not available on {0}"
1125 else:
1126 msg = "implementation detail specific to {0}"
1127 guardnames = sorted(guardnames.keys())
1128 msg = msg.format(' or '.join(guardnames))
1129 return unittest.skip(msg)
1130
1131def _parse_guards(guards):
1132 # Returns a tuple ({platform_name: run_me}, default_value)
1133 if not guards:
1134 return ({'cpython': True}, False)
Eric Smith886b40a2009-04-26 21:26:45 +00001135 is_true = list(guards.values())[0]
1136 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001137 return (guards, not is_true)
1138
1139# Use the following check to guard CPython's implementation-specific tests --
1140# or to run them only on the implementation(s) guarded by the arguments.
1141def check_impl_detail(**guards):
1142 """This function returns True or False depending on the host platform.
1143 Examples:
1144 if check_impl_detail(): # only on CPython (default)
1145 if check_impl_detail(jython=True): # only on Jython
1146 if check_impl_detail(cpython=False): # everywhere except on CPython
1147 """
1148 guards, default = _parse_guards(guards)
1149 return guards.get(platform.python_implementation().lower(), default)
1150
1151
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001152
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +00001154 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001155 if verbose:
Victor Stinnerf58087b2010-05-02 17:24:51 +00001156 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001157 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001158 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +00001159
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001160 result = runner.run(suite)
1161 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +00001162 if len(result.errors) == 1 and not result.failures:
1163 err = result.errors[0][1]
1164 elif len(result.failures) == 1 and not result.errors:
1165 err = result.failures[0][1]
1166 else:
R. David Murray723357e2009-10-19 18:06:17 +00001167 err = "multiple errors occurred"
1168 if not verbose: err += "; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +00001169 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +00001170
Barry Warsawc10d6902001-09-20 06:30:41 +00001171
Walter Dörwald21d3a322003-05-01 17:45:56 +00001172def run_unittest(*classes):
1173 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001175 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001176 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001177 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001178 if cls in sys.modules:
1179 suite.addTest(unittest.findTestCases(sys.modules[cls]))
1180 else:
1181 raise ValueError("str arguments must be keys in sys.modules")
1182 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +00001183 suite.addTest(cls)
1184 else:
1185 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001186 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +00001187
Barry Warsawc10d6902001-09-20 06:30:41 +00001188
Tim Petersa0a62222001-09-09 06:12:01 +00001189#=======================================================================
1190# doctest driver.
1191
1192def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +00001193 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +00001194
1195 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001196 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +00001197 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +00001198 """
1199
1200 import doctest
1201
1202 if verbosity is None:
1203 verbosity = verbose
1204 else:
1205 verbosity = None
1206
Tim Peters342ca752001-09-25 19:13:20 +00001207 # Direct doctest output (normally just errors) to real stdout; doctest
1208 # output shouldn't be compared by regrtest.
1209 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +00001210 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +00001211 try:
1212 f, t = doctest.testmod(module, verbose=verbosity)
1213 if f:
1214 raise TestFailed("%d of %d doctests failed" % (f, t))
1215 finally:
1216 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001217 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +00001218 print('doctest (%s) ... %d tests with zero failures' %
1219 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +00001220 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001221
Antoine Pitrou060cee22009-11-13 16:29:04 +00001222
1223#=======================================================================
1224# Support for saving and restoring the imported modules.
1225
1226def modules_setup():
1227 return sys.modules.copy(),
1228
1229def modules_cleanup(oldmodules):
1230 # Encoders/decoders are registered permanently within the internal
1231 # codec cache. If we destroy the corresponding modules their
1232 # globals will be set to None which will trip up the cached functions.
1233 encodings = [(k, v) for k, v in sys.modules.items()
1234 if k.startswith('encodings.')]
1235 sys.modules.clear()
1236 sys.modules.update(encodings)
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001237 # XXX: This kind of problem can affect more than just encodings. In particular
Eric Smitha3e8f3d2011-01-11 10:24:34 +00001238 # extension modules (such as _ssl) don't cope with reloading properly.
Nick Coghlan90be5fb2011-01-11 10:05:20 +00001239 # Really, test modules should be cleaning out the test specific modules they
1240 # know they added (ala test_runpy) rather than relying on this function (as
1241 # test_importhooks and test_pkg do currently).
1242 # Implicitly imported *real* modules should be left alone (see issue 10556).
Antoine Pitrou060cee22009-11-13 16:29:04 +00001243 sys.modules.update(oldmodules)
1244
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001245#=======================================================================
1246# Threading support to prevent reporting refleaks when running regrtest.py -R
1247
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001248# NOTE: we use thread._count() rather than threading.enumerate() (or the
1249# moral equivalent thereof) because a threading.Thread object is still alive
1250# until its __bootstrap() method has returned, even after it has been
1251# unregistered from the threading module.
1252# thread._count(), on the other hand, only gets decremented *after* the
1253# __bootstrap() method has returned, which gives us reliable reference counts
1254# at the end of a test run.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001255
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001256def threading_setup():
Victor Stinner45df8202010-04-28 22:31:17 +00001257 if _thread:
1258 return _thread._count(),
1259 else:
1260 return 1,
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001261
1262def threading_cleanup(nb_threads):
Victor Stinner45df8202010-04-28 22:31:17 +00001263 if not _thread:
1264 return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001265 _MAX_COUNT = 10
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001266 for count in range(_MAX_COUNT):
1267 n = _thread._count()
1268 if n == nb_threads:
1269 break
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001270 time.sleep(0.1)
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001271 # XXX print a warning in case of failure?
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001272
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001273def reap_threads(func):
Victor Stinner45df8202010-04-28 22:31:17 +00001274 """Use this function when threads are being used. This will
1275 ensure that the threads are cleaned up even when the test fails.
1276 If threading is unavailable this function does nothing.
1277 """
1278 if not _thread:
1279 return func
1280
Benjamin Petersonfa0d7032009-06-01 22:42:33 +00001281 @functools.wraps(func)
1282 def decorator(*args):
1283 key = threading_setup()
1284 try:
1285 return func(*args)
1286 finally:
1287 threading_cleanup(*key)
1288 return decorator
1289
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001290def reap_children():
1291 """Use this function at the end of test_main() whenever sub-processes
1292 are started. This will help ensure that no extra children (zombies)
1293 stick around to hog resources and create problems when looking
1294 for refleaks.
1295 """
1296
1297 # Reap all our dead child processes so we don't leave zombies around.
1298 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001299 if hasattr(os, 'waitpid'):
1300 any_process = -1
1301 while True:
1302 try:
1303 # This will raise an exception on Windows. That's ok.
1304 pid, status = os.waitpid(any_process, os.WNOHANG)
1305 if pid == 0:
1306 break
1307 except:
1308 break
Collin Winterf2bf2b32010-03-17 00:41:56 +00001309
1310@contextlib.contextmanager
1311def swap_attr(obj, attr, new_val):
1312 """Temporary swap out an attribute with a new object.
1313
1314 Usage:
1315 with swap_attr(obj, "attr", 5):
1316 ...
1317
1318 This will set obj.attr to 5 for the duration of the with: block,
1319 restoring the old value at the end of the block. If `attr` doesn't
1320 exist on `obj`, it will be created and then deleted at the end of the
1321 block.
1322 """
1323 if hasattr(obj, attr):
1324 real_val = getattr(obj, attr)
1325 setattr(obj, attr, new_val)
1326 try:
1327 yield
1328 finally:
1329 setattr(obj, attr, real_val)
1330 else:
1331 setattr(obj, attr, new_val)
1332 try:
1333 yield
1334 finally:
1335 delattr(obj, attr)
1336
1337@contextlib.contextmanager
1338def swap_item(obj, item, new_val):
1339 """Temporary swap out an item with a new object.
1340
1341 Usage:
1342 with swap_item(obj, "item", 5):
1343 ...
1344
1345 This will set obj["item"] to 5 for the duration of the with: block,
1346 restoring the old value at the end of the block. If `item` doesn't
1347 exist on `obj`, it will be created and then deleted at the end of the
1348 block.
1349 """
1350 if item in obj:
1351 real_val = obj[item]
1352 obj[item] = new_val
1353 try:
1354 yield
1355 finally:
1356 obj[item] = real_val
1357 else:
1358 obj[item] = new_val
1359 try:
1360 yield
1361 finally:
1362 del obj[item]
Antoine Pitrou62f68ed2010-08-04 11:48:56 +00001363
1364def strip_python_stderr(stderr):
1365 """Strip the stderr of a Python process from potential debug output
1366 emitted by the interpreter.
1367
1368 This will typically be run on the result of the communicate() method
1369 of a subprocess.Popen object.
1370 """
1371 stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
1372 return stderr
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +00001373
1374def args_from_interpreter_flags():
1375 """Return a list of command-line arguments reproducing the current
1376 settings in sys.flags."""
1377 flag_opt_map = {
1378 'bytes_warning': 'b',
1379 'dont_write_bytecode': 'B',
1380 'ignore_environment': 'E',
1381 'no_user_site': 's',
1382 'no_site': 'S',
1383 'optimize': 'O',
1384 'verbose': 'v',
1385 }
1386 args = []
1387 for flag, opt in flag_opt_map.items():
1388 v = getattr(sys.flags, flag)
1389 if v > 0:
1390 args.append('-' + opt * v)
1391 return args
Vinay Sajip129fd042010-12-10 08:19:38 +00001392
1393#============================================================
1394# Support for assertions about logging.
1395#============================================================
1396
1397class TestHandler(logging.handlers.BufferingHandler):
1398 def __init__(self, matcher):
1399 # BufferingHandler takes a "capacity" argument
1400 # so as to know when to flush. As we're overriding
1401 # shouldFlush anyway, we can set a capacity of zero.
1402 # You can call flush() manually to clear out the
1403 # buffer.
1404 logging.handlers.BufferingHandler.__init__(self, 0)
1405 self.matcher = matcher
1406
1407 def shouldFlush(self):
1408 return False
1409
1410 def emit(self, record):
1411 self.format(record)
1412 self.buffer.append(record.__dict__)
1413
1414 def matches(self, **kwargs):
1415 """
1416 Look for a saved dict whose keys/values match the supplied arguments.
1417 """
1418 result = False
1419 for d in self.buffer:
1420 if self.matcher.matches(d, **kwargs):
1421 result = True
1422 break
1423 return result
1424
1425class Matcher(object):
1426
1427 _partial_matches = ('msg', 'message')
1428
1429 def matches(self, d, **kwargs):
1430 """
1431 Try to match a single dict with the supplied arguments.
1432
1433 Keys whose values are strings and which are in self._partial_matches
1434 will be checked for partial (i.e. substring) matches. You can extend
1435 this scheme to (for example) do regular expression matching, etc.
1436 """
1437 result = True
1438 for k in kwargs:
1439 v = kwargs[k]
1440 dv = d.get(k)
1441 if not self.match_value(k, dv, v):
1442 result = False
1443 break
1444 return result
1445
1446 def match_value(self, k, dv, v):
1447 """
1448 Try to match a single stored value (dv) with a supplied value (v).
1449 """
1450 if type(v) != type(dv):
1451 result = False
1452 elif type(dv) is not str or k not in self._partial_matches:
1453 result = (v == dv)
1454 else:
1455 result = dv.find(v) >= 0
1456 return result
Brian Curtin3b4499c2010-12-28 14:31:47 +00001457
1458
1459_can_symlink = None
1460def can_symlink():
1461 global _can_symlink
1462 if _can_symlink is not None:
1463 return _can_symlink
1464 try:
1465 os.symlink(TESTFN, TESTFN + "can_symlink")
1466 can = True
Brian Curtin57160d72010-12-29 02:04:28 +00001467 except (OSError, NotImplementedError):
Brian Curtin3b4499c2010-12-28 14:31:47 +00001468 can = False
1469 _can_symlink = can
1470 return can
1471
1472def skip_unless_symlink(test):
1473 """Skip decorator for tests that require functional symlink"""
1474 ok = can_symlink()
1475 msg = "Requires functional symlink implementation"
1476 return test if ok else unittest.skip(msg)(test)
Antoine Pitroue8706232011-03-15 21:05:36 +01001477
Antoine Pitrou2c50a092011-03-15 21:02:59 +01001478def patch(test_instance, object_to_patch, attr_name, new_value):
1479 """Override 'object_to_patch'.'attr_name' with 'new_value'.
1480
1481 Also, add a cleanup procedure to 'test_instance' to restore
1482 'object_to_patch' value for 'attr_name'.
1483 The 'attr_name' should be a valid attribute for 'object_to_patch'.
1484
1485 """
1486 # check that 'attr_name' is a real attribute for 'object_to_patch'
1487 # will raise AttributeError if it does not exist
1488 getattr(object_to_patch, attr_name)
1489
1490 # keep a copy of the old value
1491 attr_is_local = False
1492 try:
1493 old_value = object_to_patch.__dict__[attr_name]
1494 except (AttributeError, KeyError):
1495 old_value = getattr(object_to_patch, attr_name, None)
1496 else:
1497 attr_is_local = True
1498
1499 # restore the value when the test is done
1500 def cleanup():
1501 if attr_is_local:
1502 setattr(object_to_patch, attr_name, old_value)
1503 else:
1504 delattr(object_to_patch, attr_name)
1505
1506 test_instance.addCleanup(cleanup)
1507
1508 # actually override the attribute
1509 setattr(object_to_patch, attr_name, new_value)