source: src/tests/test.py@ e464759

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 e464759 was 075d862, checked in by Thierry Delisle <tdelisle@…>, 9 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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