source: src/tests/test.py@ a2f86e9

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox memory 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 a2f86e9 was 1d57215, checked in by Thierry Delisle <tdelisle@…>, 9 years ago

added flush calls to test script to help live build output

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