source: src/tests/test.py @ 38736854

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

test script no longer allows to accidently delete a .c file while regenerating a test

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