blob: c4084bb3c6eca85d20a65215978e8f8b358d6962 [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
Barry Warsaw408b6d32002-07-30 23:27:12 +00003if __name__ != 'test.test_support':
Guido van Rossumd8faa362007-04-27 19:54:29 +00004 raise ImportError('test_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
11import os.path
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
Fred Drakecd1b1dd2001-03-21 18:26:33 +000015
Fred Drake1790dd42000-07-24 06:55:00 +000016class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +000017 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000018
19class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000020 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000021
22class TestSkipped(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000023 """Test skipped.
Fred Drake1790dd42000-07-24 06:55:00 +000024
Fred Drake004d5e62000-10-23 17:22:08 +000025 This can be raised to indicate that a test was deliberatly
26 skipped, but not because a feature wasn't available. For
27 example, if some resource can't be used, such as the network
28 appears to be unavailable, this should be raised instead of
29 TestFailed.
Fred Drake004d5e62000-10-23 17:22:08 +000030 """
Fred Drake1790dd42000-07-24 06:55:00 +000031
Fred Drake9a0db072003-02-03 15:19:30 +000032class ResourceDenied(TestSkipped):
33 """Test skipped because it requested a disallowed resource.
34
35 This is raised when a test calls requires() for a resource that
36 has not be enabled. It is used to distinguish between expected
37 and unexpected skips.
38 """
39
Benjamin Peterson699adb92008-05-08 22:27:58 +000040def import_module(name, deprecated=False):
41 """Import the module to be tested, raising TestSkipped if it is not
42 available."""
43 with catch_warning(record=False):
44 if deprecated:
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +000045 warnings.filterwarnings("ignore", ".+ (module|package)",
46 DeprecationWarning)
Benjamin Peterson699adb92008-05-08 22:27:58 +000047 try:
48 module = __import__(name, level=0)
49 except ImportError:
50 raise TestSkipped("No module named " + name)
51 else:
52 return module
53
Barry Warsawc0fb6052001-08-20 22:29:23 +000054verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +000055use_resources = None # Flag set to [] by regrtest.py
56max_memuse = 0 # Disable bigmem tests (they will still be run with
57 # small sizes, to make sure they work.)
Guido van Rossum531661c1996-12-20 02:58:22 +000058
Tim Peters8dee8092001-09-25 20:05:11 +000059# _original_stdout is meant to hold stdout at the time regrtest began.
60# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
61# The point is to have some flavor of stdout the user can actually see.
62_original_stdout = None
63def record_original_stdout(stdout):
64 global _original_stdout
65 _original_stdout = stdout
66
67def get_original_stdout():
68 return _original_stdout or sys.stdout
69
Guido van Rossum3bead091992-01-27 17:00:37 +000070def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +000071 try:
72 del sys.modules[name]
73 except KeyError:
74 pass
Guido van Rossum3bead091992-01-27 17:00:37 +000075
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000076def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000077 try:
78 os.unlink(filename)
79 except OSError:
80 pass
81
Christian Heimes23daade02008-02-25 12:39:23 +000082def rmtree(path):
83 try:
84 shutil.rmtree(path)
85 except OSError as e:
86 # Unix returns ENOENT, Windows returns ESRCH.
87 if e.errno not in (errno.ENOENT, errno.ESRCH):
88 raise
89
Guido van Rossum3bead091992-01-27 17:00:37 +000090def forget(modname):
Brett Cannonf1cfb622003-05-04 21:15:27 +000091 '''"Forget" a module was ever imported by removing it from sys.modules and
92 deleting any .pyc and .pyo files.'''
Fred Drake004d5e62000-10-23 17:22:08 +000093 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +000094 for dirname in sys.path:
Skip Montanaro7a98be22007-08-16 14:35:24 +000095 unlink(os.path.join(dirname, modname + '.pyc'))
Brett Cannonf1cfb622003-05-04 21:15:27 +000096 # Deleting the .pyo file cannot be within the 'try' for the .pyc since
97 # the chance exists that there is no .pyc (and thus the 'try' statement
98 # is exited) but there is a .pyo file.
Skip Montanaro7a98be22007-08-16 14:35:24 +000099 unlink(os.path.join(dirname, modname + '.pyo'))
Guido van Rossum3bead091992-01-27 17:00:37 +0000100
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000101def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000102 """Test whether a resource is enabled. Known resources are set by
103 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000104 return use_resources is not None and resource in use_resources
105
Barry Warsawc0fb6052001-08-20 22:29:23 +0000106def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000107 """Raise ResourceDenied if the specified resource is not available.
108
109 If the caller's module is __main__ then automatically return True. The
110 possibility of False being returned occurs when regrtest.py is executing."""
Skip Montanarod839ecd2003-04-24 19:06:57 +0000111 # see if the caller's module is __main__ - if so, treat as if
112 # the resource was set
113 if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
114 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000115 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000116 if msg is None:
117 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000118 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000119
Christian Heimes5e696852008-04-09 08:37:03 +0000120HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000121
Christian Heimes5e696852008-04-09 08:37:03 +0000122def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
123 """Returns an unused port that should be suitable for binding. This is
124 achieved by creating a temporary socket with the same family and type as
125 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
126 the specified host address (defaults to 0.0.0.0) with the port set to 0,
127 eliciting an unused ephemeral port from the OS. The temporary socket is
128 then closed and deleted, and the ephemeral port is returned.
129
130 Either this method or bind_port() should be used for any tests where a
131 server socket needs to be bound to a particular port for the duration of
132 the test. Which one to use depends on whether the calling code is creating
133 a python socket, or if an unused port needs to be provided in a constructor
134 or passed to an external program (i.e. the -accept argument to openssl's
135 s_server mode). Always prefer bind_port() over find_unused_port() where
136 possible. Hard coded ports should *NEVER* be used. As soon as a server
137 socket is bound to a hard coded port, the ability to run multiple instances
138 of the test simultaneously on the same host is compromised, which makes the
139 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
140 may simply manifest as a failed test, which can be recovered from without
141 intervention in most cases, but on Windows, the entire python process can
142 completely and utterly wedge, requiring someone to log in to the buildbot
143 and manually kill the affected process.
144
145 (This is easy to reproduce on Windows, unfortunately, and can be traced to
146 the SO_REUSEADDR socket option having different semantics on Windows versus
147 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
148 listen and then accept connections on identical host/ports. An EADDRINUSE
149 socket.error will be raised at some point (depending on the platform and
150 the order bind and listen were called on each socket).
151
152 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
153 will ever be raised when attempting to bind two identical host/ports. When
154 accept() is called on each socket, the second caller's process will steal
155 the port from the first caller, leaving them both in an awkwardly wedged
156 state where they'll no longer respond to any signals or graceful kills, and
157 must be forcibly killed via OpenProcess()/TerminateProcess().
158
159 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
160 instead of SO_REUSEADDR, which effectively affords the same semantics as
161 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
162 Source world compared to Windows ones, this is a common mistake. A quick
163 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
164 openssl.exe is called with the 's_server' option, for example. See
165 http://bugs.python.org/issue2550 for more info. The following site also
166 has a very thorough description about the implications of both REUSEADDR
167 and EXCLUSIVEADDRUSE on Windows:
168 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
169
170 XXX: although this approach is a vast improvement on previous attempts to
171 elicit unused ports, it rests heavily on the assumption that the ephemeral
172 port returned to us by the OS won't immediately be dished back out to some
173 other process when we close and delete our temporary socket but before our
174 calling code has a chance to bind the returned port. We can deal with this
175 issue if/when we come across it.
176 """
177
178 tempsock = socket.socket(family, socktype)
179 port = bind_port(tempsock)
180 tempsock.close()
181 del tempsock
182 return port
183
184def bind_port(sock, host=HOST):
185 """Bind the socket to a free port and return the port number. Relies on
186 ephemeral ports in order to ensure we are using an unbound port. This is
187 important as many tests may be running simultaneously, especially in a
188 buildbot environment. This method raises an exception if the sock.family
189 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
190 or SO_REUSEPORT set on it. Tests should *never* set these socket options
191 for TCP/IP sockets. The only case for setting these options is testing
192 multicasting via multiple UDP sockets.
193
194 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
195 on Windows), it will be set on the socket. This will prevent anyone else
196 from bind()'ing to our host/port for the duration of the test.
197 """
198
199 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
200 if hasattr(socket, 'SO_REUSEADDR'):
201 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
202 raise TestFailed("tests should never set the SO_REUSEADDR " \
203 "socket option on TCP/IP sockets!")
204 if hasattr(socket, 'SO_REUSEPORT'):
205 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
206 raise TestFailed("tests should never set the SO_REUSEPORT " \
207 "socket option on TCP/IP sockets!")
208 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
209 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
210
211 sock.bind((host, 0))
212 port = sock.getsockname()[1]
213 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000214
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000215FUZZ = 1e-6
216
217def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000218 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000219 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000220 fuzz = (abs(x) + abs(y)) * FUZZ
221 if abs(x-y) <= fuzz:
222 return 0
223 except:
224 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000225 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000226 for i in range(min(len(x), len(y))):
227 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000228 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000229 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000230 return (len(x) > len(y)) - (len(x) < len(y))
231 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000232
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000233try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000234 str
Neal Norwitz79212992006-08-21 16:27:31 +0000235 have_unicode = True
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000236except NameError:
Neal Norwitz79212992006-08-21 16:27:31 +0000237 have_unicode = False
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000238
Finn Bock57bc5fa2002-11-01 18:02:03 +0000239is_jython = sys.platform.startswith('java')
240
Barry Warsaw559f6682001-03-23 18:04:02 +0000241# Filename used for testing
242if os.name == 'java':
243 # Jython disallows @ in module names
244 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000245else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000246 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000247
248 # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
249 # TESTFN_UNICODE is a filename that can be encoded using the
250 # file system encoding, but *not* with the default (ascii) encoding
251 TESTFN_UNICODE = "@test-\xe0\xf2"
252 TESTFN_ENCODING = sys.getfilesystemencoding()
253 # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
254 # able to be encoded by *either* the default or filesystem encoding.
255 # This test really only makes sense on Windows NT platforms
256 # which have special Unicode support in posixmodule.
257 if (not hasattr(sys, "getwindowsversion") or
258 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
259 TESTFN_UNICODE_UNENCODEABLE = None
260 else:
261 # Japanese characters (I think - from bug 846133)
262 TESTFN_UNICODE_UNENCODEABLE = "@test-\u5171\u6709\u3055\u308c\u308b"
263 try:
264 # XXX - Note - should be using TESTFN_ENCODING here - but for
265 # Windows, "mbcs" currently always operates as if in
266 # errors=ignore' mode - hence we get '?' characters rather than
267 # the exception. 'Latin1' operates as we expect - ie, fails.
268 # See [ 850997 ] mbcs encoding ignores errors
269 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
270 except UnicodeEncodeError:
271 pass
Martin v. Löwis2411a2d2002-11-09 19:57:26 +0000272 else:
Georg Brandldb028442008-02-05 20:48:58 +0000273 print('WARNING: The filename %r CAN be encoded by the filesystem. '
274 'Unicode filename tests may not be effective'
275 % TESTFN_UNICODE_UNENCODEABLE)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000276
277# Make sure we can write to TESTFN, try in /tmp if we can't
278fp = None
279try:
280 fp = open(TESTFN, 'w+')
281except IOError:
282 TMP_TESTFN = os.path.join('/tmp', TESTFN)
283 try:
284 fp = open(TMP_TESTFN, 'w+')
285 TESTFN = TMP_TESTFN
286 del TMP_TESTFN
287 except IOError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000288 print(('WARNING: tests will fail, unable to write to: %s or %s' %
289 (TESTFN, TMP_TESTFN)))
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000290if fp is not None:
291 fp.close()
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000292 unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000293del fp
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000294
Guido van Rossume26132c1998-04-23 20:13:30 +0000295def findfile(file, here=__file__):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000296 """Try to find a file on sys.path and the working directory. If it is not
297 found the argument passed to the function is returned (this does not
298 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000299 if os.path.isabs(file):
300 return file
Fred Drake004d5e62000-10-23 17:22:08 +0000301 path = sys.path
302 path = [os.path.dirname(here)] + path
303 for dn in path:
304 fn = os.path.join(dn, file)
305 if os.path.exists(fn): return fn
306 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000307
308def verify(condition, reason='test failed'):
Guido van Rossuma1374e42001-01-19 19:01:56 +0000309 """Verify that condition is true. If not, raise TestFailed.
Marc-André Lemburg36619082001-01-17 19:11:13 +0000310
Skip Montanaroc955f892001-01-20 19:12:54 +0000311 The optional argument reason can be given to provide
Tim Peters983874d2001-01-19 05:59:21 +0000312 a better error text.
Tim Petersd2bf3b72001-01-18 02:22:22 +0000313 """
Tim Peters983874d2001-01-19 05:59:21 +0000314
Tim Petersd2bf3b72001-01-18 02:22:22 +0000315 if not condition:
Guido van Rossuma1374e42001-01-19 19:01:56 +0000316 raise TestFailed(reason)
Jeremy Hylton47793992001-02-19 15:35:26 +0000317
Tim Petersc2fe6182001-10-30 23:20:46 +0000318def vereq(a, b):
Tim Peters77902972001-12-29 17:34:57 +0000319 """Raise TestFailed if a == b is false.
320
321 This is better than verify(a == b) because, in case of failure, the
322 error message incorporates repr(a) and repr(b) so you can see the
323 inputs.
324
325 Note that "not (a == b)" isn't necessarily the same as "a != b"; the
326 former is tested.
327 """
328
Tim Petersc2fe6182001-10-30 23:20:46 +0000329 if not (a == b):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000330 raise TestFailed("%r == %r" % (a, b))
Tim Petersc2fe6182001-10-30 23:20:46 +0000331
Tim Peters2f228e72001-05-13 00:19:31 +0000332def sortdict(dict):
333 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000334 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000335 reprpairs = ["%r: %r" % pair for pair in items]
336 withcommas = ", ".join(reprpairs)
337 return "{%s}" % withcommas
338
Thomas Wouters89f507f2006-12-13 04:49:30 +0000339def check_syntax_error(testcase, statement):
Jeremy Hylton47793992001-02-19 15:35:26 +0000340 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000341 compile(statement, '<test string>', 'exec')
Jeremy Hylton47793992001-02-19 15:35:26 +0000342 except SyntaxError:
343 pass
344 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000345 testcase.fail('Missing SyntaxError: "%s"' % statement)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000346
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000347def open_urlresource(url, *args, **kw):
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000348 import urllib, urlparse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000349
Guido van Rossum360e4b82007-05-14 22:51:27 +0000350 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000351 filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
352
353 for path in [os.path.curdir, os.path.pardir]:
354 fn = os.path.join(path, filename)
355 if os.path.exists(fn):
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000356 return open(fn, *args, **kw)
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000357
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000358 print('\tfetching %s ...' % url, file=get_original_stdout())
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000359 fn, _ = urllib.urlretrieve(url, filename)
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000360 return open(fn, *args, **kw)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000361
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000362
Guido van Rossumd8faa362007-04-27 19:54:29 +0000363class WarningMessage(object):
364 "Holds the result of the latest showwarning() call"
365 def __init__(self):
366 self.message = None
367 self.category = None
368 self.filename = None
369 self.lineno = None
370
Christian Heimes33fe8092008-04-13 13:53:33 +0000371 def _showwarning(self, message, category, filename, lineno, file=None,
372 line=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000373 self.message = message
374 self.category = category
375 self.filename = filename
376 self.lineno = lineno
Christian Heimes33fe8092008-04-13 13:53:33 +0000377 self.line = line
378
379 def reset(self):
380 self._showwarning(*((None,)*6))
381
382 def __str__(self):
383 return ("{message : %r, category : %r, filename : %r, lineno : %s, "
384 "line : %r}" % (self.message,
385 self.category.__name__ if self.category else None,
386 self.filename, self.lineno, self.line))
387
Guido van Rossumd8faa362007-04-27 19:54:29 +0000388
389@contextlib.contextmanager
Benjamin Peterson699adb92008-05-08 22:27:58 +0000390def catch_warning(module=warnings, record=True):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000391 """
392 Guard the warnings filter from being permanently changed and record the
393 data of the last warning that has been issued.
394
395 Use like this:
396
Guido van Rossumaf554a02007-08-16 23:48:43 +0000397 with catch_warning() as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000398 warnings.warn("foo")
399 assert str(w.message) == "foo"
400 """
Christian Heimes33fe8092008-04-13 13:53:33 +0000401 original_filters = module.filters[:]
402 original_showwarning = module.showwarning
Benjamin Peterson699adb92008-05-08 22:27:58 +0000403 if record:
404 warning_obj = WarningMessage()
405 module.showwarning = warning_obj._showwarning
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 try:
Benjamin Peterson699adb92008-05-08 22:27:58 +0000407 yield warning_obj if record else None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000408 finally:
Christian Heimes33fe8092008-04-13 13:53:33 +0000409 module.showwarning = original_showwarning
410 module.filters = original_filters
Guido van Rossumd8faa362007-04-27 19:54:29 +0000411
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000412
413class CleanImport(object):
414 """Context manager to force import to return a new module reference.
415
416 This is useful for testing module-level behaviours, such as
417 the emission of a DepreciationWarning on import.
418
419 Use like this:
420
421 with CleanImport("foo"):
422 __import__("foo") # new reference
423 """
424
425 def __init__(self, *module_names):
426 self.original_modules = sys.modules.copy()
427 for module_name in module_names:
428 if module_name in sys.modules:
429 module = sys.modules[module_name]
430 # It is possible that module_name is just an alias for
431 # another module (e.g. stub for modules renamed in 3.x).
432 # In that case, we also need delete the real module to clear
433 # the import cache.
434 if module.__name__ != module_name:
435 del sys.modules[module.__name__]
436 del sys.modules[module_name]
437
438 def __enter__(self):
439 return self
440
441 def __exit__(self, *ignore_exc):
442 sys.modules.update(self.original_modules)
443
444
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000445class EnvironmentVarGuard(object):
446
447 """Class to help protect the environment variable properly. Can be used as
448 a context manager."""
449
450 def __init__(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 self._environ = os.environ
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000452 self._unset = set()
453 self._reset = dict()
454
455 def set(self, envvar, value):
456 if envvar not in self._environ:
457 self._unset.add(envvar)
458 else:
459 self._reset[envvar] = self._environ[envvar]
460 self._environ[envvar] = value
461
462 def unset(self, envvar):
463 if envvar in self._environ:
464 self._reset[envvar] = self._environ[envvar]
465 del self._environ[envvar]
466
467 def __enter__(self):
468 return self
469
470 def __exit__(self, *ignore_exc):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000471 for envvar, value in self._reset.items():
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000472 self._environ[envvar] = value
473 for unset in self._unset:
474 del self._environ[unset]
475
Guido van Rossumd8faa362007-04-27 19:54:29 +0000476class TransientResource(object):
477
478 """Raise ResourceDenied if an exception is raised while the context manager
479 is in effect that matches the specified exception and attributes."""
480
481 def __init__(self, exc, **kwargs):
482 self.exc = exc
483 self.attrs = kwargs
484
485 def __enter__(self):
486 return self
487
488 def __exit__(self, type_=None, value=None, traceback=None):
489 """If type_ is a subclass of self.exc and value has attributes matching
490 self.attrs, raise ResourceDenied. Otherwise let the exception
491 propagate (if any)."""
492 if type_ is not None and issubclass(self.exc, type_):
493 for attr, attr_value in self.attrs.items():
494 if not hasattr(value, attr):
495 break
496 if getattr(value, attr) != attr_value:
497 break
498 else:
499 raise ResourceDenied("an optional resource is not available")
500
501
502def transient_internet():
503 """Return a context manager that raises ResourceDenied when various issues
504 with the Internet connection manifest themselves as exceptions."""
505 time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
506 socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
507 ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
508 return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
509
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000510
Thomas Woutersed03b412007-08-28 21:37:11 +0000511@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000512def captured_output(stream_name):
513 """Run the 'with' statement body using a StringIO object in place of a
514 specific attribute on the sys module.
515 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000516
517 with captured_stdout() as s:
Neal Norwitz752abd02008-05-13 04:55:24 +0000518 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000519 assert s.getvalue() == "hello"
520 """
521 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000522 orig_stdout = getattr(sys, stream_name)
523 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000524 try:
525 yield getattr(sys, stream_name)
526 finally:
527 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000528
529def captured_stdout():
530 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000531
532
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000533#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534# Decorator for running a function in a different locale, correctly resetting
535# it afterwards.
536
537def run_with_locale(catstr, *locales):
538 def decorator(func):
539 def inner(*args, **kwds):
540 try:
541 import locale
542 category = getattr(locale, catstr)
543 orig_locale = locale.setlocale(category)
544 except AttributeError:
545 # if the test author gives us an invalid category string
546 raise
547 except:
548 # cannot retrieve original locale, so do nothing
549 locale = orig_locale = None
550 else:
551 for loc in locales:
552 try:
553 locale.setlocale(category, loc)
554 break
555 except:
556 pass
557
558 # now run the function, resetting the locale on exceptions
559 try:
560 return func(*args, **kwds)
561 finally:
562 if locale and orig_locale:
563 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000564 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565 inner.__doc__ = func.__doc__
566 return inner
567 return decorator
568
569#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000570# Big-memory-test support. Separate from 'resources' because memory use
571# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572
573# Some handy shorthands. Note that these are used for byte-limits as well
574# as size-limits, in the various bigmem tests
575_1M = 1024*1024
576_1G = 1024 * _1M
577_2G = 2 * _1G
578
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000579MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581def set_memlimit(limit):
582 import re
583 global max_memuse
584 sizes = {
585 'k': 1024,
586 'm': _1M,
587 'g': _1G,
588 't': 1024*_1G,
589 }
590 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
591 re.IGNORECASE | re.VERBOSE)
592 if m is None:
593 raise ValueError('Invalid memory limit %r' % (limit,))
594 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595 if memlimit > MAX_Py_ssize_t:
596 memlimit = MAX_Py_ssize_t
597 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 raise ValueError('Memory limit %r too low to be useful' % (limit,))
599 max_memuse = memlimit
600
601def bigmemtest(minsize, memuse, overhead=5*_1M):
602 """Decorator for bigmem tests.
603
604 'minsize' is the minimum useful size for the test (in arbitrary,
605 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
606 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
Christian Heimes33fe8092008-04-13 13:53:33 +0000607 independent of the testsize, and defaults to 5Mb.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000608
609 The decorator tries to guess a good value for 'size' and passes it to
610 the decorated test function. If minsize * memuse is more than the
611 allowed memory use (as defined by max_memuse), the test is skipped.
612 Otherwise, minsize is adjusted upward to use up to max_memuse.
613 """
614 def decorator(f):
615 def wrapper(self):
616 if not max_memuse:
617 # If max_memuse is 0 (the default),
618 # we still want to run the tests with size set to a few kb,
619 # to make sure they work. We still want to avoid using
620 # too much memory, though, but we do that noisily.
621 maxsize = 5147
622 self.failIf(maxsize * memuse + overhead > 20 * _1M)
623 else:
624 maxsize = int((max_memuse - overhead) / memuse)
625 if maxsize < minsize:
626 # Really ought to print 'test skipped' or something
627 if verbose:
628 sys.stderr.write("Skipping %s because of memory "
629 "constraint\n" % (f.__name__,))
630 return
631 # Try to keep some breathing room in memory use
632 maxsize = max(maxsize - 50 * _1M, minsize)
633 return f(self, maxsize)
634 wrapper.minsize = minsize
635 wrapper.memuse = memuse
636 wrapper.overhead = overhead
637 return wrapper
638 return decorator
639
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000640def bigaddrspacetest(f):
641 """Decorator for tests that fill the address space."""
642 def wrapper(self):
643 if max_memuse < MAX_Py_ssize_t:
644 if verbose:
645 sys.stderr.write("Skipping %s because of memory "
646 "constraint\n" % (f.__name__,))
647 else:
648 return f(self)
649 return wrapper
650
Thomas Wouters477c8d52006-05-27 19:21:47 +0000651#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000653
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000654class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000655 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000656 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000657 test(result)
658 return result
659
660
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +0000662 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000663 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +0000664 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000665 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000666 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000667
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000668 result = runner.run(suite)
669 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +0000670 if len(result.errors) == 1 and not result.failures:
671 err = result.errors[0][1]
672 elif len(result.failures) == 1 and not result.errors:
673 err = result.failures[0][1]
674 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000675 err = "errors occurred; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +0000676 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +0000677
Barry Warsawc10d6902001-09-20 06:30:41 +0000678
Walter Dörwald21d3a322003-05-01 17:45:56 +0000679def run_unittest(*classes):
680 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000681 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000682 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000683 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000684 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685 if cls in sys.modules:
686 suite.addTest(unittest.findTestCases(sys.modules[cls]))
687 else:
688 raise ValueError("str arguments must be keys in sys.modules")
689 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +0000690 suite.addTest(cls)
691 else:
692 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000693 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000694
Barry Warsawc10d6902001-09-20 06:30:41 +0000695
Tim Petersa0a62222001-09-09 06:12:01 +0000696#=======================================================================
697# doctest driver.
698
699def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +0000700 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +0000701
702 If optional argument verbosity is not specified (or is None), pass
Tim Petersbea3fb82001-09-10 01:39:21 +0000703 test_support's belief about verbosity on to doctest. Else doctest's
704 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +0000705 """
706
707 import doctest
708
709 if verbosity is None:
710 verbosity = verbose
711 else:
712 verbosity = None
713
Tim Peters342ca752001-09-25 19:13:20 +0000714 # Direct doctest output (normally just errors) to real stdout; doctest
715 # output shouldn't be compared by regrtest.
716 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +0000717 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +0000718 try:
719 f, t = doctest.testmod(module, verbose=verbosity)
720 if f:
721 raise TestFailed("%d of %d doctests failed" % (f, t))
722 finally:
723 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000724 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +0000725 print('doctest (%s) ... %d tests with zero failures' %
726 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000727 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000728
729#=======================================================================
730# Threading support to prevent reporting refleaks when running regrtest.py -R
731
732def threading_setup():
733 import threading
734 return len(threading._active), len(threading._limbo)
735
736def threading_cleanup(num_active, num_limbo):
737 import threading
738 import time
739
740 _MAX_COUNT = 10
741 count = 0
742 while len(threading._active) != num_active and count < _MAX_COUNT:
743 count += 1
744 time.sleep(0.1)
745
746 count = 0
747 while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
748 count += 1
749 time.sleep(0.1)
750
751def reap_children():
752 """Use this function at the end of test_main() whenever sub-processes
753 are started. This will help ensure that no extra children (zombies)
754 stick around to hog resources and create problems when looking
755 for refleaks.
756 """
757
758 # Reap all our dead child processes so we don't leave zombies around.
759 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000760 if hasattr(os, 'waitpid'):
761 any_process = -1
762 while True:
763 try:
764 # This will raise an exception on Windows. That's ok.
765 pid, status = os.waitpid(any_process, os.WNOHANG)
766 if pid == 0:
767 break
768 except:
769 break