5 # runtest.py - wrapper script for running SCons tests
7 # This script mainly exists to set PYTHONPATH to the right list of
8 # directories to test the SCons modules.
10 # By default, it directly uses the modules in the local tree:
11 # ./src/ (source files we ship) and ./QMTest/ (other modules we don't).
13 # HOWEVER, now that SCons has Repository support, we don't have
14 # Aegis copy all of the files into the local tree. So if you're
15 # using Aegis and want to run tests by hand using this script, you
16 # must "aecp ." the entire source tree into your local directory
17 # structure. When you're done with your change, you can then
18 # "aecpu -unch ." to un-copy any files that you haven't changed.
20 # When any -p option is specified, this script assumes it's in a
21 # directory in which a build has been performed, and sets PYTHONPATH
22 # so that it *only* references the modules that have unpacked from
23 # the specified built package, to test whether the packages are good.
27 # -a Run all tests; does a virtual 'find' for
28 # all SCons tests under the current directory.
30 # --aegis Print test results to an output file (specified
31 # by the -o option) in the format expected by
32 # aetest(5). This is intended for use in the
33 # batch_test_command field in the Aegis project
36 # -d Debug. Runs the script under the Python
37 # debugger (pdb.py) so you don't have to
38 # muck with PYTHONPATH yourself.
40 # -f file Only execute the tests listed in the specified
43 # -h Print the help and exit.
45 # -l List available tests and exit.
47 # -n No execute, just print command lines.
49 # -o file Print test results to the specified file.
50 # The --aegis and --xml options specify the
53 # -P Python Use the specified Python interpreter.
55 # -p package Test against the specified package.
57 # --passed In the final summary, also report which tests
58 # passed. The default is to only report tests
59 # which failed or returned NO RESULT.
61 # -q Quiet. By default, runtest.py prints the
62 # command line it will execute before
63 # executing it. This suppresses that print.
65 # --sp The Aegis search path.
67 # --spe The Aegis executable search path.
69 # -t Print the execution time of each test.
71 # -X The scons "script" is an executable; don't
74 # -x scons The scons script to use for tests.
76 # --xml Print test results to an output file (specified
77 # by the -o option) in an SCons-specific XML format.
78 # This is (will be) used for reporting results back
79 # to a central SCons test monitoring infrastructure.
81 # (Note: There used to be a -v option that specified the SCons
82 # version to be tested, when we were installing in a version-specific
83 # library directory. If we ever resurrect that as the default, then
84 # you can find the appropriate code in the 0.04 version of this script,
85 # rather than reinventing that wheel.)
98 if not hasattr(os, 'WEXITSTATUS'):
99 os.WEXITSTATUS = lambda x: x
105 builddir = os.path.join(cwd, 'build')
112 print_passed_summary = None
124 Usage: runtest.py [OPTIONS] [TEST ...]
126 -a, --all Run all tests.
127 --aegis Print results in Aegis format.
128 -b BASE, --baseline BASE Run test scripts against baseline BASE.
129 --builddir DIR Directory in which packages were built.
130 -d, --debug Run test scripts under the Python debugger.
131 -f FILE, --file FILE Run tests in specified FILE.
132 -h, --help Print this message and exit.
133 -l, --list List available tests and exit.
134 -n, --no-exec No execute, just print command lines.
135 --noqmtest Execute tests directly, not using QMTest.
136 -o FILE, --output FILE Print test results to FILE.
137 -P Python Use the specified Python interpreter.
138 -p PACKAGE, --package PACKAGE
139 Test against the specified PACKAGE:
141 local-tar-gz .tar.gz standalone package
142 local-zip .zip standalone package
144 src-tar-gz .tar.gz source package
145 src-zip .zip source package
146 tar-gz .tar.gz distribution
147 zip .zip distribution
148 --passed Summarize which tests passed.
149 --qmtest Run using the QMTest harness.
150 -q, --quiet Don't print the test being executed.
151 --sp PATH The Aegis search path.
152 --spe PATH The Aegis executable search path.
153 -t, --time Print test execution time.
154 -v version Specify the SCons version.
155 --verbose=LEVEL Set verbose level: 1 = print executed commands,
156 2 = print commands and non-zero output,
157 3 = print commands and all output.
158 -X Test script is executable, don't feed to Python.
159 -x SCRIPT, --exec SCRIPT Test SCRIPT.
160 --xml Print results in SCons XML format.
163 opts, args = getopt.getopt(sys.argv[1:], "ab:df:hlno:P:p:qv:Xx:t",
164 ['all', 'aegis', 'baseline=', 'builddir=',
165 'debug', 'file=', 'help',
166 'list', 'no-exec', 'noqmtest', 'output=',
167 'package=', 'passed', 'python=', 'qmtest',
168 'quiet', 'sp=', 'spe=', 'time',
173 if o in ['-a', '--all']:
175 elif o in ['-b', '--baseline']:
177 elif o in ['--builddir']:
179 if not os.path.isabs(builddir):
180 builddir = os.path.normpath(os.path.join(cwd, builddir))
181 elif o in ['-d', '--debug']:
183 pdb = os.path.join(dir, 'pdb.py')
184 if os.path.exists(pdb):
187 elif o in ['-f', '--file']:
188 if not os.path.isabs(a):
189 a = os.path.join(cwd, a)
191 elif o in ['-h', '--help']:
194 elif o in ['-l', '--list']:
196 elif o in ['-n', '--no-exec']:
198 elif o in ['--noqmtest']:
200 elif o in ['-o', '--output']:
201 if a != '-' and not os.path.isabs(a):
202 a = os.path.join(cwd, a)
204 elif o in ['-p', '--package']:
206 elif o in ['--passed']:
207 print_passed_summary = 1
208 elif o in ['-P', '--python']:
210 elif o in ['--qmtest']:
211 if sys.platform == 'win32':
212 # typically in c:/PythonXX/Scripts
216 elif o in ['-q', '--quiet']:
219 sp = string.split(a, os.pathsep)
221 spe = string.split(a, os.pathsep)
222 elif o in ['-t', '--time']:
224 elif o in ['--verbose']:
225 os.environ['TESTCMD_VERBOSE'] = a
226 elif o in ['-v', '--version']:
230 elif o in ['-x', '--exec']:
232 elif o in ['--aegis', '--xml']:
235 if not args and not all and not testlistfile:
236 sys.stderr.write("""\
237 runtest.py: No tests were specified.
238 List one or more tests on the command line, use the
239 -f option to specify a file containing a list of tests,
240 or use the -a option to find and run all tests.
245 if sys.platform in ('win32', 'cygwin'):
248 pathext = [''] + string.split(os.environ['PATHEXT'])
249 for dir in string.split(os.environ['PATH'], os.pathsep):
250 f = os.path.join(dir, file)
253 if os.path.isfile(fext):
260 for dir in string.split(os.environ['PATH'], os.pathsep):
261 f = os.path.join(dir, file)
262 if os.path.isfile(f):
267 if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
271 # See if --qmtest or --noqmtest specified
275 # Neither specified; find it in path.
277 for q in ['qmtest', 'qmtest.py']:
283 msg = ('Warning: found neither qmtest nor qmtest.py on $PATH;\n' +
284 '\tassuming --noqmtest option.\n')
285 sys.stderr.write(msg)
288 aegis = whereis('aegis')
290 if format == '--aegis' and aegis:
291 change = os.popen("aesub '$c' 2>/dev/null", "r").read()
294 paths = os.popen("aesub '$sp' 2>/dev/null", "r").read()[:-1]
295 sp = string.split(paths, os.pathsep)
297 spe = os.popen("aesub '$spe' 2>/dev/null", "r").read()[:-1]
298 spe = string.split(spe, os.pathsep)
311 _ws = re.compile('\s')
316 s = string.replace(s, '\\', '\\\\')
319 # Set up lowest-common-denominator spawning of a process on both Windows
320 # and non-Windows systems that works all the way back to Python 1.5.2.
323 except AttributeError:
324 def spawn_it(command_args):
327 os.execv(command_args[0], command_args)
329 pid, status = os.waitpid(pid, 0)
332 def spawn_it(command_args):
333 command = command_args[0]
334 command_args = map(escape, command_args)
335 return os.spawnv(os.P_WAIT, command, command_args)
338 def __init__(self, path, spe=None):
340 self.abspath = os.path.abspath(path)
343 f = os.path.join(dir, path)
344 if os.path.isfile(f):
349 class SystemExecutor(Base):
351 s = spawn_it(self.command_args)
354 sys.stdout.write("Unexpected exit status %d\n" % s)
362 except AttributeError:
363 class PopenExecutor(Base):
365 (tochild, fromchild, childerr) = os.popen3(self.command_str)
367 self.stderr = childerr.read()
368 self.stdout = fromchild.read()
370 self.status = childerr.close()
374 class PopenExecutor(Base):
376 p = popen2.Popen3(self.command_str, 1)
378 self.stdout = p.fromchild.read()
379 self.stderr = p.childerr.read()
380 self.status = p.wait()
382 class PopenExecutor(Base):
384 p = subprocess.Popen(self.command_str, shell=True)
386 self.stdout = p.stdout.read()
387 self.stdout = p.stderr.read()
388 self.status = p.wait()
390 class Aegis(SystemExecutor):
392 f.write('test_result = [\n')
394 f.write(' { file_name = "%s";\n' % self.path)
395 f.write(' exit_status = %d; },\n' % self.status)
399 class XML(PopenExecutor):
401 f.write(' <results>\n')
404 f.write(' <file_name>%s</file_name>\n' % self.path)
405 f.write(' <command_line>%s</command_line>\n' % self.command_str)
406 f.write(' <exit_status>%s</exit_status>\n' % self.status)
407 f.write(' <stdout>%s</stdout>\n' % self.stdout)
408 f.write(' <stderr>%s</stderr>\n' % self.stderr)
409 f.write(' <time>%.1f</time>\n' % self.test_time)
410 f.write(' </test>\n')
412 f.write(' <time>%.1f</time>\n' % self.total_time)
413 f.write(' </results>\n')
416 None : SystemExecutor,
421 Test = format_class[format]
427 'local-tar-gz' : None,
436 # The hard-coded "python2.1" here is the library directory
437 # name on Debian systems, not an executable, so it's all right.
439 'deb' : os.path.join('python2.1', 'site-packages')
442 if not dir.has_key(package):
443 sys.stderr.write("Unknown package '%s'\n" % package)
446 test_dir = os.path.join(builddir, 'test-%s' % package)
448 if dir[package] is None:
449 scons_script_dir = test_dir
450 globs = glob.glob(os.path.join(test_dir, 'scons-local-*'))
452 sys.stderr.write("No `scons-local-*' dir in `%s'\n" % test_dir)
455 pythonpath_dir = globs[len(globs)-1]
456 elif sys.platform == 'win32':
457 scons_script_dir = os.path.join(test_dir, dir[package], 'Scripts')
458 scons_lib_dir = os.path.join(test_dir, dir[package])
459 pythonpath_dir = scons_lib_dir
461 scons_script_dir = os.path.join(test_dir, dir[package], 'bin')
462 l = lib.get(package, 'scons')
463 scons_lib_dir = os.path.join(test_dir, dir[package], 'lib', l)
464 pythonpath_dir = scons_lib_dir
466 scons_runtest_dir = builddir
472 # XXX: Logic like the following will be necessary once
473 # we fix runtest.py to run tests within an Aegis change
474 # without symlinks back to the baseline(s).
479 # d = os.path.join(dir, 'src', 'script')
480 # f = os.path.join(d, 'scons.py')
481 # if os.path.isfile(f):
484 # spe = map(lambda x: os.path.join(x, 'src', 'engine'), spe)
485 # ld = string.join(spe, os.pathsep)
487 if not baseline or baseline == '.':
489 elif baseline == '-':
490 # Tentative code for fetching information directly from the
491 # QMTest context file.
494 #import qm.test.context
496 #context = qm.test.context.Context()
497 #context.Read('context')
500 svn_info = os.popen("svn info 2>&1", "r").read()
501 match = re.search('URL: (.*)', svn_info)
505 sys.stderr.write('runtest.py: could not find a URL:\n')
506 sys.stderr.write(svn_info)
509 base = tempfile.mkdtemp(prefix='runtest-tmp-')
511 command = 'cd %s && svn co -q %s' % (base, url)
513 base = os.path.join(base, os.path.split(url)[1])
521 scons_runtest_dir = base
523 scons_script_dir = sd or os.path.join(base, 'src', 'script')
525 scons_lib_dir = ld or os.path.join(base, 'src', 'engine')
527 pythonpath_dir = scons_lib_dir
530 # Let the version of SCons that the -x option pointed to find
532 os.environ['SCONS'] = scons
534 # Because SCons is really aggressive about finding its modules,
535 # it sometimes finds SCons modules elsewhere on the system.
536 # This forces SCons to use the modules that are being tested.
537 os.environ['SCONS_LIB_DIR'] = scons_lib_dir
540 os.environ['SCONS_EXEC'] = '1'
542 os.environ['SCONS_RUNTEST_DIR'] = scons_runtest_dir
543 os.environ['SCONS_SCRIPT_DIR'] = scons_script_dir
544 os.environ['SCONS_CWD'] = cwd
546 os.environ['SCONS_VERSION'] = version
548 old_pythonpath = os.environ.get('PYTHONPATH')
550 # FIXME: the following is necessary to pull in half of the testing
551 # harness from $srcdir/etc. Those modules should be transfered
552 # to QMTest/ once we completely cut over to using that as
553 # the harness, in which case this manipulation of PYTHONPATH
554 # should be able to go away.
555 pythonpaths = [ pythonpath_dir ]
558 if format == '--aegis':
559 q = os.path.join(dir, 'build', 'QMTest')
561 q = os.path.join(dir, 'QMTest')
562 pythonpaths.append(q)
564 os.environ['SCONS_SOURCE_PATH_EXECUTABLE'] = string.join(spe, os.pathsep)
566 os.environ['PYTHONPATH'] = string.join(pythonpaths, os.pathsep)
569 os.environ['PYTHONPATH'] = os.environ['PYTHONPATH'] + \
579 tests.extend(glob.glob(a))
582 x = os.path.join(dir, a)
589 tests.extend(glob.glob(a))
591 tests = open(testlistfile, 'r').readlines()
592 tests = filter(lambda x: x[0] != '#', tests)
593 tests = map(lambda x: x[:-1], tests)
594 elif all and not qmtest:
595 # Find all of the SCons functional tests in the local directory
596 # tree. This is anything under the 'src' subdirectory that ends
597 # with 'Tests.py', or any Python script (*.py) under the 'test'
600 # Note that there are some tests under 'src' that *begin* with
601 # 'test_', but they're packaging and installation tests, not
602 # functional tests, so we don't execute them by default. (They can
603 # still be executed by hand, though, and are routinely executed
604 # by the Aegis packaging build to make sure that we're building
608 def find_Tests_py(tdict, dirname, names):
609 for n in filter(lambda n: n[-8:] == "Tests.py", names):
610 t = os.path.join(dirname, n)
611 if not tdict.has_key(t):
613 os.path.walk('src', find_Tests_py, tdict)
615 def find_py(tdict, dirname, names):
616 for n in filter(lambda n: n[-3:] == ".py", names):
617 t = os.path.join(dirname, n)
618 if not tdict.has_key(t):
620 os.path.walk('test', find_py, tdict)
622 if format == '--aegis' and aegis:
623 cmd = "aegis -list -unf pf 2>/dev/null"
624 for line in os.popen(cmd, "r").readlines():
625 a = string.split(line)
626 if a[0] == "test" and not tdict.has_key(a[-1]):
627 tdict[a[-1]] = Test(a[-1], spe)
628 cmd = "aegis -list -unf cf 2>/dev/null"
629 for line in os.popen(cmd, "r").readlines():
630 a = string.split(line)
634 elif not tdict.has_key(a[-1]):
635 tdict[a[-1]] = Test(a[-1], spe)
642 aegis_result_stream = 'scons_tdb.AegisBaselineStream'
643 qmr_file = 'baseline.qmr'
645 aegis_result_stream = 'scons_tdb.AegisChangeStream'
646 qmr_file = 'results.qmr'
649 aegis_result_stream = aegis_result_stream + "(print_time='1')"
651 qmtest_args = [ qmtest, ]
653 if format == '--aegis':
655 if not os.path.isdir(dir):
657 qmtest_args.extend(['-D', dir])
661 '--output %s' % qmr_file,
663 '--result-stream="%s"' % aegis_result_stream,
667 qmtest_args.append('--context python="%s"' % python)
670 if format == '--xml':
671 rsclass = 'scons_tdb.SConsXMLResultStream'
673 rsclass = 'scons_tdb.AegisBatchStream'
674 qof = "r'" + outputfile + "'"
675 rs = '--result-stream="%s(filename=%s)"' % (rsclass, qof)
676 qmtest_args.append(rs)
678 if format == '--aegis':
679 tests = map(lambda x: string.replace(x, cwd+os.sep, ''), tests)
681 os.environ['SCONS'] = os.path.join(cwd, 'src', 'script', 'scons.py')
683 cmd = string.join(qmtest_args + tests, ' ')
685 sys.stdout.write(cmd + '\n')
689 status = os.WEXITSTATUS(os.system(cmd))
693 # os.chdir(scons_script_dir)
697 tests = map(Test, tests)
700 def __init__(self, file):
702 def write(self, arg):
705 def __getattr__(self, attr):
706 return getattr(self.file, attr)
708 sys.stdout = Unbuffered(sys.stdout)
712 sys.stdout.write(t.abspath + "\n")
717 if os.name == 'java':
718 python = os.path.join(sys.prefix, 'jython')
720 python = sys.executable
722 # time.clock() is the suggested interface for doing benchmarking timings,
723 # but time.time() does a better job on Linux systems, so let that be
724 # the non-Windows default.
726 if sys.platform == 'win32':
727 time_func = time.clock
729 time_func = time.time
732 print_time_func = lambda fmt, time: sys.stdout.write(fmt % time)
734 print_time_func = lambda fmt, time: None
736 total_start_time = time_func()
738 t.command_args = [python, '-tt']
740 t.command_args.append(debug)
741 t.command_args.append(t.abspath)
742 t.command_str = string.join(map(escape, t.command_args), " ")
744 sys.stdout.write(t.command_str + "\n")
745 test_start_time = time_func()
748 t.test_time = time_func() - test_start_time
749 print_time_func("Test execution time: %.1f seconds\n", t.test_time)
751 tests[0].total_time = time_func() - total_start_time
752 print_time_func("Total execution time for all tests: %.1f seconds\n", tests[0].total_time)
754 passed = filter(lambda t: t.status == 0, tests)
755 fail = filter(lambda t: t.status == 1, tests)
756 no_result = filter(lambda t: t.status == 2, tests)
758 if len(tests) != 1 and execute_tests:
759 if passed and print_passed_summary:
761 sys.stdout.write("\nPassed the following test:\n")
763 sys.stdout.write("\nPassed the following %d tests:\n" % len(passed))
764 paths = map(lambda x: x.path, passed)
765 sys.stdout.write("\t" + string.join(paths, "\n\t") + "\n")
768 sys.stdout.write("\nFailed the following test:\n")
770 sys.stdout.write("\nFailed the following %d tests:\n" % len(fail))
771 paths = map(lambda x: x.path, fail)
772 sys.stdout.write("\t" + string.join(paths, "\n\t") + "\n")
774 if len(no_result) == 1:
775 sys.stdout.write("\nNO RESULT from the following test:\n")
777 sys.stdout.write("\nNO RESULT from the following %d tests:\n" % len(no_result))
778 paths = map(lambda x: x.path, no_result)
779 sys.stdout.write("\t" + string.join(paths, "\n\t") + "\n")
782 if outputfile == '-':
785 f = open(outputfile, 'w')
787 #f.write("test_result = [\n")
792 if outputfile != '-':
795 if format == '--aegis':