source: src/tests/test.py @ 4e9151f

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 4e9151f was 4e9151f, checked in by Thierry Delisle <tdelisle@…>, 7 years ago
  • Fixed tests to no longer use make errors, pipeing CC errors directly instead
  • Tests now use the number of cores as the number of jobs if jobserver is not defined
  • Tests now support both jobserver-fds and and jobserver-auth as the file descriptor variables
  • Tests now limit the number of concurrent jobs to the total number of tests
  • Tests now ignore whitespaces and blank lines when comparing diffs
  • Property mode set to 100755
File size: 11.7 KB
RevLine 
[945047e]1#!/usr/bin/python
[efc15918]2from __future__ import print_function
3
[ced2e989]4from functools import partial
5from multiprocessing import Pool
[122cac7]6from os import listdir, environ
[0534c3c]7from os.path import isfile, join, splitext
[efc15918]8from subprocess import Popen, PIPE, STDOUT
9
10import argparse
[122cac7]11import os
12import re
[a43e1d7]13import stat
[efc15918]14import sys
[4e9151f]15import multiprocessing
[efc15918]16
17################################################################################
18#               help functions
19################################################################################
[f1231f2]20
[911348cd]21# Test class that defines what a test is
[f1231f2]22class Test:
23    def __init__(self, name, path):
24        self.name, self.path = name, path
25
[911348cd]26# parses the Makefile to find the machine type (32-bit / 64-bit)
[f1231f2]27def getMachineType():
[7895d46]28        sh('echo "void ?{}(int*a,int b){}int main(){return 0;}" > .dummy.c')
[20340c2]29        sh("make .dummy", print2stdout=False)
30        _, out = sh("file .dummy", print2stdout=False)
31        sh("rm -f .dummy.c > /dev/null 2>&1")
32        sh("rm -f .dummy > /dev/null 2>&1")
33        return re.search("ELF\s([0-9]+)-bit", out).group(1)
[f1231f2]34
[be65cca]35def listTestsFolder(folder) :
[871b664]36        path = ('./.expect/%s/' % folder) if folder else './.expect/'
37        subpath = "%s/" % folder if folder else ""
[f1231f2]38
[911348cd]39        # tests directly in the .expect folder will always be processed
[871b664]40        return map(lambda fname: Test(fname, subpath + fname),
[be65cca]41                [splitext(f)[0] for f in listdir( path )
[0534c3c]42                if not f.startswith('.') and f.endswith('.txt')
[f1231f2]43                ])
[efc15918]44
[be65cca]45# reads the directory ./.expect and indentifies the tests
46def listTests( concurrent ):
47        machineType = getMachineType()
48
49        # tests directly in the .expect folder will always be processed
[871b664]50        generic_list = listTestsFolder( "" )
[be65cca]51
[911348cd]52        # tests in the machineType folder will be ran only for the corresponding compiler
[be65cca]53        typed_list = listTestsFolder( machineType )
54
55        # tests in the concurrent folder will be ran only if concurrency is enabled
56        concurrent_list = listTestsFolder( "concurrent" ) if concurrent else []
[f1231f2]57
[911348cd]58        # append both lists to get
[be65cca]59        return generic_list + typed_list + concurrent_list;
[efc15918]60
[911348cd]61# helper functions to run terminal commands
[472ca32]62def sh(cmd, dry_run = False, print2stdout = True):
[911348cd]63        if dry_run :    # if this is a dry_run, only print the commands that would be ran
[efc15918]64                print("cmd: %s" % cmd)
[472ca32]65                return 0, None
[911348cd]66        else :                  # otherwise create a pipe and run the desired command
[472ca32]67                proc = Popen(cmd, stdout=None if print2stdout else PIPE, stderr=STDOUT, shell=True)
68                out, err = proc.communicate()
69                return proc.returncode, out
[efc15918]70
[911348cd]71# helper function to replace patterns in a file
[122cac7]72def file_replace(fname, pat, s_after):
73    # first, see if the pattern is even in the file.
74    with open(fname) as f:
75        if not any(re.search(pat, line) for line in f):
76            return # pattern does not occur in file so we are done.
77
78    # pattern is in the file, so perform replace operation.
79    with open(fname) as f:
80        out_fname = fname + ".tmp"
81        out = open(out_fname, "w")
82        for line in f:
83            out.write(re.sub(pat, s_after, line))
84        out.close()
85        os.rename(out_fname, fname)
86
[911348cd]87# tests output may differ depending on the depth of the makefile
[122cac7]88def fix_MakeLevel(file) :
89        if environ.get('MAKELEVEL') :
90                file_replace(file, "make\[%i\]" % int(environ.get('MAKELEVEL')), 'make' )
91
[911348cd]92# helper function to check if a files contains only a spacific string
[84d4d6f]93def fileContainsOnly(file, text) :
94        with open(file) as f:
95                ff = f.read().strip()
96                result = ff == text.strip()
97
98                return result;
99
[911348cd]100# check whether or not a file is executable
[a43e1d7]101def fileIsExecutable(file) :
102        try :
103                fileinfo = os.stat(file)
104                return bool(fileinfo.st_mode & stat.S_IXUSR)
105        except Exception as inst:
106                print(type(inst))    # the exception instance
107                print(inst.args)     # arguments stored in .args
108                print(inst)
109                return False
[122cac7]110
[efc15918]111################################################################################
112#               running test functions
113################################################################################
[6a1bdfd]114def run_single_test(test, generate, dry_run, debug):
[3c1d702]115
[911348cd]116        # find the output file based on the test name and options flag
[f1231f2]117        out_file = (".out/%s.log" % test.name) if not generate else (".expect/%s.txt" % test.path)
[4e9151f]118        err_file = ".err/%s.log" % test.name
[3c1d702]119
[911348cd]120        # remove any outputs from the previous tests to prevent side effects
[3c1d702]121        sh("rm -f %s" % out_file, dry_run)
[f1231f2]122        sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
[efc15918]123
[6a1bdfd]124        options = "-debug" if debug else "-nodebug";
125
[efc15918]126        # build, skipping to next test on error
[4782b39]127        make_ret, _ = sh("""%s EXTRA_FLAGS="-quiet %s" %s 2> %s 1> /dev/null""" % (make_cmd, options, test.name, out_file), dry_run)
[efc15918]128
[911348cd]129        # if the make command succeds continue otherwise skip to diff
[3c1d702]130        if make_ret == 0 :
131                # fetch optional input
[e28d0f5]132                stdinput = "< .in/%s.txt" % test.name if isfile(".in/%s.txt" % test.path) else ""
[efc15918]133
[f1231f2]134                if fileIsExecutable(test.name) :
[a43e1d7]135                        # run test
[f1231f2]136                        sh("./%s %s > %s 2>&1" % (test.name, stdinput, out_file), dry_run)
[a43e1d7]137                else :
138                        # simply cat the result into the output
[f1231f2]139                        sh("cat %s > %s" % (test.name, out_file), dry_run)
[efc15918]140
[4e9151f]141        else :
142                # command failed save the log to less temporary file
143                sh("mv %s %s" % (err_file, out_file), dry_run)
144
[3c1d702]145        retcode = 0
[472ca32]146        error = None
[122cac7]147
[4e9151f]148        # # fix output to prevent make depth to cause issues
149        # fix_MakeLevel(out_file)
[122cac7]150
[84d4d6f]151        if generate :
[911348cd]152                # if we are ounly generating the output we still need to check that the test actually exists
[f1231f2]153                if not dry_run and fileContainsOnly(out_file, "make: *** No rule to make target `%s'.  Stop." % test.name) :
[84d4d6f]154                        retcode = 1;
[38736854]155                        error = "\t\tNo make target for test %s!" % test.name
[84d4d6f]156                        sh("rm %s" % out_file, False)
157
158        else :
[3c1d702]159                # diff the output of the files
[4e9151f]160                diff_cmd = ("diff --ignore-all-space "
161                                        "--ignore-blank-lines "
162                                        "--old-group-format='\t\tmissing lines :\n"
[472ca32]163                                        "%%<' \\\n"
164                                        "--new-group-format='\t\tnew lines :\n"
165                                        "%%>' \\\n"
166                                        "--unchanged-group-format='%%=' \\"
167                                        "--changed-group-format='\t\texpected :\n"
168                                        "%%<\n"
169                                        "\t\tgot :\n"
170                                        "%%>' \\\n"
171                                        "--new-line-format='\t\t%%dn\t%%L' \\\n"
172                                        "--old-line-format='\t\t%%dn\t%%L' \\\n"
173                                        "--unchanged-line-format='' \\\n"
174                                        ".expect/%s.txt .out/%s.log")
175
[911348cd]176                # fetch return code and error from the diff command
[f1231f2]177                retcode, error = sh(diff_cmd % (test.path, test.name), dry_run, False)
[efc15918]178
179        # clean the executable
[f1231f2]180        sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
[efc15918]181
[472ca32]182        return retcode, error
[efc15918]183
[6a1bdfd]184def run_test_instance(t, generate, dry_run, debug) :
[0a1a680]185        try :
186                # print formated name
187                name_txt = "%20s  " % t.name
[ced2e989]188
[0a1a680]189                #run the test instance and collect the result
190                test_failed, error = run_single_test(t, generate, dry_run, debug)
[ced2e989]191
[0a1a680]192                # update output based on current action
193                if generate :
194                        failed_txt = "ERROR"
195                        success_txt = "Done"
196                else :
197                        failed_txt = "FAILED"
198                        success_txt = "PASSED"
199
200                #print result with error if needed
201                text = name_txt + (failed_txt if test_failed else success_txt)
202                out = sys.stdout
203                if error :
204                        text = text + "\n" + error
205                        out = sys.stderr
206
207                print(text, file = out);
208                sys.stdout.flush()
209                sys.stderr.flush()
210                return test_failed
[be65cca]211
[0a1a680]212        except KeyboardInterrupt:
213                test_failed = True
[ced2e989]214
215
[911348cd]216# run the given list of tests with the given parameters
[6a1bdfd]217def run_tests(tests, generate, dry_run, jobs, debug) :
[911348cd]218        # clean the sandbox from previous commands
[74358c3]219        sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
[911348cd]220
221        #make sure the required folder are present
[4e9151f]222        sh('mkdir -p .out .expect .err', dry_run)
[3c1d702]223
224        if generate :
[ebcd82b]225                print( "Regenerate tests for: " )
[efc15918]226
[ced2e989]227        # for each test to run
228        pool = Pool(jobs)
229        try :
[23c2b8d3]230                results = pool.map_async(partial(run_test_instance, generate=generate, dry_run=dry_run, debug=debug), tests ).get(9999)
[ced2e989]231        except KeyboardInterrupt:
232                pool.terminate()
233                print("Tests interrupted by user")
234                sys.exit(1)
[efc15918]235
[911348cd]236        #clean the workspace
[74358c3]237        sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
[efc15918]238
[ced2e989]239        for failed in results:
240                if failed :
241                        return 1
242
243        return 0
[efc15918]244
[6a1bdfd]245def yes_no(string):
246        if string == "yes" :
247                return True
248        if string == "no" :
249                return False
250        raise argparse.ArgumentTypeError(msg)
251        return False
252
253
[efc15918]254################################################################################
255#               main loop
256################################################################################
[911348cd]257# create a parser with the arguments for the tests script
[efc15918]258parser = argparse.ArgumentParser(description='Script which runs cforall tests')
[6a1bdfd]259parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='no')
[0e7b95c]260parser.add_argument('--concurrent', help='Run concurrent tests', type=yes_no, default='yes')
[efc15918]261parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
[0534c3c]262parser.add_argument('--list', help='List all test available', action='store_true')
[efc15918]263parser.add_argument('--all', help='Run all test available', action='store_true')
[0534c3c]264parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
[52c97dd]265parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int, default='8')
[efc15918]266parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
267
[911348cd]268# parse the command line arguments
[efc15918]269options = parser.parse_args()
270
[911348cd]271# script must have at least some tests to run
[0534c3c]272if (len(options.tests) > 0  and     options.all and not options.list) \
273or (len(options.tests) == 0 and not options.all and not options.list) :
[3c1d702]274        print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
275        parser.print_help()
276        sys.exit(1)
[efc15918]277
[911348cd]278# fetch the liest of all valid tests
[be65cca]279allTests = listTests( options.concurrent )
[0534c3c]280
[911348cd]281# if user wants all tests than no other treatement of the test list is required
[0534c3c]282if options.all or options.list :
283        tests = allTests
284
285else :
[911348cd]286        #otherwise we need to validate that the test list that was entered is valid
[0534c3c]287        tests = []
[f1231f2]288
[911348cd]289        # if we are regenerating the tests we need to find the information of the
290        # already existing tests and create new info for the new tests
[f1231f2]291        if options.regenerate_expected :
[38736854]292                for testname in options.tests :
293                        if testname.endswith(".c") or testname.endswith(".cc") or testname.endswith(".cpp") :
294                                print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)
295                        else :
296                                found = [test for test in allTests if test.name == testname]
297                                tests.append( found[0] if len(found) == 1 else Test(testname, testname) )
[f1231f2]298
299        else :
[911348cd]300                # otherwise we only need to validate that all tests are present in the complete list
[f1231f2]301                for testname in options.tests:
302                        test = [t for t in allTests if t.name == testname]
303
304                        if len(test) != 0 :
305                                tests.append( test[0] )
306                        else :
307                                print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr)
[0534c3c]308
[911348cd]309        # make sure we have at least some test to run
[0534c3c]310        if len(tests) == 0 :
311                print('ERROR: No valid test to run', file=sys.stderr)
312                sys.exit(1)
313
[911348cd]314# sort the test alphabetically for convenience
[f1231f2]315tests.sort(key=lambda t: t.name)
316
[911348cd]317# check if the user already passed in a number of jobs for multi-threading
[7bd045d]318make_flags = environ.get('MAKEFLAGS')
[4e9151f]319make_jobs_fds = re.search("--jobserver-(auth|fds)=\s*([0-9]+),([0-9]+)", make_flags) if make_flags else None
[850fda6]320if make_jobs_fds :
[4e9151f]321        tokens = os.read(int(make_jobs_fds.group(2)), 1024)
[850fda6]322        options.jobs = len(tokens)
[4e9151f]323        os.write(int(make_jobs_fds.group(3)), tokens)
324else :
325        options.jobs = multiprocessing.cpu_count()
[911348cd]326
327# make sure we have a valid number of jobs that corresponds to user input
328if options.jobs <= 0 :
329        print('ERROR: Invalid number of jobs', file=sys.stderr)
330        sys.exit(1)
331
[4e9151f]332options.jobs = min( options.jobs, len(tests) )
333
[6a1bdfd]334print('Running (%s) on %i cores' % ("debug" if options.debug else "no debug", options.jobs))
[850fda6]335make_cmd = "make" if make_flags else ("make -j%i" % options.jobs)
[ced2e989]336
[911348cd]337# users may want to simply list the tests
[0534c3c]338if options.list :
[f1231f2]339        print("\n".join(map(lambda t: "%s (%s)" % (t.name, t.path), tests)))
[efc15918]340
[0534c3c]341else :
[911348cd]342        # otherwise run all tests and make sure to return the correct error code
[6a1bdfd]343        sys.exit( run_tests(tests, options.regenerate_expected, options.dry_run, options.jobs, options.debug) )
Note: See TracBrowser for help on using the repository browser.