Deleted Added
sdiff udiff text old ( 13056:f483df6334a5 ) new ( 13100:fc7df026c235 )
full compact
1#!/usr/bin/env python2
2#
3# Copyright 2018 Google, Inc.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met: redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer;
9# redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the
11# documentation and/or other materials provided with the distribution;
12# neither the name of the copyright holders nor the names of its
13# contributors may be used to endorse or promote products derived from
14# this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27#
28# Authors: Gabe Black
29
30from __future__ import print_function
31
32import argparse
33import collections
34import difflib
35import functools
36import inspect
37import itertools
38import json
39import multiprocessing.pool
40import os
41import re
42import subprocess
43import sys
44
45script_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
46script_dir = os.path.dirname(script_path)
47config_path = os.path.join(script_dir, 'config.py')
48
49systemc_rel_path = 'systemc'
50tests_rel_path = os.path.join(systemc_rel_path, 'tests')
51json_rel_path = os.path.join(tests_rel_path, 'tests.json')
52
53
54
55def scons(*args):
56 args = ['scons'] + list(args)
57 subprocess.check_call(args)
58
59
60
61class Test(object):
62 def __init__(self, target, suffix, build_dir, props):
63 self.target = target
64 self.suffix = suffix
65 self.build_dir = build_dir
66 self.props = {}
67
68 for key, val in props.iteritems():
69 self.set_prop(key, val)
70
71 def set_prop(self, key, val):
72 setattr(self, key, val)
73 self.props[key] = val
74
75 def dir(self):
76 return os.path.join(self.build_dir, tests_rel_path, self.path)
77
78 def src_dir(self):
79 return os.path.join(script_dir, self.path)
80
81 def golden_dir(self):
82 return os.path.join(self.src_dir(), 'golden')
83
84 def bin(self):
85 return '.'.join([self.name, self.suffix])
86
87 def full_path(self):
88 return os.path.join(self.dir(), self.bin())
89
90 def m5out_dir(self):
91 return os.path.join(self.dir(), 'm5out.' + self.suffix)
92
93 def returncode_file(self):
94 return os.path.join(self.m5out_dir(), 'returncode')
95
96
97
98test_phase_classes = {}
99
100class TestPhaseMeta(type):
101 def __init__(cls, name, bases, d):
102 if not d.pop('abstract', False):
103 test_phase_classes[d['name']] = cls
104
105 super(TestPhaseMeta, cls).__init__(name, bases, d)
106
107class TestPhaseBase(object):
108 __metaclass__ = TestPhaseMeta
109 abstract = True
110
111 def __init__(self, main_args, *args):
112 self.main_args = main_args
113 self.args = args
114
115 def __lt__(self, other):
116 return self.number < other.number
117
118class CompilePhase(TestPhaseBase):
119 name = 'compile'
120 number = 1
121
122 def run(self, tests):
123 targets = list([test.full_path() for test in tests])
124 scons_args = [ 'USE_SYSTEMC=1' ] + list(self.args) + targets
125 scons(*scons_args)
126
127class RunPhase(TestPhaseBase):
128 name = 'execute'
129 number = 2
130
131 def run(self, tests):
132 parser = argparse.ArgumentParser()
133 parser.add_argument('--timeout', type=int, metavar='SECONDS',
134 help='Time limit for each run in seconds.',
135 default=0)
136 parser.add_argument('-j', type=int, default=1,
137 help='How many tests to run in parallel.')
138 args = parser.parse_args(self.args)
139
140 timeout_cmd = [
141 'timeout',
142 '--kill-after', str(args.timeout * 2),
143 str(args.timeout)
144 ]
145 def run_test(test):
146 cmd = []
147 if args.timeout:
148 cmd.extend(timeout_cmd)
149 cmd.extend([
150 test.full_path(),
151 '-red', test.m5out_dir(),
152 '--listener-mode=off',
153 '--quiet',
154 config_path
155 ])
156 # Ensure the output directory exists.
157 if not os.path.exists(test.m5out_dir()):
158 os.makedirs(test.m5out_dir())
159 try:
160 subprocess.check_call(cmd)
161 except subprocess.CalledProcessError, error:
162 returncode = error.returncode
163 else:
164 returncode = 0
165 with open(test.returncode_file(), 'w') as rc:
166 rc.write('%d\n' % returncode)
167
168 runnable = filter(lambda t: not t.compile_only, tests)
169 if args.j == 1:
170 map(run_test, runnable)
171 else:
172 tp = multiprocessing.pool.ThreadPool(args.j)
173 map(lambda t: tp.apply_async(run_test, (t,)), runnable)
174 tp.close()
175 tp.join()
176
177class Checker(object):
178 def __init__(self, ref, test, tag):
179 self.ref = ref
180 self.test = test
181 self.tag = tag
182
183 def check(self):
184 with open(self.text) as test_f, open(self.ref) as ref_f:
185 return test_f.read() == ref_f.read()
186
187def tagged_filt(tag, num):
188 return (r'^\n{}: \({}{}\) .*\n(In file: .*\n)?'
189 r'(In process: [\w.]* @ .*\n)?').format(tag, tag[0], num)
190
191def warning_filt(num):
192 return tagged_filt('Warning', num)
193
194def info_filt(num):
195 return tagged_filt('Info', num)
196
197class LogChecker(Checker):
198 def merge_filts(*filts):
199 filts = map(lambda f: '(' + f + ')', filts)
200 filts = '|'.join(filts)
201 return re.compile(filts, flags=re.MULTILINE)
202
203 ref_filt = merge_filts(
204 r'^\nInfo: /OSCI/SystemC: Simulation stopped by user.\n',
205 r'^SystemC Simulation\n',
206 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: ' +
207 r'You can turn off(.*\n){7}',
208 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: \n' +
209 r' sc_clock\(const char(.*\n){3}',
210 warning_filt(540),
211 warning_filt(569),
212 warning_filt(571),
213 info_filt(804),
214 )
215 test_filt = merge_filts(
216 r'^Global frequency set at \d* ticks per second\n',
217 info_filt(804),
218 )
219
220 def __init__(self, ref, test, tag, out_dir):
221 super(LogChecker, self).__init__(ref, test, tag)
222 self.out_dir = out_dir
223
224 def apply_filters(self, data, filts):
225 re.sub(filt, '', data)
226
227 def check(self):
228 test_file = os.path.basename(self.test)
229 ref_file = os.path.basename(self.ref)
230 with open(self.test) as test_f, open(self.ref) as ref_f:
231 test = re.sub(self.test_filt, '', test_f.read())
232 ref = re.sub(self.ref_filt, '', ref_f.read())
233 diff_file = '.'.join([ref_file, 'diff'])
234 diff_path = os.path.join(self.out_dir, diff_file)
235 if test != ref:
236 with open(diff_path, 'w') as diff_f:
237 for line in difflib.unified_diff(
238 ref.splitlines(True), test.splitlines(True),
239 fromfile=ref_file,
240 tofile=test_file):
241 diff_f.write(line)
242 return False
243 else:
244 if os.path.exists(diff_path):
245 os.unlink(diff_path)
246 return True
247
248class GoldenDir(object):
249 def __init__(self, path, platform):
250 self.path = path
251 self.platform = platform
252
253 contents = os.listdir(path)
254 suffix = '.' + platform
255 suffixed = filter(lambda c: c.endswith(suffix), contents)
256 bases = map(lambda t: t[:-len(platform)], suffixed)
257 common = filter(lambda t: not t.startswith(tuple(bases)), contents)
258
259 self.entries = {}
260 class Entry(object):
261 def __init__(self, e_path):
262 self.used = False
263 self.path = os.path.join(path, e_path)
264
265 def use(self):
266 self.used = True
267
268 for entry in contents:
269 self.entries[entry] = Entry(entry)
270
271 def entry(self, name):
272 def match(n):
273 return (n == name) or n.startswith(name + '.')
274 matches = { n: e for n, e in self.entries.items() if match(n) }
275
276 for match in matches.values():
277 match.use()
278
279 platform_name = '.'.join([ name, self.platform ])
280 if platform_name in matches:
281 return matches[platform_name].path
282 if name in matches:
283 return matches[name].path
284 else:
285 return None
286
287 def unused(self):
288 items = self.entries.items()
289 items = filter(lambda i: not i[1].used, items)
290
291 items.sort()
292 sources = []
293 i = 0
294 while i < len(items):
295 root = items[i][0]
296 sources.append(root)
297 i += 1
298 while i < len(items) and items[i][0].startswith(root):
299 i += 1
300 return sources
301
302class VerifyPhase(TestPhaseBase):
303 name = 'verify'
304 number = 3
305
306 def reset_status(self):
307 self._passed = []
308 self._failed = {}
309
310 def passed(self, test):
311 self._passed.append(test)
312
313 def failed(self, test, cause, note=''):
314 test.set_prop('note', note)
315 self._failed.setdefault(cause, []).append(test)
316
317 def print_status(self):
318 total_passed = len(self._passed)
319 total_failed = sum(map(len, self._failed.values()))
320 print()
321 print('Passed: {passed:4} - Failed: {failed:4}'.format(
322 passed=total_passed, failed=total_failed))
323
324 def write_result_file(self, path):
325 results = {
326 'passed': map(lambda t: t.props, self._passed),
327 'failed': {
328 cause: map(lambda t: t.props, tests) for
329 cause, tests in self._failed.iteritems()
330 }
331 }
332 with open(path, 'w') as rf:
333 json.dump(results, rf)
334
335 def print_results(self):
336 print()
337 print('Passed:')
338 for path in sorted(list([ t.path for t in self._passed ])):
339 print(' ', path)
340
341 print()
342 print('Failed:')
343
344 causes = []
345 for cause, tests in sorted(self._failed.items()):
346 block = ' ' + cause.capitalize() + ':\n'
347 for test in sorted(tests, key=lambda t: t.path):
348 block += ' ' + test.path
349 if test.note:
350 block += ' - ' + test.note
351 block += '\n'
352 causes.append(block)
353
354 print('\n'.join(causes))
355
356 def run(self, tests):
357 parser = argparse.ArgumentParser()
358 result_opts = parser.add_mutually_exclusive_group()
359 result_opts.add_argument('--result-file', action='store_true',
360 help='Create a results.json file in the current directory.')
361 result_opts.add_argument('--result-file-at', metavar='PATH',
362 help='Create a results json file at the given path.')
363 parser.add_argument('--print-results', action='store_true',
364 help='Print a list of tests that passed or failed')
365 args = parser.parse_args(self.args)
366
367 self.reset_status()
368
369 runnable = filter(lambda t: not t.compile_only, tests)
370 compile_only = filter(lambda t: t.compile_only, tests)
371
372 for test in compile_only:
373 if os.path.exists(test.full_path()):
374 self.passed(test)
375 else:
376 self.failed(test, 'compile failed')
377
378 for test in runnable:
379 with open(test.returncode_file()) as rc:
380 returncode = int(rc.read())
381
382 if returncode == 124:
383 self.failed(test, 'time out')
384 continue
385 elif returncode != 0:
386 self.failed(test, 'abort')
387 continue
388
389 out_dir = test.m5out_dir()
390
391 Diff = collections.namedtuple(
392 'Diff', 'ref, test, tag, ref_filter')
393
394 diffs = []
395
396 gd = GoldenDir(test.golden_dir(), 'linux64')
397
398 missing = []
399 log_file = '.'.join([test.name, 'log'])
400 log_path = gd.entry(log_file)
401 simout_path = os.path.join(out_dir, 'simout')
402 if not os.path.exists(simout_path):
403 missing.append('log output')
404 elif log_path:
405 diffs.append(LogChecker(log_path, simout_path,
406 log_file, out_dir))
407
408 for name in gd.unused():
409 test_path = os.path.join(out_dir, name)
410 ref_path = gd.entry(name)
411 if not os.path.exists(test_path):
412 missing.append(name)
413 else:
414 diffs.append(Checker(ref_path, test_path, name))
415
416 if missing:
417 self.failed(test, 'missing output', ' '.join(missing))
418 continue
419
420 failed_diffs = filter(lambda d: not d.check(), diffs)
421 if failed_diffs:
422 tags = map(lambda d: d.tag, failed_diffs)
423 self.failed(test, 'failed diffs', ' '.join(tags))
424 continue
425
426 self.passed(test)
427
428 if args.print_results:
429 self.print_results()
430
431 self.print_status()
432
433 result_path = None
434 if args.result_file:
435 result_path = os.path.join(os.getcwd(), 'results.json')
436 elif args.result_file_at:
437 result_path = args.result_file_at
438
439 if result_path:
440 self.write_result_file(result_path)
441
442
443parser = argparse.ArgumentParser(description='SystemC test utility')
444
445parser.add_argument('build_dir', metavar='BUILD_DIR',
446 help='The build directory (ie. build/ARM).')
447
448parser.add_argument('--update-json', action='store_true',
449 help='Update the json manifest of tests.')
450
451parser.add_argument('--flavor', choices=['debug', 'opt', 'fast'],
452 default='opt',
453 help='Flavor of binary to test.')
454
455parser.add_argument('--list', action='store_true',
456 help='List the available tests')
457
458filter_opts = parser.add_mutually_exclusive_group()
459filter_opts.add_argument('--filter', default='True',
460 help='Python expression which filters tests based '
461 'on their properties')
462filter_opts.add_argument('--filter-file', default=None,
463 type=argparse.FileType('r'),
464 help='Same as --filter, but read from a file')
465
466def collect_phases(args):
467 phase_groups = [list(g) for k, g in
468 itertools.groupby(args, lambda x: x != '--phase') if k]
469 main_args = parser.parse_args(phase_groups[0][1:])
470 phases = []
471 names = []
472 for group in phase_groups[1:]:
473 name = group[0]
474 if name in names:
475 raise RuntimeException('Phase %s specified more than once' % name)
476 phase = test_phase_classes[name]
477 phases.append(phase(main_args, *group[1:]))
478 phases.sort()
479 return main_args, phases
480
481main_args, phases = collect_phases(sys.argv)
482
483if len(phases) == 0:
484 phases = [
485 CompilePhase(main_args),
486 RunPhase(main_args),
487 VerifyPhase(main_args)
488 ]
489
490
491
492json_path = os.path.join(main_args.build_dir, json_rel_path)
493
494if main_args.update_json:
495 scons(os.path.join(json_path))
496
497with open(json_path) as f:
498 test_data = json.load(f)
499
500 if main_args.filter_file:
501 f = main_args.filter_file
502 filt = compile(f.read(), f.name, 'eval')
503 else:
504 filt = compile(main_args.filter, '<string>', 'eval')
505
506 filtered_tests = {
507 target: props for (target, props) in
508 test_data.iteritems() if eval(filt, dict(props))
509 }
510
511 if main_args.list:
512 for target, props in sorted(filtered_tests.iteritems()):
513 print('%s.%s' % (target, main_args.flavor))
514 for key, val in props.iteritems():
515 print(' %s: %s' % (key, val))
516 print('Total tests: %d' % len(filtered_tests))
517 else:
518 tests_to_run = list([
519 Test(target, main_args.flavor, main_args.build_dir, props) for
520 target, props in sorted(filtered_tests.iteritems())
521 ])
522
523 for phase in phases:
524 phase.run(tests_to_run)