blob: 4bc661945aa8bbf630a2c3a4c3e68a27e55a7bb3 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106def bind_port(sock, host='', preferred_port=54321):
107 """Try to bind the sock to a port. If we are running multiple
108 tests and we don't try multiple ports, the test can fails. This
109 makes the test more robust."""
110
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000111 # Find some random ports that hopefully no one is listening on.
112 # Ideally each test would clean up after itself and not continue listening
113 # on any ports. However, this isn't the case. The last port (0) is
114 # a stop-gap that asks the O/S to assign a port. Whenever the warning
115 # message below is printed, the test that is listening on the port should
116 # be fixed to close the socket at the end of the test.
117 # Another reason why we can't use a port is another process (possibly
118 # another instance of the test suite) is using the same port.
119 for port in [preferred_port, 9907, 10243, 32999, 0]:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120 try:
121 sock.bind((host, port))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000122 if port == 0:
123 port = sock.getsockname()[1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000124 return port
Guido van Rossumb940e112007-01-10 16:19:56 +0000125 except socket.error as e:
Guido van Rossume2c8f2d2007-05-09 23:43:17 +0000126 (err, msg) = e.args
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000127 if err != errno.EADDRINUSE:
128 raise
Georg Brandlf01fe692008-02-05 21:00:53 +0000129 print(' WARNING: failed to listen on port %d, ' % port +
130 'trying another', file=sys.__stderr__)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000131 raise TestFailed('unable to find port to listen on')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000132
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000133FUZZ = 1e-6
134
135def fcmp(x, y): # fuzzy comparison function
Neal Norwitz79212992006-08-21 16:27:31 +0000136 if isinstance(x, float) or isinstance(y, float):
Fred Drake004d5e62000-10-23 17:22:08 +0000137 try:
Fred Drake004d5e62000-10-23 17:22:08 +0000138 fuzz = (abs(x) + abs(y)) * FUZZ
139 if abs(x-y) <= fuzz:
140 return 0
141 except:
142 pass
Neal Norwitz79212992006-08-21 16:27:31 +0000143 elif type(x) == type(y) and isinstance(x, (tuple, list)):
Fred Drake004d5e62000-10-23 17:22:08 +0000144 for i in range(min(len(x), len(y))):
145 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000146 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000147 return outcome
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000148 return (len(x) > len(y)) - (len(x) < len(y))
149 return (x > y) - (x < y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000150
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000151try:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000152 str
Neal Norwitz79212992006-08-21 16:27:31 +0000153 have_unicode = True
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000154except NameError:
Neal Norwitz79212992006-08-21 16:27:31 +0000155 have_unicode = False
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000156
Finn Bock57bc5fa2002-11-01 18:02:03 +0000157is_jython = sys.platform.startswith('java')
158
Barry Warsaw559f6682001-03-23 18:04:02 +0000159# Filename used for testing
160if os.name == 'java':
161 # Jython disallows @ in module names
162 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000163else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000164 TESTFN = '@test'
Walter Dörwald9b775532007-06-08 14:30:53 +0000165
166 # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
167 # TESTFN_UNICODE is a filename that can be encoded using the
168 # file system encoding, but *not* with the default (ascii) encoding
169 TESTFN_UNICODE = "@test-\xe0\xf2"
170 TESTFN_ENCODING = sys.getfilesystemencoding()
171 # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
172 # able to be encoded by *either* the default or filesystem encoding.
173 # This test really only makes sense on Windows NT platforms
174 # which have special Unicode support in posixmodule.
175 if (not hasattr(sys, "getwindowsversion") or
176 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
177 TESTFN_UNICODE_UNENCODEABLE = None
178 else:
179 # Japanese characters (I think - from bug 846133)
180 TESTFN_UNICODE_UNENCODEABLE = "@test-\u5171\u6709\u3055\u308c\u308b"
181 try:
182 # XXX - Note - should be using TESTFN_ENCODING here - but for
183 # Windows, "mbcs" currently always operates as if in
184 # errors=ignore' mode - hence we get '?' characters rather than
185 # the exception. 'Latin1' operates as we expect - ie, fails.
186 # See [ 850997 ] mbcs encoding ignores errors
187 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
188 except UnicodeEncodeError:
189 pass
Martin v. Löwis2411a2d2002-11-09 19:57:26 +0000190 else:
Georg Brandldb028442008-02-05 20:48:58 +0000191 print('WARNING: The filename %r CAN be encoded by the filesystem. '
192 'Unicode filename tests may not be effective'
193 % TESTFN_UNICODE_UNENCODEABLE)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000194
195# Make sure we can write to TESTFN, try in /tmp if we can't
196fp = None
197try:
198 fp = open(TESTFN, 'w+')
199except IOError:
200 TMP_TESTFN = os.path.join('/tmp', TESTFN)
201 try:
202 fp = open(TMP_TESTFN, 'w+')
203 TESTFN = TMP_TESTFN
204 del TMP_TESTFN
205 except IOError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000206 print(('WARNING: tests will fail, unable to write to: %s or %s' %
207 (TESTFN, TMP_TESTFN)))
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000208if fp is not None:
209 fp.close()
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000210 unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211del fp
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000212
Guido van Rossume26132c1998-04-23 20:13:30 +0000213def findfile(file, here=__file__):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000214 """Try to find a file on sys.path and the working directory. If it is not
215 found the argument passed to the function is returned (this does not
216 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000217 if os.path.isabs(file):
218 return file
Fred Drake004d5e62000-10-23 17:22:08 +0000219 path = sys.path
220 path = [os.path.dirname(here)] + path
221 for dn in path:
222 fn = os.path.join(dn, file)
223 if os.path.exists(fn): return fn
224 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000225
226def verify(condition, reason='test failed'):
Guido van Rossuma1374e42001-01-19 19:01:56 +0000227 """Verify that condition is true. If not, raise TestFailed.
Marc-André Lemburg36619082001-01-17 19:11:13 +0000228
Skip Montanaroc955f892001-01-20 19:12:54 +0000229 The optional argument reason can be given to provide
Tim Peters983874d2001-01-19 05:59:21 +0000230 a better error text.
Tim Petersd2bf3b72001-01-18 02:22:22 +0000231 """
Tim Peters983874d2001-01-19 05:59:21 +0000232
Tim Petersd2bf3b72001-01-18 02:22:22 +0000233 if not condition:
Guido van Rossuma1374e42001-01-19 19:01:56 +0000234 raise TestFailed(reason)
Jeremy Hylton47793992001-02-19 15:35:26 +0000235
Tim Petersc2fe6182001-10-30 23:20:46 +0000236def vereq(a, b):
Tim Peters77902972001-12-29 17:34:57 +0000237 """Raise TestFailed if a == b is false.
238
239 This is better than verify(a == b) because, in case of failure, the
240 error message incorporates repr(a) and repr(b) so you can see the
241 inputs.
242
243 Note that "not (a == b)" isn't necessarily the same as "a != b"; the
244 former is tested.
245 """
246
Tim Petersc2fe6182001-10-30 23:20:46 +0000247 if not (a == b):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248 raise TestFailed("%r == %r" % (a, b))
Tim Petersc2fe6182001-10-30 23:20:46 +0000249
Tim Peters2f228e72001-05-13 00:19:31 +0000250def sortdict(dict):
251 "Like repr(dict), but in sorted order."
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000252 items = sorted(dict.items())
Tim Peters2f228e72001-05-13 00:19:31 +0000253 reprpairs = ["%r: %r" % pair for pair in items]
254 withcommas = ", ".join(reprpairs)
255 return "{%s}" % withcommas
256
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257def check_syntax_error(testcase, statement):
Jeremy Hylton47793992001-02-19 15:35:26 +0000258 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000259 compile(statement, '<test string>', 'exec')
Jeremy Hylton47793992001-02-19 15:35:26 +0000260 except SyntaxError:
261 pass
262 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000263 testcase.fail('Missing SyntaxError: "%s"' % statement)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000264
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000265def open_urlresource(url, *args, **kw):
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000266 import urllib, urlparse
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000267
Guido van Rossum360e4b82007-05-14 22:51:27 +0000268 requires('urlfetch')
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000269 filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
270
271 for path in [os.path.curdir, os.path.pardir]:
272 fn = os.path.join(path, filename)
273 if os.path.exists(fn):
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000274 return open(fn, *args, **kw)
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000275
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000276 print('\tfetching %s ...' % url, file=get_original_stdout())
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000277 fn, _ = urllib.urlretrieve(url, filename)
Martin v. Löwis234a34a2007-08-30 20:58:02 +0000278 return open(fn, *args, **kw)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000279
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000280
Guido van Rossumd8faa362007-04-27 19:54:29 +0000281class WarningMessage(object):
282 "Holds the result of the latest showwarning() call"
283 def __init__(self):
284 self.message = None
285 self.category = None
286 self.filename = None
287 self.lineno = None
288
289 def _showwarning(self, message, category, filename, lineno, file=None):
290 self.message = message
291 self.category = category
292 self.filename = filename
293 self.lineno = lineno
294
295@contextlib.contextmanager
296def catch_warning():
297 """
298 Guard the warnings filter from being permanently changed and record the
299 data of the last warning that has been issued.
300
301 Use like this:
302
Guido van Rossumaf554a02007-08-16 23:48:43 +0000303 with catch_warning() as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304 warnings.warn("foo")
305 assert str(w.message) == "foo"
306 """
307 warning = WarningMessage()
308 original_filters = warnings.filters[:]
309 original_showwarning = warnings.showwarning
310 warnings.showwarning = warning._showwarning
311 try:
312 yield warning
313 finally:
314 warnings.showwarning = original_showwarning
315 warnings.filters = original_filters
316
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000317class EnvironmentVarGuard(object):
318
319 """Class to help protect the environment variable properly. Can be used as
320 a context manager."""
321
322 def __init__(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000323 self._environ = os.environ
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000324 self._unset = set()
325 self._reset = dict()
326
327 def set(self, envvar, value):
328 if envvar not in self._environ:
329 self._unset.add(envvar)
330 else:
331 self._reset[envvar] = self._environ[envvar]
332 self._environ[envvar] = value
333
334 def unset(self, envvar):
335 if envvar in self._environ:
336 self._reset[envvar] = self._environ[envvar]
337 del self._environ[envvar]
338
339 def __enter__(self):
340 return self
341
342 def __exit__(self, *ignore_exc):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000343 for envvar, value in self._reset.items():
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000344 self._environ[envvar] = value
345 for unset in self._unset:
346 del self._environ[unset]
347
Guido van Rossumd8faa362007-04-27 19:54:29 +0000348class TransientResource(object):
349
350 """Raise ResourceDenied if an exception is raised while the context manager
351 is in effect that matches the specified exception and attributes."""
352
353 def __init__(self, exc, **kwargs):
354 self.exc = exc
355 self.attrs = kwargs
356
357 def __enter__(self):
358 return self
359
360 def __exit__(self, type_=None, value=None, traceback=None):
361 """If type_ is a subclass of self.exc and value has attributes matching
362 self.attrs, raise ResourceDenied. Otherwise let the exception
363 propagate (if any)."""
364 if type_ is not None and issubclass(self.exc, type_):
365 for attr, attr_value in self.attrs.items():
366 if not hasattr(value, attr):
367 break
368 if getattr(value, attr) != attr_value:
369 break
370 else:
371 raise ResourceDenied("an optional resource is not available")
372
373
374def transient_internet():
375 """Return a context manager that raises ResourceDenied when various issues
376 with the Internet connection manifest themselves as exceptions."""
377 time_out = TransientResource(IOError, errno=errno.ETIMEDOUT)
378 socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET)
379 ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET)
380 return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
381
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000382
Thomas Woutersed03b412007-08-28 21:37:11 +0000383@contextlib.contextmanager
384def captured_stdout():
385 """Run the with statement body using a StringIO object as sys.stdout.
386 Example use::
387
388 with captured_stdout() as s:
389 print "hello"
390 assert s.getvalue() == "hello"
391 """
392 import io
393 orig_stdout = sys.stdout
394 sys.stdout = io.StringIO()
395 yield sys.stdout
396 sys.stdout = orig_stdout
397
398
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000399#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000400# Decorator for running a function in a different locale, correctly resetting
401# it afterwards.
402
403def run_with_locale(catstr, *locales):
404 def decorator(func):
405 def inner(*args, **kwds):
406 try:
407 import locale
408 category = getattr(locale, catstr)
409 orig_locale = locale.setlocale(category)
410 except AttributeError:
411 # if the test author gives us an invalid category string
412 raise
413 except:
414 # cannot retrieve original locale, so do nothing
415 locale = orig_locale = None
416 else:
417 for loc in locales:
418 try:
419 locale.setlocale(category, loc)
420 break
421 except:
422 pass
423
424 # now run the function, resetting the locale on exceptions
425 try:
426 return func(*args, **kwds)
427 finally:
428 if locale and orig_locale:
429 locale.setlocale(category, orig_locale)
Neal Norwitz221085d2007-02-25 20:55:47 +0000430 inner.__name__ = func.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431 inner.__doc__ = func.__doc__
432 return inner
433 return decorator
434
435#=======================================================================
Georg Brandldb028442008-02-05 20:48:58 +0000436# Big-memory-test support. Separate from 'resources' because memory use
437# should be configurable.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000438
439# Some handy shorthands. Note that these are used for byte-limits as well
440# as size-limits, in the various bigmem tests
441_1M = 1024*1024
442_1G = 1024 * _1M
443_2G = 2 * _1G
444
Thomas Woutersd2cf20e2007-08-30 22:57:53 +0000445MAX_Py_ssize_t = sys.maxsize
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000446
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447def set_memlimit(limit):
448 import re
449 global max_memuse
450 sizes = {
451 'k': 1024,
452 'm': _1M,
453 'g': _1G,
454 't': 1024*_1G,
455 }
456 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
457 re.IGNORECASE | re.VERBOSE)
458 if m is None:
459 raise ValueError('Invalid memory limit %r' % (limit,))
460 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000461 if memlimit > MAX_Py_ssize_t:
462 memlimit = MAX_Py_ssize_t
463 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000464 raise ValueError('Memory limit %r too low to be useful' % (limit,))
465 max_memuse = memlimit
466
467def bigmemtest(minsize, memuse, overhead=5*_1M):
468 """Decorator for bigmem tests.
469
470 'minsize' is the minimum useful size for the test (in arbitrary,
471 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
472 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
473 independant of the testsize, and defaults to 5Mb.
474
475 The decorator tries to guess a good value for 'size' and passes it to
476 the decorated test function. If minsize * memuse is more than the
477 allowed memory use (as defined by max_memuse), the test is skipped.
478 Otherwise, minsize is adjusted upward to use up to max_memuse.
479 """
480 def decorator(f):
481 def wrapper(self):
482 if not max_memuse:
483 # If max_memuse is 0 (the default),
484 # we still want to run the tests with size set to a few kb,
485 # to make sure they work. We still want to avoid using
486 # too much memory, though, but we do that noisily.
487 maxsize = 5147
488 self.failIf(maxsize * memuse + overhead > 20 * _1M)
489 else:
490 maxsize = int((max_memuse - overhead) / memuse)
491 if maxsize < minsize:
492 # Really ought to print 'test skipped' or something
493 if verbose:
494 sys.stderr.write("Skipping %s because of memory "
495 "constraint\n" % (f.__name__,))
496 return
497 # Try to keep some breathing room in memory use
498 maxsize = max(maxsize - 50 * _1M, minsize)
499 return f(self, maxsize)
500 wrapper.minsize = minsize
501 wrapper.memuse = memuse
502 wrapper.overhead = overhead
503 return wrapper
504 return decorator
505
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506def bigaddrspacetest(f):
507 """Decorator for tests that fill the address space."""
508 def wrapper(self):
509 if max_memuse < MAX_Py_ssize_t:
510 if verbose:
511 sys.stderr.write("Skipping %s because of memory "
512 "constraint\n" % (f.__name__,))
513 else:
514 return f(self)
515 return wrapper
516
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517#=======================================================================
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518# unittest integration.
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000519
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000520class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000521 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000522 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000523 test(result)
524 return result
525
526
Guido van Rossumd8faa362007-04-27 19:54:29 +0000527def _run_suite(suite):
Barry Warsawc88425e2001-09-20 06:31:22 +0000528 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000529 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +0000530 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000531 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000532 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000533
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000534 result = runner.run(suite)
535 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +0000536 if len(result.errors) == 1 and not result.failures:
537 err = result.errors[0][1]
538 elif len(result.failures) == 1 and not result.errors:
539 err = result.failures[0][1]
540 else:
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000541 err = "errors occurred; run in verbose mode for details"
Tim Peters2d84f2c2001-09-08 03:37:56 +0000542 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +0000543
Barry Warsawc10d6902001-09-20 06:30:41 +0000544
Walter Dörwald21d3a322003-05-01 17:45:56 +0000545def run_unittest(*classes):
546 """Run tests from unittest.TestCase-derived classes."""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547 valid_types = (unittest.TestSuite, unittest.TestCase)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000548 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000549 for cls in classes:
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000550 if isinstance(cls, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000551 if cls in sys.modules:
552 suite.addTest(unittest.findTestCases(sys.modules[cls]))
553 else:
554 raise ValueError("str arguments must be keys in sys.modules")
555 elif isinstance(cls, valid_types):
Raymond Hettinger21d99872003-07-16 02:59:32 +0000556 suite.addTest(cls)
557 else:
558 suite.addTest(unittest.makeSuite(cls))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000559 _run_suite(suite)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000560
Barry Warsawc10d6902001-09-20 06:30:41 +0000561
Tim Petersa0a62222001-09-09 06:12:01 +0000562#=======================================================================
563# doctest driver.
564
565def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +0000566 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +0000567
568 If optional argument verbosity is not specified (or is None), pass
Tim Petersbea3fb82001-09-10 01:39:21 +0000569 test_support's belief about verbosity on to doctest. Else doctest's
570 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +0000571 """
572
573 import doctest
574
575 if verbosity is None:
576 verbosity = verbose
577 else:
578 verbosity = None
579
Tim Peters342ca752001-09-25 19:13:20 +0000580 # Direct doctest output (normally just errors) to real stdout; doctest
581 # output shouldn't be compared by regrtest.
582 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +0000583 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +0000584 try:
585 f, t = doctest.testmod(module, verbose=verbosity)
586 if f:
587 raise TestFailed("%d of %d doctests failed" % (f, t))
588 finally:
589 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000590 if verbose:
Georg Brandldb028442008-02-05 20:48:58 +0000591 print('doctest (%s) ... %d tests with zero failures' %
592 (module.__name__, t))
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000593 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000594
595#=======================================================================
596# Threading support to prevent reporting refleaks when running regrtest.py -R
597
598def threading_setup():
599 import threading
600 return len(threading._active), len(threading._limbo)
601
602def threading_cleanup(num_active, num_limbo):
603 import threading
604 import time
605
606 _MAX_COUNT = 10
607 count = 0
608 while len(threading._active) != num_active and count < _MAX_COUNT:
609 count += 1
610 time.sleep(0.1)
611
612 count = 0
613 while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
614 count += 1
615 time.sleep(0.1)
616
617def reap_children():
618 """Use this function at the end of test_main() whenever sub-processes
619 are started. This will help ensure that no extra children (zombies)
620 stick around to hog resources and create problems when looking
621 for refleaks.
622 """
623
624 # Reap all our dead child processes so we don't leave zombies around.
625 # These hog resources and might be causing some of the buildbots to die.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626 if hasattr(os, 'waitpid'):
627 any_process = -1
628 while True:
629 try:
630 # This will raise an exception on Windows. That's ok.
631 pid, status = os.waitpid(any_process, os.WNOHANG)
632 if pid == 0:
633 break
634 except:
635 break