source: src/tests/test.py @ 86ad276

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

Tests now properly work with multiple architectures

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