source: tests/test.py @ 6044200

aaron-thesisarm-ehcleanup-dtorsdeferred_resnjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexer
Last change on this file since 6044200 was 6044200, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Tests now properly ignore expected files with bogus prefixes/suffixes
closes #116

  • Property mode set to 100755
File size: 10.0 KB
Line 
1#!/usr/bin/python
2from __future__ import print_function
3
4from pybin.tools import *
5from pybin.test_run import *
6from pybin import settings
7
8import argparse
9import re
10import sys
11import time
12
13################################################################################
14#               help functions
15################################################################################
16
17def findTests():
18        expected = []
19
20        def matchTest(path):
21                match = re.search("^%s\/([\w\/\-_]*).expect\/([\w\-_]+)(\.[\w\-_]+)?\.txt$" % settings.SRCDIR, path)
22                if match :
23                        test = Test()
24                        test.name = match.group(2)
25                        test.path = match.group(1)
26                        test.arch = match.group(3)[1:] if match.group(3) else None
27                        if settings.arch.match(test.arch):
28                                expected.append(test)
29
30        pathWalk( matchTest )
31
32        return expected
33
34# reads the directory ./.expect and indentifies the tests
35def listTests( includes, excludes ):
36        # tests directly in the .expect folder will always be processed
37        test_list = findTests()
38
39        # if we have a limited number of includes, filter by them
40        if includes:
41                test_list = [x for x in test_list if
42                        x.target().startswith( tuple(includes) )
43                ]
44
45        # # if we have a folders to excludes, filter by them
46        if excludes:
47                test_list = [x for x in test_list if not
48                        x.target().startswith( tuple(excludes) )
49                ]
50
51        return test_list
52
53# from the found tests, filter all the valid tests/desired tests
54def validTests( options ):
55        tests = []
56
57        # if we are regenerating the tests we need to find the information of the
58        # already existing tests and create new info for the new tests
59        if options.regenerate_expected :
60                for testname in options.tests :
61                        testname = canonicalPath( testname )
62                        if Test.valid_name(testname):
63                                found = [test for test in allTests if canonicalPath( test.target() ) == testname]
64                                tests.append( found[0] if len(found) == 1 else Test.from_target(testname) )
65                        else :
66                                print('ERROR: "%s", tests are not allowed to end with a C/C++/CFA extension, ignoring it' % testname, file=sys.stderr)
67
68        else :
69                # otherwise we only need to validate that all tests are present in the complete list
70                for testname in options.tests:
71                        test = [t for t in allTests if pathCmp( t.target(), testname )]
72
73                        if test :
74                                tests.append( test[0] )
75                        else :
76                                print('ERROR: No expected file for test %s, ignoring it' % testname, file=sys.stderr)
77
78        return tests
79
80# parses the option
81def getOptions():
82        # create a parser with the arguments for the tests script
83        parser = argparse.ArgumentParser(description='Script which runs cforall tests')
84        parser.add_argument('--debug', help='Run all tests in debug or release', type=yes_no, default='yes')
85        parser.add_argument('--install', help='Run all tests based on installed binaries or tree binaries', type=yes_no, default='no')
86        parser.add_argument('--arch', help='Test for specific architecture', type=str, default='')
87        parser.add_argument('--timeout', help='Maximum duration in seconds after a single test is considered to have timed out', type=int, default=60)
88        parser.add_argument('--global-timeout', help='Maximum cumulative duration in seconds after the ALL tests are considered to have timed out', type=int, default=7200)
89        parser.add_argument('--dry-run', help='Don\'t run the tests, only output the commands', action='store_true')
90        parser.add_argument('--list', help='List all test available', action='store_true')
91        parser.add_argument('--all', help='Run all test available', action='store_true')
92        parser.add_argument('--regenerate-expected', help='Regenerate the .expect by running the specified tets, can be used with --all option', action='store_true')
93        parser.add_argument('-j', '--jobs', help='Number of tests to run simultaneously', type=int)
94        parser.add_argument('--list-comp', help='List all valide arguments', action='store_true')
95        parser.add_argument('-I','--include', help='Directory of test to include, can be used multiple time, All  if omitted', action='append')
96        parser.add_argument('-E','--exclude', help='Directory of test to exclude, can be used multiple time, None if omitted', action='append')
97        parser.add_argument('tests', metavar='test', type=str, nargs='*', help='a list of tests to run')
98
99        try:
100                options =  parser.parse_args()
101        except:
102                print('ERROR: invalid arguments', file=sys.stderr)
103                parser.print_help(sys.stderr)
104                sys.exit(1)
105
106        # script must have at least some tests to run or be listing
107        listing    = options.list or options.list_comp
108        all_tests  = options.all
109        some_tests = len(options.tests) > 0
110        some_dirs  = len(options.include) > 0 if options.include else 0
111
112        # check that exactly one of the booleans is set to true
113        if not sum( (listing, all_tests, some_tests, some_dirs) ) > 0 :
114                print('ERROR: must have option \'--all\', \'--list\', \'--include\', \'-I\' or non-empty test list', file=sys.stderr)
115                parser.print_help()
116                sys.exit(1)
117
118        return options
119
120################################################################################
121#               running test functions
122################################################################################
123# fix the absolute paths in the output
124def fixoutput( fname ):
125        if not is_ascii(fname):
126                return
127
128        file_replace(fname, "%s/" % settings.SRCDIR, "")
129
130
131# logic to run a single test and return the result (No handling of printing or other test framework logic)
132def run_single_test(test):
133
134        # find the output file based on the test name and options flag
135        exe_file = test.target_executable();
136        out_file = test.target_output()
137        err_file = test.error_log()
138        cmp_file = test.expect()
139        in_file  = test.input()
140
141        # prepare the proper directories
142        test.prepare()
143
144        # build, skipping to next test on error
145        before = time.time()
146        make_ret, _ = make( test.target(),
147                redirects  = "2> %s 1> /dev/null" % out_file,
148                error_file = err_file
149        )
150        after = time.time()
151
152        comp_dur = after - before
153
154        run_dur = None
155
156        # if the make command succeds continue otherwise skip to diff
157        if make_ret == 0 or settings.dry_run:
158                before = time.time()
159                if settings.dry_run or fileIsExecutable(exe_file) :
160                        # run test
161                        retcode, _ = sh("timeout %d %s > %s 2>&1" % (settings.timeout.single, exe_file, out_file), input = in_file)
162                else :
163                        # simply cat the result into the output
164                        retcode, _ = sh("cat %s > %s" % (exe_file, out_file))
165
166                after = time.time()
167                run_dur = after - before
168        else:
169                retcode, _ = sh("mv %s %s" % (err_file, out_file))
170
171
172        if retcode == 0:
173                # fixoutput(out_file)
174                if settings.generating :
175                        # if we are ounly generating the output we still need to check that the test actually exists
176                        if not settings.dry_run and fileContainsOnly(out_file, "make: *** No rule to make target `%s'.  Stop." % test.target()) :
177                                retcode = 1;
178                                error = "\t\tNo make target for test %s!" % test.target()
179                                sh("rm %s" % out_file, False)
180                        else:
181                                error = None
182                else :
183                        # fetch return code and error from the diff command
184                        retcode, error = diff(cmp_file, out_file)
185
186        else:
187                with open (out_file, "r") as myfile:
188                        error = myfile.read()
189
190
191        # clean the executable
192        sh("rm -f %s > /dev/null 2>&1" % test.target())
193
194        return retcode, error, [comp_dur, run_dur]
195
196# run a single test and handle the errors, outputs, printing, exception handling, etc.
197def run_test_worker(t) :
198
199        with SignalHandling():
200                # print formated name
201                name_txt = "%20s  " % t.name
202
203                retcode, error, duration = run_single_test(t)
204
205                # update output based on current action
206                result_txt = TestResult.toString( retcode, duration )
207
208                #print result with error if needed
209                text = name_txt + result_txt
210                out = sys.stdout
211                if error :
212                        text = text + "\n" + error
213                        out = sys.stderr
214
215                print(text, file = out)
216                sys.stdout.flush()
217                sys.stderr.flush()
218
219        return retcode != TestResult.SUCCESS
220
221# run the given list of tests with the given parameters
222def run_tests(tests, jobs) :
223        # clean the sandbox from previous commands
224        make('clean', redirects = '> /dev/null 2>&1')
225
226        # create the executor for our jobs and handle the signal properly
227        pool = setupPool(jobs)
228
229        # for each test to run
230        try :
231                results = pool.map_async(
232                        run_test_worker,
233                        tests,
234                        chunksize = 1
235                ).get(settings.timeout.total)
236        except KeyboardInterrupt:
237                pool.terminate()
238                print("Tests interrupted by user")
239                sys.exit(1)
240
241        # clean the workspace
242        make('clean', redirects = '> /dev/null 2>&1')
243
244        for failed in results:
245                if failed :
246                        return 1
247
248        return 0
249
250
251################################################################################
252#               main loop
253################################################################################
254if __name__ == "__main__":
255
256        # parse the command line arguments
257        options = getOptions()
258
259        # init global settings
260        settings.init( options )
261
262        # fetch the liest of all valid tests
263        allTests = listTests( options.include, options.exclude )
264
265        # if user wants all tests than no other treatement of the test list is required
266        if options.all or options.list or options.list_comp or options.include :
267                tests = allTests
268
269        #otherwise we need to validate that the test list that was entered is valid
270        else :
271                tests = validTests( options )
272
273        # make sure we have at least some test to run
274        if not tests :
275                print('ERROR: No valid test to run', file=sys.stderr)
276                sys.exit(1)
277
278
279        # sort the test alphabetically for convenience
280        tests.sort(key=lambda t: (t.arch if t.arch else '') + t.target())
281
282        # users may want to simply list the tests
283        if options.list_comp :
284                print("-h --help --debug --dry-run --list --arch --all --regenerate-expected --install --timeout --global-timeout -j --jobs ", end='')
285                print(" ".join(map(lambda t: "%s" % (t.target()), tests)))
286
287        elif options.list :
288                print("Listing for %s:%s"% (settings.arch.string, settings.debug.string))
289                fancy_print("\n".join(map(lambda t: "%s" % (t.toString()), tests)))
290
291        else :
292                # check the build configuration works
293                settings.validate()
294
295                options.jobs, forceJobs = jobCount( options, tests )
296                settings.updateMakeCmd(forceJobs, options.jobs)
297
298                print('%s (%s:%s) on %i cores' % (
299                        'Regenerate tests' if settings.generating else 'Running',
300                        settings.arch.string,
301                        settings.debug.string,
302                        options.jobs
303                ))
304
305                # otherwise run all tests and make sure to return the correct error code
306                sys.exit( run_tests(tests, options.jobs) )
Note: See TracBrowser for help on using the repository browser.