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
Line 
1#!/usr/bin/python
2from __future__ import print_function
3
4from functools import partial
5from multiprocessing import Pool
6from os import listdir, environ
7from os.path import isfile, join, splitext
8from subprocess import Popen, PIPE, STDOUT
9
10import argparse
11import os
12import re
13import stat
14import sys
15import multiprocessing
16
17################################################################################
18# help functions
19################################################################################
20
21# Test class that defines what a test is
22class Test:
23 def __init__(self, name, path):
24 self.name, self.path = name, path
25
26# parses the Makefile to find the machine type (32-bit / 64-bit)
27def getMachineType():
28 sh('echo "void ?{}(int*a,int b){}int main(){return 0;}" > .dummy.c')
29 ret, out = sh("make .dummy", print2stdout=False)
30 if ret != 0:
31 print("Failed to identify architecture:")
32 print(out)
33 print("Stopping")
34 sys.exit(1)
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)
39
40def listTestsFolder(folder) :
41 path = ('./.expect/%s/' % folder) if folder else './.expect/'
42 subpath = "%s/" % folder if folder else ""
43
44 # tests directly in the .expect folder will always be processed
45 return map(lambda fname: Test(fname, subpath + fname),
46 [splitext(f)[0] for f in listdir( path )
47 if not f.startswith('.') and f.endswith('.txt')
48 ])
49
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
55 generic_list = listTestsFolder( "" )
56
57 # tests in the machineType folder will be ran only for the corresponding compiler
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 []
62
63 # append both lists to get
64 return generic_list + typed_list + concurrent_list;
65
66# helper functions to run terminal commands
67def sh(cmd, dry_run = False, print2stdout = True):
68 if dry_run : # if this is a dry_run, only print the commands that would be ran
69 print("cmd: %s" % cmd)
70 return 0, None
71 else : # otherwise create a pipe and run the desired command
72 proc = Popen(cmd, stdout=None if print2stdout else PIPE, stderr=STDOUT, shell=True)
73 out, err = proc.communicate()
74 return proc.returncode, out
75
76# helper function to replace patterns in a file
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
92# tests output may differ depending on the depth of the makefile
93def fix_MakeLevel(file) :
94 if environ.get('MAKELEVEL') :
95 file_replace(file, "make\[%i\]" % int(environ.get('MAKELEVEL')), 'make' )
96
97# helper function to check if a files contains only a spacific string
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
105# check whether or not a file is executable
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
115
116################################################################################
117# running test functions
118################################################################################
119def run_single_test(test, generate, dry_run, debug):
120
121 # find the output file based on the test name and options flag
122 out_file = (".out/%s.log" % test.name) if not generate else (".expect/%s.txt" % test.path)
123 err_file = ".err/%s.log" % test.name
124
125 # remove any outputs from the previous tests to prevent side effects
126 sh("rm -f %s" % out_file, dry_run)
127 sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
128
129 options = "-debug" if debug else "-nodebug";
130
131 # build, skipping to next test on error
132 make_ret, _ = sh("""%s EXTRA_FLAGS="-quiet %s" %s 2> %s 1> /dev/null""" % (make_cmd, options, test.name, out_file), dry_run)
133
134 # if the make command succeds continue otherwise skip to diff
135 if make_ret == 0 :
136 # fetch optional input
137 stdinput = "< .in/%s.txt" % test.name if isfile(".in/%s.txt" % test.path) else ""
138
139 if fileIsExecutable(test.name) :
140 # run test
141 sh("./%s %s > %s 2>&1" % (test.name, stdinput, out_file), dry_run)
142 else :
143 # simply cat the result into the output
144 sh("cat %s > %s" % (test.name, out_file), dry_run)
145
146 else :
147 # command failed save the log to less temporary file
148 sh("mv %s %s" % (err_file, out_file), dry_run)
149
150 retcode = 0
151 error = None
152
153 # # fix output to prevent make depth to cause issues
154 # fix_MakeLevel(out_file)
155
156 if generate :
157 # if we are ounly generating the output we still need to check that the test actually exists
158 if not dry_run and fileContainsOnly(out_file, "make: *** No rule to make target `%s'. Stop." % test.name) :
159 retcode = 1;
160 error = "\t\tNo make target for test %s!" % test.name
161 sh("rm %s" % out_file, False)
162
163 else :
164 # diff the output of the files
165 diff_cmd = ("diff --ignore-all-space "
166 "--ignore-blank-lines "
167 "--old-group-format='\t\tmissing lines :\n"
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
181 # fetch return code and error from the diff command
182 retcode, error = sh(diff_cmd % (test.path, test.name), dry_run, False)
183
184 # clean the executable
185 sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
186
187 return retcode, error
188
189def run_test_instance(t, generate, dry_run, debug) :
190 try :
191 # print formated name
192 name_txt = "%20s " % t.name
193
194 #run the test instance and collect the result
195 test_failed, error = run_single_test(t, generate, dry_run, debug)
196
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
216
217 except KeyboardInterrupt:
218 test_failed = True
219
220
221# run the given list of tests with the given parameters
222def run_tests(tests, generate, dry_run, jobs, debug) :
223 # clean the sandbox from previous commands
224 sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
225
226 #make sure the required folder are present
227 sh('mkdir -p .out .expect .err', dry_run)
228
229 if generate :
230 print( "Regenerate tests for: " )
231
232 # for each test to run
233 pool = Pool(jobs)
234 try :
235 results = pool.map_async(partial(run_test_instance, generate=generate, dry_run=dry_run, debug=debug), tests ).get(9999)
236 except KeyboardInterrupt:
237 pool.terminate()
238 print("Tests interrupted by user")
239 sys.exit(1)
240
241 #clean the workspace
242 sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
243
244 for failed in results:
245 if failed :
246 return 1
247
248 return 0
249
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
259################################################################################
260# main loop
261################################################################################
262# create a parser with the arguments for the tests script
263parser = argparse.ArgumentParser(description='Script which runs cforall tests')
264parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='no')
265parser.add_argument('--concurrent', help='Run concurrent tests', type=yes_no, default='yes')
266parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
267parser.add_argument('--list', help='List all test available', action='store_true')
268parser.add_argument('--all', help='Run all test available', action='store_true')
269parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
270parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int, default='8')
271parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
272
273# parse the command line arguments
274options = parser.parse_args()
275
276# script must have at least some tests to run
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) :
279 print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
280 parser.print_help()
281 sys.exit(1)
282
283# fetch the liest of all valid tests
284allTests = listTests( options.concurrent )
285
286# if user wants all tests than no other treatement of the test list is required
287if options.all or options.list :
288 tests = allTests
289
290else :
291 #otherwise we need to validate that the test list that was entered is valid
292 tests = []
293
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
296 if options.regenerate_expected :
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) )
303
304 else :
305 # otherwise we only need to validate that all tests are present in the complete list
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)
313
314 # make sure we have at least some test to run
315 if len(tests) == 0 :
316 print('ERROR: No valid test to run', file=sys.stderr)
317 sys.exit(1)
318
319# sort the test alphabetically for convenience
320tests.sort(key=lambda t: t.name)
321
322# check if the user already passed in a number of jobs for multi-threading
323make_flags = environ.get('MAKEFLAGS')
324make_jobs_fds = re.search("--jobserver-(auth|fds)=\s*([0-9]+),([0-9]+)", make_flags) if make_flags else None
325if make_jobs_fds :
326 tokens = os.read(int(make_jobs_fds.group(2)), 1024)
327 options.jobs = len(tokens)
328 os.write(int(make_jobs_fds.group(3)), tokens)
329else :
330 options.jobs = multiprocessing.cpu_count()
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
337options.jobs = min( options.jobs, len(tests) )
338
339print('Running (%s) on %i cores' % ("debug" if options.debug else "no debug", options.jobs))
340make_cmd = "make" if make_flags else ("make -j%i" % options.jobs)
341
342# users may want to simply list the tests
343if options.list :
344 print("\n".join(map(lambda t: "%s (%s)" % (t.name, t.path), tests)))
345
346else :
347 # otherwise run all tests and make sure to return the correct error code
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.