source: src/tests/test.py @ 911348cd

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 911348cd was 911348cd, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

added comments and options support for multi-threaded tests

  • Property mode set to 100755
File size: 9.7 KB
Line 
1#!/usr/bin/python
2from __future__ import print_function
3
4from os import listdir, environ
5from os.path import isfile, join, splitext
6from subprocess import Popen, PIPE, STDOUT
7
8import argparse
9import os
10import re
11import stat
12import sys
13
14################################################################################
15#               help functions
16################################################################################
17
18# Test class that defines what a test is
19class Test:
20    def __init__(self, name, path):
21        self.name, self.path = name, path
22
23# parses the Makefile to find the machine type (32-bit / 64-bit)
24def getMachineType():
25        with open('Makefile') as file:
26                makefile = file.read()
27                m = re.search("CFA_FLAGS\s*=\s*-m(.*)", makefile)
28                return m.group(1)
29
30# reads the directory ./.expect and indentifies the tests
31def listTests():
32        machineType = getMachineType()
33
34        # tests directly in the .expect folder will always be processed
35        generic_list = map(lambda fname: Test(fname, fname),
36                [splitext(f)[0] for f in listdir('./.expect')
37                if not f.startswith('.') and f.endswith('.txt')
38                ])
39
40        # tests in the machineType folder will be ran only for the corresponding compiler
41        typed_list = map(lambda fname: Test( fname, "%s/%s" % (machineType, fname) ),
42                [splitext(f)[0] for f in listdir("./.expect/%s" % machineType)
43                if not f.startswith('.') and f.endswith('.txt')
44                ])
45
46        # append both lists to get
47        return generic_list + typed_list
48
49# helper functions to run terminal commands
50def sh(cmd, dry_run = False, print2stdout = True):
51        if dry_run :    # if this is a dry_run, only print the commands that would be ran
52                print("cmd: %s" % cmd)
53                return 0, None
54        else :                  # otherwise create a pipe and run the desired command
55                proc = Popen(cmd, stdout=None if print2stdout else PIPE, stderr=STDOUT, shell=True)
56                out, err = proc.communicate()
57                return proc.returncode, out
58
59# helper function to replace patterns in a file
60def file_replace(fname, pat, s_after):
61    # first, see if the pattern is even in the file.
62    with open(fname) as f:
63        if not any(re.search(pat, line) for line in f):
64            return # pattern does not occur in file so we are done.
65
66    # pattern is in the file, so perform replace operation.
67    with open(fname) as f:
68        out_fname = fname + ".tmp"
69        out = open(out_fname, "w")
70        for line in f:
71            out.write(re.sub(pat, s_after, line))
72        out.close()
73        os.rename(out_fname, fname)
74
75# tests output may differ depending on the depth of the makefile
76def fix_MakeLevel(file) :
77        if environ.get('MAKELEVEL') :
78                file_replace(file, "make\[%i\]" % int(environ.get('MAKELEVEL')), 'make' )
79
80# helper function to check if a files contains only a spacific string
81def fileContainsOnly(file, text) :
82        with open(file) as f:
83                ff = f.read().strip()
84                result = ff == text.strip()
85
86                return result;
87
88# check whether or not a file is executable
89def fileIsExecutable(file) :
90        try :
91                fileinfo = os.stat(file)
92                return bool(fileinfo.st_mode & stat.S_IXUSR)
93        except Exception as inst:
94                print(type(inst))    # the exception instance
95                print(inst.args)     # arguments stored in .args
96                print(inst)
97                return False
98
99# find the test data for a given test name
100def filterTests(testname) :
101        found = [test for test in allTests if test.name == testname]
102        return (found[0] if len(found) == 1 else Test(testname, testname) )
103
104################################################################################
105#               running test functions
106################################################################################
107def run_test_instance(test, generate, dry_run):
108
109        # find the output file based on the test name and options flag
110        out_file = (".out/%s.log" % test.name) if not generate else (".expect/%s.txt" % test.path)
111
112        # remove any outputs from the previous tests to prevent side effects
113        sh("rm -f %s" % out_file, dry_run)
114        sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
115
116        # build, skipping to next test on error
117        make_ret, _ = sh("%s %s 2> %s 1> /dev/null" % (make_cmd, test.name, out_file), dry_run)
118
119        # if the make command succeds continue otherwise skip to diff
120        if make_ret == 0 :
121                # fetch optional input
122                stdinput = "< .in/%s.txt" % test.name if isfile(".in/%s.txt" % test.path) else ""
123
124                if fileIsExecutable(test.name) :
125                        # run test
126                        sh("./%s %s > %s 2>&1" % (test.name, stdinput, out_file), dry_run)
127                else :
128                        # simply cat the result into the output
129                        sh("cat %s > %s" % (test.name, out_file), dry_run)
130
131        retcode = 0
132        error = None
133
134        # fix output to prevent make depth to cause issues
135        fix_MakeLevel(out_file)
136
137        if generate :
138                # if we are ounly generating the output we still need to check that the test actually exists
139                if not dry_run and fileContainsOnly(out_file, "make: *** No rule to make target `%s'.  Stop." % test.name) :
140                        retcode = 1;
141                        error = "\t\tNo make target for test %s!" % test
142                        sh("rm %s" % out_file, False)
143
144        else :
145                # diff the output of the files
146                diff_cmd = ("diff --old-group-format='\t\tmissing lines :\n"
147                                        "%%<' \\\n"
148                                        "--new-group-format='\t\tnew lines :\n"
149                                        "%%>' \\\n"
150                                        "--unchanged-group-format='%%=' \\"
151                                        "--changed-group-format='\t\texpected :\n"
152                                        "%%<\n"
153                                        "\t\tgot :\n"
154                                        "%%>' \\\n"
155                                        "--new-line-format='\t\t%%dn\t%%L' \\\n"
156                                        "--old-line-format='\t\t%%dn\t%%L' \\\n"
157                                        "--unchanged-line-format='' \\\n"
158                                        ".expect/%s.txt .out/%s.log")
159
160                # fetch return code and error from the diff command
161                retcode, error = sh(diff_cmd % (test.path, test.name), dry_run, False)
162
163        # clean the executable
164        sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
165
166        return retcode, error
167
168# run the given list of tests with the given parameters
169def run_tests(tests, generate, dry_run, jobs) :
170        # clean the sandbox from previous commands
171        sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
172
173        #make sure the required folder are present
174        sh('mkdir -p .out .expect', dry_run)
175
176        if generate :
177                print( "Regenerate tests for: " )
178
179        failed = False;
180        # for eeach test to run
181        for t in tests:
182                # print formated name
183                print("%20s  " % t.name, end="")
184                sys.stdout.flush()
185
186                #run the test instance and collect the result
187                test_failed, error = run_test_instance(t, generate, dry_run)
188
189                # aggregate test suite result
190                failed = test_failed or failed
191
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                print(failed_txt if test_failed else success_txt)
202                if error :
203                        print(error, file=sys.stderr)
204
205        #clean the workspace
206        sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
207
208        return 1 if failed else 0
209
210################################################################################
211#               main loop
212################################################################################
213# create a parser with the arguments for the tests script
214parser = argparse.ArgumentParser(description='Script which runs cforall tests')
215parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
216parser.add_argument('--list', help='List all test available', action='store_true')
217parser.add_argument('--all', help='Run all test available', action='store_true')
218parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
219parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int, default='1')
220parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
221
222# parse the command line arguments
223options = parser.parse_args()
224
225# script must have at least some tests to run
226if (len(options.tests) > 0  and     options.all and not options.list) \
227or (len(options.tests) == 0 and not options.all and not options.list) :
228        print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
229        parser.print_help()
230        sys.exit(1)
231
232# fetch the liest of all valid tests
233allTests = listTests()
234
235# if user wants all tests than no other treatement of the test list is required
236if options.all or options.list :
237        tests = allTests
238
239else :
240        #otherwise we need to validate that the test list that was entered is valid
241        tests = []
242
243        # if we are regenerating the tests we need to find the information of the
244        # already existing tests and create new info for the new tests
245        if options.regenerate_expected :
246                tests = map(filterTests, options.tests)
247
248        else :
249                # otherwise we only need to validate that all tests are present in the complete list
250                for testname in options.tests:
251                        test = [t for t in allTests if t.name == testname]
252
253                        if len(test) != 0 :
254                                tests.append( test[0] )
255                        else :
256                                print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr)
257
258        # make sure we have at least some test to run
259        if len(tests) == 0 :
260                print('ERROR: No valid test to run', file=sys.stderr)
261                sys.exit(1)
262
263# sort the test alphabetically for convenience
264tests.sort(key=lambda t: t.name)
265
266# check if the user already passed in a number of jobs for multi-threading
267make_flags = environ.get('MAKEFLAGS')
268make_has_max_jobs = make_flags and "-j" in make_flags
269make_max_jobs = re.search("(-j|--jobs)\s*([0-9]+)", make_flags).group(2) if make_has_max_jobs else None
270make_cmd = "make" if make_has_max_jobs else "make -j8"
271
272# make sure we have a valid number of jobs that corresponds to user input
273options.jobs = int(make_max_jobs) if make_max_jobs else options.jobs
274if options.jobs <= 0 :
275        print('ERROR: Invalid number of jobs', file=sys.stderr)
276        sys.exit(1)
277
278
279# users may want to simply list the tests
280if options.list :
281        print("\n".join(map(lambda t: "%s (%s)" % (t.name, t.path), tests)))
282
283else :
284        # otherwise run all tests and make sure to return the correct error code
285        sys.exit( run_tests(tests, options.regenerate_expected, options.dry_run) )
Note: See TracBrowser for help on using the repository browser.