blob: 9cd50a02f2f6f30ccd2d23eaf196eb8224d6ce6b [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
8import socket
Fred Drakecd1b1dd2001-03-21 18:26:33 +00009import sys
Guido van Rossumd8faa362007-04-27 19:54:29 +000010import os
Benjamin Petersone549ead2009-03-28 21:42:05 +000011import platform
Christian Heimes23daade02008-02-25 12:39:23 +000012import shutil
Thomas Wouters902d6eb2007-01-09 23:18:33 +000013import warnings
Guido van Rossumd8faa362007-04-27 19:54:29 +000014import unittest
R. David Murraya21e4ca2009-03-31 23:16:50 +000015import importlib
Fred Drakecd1b1dd2001-03-21 18:26:33 +000016
Benjamin Petersone549ead2009-03-28 21:42:05 +000017__all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
Benjamin Peterson744c2cd2008-05-26 16:26:37 +000018 "verbose", "use_resources", "max_memuse", "record_original_stdout",
19 "get_original_stdout", "unload", "unlink", "rmtree", "forget",
20 "is_resource_enabled", "requires", "find_unused_port", "bind_port",
Benjamin Peterson79e48032008-05-26 17:44:33 +000021 "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "findfile", "verify",
22 "vereq", "sortdict", "check_syntax_error", "open_urlresource",
Benjamin Petersonfcf5d632008-10-16 23:24:44 +000023 "check_warnings", "CleanImport", "EnvironmentVarGuard",
Benjamin Peterson79e48032008-05-26 17:44:33 +000024 "TransientResource", "captured_output", "captured_stdout",
25 "TransientResource", "transient_internet", "run_with_locale",
26 "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
27 "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
R. David Murraya21e4ca2009-03-31 23:16:50 +000028 "reap_children", "cpython_only", "check_impl_detail", "get_attribute"]
Benjamin Peterson744c2cd2008-05-26 16:26:37 +000029
Fred Drake1790dd42000-07-24 06:55:00 +000030class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000031 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000032
33class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000034 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000035
Benjamin Petersone549ead2009-03-28 21:42:05 +000036class ResourceDenied(unittest.SkipTest):
Fred Drake9a0db072003-02-03 15:19:30 +000037 """Test skipped because it requested a disallowed resource.
38
39 This is raised when a test calls requires() for a resource that
40 has not be enabled. It is used to distinguish between expected
41 and unexpected skips.
42 """
43
Benjamin Peterson699adb92008-05-08 22:27:58 +000044def import_module(name, deprecated=False):
R. David Murraya21e4ca2009-03-31 23:16:50 +000045 """Import and return the module to be tested, raising SkipTest if
46 it is not available.
47
48 If deprecated is True, any module or package deprecation messages
49 will be suppressed."""
Benjamin Petersonfcf5d632008-10-16 23:24:44 +000050 with warnings.catch_warnings():
Benjamin Peterson699adb92008-05-08 22:27:58 +000051 if deprecated:
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +000052 warnings.filterwarnings("ignore", ".+ (module|package)",
53 DeprecationWarning)
Benjamin Peterson699adb92008-05-08 22:27:58 +000054 try:
R. David Murraya21e4ca2009-03-31 23:16:50 +000055 module = importlib.import_module(name)
56 except ImportError as msg:
57 raise unittest.SkipTest(str(msg))
Benjamin Peterson699adb92008-05-08 22:27:58 +000058 else:
59 return module
60
R. David Murraya21e4ca2009-03-31 23:16:50 +000061def get_attribute(obj, name):
62 """Get an attribute, raising SkipTest if AttributeError is raised."""
63 try:
64 attribute = getattr(obj, name)
65 except AttributeError:
66 raise unittest.SkipTest("module %s has no attribute %s" % (
67 obj.__name__, name))
68 else:
69 return attribute
70
Barry Warsawc0fb6052001-08-20 22:29:23 +000071verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +000072use_resources = None # Flag set to [] by regrtest.py
73max_memuse = 0 # Disable bigmem tests (they will still be run with
74 # small sizes, to make sure they work.)
Neal Norwitz3ce5d922008-08-24 07:08:55 +000075real_max_memuse = 0
Guido van Rossum531661c1996-12-20 02:58:22 +000076
Tim Peters8dee8092001-09-25 20:05:11 +000077# _original_stdout is meant to hold stdout at the time regrtest began.
78# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
79# The point is to have some flavor of stdout the user can actually see.
80_original_stdout = None
81def record_original_stdout(stdout):
82 global _original_stdout
83 _original_stdout = stdout
84
85def get_original_stdout():
86 return _original_stdout or sys.stdout
87
Guido van Rossum3bead091992-01-27 17:00:37 +000088def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +000089 try:
90 del sys.modules[name]
91 except KeyError:
92 pass
Guido van Rossum3bead091992-01-27 17:00:37 +000093
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000094def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000095 try:
96 os.unlink(filename)
97 except OSError:
98 pass
99
Christian Heimes23daade02008-02-25 12:39:23 +0000100def rmtree(path):
101 try:
102 shutil.rmtree(path)
103 except OSError as e:
104 # Unix returns ENOENT, Windows returns ESRCH.
105 if e.errno not in (errno.ENOENT, errno.ESRCH):
106 raise
107
Guido van Rossum3bead091992-01-27 17:00:37 +0000108def forget(modname):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000109 '''"Forget" a module was ever imported by removing it from sys.modules and
110 deleting any .pyc and .pyo files.'''
Fred Drake004d5e62000-10-23 17:22:08 +0000111 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +0000112 for dirname in sys.path:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000113 unlink(os.path.join(dirname, modname + '.pyc'))
Brett Cannonf1cfb622003-05-04 21:15:27 +0000114 # Deleting the .pyo file cannot be within the 'try' for the .pyc since
115 # the chance exists that there is no .pyc (and thus the 'try' statement
116 # is exited) but there is a .pyo file.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000117 unlink(os.path.join(dirname, modname + '.pyo'))
Guido van Rossum3bead091992-01-27 17:00:37 +0000118
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000119def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000120 """Test whether a resource is enabled. Known resources are set by
121 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000122 return use_resources is not None and resource in use_resources
123
Barry Warsawc0fb6052001-08-20 22:29:23 +0000124def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000125 """Raise ResourceDenied if the specified resource is not available.
126
127 If the caller's module is __main__ then automatically return True. The
128 possibility of False being returned occurs when regrtest.py is executing."""
Skip Montanarod839ecd2003-04-24 19:06:57 +0000129 # see if the caller's module is __main__ - if so, treat as if
130 # the resource was set
Benjamin Petersone549ead2009-03-28 21:42:05 +0000131 if sys._getframe(1).f_globals.get("__name__") == "__main__":
Skip Montanarod839ecd2003-04-24 19:06:57 +0000132 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000133 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000134 if msg is None:
135 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000136 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000137
Christian Heimes5e696852008-04-09 08:37:03 +0000138HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139
Christian Heimes5e696852008-04-09 08:37:03 +0000140def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
141 """Returns an unused port that should be suitable for binding. This is
142 achieved by creating a temporary socket with the same family and type as
143 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
144 the specified host address (defaults to 0.0.0.0) with the port set to 0,
145 eliciting an unused ephemeral port from the OS. The temporary socket is
146 then closed and deleted, and the ephemeral port is returned.
147
148 Either this method or bind_port() should be used for any tests where a
149 server socket needs to be bound to a particular port for the duration of
150 the test. Which one to use depends on whether the calling code is creating
151 a python socket, or if an unused port needs to be provided in a constructor
152 or passed to an external program (i.e. the -accept argument to openssl's
153 s_server mode). Always prefer bind_port() over find_unused_port() where
154 possible. Hard coded ports should *NEVER* be used. As soon as a server
155 socket is bound to a hard coded port, the ability to run multiple instances
156 of the test simultaneously on the same host is compromised, which makes the
157 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
158 may simply manifest as a failed test, which can be recovered from without
159 intervention in most cases, but on Windows, the entire python process can
160 completely and utterly wedge, requiring someone to log in to the buildbot
161 and manually kill the affected process.
162
163 (This is easy to reproduce on Windows, unfortunately, and can be traced to
164 the SO_REUSEADDR socket option having different semantics on Windows versus
165 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
166 listen and then accept connections on identical host/ports. An EADDRINUSE
167 socket.error will be raised at some point (depending on the platform and
168 the order bind and listen were called on each socket).
169
170 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
171 will ever be raised when attempting to bind two identical host/ports. When
172 accept() is called on each socket, the second caller's process will steal
173 the port from the first caller, leaving them both in an awkwardly wedged
174 state where they'll no longer respond to any signals or graceful kills, and
175 must be forcibly killed via OpenProcess()/TerminateProcess().
176
177 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
178 instead of SO_REUSEADDR, which effectively affords the same semantics as
179 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
180 Source world compared to Windows ones, this is a common mistake. A quick
181 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
182 openssl.exe is called with the 's_server' option, for example. See
183 http://bugs.python.org/issue2550 for more info. The following site also
184 has a very thorough description about the implications of both REUSEADDR
185 and EXCLUSIVEADDRUSE on Windows:
186 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
187
188 XXX: although this approach is a vast improvement on previous attempts to
189 elicit unused ports, it rests heavily on the assumption that the ephemeral
190 port returned to us by the OS won't immediately be dished back out to some
191 other process when we close and delete our temporary socket but before our
192 calling code has a chance to bind the returned port. We can deal with this
193 issue if/when we come across it.
194 """
195
196 tempsock = socket.socket(family, socktype)
197 port = bind_port(tempsock)
198 tempsock.close()
199 del tempsock
200 return port
201
202def bind_port(sock, host=HOST):
203 """Bind the socket to a free port and return the port number. Relies on
204 ephemeral ports in order to ensure we are using an unbound port. This is
205 important as many tests may be running simultaneously, especially in a
206 buildbot environment. This method raises an exception if the sock.family
207 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
208 or SO_REUSEPORT set on it. Tests should *never* set these socket options
209 for TCP/IP sockets. The only case for setting these options is testing
210 multicasting via multiple UDP sockets.
211
212 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
213 on Windows), it will be set on the socket. This will prevent anyone else
214 from bind()'ing to our host/port for the duration of the test.
215 """
216
217 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
218 if hasattr(socket, 'SO_REUSEADDR'):
219 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
220 raise TestFailed("tests should never set the SO_REUSEADDR " \
221 "socket option on TCP/IP sockets!")
222 if hasattr(socket, 'SO_REUSEPORT'):
223 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
224 raise TestFailed("tests should never set the SO_REUSEPORT " \
225 "socket option on TCP/IP sockets!")
226 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
227 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
228
229 sock.bind((host, 0))
230 port = sock.getsockname()[1]
231 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000232
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000233FUZZ = 1e-6
234
235def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000236 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000237 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000238 fuzz = (abs(x) + abs(y)) * FUZZ
239 if abs(x-y) <= fuzz:
240 return 0
241 except:
242 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000243 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000244 for i in range(min(len(x), len(y))):
245 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000246 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000247 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000248 return (len(x) > len(y)) - (len(x) < len(y))
249 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000250
Finn Bock57bc5fa2002-11-01 18:02:03 +0000251is_jython = sys.platform.startswith('java')
252
Barry Warsaw559f6682001-03-23 18:04:02 +0000253# Filename used for testing
254if os.name == 'java':
255 # Jython disallows @ in module names
256 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000257else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000258 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000259
260 # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
261 # TESTFN_UNICODE is a filename that can be encoded using the
262 # file system encoding, but *not* with the default (ascii) encoding
263 TESTFN_UNICODE = "@test-\xe0\xf2"
264 TESTFN_ENCODING = sys.getfilesystemencoding()
265 # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
266 # able to be encoded by *either* the default or filesystem encoding.
267 # This test really only makes sense on Windows NT platforms
268 # which have special Unicode support in posixmodule.
269 if (not hasattr(sys, "getwindowsversion") or
270 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
271 TESTFN_UNICODE_UNENCODEABLE = None
272 else:
273 # Japanese characters (I think - from bug 846133)
274 TESTFN_UNICODE_UNENCODEABLE = "@test-\u5171\u6709\u3055\u308c\u308b"
275 try:
276 # XXX - Note - should be using TESTFN_ENCODING here - but for
277 # Windows, "mbcs" currently always operates as if in
278 # errors=ignore' mode - hence we get '?' characters rather than
279 # the exception. 'Latin1' operates as we expect - ie, fails.
280 # See [ 850997 ] mbcs encoding ignores errors
281 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
282 except UnicodeEncodeError:
283 pass
Martin v. Löwis2411a2d2002-11-09 19:57:26 +0000284 else:
Georg Brandldb028442008-02-05 20:48:58 +0000285 print('WARNING: The filename %r CAN be encoded by the filesystem. '
286 'Unicode filename tests may not be effective'
287 % TESTFN_UNICODE_UNENCODEABLE)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000288
289# Make sure we can write to TESTFN, try in /tmp if we can't
290fp = None
291try:
292 fp = open(TESTFN, 'w+')
293except IOError:
294 TMP_TESTFN = os.path.join('/tmp', TESTFN)
295 try:
296 fp = open(TMP_TESTFN, 'w+')
297 TESTFN = TMP_TESTFN
298 del TMP_TESTFN
299 except IOError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000300 print(('WARNING: tests will fail, unable to write to: %s or %s' %
301 (TESTFN, TMP_TESTFN)))
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000302if fp is not None:
303 fp.close()
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000304 unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000305del fp
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000306
Guido van Rossume26132c1998-04-23 20:13:30 +0000307def findfile(file, here=__file__):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000308 """Try to find a file on sys.path and the working directory. If it is not
309 found the argument passed to the function is returned (this does not
310 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000311 if os.path.isabs(file):
312 return file
Fred Drake004d5e62000-10-23 17:22:08 +0000313 path = sys.path
314 path = [os.path.dirname(here)] + path
315 for dn in path:
316 fn = os.path.join(dn, file)
317 if os.path.exists(fn): return fn
318 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000319
320def verify(condition, reason='test failed'):
Guido van Rossuma1374e42001-01-19 19:01:56 +0000321 """Verify that condition is true. If not, raise TestFailed.
Marc-André Lemburg36619082001-01-17 19:11:13 +0000322
Skip Montanaroc955f892001-01-20 19:12:54 +0000323 The optional argument reason can be given to provide
Tim Peters983874d2001-01-19 05:59:21 +0000324 a better error text.
Tim Petersd2bf3b72001-01-18 02:22:22 +0000325 """
Tim Peters983874d2001-01-19 05:59:21 +0000326
Tim Petersd2bf3b72001-01-18 02:22:22 +0000327 if not condition:
Guido van Rossuma1374e42001-01-19 19:01:56 +0000328 raise TestFailed(reason)
Jeremy Hylton47793992001-02-19 15:35:26 +0000329
Tim Petersc2fe6182001-10-30 23:20:46 +0000330def vereq(a, b):
Tim Peters77902972001-12-29 17:34:57 +0000331 """Raise TestFailed if a == b is false.
332
333 This is better than verify(a == b) because, in case of failure, the
334 error message incorporates repr(a) and repr(b) so you can see the
335 inputs.
336
337 Note that "not (a == b)" isn't necessarily the same as "a != b"; the
338 former is tested.
339 """
340
Tim Petersc2fe6182001-10-30 23:20:46 +0000341 if not (a == b):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000342 raise TestFailed("%r == %r" % (a, b))
Tim Petersc2fe6182001-10-30 23:20:46 +0000343
Tim Peters2f228e72001-05-13 00:19:31 +0000344def sortdict(dict):
345 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000346 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000347 reprpairs = ["%r: %r" % pair for pair in items]
348 withcommas = ", ".join(reprpairs)
349 return "{%s}" % withcommas
350
Benjamin Peterson7522c742009-01-19 21:00:09 +0000351def make_bad_fd():
352 """
353 Create an invalid file descriptor by opening and closing a file and return
354 its fd.
355 """
356 file = open(TESTFN, "wb")
357 try:
358 return file.fileno()
359 finally:
360 file.close()
361 unlink(TESTFN)
362
Thomas Wouters89f507f2006-12-13 04:49:30 +0000363def check_syntax_error(testcase, statement):
Benjamin Petersone549ead2009-03-28 21:42:05 +0000364 testcase.assertRaises(SyntaxError, compile, statement,
365 '<test string>', 'exec')
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000366
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000367def open_urlresource(url, *args, **kw):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000368 import urllib.request, urllib.parse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000369
Guido van Rossum360e4b82007-05-14 22:51:27 +0000370 requires('urlfetch')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000371 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000372
373 for path in [os.path.curdir, os.path.pardir]:
374 fn = os.path.join(path, filename)
375 if os.path.exists(fn):
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000376 return open(fn, *args, **kw)
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000377
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000378 print('\tfetching %s ...' % url, file=get_original_stdout())
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000379 fn, _ = urllib.request.urlretrieve(url, filename)
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000380 return open(fn, *args, **kw)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000381
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000382
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000383class WarningsRecorder(object):
384 """Convenience wrapper for the warnings list returned on
385 entry to the warnings.catch_warnings() context manager.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000386 """
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000387 def __init__(self, warnings_list):
388 self.warnings = warnings_list
389
390 def __getattr__(self, attr):
391 if self.warnings:
392 return getattr(self.warnings[-1], attr)
393 elif attr in warnings.WarningMessage._WARNING_DETAILS:
394 return None
395 raise AttributeError("%r has no attribute %r" % (self, attr))
396
397 def reset(self):
398 del self.warnings[:]
399
400@contextlib.contextmanager
401def check_warnings():
402 with warnings.catch_warnings(record=True) as w:
403 yield WarningsRecorder(w)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000404
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000405
406class CleanImport(object):
407 """Context manager to force import to return a new module reference.
408
409 This is useful for testing module-level behaviours, such as
Nick Coghlanb1304932008-07-13 12:25:08 +0000410 the emission of a DeprecationWarning on import.
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000411
412 Use like this:
413
414 with CleanImport("foo"):
415 __import__("foo") # new reference
416 """
417
418 def __init__(self, *module_names):
419 self.original_modules = sys.modules.copy()
420 for module_name in module_names:
421 if module_name in sys.modules:
422 module = sys.modules[module_name]
423 # It is possible that module_name is just an alias for
424 # another module (e.g. stub for modules renamed in 3.x).
425 # In that case, we also need delete the real module to clear
426 # the import cache.
427 if module.__name__ != module_name:
428 del sys.modules[module.__name__]
429 del sys.modules[module_name]
430
431 def __enter__(self):
432 return self
433
434 def __exit__(self, *ignore_exc):
435 sys.modules.update(self.original_modules)
436
437
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000438class EnvironmentVarGuard(object):
439
440 """Class to help protect the environment variable properly. Can be used as
441 a context manager."""
442
443 def __init__(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000444 self._environ = os.environ
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000445 self._unset = set()
446 self._reset = dict()
447
448 def set(self, envvar, value):
449 if envvar not in self._environ:
450 self._unset.add(envvar)
451 else:
452 self._reset[envvar] = self._environ[envvar]
453 self._environ[envvar] = value
454
455 def unset(self, envvar):
456 if envvar in self._environ:
457 self._reset[envvar] = self._environ[envvar]
458 del self._environ[envvar]
459
460 def __enter__(self):
461 return self
462
463 def __exit__(self, *ignore_exc):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000464 for envvar, value in self._reset.items():
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000465 self._environ[envvar] = value
466 for unset in self._unset:
467 del self._environ[unset]
468
Guido van Rossumd8faa362007-04-27 19:54:29 +0000469class TransientResource(object):
470
471 """Raise ResourceDenied if an exception is raised while the context manager
472 is in effect that matches the specified exception and attributes."""
473
474 def __init__(self, exc, **kwargs):
475 self.exc = exc
476 self.attrs = kwargs
477
478 def __enter__(self):
479 return self
480
481 def __exit__(self, type_=None, value=None, traceback=None):
482 """If type_ is a subclass of self.exc and value has attributes matching
483 self.attrs, raise ResourceDenied. Otherwise let the exception
484 propagate (if any)."""
485 if type_ is not None and issubclass(self.exc, type_):
486 for attr, attr_value in self.attrs.items():
487 if not hasattr(value, attr):
488 break
489 if getattr(value, attr) != attr_value:
490 break
491 else:
492 raise ResourceDenied("an optional resource is not available")
493
494
495def transient_internet():
496 """Return a context manager that raises ResourceDenied when various issues
497 with the Internet connection manifest themselves as exceptions."""
498 time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
499 socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
500 ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
501 return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
502
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000503
Thomas Woutersed03b412007-08-28 21:37:11 +0000504@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000505def captured_output(stream_name):
506 """Run the 'with' statement body using a StringIO object in place of a
507 specific attribute on the sys module.
508 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000509
510 with captured_stdout() as s:
Neal Norwitz752abd02008-05-13 04:55:24 +0000511 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000512 assert s.getvalue() == "hello"
513 """
514 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000515 orig_stdout = getattr(sys, stream_name)
516 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000517 try:
518 yield getattr(sys, stream_name)
519 finally:
520 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000521
522def captured_stdout():
523 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000524
Benjamin Petersone549ead2009-03-28 21:42:05 +0000525def gc_collect():
526 """Force as many objects as possible to be collected.
527
528 In non-CPython implementations of Python, this is needed because timely
529 deallocation is not guaranteed by the garbage collector. (Even in CPython
530 this can be the case in case of reference cycles.) This means that __del__
531 methods may be called later than expected and weakrefs may remain alive for
532 longer than expected. This function tries its best to force all garbage
533 objects to disappear.
534 """
535 import gc
536 gc.collect()
537 gc.collect()
538 gc.collect()
539
Thomas Woutersed03b412007-08-28 21:37:11 +0000540
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000541#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542# Decorator for running a function in a different locale, correctly resetting
543# it afterwards.
544
545def run_with_locale(catstr, *locales):
546 def decorator(func):
547 def inner(*args, **kwds):
548 try:
549 import locale
550 category = getattr(locale, catstr)
551 orig_locale = locale.setlocale(category)
552 except AttributeError:
553 # if the test author gives us an invalid category string
554 raise
555 except:
556 # cannot retrieve original locale, so do nothing
557 locale = orig_locale = None
558 else:
559 for loc in locales:
560 try:
561 locale.setlocale(category, loc)
562 break
563 except:
564 pass
565
566 # now run the function, resetting the locale on exceptions
567 try:
568 return func(*args, **kwds)
569 finally:
570 if locale and orig_locale:
571 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000572 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000573 inner.__doc__ = func.__doc__
574 return inner
575 return decorator
576
577#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000578# Big-memory-test support. Separate from 'resources' because memory use
579# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000580
581# Some handy shorthands. Note that these are used for byte-limits as well
582# as size-limits, in the various bigmem tests
583_1M = 1024*1024
584_1G = 1024 * _1M
585_2G = 2 * _1G
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000586_4G = 4 * _1G
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000588MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590def set_memlimit(limit):
591 import re
592 global max_memuse
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000593 global real_max_memuse
Thomas Wouters477c8d52006-05-27 19:21:47 +0000594 sizes = {
595 'k': 1024,
596 'm': _1M,
597 'g': _1G,
598 't': 1024*_1G,
599 }
600 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
601 re.IGNORECASE | re.VERBOSE)
602 if m is None:
603 raise ValueError('Invalid memory limit %r' % (limit,))
604 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000605 real_max_memuse = memlimit
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606 if memlimit > MAX_Py_ssize_t:
607 memlimit = MAX_Py_ssize_t
608 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000609 raise ValueError('Memory limit %r too low to be useful' % (limit,))
610 max_memuse = memlimit
611
612def bigmemtest(minsize, memuse, overhead=5*_1M):
613 """Decorator for bigmem tests.
614
615 'minsize' is the minimum useful size for the test (in arbitrary,
616 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
617 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
Christian Heimes33fe8092008-04-13 13:53:33 +0000618 independent of the testsize, and defaults to 5Mb.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000619
620 The decorator tries to guess a good value for 'size' and passes it to
621 the decorated test function. If minsize * memuse is more than the
622 allowed memory use (as defined by max_memuse), the test is skipped.
623 Otherwise, minsize is adjusted upward to use up to max_memuse.
624 """
625 def decorator(f):
626 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000627 # Retrieve values in case someone decided to adjust them
628 minsize = wrapper.minsize
629 memuse = wrapper.memuse
630 overhead = wrapper.overhead
Thomas Wouters477c8d52006-05-27 19:21:47 +0000631 if not max_memuse:
632 # If max_memuse is 0 (the default),
633 # we still want to run the tests with size set to a few kb,
634 # to make sure they work. We still want to avoid using
635 # too much memory, though, but we do that noisily.
636 maxsize = 5147
637 self.failIf(maxsize * memuse + overhead > 20 * _1M)
638 else:
639 maxsize = int((max_memuse - overhead) / memuse)
640 if maxsize < minsize:
641 # Really ought to print 'test skipped' or something
642 if verbose:
643 sys.stderr.write("Skipping %s because of memory "
644 "constraint\n" % (f.__name__,))
645 return
646 # Try to keep some breathing room in memory use
647 maxsize = max(maxsize - 50 * _1M, minsize)
648 return f(self, maxsize)
649 wrapper.minsize = minsize
650 wrapper.memuse = memuse
651 wrapper.overhead = overhead
652 return wrapper
653 return decorator
654
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000655def precisionbigmemtest(size, memuse, overhead=5*_1M):
656 def decorator(f):
657 def wrapper(self):
Antoine Pitrou7cdb4952009-03-07 23:40:49 +0000658 size = wrapper.size
659 memuse = wrapper.memuse
660 overhead = wrapper.overhead
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000661 if not real_max_memuse:
662 maxsize = 5147
663 else:
664 maxsize = size
665
666 if real_max_memuse and real_max_memuse < maxsize * memuse:
667 if verbose:
668 sys.stderr.write("Skipping %s because of memory "
669 "constraint\n" % (f.__name__,))
670 return
671
672 return f(self, maxsize)
673 wrapper.size = size
674 wrapper.memuse = memuse
675 wrapper.overhead = overhead
676 return wrapper
677 return decorator
678
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679def bigaddrspacetest(f):
680 """Decorator for tests that fill the address space."""
681 def wrapper(self):
682 if max_memuse < MAX_Py_ssize_t:
683 if verbose:
684 sys.stderr.write("Skipping %s because of memory "
685 "constraint\n" % (f.__name__,))
686 else:
687 return f(self)
688 return wrapper
689
Thomas Wouters477c8d52006-05-27 19:21:47 +0000690#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000692
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000693class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000694 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000695 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000696 test(result)
697 return result
698
Benjamin Petersone549ead2009-03-28 21:42:05 +0000699def _id(obj):
700 return obj
701
702def requires_resource(resource):
703 if resource_is_enabled(resource):
704 return _id
705 else:
706 return unittest.skip("resource {0!r} is not enabled".format(resource))
707
708def cpython_only(test):
709 """
710 Decorator for tests only applicable on CPython.
711 """
712 return impl_detail(cpython=True)(test)
713
714def impl_detail(msg=None, **guards):
715 if check_impl_detail(**guards):
716 return _id
717 if msg is None:
718 guardnames, default = _parse_guards(guards)
719 if default:
720 msg = "implementation detail not available on {0}"
721 else:
722 msg = "implementation detail specific to {0}"
723 guardnames = sorted(guardnames.keys())
724 msg = msg.format(' or '.join(guardnames))
725 return unittest.skip(msg)
726
727def _parse_guards(guards):
728 # Returns a tuple ({platform_name: run_me}, default_value)
729 if not guards:
730 return ({'cpython': True}, False)
731 is_true = guards.values()[0]
732 assert guards.values() == [is_true] * len(guards) # all True or all False
733 return (guards, not is_true)
734
735# Use the following check to guard CPython's implementation-specific tests --
736# or to run them only on the implementation(s) guarded by the arguments.
737def check_impl_detail(**guards):
738 """This function returns True or False depending on the host platform.
739 Examples:
740 if check_impl_detail(): # only on CPython (default)
741 if check_impl_detail(jython=True): # only on Jython
742 if check_impl_detail(cpython=False): # everywhere except on CPython
743 """
744 guards, default = _parse_guards(guards)
745 return guards.get(platform.python_implementation().lower(), default)
746
747
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000748
Guido van Rossumd8faa362007-04-27 19:54:29 +0000749def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +0000750 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000751 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +0000752 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000753 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000754 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000755
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000756 result = runner.run(suite)
757 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +0000758 if len(result.errors) == 1 and not result.failures:
759 err = result.errors[0][1]
760 elif len(result.failures) == 1 and not result.errors:
761 err = result.failures[0][1]
762 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000763 err = "errors occurred; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +0000764 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +0000765
Barry Warsawc10d6902001-09-20 06:30:41 +0000766
Walter Dörwald21d3a322003-05-01 17:45:56 +0000767def run_unittest(*classes):
768 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000770 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000771 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000772 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000773 if cls in sys.modules:
774 suite.addTest(unittest.findTestCases(sys.modules[cls]))
775 else:
776 raise ValueError("str arguments must be keys in sys.modules")
777 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +0000778 suite.addTest(cls)
779 else:
780 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000781 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000782
Barry Warsawc10d6902001-09-20 06:30:41 +0000783
Tim Petersa0a62222001-09-09 06:12:01 +0000784#=======================================================================
785# doctest driver.
786
787def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +0000788 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +0000789
790 If optional argument verbosity is not specified (or is None), pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000791 support's belief about verbosity on to doctest. Else doctest's
Tim Petersbea3fb82001-09-10 01:39:21 +0000792 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +0000793 """
794
795 import doctest
796
797 if verbosity is None:
798 verbosity = verbose
799 else:
800 verbosity = None
801
Tim Peters342ca752001-09-25 19:13:20 +0000802 # Direct doctest output (normally just errors) to real stdout; doctest
803 # output shouldn't be compared by regrtest.
804 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +0000805 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +0000806 try:
807 f, t = doctest.testmod(module, verbose=verbosity)
808 if f:
809 raise TestFailed("%d of %d doctests failed" % (f, t))
810 finally:
811 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000812 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +0000813 print('doctest (%s) ... %d tests with zero failures' %
814 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000815 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000816
817#=======================================================================
818# Threading support to prevent reporting refleaks when running regrtest.py -R
819
820def threading_setup():
821 import threading
822 return len(threading._active), len(threading._limbo)
823
824def threading_cleanup(num_active, num_limbo):
825 import threading
826 import time
827
828 _MAX_COUNT = 10
829 count = 0
830 while len(threading._active) != num_active and count < _MAX_COUNT:
831 count += 1
832 time.sleep(0.1)
833
834 count = 0
835 while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
836 count += 1
837 time.sleep(0.1)
838
839def reap_children():
840 """Use this function at the end of test_main() whenever sub-processes
841 are started. This will help ensure that no extra children (zombies)
842 stick around to hog resources and create problems when looking
843 for refleaks.
844 """
845
846 # Reap all our dead child processes so we don't leave zombies around.
847 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000848 if hasattr(os, 'waitpid'):
849 any_process = -1
850 while True:
851 try:
852 # This will raise an exception on Windows. That's ok.
853 pid, status = os.waitpid(any_process, os.WNOHANG)
854 if pid == 0:
855 break
856 except:
857 break