source: src/tests/test.py @ a62cbb3

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 a62cbb3 was a62cbb3, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Fixed enable-threading option and removed extraneous debug print

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