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
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 multiprocessing
12import os
13import re
14import signal
15import stat
16import sys
17
18################################################################################
19# help functions
20################################################################################
21
22# Test class that defines what a test is
23class Test:
24 def __init__(self, name, path):
25 self.name, self.path = name, path
26
27# parses the Makefile to find the machine type (32-bit / 64-bit)
28def getMachineType():
29 sh('echo "void ?{}(int*a,int b){}int main(){return 0;}" > .dummy.c')
30 ret, out = sh("make .dummy -s", print2stdout=False)
31
32 if ret != 0:
33 print("Failed to identify architecture:")
34 print(out)
35 print("Stopping")
36 sh("rm -f .dummy.c > /dev/null 2>&1")
37 sh("rm -f .dummy > /dev/null 2>&1")
38 sys.exit(1)
39
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)
44
45def listTestsFolder(folder) :
46 path = ('./.expect/%s/' % folder) if folder else './.expect/'
47 subpath = "%s/" % folder if folder else ""
48
49 # tests directly in the .expect folder will always be processed
50 return map(lambda fname: Test(fname, subpath + fname),
51 [splitext(f)[0] for f in listdir( path )
52 if not f.startswith('.') and f.endswith('.txt')
53 ])
54
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
60 generic_list = listTestsFolder( "" )
61
62 # tests in the machineType folder will be ran only for the corresponding compiler
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 []
67
68 # append both lists to get
69 return generic_list + typed_list + concurrent_list;
70
71# helper functions to run terminal commands
72def sh(cmd, dry_run = False, print2stdout = True):
73 if dry_run : # if this is a dry_run, only print the commands that would be ran
74 print("cmd: %s" % cmd)
75 return 0, None
76 else : # otherwise create a pipe and run the desired command
77 proc = Popen(cmd, stdout=None if print2stdout else PIPE, stderr=STDOUT, shell=True)
78 out, err = proc.communicate()
79 return proc.returncode, out
80
81# helper function to replace patterns in a file
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
97# tests output may differ depending on the depth of the makefile
98def fix_MakeLevel(file) :
99 if environ.get('MAKELEVEL') :
100 file_replace(file, "make\[%i\]" % int(environ.get('MAKELEVEL')), 'make' )
101
102# helper function to check if a files contains only a spacific string
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
110# check whether or not a file is executable
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
120
121################################################################################
122# running test functions
123################################################################################
124def run_single_test(test, generate, dry_run, debug):
125
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
130
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)
134
135 options = "-debug" if debug else "-nodebug";
136
137 # build, skipping to next test on error
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)
139
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 ""
144
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)
151
152 else :
153 # command failed save the log to less temporary file
154 sh("mv %s %s" % (err_file, out_file), dry_run)
155
156 retcode = 0
157 error = None
158
159 # # fix output to prevent make depth to cause issues
160 # fix_MakeLevel(out_file)
161
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)
168
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)
192
193 return retcode, error
194
195def run_test_instance(t, generate, dry_run, debug) :
196
197 signal.signal(signal.SIGINT, signal.SIG_DFL)
198 # print formated name
199 name_txt = "%20s " % t.name
200
201 #run the test instance and collect the result
202 test_failed, error = run_single_test(t, generate, dry_run, debug)
203
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"
211
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
218
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
225
226
227# run the given list of tests with the given parameters
228def run_tests(tests, generate, dry_run, jobs, debug) :
229 # clean the sandbox from previous commands
230 sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
231
232 #make sure the required folder are present
233 sh('mkdir -p .out .expect .err', dry_run)
234
235 if generate :
236 print( "Regenerate tests for: " )
237
238 # for each test to run
239 original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
240 pool = Pool(jobs)
241 signal.signal(signal.SIGINT, original_sigint_handler)
242 try :
243 results = pool.map_async(partial(run_test_instance, generate=generate, dry_run=dry_run, debug=debug), tests ).get(9999)
244 except KeyboardInterrupt:
245 pool.terminate()
246 print("Tests interrupted by user")
247 sys.exit(1)
248
249 #clean the workspace
250 sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
251
252 for failed in results:
253 if failed :
254 return 1
255
256 return 0
257
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
267################################################################################
268# main loop
269################################################################################
270abspath = os.path.abspath(__file__)
271dname = os.path.dirname(abspath)
272os.chdir(dname)
273
274# create a parser with the arguments for the tests script
275parser = argparse.ArgumentParser(description='Script which runs cforall tests')
276parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='no')
277parser.add_argument('--concurrent', help='Run concurrent tests', type=yes_no, default='yes')
278parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
279parser.add_argument('--list', help='List all test available', action='store_true')
280parser.add_argument('--all', help='Run all test available', action='store_true')
281parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
282parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int, default='8')
283parser.add_argument('--list-comp', help='List all valide arguments', action='store_true')
284parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
285
286
287# parse the command line arguments
288options = parser.parse_args()
289do_list = options.list or options.list_comp
290
291# script must have at least some tests to run
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) :
294 print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
295 parser.print_help()
296 sys.exit(1)
297
298# fetch the liest of all valid tests
299allTests = listTests( options.concurrent )
300
301# if user wants all tests than no other treatement of the test list is required
302if options.all or do_list :
303 tests = allTests
304
305else :
306 #otherwise we need to validate that the test list that was entered is valid
307 tests = []
308
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
311 if options.regenerate_expected :
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) )
318
319 else :
320 # otherwise we only need to validate that all tests are present in the complete list
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)
328
329 # make sure we have at least some test to run
330 if len(tests) == 0 :
331 print('ERROR: No valid test to run', file=sys.stderr)
332 sys.exit(1)
333
334# sort the test alphabetically for convenience
335tests.sort(key=lambda t: t.name)
336
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)))
341
342elif options.list :
343 print("\n".join(map(lambda t: "%s (%s)" % (t.name, t.path), tests)))
344
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()
355
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)
360
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)
365
366 # otherwise run all tests and make sure to return the correct error code
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.