source: tests/test.py@ 9cb89b87

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 9cb89b87 was 8ef95679, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Forgot to remove print

  • Property mode set to 100755
File size: 11.5 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 tempfile
11import time
12
13import os
14import psutil
15import signal
16
17################################################################################
18# help functions
19################################################################################
20
21def find_tests():
22 expected = []
23
24 def match_test(path):
25 match = re.search("^%s\/([\w\/\-_]*).expect\/([\w\-_]+)(\.[\w\-_]+)?\.txt$" % settings.SRCDIR, path)
26 if match :
27 test = Test()
28 test.name = match.group(2)
29 test.path = match.group(1)
30 test.arch = match.group(3)[1:] if match.group(3) else None
31 if settings.arch.match(test.arch):
32 expected.append(test)
33
34 path_walk( match_test )
35
36 return expected
37
38# reads the directory ./.expect and indentifies the tests
39def list_tests( includes, excludes ):
40 # tests directly in the .expect folder will always be processed
41 test_list = find_tests()
42
43 # if we have a limited number of includes, filter by them
44 if includes:
45 test_list = [x for x in test_list if
46 x.target().startswith( tuple(includes) )
47 ]
48
49 # # if we have a folders to excludes, filter by them
50 if excludes:
51 test_list = [x for x in test_list if not
52 x.target().startswith( tuple(excludes) )
53 ]
54
55 return test_list
56
57# from the found tests, filter all the valid tests/desired tests
58def valid_tests( options ):
59 tests = []
60
61 # if we are regenerating the tests we need to find the information of the
62 # already existing tests and create new info for the new tests
63 if options.regenerate_expected :
64 for testname in options.tests :
65 testname = canonical_path( testname )
66 if Test.valid_name(testname):
67 found = [test for test in all_tests if canonical_path( test.target() ) == testname]
68 tests.append( found[0] if len(found) == 1 else Test.from_target(testname) )
69 else :
70 print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)
71
72 else :
73 # otherwise we only need to validate that all tests are present in the complete list
74 for testname in options.tests:
75 test = [t for t in all_tests if path_cmp( t.target(), testname )]
76
77 if test :
78 tests.append( test[0] )
79 else :
80 print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr)
81
82 return tests
83
84# parses the option
85def parse_args():
86 # create a parser with the arguments for the tests script
87 parser = argparse.ArgumentParser(description='Script which runs cforall tests')
88 parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='yes')
89 parser.add_argument('--install', help='Run all tests based on installed binaries or tree binaries', type=yes_no, default='no')
90 parser.add_argument('--arch', help='Test for specific architecture', type=str, default='')
91 parser.add_argument('--timeout', help='Maximum duration in seconds after a single test is considered to have timed out', type=int, default=60)
92 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)
93 parser.add_argument('--timeout-with-gdb', help='Instead of killing the command when it times out, orphan it and print process id to allow gdb to attach', type=yes_no, default="no")
94 parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
95 parser.add_argument('--list', help='List all test available', action='store_true')
96 parser.add_argument('--all', help='Run all test available', action='store_true')
97 parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
98 parser.add_argument('--archive-errors', help='If called with a valid path, on test crashes the test script will copy the core dump and the executable to the specified path.', type=str, default='')
99 parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int)
100 parser.add_argument('--list-comp', help='List all valide arguments', action='store_true')
101 parser.add_argument('-I','--include', help='Directory of test to include, can be used multiple time, All if omitted', action='append')
102 parser.add_argument('-E','--exclude', help='Directory of test to exclude, can be used multiple time, None if omitted', action='append')
103 parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
104
105 try:
106 options = parser.parse_args()
107 except:
108 print('ERROR: invalid arguments', file=sys.stderr)
109 parser.print_help(sys.stderr)
110 sys.exit(1)
111
112 # script must have at least some tests to run or be listing
113 listing = options.list or options.list_comp
114 all_tests = options.all
115 some_tests = len(options.tests) > 0
116 some_dirs = len(options.include) > 0 if options.include else 0
117
118 # check that exactly one of the booleans is set to true
119 if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 :
120 print('''ERROR: must have option '--all', '--list', '--include', '-I' or non-empty test list''', file=sys.stderr)
121 parser.print_help()
122 sys.exit(1)
123
124 return options
125
126################################################################################
127# running test functions
128################################################################################
129def success(val):
130 return val == 0 or settings.dry_run
131
132def no_rule(file, target):
133 return not settings.dry_run and file_contains_only(file, "make: *** No rule to make target `%s'. Stop." % target)
134
135# logic to run a single test and return the result (No handling of printing or other test framework logic)
136def run_single_test(test):
137
138 # find the output file based on the test name and options flag
139 exe_file = test.target_executable();
140 out_file = test.target_output()
141 err_file = test.error_log()
142 cmp_file = test.expect()
143 in_file = test.input()
144
145 # prepare the proper directories
146 test.prepare()
147
148 # build, skipping to next test on error
149 with Timed() as comp_dur:
150 make_ret, _ = make( test.target(), output_file=subprocess.DEVNULL, error=out_file, error_file = err_file )
151
152 run_dur = None
153 # run everything in a temp directory to make sure core file are handled properly
154 with tempdir():
155 # if the make command succeeds continue otherwise skip to diff
156 if success(make_ret):
157 with Timed() as run_dur:
158 if settings.dry_run or is_exe(exe_file):
159 # run test
160 retcode, _ = sh(exe_file, output_file=out_file, input_file=in_file, timeout=True)
161 else :
162 # simply cat the result into the output
163 retcode = cat(exe_file, out_file)
164 else:
165 retcode = mv(err_file, out_file)
166
167 if success(retcode):
168 if settings.generating :
169 # if we are ounly generating the output we still need to check that the test actually exists
170 if no_rule(out_file, test.target()) :
171 retcode = 1
172 error = "\t\tNo make target for test %s!" % test.target()
173 rm(out_file)
174 else:
175 error = None
176 else :
177 # fetch return code and error from the diff command
178 retcode, error = diff(cmp_file, out_file)
179
180 else:
181 with open (out_file, "r") as myfile:
182 error = myfile.read()
183
184 ret, info = core_info(exe_file)
185 error = error + info if error else info
186
187 if settings.archive:
188 error = error + '\n' + core_archive(settings.archive, test.target(), exe_file)
189
190
191
192 # clean the executable
193 rm(exe_file)
194
195 return retcode, error, [comp_dur.duration, run_dur.duration if run_dur else None]
196
197# run a single test and handle the errors, outputs, printing, exception handling, etc.
198def run_test_worker(t) :
199 try :
200 # print formated name
201 name_txt = '{0:{width}} '.format(t.target(), width=settings.output_width)
202
203 retcode, error, duration = run_single_test(t)
204
205 # update output based on current action
206 result_txt = TestResult.toString( retcode, duration )
207
208 #print result with error if needed
209 text = '\t' + name_txt + result_txt
210 out = sys.stdout
211 if error :
212 text = text + '\n' + error
213
214 return retcode == TestResult.SUCCESS, text
215 except KeyboardInterrupt:
216 return False, ""
217 except Exception as ex:
218 print("Unexpected error in worker thread: %s" % ex, file=sys.stderr)
219 sys.stderr.flush()
220 return False, ""
221
222
223# run the given list of tests with the given parameters
224def run_tests(tests, jobs) :
225 # clean the sandbox from previous commands
226 make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
227
228 # since python prints stacks by default on a interrupt, redo the interrupt handling to be silent
229 def worker_init():
230 def sig_int(signal_num, frame):
231 pass
232
233 signal.signal(signal.SIGINT, sig_int)
234
235 # create the executor for our jobs and handle the signal properly
236 pool = multiprocessing.Pool(jobs, worker_init)
237
238 failed = False
239
240 def stop(x, y):
241 print("Tests interrupted by user", file=sys.stderr)
242 sys.exit(1)
243 signal.signal(signal.SIGINT, stop)
244
245 # for each test to run
246 try :
247 num = len(tests)
248 fancy = sys.stdout.isatty()
249 results = pool.imap_unordered(
250 run_test_worker,
251 tests,
252 chunksize = 1
253 )
254
255 for i, (succ, txt) in enumerate(timed(results, timeout = settings.timeout.total), 1) :
256 if not succ :
257 failed = True
258
259 print(" " + txt)
260
261 if(fancy and i != num):
262 print("%d/%d" % (i, num), end='\r')
263 sys.stdout.flush()
264
265 except KeyboardInterrupt:
266 print("Tests interrupted by user", file=sys.stderr)
267 pool.terminate()
268 pool.join()
269 failed = True
270 except multiprocessing.TimeoutError:
271 print("ERROR: Test suite timed out", file=sys.stderr)
272 pool.terminate()
273 pool.join()
274 failed = True
275 killgroup() # needed to cleanly kill all children
276
277
278 # clean the workspace
279 make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
280
281 return 1 if failed else 0
282
283
284################################################################################
285# main loop
286################################################################################
287if __name__ == "__main__":
288
289 # parse the command line arguments
290 options = parse_args()
291
292 # init global settings
293 settings.init( options )
294
295 # fetch the liest of all valid tests
296 all_tests = list_tests( options.include, options.exclude )
297
298
299 # if user wants all tests than no other treatement of the test list is required
300 if options.all or options.list or options.list_comp or options.include :
301 tests = all_tests
302
303 #otherwise we need to validate that the test list that was entered is valid
304 else :
305 tests = valid_tests( options )
306
307 # make sure we have at least some test to run
308 if not tests :
309 print('ERROR: No valid test to run', file=sys.stderr)
310 sys.exit(1)
311
312
313 # sort the test alphabetically for convenience
314 tests.sort(key=lambda t: (t.arch if t.arch else '') + t.target())
315
316 # users may want to simply list the tests
317 if options.list_comp :
318 print("-h --help --debug --dry-run --list --arch --all --regenerate-expected --archive-errors --install --timeout --global-timeout --timeout-with-gdb -j --jobs ", end='')
319 print(" ".join(map(lambda t: "%s" % (t.target()), tests)))
320
321 elif options.list :
322 print("Listing for %s:%s"% (settings.arch.string, settings.debug.string))
323 fancy_print("\n".join(map(lambda t: t.toString(), tests)))
324
325 else :
326 # check the build configuration works
327 settings.prep_output(tests)
328 settings.validate()
329
330 options.jobs, forceJobs = job_count( options, tests )
331 settings.update_make_cmd(forceJobs, options.jobs)
332
333 print('%s %i tests on %i cores (%s:%s)' % (
334 'Regenerating' if settings.generating else 'Running',
335 len(tests),
336 options.jobs,
337 settings.arch.string,
338 settings.debug.string
339 ))
340
341 # otherwise run all tests and make sure to return the correct error code
342 sys.exit( run_tests(tests, options.jobs) )
Note: See TracBrowser for help on using the repository browser.