blob: 431b66bb092f7a90446a9fc072a0515986755ded [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
Barry Warsawc0fb6052001-08-20 22:29:23 +000040verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +000041use_resources = None # Flag set to [] by regrtest.py
42max_memuse = 0 # Disable bigmem tests (they will still be run with
43 # small sizes, to make sure they work.)
Guido van Rossum531661c1996-12-20 02:58:22 +000044
Tim Peters8dee8092001-09-25 20:05:11 +000045# _original_stdout is meant to hold stdout at the time regrtest began.
46# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
47# The point is to have some flavor of stdout the user can actually see.
48_original_stdout = None
49def record_original_stdout(stdout):
50 global _original_stdout
51 _original_stdout = stdout
52
53def get_original_stdout():
54 return _original_stdout or sys.stdout
55
Guido van Rossum3bead091992-01-27 17:00:37 +000056def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +000057 try:
58 del sys.modules[name]
59 except KeyError:
60 pass
Guido van Rossum3bead091992-01-27 17:00:37 +000061
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000062def unlink(filename):
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000063 try:
64 os.unlink(filename)
65 except OSError:
66 pass
67
Christian Heimes23daade02008-02-25 12:39:23 +000068def rmtree(path):
69 try:
70 shutil.rmtree(path)
71 except OSError as e:
72 # Unix returns ENOENT, Windows returns ESRCH.
73 if e.errno not in (errno.ENOENT, errno.ESRCH):
74 raise
75
Guido van Rossum3bead091992-01-27 17:00:37 +000076def forget(modname):
Brett Cannonf1cfb622003-05-04 21:15:27 +000077 '''"Forget" a module was ever imported by removing it from sys.modules and
78 deleting any .pyc and .pyo files.'''
Fred Drake004d5e62000-10-23 17:22:08 +000079 unload(modname)
Fred Drake004d5e62000-10-23 17:22:08 +000080 for dirname in sys.path:
Skip Montanaro7a98be22007-08-16 14:35:24 +000081 unlink(os.path.join(dirname, modname + '.pyc'))
Brett Cannonf1cfb622003-05-04 21:15:27 +000082 # Deleting the .pyo file cannot be within the 'try' for the .pyc since
83 # the chance exists that there is no .pyc (and thus the 'try' statement
84 # is exited) but there is a .pyo file.
Skip Montanaro7a98be22007-08-16 14:35:24 +000085 unlink(os.path.join(dirname, modname + '.pyo'))
Guido van Rossum3bead091992-01-27 17:00:37 +000086
Tim Petersb4ee4eb2002-12-04 03:26:57 +000087def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +000088 """Test whether a resource is enabled. Known resources are set by
89 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +000090 return use_resources is not None and resource in use_resources
91
Barry Warsawc0fb6052001-08-20 22:29:23 +000092def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +000093 """Raise ResourceDenied if the specified resource is not available.
94
95 If the caller's module is __main__ then automatically return True. The
96 possibility of False being returned occurs when regrtest.py is executing."""
Skip Montanarod839ecd2003-04-24 19:06:57 +000097 # see if the caller's module is __main__ - if so, treat as if
98 # the resource was set
99 if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
100 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +0000101 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +0000102 if msg is None:
103 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +0000104 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +0000105
Christian Heimes5e696852008-04-09 08:37:03 +0000106HOST = 'localhost'
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107
Christian Heimes5e696852008-04-09 08:37:03 +0000108def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
109 """Returns an unused port that should be suitable for binding. This is
110 achieved by creating a temporary socket with the same family and type as
111 the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
112 the specified host address (defaults to 0.0.0.0) with the port set to 0,
113 eliciting an unused ephemeral port from the OS. The temporary socket is
114 then closed and deleted, and the ephemeral port is returned.
115
116 Either this method or bind_port() should be used for any tests where a
117 server socket needs to be bound to a particular port for the duration of
118 the test. Which one to use depends on whether the calling code is creating
119 a python socket, or if an unused port needs to be provided in a constructor
120 or passed to an external program (i.e. the -accept argument to openssl's
121 s_server mode). Always prefer bind_port() over find_unused_port() where
122 possible. Hard coded ports should *NEVER* be used. As soon as a server
123 socket is bound to a hard coded port, the ability to run multiple instances
124 of the test simultaneously on the same host is compromised, which makes the
125 test a ticking time bomb in a buildbot environment. On Unix buildbots, this
126 may simply manifest as a failed test, which can be recovered from without
127 intervention in most cases, but on Windows, the entire python process can
128 completely and utterly wedge, requiring someone to log in to the buildbot
129 and manually kill the affected process.
130
131 (This is easy to reproduce on Windows, unfortunately, and can be traced to
132 the SO_REUSEADDR socket option having different semantics on Windows versus
133 Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
134 listen and then accept connections on identical host/ports. An EADDRINUSE
135 socket.error will be raised at some point (depending on the platform and
136 the order bind and listen were called on each socket).
137
138 However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
139 will ever be raised when attempting to bind two identical host/ports. When
140 accept() is called on each socket, the second caller's process will steal
141 the port from the first caller, leaving them both in an awkwardly wedged
142 state where they'll no longer respond to any signals or graceful kills, and
143 must be forcibly killed via OpenProcess()/TerminateProcess().
144
145 The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
146 instead of SO_REUSEADDR, which effectively affords the same semantics as
147 SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open
148 Source world compared to Windows ones, this is a common mistake. A quick
149 look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
150 openssl.exe is called with the 's_server' option, for example. See
151 http://bugs.python.org/issue2550 for more info. The following site also
152 has a very thorough description about the implications of both REUSEADDR
153 and EXCLUSIVEADDRUSE on Windows:
154 http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
155
156 XXX: although this approach is a vast improvement on previous attempts to
157 elicit unused ports, it rests heavily on the assumption that the ephemeral
158 port returned to us by the OS won't immediately be dished back out to some
159 other process when we close and delete our temporary socket but before our
160 calling code has a chance to bind the returned port. We can deal with this
161 issue if/when we come across it.
162 """
163
164 tempsock = socket.socket(family, socktype)
165 port = bind_port(tempsock)
166 tempsock.close()
167 del tempsock
168 return port
169
170def bind_port(sock, host=HOST):
171 """Bind the socket to a free port and return the port number. Relies on
172 ephemeral ports in order to ensure we are using an unbound port. This is
173 important as many tests may be running simultaneously, especially in a
174 buildbot environment. This method raises an exception if the sock.family
175 is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
176 or SO_REUSEPORT set on it. Tests should *never* set these socket options
177 for TCP/IP sockets. The only case for setting these options is testing
178 multicasting via multiple UDP sockets.
179
180 Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
181 on Windows), it will be set on the socket. This will prevent anyone else
182 from bind()'ing to our host/port for the duration of the test.
183 """
184
185 if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
186 if hasattr(socket, 'SO_REUSEADDR'):
187 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
188 raise TestFailed("tests should never set the SO_REUSEADDR " \
189 "socket option on TCP/IP sockets!")
190 if hasattr(socket, 'SO_REUSEPORT'):
191 if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
192 raise TestFailed("tests should never set the SO_REUSEPORT " \
193 "socket option on TCP/IP sockets!")
194 if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
195 sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
196
197 sock.bind((host, 0))
198 port = sock.getsockname()[1]
199 return port
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000200
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000201FUZZ = 1e-6
202
203def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000204 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000205 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000206 fuzz = (abs(x) + abs(y)) * FUZZ
207 if abs(x-y) <= fuzz:
208 return 0
209 except:
210 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000211 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000212 for i in range(min(len(x), len(y))):
213 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000214 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000215 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000216 return (len(x) > len(y)) - (len(x) < len(y))
217 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000218
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000219try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000220 str
Neal Norwitz79212992006-08-21 16:27:31 +0000221 have_unicode = True
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000222except NameError:
Neal Norwitz79212992006-08-21 16:27:31 +0000223 have_unicode = False
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000224
Finn Bock57bc5fa2002-11-01 18:02:03 +0000225is_jython = sys.platform.startswith('java')
226
Barry Warsaw559f6682001-03-23 18:04:02 +0000227# Filename used for testing
228if os.name == 'java':
229 # Jython disallows @ in module names
230 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000231else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000232 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000233
234 # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
235 # TESTFN_UNICODE is a filename that can be encoded using the
236 # file system encoding, but *not* with the default (ascii) encoding
237 TESTFN_UNICODE = "@test-\xe0\xf2"
238 TESTFN_ENCODING = sys.getfilesystemencoding()
239 # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
240 # able to be encoded by *either* the default or filesystem encoding.
241 # This test really only makes sense on Windows NT platforms
242 # which have special Unicode support in posixmodule.
243 if (not hasattr(sys, "getwindowsversion") or
244 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
245 TESTFN_UNICODE_UNENCODEABLE = None
246 else:
247 # Japanese characters (I think - from bug 846133)
248 TESTFN_UNICODE_UNENCODEABLE = "@test-\u5171\u6709\u3055\u308c\u308b"
249 try:
250 # XXX - Note - should be using TESTFN_ENCODING here - but for
251 # Windows, "mbcs" currently always operates as if in
252 # errors=ignore' mode - hence we get '?' characters rather than
253 # the exception. 'Latin1' operates as we expect - ie, fails.
254 # See [ 850997 ] mbcs encoding ignores errors
255 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
256 except UnicodeEncodeError:
257 pass
Martin v. Löwis2411a2d2002-11-09 19:57:26 +0000258 else:
Georg Brandldb028442008-02-05 20:48:58 +0000259 print('WARNING: The filename %r CAN be encoded by the filesystem. '
260 'Unicode filename tests may not be effective'
261 % TESTFN_UNICODE_UNENCODEABLE)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000262
263# Make sure we can write to TESTFN, try in /tmp if we can't
264fp = None
265try:
266 fp = open(TESTFN, 'w+')
267except IOError:
268 TMP_TESTFN = os.path.join('/tmp', TESTFN)
269 try:
270 fp = open(TMP_TESTFN, 'w+')
271 TESTFN = TMP_TESTFN
272 del TMP_TESTFN
273 except IOError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000274 print(('WARNING: tests will fail, unable to write to: %s or %s' %
275 (TESTFN, TMP_TESTFN)))
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000276if fp is not None:
277 fp.close()
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000278 unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000279del fp
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000280
Guido van Rossume26132c1998-04-23 20:13:30 +0000281def findfile(file, here=__file__):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000282 """Try to find a file on sys.path and the working directory. If it is not
283 found the argument passed to the function is returned (this does not
284 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000285 if os.path.isabs(file):
286 return file
Fred Drake004d5e62000-10-23 17:22:08 +0000287 path = sys.path
288 path = [os.path.dirname(here)] + path
289 for dn in path:
290 fn = os.path.join(dn, file)
291 if os.path.exists(fn): return fn
292 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000293
294def verify(condition, reason='test failed'):
Guido van Rossuma1374e42001-01-19 19:01:56 +0000295 """Verify that condition is true. If not, raise TestFailed.
Marc-André Lemburg36619082001-01-17 19:11:13 +0000296
Skip Montanaroc955f892001-01-20 19:12:54 +0000297 The optional argument reason can be given to provide
Tim Peters983874d2001-01-19 05:59:21 +0000298 a better error text.
Tim Petersd2bf3b72001-01-18 02:22:22 +0000299 """
Tim Peters983874d2001-01-19 05:59:21 +0000300
Tim Petersd2bf3b72001-01-18 02:22:22 +0000301 if not condition:
Guido van Rossuma1374e42001-01-19 19:01:56 +0000302 raise TestFailed(reason)
Jeremy Hylton47793992001-02-19 15:35:26 +0000303
Tim Petersc2fe6182001-10-30 23:20:46 +0000304def vereq(a, b):
Tim Peters77902972001-12-29 17:34:57 +0000305 """Raise TestFailed if a == b is false.
306
307 This is better than verify(a == b) because, in case of failure, the
308 error message incorporates repr(a) and repr(b) so you can see the
309 inputs.
310
311 Note that "not (a == b)" isn't necessarily the same as "a != b"; the
312 former is tested.
313 """
314
Tim Petersc2fe6182001-10-30 23:20:46 +0000315 if not (a == b):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000316 raise TestFailed("%r == %r" % (a, b))
Tim Petersc2fe6182001-10-30 23:20:46 +0000317
Tim Peters2f228e72001-05-13 00:19:31 +0000318def sortdict(dict):
319 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000320 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000321 reprpairs = ["%r: %r" % pair for pair in items]
322 withcommas = ", ".join(reprpairs)
323 return "{%s}" % withcommas
324
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325def check_syntax_error(testcase, statement):
Jeremy Hylton47793992001-02-19 15:35:26 +0000326 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000327 compile(statement, '<test string>', 'exec')
Jeremy Hylton47793992001-02-19 15:35:26 +0000328 except SyntaxError:
329 pass
330 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000331 testcase.fail('Missing SyntaxError: "%s"' % statement)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000332
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000333def open_urlresource(url, *args, **kw):
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000334 import urllib, urlparse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000335
Guido van Rossum360e4b82007-05-14 22:51:27 +0000336 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000337 filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
338
339 for path in [os.path.curdir, os.path.pardir]:
340 fn = os.path.join(path, filename)
341 if os.path.exists(fn):
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000342 return open(fn, *args, **kw)
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000343
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000344 print('\tfetching %s ...' % url, file=get_original_stdout())
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000345 fn, _ = urllib.urlretrieve(url, filename)
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000346 return open(fn, *args, **kw)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000347
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000348
Guido van Rossumd8faa362007-04-27 19:54:29 +0000349class WarningMessage(object):
350 "Holds the result of the latest showwarning() call"
351 def __init__(self):
352 self.message = None
353 self.category = None
354 self.filename = None
355 self.lineno = None
356
Christian Heimes33fe8092008-04-13 13:53:33 +0000357 def _showwarning(self, message, category, filename, lineno, file=None,
358 line=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000359 self.message = message
360 self.category = category
361 self.filename = filename
362 self.lineno = lineno
Christian Heimes33fe8092008-04-13 13:53:33 +0000363 self.line = line
364
365 def reset(self):
366 self._showwarning(*((None,)*6))
367
368 def __str__(self):
369 return ("{message : %r, category : %r, filename : %r, lineno : %s, "
370 "line : %r}" % (self.message,
371 self.category.__name__ if self.category else None,
372 self.filename, self.lineno, self.line))
373
Guido van Rossumd8faa362007-04-27 19:54:29 +0000374
375@contextlib.contextmanager
Christian Heimes33fe8092008-04-13 13:53:33 +0000376def catch_warning(module=warnings):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000377 """
378 Guard the warnings filter from being permanently changed and record the
379 data of the last warning that has been issued.
380
381 Use like this:
382
Guido van Rossumaf554a02007-08-16 23:48:43 +0000383 with catch_warning() as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000384 warnings.warn("foo")
385 assert str(w.message) == "foo"
386 """
Christian Heimes33fe8092008-04-13 13:53:33 +0000387 warning_obj = WarningMessage()
388 original_filters = module.filters[:]
389 original_showwarning = module.showwarning
390 module.showwarning = warning_obj._showwarning
Guido van Rossumd8faa362007-04-27 19:54:29 +0000391 try:
Christian Heimes33fe8092008-04-13 13:53:33 +0000392 yield warning_obj
Guido van Rossumd8faa362007-04-27 19:54:29 +0000393 finally:
Christian Heimes33fe8092008-04-13 13:53:33 +0000394 module.showwarning = original_showwarning
395 module.filters = original_filters
Guido van Rossumd8faa362007-04-27 19:54:29 +0000396
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000397class EnvironmentVarGuard(object):
398
399 """Class to help protect the environment variable properly. Can be used as
400 a context manager."""
401
402 def __init__(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000403 self._environ = os.environ
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000404 self._unset = set()
405 self._reset = dict()
406
407 def set(self, envvar, value):
408 if envvar not in self._environ:
409 self._unset.add(envvar)
410 else:
411 self._reset[envvar] = self._environ[envvar]
412 self._environ[envvar] = value
413
414 def unset(self, envvar):
415 if envvar in self._environ:
416 self._reset[envvar] = self._environ[envvar]
417 del self._environ[envvar]
418
419 def __enter__(self):
420 return self
421
422 def __exit__(self, *ignore_exc):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000423 for envvar, value in self._reset.items():
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000424 self._environ[envvar] = value
425 for unset in self._unset:
426 del self._environ[unset]
427
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428class TransientResource(object):
429
430 """Raise ResourceDenied if an exception is raised while the context manager
431 is in effect that matches the specified exception and attributes."""
432
433 def __init__(self, exc, **kwargs):
434 self.exc = exc
435 self.attrs = kwargs
436
437 def __enter__(self):
438 return self
439
440 def __exit__(self, type_=None, value=None, traceback=None):
441 """If type_ is a subclass of self.exc and value has attributes matching
442 self.attrs, raise ResourceDenied. Otherwise let the exception
443 propagate (if any)."""
444 if type_ is not None and issubclass(self.exc, type_):
445 for attr, attr_value in self.attrs.items():
446 if not hasattr(value, attr):
447 break
448 if getattr(value, attr) != attr_value:
449 break
450 else:
451 raise ResourceDenied("an optional resource is not available")
452
453
454def transient_internet():
455 """Return a context manager that raises ResourceDenied when various issues
456 with the Internet connection manifest themselves as exceptions."""
457 time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
458 socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
459 ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
460 return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
461
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000462
Thomas Woutersed03b412007-08-28 21:37:11 +0000463@contextlib.contextmanager
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000464def captured_output(stream_name):
465 """Run the 'with' statement body using a StringIO object in place of a
466 specific attribute on the sys module.
467 Example use (with 'stream_name=stdout')::
Thomas Woutersed03b412007-08-28 21:37:11 +0000468
469 with captured_stdout() as s:
470 print "hello"
471 assert s.getvalue() == "hello"
472 """
473 import io
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000474 orig_stdout = getattr(sys, stream_name)
475 setattr(sys, stream_name, io.StringIO())
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000476 try:
477 yield getattr(sys, stream_name)
478 finally:
479 setattr(sys, stream_name, orig_stdout)
Benjamin Petersonad9d48d2008-04-02 21:49:44 +0000480
481def captured_stdout():
482 return captured_output("stdout")
Thomas Woutersed03b412007-08-28 21:37:11 +0000483
484
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000485#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000486# Decorator for running a function in a different locale, correctly resetting
487# it afterwards.
488
489def run_with_locale(catstr, *locales):
490 def decorator(func):
491 def inner(*args, **kwds):
492 try:
493 import locale
494 category = getattr(locale, catstr)
495 orig_locale = locale.setlocale(category)
496 except AttributeError:
497 # if the test author gives us an invalid category string
498 raise
499 except:
500 # cannot retrieve original locale, so do nothing
501 locale = orig_locale = None
502 else:
503 for loc in locales:
504 try:
505 locale.setlocale(category, loc)
506 break
507 except:
508 pass
509
510 # now run the function, resetting the locale on exceptions
511 try:
512 return func(*args, **kwds)
513 finally:
514 if locale and orig_locale:
515 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000516 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517 inner.__doc__ = func.__doc__
518 return inner
519 return decorator
520
521#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000522# Big-memory-test support. Separate from 'resources' because memory use
523# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000524
525# Some handy shorthands. Note that these are used for byte-limits as well
526# as size-limits, in the various bigmem tests
527_1M = 1024*1024
528_1G = 1024 * _1M
529_2G = 2 * _1G
530
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000531MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000532
Thomas Wouters477c8d52006-05-27 19:21:47 +0000533def set_memlimit(limit):
534 import re
535 global max_memuse
536 sizes = {
537 'k': 1024,
538 'm': _1M,
539 'g': _1G,
540 't': 1024*_1G,
541 }
542 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
543 re.IGNORECASE | re.VERBOSE)
544 if m is None:
545 raise ValueError('Invalid memory limit %r' % (limit,))
546 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000547 if memlimit > MAX_Py_ssize_t:
548 memlimit = MAX_Py_ssize_t
549 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000550 raise ValueError('Memory limit %r too low to be useful' % (limit,))
551 max_memuse = memlimit
552
553def bigmemtest(minsize, memuse, overhead=5*_1M):
554 """Decorator for bigmem tests.
555
556 'minsize' is the minimum useful size for the test (in arbitrary,
557 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
558 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
Christian Heimes33fe8092008-04-13 13:53:33 +0000559 independent of the testsize, and defaults to 5Mb.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560
561 The decorator tries to guess a good value for 'size' and passes it to
562 the decorated test function. If minsize * memuse is more than the
563 allowed memory use (as defined by max_memuse), the test is skipped.
564 Otherwise, minsize is adjusted upward to use up to max_memuse.
565 """
566 def decorator(f):
567 def wrapper(self):
568 if not max_memuse:
569 # If max_memuse is 0 (the default),
570 # we still want to run the tests with size set to a few kb,
571 # to make sure they work. We still want to avoid using
572 # too much memory, though, but we do that noisily.
573 maxsize = 5147
574 self.failIf(maxsize * memuse + overhead > 20 * _1M)
575 else:
576 maxsize = int((max_memuse - overhead) / memuse)
577 if maxsize < minsize:
578 # Really ought to print 'test skipped' or something
579 if verbose:
580 sys.stderr.write("Skipping %s because of memory "
581 "constraint\n" % (f.__name__,))
582 return
583 # Try to keep some breathing room in memory use
584 maxsize = max(maxsize - 50 * _1M, minsize)
585 return f(self, maxsize)
586 wrapper.minsize = minsize
587 wrapper.memuse = memuse
588 wrapper.overhead = overhead
589 return wrapper
590 return decorator
591
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000592def bigaddrspacetest(f):
593 """Decorator for tests that fill the address space."""
594 def wrapper(self):
595 if max_memuse < MAX_Py_ssize_t:
596 if verbose:
597 sys.stderr.write("Skipping %s because of memory "
598 "constraint\n" % (f.__name__,))
599 else:
600 return f(self)
601 return wrapper
602
Thomas Wouters477c8d52006-05-27 19:21:47 +0000603#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +0000604# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000605
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000606class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000607 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000608 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000609 test(result)
610 return result
611
612
Guido van Rossumd8faa362007-04-27 19:54:29 +0000613def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +0000614 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000615 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +0000616 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000617 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000618 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000619
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000620 result = runner.run(suite)
621 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +0000622 if len(result.errors) == 1 and not result.failures:
623 err = result.errors[0][1]
624 elif len(result.failures) == 1 and not result.errors:
625 err = result.failures[0][1]
626 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000627 err = "errors occurred; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +0000628 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +0000629
Barry Warsawc10d6902001-09-20 06:30:41 +0000630
Walter Dörwald21d3a322003-05-01 17:45:56 +0000631def run_unittest(*classes):
632 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000634 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000635 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000636 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637 if cls in sys.modules:
638 suite.addTest(unittest.findTestCases(sys.modules[cls]))
639 else:
640 raise ValueError("str arguments must be keys in sys.modules")
641 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +0000642 suite.addTest(cls)
643 else:
644 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000645 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000646
Barry Warsawc10d6902001-09-20 06:30:41 +0000647
Tim Petersa0a62222001-09-09 06:12:01 +0000648#=======================================================================
649# doctest driver.
650
651def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +0000652 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +0000653
654 If optional argument verbosity is not specified (or is None), pass
Tim Petersbea3fb82001-09-10 01:39:21 +0000655 test_support's belief about verbosity on to doctest. Else doctest's
656 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +0000657 """
658
659 import doctest
660
661 if verbosity is None:
662 verbosity = verbose
663 else:
664 verbosity = None
665
Tim Peters342ca752001-09-25 19:13:20 +0000666 # Direct doctest output (normally just errors) to real stdout; doctest
667 # output shouldn't be compared by regrtest.
668 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +0000669 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +0000670 try:
671 f, t = doctest.testmod(module, verbose=verbosity)
672 if f:
673 raise TestFailed("%d of %d doctests failed" % (f, t))
674 finally:
675 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000676 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +0000677 print('doctest (%s) ... %d tests with zero failures' %
678 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000679 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000680
681#=======================================================================
682# Threading support to prevent reporting refleaks when running regrtest.py -R
683
684def threading_setup():
685 import threading
686 return len(threading._active), len(threading._limbo)
687
688def threading_cleanup(num_active, num_limbo):
689 import threading
690 import time
691
692 _MAX_COUNT = 10
693 count = 0
694 while len(threading._active) != num_active and count < _MAX_COUNT:
695 count += 1
696 time.sleep(0.1)
697
698 count = 0
699 while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
700 count += 1
701 time.sleep(0.1)
702
703def reap_children():
704 """Use this function at the end of test_main() whenever sub-processes
705 are started. This will help ensure that no extra children (zombies)
706 stick around to hog resources and create problems when looking
707 for refleaks.
708 """
709
710 # Reap all our dead child processes so we don't leave zombies around.
711 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000712 if hasattr(os, 'waitpid'):
713 any_process = -1
714 while True:
715 try:
716 # This will raise an exception on Windows. That's ok.
717 pid, status = os.waitpid(any_process, os.WNOHANG)
718 if pid == 0:
719 break
720 except:
721 break