source: tests/test.py @ ed96731

Last change on this file since ed96731 was b24cbaf, checked in by Michael Brooks <mlbrooks@…>, 2 months ago

Reduce test suite's reliance on makefile.am EXTRA_DIST entries for including .in files in distribution (required for nightly build success).

Second attempt to fix Promote build by including recently added test data files.

  • Property mode set to 100755
File size: 15.6 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
[136f86b]8import itertools
[122cac7]9import re
[efc15918]10import sys
[f806b61]11import tempfile
[ca54499]12import time
[efc15918]13
[2cd949b]14import os
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):
[195d1d8]25                match = re.search(r'^%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)
[0fc91db1]30                        test.arch = match.group(3)[1:] if match.group(3) else None
[a2f2fda]31
[136f86b]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
[136f86b]55        # sort the test alphabetically for convenience
56        test_list.sort(key=lambda t: ('~' if t.arch else '') + t.target() + (t.arch if t.arch else ''))
57
[0ad0c55]58        return test_list
[efc15918]59
[c07d724]60# from the found tests, filter all the valid tests/desired tests
[5bf1f3e]61def valid_tests( options ):
[c07d724]62        tests = []
63
64        # if we are regenerating the tests we need to find the information of the
65        # already existing tests and create new info for the new tests
66        if options.regenerate_expected :
67                for testname in options.tests :
[a2f2fda]68                        testname = os.path.normpath( os.path.join(settings.SRCDIR, testname) )
69
[41af19c]70                        # first check if this is a valid name to regenerate
[bacc36c]71                        if Test.valid_name(testname):
[41af19c]72                                # this is a valid name, let's check if it already exists
[5bf1f3e]73                                found = [test for test in all_tests if canonical_path( test.target() ) == testname]
[a51b8f6]74                                setup = settings.all_arch if options.arch else [None]
[41af19c]75                                if not found:
[0fc91db1]76                                        # it's a new name, create it according to the name and specified architecture
77                                        tests.extend( [Test.new_target(testname, arch) for arch in setup] )
[41af19c]78                                elif len(found) == 1 and not found[0].arch:
79                                        # we found a single test, the user better be wanting to create a cross platform test
80                                        if options.arch:
81                                                print('ERROR: "%s", test has no specified architecture but --arch was specified, ignoring it' % testname, file=sys.stderr)
82                                        else:
83                                                tests.append( found[0] )
84                                else:
85                                        # this test is already cross platform, just add a test for each platform the user asked
[0fc91db1]86                                        tests.extend( [Test.new_target(testname, arch) for arch in setup] )
[41af19c]87
88                                        # print a warning if it users didn't ask for a specific architecture
[ad4832f1]89                                        found_arch = [f.arch for f in found if f.arch]
90                                        if found_arch and not options.arch:
[41af19c]91                                                print('WARNING: "%s", test has architecture specific expected files but --arch was not specified, regenerating only for current host' % testname, file=sys.stderr)
92
[c07d724]93                        else :
[bacc36c]94                                print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)
[c07d724]95
96        else :
97                # otherwise we only need to validate that all tests are present in the complete list
98                for testname in options.tests:
[5bf1f3e]99                        test = [t for t in all_tests if path_cmp( t.target(), testname )]
[c07d724]100
[bacc36c]101                        if test :
[136f86b]102                                tests.extend( test )
[c07d724]103                        else :
104                                print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr)
105
106        return tests
107
108# parses the option
[5bf1f3e]109def parse_args():
[c07d724]110        # create a parser with the arguments for the tests script
111        parser = argparse.ArgumentParser(description='Script which runs cforall tests')
[99581ee]112        parser.add_argument('--arch', help='Test for specific architecture', type=comma_separated(str), default=None)
[136f86b]113        parser.add_argument('--debug', help='Run all tests in debug or release', type=comma_separated(yes_no), default='yes')
114        parser.add_argument('--install', help='Run all tests based on installed binaries or tree binaries', type=comma_separated(yes_no), default='no')
115        parser.add_argument('--continue', help='When multiple specifications are passed (debug/install/arch), sets whether or not to continue if the last specification failed', type=yes_no, default='yes', dest='continue_')
[950c58e]116        parser.add_argument('--no-invariant', help='Tell the compiler not to check invariants.', action='store_false', dest='invariant')
117        parser.add_argument('--invariant', help='Tell the compiler to check invariants.', action='store_const', const=True)
[15b5abac]118        parser.add_argument('--timeout', help='Maximum duration in seconds after a single test is considered to have timed out', type=int, default=240)
[afe8882]119        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]120        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]121        parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
122        parser.add_argument('--list', help='List all test available', action='store_true')
123        parser.add_argument('--all', help='Run all test available', action='store_true')
124        parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
[dcfedca]125        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='')
[ef56087]126        parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously, 0 (default) for unlimited', nargs='?', const=0, type=int)
[e85a72b8]127        parser.add_argument('--list-comp', help='List all valid arguments', action='store_true')
[a468e1e9]128        parser.add_argument('--list-dist', help='List all tests for distribution', action='store_true')
[0ad0c55]129        parser.add_argument('-I','--include', help='Directory of test to include, can be used multiple time, All  if omitted', action='append')
130        parser.add_argument('-E','--exclude', help='Directory of test to exclude, can be used multiple time, None if omitted', action='append')
[c07d724]131        parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
132
[575a6e5]133        try:
134                options =  parser.parse_args()
135        except:
136                print('ERROR: invalid arguments', file=sys.stderr)
137                parser.print_help(sys.stderr)
[5b993e0]138                sys.exit(1)
[c07d724]139
140        # script must have at least some tests to run or be listing
[a468e1e9]141        listing    = options.list or options.list_comp or options.list_dist
[c07d724]142        all_tests  = options.all
143        some_tests = len(options.tests) > 0
[0ad0c55]144        some_dirs  = len(options.include) > 0 if options.include else 0
[c07d724]145
146        # check that exactly one of the booleans is set to true
[0ad0c55]147        if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 :
[5b993e0]148                print('''ERROR: must have option '--all', '--list', '--include', '-I' or non-empty test list''', file=sys.stderr)
[c07d724]149                parser.print_help()
150                sys.exit(1)
151
152        return options
153
[efc15918]154################################################################################
155#               running test functions
156################################################################################
[0c13238]157def success(val):
158        return val == 0 or settings.dry_run
[f85bc15]159
[5bf1f3e]160def no_rule(file, target):
161        return not settings.dry_run and file_contains_only(file, "make: *** No rule to make target `%s'.  Stop." % target)
[f85bc15]162
[c07d724]163# logic to run a single test and return the result (No handling of printing or other test framework logic)
[209383b]164def run_single_test(test):
[3c1d702]165
[c07d724]166        # find the output file based on the test name and options flag
[f85bc15]167        exe_file = test.target_executable();
[bacc36c]168        out_file = test.target_output()
169        err_file = test.error_log()
170        cmp_file = test.expect()
171        in_file  = test.input()
[0ad0c55]172
173        # prepare the proper directories
[bacc36c]174        test.prepare()
[efc15918]175
[a5ea261]176        # extra flags for cfa to pass through make.
177        cfa_flags = 'CFAFLAGS=--invariant' if settings.invariant else None
178
[e6cfb4e2]179        # ----------
180        # MAKE
181        # ----------
[c07d724]182        # build, skipping to next test on error
[0c13238]183        with Timed() as comp_dur:
[a5ea261]184                make_ret, _, _ = make(test.target(), flags=cfa_flags, output_file=subprocess.DEVNULL, error=out_file, error_file=err_file)
[efc15918]185
[e6cfb4e2]186        # ----------
187        # RUN
188        # ----------
[f806b61]189        # run everything in a temp directory to make sure core file are handled properly
[e6cfb4e2]190        run_dur = None
[f806b61]191        with tempdir():
[103c292]192                # if the make command succeeds continue otherwise skip to diff
[f806b61]193                if success(make_ret):
194                        with Timed() as run_dur:
195                                if settings.dry_run or is_exe(exe_file):
196                                        # run test
[f58522b0]197                                        retcode, _, _ = sh(exe_file, output_file=out_file, input_file=in_file, timeout=True, nice=True)
[f806b61]198                                else :
199                                        # simply cat the result into the output
200                                        retcode = cat(exe_file, out_file)
201                else:
202                        retcode = mv(err_file, out_file)
203
204                if success(retcode):
205                        if settings.generating :
[eb67b47]206                                # if we are only generating the output we still need to check that the test actually exists
[f806b61]207                                if no_rule(out_file, test.target()) :
208                                        retcode = 1
209                                        error = "\t\tNo make target for test %s!" % test.target()
210                                        rm(out_file)
211                                else:
212                                        error = None
[0c13238]213                        else :
[f806b61]214                                # fetch return code and error from the diff command
[cc9b520]215                                retcode, error, _ = diff(cmp_file, out_file)
[f806b61]216
217                else:
[62cc231]218                        if os.stat(out_file).st_size < 1048576:
[09bbe78]219                                with open (out_file, "r", encoding='latin-1') as myfile:  # use latin-1 so all chars mean something.
[65583e2]220                                        error = myfile.read()
221                        else:
222                                error = "Output log can't be read, file is bigger than 1MB, see {} for actual error\n".format(out_file)
[f806b61]223
[b053083]224                        ret, info = core_info(exe_file)
225                        error = error + info if error else info
[0c13238]226
[dcfedca]227                        if settings.archive:
228                                error = error + '\n' + core_archive(settings.archive, test.target(), exe_file)
229
[0c13238]230
[b5f9829]231
[c07d724]232        # clean the executable
[0c13238]233        rm(exe_file)
[efc15918]234
[0c13238]235        return retcode, error, [comp_dur.duration, run_dur.duration if run_dur else None]
[efc15918]236
[c07d724]237# run a single test and handle the errors, outputs, printing, exception handling, etc.
[209383b]238def run_test_worker(t) :
[1bb2488]239        try :
[bacc36c]240                # print formated name
[767a8ef]241                name_txt = t.format_target(width=settings.output_width) + '  '
[ced2e989]242
[ca54499]243                retcode, error, duration = run_single_test(t)
[0a1a680]244
[bacc36c]245                # update output based on current action
[172a88d]246                result_key, result_txt = TestResult.toString( retcode, duration )
[bacc36c]247
248                #print result with error if needed
[a45fc7b]249                text = '\t' + name_txt + result_txt
[bacc36c]250                out = sys.stdout
251                if error :
[2b10f95]252                        text = text + '\n' + error
[bacc36c]253
[172a88d]254                return retcode == TestResult.SUCCESS, result_key, text
[1bb2488]255        except KeyboardInterrupt:
[172a88d]256                return False, 'keybrd', ""
[a2f2fda]257        # except Exception as ex:
258        #       print("Unexpected error in worker thread running {}: {}".format(t.target(), ex), file=sys.stderr)
259        #       sys.stderr.flush()
260        #       return False, ""
[35a408b7]261
[ced2e989]262
[911348cd]263# run the given list of tests with the given parameters
[209383b]264def run_tests(tests, jobs) :
[911348cd]265        # clean the sandbox from previous commands
[d65f92c]266        make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
[efc15918]267
[21c3ea1]268        # create the executor for our jobs
269        pool = multiprocessing.Pool(jobs)
[c07d724]270
[e791851]271        failed = False
[172a88d]272        rescnts = {     'pass': 0, 'fail': 0, 'time': 0, 'keybrd': 0 }
273        other = 0
[e791851]274
[c07d724]275        # for each test to run
[ced2e989]276        try :
[e791851]277                num = len(tests)
278                fancy = sys.stdout.isatty()
[35a408b7]279                results = pool.imap_unordered(
[209383b]280                        run_test_worker,
[bacc36c]281                        tests,
282                        chunksize = 1
[35a408b7]283                )
284
[172a88d]285                for i, (succ, code, txt) in enumerate(timed(results, timeout = settings.timeout.total), 1) :
286                        if code in rescnts.keys():
287                                rescnts[code] += 1
288                        else:
289                                other += 1
290
[e791851]291                        if not succ :
292                                failed = True
293
294                        print("       " + txt)
295
296                        if(fancy and i != num):
297                                print("%d/%d" % (i, num), end='\r')
298                                sys.stdout.flush()
299
[ced2e989]300        except KeyboardInterrupt:
[e791851]301                print("Tests interrupted by user", file=sys.stderr)
[35a408b7]302                pool.terminate()
303                pool.join()
[e791851]304                failed = True
305        except multiprocessing.TimeoutError:
306                print("ERROR: Test suite timed out", file=sys.stderr)
[35a408b7]307                pool.terminate()
308                pool.join()
[e791851]309                failed = True
[35a408b7]310                killgroup() # needed to cleanly kill all children
311
[efc15918]312
[c07d724]313        # clean the workspace
[d65f92c]314        make('clean', output_file=subprocess.DEVNULL, error=subprocess.DEVNULL)
[efc15918]315
[172a88d]316        print("{} passes, {} failures, {} timeouts, {} cancelled, {} other".format(rescnts['pass'], rescnts['fail'], rescnts['time'], rescnts['keybrd'], other))
317
[136f86b]318        return failed
[efc15918]319
[6a1bdfd]320
[efc15918]321################################################################################
322#               main loop
323################################################################################
[c07d724]324if __name__ == "__main__":
[f803a75]325
[c07d724]326        # parse the command line arguments
[5bf1f3e]327        options = parse_args()
[f1231f2]328
[bacc36c]329        # init global settings
330        settings.init( options )
331
[a468e1e9]332        # --------------------------------------------------
333        # list all the test for auto completion programs
334        # not pretty, single line, with the command line options
[c07d724]335        if options.list_comp :
[2980667]336                # fetch the liest of all valid tests
337                tests = list_tests( None, None )
338
339                # print the possible options
[e173d3c]340                print("-h --help --debug --dry-run --list --arch --all --regenerate-expected --archive-errors --install --timeout --global-timeout --timeout-with-gdb -j --jobs -I --include -E --exclude --continue ", end='')
[0ad0c55]341                print(" ".join(map(lambda t: "%s" % (t.target()), tests)))
[911348cd]342
[a468e1e9]343                # done
344                sys.exit(0)
345
346        # --------------------------------------------------
347        # list all the test for auto completion programs
348        if options.list_dist :
349                # fetch the liest of all valid tests
350                tests = list_tests( None, None )
351
352                for t in tests:
353                        print(os.path.relpath(t.expect(), settings.SRCDIR), end=' ')
[b24cbaf]354                        print(os.path.relpath(t.inputs_all() , settings.SRCDIR), end=' ')
[cc9b520]355                        code, out, err = make_recon(t.target())
[a468e1e9]356
357                        if code != 0:
[cc9b520]358                                print('ERROR: recond failed for test {}: {} \'{}\''.format(t.target(), code, err), file=sys.stderr)
[a468e1e9]359                                sys.exit(1)
360
[195d1d8]361                        print(' '.join(re.findall(r'([^\s]+\.cfa)', out)), end=' ')
[a468e1e9]362
363                # done
364                sys.exit(0)
365
366
367        # --------------------------------------------------
368        # list all the tests for users, in a pretty format
369        if options.list :
[2980667]370                # fetch the liest of all valid tests
371                tests = list_tests( options.include, options.exclude )
372
373                # print the available tests
[5b993e0]374                fancy_print("\n".join(map(lambda t: t.toString(), tests)))
[911348cd]375
[a468e1e9]376                # done
377                sys.exit(0)
378
379        # fetch the liest of all valid tests
380        all_tests = list_tests( options.include, options.exclude )
381
382        # if user wants all tests than no other treatement of the test list is required
383        if options.all or options.include :
384                tests = all_tests
385
386        #otherwise we need to validate that the test list that was entered is valid
[b98c913]387        else :
[a468e1e9]388                tests = valid_tests( options )
389
390        # make sure we have at least some test to run
391        if not tests :
392                print('ERROR: No valid test to run', file=sys.stderr)
393                sys.exit(1)
394
395        # prep invariants
396        settings.prep_output(tests)
397        failed = 0
398
399        # check if the expected files aren't empty
400        if not options.regenerate_expected:
401                for t in tests:
402                        if is_empty(t.expect()):
403                                print('WARNING: test "{}" has empty .expect file'.format(t.target()), file=sys.stderr)
404
[fc01219]405        options.jobs = job_count( options )
[9cd44ba]406
[a468e1e9]407        # for each build configurations, run the test
408        with Timed() as total_dur:
[0fc91db1]409                for arch, debug, install in itertools.product(settings.all_arch, settings.all_debug, settings.all_install):
[a468e1e9]410                        settings.arch    = arch
411                        settings.debug   = debug
412                        settings.install = install
413
414                        # filter out the tests for a different architecture
415                        # tests are the same across debug/install
[0fc91db1]416                        local_tests = settings.arch.filter( tests )
[a468e1e9]417
418                        # check the build configuration works
419                        settings.validate()
[9cd44ba]420                        jobs = min(options.jobs, len(local_tests))
[a468e1e9]421
422                        # print configuration
[0fc91db1]423                        print('%s %i tests on %i cores (%s - %s)' % (
[a468e1e9]424                                'Regenerating' if settings.generating else 'Running',
425                                len(local_tests),
[9cd44ba]426                                jobs,
[a468e1e9]427                                settings.arch.string,
428                                settings.debug.string
429                        ))
430                        if not local_tests :
431                                print('WARNING: No tests for this configuration')
432                                continue
433
434                        # otherwise run all tests and make sure to return the correct error code
[9cd44ba]435                        failed = run_tests(local_tests, jobs)
[a468e1e9]436                        if failed:
437                                if not settings.continue_:
438                                        break
439
440        print('Tests took %s' % fmtDur( total_dur.duration ))
441        sys.exit( failed )
Note: See TracBrowser for help on using the repository browser.