blob: a9d5dabcc76af0bc502deee5b573f3c45f675614 [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':
4 raise ImportError, 'test_support must be imported from the test package'
5
Fred Drakecd1b1dd2001-03-21 18:26:33 +00006import sys
7
Fred Drake1790dd42000-07-24 06:55:00 +00008class Error(Exception):
Fred Drake004d5e62000-10-23 17:22:08 +00009 """Base class for regression test exceptions."""
Fred Drake1790dd42000-07-24 06:55:00 +000010
11class TestFailed(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000012 """Test failed."""
Fred Drake1790dd42000-07-24 06:55:00 +000013
14class TestSkipped(Error):
Fred Drake004d5e62000-10-23 17:22:08 +000015 """Test skipped.
Fred Drake1790dd42000-07-24 06:55:00 +000016
Fred Drake004d5e62000-10-23 17:22:08 +000017 This can be raised to indicate that a test was deliberatly
18 skipped, but not because a feature wasn't available. For
19 example, if some resource can't be used, such as the network
20 appears to be unavailable, this should be raised instead of
21 TestFailed.
Fred Drake004d5e62000-10-23 17:22:08 +000022 """
Fred Drake1790dd42000-07-24 06:55:00 +000023
Fred Drake9a0db072003-02-03 15:19:30 +000024class ResourceDenied(TestSkipped):
25 """Test skipped because it requested a disallowed resource.
26
27 This is raised when a test calls requires() for a resource that
28 has not be enabled. It is used to distinguish between expected
29 and unexpected skips.
30 """
31
Barry Warsawc0fb6052001-08-20 22:29:23 +000032verbose = 1 # Flag set to 0 by regrtest.py
Thomas Wouters477c8d52006-05-27 19:21:47 +000033use_resources = None # Flag set to [] by regrtest.py
34max_memuse = 0 # Disable bigmem tests (they will still be run with
35 # small sizes, to make sure they work.)
Guido van Rossum531661c1996-12-20 02:58:22 +000036
Tim Peters8dee8092001-09-25 20:05:11 +000037# _original_stdout is meant to hold stdout at the time regrtest began.
38# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
39# The point is to have some flavor of stdout the user can actually see.
40_original_stdout = None
41def record_original_stdout(stdout):
42 global _original_stdout
43 _original_stdout = stdout
44
45def get_original_stdout():
46 return _original_stdout or sys.stdout
47
Guido van Rossum3bead091992-01-27 17:00:37 +000048def unload(name):
Fred Drake004d5e62000-10-23 17:22:08 +000049 try:
50 del sys.modules[name]
51 except KeyError:
52 pass
Guido van Rossum3bead091992-01-27 17:00:37 +000053
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000054def unlink(filename):
55 import os
56 try:
57 os.unlink(filename)
58 except OSError:
59 pass
60
Guido van Rossum3bead091992-01-27 17:00:37 +000061def forget(modname):
Brett Cannonf1cfb622003-05-04 21:15:27 +000062 '''"Forget" a module was ever imported by removing it from sys.modules and
63 deleting any .pyc and .pyo files.'''
Fred Drake004d5e62000-10-23 17:22:08 +000064 unload(modname)
Fred Drakecd1b1dd2001-03-21 18:26:33 +000065 import os
Fred Drake004d5e62000-10-23 17:22:08 +000066 for dirname in sys.path:
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000067 unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
Brett Cannonf1cfb622003-05-04 21:15:27 +000068 # Deleting the .pyo file cannot be within the 'try' for the .pyc since
69 # the chance exists that there is no .pyc (and thus the 'try' statement
70 # is exited) but there is a .pyo file.
Neal Norwitz0e17f8c2006-01-23 07:51:27 +000071 unlink(os.path.join(dirname, modname + os.extsep + 'pyo'))
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Tim Petersb4ee4eb2002-12-04 03:26:57 +000073def is_resource_enabled(resource):
Brett Cannonf1cfb622003-05-04 21:15:27 +000074 """Test whether a resource is enabled. Known resources are set by
75 regrtest.py."""
Tim Petersb4ee4eb2002-12-04 03:26:57 +000076 return use_resources is not None and resource in use_resources
77
Barry Warsawc0fb6052001-08-20 22:29:23 +000078def requires(resource, msg=None):
Brett Cannonf1cfb622003-05-04 21:15:27 +000079 """Raise ResourceDenied if the specified resource is not available.
80
81 If the caller's module is __main__ then automatically return True. The
82 possibility of False being returned occurs when regrtest.py is executing."""
Skip Montanarod839ecd2003-04-24 19:06:57 +000083 # see if the caller's module is __main__ - if so, treat as if
84 # the resource was set
85 if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
86 return
Tim Petersb4ee4eb2002-12-04 03:26:57 +000087 if not is_resource_enabled(resource):
Barry Warsawc0fb6052001-08-20 22:29:23 +000088 if msg is None:
89 msg = "Use of the `%s' resource not enabled" % resource
Fred Drake9a0db072003-02-03 15:19:30 +000090 raise ResourceDenied(msg)
Barry Warsawc0fb6052001-08-20 22:29:23 +000091
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092def bind_port(sock, host='', preferred_port=54321):
93 """Try to bind the sock to a port. If we are running multiple
94 tests and we don't try multiple ports, the test can fails. This
95 makes the test more robust."""
96
97 import socket, errno
98 # some random ports that hopefully no one is listening on.
99 for port in [preferred_port, 9907, 10243, 32999]:
100 try:
101 sock.bind((host, port))
102 return port
103 except socket.error, (err, msg):
104 if err != errno.EADDRINUSE:
105 raise
106 print >>sys.__stderr__, \
107 ' WARNING: failed to listen on port %d, trying another' % port
108 raise TestFailed, 'unable to find port to listen on'
109
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000110FUZZ = 1e-6
111
112def fcmp(x, y): # fuzzy comparison function
Fred Drake004d5e62000-10-23 17:22:08 +0000113 if type(x) == type(0.0) or type(y) == type(0.0):
114 try:
115 x, y = coerce(x, y)
116 fuzz = (abs(x) + abs(y)) * FUZZ
117 if abs(x-y) <= fuzz:
118 return 0
119 except:
120 pass
121 elif type(x) == type(y) and type(x) in (type(()), type([])):
122 for i in range(min(len(x), len(y))):
123 outcome = fcmp(x[i], y[i])
Fred Drake132dce22000-12-12 23:11:42 +0000124 if outcome != 0:
Fred Drake004d5e62000-10-23 17:22:08 +0000125 return outcome
126 return cmp(len(x), len(y))
127 return cmp(x, y)
Guido van Rossum35fb82a1993-01-26 13:04:43 +0000128
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000129try:
130 unicode
131 have_unicode = 1
132except NameError:
133 have_unicode = 0
134
Finn Bock57bc5fa2002-11-01 18:02:03 +0000135is_jython = sys.platform.startswith('java')
136
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000137import os
Barry Warsaw559f6682001-03-23 18:04:02 +0000138# Filename used for testing
139if os.name == 'java':
140 # Jython disallows @ in module names
141 TESTFN = '$test'
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000142elif os.name == 'riscos':
143 TESTFN = 'testfile'
144else:
Barry Warsaw559f6682001-03-23 18:04:02 +0000145 TESTFN = '@test'
Mark Hammondef8b6542001-05-13 08:04:26 +0000146 # Unicode name only used if TEST_FN_ENCODING exists for the platform.
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000147 if have_unicode:
Mark Hammondb337dd92003-12-03 01:27:23 +0000148 # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
149 # TESTFN_UNICODE is a filename that can be encoded using the
150 # file system encoding, but *not* with the default (ascii) encoding
Martin v. Löwis2411a2d2002-11-09 19:57:26 +0000151 if isinstance('', unicode):
152 # python -U
153 # XXX perhaps unicode() should accept Unicode strings?
Tim Petersc6c5ece2003-12-04 05:39:43 +0000154 TESTFN_UNICODE = "@test-\xe0\xf2"
Martin v. Löwis2411a2d2002-11-09 19:57:26 +0000155 else:
Tim Petersc6c5ece2003-12-04 05:39:43 +0000156 # 2 latin characters.
157 TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1")
158 TESTFN_ENCODING = sys.getfilesystemencoding()
159 # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be
Mark Hammondb337dd92003-12-03 01:27:23 +0000160 # able to be encoded by *either* the default or filesystem encoding.
Tim Petersc6c5ece2003-12-04 05:39:43 +0000161 # This test really only makes sense on Windows NT platforms
Mark Hammond2e8624c2003-12-03 22:16:47 +0000162 # which have special Unicode support in posixmodule.
Tim Petersc6c5ece2003-12-04 05:39:43 +0000163 if (not hasattr(sys, "getwindowsversion") or
164 sys.getwindowsversion()[3] < 2): # 0=win32s or 1=9x/ME
Tim Peters58eb11c2004-01-18 20:29:55 +0000165 TESTFN_UNICODE_UNENCODEABLE = None
Mark Hammondb337dd92003-12-03 01:27:23 +0000166 else:
Mark Hammond2e8624c2003-12-03 22:16:47 +0000167 # Japanese characters (I think - from bug 846133)
Martin v. Löwise2713be2005-03-08 15:03:08 +0000168 TESTFN_UNICODE_UNENCODEABLE = eval('u"@test-\u5171\u6709\u3055\u308c\u308b"')
Mark Hammond2e8624c2003-12-03 22:16:47 +0000169 try:
170 # XXX - Note - should be using TESTFN_ENCODING here - but for
Tim Petersc6c5ece2003-12-04 05:39:43 +0000171 # Windows, "mbcs" currently always operates as if in
Mark Hammond2e8624c2003-12-03 22:16:47 +0000172 # errors=ignore' mode - hence we get '?' characters rather than
173 # the exception. 'Latin1' operates as we expect - ie, fails.
174 # See [ 850997 ] mbcs encoding ignores errors
175 TESTFN_UNICODE_UNENCODEABLE.encode("Latin1")
176 except UnicodeEncodeError:
177 pass
178 else:
179 print \
180 'WARNING: The filename %r CAN be encoded by the filesystem. ' \
181 'Unicode filename tests may not be effective' \
182 % TESTFN_UNICODE_UNENCODEABLE
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000183
184# Make sure we can write to TESTFN, try in /tmp if we can't
185fp = None
186try:
187 fp = open(TESTFN, 'w+')
188except IOError:
189 TMP_TESTFN = os.path.join('/tmp', TESTFN)
190 try:
191 fp = open(TMP_TESTFN, 'w+')
192 TESTFN = TMP_TESTFN
193 del TMP_TESTFN
194 except IOError:
Tim Peters3de75262002-11-09 05:26:15 +0000195 print ('WARNING: tests will fail, unable to write to: %s or %s' %
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000196 (TESTFN, TMP_TESTFN))
197if fp is not None:
198 fp.close()
Neal Norwitz0e17f8c2006-01-23 07:51:27 +0000199 unlink(TESTFN)
Neal Norwitz26a1eef2002-11-03 00:35:53 +0000200del os, fp
Guido van Rossuma8f7e592001-03-13 09:31:07 +0000201
Guido van Rossume26132c1998-04-23 20:13:30 +0000202def findfile(file, here=__file__):
Brett Cannonf1cfb622003-05-04 21:15:27 +0000203 """Try to find a file on sys.path and the working directory. If it is not
204 found the argument passed to the function is returned (this does not
205 necessarily signal failure; could still be the legitimate path)."""
Fred Drake004d5e62000-10-23 17:22:08 +0000206 import os
207 if os.path.isabs(file):
208 return file
Fred Drake004d5e62000-10-23 17:22:08 +0000209 path = sys.path
210 path = [os.path.dirname(here)] + path
211 for dn in path:
212 fn = os.path.join(dn, file)
213 if os.path.exists(fn): return fn
214 return file
Marc-André Lemburg36619082001-01-17 19:11:13 +0000215
216def verify(condition, reason='test failed'):
Guido van Rossuma1374e42001-01-19 19:01:56 +0000217 """Verify that condition is true. If not, raise TestFailed.
Marc-André Lemburg36619082001-01-17 19:11:13 +0000218
Skip Montanaroc955f892001-01-20 19:12:54 +0000219 The optional argument reason can be given to provide
Tim Peters983874d2001-01-19 05:59:21 +0000220 a better error text.
Tim Petersd2bf3b72001-01-18 02:22:22 +0000221 """
Tim Peters983874d2001-01-19 05:59:21 +0000222
Tim Petersd2bf3b72001-01-18 02:22:22 +0000223 if not condition:
Guido van Rossuma1374e42001-01-19 19:01:56 +0000224 raise TestFailed(reason)
Jeremy Hylton47793992001-02-19 15:35:26 +0000225
Tim Petersc2fe6182001-10-30 23:20:46 +0000226def vereq(a, b):
Tim Peters77902972001-12-29 17:34:57 +0000227 """Raise TestFailed if a == b is false.
228
229 This is better than verify(a == b) because, in case of failure, the
230 error message incorporates repr(a) and repr(b) so you can see the
231 inputs.
232
233 Note that "not (a == b)" isn't necessarily the same as "a != b"; the
234 former is tested.
235 """
236
Tim Petersc2fe6182001-10-30 23:20:46 +0000237 if not (a == b):
238 raise TestFailed, "%r == %r" % (a, b)
239
Tim Peters2f228e72001-05-13 00:19:31 +0000240def sortdict(dict):
241 "Like repr(dict), but in sorted order."
242 items = dict.items()
243 items.sort()
244 reprpairs = ["%r: %r" % pair for pair in items]
245 withcommas = ", ".join(reprpairs)
246 return "{%s}" % withcommas
247
Jeremy Hylton47793992001-02-19 15:35:26 +0000248def check_syntax(statement):
249 try:
250 compile(statement, '<string>', 'exec')
251 except SyntaxError:
252 pass
253 else:
254 print 'Missing SyntaxError: "%s"' % statement
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000255
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000256def open_urlresource(url):
257 import urllib, urlparse
258 import os.path
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000259
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000260 filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
261
262 for path in [os.path.curdir, os.path.pardir]:
263 fn = os.path.join(path, filename)
264 if os.path.exists(fn):
265 return open(fn)
266
267 requires('urlfetch')
268 print >> get_original_stdout(), '\tfetching %s ...' % url
269 fn, _ = urllib.urlretrieve(url, filename)
270 return open(fn)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000271
272#=======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273# Decorator for running a function in a different locale, correctly resetting
274# it afterwards.
275
276def run_with_locale(catstr, *locales):
277 def decorator(func):
278 def inner(*args, **kwds):
279 try:
280 import locale
281 category = getattr(locale, catstr)
282 orig_locale = locale.setlocale(category)
283 except AttributeError:
284 # if the test author gives us an invalid category string
285 raise
286 except:
287 # cannot retrieve original locale, so do nothing
288 locale = orig_locale = None
289 else:
290 for loc in locales:
291 try:
292 locale.setlocale(category, loc)
293 break
294 except:
295 pass
296
297 # now run the function, resetting the locale on exceptions
298 try:
299 return func(*args, **kwds)
300 finally:
301 if locale and orig_locale:
302 locale.setlocale(category, orig_locale)
303 inner.func_name = func.func_name
304 inner.__doc__ = func.__doc__
305 return inner
306 return decorator
307
308#=======================================================================
309# Big-memory-test support. Separate from 'resources' because memory use should be configurable.
310
311# Some handy shorthands. Note that these are used for byte-limits as well
312# as size-limits, in the various bigmem tests
313_1M = 1024*1024
314_1G = 1024 * _1M
315_2G = 2 * _1G
316
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000317# Hack to get at the maximum value an internal index can take.
318class _Dummy:
319 def __getslice__(self, i, j):
320 return j
321MAX_Py_ssize_t = _Dummy()[:]
322
Thomas Wouters477c8d52006-05-27 19:21:47 +0000323def set_memlimit(limit):
324 import re
325 global max_memuse
326 sizes = {
327 'k': 1024,
328 'm': _1M,
329 'g': _1G,
330 't': 1024*_1G,
331 }
332 m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
333 re.IGNORECASE | re.VERBOSE)
334 if m is None:
335 raise ValueError('Invalid memory limit %r' % (limit,))
336 memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000337 if memlimit > MAX_Py_ssize_t:
338 memlimit = MAX_Py_ssize_t
339 if memlimit < _2G - 1:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340 raise ValueError('Memory limit %r too low to be useful' % (limit,))
341 max_memuse = memlimit
342
343def bigmemtest(minsize, memuse, overhead=5*_1M):
344 """Decorator for bigmem tests.
345
346 'minsize' is the minimum useful size for the test (in arbitrary,
347 test-interpreted units.) 'memuse' is the number of 'bytes per size' for
348 the test, or a good estimate of it. 'overhead' specifies fixed overhead,
349 independant of the testsize, and defaults to 5Mb.
350
351 The decorator tries to guess a good value for 'size' and passes it to
352 the decorated test function. If minsize * memuse is more than the
353 allowed memory use (as defined by max_memuse), the test is skipped.
354 Otherwise, minsize is adjusted upward to use up to max_memuse.
355 """
356 def decorator(f):
357 def wrapper(self):
358 if not max_memuse:
359 # If max_memuse is 0 (the default),
360 # we still want to run the tests with size set to a few kb,
361 # to make sure they work. We still want to avoid using
362 # too much memory, though, but we do that noisily.
363 maxsize = 5147
364 self.failIf(maxsize * memuse + overhead > 20 * _1M)
365 else:
366 maxsize = int((max_memuse - overhead) / memuse)
367 if maxsize < minsize:
368 # Really ought to print 'test skipped' or something
369 if verbose:
370 sys.stderr.write("Skipping %s because of memory "
371 "constraint\n" % (f.__name__,))
372 return
373 # Try to keep some breathing room in memory use
374 maxsize = max(maxsize - 50 * _1M, minsize)
375 return f(self, maxsize)
376 wrapper.minsize = minsize
377 wrapper.memuse = memuse
378 wrapper.overhead = overhead
379 return wrapper
380 return decorator
381
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000382def bigaddrspacetest(f):
383 """Decorator for tests that fill the address space."""
384 def wrapper(self):
385 if max_memuse < MAX_Py_ssize_t:
386 if verbose:
387 sys.stderr.write("Skipping %s because of memory "
388 "constraint\n" % (f.__name__,))
389 else:
390 return f(self)
391 return wrapper
392
Thomas Wouters477c8d52006-05-27 19:21:47 +0000393#=======================================================================
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000394# Preliminary PyUNIT integration.
395
396import unittest
397
398
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000399class BasicTestRunner:
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000400 def run(self, test):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000401 result = unittest.TestResult()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000402 test(result)
403 return result
404
405
Fred Drake26641032001-10-04 19:46:07 +0000406def run_suite(suite, testclass=None):
Barry Warsawc88425e2001-09-20 06:31:22 +0000407 """Run tests from a unittest.TestSuite-derived class."""
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000408 if verbose:
Fred Drake84a59342001-03-23 04:21:17 +0000409 runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000410 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000411 runner = BasicTestRunner()
Fred Drakecd1b1dd2001-03-21 18:26:33 +0000412
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000413 result = runner.run(suite)
414 if not result.wasSuccessful():
Fred Drake14f6c182001-07-16 18:51:32 +0000415 if len(result.errors) == 1 and not result.failures:
416 err = result.errors[0][1]
417 elif len(result.failures) == 1 and not result.errors:
418 err = result.failures[0][1]
419 else:
Fred Drake26641032001-10-04 19:46:07 +0000420 if testclass is None:
421 msg = "errors occurred; run in verbose mode for details"
422 else:
423 msg = "errors occurred in %s.%s" \
424 % (testclass.__module__, testclass.__name__)
425 raise TestFailed(msg)
Tim Peters2d84f2c2001-09-08 03:37:56 +0000426 raise TestFailed(err)
Tim Petersa0a62222001-09-09 06:12:01 +0000427
Barry Warsawc10d6902001-09-20 06:30:41 +0000428
Walter Dörwald21d3a322003-05-01 17:45:56 +0000429def run_unittest(*classes):
430 """Run tests from unittest.TestCase-derived classes."""
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000431 suite = unittest.TestSuite()
Walter Dörwald21d3a322003-05-01 17:45:56 +0000432 for cls in classes:
Raymond Hettingerf3590622003-07-16 04:29:42 +0000433 if isinstance(cls, (unittest.TestSuite, unittest.TestCase)):
Raymond Hettinger21d99872003-07-16 02:59:32 +0000434 suite.addTest(cls)
435 else:
436 suite.addTest(unittest.makeSuite(cls))
Walter Dörwald21d3a322003-05-01 17:45:56 +0000437 if len(classes)==1:
438 testclass = classes[0]
439 else:
440 testclass = None
441 run_suite(suite, testclass)
Raymond Hettinger9dcbbea2003-04-27 07:54:23 +0000442
Barry Warsawc10d6902001-09-20 06:30:41 +0000443
Tim Petersa0a62222001-09-09 06:12:01 +0000444#=======================================================================
445# doctest driver.
446
447def run_doctest(module, verbosity=None):
Tim Peters17111f32001-10-03 04:08:26 +0000448 """Run doctest on the given module. Return (#failures, #tests).
Tim Petersa0a62222001-09-09 06:12:01 +0000449
450 If optional argument verbosity is not specified (or is None), pass
Tim Petersbea3fb82001-09-10 01:39:21 +0000451 test_support's belief about verbosity on to doctest. Else doctest's
452 usual behavior is used (it searches sys.argv for -v).
Tim Petersa0a62222001-09-09 06:12:01 +0000453 """
454
455 import doctest
456
457 if verbosity is None:
458 verbosity = verbose
459 else:
460 verbosity = None
461
Tim Peters342ca752001-09-25 19:13:20 +0000462 # Direct doctest output (normally just errors) to real stdout; doctest
463 # output shouldn't be compared by regrtest.
464 save_stdout = sys.stdout
Tim Peters8dee8092001-09-25 20:05:11 +0000465 sys.stdout = get_original_stdout()
Tim Peters342ca752001-09-25 19:13:20 +0000466 try:
467 f, t = doctest.testmod(module, verbose=verbosity)
468 if f:
469 raise TestFailed("%d of %d doctests failed" % (f, t))
470 finally:
471 sys.stdout = save_stdout
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000472 if verbose:
Raymond Hettinger1ba24b42003-05-17 01:59:57 +0000473 print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
Raymond Hettinger35b34bd2003-05-17 00:58:33 +0000474 return f, t
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000475
476#=======================================================================
477# Threading support to prevent reporting refleaks when running regrtest.py -R
478
479def threading_setup():
480 import threading
481 return len(threading._active), len(threading._limbo)
482
483def threading_cleanup(num_active, num_limbo):
484 import threading
485 import time
486
487 _MAX_COUNT = 10
488 count = 0
489 while len(threading._active) != num_active and count < _MAX_COUNT:
490 count += 1
491 time.sleep(0.1)
492
493 count = 0
494 while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
495 count += 1
496 time.sleep(0.1)
497
498def reap_children():
499 """Use this function at the end of test_main() whenever sub-processes
500 are started. This will help ensure that no extra children (zombies)
501 stick around to hog resources and create problems when looking
502 for refleaks.
503 """
504
505 # Reap all our dead child processes so we don't leave zombies around.
506 # These hog resources and might be causing some of the buildbots to die.
507 import os
508 if hasattr(os, 'waitpid'):
509 any_process = -1
510 while True:
511 try:
512 # This will raise an exception on Windows. That's ok.
513 pid, status = os.waitpid(any_process, os.WNOHANG)
514 if pid == 0:
515 break
516 except:
517 break