source: src/tests/test.py@ 409433da

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 409433da was 0e7b95c, checked in by Thierry Delisle <tdelisle@…>, 9 years ago

Tests now run with concurrency by default

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