verify.py revision 13002:b8d58d5f25a5
110447Snilay@cs.wisc.edu#!/usr/bin/env python2
210447Snilay@cs.wisc.edu#
310447Snilay@cs.wisc.edu# Copyright 2018 Google, Inc.
410447Snilay@cs.wisc.edu#
510447Snilay@cs.wisc.edu# Redistribution and use in source and binary forms, with or without
610447Snilay@cs.wisc.edu# modification, are permitted provided that the following conditions are
710447Snilay@cs.wisc.edu# met: redistributions of source code must retain the above copyright
810447Snilay@cs.wisc.edu# notice, this list of conditions and the following disclaimer;
910447Snilay@cs.wisc.edu# redistributions in binary form must reproduce the above copyright
1010447Snilay@cs.wisc.edu# notice, this list of conditions and the following disclaimer in the
1110447Snilay@cs.wisc.edu# documentation and/or other materials provided with the distribution;
1210447Snilay@cs.wisc.edu# neither the name of the copyright holders nor the names of its
1310447Snilay@cs.wisc.edu# contributors may be used to endorse or promote products derived from
1410447Snilay@cs.wisc.edu# this software without specific prior written permission.
1510447Snilay@cs.wisc.edu#
1610447Snilay@cs.wisc.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1710447Snilay@cs.wisc.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1810447Snilay@cs.wisc.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1910447Snilay@cs.wisc.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2010447Snilay@cs.wisc.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2110447Snilay@cs.wisc.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2210447Snilay@cs.wisc.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2310447Snilay@cs.wisc.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2410447Snilay@cs.wisc.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2510447Snilay@cs.wisc.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2610447Snilay@cs.wisc.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2710447Snilay@cs.wisc.edu#
2810447Snilay@cs.wisc.edu# Authors: Gabe Black
2910447Snilay@cs.wisc.edu
3010447Snilay@cs.wisc.edufrom __future__ import print_function
3110447Snilay@cs.wisc.edu
3210447Snilay@cs.wisc.eduimport argparse
3310447Snilay@cs.wisc.eduimport functools
3410447Snilay@cs.wisc.eduimport inspect
3510447Snilay@cs.wisc.eduimport itertools
3610447Snilay@cs.wisc.eduimport json
3710447Snilay@cs.wisc.eduimport multiprocessing.pool
3810447Snilay@cs.wisc.eduimport os
3910447Snilay@cs.wisc.eduimport subprocess
4010447Snilay@cs.wisc.eduimport sys
4110447Snilay@cs.wisc.edu
4210447Snilay@cs.wisc.eduscript_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
4310447Snilay@cs.wisc.eduscript_dir = os.path.dirname(script_path)
4410447Snilay@cs.wisc.educonfig_path = os.path.join(script_dir, 'config.py')
4510447Snilay@cs.wisc.edu
4610447Snilay@cs.wisc.edusystemc_rel_path = 'systemc'
4710447Snilay@cs.wisc.edutests_rel_path = os.path.join(systemc_rel_path, 'tests')
4810447Snilay@cs.wisc.edujson_rel_path = os.path.join(tests_rel_path, 'tests.json')
4910447Snilay@cs.wisc.edu
5010447Snilay@cs.wisc.edu
5110447Snilay@cs.wisc.edu
5210447Snilay@cs.wisc.edudef scons(*args):
5310447Snilay@cs.wisc.edu    args = ['scons'] + list(args)
5410447Snilay@cs.wisc.edu    subprocess.check_call(args)
5510447Snilay@cs.wisc.edu
5610447Snilay@cs.wisc.edu
5710447Snilay@cs.wisc.edu
5810447Snilay@cs.wisc.educlass Test(object):
5910447Snilay@cs.wisc.edu    def __init__(self, target, suffix, build_dir, props):
6010447Snilay@cs.wisc.edu        self.target = target
6110447Snilay@cs.wisc.edu        self.suffix = suffix
6210447Snilay@cs.wisc.edu        self.build_dir = build_dir
6310447Snilay@cs.wisc.edu
6410447Snilay@cs.wisc.edu        for key, val in props.iteritems():
6510447Snilay@cs.wisc.edu            setattr(self, key, val)
6610447Snilay@cs.wisc.edu
6710447Snilay@cs.wisc.edu    def dir(self):
6810447Snilay@cs.wisc.edu        return os.path.join(self.build_dir, tests_rel_path, self.path)
6910447Snilay@cs.wisc.edu
7010447Snilay@cs.wisc.edu    def src_dir(self):
7110447Snilay@cs.wisc.edu        return os.path.join(script_dir, self.path)
7210447Snilay@cs.wisc.edu
7310447Snilay@cs.wisc.edu    def golden_dir(self):
7410447Snilay@cs.wisc.edu        return os.path.join(self.src_dir(), 'golden')
7510447Snilay@cs.wisc.edu
7610447Snilay@cs.wisc.edu    def bin(self):
7710447Snilay@cs.wisc.edu        return '.'.join([self.name, self.suffix])
7810447Snilay@cs.wisc.edu
7910447Snilay@cs.wisc.edu    def full_path(self):
8010447Snilay@cs.wisc.edu        return os.path.join(self.dir(), self.bin())
8110447Snilay@cs.wisc.edu
8210447Snilay@cs.wisc.edu    def m5out_dir(self):
8310447Snilay@cs.wisc.edu        return os.path.join(self.dir(), 'm5out.' + self.suffix)
8410447Snilay@cs.wisc.edu
8510447Snilay@cs.wisc.edu    def returncode_file(self):
8610447Snilay@cs.wisc.edu        return os.path.join(self.m5out_dir(), 'returncode')
8710447Snilay@cs.wisc.edu
8810447Snilay@cs.wisc.edu
8910447Snilay@cs.wisc.edu
9010447Snilay@cs.wisc.edutest_phase_classes = {}
9110447Snilay@cs.wisc.edu
9210447Snilay@cs.wisc.educlass TestPhaseMeta(type):
9310447Snilay@cs.wisc.edu    def __init__(cls, name, bases, d):
9410447Snilay@cs.wisc.edu        if not d.pop('abstract', False):
9510447Snilay@cs.wisc.edu            test_phase_classes[d['name']] = cls
9610447Snilay@cs.wisc.edu
9710447Snilay@cs.wisc.edu        super(TestPhaseMeta, cls).__init__(name, bases, d)
9810447Snilay@cs.wisc.edu
9910447Snilay@cs.wisc.educlass TestPhaseBase(object):
10010447Snilay@cs.wisc.edu    __metaclass__ = TestPhaseMeta
10110447Snilay@cs.wisc.edu    abstract = True
10210447Snilay@cs.wisc.edu
10310447Snilay@cs.wisc.edu    def __init__(self, main_args, *args):
10410447Snilay@cs.wisc.edu        self.main_args = main_args
10510447Snilay@cs.wisc.edu        self.args = args
10610447Snilay@cs.wisc.edu
10710447Snilay@cs.wisc.edu    def __lt__(self, other):
10810447Snilay@cs.wisc.edu        return self.number < other.number
10910447Snilay@cs.wisc.edu
11010447Snilay@cs.wisc.educlass CompilePhase(TestPhaseBase):
11110447Snilay@cs.wisc.edu    name = 'compile'
11210447Snilay@cs.wisc.edu    number = 1
113
114    def run(self, tests):
115        targets = list([test.full_path() for test in tests])
116        scons_args = list(self.args) + targets
117        scons(*scons_args)
118
119class RunPhase(TestPhaseBase):
120    name = 'execute'
121    number = 2
122
123    def run(self, tests):
124        parser = argparse.ArgumentParser()
125        parser.add_argument('--timeout', type=int, metavar='SECONDS',
126                            help='Time limit for each run in seconds.',
127                            default=0)
128        parser.add_argument('-j', type=int, default=1,
129                help='How many tests to run in parallel.')
130        args = parser.parse_args(self.args)
131
132        timeout_cmd = [
133            'timeout',
134            '--kill-after', str(args.timeout * 2),
135            str(args.timeout)
136        ]
137        def run_test(test):
138            cmd = []
139            if args.timeout:
140                cmd.extend(timeout_cmd)
141            cmd.extend([
142                test.full_path(),
143                '-red', test.m5out_dir(),
144                '--listener-mode=off',
145                config_path
146            ])
147            # Ensure the output directory exists.
148            if not os.path.exists(test.m5out_dir()):
149                os.makedirs(test.m5out_dir())
150            try:
151                subprocess.check_call(cmd)
152            except subprocess.CalledProcessError, error:
153                returncode = error.returncode
154            else:
155                returncode = 0
156            with open(test.returncode_file(), 'w') as rc:
157                rc.write('%d\n' % returncode)
158
159        runnable = filter(lambda t: not t.compile_only, tests)
160        if args.j == 1:
161            map(run_test, runnable)
162        else:
163            tp = multiprocessing.pool.ThreadPool(args.j)
164            map(lambda t: tp.apply_async(run_test, (t,)), runnable)
165            tp.close()
166            tp.join()
167
168class VerifyPhase(TestPhaseBase):
169    name = 'verify'
170    number = 3
171
172    def reset_status(self):
173        self._passed = []
174        self._failed = {}
175
176    def passed(self, test):
177        self._passed.append(test)
178
179    def failed(self, test, cause):
180        self._failed.setdefault(cause, []).append(test)
181
182    def print_status(self):
183        total_passed = len(self._passed)
184        total_failed = sum(map(len, self._failed.values()))
185        print()
186        print('Passed: {passed:4} - Failed: {failed:4}'.format(
187                  passed=total_passed, failed=total_failed))
188
189    def write_result_file(self, path):
190        passed = map(lambda t: t.path, self._passed)
191        passed.sort()
192        failed = {
193            cause: map(lambda t: t.path, tests) for
194                       cause, tests in self._failed.iteritems()
195        }
196        for tests in failed.values():
197            tests.sort()
198        results = { 'passed': passed, 'failed': failed }
199        with open(path, 'w') as rf:
200            json.dump(results, rf)
201
202    def print_results(self):
203        passed = map(lambda t: t.path, self._passed)
204        passed.sort()
205        failed = {
206            cause: map(lambda t: t.path, tests) for
207                       cause, tests in self._failed.iteritems()
208        }
209        for tests in failed.values():
210            tests.sort()
211
212        print()
213        print('Passed:')
214        map(lambda t: print('    ', t), passed)
215
216        print()
217        print('Failed:')
218        categories = failed.items()
219        categories.sort()
220
221        def cat_str((cause, tests)):
222            heading = '  ' + cause.capitalize() + ':\n'
223            test_lines = ['    ' + test + '\n'for test in tests]
224            return heading + ''.join(test_lines)
225        blocks = map(cat_str, categories)
226
227        print('\n'.join(blocks))
228
229    def run(self, tests):
230        parser = argparse.ArgumentParser()
231        result_opts = parser.add_mutually_exclusive_group()
232        result_opts.add_argument('--result-file', action='store_true',
233                help='Create a results.json file in the current directory.')
234        result_opts.add_argument('--result-file-at', metavar='PATH',
235                help='Create a results json file at the given path.')
236        parser.add_argument('--print-results', action='store_true',
237                help='Print a list of tests that passed or failed')
238        args = parser.parse_args(self.args)
239
240        self.reset_status()
241
242        runnable = filter(lambda t: not t.compile_only, tests)
243        compile_only = filter(lambda t: t.compile_only, tests)
244
245        for test in compile_only:
246            if os.path.exists(test.full_path()):
247                self.passed(test)
248            else:
249                self.failed(test, 'compile failed')
250
251        for test in runnable:
252            with open(test.returncode_file()) as rc:
253                returncode = int(rc.read())
254
255            if returncode == 0:
256                self.passed(test)
257            elif returncode == 124:
258                self.failed(test, 'time out')
259            else:
260                self.failed(test, 'abort')
261
262        if args.print_results:
263            self.print_results()
264
265        self.print_status()
266
267        result_path = None
268        if args.result_file:
269            result_path = os.path.join(os.getcwd(), 'results.json')
270        elif args.result_file_at:
271            result_path = args.result_file_at
272
273        if result_path:
274            self.write_result_file(result_path)
275
276
277parser = argparse.ArgumentParser(description='SystemC test utility')
278
279parser.add_argument('build_dir', metavar='BUILD_DIR',
280                    help='The build directory (ie. build/ARM).')
281
282parser.add_argument('--update-json', action='store_true',
283                    help='Update the json manifest of tests.')
284
285parser.add_argument('--flavor', choices=['debug', 'opt', 'fast'],
286                    default='opt',
287                    help='Flavor of binary to test.')
288
289parser.add_argument('--list', action='store_true',
290                    help='List the available tests')
291
292filter_opts = parser.add_mutually_exclusive_group()
293filter_opts.add_argument('--filter', default='True',
294                         help='Python expression which filters tests based '
295                         'on their properties')
296filter_opts.add_argument('--filter-file', default=None,
297                         type=argparse.FileType('r'),
298                         help='Same as --filter, but read from a file')
299
300def collect_phases(args):
301    phase_groups = [list(g) for k, g in
302                    itertools.groupby(args, lambda x: x != '--phase') if k]
303    main_args = parser.parse_args(phase_groups[0][1:])
304    phases = []
305    names = []
306    for group in phase_groups[1:]:
307        name = group[0]
308        if name in names:
309            raise RuntimeException('Phase %s specified more than once' % name)
310        phase = test_phase_classes[name]
311        phases.append(phase(main_args, *group[1:]))
312    phases.sort()
313    return main_args, phases
314
315main_args, phases = collect_phases(sys.argv)
316
317if len(phases) == 0:
318    phases = [
319        CompilePhase(main_args),
320        RunPhase(main_args),
321        VerifyPhase(main_args)
322    ]
323
324
325
326json_path = os.path.join(main_args.build_dir, json_rel_path)
327
328if main_args.update_json:
329    scons(os.path.join(json_path))
330
331with open(json_path) as f:
332    test_data = json.load(f)
333
334    if main_args.filter_file:
335        f = main_args.filter_file
336        filt = compile(f.read(), f.name, 'eval')
337    else:
338        filt = compile(main_args.filter, '<string>', 'eval')
339
340    filtered_tests = {
341        target: props for (target, props) in
342                    test_data.iteritems() if eval(filt, dict(props))
343    }
344
345    if main_args.list:
346        for target, props in sorted(filtered_tests.iteritems()):
347            print('%s.%s' % (target, main_args.flavor))
348            for key, val in props.iteritems():
349                print('    %s: %s' % (key, val))
350        print('Total tests: %d' % len(filtered_tests))
351    else:
352        tests_to_run = list([
353            Test(target, main_args.flavor, main_args.build_dir, props) for
354                target, props in sorted(filtered_tests.iteritems())
355        ])
356
357        for phase in phases:
358            phase.run(tests_to_run)
359