blob: 79b899eddf5b7d50f9359f136f9482935d137cd0 [file] [log] [blame]
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001#!/usr/bin/env python2
2# -*- coding: utf-8 -*-
3# Copyright 2018 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6"""Evaluate ChromeOS autotest.
7
8Note that by default 'test_that' will install dependency packages of autotest
9only once. For example, if you overwrote chrome's unittest binary, your new
Kuang-che Wu927231f2018-07-24 14:21:56 +080010binary will be persistent across autotest runs. Add --reinstall if you want
Kuang-che Wub9705bd2018-06-28 17:59:18 +080011clean autotest install.
12"""
13from __future__ import print_function
14import argparse
15import json
16import logging
17import os
18import re
19import subprocess
20import sys
21
22from bisect_kit import cli
23from bisect_kit import common
24from bisect_kit import configure
25from bisect_kit import cros_util
26from bisect_kit import util
27
28logger = logging.getLogger(__name__)
29
30OLD = 'old'
31NEW = 'new'
32SKIP = 'skip'
33FATAL = 'fatal'
34
35EXIT_CODE_MAP = {
36 OLD: 0,
37 NEW: 1,
38 SKIP: 125,
39 FATAL: 126,
40}
41
42
43def create_argument_parser():
44 parser = argparse.ArgumentParser(description=__doc__)
45 common.add_common_arguments(parser)
46 parser.add_argument(
47 'dut',
48 nargs='?',
49 type=cli.argtype_notempty,
50 metavar='DUT',
51 default=configure.get('DUT', ''))
52 parser.add_argument(
53 '--chromeos_root',
54 type=cli.argtype_dir_path,
55 metavar='CHROMEOS_ROOT',
56 default=configure.get('CHROMEOS_ROOT', ''),
57 help='ChromeOS tree root')
58 parser.add_argument(
Kuang-che Wud4603d72018-11-29 17:51:21 +080059 '--chrome_root',
60 metavar='CHROME_ROOT',
61 type=cli.argtype_dir_path,
62 default=configure.get('CHROME_ROOT'),
63 help='Chrome tree root; necessary for telemetry tests')
64 parser.add_argument(
Kuang-che Wub9705bd2018-06-28 17:59:18 +080065 '--prebuilt',
66 action='store_true',
67 help='Run autotest using existing prebuilt package if specified; '
68 'otherwise use the default one')
69 parser.add_argument(
70 '--reinstall',
71 action='store_true',
72 help='Remove existing autotest folder on the DUT first')
Kuang-che Wu85c613c2019-01-09 15:46:11 +080073
74 group = parser.add_argument_group(title='Options for normal autotest tests')
75 group.add_argument(
76 '--test_name', help='Test name, like "video_VideoDecodeAccelerator.h264"')
77 group.add_argument(
78 '--metric',
79 help=
80 'Metric name of performance test; example: "cheets_SystemRawImageSize"')
81 group.add_argument(
82 '--old_value',
83 type=float,
84 help='For performance test, old value of given metric')
85 group.add_argument(
86 '--new_value',
87 type=float,
88 help='For performance test, new value of given metric')
89 group.add_argument(
Kuang-che Wub9705bd2018-06-28 17:59:18 +080090 '--args',
91 help='Extra args passed to "test_that --args"; Overrides the default')
92
Kuang-che Wu85c613c2019-01-09 15:46:11 +080093 group = parser.add_argument_group(title='Options for CTS/GTS tests')
94 group.add_argument('--cts_revision', help='CTS revision, like "9.0_r3"')
95 group.add_argument('--cts_abi', choices=['arm', 'x86'])
96 group.add_argument(
97 '--cts_prefix',
98 help='Prefix of autotest test name, '
99 'like cheets_CTS_N, cheets_CTS_P, cheets_GTS')
100 group.add_argument(
101 '--cts_module', help='CTS/GTS module name, like "CtsCameraTestCases"')
102 group.add_argument(
103 '--cts_test',
104 help='CTS/GTS test name, like '
105 '"android.hardware.cts.CameraTest#testDisplayOrientation"')
106 group.add_argument('--cts_timeout', type=float, help='timeout, in seconds')
107
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800108 return parser
109
110
111def parse_test_report_log(result_log, metric):
112 """Parses autotest result log.
113
114 Args:
115 result_log: content of test_report.log
116 metric: what metric to capture if not None
117
118 Returns:
119 passed, values:
120 passed: True if test run successfully
121 values: captured metric values; None if test failed or metric is None
122 """
123 m = re.search(r'Total PASS: (\d+)/(\d+)', result_log)
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800124 passed = (m and m.group(1) == m.group(2))
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800125
126 if not metric:
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800127 return passed, None
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800128
129 values = []
130 for line in result_log.splitlines():
131 m = re.match(r'^(\S+)\s+(\w+)(?:\{\d+\})?\s+(\d+\.\d+)$', line)
132 if not m:
133 continue
134 if m.group(2) == metric:
135 values.append(float(m.group(3)))
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800136 return passed, values
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800137
138
139def parse_test_result_chart(json_path, metric):
140 data = json.load(open(json_path))
Kuang-che Wu3331caf2018-09-06 19:47:02 +0800141
142 # format 1, telemetry
143 if 'charts' in data:
144 summary = data['charts'][metric]['summary']
145
146 # format 2, autotest without graph
147 elif metric in data:
148 summary = data[metric]['summary']
149
150 # format 3, autotest with graph
151 elif metric.count('.') == 1:
152 name, subname = metric.split('.')
153 summary = data[name][subname]
154
155 else:
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800156 logger.error('metric "%s" not in %s', metric, json_path)
Kuang-che Wudd802672018-08-10 19:40:14 +0800157 return []
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800158
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800159 if 'values' in summary:
160 return summary['values']
161 return [summary['value']]
162
163
164def get_additional_test_args(test_name):
165 """Gets extra arguments to specific test.
166
167 Some tests may require special arguments to run.
168
169 Args:
170 test_name: test name
171
172 Returns:
173 arguments (str)
174 """
175 if test_name.startswith('telemetry_'):
176 return 'local=True'
177 return ''
178
179
180def run_test(opts):
181 """Runs an autotest test.
182
183 Args:
184 opts: An argparse.Namespace to hold command line arguments.
185
186 Returns:
187 path of test result (outside chroot)
188 """
189 if opts.reinstall:
190 util.check_call('ssh', opts.dut, 'rm', '-rf', '/usr/local/autotest')
191
192 prebuilt_autotest_dir = os.path.join(cros_util.chromeos_root_inside_chroot,
193 cros_util.prebuilt_autotest_dir)
194 # Set results dir inside source tree, so it's easier to access them outside
195 # chroot.
196 results_dir = os.path.join(cros_util.chromeos_root_inside_chroot,
197 'tmp/autotest_results_tmp')
198 if opts.prebuilt:
199 test_that_bin = os.path.join(prebuilt_autotest_dir,
200 'site_utils/test_that.py')
201 else:
202 test_that_bin = '/usr/bin/test_that'
203 cmd = [test_that_bin, opts.dut, opts.test_name, '--results_dir', results_dir]
204 if opts.prebuilt:
205 cmd += ['--autotest_dir', prebuilt_autotest_dir]
206
207 args = get_additional_test_args(opts.test_name)
208 if opts.args:
209 if args:
Kuang-che Wu74768d32018-09-07 12:03:24 +0800210 logger.info(
211 'default test_that args `%s` is overridden by '
212 'command line option `%s`', args, opts.args)
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800213 cmd += ['--args', opts.args]
214 elif args:
215 cmd += ['--args', args]
216
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800217 try:
Kuang-che Wud4603d72018-11-29 17:51:21 +0800218 output = cros_util.cros_sdk(
219 opts.chromeos_root, *cmd, chrome_root=opts.chrome_root)
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800220 except subprocess.CalledProcessError as e:
221 output = e.output
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800222
223 m = re.search(r'Finished running tests. Results can be found in (\S+)',
224 output)
225 if not m:
226 logger.error('result dir is unknown')
227 return None
228 assert m.group(1) == results_dir
229 return results_dir.replace(cros_util.chromeos_root_inside_chroot,
230 opts.chromeos_root)
231
232
233def gather_test_result(opts, result_dir):
234 result_log_path = os.path.join(result_dir, 'test_report.log')
235 result_log = open(result_log_path).read()
236
237 passed, values = parse_test_report_log(result_log, opts.metric)
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800238 if opts.metric and not values:
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800239 values = []
240 for root, _, files in os.walk(result_dir):
241 for filename in files:
242 if filename != 'results-chart.json':
243 continue
244 full_path = os.path.join(root, filename)
245 values += parse_test_result_chart(full_path, opts.metric)
246
247 return passed, values
248
249
250def main(args=None):
251 common.init()
252 parser = create_argument_parser()
253 opts = parser.parse_args(args)
254 common.config_logging(opts)
255
256 if not cros_util.is_dut(opts.dut):
257 return FATAL
258
Kuang-che Wu85c613c2019-01-09 15:46:11 +0800259 is_cts = (
260 opts.cts_revision or opts.cts_abi or opts.cts_prefix or opts.cts_module or
261 opts.cts_test or opts.cts_timeout)
262 if is_cts:
263 if opts.test_name or opts.metric or opts.args:
264 parser.error(
265 'do not specify --test_name, --metric, --args for CTS/GTS tests')
266 opts.test_name = '%s.tradefed-run-test' % opts.cts_prefix
267 opts.args = 'module=%s test=%s' % (opts.cts_module, opts.cts_test)
268 if opts.cts_revision:
269 opts.args += ' revision=%s' % opts.cts_revision
270 if opts.cts_abi:
271 opts.args += ' abi=%s' % opts.cts_abi
272 if opts.cts_timeout:
273 opts.args += ' timeout=%s' % opts.cts_timeout
274 else:
275 if not opts.test_name:
276 parser.error('argument --test_name is required')
277
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800278 # Verify command line options.
279 if opts.metric:
280 if opts.old_value is None:
281 logger.error('--old_value is not provided')
282 return FATAL
283 if opts.new_value is None:
284 logger.error('--new_value is not provided')
285 return FATAL
286 else:
287 if opts.old_value is not None:
288 logger.error('--old_value is provided but --metric is not')
289 return FATAL
290 if opts.new_value is not None:
291 logger.error('--new_value is provided but --metric is not')
292 return FATAL
Kuang-che Wud4603d72018-11-29 17:51:21 +0800293 if opts.test_name.startswith('telemetry_'):
294 if not opts.chrome_root:
295 logger.error('--chrome_root is mandatory for telemetry tests')
296 return FATAL
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800297
Kuang-che Wue47162d2018-10-29 17:24:04 +0800298 # Some versions of ChromeOS SDK is broken and ship bad 'ssh' executable. This
299 # works around the issue before we fixed the issue.
300 # TODO(kcwu): fix crbug/899490
301 cros_util.cros_sdk(opts.chromeos_root, 'sudo', 'emerge', 'net-misc/openssh')
302
Kuang-che Wu171dcb62018-10-25 12:37:05 +0800303 result_dir = run_test(opts)
304 if not result_dir:
Kuang-che Wudd802672018-08-10 19:40:14 +0800305 return FATAL
306
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800307 passed, values = gather_test_result(opts, result_dir)
308
309 if opts.metric:
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800310 if not values:
311 logger.warning('no values found; SKIP')
312 return SKIP
313
314 print('BISECT_RESULT_VALUES=', ' '.join(map(str, values)))
315 average = float(sum(values)) / len(values)
Kuang-che Wu689f1542018-08-20 17:45:58 +0800316 if abs(average - opts.old_value) < abs(average - opts.new_value):
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800317 logger.info('values=%s, average=%s; OLD', values, average)
318 return OLD
319 logger.info('values=%s, average=%s; NEW', values, average)
320 return NEW
321 else:
322 if passed:
323 logger.info('passed')
324 return OLD
325 logger.info('failed')
326 return NEW
327
328
329if __name__ == '__main__':
330 sys.exit(EXIT_CODE_MAP[main()])