5 This will find all modules whose name is "test_*" in the test
6 directory, and run them. Various command line options provide
11 -v: verbose -- run tests in verbose mode with output to stdout
12 -q: quiet -- don't print anything except if a test fails
13 -g: generate -- write the output file for a test instead of comparing it
14 -x: exclude -- arguments are tests to *exclude*
15 -s: single -- run only a single test (see below)
16 -r: random -- randomize test execution order
17 -f: fromfile -- read names of tests to run from a file (see below)
18 -l: findleaks -- if GC is available detect tests that leak memory
19 -u: use -- specify which special resource intensive tests to run
20 -h: help -- print this text and exit
21 -t: threshold -- call gc.set_threshold(N)
23 If non-option arguments are present, they are names for tests to run,
24 unless -x is given, in which case they are names for tests not to run.
25 If no test names are given, all tests are run.
27 -v is incompatible with -g and does not compare test output files.
29 -s means to run only a single test and exit. This is useful when
30 doing memory analysis on the Python interpreter (which tend to consume
31 too many resources to run the full regression test non-stop). The
32 file /tmp/pynexttest is read to find the next test to run. If this
33 file is missing, the first test_*.py file in testdir or on the command
34 line is used. (actually tempfile.gettempdir() is used instead of
37 -f reads the names of tests from the file given as f's argument, one
38 or more test names per line. Whitespace is ignored. Blank lines and
39 lines beginning with '#' are ignored. This is especially useful for
40 whittling down failures involving interactions among tests.
42 -u is used to specify which special resource intensive tests to run,
43 such as those requiring large file support or network connectivity.
44 The argument is a comma-separated list of words indicating the
45 resources to test. Currently only the following are defined:
47 all - Enable all special resources.
49 audio - Tests that use the audio device. (There are known
50 cases of broken audio drivers that can crash Python or
51 even the Linux kernel.)
53 curses - Tests that use curses and will modify the terminal's
54 state and output modes.
56 largefile - It is okay to run some test that may create huge
57 files. These tests can take a long time and may
58 consume >2GB of disk space temporarily.
60 network - It is okay to run tests that use external network
61 resource, e.g. testing SSL support for sockets.
63 bsddb - It is okay to run the bsddb testsuite, which takes
64 a long time to complete.
66 To enable all resources except one, use '-uall,-<resource>'. For
67 example, to run all the tests except for the bsddb tests, give the
68 option '-uall,-bsddb'.
80 # I see no other way to suppress these warnings;
81 # putting them in test_grammar.py has no effect:
82 warnings
.filterwarnings("ignore", "hex/oct constants", FutureWarning
,
83 ".*test.test_grammar$")
84 if sys
.maxint
> 0x7fffffff:
85 # Also suppress them in <string>, because for 64-bit platforms,
86 # that's where test_grammar.py hides them.
87 warnings
.filterwarnings("ignore", "hex/oct constants", FutureWarning
,
90 # MacOSX (a.k.a. Darwin) has a default stack size that is too small
91 # for deeply recursive regular expressions. We see this as crashes in
92 # the Python test suite when running test_re.py and test_sre.py. The
93 # fix is to set the stack limit to 2048.
94 # This approach may also be useful for other Unixy platforms that
95 # suffer from small default stack limits.
96 if sys
.platform
== 'darwin':
102 soft
, hard
= resource
.getrlimit(resource
.RLIMIT_STACK
)
103 newsoft
= min(hard
, max(soft
, 1024*2048))
104 resource
.setrlimit(resource
.RLIMIT_STACK
, (newsoft
, hard
))
106 from test
import test_support
108 RESOURCE_NAMES
= ('audio', 'curses', 'largefile', 'network', 'bsddb')
111 def usage(code
, msg
=''):
117 def main(tests
=None, testdir
=None, verbose
=0, quiet
=0, generate
=0,
118 exclude
=0, single
=0, randomize
=0, fromfile
=None, findleaks
=0,
120 """Execute a test suite.
122 This also parses command-line options and modifies its behavior
125 tests -- a list of strings containing test names (optional)
126 testdir -- the directory in which to look for tests (optional)
128 Users other than the Python test suite will certainly want to
129 specify testdir; if it's omitted, the directory containing the
130 Python test suite is searched for.
132 If the tests argument is omitted, the tests listed on the
133 command-line will be used. If that's empty, too, then all *.py
134 files beginning with test_ will be used.
136 The other default arguments (verbose, quiet, generate, exclude,
137 single, randomize, findleaks, and use_resources) allow programmers
138 calling main() directly to set the values that would normally be
139 set by flags on the command line.
143 test_support
.record_original_stdout(sys
.stdout
)
145 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'hvgqxsrf:lu:t:',
146 ['help', 'verbose', 'quiet', 'generate',
147 'exclude', 'single', 'random', 'fromfile',
148 'findleaks', 'use=', 'threshold='])
149 except getopt
.error
, msg
:
153 if use_resources
is None:
156 if o
in ('-h', '--help'):
158 elif o
in ('-v', '--verbose'):
160 elif o
in ('-q', '--quiet'):
163 elif o
in ('-g', '--generate'):
165 elif o
in ('-x', '--exclude'):
167 elif o
in ('-s', '--single'):
169 elif o
in ('-r', '--randomize'):
171 elif o
in ('-f', '--fromfile'):
173 elif o
in ('-l', '--findleaks'):
175 elif o
in ('-t', '--threshold'):
177 gc
.set_threshold(int(a
))
178 elif o
in ('-u', '--use'):
179 u
= [x
.lower() for x
in a
.split(',')]
182 use_resources
[:] = RESOURCE_NAMES
188 if r
not in RESOURCE_NAMES
:
189 usage(1, 'Invalid -u/--use option: ' + a
)
191 if r
in use_resources
:
192 use_resources
.remove(r
)
193 elif r
not in use_resources
:
194 use_resources
.append(r
)
195 if generate
and verbose
:
196 usage(2, "-g and -v don't go together!")
197 if single
and fromfile
:
198 usage(2, "-s and -f don't go together!")
203 resource_denieds
= []
209 print 'No GC available, disabling findleaks.'
212 # Uncomment the line below to report garbage that is not
213 # freeable by reference counting alone. By default only
214 # garbage that is not collectable by the GC is reported.
215 #gc.set_debug(gc.DEBUG_SAVEALL)
219 from tempfile
import gettempdir
220 filename
= os
.path
.join(gettempdir(), 'pynexttest')
222 fp
= open(filename
, 'r')
223 next
= fp
.read().strip()
233 guts
= line
.split() # assuming no test has whitespace in its name
234 if guts
and not guts
[0].startswith('#'):
238 # Strip .py extensions.
240 args
= map(removepy
, args
)
242 tests
= map(removepy
, tests
)
244 stdtests
= STDTESTS
[:]
245 nottests
= NOTTESTS
[:]
252 tests
= tests
or args
or findtests(testdir
, stdtests
, nottests
)
256 random
.shuffle(tests
)
257 test_support
.verbose
= verbose
# Tell tests to be moderately quiet
258 test_support
.use_resources
= use_resources
259 save_modules
= sys
.modules
.keys()
264 ok
= runtest(test
, generate
, verbose
, quiet
, testdir
)
272 resource_denieds
.append(test
)
276 print "Warning: test created", len(gc
.garbage
),
277 print "uncollectable object(s)."
278 # move the uncollectable objects somewhere so we don't see
280 found_garbage
.extend(gc
.garbage
)
282 # Unload the newly imported modules (best effort finalization)
283 for module
in sys
.modules
.keys():
284 if module
not in save_modules
and module
.startswith("test."):
285 test_support
.unload(module
)
287 # The lists won't be sorted if running with -r
292 if good
and not quiet
:
293 if not bad
and not skipped
and len(good
) > 1:
295 print count(len(good
), "test"), "OK."
297 print "CAUTION: stdout isn't compared in verbose mode:"
298 print "a test that passes in verbose mode may fail without it."
300 print count(len(bad
), "test"), "failed:"
302 if skipped
and not quiet
:
303 print count(len(skipped
), "test"), "skipped:"
309 surprise
= Set(skipped
) - e
.getexpected() - Set(resource_denieds
)
311 print count(len(surprise
), "skip"), \
312 "unexpected on", plat
+ ":"
315 print "Those skips are all expected on", plat
+ "."
317 print "Ask someone to teach regrtest.py about which tests are"
318 print "expected to get skipped on", plat
+ "."
321 alltests
= findtests(testdir
, stdtests
, nottests
)
322 for i
in range(len(alltests
)):
323 if tests
[0] == alltests
[i
]:
324 if i
== len(alltests
) - 1:
327 fp
= open(filename
, 'w')
328 fp
.write(alltests
[i
+1] + '\n')
334 sys
.exit(len(bad
) > 0)
353 def findtests(testdir
=None, stdtests
=STDTESTS
, nottests
=NOTTESTS
):
354 """Return a list of all applicable test modules."""
355 if not testdir
: testdir
= findtestdir()
356 names
= os
.listdir(testdir
)
359 if name
[:5] == "test_" and name
[-3:] == os
.extsep
+"py":
361 if modname
not in stdtests
and modname
not in nottests
:
362 tests
.append(modname
)
364 return stdtests
+ tests
366 def runtest(test
, generate
, verbose
, quiet
, testdir
= None):
367 """Run a single test.
368 test -- the name of the test
369 generate -- if true, generate output, instead of running the test
370 and comparing it to a previously created output file
371 verbose -- if true, print more messages
372 quiet -- if true, don't print 'skipped' messages (probably redundant)
373 testdir -- test directory
375 test_support
.unload(test
)
376 if not testdir
: testdir
= findtestdir()
377 outputdir
= os
.path
.join(testdir
, "output")
378 outputfile
= os
.path
.join(outputdir
, test
)
382 cfp
= StringIO
.StringIO()
384 save_stdout
= sys
.stdout
388 print test
# Output file starts with test name
389 if test
.startswith('test.'):
392 # Always import it from the test package
393 abstest
= 'test.' + test
394 the_package
= __import__(abstest
, globals(), locals(), [])
395 the_module
= getattr(the_package
, test
)
396 # Most tests run to completion simply as a side-effect of
397 # being imported. For the benefit of tests that can't run
398 # that way (like test_threaded_import), explicitly invoke
399 # their test_main() function (if it exists).
400 indirect_test
= getattr(the_module
, "test_main", None)
401 if indirect_test
is not None:
404 sys
.stdout
= save_stdout
405 except test_support
.ResourceDenied
, msg
:
407 print test
, "skipped --", msg
410 except (ImportError, test_support
.TestSkipped
), msg
:
412 print test
, "skipped --", msg
415 except KeyboardInterrupt:
417 except test_support
.TestFailed
, msg
:
418 print "test", test
, "failed --", msg
422 type, value
= sys
.exc_info()[:2]
423 print "test", test
, "crashed --", str(type) + ":", value
426 traceback
.print_exc(file=sys
.stdout
)
432 output
= cfp
.getvalue()
434 if output
== test
+ "\n":
435 if os
.path
.exists(outputfile
):
436 # Write it since it already exists (and the contents
437 # may have changed), but let the user know it isn't
439 print "output file", outputfile
, \
440 "is no longer needed; consider removing it"
442 # We don't need it, so don't create it.
444 fp
= open(outputfile
, "w")
448 if os
.path
.exists(outputfile
):
449 fp
= open(outputfile
, "r")
453 expected
= test
+ "\n"
454 if output
== expected
:
456 print "test", test
, "produced unexpected output:"
458 reportdiff(expected
, output
)
462 def reportdiff(expected
, output
):
465 a
= expected
.splitlines(1)
466 b
= output
.splitlines(1)
467 sm
= difflib
.SequenceMatcher(a
=a
, b
=b
)
468 tuples
= sm
.get_opcodes()
471 # x0:x1 are 0-based slice indices; convert to 1-based line indices.
474 return "line " + str(x0
)
476 return "lines %d-%d" % (x0
, x1
)
478 for op
, a0
, a1
, b0
, b1
in tuples
:
483 print "***", pair(a0
, a1
), "of expected output missing:"
484 for line
in a
[a0
:a1
]:
487 elif op
== 'replace':
488 print "*** mismatch between", pair(a0
, a1
), "of expected", \
489 "output and", pair(b0
, b1
), "of actual output:"
490 for line
in difflib
.ndiff(a
[a0
:a1
], b
[b0
:b1
]):
494 print "***", pair(b0
, b1
), "of actual output doesn't appear", \
495 "in expected output after line", str(a1
)+":"
496 for line
in b
[b0
:b1
]:
500 print "get_opcodes() returned bad tuple?!?!", (op
, a0
, a1
, b0
, b1
)
505 if __name__
== '__main__':
509 testdir
= os
.path
.dirname(file) or os
.curdir
513 if name
.endswith(os
.extsep
+ "py"):
519 return "%d %s" % (n
, word
)
521 return "%d %ss" % (n
, word
)
523 def printlist(x
, width
=70, indent
=4):
524 """Print the elements of iterable x to stdout.
526 Optional arg width (default 70) is the maximum line length.
527 Optional arg indent (default 4) is the number of blanks with which to
531 from textwrap
import fill
532 blanks
= ' ' * indent
533 print fill(' '.join(map(str, x
)), width
,
534 initial_indent
=blanks
, subsequent_indent
=blanks
)
536 # Map sys.platform to a string containing the basenames of tests
537 # expected to be skipped on that platform.
541 # The _ExpectedSkips constructor adds this to the set of expected
542 # skips if not os.path.supports_unicode_filenames.
544 # Whether a skip is expected here depends on whether a large test
545 # input file has been downloaded. test_normalization.skip_expected
548 # Controlled by test_socket_ssl.skip_expected. Requires the network
549 # resource, and a socket module with ssl support.
551 # Controlled by test_timeout.skip_expected. Requires the network
552 # resource and a socket module.
743 test_threadedtempfile
784 test_threadedtempfile
953 class _ExpectedSkips
:
956 from test
import test_normalization
957 from test
import test_socket_ssl
958 from test
import test_timeout
961 if sys
.platform
in _expectations
:
962 s
= _expectations
[sys
.platform
]
963 self
.expected
= Set(s
.split())
965 if not os
.path
.supports_unicode_filenames
:
966 self
.expected
.add('test_pep277')
968 if test_normalization
.skip_expected
:
969 self
.expected
.add('test_normalization')
971 if test_socket_ssl
.skip_expected
:
972 self
.expected
.add('test_socket_ssl')
974 if test_timeout
.skip_expected
:
975 self
.expected
.add('test_timeout')
977 if not sys
.platform
in ("mac", "darwin"):
978 self
.expected
.add("test_macostools")
979 self
.expected
.add("test_macfs")
980 self
.expected
.add("test_aepack")
982 if sys
.platform
!= "win32":
983 self
.expected
.add("test_winreg")
984 self
.expected
.add("test_winsound")
989 "Return true iff _ExpectedSkips knows about the current platform."
992 def getexpected(self
):
993 """Return set of test names we expect to skip on current platform.
995 self.isvalid() must be true.
998 assert self
.isvalid()
1001 if __name__
== '__main__':
1002 # Remove regrtest.py's own directory from the module search path. This
1003 # prevents relative imports from working, and relative imports will screw
1004 # up the testing framework. E.g. if both test.test_support and
1005 # test_support are imported, they will not contain the same globals, and
1006 # much of the testing framework relies on the globals in the
1007 # test.test_support module.
1008 mydir
= os
.path
.abspath(os
.path
.normpath(os
.path
.dirname(sys
.argv
[0])))
1009 i
= pathlen
= len(sys
.path
)
1012 if os
.path
.abspath(os
.path
.normpath(sys
.path
[i
])) == mydir
:
1014 if len(sys
.path
) == pathlen
:
1015 print 'Could not find %r in sys.path to remove it' % mydir