source: src/tests/test.py@ 278516c

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 278516c was 47f9422, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Fixed machinte type dependency on tests folders not in the git repo

  • Property mode set to 100755
File size: 11.8 KB
RevLine 
[945047e]1#!/usr/bin/python
[efc15918]2from __future__ import print_function
3
[ced2e989]4from functools import partial
5from multiprocessing import Pool
[122cac7]6from os import listdir, environ
[0534c3c]7from os.path import isfile, join, splitext
[efc15918]8from subprocess import Popen, PIPE, STDOUT
9
10import argparse
[122cac7]11import os
12import re
[a43e1d7]13import stat
[efc15918]14import sys
[4e9151f]15import multiprocessing
[efc15918]16
17################################################################################
18# help functions
19################################################################################
[f1231f2]20
[911348cd]21# Test class that defines what a test is
[f1231f2]22class Test:
23 def __init__(self, name, path):
24 self.name, self.path = name, path
25
[911348cd]26# parses the Makefile to find the machine type (32-bit / 64-bit)
[f1231f2]27def getMachineType():
[7895d46]28 sh('echo "void ?{}(int*a,int b){}int main(){return 0;}" > .dummy.c')
[00303d50]29 ret, out = sh("make .dummy", print2stdout=False)
30 if ret != 0:
[47f9422]31 print("Failed to identify architecture:")
[00303d50]32 print(out)
[47f9422]33 print("Stopping")
34 sys.exit(1)
[20340c2]35 _, out = sh("file .dummy", print2stdout=False)
36 sh("rm -f .dummy.c > /dev/null 2>&1")
37 sh("rm -f .dummy > /dev/null 2>&1")
38 return re.search("ELF\s([0-9]+)-bit", out).group(1)
[f1231f2]39
[be65cca]40def listTestsFolder(folder) :
[871b664]41 path = ('./.expect/%s/' % folder) if folder else './.expect/'
42 subpath = "%s/" % folder if folder else ""
[f1231f2]43
[911348cd]44 # tests directly in the .expect folder will always be processed
[871b664]45 return map(lambda fname: Test(fname, subpath + fname),
[be65cca]46 [splitext(f)[0] for f in listdir( path )
[0534c3c]47 if not f.startswith('.') and f.endswith('.txt')
[f1231f2]48 ])
[efc15918]49
[be65cca]50# reads the directory ./.expect and indentifies the tests
51def listTests( concurrent ):
52 machineType = getMachineType()
53
54 # tests directly in the .expect folder will always be processed
[871b664]55 generic_list = listTestsFolder( "" )
[be65cca]56
[911348cd]57 # tests in the machineType folder will be ran only for the corresponding compiler
[be65cca]58 typed_list = listTestsFolder( machineType )
59
60 # tests in the concurrent folder will be ran only if concurrency is enabled
61 concurrent_list = listTestsFolder( "concurrent" ) if concurrent else []
[f1231f2]62
[911348cd]63 # append both lists to get
[be65cca]64 return generic_list + typed_list + concurrent_list;
[efc15918]65
[911348cd]66# helper functions to run terminal commands
[472ca32]67def sh(cmd, dry_run = False, print2stdout = True):
[911348cd]68 if dry_run : # if this is a dry_run, only print the commands that would be ran
[efc15918]69 print("cmd: %s" % cmd)
[472ca32]70 return 0, None
[911348cd]71 else : # otherwise create a pipe and run the desired command
[472ca32]72 proc = Popen(cmd, stdout=None if print2stdout else PIPE, stderr=STDOUT, shell=True)
73 out, err = proc.communicate()
74 return proc.returncode, out
[efc15918]75
[911348cd]76# helper function to replace patterns in a file
[122cac7]77def file_replace(fname, pat, s_after):
78 # first, see if the pattern is even in the file.
79 with open(fname) as f:
80 if not any(re.search(pat, line) for line in f):
81 return # pattern does not occur in file so we are done.
82
83 # pattern is in the file, so perform replace operation.
84 with open(fname) as f:
85 out_fname = fname + ".tmp"
86 out = open(out_fname, "w")
87 for line in f:
88 out.write(re.sub(pat, s_after, line))
89 out.close()
90 os.rename(out_fname, fname)
91
[911348cd]92# tests output may differ depending on the depth of the makefile
[122cac7]93def fix_MakeLevel(file) :
94 if environ.get('MAKELEVEL') :
95 file_replace(file, "make\[%i\]" % int(environ.get('MAKELEVEL')), 'make' )
96
[911348cd]97# helper function to check if a files contains only a spacific string
[84d4d6f]98def fileContainsOnly(file, text) :
99 with open(file) as f:
100 ff = f.read().strip()
101 result = ff == text.strip()
102
103 return result;
104
[911348cd]105# check whether or not a file is executable
[a43e1d7]106def fileIsExecutable(file) :
107 try :
108 fileinfo = os.stat(file)
109 return bool(fileinfo.st_mode & stat.S_IXUSR)
110 except Exception as inst:
111 print(type(inst)) # the exception instance
112 print(inst.args) # arguments stored in .args
113 print(inst)
114 return False
[122cac7]115
[efc15918]116################################################################################
117# running test functions
118################################################################################
[6a1bdfd]119def run_single_test(test, generate, dry_run, debug):
[3c1d702]120
[911348cd]121 # find the output file based on the test name and options flag
[f1231f2]122 out_file = (".out/%s.log" % test.name) if not generate else (".expect/%s.txt" % test.path)
[4e9151f]123 err_file = ".err/%s.log" % test.name
[3c1d702]124
[911348cd]125 # remove any outputs from the previous tests to prevent side effects
[3c1d702]126 sh("rm -f %s" % out_file, dry_run)
[f1231f2]127 sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
[efc15918]128
[6a1bdfd]129 options = "-debug" if debug else "-nodebug";
130
[efc15918]131 # build, skipping to next test on error
[4782b39]132 make_ret, _ = sh("""%s EXTRA_FLAGS="-quiet %s" %s 2> %s 1> /dev/null""" % (make_cmd, options, test.name, out_file), dry_run)
[efc15918]133
[911348cd]134 # if the make command succeds continue otherwise skip to diff
[3c1d702]135 if make_ret == 0 :
136 # fetch optional input
[e28d0f5]137 stdinput = "< .in/%s.txt" % test.name if isfile(".in/%s.txt" % test.path) else ""
[efc15918]138
[f1231f2]139 if fileIsExecutable(test.name) :
[a43e1d7]140 # run test
[f1231f2]141 sh("./%s %s > %s 2>&1" % (test.name, stdinput, out_file), dry_run)
[a43e1d7]142 else :
143 # simply cat the result into the output
[f1231f2]144 sh("cat %s > %s" % (test.name, out_file), dry_run)
[efc15918]145
[4e9151f]146 else :
147 # command failed save the log to less temporary file
148 sh("mv %s %s" % (err_file, out_file), dry_run)
149
[3c1d702]150 retcode = 0
[472ca32]151 error = None
[122cac7]152
[4e9151f]153 # # fix output to prevent make depth to cause issues
154 # fix_MakeLevel(out_file)
[122cac7]155
[84d4d6f]156 if generate :
[911348cd]157 # if we are ounly generating the output we still need to check that the test actually exists
[f1231f2]158 if not dry_run and fileContainsOnly(out_file, "make: *** No rule to make target `%s'. Stop." % test.name) :
[84d4d6f]159 retcode = 1;
[38736854]160 error = "\t\tNo make target for test %s!" % test.name
[84d4d6f]161 sh("rm %s" % out_file, False)
162
163 else :
[3c1d702]164 # diff the output of the files
[4e9151f]165 diff_cmd = ("diff --ignore-all-space "
166 "--ignore-blank-lines "
167 "--old-group-format='\t\tmissing lines :\n"
[472ca32]168 "%%<' \\\n"
169 "--new-group-format='\t\tnew lines :\n"
170 "%%>' \\\n"
171 "--unchanged-group-format='%%=' \\"
172 "--changed-group-format='\t\texpected :\n"
173 "%%<\n"
174 "\t\tgot :\n"
175 "%%>' \\\n"
176 "--new-line-format='\t\t%%dn\t%%L' \\\n"
177 "--old-line-format='\t\t%%dn\t%%L' \\\n"
178 "--unchanged-line-format='' \\\n"
179 ".expect/%s.txt .out/%s.log")
180
[911348cd]181 # fetch return code and error from the diff command
[f1231f2]182 retcode, error = sh(diff_cmd % (test.path, test.name), dry_run, False)
[efc15918]183
184 # clean the executable
[f1231f2]185 sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
[efc15918]186
[472ca32]187 return retcode, error
[efc15918]188
[6a1bdfd]189def run_test_instance(t, generate, dry_run, debug) :
[0a1a680]190 try :
191 # print formated name
192 name_txt = "%20s " % t.name
[ced2e989]193
[0a1a680]194 #run the test instance and collect the result
195 test_failed, error = run_single_test(t, generate, dry_run, debug)
[ced2e989]196
[0a1a680]197 # update output based on current action
198 if generate :
199 failed_txt = "ERROR"
200 success_txt = "Done"
201 else :
202 failed_txt = "FAILED"
203 success_txt = "PASSED"
204
205 #print result with error if needed
206 text = name_txt + (failed_txt if test_failed else success_txt)
207 out = sys.stdout
208 if error :
209 text = text + "\n" + error
210 out = sys.stderr
211
212 print(text, file = out);
213 sys.stdout.flush()
214 sys.stderr.flush()
215 return test_failed
[be65cca]216
[0a1a680]217 except KeyboardInterrupt:
218 test_failed = True
[ced2e989]219
220
[911348cd]221# run the given list of tests with the given parameters
[6a1bdfd]222def run_tests(tests, generate, dry_run, jobs, debug) :
[911348cd]223 # clean the sandbox from previous commands
[74358c3]224 sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
[911348cd]225
226 #make sure the required folder are present
[4e9151f]227 sh('mkdir -p .out .expect .err', dry_run)
[3c1d702]228
229 if generate :
[ebcd82b]230 print( "Regenerate tests for: " )
[efc15918]231
[ced2e989]232 # for each test to run
233 pool = Pool(jobs)
234 try :
[23c2b8d3]235 results = pool.map_async(partial(run_test_instance, generate=generate, dry_run=dry_run, debug=debug), tests ).get(9999)
[ced2e989]236 except KeyboardInterrupt:
237 pool.terminate()
238 print("Tests interrupted by user")
239 sys.exit(1)
[efc15918]240
[911348cd]241 #clean the workspace
[74358c3]242 sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
[efc15918]243
[ced2e989]244 for failed in results:
245 if failed :
246 return 1
247
248 return 0
[efc15918]249
[6a1bdfd]250def yes_no(string):
251 if string == "yes" :
252 return True
253 if string == "no" :
254 return False
255 raise argparse.ArgumentTypeError(msg)
256 return False
257
258
[efc15918]259################################################################################
260# main loop
261################################################################################
[911348cd]262# create a parser with the arguments for the tests script
[efc15918]263parser = argparse.ArgumentParser(description='Script which runs cforall tests')
[6a1bdfd]264parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='no')
[0e7b95c]265parser.add_argument('--concurrent', help='Run concurrent tests', type=yes_no, default='yes')
[efc15918]266parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
[0534c3c]267parser.add_argument('--list', help='List all test available', action='store_true')
[efc15918]268parser.add_argument('--all', help='Run all test available', action='store_true')
[0534c3c]269parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
[52c97dd]270parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int, default='8')
[efc15918]271parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
272
[911348cd]273# parse the command line arguments
[efc15918]274options = parser.parse_args()
275
[911348cd]276# script must have at least some tests to run
[0534c3c]277if (len(options.tests) > 0 and options.all and not options.list) \
278or (len(options.tests) == 0 and not options.all and not options.list) :
[3c1d702]279 print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
280 parser.print_help()
281 sys.exit(1)
[efc15918]282
[911348cd]283# fetch the liest of all valid tests
[be65cca]284allTests = listTests( options.concurrent )
[0534c3c]285
[911348cd]286# if user wants all tests than no other treatement of the test list is required
[0534c3c]287if options.all or options.list :
288 tests = allTests
289
290else :
[911348cd]291 #otherwise we need to validate that the test list that was entered is valid
[0534c3c]292 tests = []
[f1231f2]293
[911348cd]294 # if we are regenerating the tests we need to find the information of the
295 # already existing tests and create new info for the new tests
[f1231f2]296 if options.regenerate_expected :
[38736854]297 for testname in options.tests :
298 if testname.endswith(".c") or testname.endswith(".cc") or testname.endswith(".cpp") :
299 print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)
300 else :
301 found = [test for test in allTests if test.name == testname]
302 tests.append( found[0] if len(found) == 1 else Test(testname, testname) )
[f1231f2]303
304 else :
[911348cd]305 # otherwise we only need to validate that all tests are present in the complete list
[f1231f2]306 for testname in options.tests:
307 test = [t for t in allTests if t.name == testname]
308
309 if len(test) != 0 :
310 tests.append( test[0] )
311 else :
312 print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr)
[0534c3c]313
[911348cd]314 # make sure we have at least some test to run
[0534c3c]315 if len(tests) == 0 :
316 print('ERROR: No valid test to run', file=sys.stderr)
317 sys.exit(1)
318
[911348cd]319# sort the test alphabetically for convenience
[f1231f2]320tests.sort(key=lambda t: t.name)
321
[911348cd]322# check if the user already passed in a number of jobs for multi-threading
[7bd045d]323make_flags = environ.get('MAKEFLAGS')
[4e9151f]324make_jobs_fds = re.search("--jobserver-(auth|fds)=\s*([0-9]+),([0-9]+)", make_flags) if make_flags else None
[850fda6]325if make_jobs_fds :
[4e9151f]326 tokens = os.read(int(make_jobs_fds.group(2)), 1024)
[850fda6]327 options.jobs = len(tokens)
[4e9151f]328 os.write(int(make_jobs_fds.group(3)), tokens)
329else :
330 options.jobs = multiprocessing.cpu_count()
[911348cd]331
332# make sure we have a valid number of jobs that corresponds to user input
333if options.jobs <= 0 :
334 print('ERROR: Invalid number of jobs', file=sys.stderr)
335 sys.exit(1)
336
[4e9151f]337options.jobs = min( options.jobs, len(tests) )
338
[6a1bdfd]339print('Running (%s) on %i cores' % ("debug" if options.debug else "no debug", options.jobs))
[850fda6]340make_cmd = "make" if make_flags else ("make -j%i" % options.jobs)
[ced2e989]341
[911348cd]342# users may want to simply list the tests
[0534c3c]343if options.list :
[f1231f2]344 print("\n".join(map(lambda t: "%s (%s)" % (t.name, t.path), tests)))
[efc15918]345
[0534c3c]346else :
[911348cd]347 # otherwise run all tests and make sure to return the correct error code
[6a1bdfd]348 sys.exit( run_tests(tests, options.regenerate_expected, options.dry_run, options.jobs, options.debug) )
Note: See TracBrowser for help on using the repository browser.