source: tests/test.py @ 73e30dcf

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 73e30dcf was 73e30dcf, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Forgot new argument in list_comp

  • Property mode set to 100755
File size: 11.5 KB
RevLine 
[5b993e0]1#!/usr/bin/python3
[efc15918]2
[c07d724]3from pybin.tools import *
[0ad0c55]4from pybin.test_run import *
[bacc36c]5from pybin import settings
[efc15918]6
7import argparse
[122cac7]8import re
[efc15918]9import sys
[f806b61]10import tempfile
[ca54499]11import time
[efc15918]12
[2cd949b]13import os
14import psutil
15import signal
16
[efc15918]17################################################################################
18#               help functions
19################################################################################
[f1231f2]20
[5bf1f3e]21def find_tests():
[0ad0c55]22        expected = []
[f1231f2]23
[5bf1f3e]24        def match_test(path):
[6044200]25                match = re.search("^%s\/([\w\/\-_]*).expect\/([\w\-_]+)(\.[\w\-_]+)?\.txt$" % settings.SRCDIR, path)
[bacc36c]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
[f3b9efc]31                        if settings.arch.match(test.arch):
32                                expected.append(test)
[f803a75]33
[5bf1f3e]34        path_walk( match_test )
[c07d724]35
[0ad0c55]36        return expected
[efc15918]37
[be65cca]38# reads the directory ./.expect and indentifies the tests
[5bf1f3e]39def list_tests( includes, excludes ):
[be65cca]40        # tests directly in the .expect folder will always be processed
[5bf1f3e]41        test_list = find_tests()
[be65cca]42
[0ad0c55]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
[a85e44c]46                        x.target().startswith( tuple(includes) )
[0ad0c55]47                ]
[be65cca]48
[0ad0c55]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
[a85e44c]52                        x.target().startswith( tuple(excludes) )
[0ad0c55]53                ]
[f1231f2]54
[0ad0c55]55        return test_list
[efc15918]56
[c07d724]57# from the found tests, filter all the valid tests/desired tests
[5bf1f3e]58def valid_tests( options ):
[c07d724]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 :
[5bf1f3e]65                        testname = canonical_path( testname )
[bacc36c]66                        if Test.valid_name(testname):
[5bf1f3e]67                                found = [test for test in all_tests if canonical_path( test.target() ) == testname]
[bacc36c]68                                tests.append( found[0] if len(found) == 1 else Test.from_target(testname) )
[c07d724]69                        else :
[bacc36c]70                                print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)
[c07d724]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:
[5bf1f3e]75                        test = [t for t in all_tests if path_cmp( t.target(), testname )]
[c07d724]76
[bacc36c]77                        if test :
[c07d724]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
[5bf1f3e]85def parse_args():
[c07d724]86        # create a parser with the arguments for the tests script
87        parser = argparse.ArgumentParser(description='Script which runs cforall tests')
[28582b2]88        parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='yes')
[a5121bf]89        parser.add_argument('--install', help='Run all tests based on installed binaries or tree binaries', type=yes_no, default='no')
[bacc36c]90        parser.add_argument('--arch', help='Test for specific architecture', type=str, default='')
[afe8882]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)
[d658183]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")
[c07d724]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')
[dcfedca]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='')
[d142ec5]99        parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int)
[c07d724]100        parser.add_argument('--list-comp', help='List all valide arguments', action='store_true')
[0ad0c55]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')
[c07d724]103        parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
104
[575a6e5]105        try:
106                options =  parser.parse_args()
107        except:
108                print('ERROR: invalid arguments', file=sys.stderr)
109                parser.print_help(sys.stderr)
[5b993e0]110                sys.exit(1)
[c07d724]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
[0ad0c55]116        some_dirs  = len(options.include) > 0 if options.include else 0
[c07d724]117
118        # check that exactly one of the booleans is set to true
[0ad0c55]119        if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 :
[5b993e0]120                print('''ERROR: must have option '--all', '--list', '--include', '-I' or non-empty test list''', file=sys.stderr)
[c07d724]121                parser.print_help()
122                sys.exit(1)
123
124        return options
125
[efc15918]126################################################################################
127#               running test functions
128################################################################################
[0c13238]129def success(val):
130        return val == 0 or settings.dry_run
[f85bc15]131
[5bf1f3e]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)
[f85bc15]134
[c07d724]135# logic to run a single test and return the result (No handling of printing or other test framework logic)
[209383b]136def run_single_test(test):
[3c1d702]137
[c07d724]138        # find the output file based on the test name and options flag
[f85bc15]139        exe_file = test.target_executable();
[bacc36c]140        out_file = test.target_output()
141        err_file = test.error_log()
142        cmp_file = test.expect()
143        in_file  = test.input()
[0ad0c55]144
145        # prepare the proper directories
[bacc36c]146        test.prepare()
[efc15918]147
[c07d724]148        # build, skipping to next test on error
[0c13238]149        with Timed() as comp_dur:
[d65f92c]150                make_ret, _ = make( test.target(), output_file=subprocess.DEVNULL, error=out_file, error_file = err_file )
[efc15918]151
[0c13238]152        run_dur = None
[f806b61]153        # run everything in a temp directory to make sure core file are handled properly
154        with tempdir():
[103c292]155                # if the make command succeeds continue otherwise skip to diff
[f806b61]156                if success(make_ret):
157                        with Timed() as run_dur:
158                                if settings.dry_run or is_exe(exe_file):
159                                        # run test
[d65f92c]160                                        retcode, _ = sh(exe_file, output_file=out_file, input_file=in_file, timeout=True)
[f806b61]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
[0c13238]176                        else :
[f806b61]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
[0c13238]186
[dcfedca]187                        if settings.archive:
188                                error = error + '\n' + core_archive(settings.archive, test.target(), exe_file)
189
[0c13238]190
[b5f9829]191
[c07d724]192        # clean the executable
[0c13238]193        rm(exe_file)
[efc15918]194
[d658183]195        print("HERE")
196
[0c13238]197        return retcode, error, [comp_dur.duration, run_dur.duration if run_dur else None]
[efc15918]198
[c07d724]199# run a single test and handle the errors, outputs, printing, exception handling, etc.
[209383b]200def run_test_worker(t) :
[1bb2488]201        try :
[bacc36c]202                # print formated name
[5bf1f3e]203                name_txt = '{0:{width}}  '.format(t.target(), width=settings.output_width)
[ced2e989]204
[ca54499]205                retcode, error, duration = run_single_test(t)
[0a1a680]206
[bacc36c]207                # update output based on current action
[ca54499]208                result_txt = TestResult.toString( retcode, duration )
[bacc36c]209
210                #print result with error if needed
[a45fc7b]211                text = '\t' + name_txt + result_txt
[bacc36c]212                out = sys.stdout
213                if error :
[2b10f95]214                        text = text + '\n' + error
[bacc36c]215
[e791851]216                return retcode == TestResult.SUCCESS, text
[1bb2488]217        except KeyboardInterrupt:
[35a408b7]218                return False, ""
[8364209]219        except Exception as ex:
220                print("Unexpected error in worker thread: %s" % ex, file=sys.stderr)
[35a408b7]221                sys.stderr.flush()
222                return False, ""
223
[ced2e989]224
[911348cd]225# run the given list of tests with the given parameters
[209383b]226def run_tests(tests, jobs) :
[911348cd]227        # clean the sandbox from previous commands
[d65f92c]228        make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
[efc15918]229
[2cd949b]230        # since python prints stacks by default on a interrupt, redo the interrupt handling to be silent
231        def worker_init():
232                def sig_int(signal_num, frame):
233                        pass
234
235                signal.signal(signal.SIGINT, sig_int)
236
[c07d724]237        # create the executor for our jobs and handle the signal properly
[2cd949b]238        pool = multiprocessing.Pool(jobs, worker_init)
[c07d724]239
[e791851]240        failed = False
241
[2cd949b]242        def stop(x, y):
243                print("Tests interrupted by user", file=sys.stderr)
244                sys.exit(1)
245        signal.signal(signal.SIGINT, stop)
246
[c07d724]247        # for each test to run
[ced2e989]248        try :
[e791851]249                num = len(tests)
250                fancy = sys.stdout.isatty()
[35a408b7]251                results = pool.imap_unordered(
[209383b]252                        run_test_worker,
[bacc36c]253                        tests,
254                        chunksize = 1
[35a408b7]255                )
256
257                for i, (succ, txt) in enumerate(timed(results, timeout = settings.timeout.total), 1) :
[e791851]258                        if not succ :
259                                failed = True
260
261                        print("       " + txt)
262
263                        if(fancy and i != num):
264                                print("%d/%d" % (i, num), end='\r')
265                                sys.stdout.flush()
266
[ced2e989]267        except KeyboardInterrupt:
[e791851]268                print("Tests interrupted by user", file=sys.stderr)
[35a408b7]269                pool.terminate()
270                pool.join()
[e791851]271                failed = True
272        except multiprocessing.TimeoutError:
273                print("ERROR: Test suite timed out", file=sys.stderr)
[35a408b7]274                pool.terminate()
275                pool.join()
[e791851]276                failed = True
[35a408b7]277                killgroup() # needed to cleanly kill all children
278
[efc15918]279
[c07d724]280        # clean the workspace
[d65f92c]281        make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
[efc15918]282
[e791851]283        return 1 if failed else 0
[efc15918]284
[6a1bdfd]285
[efc15918]286################################################################################
287#               main loop
288################################################################################
[c07d724]289if __name__ == "__main__":
[f803a75]290
[c07d724]291        # parse the command line arguments
[5bf1f3e]292        options = parse_args()
[f1231f2]293
[bacc36c]294        # init global settings
295        settings.init( options )
296
[c07d724]297        # fetch the liest of all valid tests
[5bf1f3e]298        all_tests = list_tests( options.include, options.exclude )
[f1231f2]299
[0c13238]300
[c07d724]301        # if user wants all tests than no other treatement of the test list is required
[0ad0c55]302        if options.all or options.list or options.list_comp or options.include :
[5bf1f3e]303                tests = all_tests
[0534c3c]304
[f3b9efc]305        #otherwise we need to validate that the test list that was entered is valid
[c07d724]306        else :
[5bf1f3e]307                tests = valid_tests( options )
[0534c3c]308
[dd226e3]309        # make sure we have at least some test to run
310        if not tests :
311                print('ERROR: No valid test to run', file=sys.stderr)
312                sys.exit(1)
313
314
[c07d724]315        # sort the test alphabetically for convenience
[f3b9efc]316        tests.sort(key=lambda t: (t.arch if t.arch else '') + t.target())
[f1231f2]317
[c07d724]318        # users may want to simply list the tests
319        if options.list_comp :
[73e30dcf]320                print("-h --help --debug --dry-run --list --arch --all --regenerate-expected --archive-errors --install --timeout --global-timeout --timeout-with-gdb -j --jobs ", end='')
[0ad0c55]321                print(" ".join(map(lambda t: "%s" % (t.target()), tests)))
[911348cd]322
[c07d724]323        elif options.list :
[f3b9efc]324                print("Listing for %s:%s"% (settings.arch.string, settings.debug.string))
[5b993e0]325                fancy_print("\n".join(map(lambda t: t.toString(), tests)))
[911348cd]326
[b98c913]327        else :
[28582b2]328                # check the build configuration works
[d3c1c6a]329                settings.prep_output(tests)
[28582b2]330                settings.validate()
331
[5bf1f3e]332                options.jobs, forceJobs = job_count( options, tests )
333                settings.update_make_cmd(forceJobs, options.jobs)
[b98c913]334
[2b10f95]335                print('%s %i tests on %i cores (%s:%s)' % (
336                        'Regenerating' if settings.generating else 'Running',
337                        len(tests),
338                        options.jobs,
[f3b9efc]339                        settings.arch.string,
[2b10f95]340                        settings.debug.string
[bacc36c]341                ))
[efc15918]342
[c07d724]343                # otherwise run all tests and make sure to return the correct error code
[209383b]344                sys.exit( run_tests(tests, options.jobs) )
Note: See TracBrowser for help on using the repository browser.