#!/usr/bin/env python## __COPYRIGHT__## runtest.py - wrapper script for running SCons tests## This script mainly exists to set PYTHONPATH to the right list of# directories to test the SCons modules.## By default, it directly uses the modules in the local tree:# ./src/ (source files we ship) and ./QMTest/ (other modules we don't).## HOWEVER, now that SCons has Repository support, we don't have# Aegis copy all of the files into the local tree. So if you're# using Aegis and want to run tests by hand using this script, you# must "aecp ." the entire source tree into your local directory# structure. When you're done with your change, you can then# "aecpu -unch ." to un-copy any files that you haven't changed.## When any -p option is specified, this script assumes it's in a# directory in which a build has been performed, and sets PYTHONPATH# so that it *only* references the modules that have unpacked from# the specified built package, to test whether the packages are good.## Options:## -3 Run with the python -3 option,## -a Run all tests; does a virtual 'find' for# all SCons tests under the current directory.# You can also specify a list of subdirectories# (not available with the "--qmtest" option!). Then,# only the given folders are searched for test files.## --aegis Print test results to an output file (specified# by the -o option) in the format expected by# aetest(5). This is intended for use in the# batch_test_command field in the Aegis project# config file.## -d Debug. Runs the script under the Python# debugger (pdb.py) so you don't have to# muck with PYTHONPATH yourself.## -e Starts the script in external mode, for# testing separate Tools and packages.## -f file Only execute the tests listed in the specified# file.## -h Print the help and exit.## -k Suppress printing of count and percent progress for# the single tests.## -l List available tests and exit.## -n No execute, just print command lines.## -o file Print test results to the specified file.# The --aegis and --xml options specify the# output format.## -P Python Use the specified Python interpreter.## -p package Test against the specified package.## --passed In the final summary, also report which tests# passed. The default is to only report tests# which failed or returned NO RESULT.## -q Quiet. By default, runtest.py prints the# command line it will execute before# executing it. This suppresses that print.## -s Short progress. Prints only the command line# and a percentage value, based on the total and# current number of tests.# All stdout and stderr messages get suppressed (this# does only work with subprocess though)!## --sp The Aegis search path.## --spe The Aegis executable search path.## -t Print the execution time of each test.## -X The scons "script" is an executable; don't# feed it to Python.## -x scons The scons script to use for tests.## --xml Print test results to an output file (specified# by the -o option) in an SCons-specific XML format.# This is (will be) used for reporting results back# to a central SCons test monitoring infrastructure.## (Note: There used to be a -v option that specified the SCons# version to be tested, when we were installing in a version-specific# library directory. If we ever resurrect that as the default, then# you can find the appropriate code in the 0.04 version of this script,# rather than reinventing that wheel.)importgetoptimportglobimportosimportreimportstatimportsysimporttimetry:sortedexceptNameError:# Pre-2.4 Python has no sorted() function.## The pre-2.4 Python list.sort() method does not support# list.sort(key=) nor list.sort(reverse=) keyword arguments, so# we must implement the functionality of those keyword arguments# by hand instead of passing them to list.sort().defsorted(iterable,cmp=None,key=None,reverse=0):ifkeyisnotNone:result=[(key(x),x)forxiniterable]else:result=iterable[:]ifcmpisNone:# Pre-2.3 Python does not support list.sort(None).result.sort()else:result.sort(cmp)ifkeyisnotNone:result=[t1fort0,t1inresult]ifreverse:result.reverse()returnresultcwd=os.getcwd()all=0baseline=0builddir=os.path.join(cwd,'build')external=0debug=''execute_tests=1format=Nonelist_only=Noneprintcommand=1package=Noneprint_passed_summary=Nonepython3incompatibilities=Nonescons=Nonescons_exec=Noneoutputfile=Nonetestlistfile=Noneversion=''print_times=Nonepython=Nonesp=Nonespe=Noneprint_progress=1suppress_stdout=Falsesuppress_stderr=Falseallow_pipe_files=Truehelpstr="""\Usage: runtest.py [OPTIONS] [TEST ...]Options: -3 Warn about Python 3.x incompatibilities. -a, --all Run all tests. --aegis Print results in Aegis format. -b BASE, --baseline BASE Run test scripts against baseline BASE. --builddir DIR Directory in which packages were built. -d, --debug Run test scripts under the Python debugger. -e, --external Run the script in external mode (for testing separate Tools) -f FILE, --file FILE Run tests in specified FILE. -h, --help Print this message and exit. -k, --no-progress Suppress count and percent progress messages. -l, --list List available tests and exit. -n, --no-exec No execute, just print command lines. --noqmtest Execute tests directly, not using QMTest. --nopipefiles Doesn't use the "file pipe" workaround for subprocess.Popen() for starting tests. WARNING: Only use this when too much file traffic is giving you trouble AND you can be sure that none of your tests create output that exceed 65K chars! You might run into some deadlocks else. -o FILE, --output FILE Print test results to FILE. -P Python Use the specified Python interpreter. -p PACKAGE, --package PACKAGE Test against the specified PACKAGE: deb Debian local-tar-gz .tar.gz standalone package local-zip .zip standalone package rpm Red Hat src-tar-gz .tar.gz source package src-zip .zip source package tar-gz .tar.gz distribution zip .zip distribution --passed Summarize which tests passed. --qmtest Run using the QMTest harness. -q, --quiet Don't print the test being executed. --sp PATH The Aegis search path. --spe PATH The Aegis executable search path. -t, --time Print test execution time. -v version Specify the SCons version. --verbose=LEVEL Set verbose level: 1 = print executed commands, 2 = print commands and non-zero output, 3 = print commands and all output. -X Test script is executable, don't feed to Python. -x SCRIPT, --exec SCRIPT Test SCRIPT. --xml Print results in SCons XML format.Environment Variables: PRESERVE, PRESERVE_{PASS,FAIL,NO_RESULT}: preserve test subdirs TESTCMD_VERBOSE: turn on verbosity in TestCommand"""opts,args=getopt.getopt(sys.argv[1:],"3ab:def:hklno:P:p:qsv:Xx:t",['all','aegis','baseline=','builddir=','debug','external','file=','help','no-progress','list','no-exec','noqmtest','nopipefiles','output=','package=','passed','python=','qmtest','quiet','short-progress','sp=','spe=','time','version=','exec=','verbose=','xml'])foro,ainopts:ifoin['-3']:python3incompatibilities=1elifoin['-a','--all']:all=1elifoin['-b','--baseline']:baseline=aelifoin['--builddir']:builddir=aifnotos.path.isabs(builddir):builddir=os.path.normpath(os.path.join(cwd,builddir))elifoin['-d','--debug']:fordirinsys.path:pdb=os.path.join(dir,'pdb.py')ifos.path.exists(pdb):debug=pdbbreakelifoin['-e','--external']:external=1elifoin['-f','--file']:ifnotos.path.isabs(a):a=os.path.join(cwd,a)testlistfile=aelifoin['-h','--help']:printhelpstrsys.exit(0)elifoin['-k','--no-progress']:print_progress=0elifoin['-l','--list']:list_only=1elifoin['-n','--no-exec']:execute_tests=Noneelifoin['--noqmtest']:qmtest=Noneelifoin['--nopipefiles']:allow_pipe_files=Falseelifoin['-o','--output']:ifa!='-'andnotos.path.isabs(a):a=os.path.join(cwd,a)outputfile=aelifoin['-p','--package']:package=aelifoin['--passed']:print_passed_summary=1elifoin['-P','--python']:python=aelifoin['--qmtest']:ifsys.platform=='win32':# typically in c:/PythonXX/Scriptsqmtest='qmtest.py'else:qmtest='qmtest'elifoin['-q','--quiet']:printcommand=0suppress_stdout=Truesuppress_stderr=Trueelifoin['-s','--short-progress']:print_progress=1suppress_stdout=Truesuppress_stderr=Trueelifoin['--sp']:sp=a.split(os.pathsep)elifoin['--spe']:spe=a.split(os.pathsep)elifoin['-t','--time']:print_times=1elifoin['--verbose']:os.environ['TESTCMD_VERBOSE']=aelifoin['-v','--version']:version=aelifoin['-X']:scons_exec=1elifoin['-x','--exec']:scons=aelifoin['--aegis','--xml']:format=oifnotargsandnotallandnottestlistfile:sys.stderr.write("""\runtest.py: No tests were specified. List one or more tests on the command line, use the -f option to specify a file containing a list of tests, or use the -a option to find and run all tests.""")sys.exit(1)ifsys.platformin('win32','cygwin'):defwhereis(file):pathext=['']+os.environ['PATHEXT'].split(os.pathsep)fordirinos.environ['PATH'].split(os.pathsep):f=os.path.join(dir,file)forextinpathext:fext=f+extifos.path.isfile(fext):returnfextreturnNoneelse:defwhereis(file):fordirinos.environ['PATH'].split(os.pathsep):f=os.path.join(dir,file)ifos.path.isfile(f):try:st=os.stat(f)exceptOSError:continueifstat.S_IMODE(st[stat.ST_MODE])&0111:returnfreturnNone# See if --qmtest or --noqmtest specifiedtry:qmtestexceptNameError:qmtest=None# Old code for using QMTest by default if it's installed.# We now default to not using QMTest unless explicitly asked for.#for q in ['qmtest', 'qmtest.py']:# path = whereis(q)# if path:# # The name was found on $PATH; just execute the found name so# # we don't have to worry about paths containing white space.# qmtest = q# break#if not qmtest:# msg = ('Warning: found neither qmtest nor qmtest.py on $PATH;\n' +# '\tassuming --noqmtest option.\n')# sys.stderr.write(msg)# sys.stderr.flush()aegis=whereis('aegis')ifformat=='--aegis'andaegis:change=os.popen("aesub '$c' 2>/dev/null","r").read()ifchange:ifspisNone:paths=os.popen("aesub '$sp' 2>/dev/null","r").read()[:-1]sp=paths.split(os.pathsep)ifspeisNone:spe=os.popen("aesub '$spe' 2>/dev/null","r").read()[:-1]spe=spe.split(os.pathsep)else:aegis=NoneifspisNone:sp=[]ifspeisNone:spe=[]sp.append(builddir)sp.append(cwd)#_ws=re.compile('\s')defescape(s):if_ws.search(s):s='"'+s+'"'s=s.replace('\\','\\\\')returns# Try to use subprocess instead of the more low-level# spawn command...use_subprocess=Truetry:importsubprocessexcept:use_subprocess=Falseifuse_subprocess:ifnotsuppress_stdoutandnotsuppress_stderr:# Without any output suppressed, we let the subprocess# write its stuff freely to stdout/stderr.defspawn_it(command_args):p=subprocess.Popen(' '.join(command_args),shell=True)return(None,None,p.wait())else:# Else, we catch the output of both pipes...ifallow_pipe_files:# The subprocess.Popen() suffers from a well-known# problem. Data for stdout/stderr is read into a # memory buffer of fixed size, 65K which is not very much.# When it fills up, it simply stops letting the child process# write to it. The child will then sit and patiently wait to# be able to write the rest of its output. Hang! # In order to work around this, we follow a suggestion# by Anders Pearson in# http://http://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/# and pass temp file objects to Popen() instead of the ubiquitous# subprocess.PIPE. defspawn_it(command_args):# Create temporary filesimporttempfiletmp_stdout=tempfile.TemporaryFile(mode='w+t')tmp_stderr=tempfile.TemporaryFile(mode='w+t')# Start subprocess...p=subprocess.Popen(' '.join(command_args),stdout=tmp_stdout,stderr=tmp_stderr,shell=True)# ... and wait for it to finish.ret=p.wait()try:# Rewind to start of filestmp_stdout.seek(0)tmp_stderr.seek(0)# Read outputspawned_stdout=tmp_stdout.read()spawned_stderr=tmp_stderr.read()finally:# Remove temp files by closing themtmp_stdout.close()tmp_stderr.close()# Return valuesreturn(spawned_stderr,spawned_stdout,ret)else:# We get here only if the user gave the '--nopipefiles'# option, meaning the "temp file" approach for# subprocess.communicate() above shouldn't be used.# He hopefully knows what he's doing, but again we have a# potential deadlock situation in the following code:# If the subprocess writes a lot of data to its stderr,# the pipe will fill up (nobody's reading it yet) and the# subprocess will wait for someone to read it. # But the parent process is trying to read from stdin# (but the subprocess isn't writing anything there). # Hence a deadlock.# Be dragons here! Better don't use this!defspawn_it(command_args):p=subprocess.Popen(' '.join(command_args),stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)spawned_stdout=p.stdout.read()spawned_stderr=p.stderr.read()return(spawned_stderr,spawned_stdout,p.wait())else:has_subprocess=False# Set up lowest-common-denominator spawning of a process on both Windows# and non-Windows systems that works all the way back to Python 1.5.2.try:os.spawnvexceptAttributeError:defspawn_it(command_args):pid=os.fork()ifpid==0:os.execv(command_args[0],command_args)else:pid,status=os.waitpid(pid,0)return(None,None,status>>8)else:defspawn_it(command_args):command=command_args[0]command_args=[escape(c)forcincommand_args]return(None,None,os.spawnv(os.P_WAIT,command,command_args))classBase(object):def__init__(self,path,spe=None):self.path=pathself.abspath=os.path.abspath(path)ifspe:fordirinspe:f=os.path.join(dir,path)ifos.path.isfile(f):self.abspath=fbreakself.status=NoneclassSystemExecutor(Base):defexecute(self):self.stderr,self.stdout,s=spawn_it(self.command_args)self.status=sifs<0ors>2:sys.stdout.write("Unexpected exit status %d\n"%s)ifnotuse_subprocess:importpopen2try:popen2.Popen3exceptAttributeError:classPopenExecutor(Base):defexecute(self):(tochild,fromchild,childerr)=os.popen3(self.command_str)tochild.close()self.stderr=childerr.read()self.stdout=fromchild.read()fromchild.close()self.status=childerr.close()ifnotself.status:self.status=0else:self.status=self.status>>8else:classPopenExecutor(Base):defexecute(self):p=popen2.Popen3(self.command_str,1)p.tochild.close()self.stdout=p.fromchild.read()self.stderr=p.childerr.read()self.status=p.wait()self.status=self.status>>8else:classPopenExecutor(Base):# For an explanation of the following 'if ... else'# and the 'allow_pipe_files' option, please check out the# use_subprocess path in the definition of spawn_it() above.ifallow_pipe_files:defexecute(self):# Create temporary filesimporttempfiletmp_stdout=tempfile.TemporaryFile(mode='w+t')tmp_stderr=tempfile.TemporaryFile(mode='w+t')# Start subprocess...p=subprocess.Popen(self.command_str,stdout=tmp_stdout,stderr=tmp_stderr,shell=True)# ... and wait for it to finish.self.status=p.wait()try:# Rewind to start of filestmp_stdout.seek(0)tmp_stderr.seek(0)# Read outputself.stdout=tmp_stdout.read()self.stderr=tmp_stderr.read()finally:# Remove temp files by closing themtmp_stdout.close()tmp_stderr.close()else:defexecute(self):p=subprocess.Popen(self.command_str,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)self.stdout=p.stdout.read()self.stderr=p.stderr.read()self.status=p.wait()classAegis(SystemExecutor):defheader(self,f):f.write('test_result = [\n')defwrite(self,f):f.write(' { file_name = "%s";\n'%self.path)f.write(' exit_status = %d; },\n'%self.status)deffooter(self,f):f.write('];\n')classXML(PopenExecutor):defheader(self,f):f.write(' <results>\n')defwrite(self,f):f.write(' <test>\n')f.write(' <file_name>%s</file_name>\n'%self.path)f.write(' <command_line>%s</command_line>\n'%self.command_str)f.write(' <exit_status>%s</exit_status>\n'%self.status)f.write(' <stdout>%s</stdout>\n'%self.stdout)f.write(' <stderr>%s</stderr>\n'%self.stderr)f.write(' <time>%.1f</time>\n'%self.test_time)f.write(' </test>\n')deffooter(self,f):f.write(' <time>%.1f</time>\n'%self.total_time)f.write(' </results>\n')format_class={None:SystemExecutor,'--aegis':Aegis,'--xml':XML,}Test=format_class[format]ifpackage:dir={'deb':'usr','local-tar-gz':None,'local-zip':None,'rpm':'usr','src-tar-gz':'','src-zip':'','tar-gz':'','zip':'',}# The hard-coded "python2.1" here is the library directory# name on Debian systems, not an executable, so it's all right.lib={'deb':os.path.join('python2.1','site-packages')}ifpackagenotindir:sys.stderr.write("Unknown package '%s'\n"%package)sys.exit(2)test_dir=os.path.join(builddir,'test-%s'%package)ifdir[package]isNone:scons_script_dir=test_dirglobs=glob.glob(os.path.join(test_dir,'scons-local-*'))ifnotglobs:sys.stderr.write("No `scons-local-*' dir in `%s'\n"%test_dir)sys.exit(2)scons_lib_dir=Nonepythonpath_dir=globs[len(globs)-1]elifsys.platform=='win32':scons_script_dir=os.path.join(test_dir,dir[package],'Scripts')scons_lib_dir=os.path.join(test_dir,dir[package])pythonpath_dir=scons_lib_direlse:scons_script_dir=os.path.join(test_dir,dir[package],'bin')l=lib.get(package,'scons')scons_lib_dir=os.path.join(test_dir,dir[package],'lib',l)pythonpath_dir=scons_lib_dirscons_runtest_dir=builddirelse:sd=Noneld=None# XXX: Logic like the following will be necessary once# we fix runtest.py to run tests within an Aegis change# without symlinks back to the baseline(s).##if spe:# if not scons:# for dir in spe:# d = os.path.join(dir, 'src', 'script')# f = os.path.join(d, 'scons.py')# if os.path.isfile(f):# sd = d# scons = f# spe = map(lambda x: os.path.join(x, 'src', 'engine'), spe)# ld = os.pathsep.join(spe)ifnotbaselineorbaseline=='.':base=cwdelifbaseline=='-':# Tentative code for fetching information directly from the# QMTest context file.##import qm.common#import qm.test.context#qm.rc.Load("test")#context = qm.test.context.Context()#context.Read('context')url=Nonesvn_info=os.popen("svn info 2>&1","r").read()match=re.search('URL: (.*)',svn_info)ifmatch:url=match.group(1)ifnoturl:sys.stderr.write('runtest.py: could not find a URL:\n')sys.stderr.write(svn_info)sys.exit(1)importtempfilebase=tempfile.mkdtemp(prefix='runtest-tmp-')command='cd %s && svn co -q %s'%(base,url)base=os.path.join(base,os.path.split(url)[1])ifprintcommand:printcommandifexecute_tests:os.system(command)else:base=baselinescons_runtest_dir=baseifnotexternal:scons_script_dir=sdoros.path.join(base,'src','script')scons_lib_dir=ldoros.path.join(base,'src','engine')else:scons_script_dir=sdor''scons_lib_dir=ldor''pythonpath_dir=scons_lib_dirifscons:# Let the version of SCons that the -x option pointed to find# its own modules.os.environ['SCONS']=sconselifscons_lib_dir:# Because SCons is really aggressive about finding its modules,# it sometimes finds SCons modules elsewhere on the system.# This forces SCons to use the modules that are being tested.os.environ['SCONS_LIB_DIR']=scons_lib_dirifscons_exec:os.environ['SCONS_EXEC']='1'ifexternal:os.environ['SCONS_EXTERNAL_TEST']='1'os.environ['SCONS_RUNTEST_DIR']=scons_runtest_diros.environ['SCONS_SCRIPT_DIR']=scons_script_diros.environ['SCONS_CWD']=cwdos.environ['SCONS_VERSION']=versionold_pythonpath=os.environ.get('PYTHONPATH')# FIXME: the following is necessary to pull in half of the testing# harness from $srcdir/etc. Those modules should be transfered# to QMTest/ once we completely cut over to using that as# the harness, in which case this manipulation of PYTHONPATH# should be able to go away.pythonpaths=[pythonpath_dir]fordirinsp:ifformat=='--aegis':q=os.path.join(dir,'build','QMTest')else:q=os.path.join(dir,'QMTest')pythonpaths.append(q)# Add path of the QMTest folder to PYTHONPATHscriptpath=os.path.dirname(os.path.realpath(__file__))pythonpaths.append(os.path.join(scriptpath,'QMTest'))os.environ['SCONS_SOURCE_PATH_EXECUTABLE']=os.pathsep.join(spe)os.environ['PYTHONPATH']=os.pathsep.join(pythonpaths)ifold_pythonpath:os.environ['PYTHONPATH']=os.environ['PYTHONPATH']+ \
os.pathsep+ \
old_pythonpathifpython3incompatibilities:os.environ['SCONS_HORRIBLE_REGRESSION_TEST_HACK']='1'tests=[]deffind_Tests_py(directory):result=[]fordirpath,dirnames,filenamesinos.walk(directory):if'sconstest.skip'infilenames:continueforfnameinfilenames:iffname.endswith("Tests.py"):result.append(os.path.join(dirpath,fname))returnsorted(result)deffind_py(directory):result=[]fordirpath,dirnames,filenamesinos.walk(directory):if'sconstest.skip'infilenames:continuetry:exclude_fp=open(os.path.join(dirpath,".exclude_tests"))exceptEnvironmentError:excludes=[]else:excludes=[e.split('#',1)[0].strip()foreinexclude_fp.readlines()]forfnameinfilenames:iffname.endswith(".py")andfnamenotinexcludes:result.append(os.path.join(dirpath,fname))returnsorted(result)deffind_sconstest_py(directory):result=[]fordirpath,dirnames,filenamesinos.walk(directory):# Skip folders containing a sconstest.skip fileif'sconstest.skip'infilenames:continuetry:exclude_fp=open(os.path.join(dirpath,".exclude_tests"))exceptEnvironmentError:excludes=[]else:excludes=[e.split('#',1)[0].strip()foreinexclude_fp.readlines()]forfnameinfilenames:iffname.endswith(".py")andfname.startswith("sconstest-")andfnamenotinexcludes:result.append(os.path.join(dirpath,fname))returnsorted(result)ifargs:ifspe:forainargs:ifos.path.isabs(a):tests.extend(glob.glob(a))else:fordirinspe:x=os.path.join(dir,a)globs=glob.glob(x)ifglobs:tests.extend(globs)breakelse:forainargs:forpathinglob.glob(a):ifos.path.isdir(path):ifpath[:3]=='src':tests.extend(find_Tests_py(path))elifpath[:4]=='test':tests.extend(find_py(path))tests.extend(find_sconstest_py(path))else:tests.append(path)eliftestlistfile:tests=open(testlistfile,'r').readlines()tests=[xforxintestsifx[0]!='#']tests=[x[:-1]forxintests]tests=[x.strip()forxintests]elifallandnotqmtest:# Find all of the SCons functional tests in the local directory# tree. This is anything under the 'src' subdirectory that ends# with 'Tests.py', or any Python script (*.py) under the 'test'# subdirectory.## Note that there are some tests under 'src' that *begin* with# 'test_', but they're packaging and installation tests, not# functional tests, so we don't execute them by default. (They can# still be executed by hand, though, and are routinely executed# by the Aegis packaging build to make sure that we're building# things correctly.)tests.extend(find_Tests_py('src'))tests.extend(find_py('test'))tests.extend(find_sconstest_py('test'))ifformat=='--aegis'andaegis:cmd="aegis -list -unf pf 2>/dev/null"forlineinos.popen(cmd,"r").readlines():a=line.split()ifa[0]=="test"anda[-1]notintests:tests.append(Test(a[-1],spe))cmd="aegis -list -unf cf 2>/dev/null"forlineinos.popen(cmd,"r").readlines():a=line.split()ifa[0]=="test":ifa[1]=="remove":tests.remove(a[-1])elifa[-1]notintests:tests.append(Test(a[-1],spe))tests.sort()ifqmtest:ifbaseline:aegis_result_stream='scons_tdb.AegisBaselineStream'qmr_file='baseline.qmr'else:aegis_result_stream='scons_tdb.AegisChangeStream'qmr_file='results.qmr'ifprint_times:aegis_result_stream=aegis_result_stream+"(print_time='1')"qmtest_args=[qmtest,]ifformat=='--aegis':dir=builddirifnotos.path.isdir(dir):dir=cwdqmtest_args.extend(['-D',dir])qmtest_args.extend(['run','--output %s'%qmr_file,'--format none','--result-stream="%s"'%aegis_result_stream,])ifpython:qmtest_args.append('--context python="%s"'%python)ifoutputfile:ifformat=='--xml':rsclass='scons_tdb.SConsXMLResultStream'else:rsclass='scons_tdb.AegisBatchStream'qof="r'"+outputfile+"'"rs='--result-stream="%s(filename=%s)"'%(rsclass,qof)qmtest_args.append(rs)ifformat=='--aegis':tests=[x.replace(cwd+os.sep,'')forxintests]else:os.environ['SCONS']=os.path.join(cwd,'src','script','scons.py')cmd=' '.join(qmtest_args+tests)ifprintcommand:sys.stdout.write(cmd+'\n')sys.stdout.flush()status=0ifexecute_tests:status=os.system(cmd)try:wexitstatus=os.WEXITSTATUSexceptAttributeError:passelse:status=wexitstatus(status)sys.exit(status)#try:# os.chdir(scons_script_dir)#except OSError:# passtests=[Test(t)fortintests]classUnbuffered(object):def__init__(self,file):self.file=fileself.softspace=0## backward compatibility; not supported in Py3kdefwrite(self,arg):self.file.write(arg)self.file.flush()def__getattr__(self,attr):returngetattr(self.file,attr)sys.stdout=Unbuffered(sys.stdout)sys.stderr=Unbuffered(sys.stderr)iflist_only:fortintests:sys.stdout.write(t.path+"\n")sys.exit(0)#ifnotpython:ifos.name=='java':python=os.path.join(sys.prefix,'jython')else:python=sys.executableos.environ["python_executable"]=python# time.clock() is the suggested interface for doing benchmarking timings,# but time.time() does a better job on Linux systems, so let that be# the non-Windows default.ifsys.platform=='win32':time_func=time.clockelse:time_func=time.timeifprint_times:print_time_func=lambdafmt,time:sys.stdout.write(fmt%time)else:print_time_func=lambdafmt,time:Nonetotal_start_time=time_func()total_num_tests=len(tests)foridx,tinenumerate(tests):command_args=['-tt']ifpython3incompatibilities:command_args.append('-3')ifdebug:command_args.append(debug)command_args.append(t.path)t.command_args=[python]+command_argst.command_str=" ".join([escape(python)]+command_args)ifprintcommand:ifprint_progress:sys.stdout.write("%d/%d (%.2f%s) %s\n"%(idx+1,total_num_tests,float(idx+1)*100.0/float(total_num_tests),'%',t.command_str))else:sys.stdout.write(t.command_str+"\n")ifexternal:head,tail=os.path.split(t.abspath)ifhead:os.environ['PYTHON_SCRIPT_DIR']=headelse:os.environ['PYTHON_SCRIPT_DIR']=''test_start_time=time_func()ifexecute_tests:t.execute()ifnotsuppress_stdoutandt.stdout:printt.stdoutifnotsuppress_stderrandt.stderr:printt.stderrt.test_time=time_func()-test_start_timeprint_time_func("Test execution time: %.1f seconds\n",t.test_time)iflen(tests)>0:tests[0].total_time=time_func()-total_start_timeprint_time_func("Total execution time for all tests: %.1f seconds\n",tests[0].total_time)passed=[tfortintestsift.status==0]fail=[tfortintestsift.status==1]no_result=[tfortintestsift.status==2]iflen(tests)!=1andexecute_tests:ifpassedandprint_passed_summary:iflen(passed)==1:sys.stdout.write("\nPassed the following test:\n")else:sys.stdout.write("\nPassed the following %d tests:\n"%len(passed))paths=[x.pathforxinpassed]sys.stdout.write("\t"+"\n\t".join(paths)+"\n")iffail:iflen(fail)==1:sys.stdout.write("\nFailed the following test:\n")else:sys.stdout.write("\nFailed the following %d tests:\n"%len(fail))paths=[x.pathforxinfail]sys.stdout.write("\t"+"\n\t".join(paths)+"\n")ifno_result:iflen(no_result)==1:sys.stdout.write("\nNO RESULT from the following test:\n")else:sys.stdout.write("\nNO RESULT from the following %d tests:\n"%len(no_result))paths=[x.pathforxinno_result]sys.stdout.write("\t"+"\n\t".join(paths)+"\n")ifoutputfile:ifoutputfile=='-':f=sys.stdoutelse:f=open(outputfile,'w')tests[0].header(f)#f.write("test_result = [\n")fortintests:t.write(f)tests[0].footer(f)#f.write("];\n")ifoutputfile!='-':f.close()ifformat=='--aegis':sys.exit(0)eliflen(fail):sys.exit(1)eliflen(no_result):sys.exit(2)else:sys.exit(0)# Local Variables:# tab-width:4# indent-tabs-mode:nil# End:# vim: set expandtab tabstop=4 shiftwidth=4: