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 curses - Tests that use curses and will modify the terminal's
50 state and output modes.
52 largefile - It is okay to run some test that may create huge
53 files. These tests can take a long time and may
54 consume >2GB of disk space temporarily.
56 network - It is okay to run tests that use external network
57 resource, e.g. testing SSL support for sockets.
59 bsddb - It is okay to run the bsddb testsuite, which takes
60 a long time to complete.
62 To enable all resources except one, use '-uall,-<resource>'. For
63 example, to run all the tests except for the bsddb tests, give the
64 option '-uall,-bsddb'.
76 # I see no other way to suppress these warnings;
77 # putting them in test_grammar.py has no effect:
78 warnings
.filterwarnings("ignore", "hex/oct constants", FutureWarning
,
79 ".*test.test_grammar$")
80 if sys
.maxint
> 0x7fffffff:
81 # Also suppress them in <string>, because for 64-bit platforms,
82 # that's where test_grammar.py hides them.
83 warnings
.filterwarnings("ignore", "hex/oct constants", FutureWarning
,
86 # MacOSX (a.k.a. Darwin) has a default stack size that is too small
87 # for deeply recursive regular expressions. We see this as crashes in
88 # the Python test suite when running test_re.py and test_sre.py. The
89 # fix is to set the stack limit to 2048.
90 # This approach may also be useful for other Unixy platforms that
91 # suffer from small default stack limits.
92 if sys
.platform
== 'darwin':
98 soft
, hard
= resource
.getrlimit(resource
.RLIMIT_STACK
)
99 newsoft
= min(hard
, max(soft
, 1024*2048))
100 resource
.setrlimit(resource
.RLIMIT_STACK
, (newsoft
, hard
))
102 from test
import test_support
104 RESOURCE_NAMES
= ('curses', 'largefile', 'network', 'bsddb')
107 def usage(code
, msg
=''):
113 def main(tests
=None, testdir
=None, verbose
=0, quiet
=0, generate
=0,
114 exclude
=0, single
=0, randomize
=0, fromfile
=None, findleaks
=0,
116 """Execute a test suite.
118 This also parses command-line options and modifies its behavior
121 tests -- a list of strings containing test names (optional)
122 testdir -- the directory in which to look for tests (optional)
124 Users other than the Python test suite will certainly want to
125 specify testdir; if it's omitted, the directory containing the
126 Python test suite is searched for.
128 If the tests argument is omitted, the tests listed on the
129 command-line will be used. If that's empty, too, then all *.py
130 files beginning with test_ will be used.
132 The other default arguments (verbose, quiet, generate, exclude,
133 single, randomize, findleaks, and use_resources) allow programmers
134 calling main() directly to set the values that would normally be
135 set by flags on the command line.
139 test_support
.record_original_stdout(sys
.stdout
)
141 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'hvgqxsrf:lu:t:',
142 ['help', 'verbose', 'quiet', 'generate',
143 'exclude', 'single', 'random', 'fromfile',
144 'findleaks', 'use=', 'threshold='])
145 except getopt
.error
, msg
:
149 if use_resources
is None:
152 if o
in ('-h', '--help'):
154 elif o
in ('-v', '--verbose'):
156 elif o
in ('-q', '--quiet'):
159 elif o
in ('-g', '--generate'):
161 elif o
in ('-x', '--exclude'):
163 elif o
in ('-s', '--single'):
165 elif o
in ('-r', '--randomize'):
167 elif o
in ('-f', '--fromfile'):
169 elif o
in ('-l', '--findleaks'):
171 elif o
in ('-t', '--threshold'):
173 gc
.set_threshold(int(a
))
174 elif o
in ('-u', '--use'):
175 u
= [x
.lower() for x
in a
.split(',')]
178 use_resources
[:] = RESOURCE_NAMES
184 if r
not in RESOURCE_NAMES
:
185 usage(1, 'Invalid -u/--use option: ' + a
)
187 if r
in use_resources
:
188 use_resources
.remove(r
)
189 elif r
not in use_resources
:
190 use_resources
.append(r
)
191 if generate
and verbose
:
192 usage(2, "-g and -v don't go together!")
193 if single
and fromfile
:
194 usage(2, "-s and -f don't go together!")
204 print 'No GC available, disabling findleaks.'
207 # Uncomment the line below to report garbage that is not
208 # freeable by reference counting alone. By default only
209 # garbage that is not collectable by the GC is reported.
210 #gc.set_debug(gc.DEBUG_SAVEALL)
214 from tempfile
import gettempdir
215 filename
= os
.path
.join(gettempdir(), 'pynexttest')
217 fp
= open(filename
, 'r')
218 next
= fp
.read().strip()
228 guts
= line
.split() # assuming no test has whitespace in its name
229 if guts
and not guts
[0].startswith('#'):
233 # Strip .py extensions.
235 args
= map(removepy
, args
)
237 tests
= map(removepy
, tests
)
239 stdtests
= STDTESTS
[:]
240 nottests
= NOTTESTS
[:]
247 tests
= tests
or args
or findtests(testdir
, stdtests
, nottests
)
251 random
.shuffle(tests
)
252 test_support
.verbose
= verbose
# Tell tests to be moderately quiet
253 test_support
.use_resources
= use_resources
254 save_modules
= sys
.modules
.keys()
259 ok
= runtest(test
, generate
, verbose
, quiet
, testdir
)
269 print "Warning: test created", len(gc
.garbage
),
270 print "uncollectable object(s)."
271 # move the uncollectable objects somewhere so we don't see
273 found_garbage
.extend(gc
.garbage
)
275 # Unload the newly imported modules (best effort finalization)
276 for module
in sys
.modules
.keys():
277 if module
not in save_modules
and module
.startswith("test."):
278 test_support
.unload(module
)
280 # The lists won't be sorted if running with -r
285 if good
and not quiet
:
286 if not bad
and not skipped
and len(good
) > 1:
288 print count(len(good
), "test"), "OK."
290 print "CAUTION: stdout isn't compared in verbose mode:"
291 print "a test that passes in verbose mode may fail without it."
293 print count(len(bad
), "test"), "failed:"
295 if skipped
and not quiet
:
296 print count(len(skipped
), "test"), "skipped:"
302 surprise
= Set(skipped
) - e
.getexpected()
304 print count(len(surprise
), "skip"), \
305 "unexpected on", plat
+ ":"
308 print "Those skips are all expected on", plat
+ "."
310 print "Ask someone to teach regrtest.py about which tests are"
311 print "expected to get skipped on", plat
+ "."
314 alltests
= findtests(testdir
, stdtests
, nottests
)
315 for i
in range(len(alltests
)):
316 if tests
[0] == alltests
[i
]:
317 if i
== len(alltests
) - 1:
320 fp
= open(filename
, 'w')
321 fp
.write(alltests
[i
+1] + '\n')
327 sys
.exit(len(bad
) > 0)
348 def findtests(testdir
=None, stdtests
=STDTESTS
, nottests
=NOTTESTS
):
349 """Return a list of all applicable test modules."""
350 if not testdir
: testdir
= findtestdir()
351 names
= os
.listdir(testdir
)
354 if name
[:5] == "test_" and name
[-3:] == os
.extsep
+"py":
356 if modname
not in stdtests
and modname
not in nottests
:
357 tests
.append(modname
)
359 return stdtests
+ tests
361 def runtest(test
, generate
, verbose
, quiet
, testdir
= None):
362 """Run a single test.
363 test -- the name of the test
364 generate -- if true, generate output, instead of running the test
365 and comparing it to a previously created output file
366 verbose -- if true, print more messages
367 quiet -- if true, don't print 'skipped' messages (probably redundant)
368 testdir -- test directory
370 test_support
.unload(test
)
371 if not testdir
: testdir
= findtestdir()
372 outputdir
= os
.path
.join(testdir
, "output")
373 outputfile
= os
.path
.join(outputdir
, test
)
377 cfp
= StringIO
.StringIO()
379 save_stdout
= sys
.stdout
383 print test
# Output file starts with test name
384 if test
.startswith('test.'):
387 # Always import it from the test package
388 abstest
= 'test.' + test
389 the_package
= __import__(abstest
, globals(), locals(), [])
390 the_module
= getattr(the_package
, test
)
391 # Most tests run to completion simply as a side-effect of
392 # being imported. For the benefit of tests that can't run
393 # that way (like test_threaded_import), explicitly invoke
394 # their test_main() function (if it exists).
395 indirect_test
= getattr(the_module
, "test_main", None)
396 if indirect_test
is not None:
399 sys
.stdout
= save_stdout
400 except (ImportError, test_support
.TestSkipped
), msg
:
402 print test
, "skipped --", msg
405 except KeyboardInterrupt:
407 except test_support
.TestFailed
, msg
:
408 print "test", test
, "failed --", msg
412 type, value
= sys
.exc_info()[:2]
413 print "test", test
, "crashed --", str(type) + ":", value
416 traceback
.print_exc(file=sys
.stdout
)
422 output
= cfp
.getvalue()
424 if output
== test
+ "\n":
425 if os
.path
.exists(outputfile
):
426 # Write it since it already exists (and the contents
427 # may have changed), but let the user know it isn't
429 print "output file", outputfile
, \
430 "is no longer needed; consider removing it"
432 # We don't need it, so don't create it.
434 fp
= open(outputfile
, "w")
438 if os
.path
.exists(outputfile
):
439 fp
= open(outputfile
, "r")
443 expected
= test
+ "\n"
444 if output
== expected
:
446 print "test", test
, "produced unexpected output:"
448 reportdiff(expected
, output
)
452 def reportdiff(expected
, output
):
455 a
= expected
.splitlines(1)
456 b
= output
.splitlines(1)
457 sm
= difflib
.SequenceMatcher(a
=a
, b
=b
)
458 tuples
= sm
.get_opcodes()
461 # x0:x1 are 0-based slice indices; convert to 1-based line indices.
464 return "line " + str(x0
)
466 return "lines %d-%d" % (x0
, x1
)
468 for op
, a0
, a1
, b0
, b1
in tuples
:
473 print "***", pair(a0
, a1
), "of expected output missing:"
474 for line
in a
[a0
:a1
]:
477 elif op
== 'replace':
478 print "*** mismatch between", pair(a0
, a1
), "of expected", \
479 "output and", pair(b0
, b1
), "of actual output:"
480 for line
in difflib
.ndiff(a
[a0
:a1
], b
[b0
:b1
]):
484 print "***", pair(b0
, b1
), "of actual output doesn't appear", \
485 "in expected output after line", str(a1
)+":"
486 for line
in b
[b0
:b1
]:
490 print "get_opcodes() returned bad tuple?!?!", (op
, a0
, a1
, b0
, b1
)
495 if __name__
== '__main__':
499 testdir
= os
.path
.dirname(file) or os
.curdir
503 if name
.endswith(os
.extsep
+ "py"):
509 return "%d %s" % (n
, word
)
511 return "%d %ss" % (n
, word
)
513 def printlist(x
, width
=70, indent
=4):
514 """Print the elements of iterable x to stdout.
516 Optional arg width (default 70) is the maximum line length.
517 Optional arg indent (default 4) is the number of blanks with which to
521 from textwrap
import fill
522 blanks
= ' ' * indent
523 print fill(' '.join(map(str, x
)), width
,
524 initial_indent
=blanks
, subsequent_indent
=blanks
)
526 # Map sys.platform to a string containing the basenames of tests
527 # expected to be skipped on that platform.
531 # The _ExpectedSkips constructor adds this to the set of expected
532 # skips if not os.path.supports_unicode_filenames.
534 # Whether a skip is expected here depends on whether a large test
535 # input file has been downloaded. test_normalization.skip_expected
538 # Controlled by test_socket_ssl.skip_expected. Requires the network
539 # resource, and a socket module with ssl support.
716 test_threadedtempfile
756 test_threadedtempfile
922 class _ExpectedSkips
:
925 from test
import test_normalization
926 from test
import test_socket_ssl
929 if sys
.platform
in _expectations
:
930 s
= _expectations
[sys
.platform
]
931 self
.expected
= Set(s
.split())
933 if not os
.path
.supports_unicode_filenames
:
934 self
.expected
.add('test_pep277')
936 if test_normalization
.skip_expected
:
937 self
.expected
.add('test_normalization')
939 if test_socket_ssl
.skip_expected
:
940 self
.expected
.add('test_socket_ssl')
945 "Return true iff _ExpectedSkips knows about the current platform."
948 def getexpected(self
):
949 """Return set of test names we expect to skip on current platform.
951 self.isvalid() must be true.
954 assert self
.isvalid()
957 if __name__
== '__main__':
958 # Remove regrtest.py's own directory from the module search path. This
959 # prevents relative imports from working, and relative imports will screw
960 # up the testing framework. E.g. if both test.test_support and
961 # test_support are imported, they will not contain the same globals, and
962 # much of the testing framework relies on the globals in the
963 # test.test_support module.
964 mydir
= os
.path
.abspath(os
.path
.normpath(os
.path
.dirname(sys
.argv
[0])))
965 i
= pathlen
= len(sys
.path
)
968 if os
.path
.abspath(os
.path
.normpath(sys
.path
[i
])) == mydir
:
970 if len(sys
.path
) == pathlen
:
971 print 'Could not find %r in sys.path to remove it' % mydir