source: tests/test.py @ 92a9768

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 92a9768 was 2cd949b, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Tentative fix of tests printing several pages of output when interrupted by keyboard

  • Property mode set to 100755
File size: 11.3 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('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
94        parser.add_argument('--list', help='List all test available', action='store_true')
95        parser.add_argument('--all', help='Run all test available', action='store_true')
96        parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
97        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='')
98        parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int)
99        parser.add_argument('--list-comp', help='List all valide arguments', action='store_true')
100        parser.add_argument('-I','--include', help='Directory of test to include, can be used multiple time, All  if omitted', action='append')
101        parser.add_argument('-E','--exclude', help='Directory of test to exclude, can be used multiple time, None if omitted', action='append')
102        parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
103
104        try:
105                options =  parser.parse_args()
106        except:
107                print('ERROR: invalid arguments', file=sys.stderr)
108                parser.print_help(sys.stderr)
109                sys.exit(1)
110
111        # script must have at least some tests to run or be listing
112        listing    = options.list or options.list_comp
113        all_tests  = options.all
114        some_tests = len(options.tests) > 0
115        some_dirs  = len(options.include) > 0 if options.include else 0
116
117        # check that exactly one of the booleans is set to true
118        if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 :
119                print('''ERROR: must have option '--all', '--list', '--include', '-I' or non-empty test list''', file=sys.stderr)
120                parser.print_help()
121                sys.exit(1)
122
123        return options
124
125################################################################################
126#               running test functions
127################################################################################
128def success(val):
129        return val == 0 or settings.dry_run
130
131def no_rule(file, target):
132        return not settings.dry_run and file_contains_only(file, "make: *** No rule to make target `%s'.  Stop." % target)
133
134# logic to run a single test and return the result (No handling of printing or other test framework logic)
135def run_single_test(test):
136
137        # find the output file based on the test name and options flag
138        exe_file = test.target_executable();
139        out_file = test.target_output()
140        err_file = test.error_log()
141        cmp_file = test.expect()
142        in_file  = test.input()
143
144        # prepare the proper directories
145        test.prepare()
146
147        # build, skipping to next test on error
148        with Timed() as comp_dur:
149                make_ret, _ = make( test.target(), output_file=subprocess.DEVNULL, error=out_file, error_file = err_file )
150
151        run_dur = None
152        # run everything in a temp directory to make sure core file are handled properly
153        with tempdir():
154                # if the make command succeds continue otherwise skip to diff
155                if success(make_ret):
156                        with Timed() as run_dur:
157                                if settings.dry_run or is_exe(exe_file):
158                                        # run test
159                                        retcode, _ = sh(exe_file, output_file=out_file, input_file=in_file, timeout=True)
160                                else :
161                                        # simply cat the result into the output
162                                        retcode = cat(exe_file, out_file)
163                else:
164                        retcode = mv(err_file, out_file)
165
166                if success(retcode):
167                        if settings.generating :
168                                # if we are ounly generating the output we still need to check that the test actually exists
169                                if no_rule(out_file, test.target()) :
170                                        retcode = 1
171                                        error = "\t\tNo make target for test %s!" % test.target()
172                                        rm(out_file)
173                                else:
174                                        error = None
175                        else :
176                                # fetch return code and error from the diff command
177                                retcode, error = diff(cmp_file, out_file)
178
179                else:
180                        with open (out_file, "r") as myfile:
181                                error = myfile.read()
182
183                        ret, info = core_info(exe_file)
184                        error = error + info if error else info
185
186                        if settings.archive:
187                                error = error + '\n' + core_archive(settings.archive, test.target(), exe_file)
188
189
190
191        # clean the executable
192        rm(exe_file)
193
194        return retcode, error, [comp_dur.duration, run_dur.duration if run_dur else None]
195
196# run a single test and handle the errors, outputs, printing, exception handling, etc.
197def run_test_worker(t) :
198        try :
199                # print formated name
200                name_txt = '{0:{width}}  '.format(t.target(), width=settings.output_width)
201
202                retcode, error, duration = run_single_test(t)
203
204                # update output based on current action
205                result_txt = TestResult.toString( retcode, duration )
206
207                #print result with error if needed
208                text = '\t' + name_txt + result_txt
209                out = sys.stdout
210                if error :
211                        text = text + '\n' + error
212
213                return retcode == TestResult.SUCCESS, text
214        except KeyboardInterrupt:
215                return False, ""
216        except Exception as ex:
217                print("Unexpected error in worker thread: %s" % ex, file=sys.stderr)
218                sys.stderr.flush()
219                return False, ""
220
221
222# run the given list of tests with the given parameters
223def run_tests(tests, jobs) :
224        # clean the sandbox from previous commands
225        make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
226
227        # since python prints stacks by default on a interrupt, redo the interrupt handling to be silent
228        def worker_init():
229                def sig_int(signal_num, frame):
230                        pass
231
232                signal.signal(signal.SIGINT, sig_int)
233
234        # create the executor for our jobs and handle the signal properly
235        pool = multiprocessing.Pool(jobs, worker_init)
236
237        failed = False
238
239        def stop(x, y):
240                print("Tests interrupted by user", file=sys.stderr)
241                sys.exit(1)
242        signal.signal(signal.SIGINT, stop)
243
244        # for each test to run
245        try :
246                num = len(tests)
247                fancy = sys.stdout.isatty()
248                results = pool.imap_unordered(
249                        run_test_worker,
250                        tests,
251                        chunksize = 1
252                )
253
254                for i, (succ, txt) in enumerate(timed(results, timeout = settings.timeout.total), 1) :
255                        if not succ :
256                                failed = True
257
258                        print("       " + txt)
259
260                        if(fancy and i != num):
261                                print("%d/%d" % (i, num), end='\r')
262                                sys.stdout.flush()
263
264        except KeyboardInterrupt:
265                print("Tests interrupted by user", file=sys.stderr)
266                pool.terminate()
267                pool.join()
268                failed = True
269        except multiprocessing.TimeoutError:
270                print("ERROR: Test suite timed out", file=sys.stderr)
271                pool.terminate()
272                pool.join()
273                failed = True
274                killgroup() # needed to cleanly kill all children
275
276
277        # clean the workspace
278        make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
279
280        return 1 if failed else 0
281
282
283################################################################################
284#               main loop
285################################################################################
286if __name__ == "__main__":
287
288        # parse the command line arguments
289        options = parse_args()
290
291        # init global settings
292        settings.init( options )
293
294        # fetch the liest of all valid tests
295        all_tests = list_tests( options.include, options.exclude )
296
297
298        # if user wants all tests than no other treatement of the test list is required
299        if options.all or options.list or options.list_comp or options.include :
300                tests = all_tests
301
302        #otherwise we need to validate that the test list that was entered is valid
303        else :
304                tests = valid_tests( options )
305
306        # make sure we have at least some test to run
307        if not tests :
308                print('ERROR: No valid test to run', file=sys.stderr)
309                sys.exit(1)
310
311
312        # sort the test alphabetically for convenience
313        tests.sort(key=lambda t: (t.arch if t.arch else '') + t.target())
314
315        # users may want to simply list the tests
316        if options.list_comp :
317                print("-h --help --debug --dry-run --list --arch --all --regenerate-expected --archive-errors --install --timeout --global-timeout -j --jobs ", end='')
318                print(" ".join(map(lambda t: "%s" % (t.target()), tests)))
319
320        elif options.list :
321                print("Listing for %s:%s"% (settings.arch.string, settings.debug.string))
322                fancy_print("\n".join(map(lambda t: t.toString(), tests)))
323
324        else :
325                # check the build configuration works
326                settings.prep_output(tests)
327                settings.validate()
328
329                options.jobs, forceJobs = job_count( options, tests )
330                settings.update_make_cmd(forceJobs, options.jobs)
331
332                print('%s %i tests on %i cores (%s:%s)' % (
333                        'Regenerating' if settings.generating else 'Running',
334                        len(tests),
335                        options.jobs,
336                        settings.arch.string,
337                        settings.debug.string
338                ))
339
340                # otherwise run all tests and make sure to return the correct error code
341                sys.exit( run_tests(tests, options.jobs) )
Note: See TracBrowser for help on using the repository browser.