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
Line 
1#!/usr/bin/python
2from __future__ import print_function
3
4from functools import partial
5from multiprocessing import Pool
6from os import listdir, environ
7from os.path import isfile, join, splitext
8from subprocess import Popen, PIPE, STDOUT
9
10import argparse
11import os
12import re
13import stat
14import sys
15import multiprocessing
16
17################################################################################
18#               help functions
19################################################################################
20
21# Test class that defines what a test is
22class Test:
23    def __init__(self, name, path):
24        self.name, self.path = name, path
25
26# parses the Makefile to find the machine type (32-bit / 64-bit)
27def getMachineType():
28        sh('echo "void ?{}(int*a,int b){}int main(){return 0;}" > .dummy.c')
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)
34
35def listTestsFolder(folder) :
36        path = ('./.expect/%s/' % folder) if folder else './.expect/'
37        subpath = "%s/" % folder if folder else ""
38
39        # tests directly in the .expect folder will always be processed
40        return map(lambda fname: Test(fname, subpath + fname),
41                [splitext(f)[0] for f in listdir( path )
42                if not f.startswith('.') and f.endswith('.txt')
43                ])
44
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
50        generic_list = listTestsFolder( "" )
51
52        # tests in the machineType folder will be ran only for the corresponding compiler
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 []
57
58        # append both lists to get
59        return generic_list + typed_list + concurrent_list;
60
61# helper functions to run terminal commands
62def sh(cmd, dry_run = False, print2stdout = True):
63        if dry_run :    # if this is a dry_run, only print the commands that would be ran
64                print("cmd: %s" % cmd)
65                return 0, None
66        else :                  # otherwise create a pipe and run the desired command
67                proc = Popen(cmd, stdout=None if print2stdout else PIPE, stderr=STDOUT, shell=True)
68                out, err = proc.communicate()
69                return proc.returncode, out
70
71# helper function to replace patterns in a file
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
87# tests output may differ depending on the depth of the makefile
88def fix_MakeLevel(file) :
89        if environ.get('MAKELEVEL') :
90                file_replace(file, "make\[%i\]" % int(environ.get('MAKELEVEL')), 'make' )
91
92# helper function to check if a files contains only a spacific string
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
100# check whether or not a file is executable
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
110
111################################################################################
112#               running test functions
113################################################################################
114def run_single_test(test, generate, dry_run, debug):
115
116        # find the output file based on the test name and options flag
117        out_file = (".out/%s.log" % test.name) if not generate else (".expect/%s.txt" % test.path)
118        err_file = ".err/%s.log" % test.name
119
120        # remove any outputs from the previous tests to prevent side effects
121        sh("rm -f %s" % out_file, dry_run)
122        sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
123
124        options = "-debug" if debug else "-nodebug";
125
126        # build, skipping to next test on error
127        make_ret, _ = sh("""%s EXTRA_FLAGS="-quiet %s" %s 2> %s 1> /dev/null""" % (make_cmd, options, test.name, out_file), dry_run)
128
129        # if the make command succeds continue otherwise skip to diff
130        if make_ret == 0 :
131                # fetch optional input
132                stdinput = "< .in/%s.txt" % test.name if isfile(".in/%s.txt" % test.path) else ""
133
134                if fileIsExecutable(test.name) :
135                        # run test
136                        sh("./%s %s > %s 2>&1" % (test.name, stdinput, out_file), dry_run)
137                else :
138                        # simply cat the result into the output
139                        sh("cat %s > %s" % (test.name, out_file), dry_run)
140
141        else :
142                # command failed save the log to less temporary file
143                sh("mv %s %s" % (err_file, out_file), dry_run)
144
145        retcode = 0
146        error = None
147
148        # # fix output to prevent make depth to cause issues
149        # fix_MakeLevel(out_file)
150
151        if generate :
152                # if we are ounly generating the output we still need to check that the test actually exists
153                if not dry_run and fileContainsOnly(out_file, "make: *** No rule to make target `%s'.  Stop." % test.name) :
154                        retcode = 1;
155                        error = "\t\tNo make target for test %s!" % test.name
156                        sh("rm %s" % out_file, False)
157
158        else :
159                # diff the output of the files
160                diff_cmd = ("diff --ignore-all-space "
161                                        "--ignore-blank-lines "
162                                        "--old-group-format='\t\tmissing lines :\n"
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
176                # fetch return code and error from the diff command
177                retcode, error = sh(diff_cmd % (test.path, test.name), dry_run, False)
178
179        # clean the executable
180        sh("rm -f %s > /dev/null 2>&1" % test.name, dry_run)
181
182        return retcode, error
183
184def run_test_instance(t, generate, dry_run, debug) :
185        try :
186                # print formated name
187                name_txt = "%20s  " % t.name
188
189                #run the test instance and collect the result
190                test_failed, error = run_single_test(t, generate, dry_run, debug)
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                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
211
212        except KeyboardInterrupt:
213                test_failed = True
214
215
216# run the given list of tests with the given parameters
217def run_tests(tests, generate, dry_run, jobs, debug) :
218        # clean the sandbox from previous commands
219        sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
220
221        #make sure the required folder are present
222        sh('mkdir -p .out .expect .err', dry_run)
223
224        if generate :
225                print( "Regenerate tests for: " )
226
227        # for each test to run
228        pool = Pool(jobs)
229        try :
230                results = pool.map_async(partial(run_test_instance, generate=generate, dry_run=dry_run, debug=debug), tests ).get(9999)
231        except KeyboardInterrupt:
232                pool.terminate()
233                print("Tests interrupted by user")
234                sys.exit(1)
235
236        #clean the workspace
237        sh("%s clean > /dev/null 2>&1" % make_cmd, dry_run)
238
239        for failed in results:
240                if failed :
241                        return 1
242
243        return 0
244
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
254################################################################################
255#               main loop
256################################################################################
257# create a parser with the arguments for the tests script
258parser = argparse.ArgumentParser(description='Script which runs cforall tests')
259parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='no')
260parser.add_argument('--concurrent', help='Run concurrent tests', type=yes_no, default='yes')
261parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
262parser.add_argument('--list', help='List all test available', action='store_true')
263parser.add_argument('--all', help='Run all test available', action='store_true')
264parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
265parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int, default='8')
266parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
267
268# parse the command line arguments
269options = parser.parse_args()
270
271# script must have at least some tests to run
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) :
274        print('ERROR: must have option \'--all\' or non-empty test list', file=sys.stderr)
275        parser.print_help()
276        sys.exit(1)
277
278# fetch the liest of all valid tests
279allTests = listTests( options.concurrent )
280
281# if user wants all tests than no other treatement of the test list is required
282if options.all or options.list :
283        tests = allTests
284
285else :
286        #otherwise we need to validate that the test list that was entered is valid
287        tests = []
288
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
291        if options.regenerate_expected :
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) )
298
299        else :
300                # otherwise we only need to validate that all tests are present in the complete list
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)
308
309        # make sure we have at least some test to run
310        if len(tests) == 0 :
311                print('ERROR: No valid test to run', file=sys.stderr)
312                sys.exit(1)
313
314# sort the test alphabetically for convenience
315tests.sort(key=lambda t: t.name)
316
317# check if the user already passed in a number of jobs for multi-threading
318make_flags = environ.get('MAKEFLAGS')
319make_jobs_fds = re.search("--jobserver-(auth|fds)=\s*([0-9]+),([0-9]+)", make_flags) if make_flags else None
320if make_jobs_fds :
321        tokens = os.read(int(make_jobs_fds.group(2)), 1024)
322        options.jobs = len(tokens)
323        os.write(int(make_jobs_fds.group(3)), tokens)
324else :
325        options.jobs = multiprocessing.cpu_count()
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
332options.jobs = min( options.jobs, len(tests) )
333
334print('Running (%s) on %i cores' % ("debug" if options.debug else "no debug", options.jobs))
335make_cmd = "make" if make_flags else ("make -j%i" % options.jobs)
336
337# users may want to simply list the tests
338if options.list :
339        print("\n".join(map(lambda t: "%s (%s)" % (t.name, t.path), tests)))
340
341else :
342        # otherwise run all tests and make sure to return the correct error code
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.