source: tests/test.py@ eb60b04

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since eb60b04 was d3c1c6a, checked in by tdelisle <tdelisle@…>, 7 years ago

Tests now prints path+name when runnning

  • Property mode set to 100755
File size: 9.8 KB
Line 
1#!/usr/bin/python3
2
3from pybin.tools import *
4from pybin.test_run import *
5from pybin import settings
6
7import argparse
8import re
9import sys
10import time
11
12################################################################################
13# help functions
14################################################################################
15
16def findTests():
17 expected = []
18
19 def matchTest(path):
20 match = re.search("^%s\/([\w\/\-_]*).expect\/([\w\-_]+)(\.[\w\-_]+)?\.txt$" % settings.SRCDIR, path)
21 if match :
22 test = Test()
23 test.name = match.group(2)
24 test.path = match.group(1)
25 test.arch = match.group(3)[1:] if match.group(3) else None
26 if settings.arch.match(test.arch):
27 expected.append(test)
28
29 pathWalk( matchTest )
30
31 return expected
32
33# reads the directory ./.expect and indentifies the tests
34def listTests( includes, excludes ):
35 # tests directly in the .expect folder will always be processed
36 test_list = findTests()
37
38 # if we have a limited number of includes, filter by them
39 if includes:
40 test_list = [x for x in test_list if
41 x.target().startswith( tuple(includes) )
42 ]
43
44 # # if we have a folders to excludes, filter by them
45 if excludes:
46 test_list = [x for x in test_list if not
47 x.target().startswith( tuple(excludes) )
48 ]
49
50 return test_list
51
52# from the found tests, filter all the valid tests/desired tests
53def validTests( options ):
54 tests = []
55
56 # if we are regenerating the tests we need to find the information of the
57 # already existing tests and create new info for the new tests
58 if options.regenerate_expected :
59 for testname in options.tests :
60 testname = canonicalPath( testname )
61 if Test.valid_name(testname):
62 found = [test for test in allTests if canonicalPath( test.target() ) == testname]
63 tests.append( found[0] if len(found) == 1 else Test.from_target(testname) )
64 else :
65 print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)
66
67 else :
68 # otherwise we only need to validate that all tests are present in the complete list
69 for testname in options.tests:
70 test = [t for t in allTests if pathCmp( t.target(), testname )]
71
72 if test :
73 tests.append( test[0] )
74 else :
75 print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr)
76
77 return tests
78
79# parses the option
80def getOptions():
81 # create a parser with the arguments for the tests script
82 parser = argparse.ArgumentParser(description='Script which runs cforall tests')
83 parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='yes')
84 parser.add_argument('--install', help='Run all tests based on installed binaries or tree binaries', type=yes_no, default='no')
85 parser.add_argument('--arch', help='Test for specific architecture', type=str, default='')
86 parser.add_argument('--timeout', help='Maximum duration in seconds after a single test is considered to have timed out', type=int, default=60)
87 parser.add_argument('--global-timeout', help='Maximum cumulative duration in seconds after the ALL tests are considered to have timed out', type=int, default=7200)
88 parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
89 parser.add_argument('--list', help='List all test available', action='store_true')
90 parser.add_argument('--all', help='Run all test available', action='store_true')
91 parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
92 parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int)
93 parser.add_argument('--list-comp', help='List all valide arguments', action='store_true')
94 parser.add_argument('-I','--include', help='Directory of test to include, can be used multiple time, All if omitted', action='append')
95 parser.add_argument('-E','--exclude', help='Directory of test to exclude, can be used multiple time, None if omitted', action='append')
96 parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
97
98 try:
99 options = parser.parse_args()
100 except:
101 print('ERROR: invalid arguments', file=sys.stderr)
102 parser.print_help(sys.stderr)
103 sys.exit(1)
104
105 # script must have at least some tests to run or be listing
106 listing = options.list or options.list_comp
107 all_tests = options.all
108 some_tests = len(options.tests) > 0
109 some_dirs = len(options.include) > 0 if options.include else 0
110
111 # check that exactly one of the booleans is set to true
112 if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 :
113 print('''ERROR: must have option '--all', '--list', '--include', '-I' or non-empty test list''', file=sys.stderr)
114 parser.print_help()
115 sys.exit(1)
116
117 return options
118
119################################################################################
120# running test functions
121################################################################################
122def success(val):
123 return val == 0 or settings.dry_run
124
125def isExe(file):
126 return settings.dry_run or fileIsExecutable(file)
127
128def noRule(file, target):
129 return not settings.dry_run and fileContainsOnly(file, "make: *** No rule to make target `%s'. Stop." % target)
130
131# logic to run a single test and return the result (No handling of printing or other test framework logic)
132def run_single_test(test):
133
134 # find the output file based on the test name and options flag
135 exe_file = test.target_executable();
136 out_file = test.target_output()
137 err_file = test.error_log()
138 cmp_file = test.expect()
139 in_file = test.input()
140
141 # prepare the proper directories
142 test.prepare()
143
144 # build, skipping to next test on error
145 with Timed() as comp_dur:
146 make_ret, _ = make( test.target(), redirects = ("2> %s 1> /dev/null" % out_file), error_file = err_file )
147
148 # if the make command succeds continue otherwise skip to diff
149 run_dur = None
150 if success(make_ret):
151 with Timed() as run_dur:
152 if isExe(exe_file):
153 # run test
154 retcode = run(exe_file, out_file, in_file)
155 else :
156 # simply cat the result into the output
157 retcode = cat(exe_file, out_file)
158 else:
159 retcode = mv(err_file, out_file)
160
161 if success(retcode):
162 if settings.generating :
163 # if we are ounly generating the output we still need to check that the test actually exists
164 if noRule(out_file, test.target()) :
165 retcode = 1
166 error = "\t\tNo make target for test %s!" % test.target()
167 rm(out_file)
168 else:
169 error = None
170 else :
171 # fetch return code and error from the diff command
172 retcode, error = diff(cmp_file, out_file)
173
174 else:
175 with open (out_file, "r") as myfile:
176 error = myfile.read()
177
178 ret, info = coreInfo(exe_file)
179 error = error + info
180
181
182
183 # clean the executable
184 rm(exe_file)
185
186 return retcode, error, [comp_dur.duration, run_dur.duration if run_dur else None]
187
188# run a single test and handle the errors, outputs, printing, exception handling, etc.
189def run_test_worker(t) :
190 with SignalHandling():
191 # print formated name
192 name_txt = '{0:{width}} '.format(t.target(), width=settings.width)
193
194 retcode, error, duration = run_single_test(t)
195
196 # update output based on current action
197 result_txt = TestResult.toString( retcode, duration )
198
199 #print result with error if needed
200 text = name_txt + result_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 return retcode != TestResult.SUCCESS
211
212# run the given list of tests with the given parameters
213def run_tests(tests, jobs) :
214 # clean the sandbox from previous commands
215 make('clean', redirects = '> /dev/null 2>&1')
216
217 # create the executor for our jobs and handle the signal properly
218 pool = setupPool(jobs)
219
220 # for each test to run
221 try :
222 results = pool.map_async(
223 run_test_worker,
224 tests,
225 chunksize = 1
226 ).get(settings.timeout.total)
227 except KeyboardInterrupt:
228 pool.terminate()
229 print("Tests interrupted by user")
230 sys.exit(1)
231
232 # clean the workspace
233 make('clean', redirects = '> /dev/null 2>&1')
234
235 for failed in results:
236 if failed :
237 return 1
238
239 return 0
240
241
242################################################################################
243# main loop
244################################################################################
245if __name__ == "__main__":
246
247 # parse the command line arguments
248 options = getOptions()
249
250 # init global settings
251 settings.init( options )
252
253 # fetch the liest of all valid tests
254 allTests = listTests( options.include, options.exclude )
255
256
257 # if user wants all tests than no other treatement of the test list is required
258 if options.all or options.list or options.list_comp or options.include :
259 tests = allTests
260
261 #otherwise we need to validate that the test list that was entered is valid
262 else :
263 tests = validTests( options )
264
265 # make sure we have at least some test to run
266 if not tests :
267 print('ERROR: No valid test to run', file=sys.stderr)
268 sys.exit(1)
269
270
271 # sort the test alphabetically for convenience
272 tests.sort(key=lambda t: (t.arch if t.arch else '') + t.target())
273
274 # users may want to simply list the tests
275 if options.list_comp :
276 print("-h --help --debug --dry-run --list --arch --all --regenerate-expected --install --timeout --global-timeout -j --jobs ", end='')
277 print(" ".join(map(lambda t: "%s" % (t.target()), tests)))
278
279 elif options.list :
280 print("Listing for %s:%s"% (settings.arch.string, settings.debug.string))
281 fancy_print("\n".join(map(lambda t: t.toString(), tests)))
282
283 else :
284 # check the build configuration works
285 settings.prep_output(tests)
286 settings.validate()
287
288 options.jobs, forceJobs = jobCount( options, tests )
289 settings.updateMakeCmd(forceJobs, options.jobs)
290
291 print('%s (%s:%s) on %i cores' % (
292 'Regenerate tests' if settings.generating else 'Running',
293 settings.arch.string,
294 settings.debug.string,
295 options.jobs
296 ))
297
298 # otherwise run all tests and make sure to return the correct error code
299 sys.exit( run_tests(tests, options.jobs) )
Note: See TracBrowser for help on using the repository browser.