Revert of Remove OneClickSigninHelper since it is no longer used. (patchset #5 id...
[chromium-blink-merge.git] / build / android / buildbot / bb_device_steps.py
blobc9be13a045d26f404da1a804365f67c11fd52bb8
1 #!/usr/bin/env python
2 # Copyright (c) 2013 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 import collections
7 import glob
8 import hashlib
9 import json
10 import os
11 import random
12 import re
13 import shutil
14 import sys
16 import bb_utils
17 import bb_annotations
19 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
20 import provision_devices
21 from pylib import android_commands
22 from pylib import constants
23 from pylib.device import device_utils
24 from pylib.gtest import gtest_config
26 CHROME_SRC_DIR = bb_utils.CHROME_SRC
27 DIR_BUILD_ROOT = os.path.dirname(CHROME_SRC_DIR)
28 CHROME_OUT_DIR = bb_utils.CHROME_OUT_DIR
29 BLINK_SCRIPTS_DIR = 'third_party/WebKit/Tools/Scripts'
31 SLAVE_SCRIPTS_DIR = os.path.join(bb_utils.BB_BUILD_DIR, 'scripts', 'slave')
32 LOGCAT_DIR = os.path.join(bb_utils.CHROME_OUT_DIR, 'logcat')
33 GS_URL = 'https://storage.googleapis.com'
34 GS_AUTH_URL = 'https://storage.cloud.google.com'
36 # Describes an instrumation test suite:
37 # test: Name of test we're running.
38 # apk: apk to be installed.
39 # apk_package: package for the apk to be installed.
40 # test_apk: apk to run tests on.
41 # test_data: data folder in format destination:source.
42 # host_driven_root: The host-driven test root directory.
43 # annotation: Annotation of the tests to include.
44 # exclude_annotation: The annotation of the tests to exclude.
45 I_TEST = collections.namedtuple('InstrumentationTest', [
46 'name', 'apk', 'apk_package', 'test_apk', 'test_data', 'isolate_file_path',
47 'host_driven_root', 'annotation', 'exclude_annotation', 'extra_flags'])
50 def SrcPath(*path):
51 return os.path.join(CHROME_SRC_DIR, *path)
54 def I(name, apk, apk_package, test_apk, test_data, isolate_file_path=None,
55 host_driven_root=None, annotation=None, exclude_annotation=None,
56 extra_flags=None):
57 return I_TEST(name, apk, apk_package, test_apk, test_data, isolate_file_path,
58 host_driven_root, annotation, exclude_annotation, extra_flags)
60 INSTRUMENTATION_TESTS = dict((suite.name, suite) for suite in [
61 I('ContentShell',
62 'ContentShell.apk',
63 'org.chromium.content_shell_apk',
64 'ContentShellTest',
65 'content:content/test/data/android/device_files',
66 isolate_file_path='content/content_shell_test_apk.isolate'),
67 I('ChromeShell',
68 'ChromeShell.apk',
69 'org.chromium.chrome.shell',
70 'ChromeShellTest',
71 'chrome:chrome/test/data/android/device_files',
72 isolate_file_path='chrome/chrome_shell_test_apk.isolate',
73 host_driven_root=constants.CHROME_SHELL_HOST_DRIVEN_DIR),
74 I('AndroidWebView',
75 'AndroidWebView.apk',
76 'org.chromium.android_webview.shell',
77 'AndroidWebViewTest',
78 'webview:android_webview/test/data/device_files',
79 isolate_file_path='android_webview/android_webview_test_apk.isolate'),
80 I('ChromeSyncShell',
81 'ChromeSyncShell.apk',
82 'org.chromium.chrome.browser.sync',
83 'ChromeSyncShellTest',
84 None),
87 InstallablePackage = collections.namedtuple('InstallablePackage', [
88 'name', 'apk', 'apk_package'])
90 INSTALLABLE_PACKAGES = dict((package.name, package) for package in (
91 [InstallablePackage(i.name, i.apk, i.apk_package)
92 for i in INSTRUMENTATION_TESTS.itervalues()] +
93 [InstallablePackage('ChromeDriverWebViewShell',
94 'ChromeDriverWebViewShell.apk',
95 'org.chromium.chromedriver_webview_shell')]))
97 VALID_TESTS = set(['chromedriver', 'chrome_proxy', 'gpu',
98 'telemetry_unittests', 'telemetry_perf_unittests', 'ui',
99 'unit', 'webkit', 'webkit_layout', 'python_unittests'])
101 RunCmd = bb_utils.RunCmd
104 def _GetRevision(options):
105 """Get the SVN revision number.
107 Args:
108 options: options object.
110 Returns:
111 The revision number.
113 revision = options.build_properties.get('got_revision')
114 if not revision:
115 revision = options.build_properties.get('revision', 'testing')
116 return revision
119 def _RunTest(options, cmd, suite):
120 """Run test command with runtest.py.
122 Args:
123 options: options object.
124 cmd: the command to run.
125 suite: test name.
127 property_args = bb_utils.EncodeProperties(options)
128 args = [os.path.join(SLAVE_SCRIPTS_DIR, 'runtest.py')] + property_args
129 args += ['--test-platform', 'android']
130 if options.factory_properties.get('generate_gtest_json'):
131 args.append('--generate-json-file')
132 args += ['-o', 'gtest-results/%s' % suite,
133 '--annotate', 'gtest',
134 '--build-number', str(options.build_properties.get('buildnumber',
135 '')),
136 '--builder-name', options.build_properties.get('buildername', '')]
137 if options.target == 'Release':
138 args += ['--target', 'Release']
139 else:
140 args += ['--target', 'Debug']
141 if options.flakiness_server:
142 args += ['--flakiness-dashboard-server=%s' %
143 options.flakiness_server]
144 args += cmd
145 RunCmd(args, cwd=DIR_BUILD_ROOT)
148 def RunTestSuites(options, suites, suites_options=None):
149 """Manages an invocation of test_runner.py for gtests.
151 Args:
152 options: options object.
153 suites: List of suite names to run.
154 suites_options: Command line options dictionary for particular suites.
155 For example,
156 {'content_browsertests', ['--num_retries=1', '--release']}
157 will add the options only to content_browsertests.
160 if not suites_options:
161 suites_options = {}
163 args = ['--verbose']
164 if options.target == 'Release':
165 args.append('--release')
166 if options.asan:
167 args.append('--tool=asan')
168 if options.gtest_filter:
169 args.append('--gtest-filter=%s' % options.gtest_filter)
171 for suite in suites:
172 bb_annotations.PrintNamedStep(suite)
173 cmd = [suite] + args
174 cmd += suites_options.get(suite, [])
175 if suite == 'content_browsertests':
176 cmd.append('--num_retries=1')
177 _RunTest(options, cmd, suite)
180 def RunChromeDriverTests(options):
181 """Run all the steps for running chromedriver tests."""
182 bb_annotations.PrintNamedStep('chromedriver_annotation')
183 RunCmd(['chrome/test/chromedriver/run_buildbot_steps.py',
184 '--android-packages=%s,%s,%s,%s' %
185 ('chrome_shell',
186 'chrome_stable',
187 'chrome_beta',
188 'chromedriver_webview_shell'),
189 '--revision=%s' % _GetRevision(options),
190 '--update-log'])
192 def RunChromeProxyTests(options):
193 """Run the chrome_proxy tests.
195 Args:
196 options: options object.
198 InstallApk(options, INSTRUMENTATION_TESTS['ChromeShell'], False)
199 args = ['--browser', 'android-chrome-shell']
200 devices = android_commands.GetAttachedDevices()
201 if devices:
202 args = args + ['--device', devices[0]]
203 bb_annotations.PrintNamedStep('chrome_proxy')
204 RunCmd(['tools/chrome_proxy/run_tests'] + args)
207 def RunTelemetryTests(options, step_name, run_tests_path):
208 """Runs either telemetry_perf_unittests or telemetry_unittests.
210 Args:
211 options: options object.
212 step_name: either 'telemetry_unittests' or 'telemetry_perf_unittests'
213 run_tests_path: path to run_tests script (tools/perf/run_tests for
214 perf_unittests and tools/telemetry/run_tests for
215 telemetry_unittests)
217 InstallApk(options, INSTRUMENTATION_TESTS['ChromeShell'], False)
218 args = ['--browser', 'android-chrome-shell']
219 devices = android_commands.GetAttachedDevices()
220 if devices:
221 args = args + ['--device', 'android']
222 bb_annotations.PrintNamedStep(step_name)
223 RunCmd([run_tests_path] + args)
226 def InstallApk(options, test, print_step=False):
227 """Install an apk to all phones.
229 Args:
230 options: options object
231 test: An I_TEST namedtuple
232 print_step: Print a buildbot step
234 if print_step:
235 bb_annotations.PrintNamedStep('install_%s' % test.name.lower())
237 args = ['--apk_package', test.apk_package]
238 if options.target == 'Release':
239 args.append('--release')
240 args.append(test.apk)
242 RunCmd(['build/android/adb_install_apk.py'] + args, halt_on_failure=True)
245 def RunInstrumentationSuite(options, test, flunk_on_failure=True,
246 python_only=False, official_build=False):
247 """Manages an invocation of test_runner.py for instrumentation tests.
249 Args:
250 options: options object
251 test: An I_TEST namedtuple
252 flunk_on_failure: Flunk the step if tests fail.
253 Python: Run only host driven Python tests.
254 official_build: Run official-build tests.
256 bb_annotations.PrintNamedStep('%s_instrumentation_tests' % test.name.lower())
258 if test.apk:
259 InstallApk(options, test)
260 args = ['--test-apk', test.test_apk, '--verbose']
261 if test.test_data:
262 args.extend(['--test_data', test.test_data])
263 if options.target == 'Release':
264 args.append('--release')
265 if options.asan:
266 args.append('--tool=asan')
267 if options.flakiness_server:
268 args.append('--flakiness-dashboard-server=%s' %
269 options.flakiness_server)
270 if options.coverage_bucket:
271 args.append('--coverage-dir=%s' % options.coverage_dir)
272 if test.isolate_file_path:
273 args.append('--isolate-file-path=%s' % test.isolate_file_path)
274 if test.host_driven_root:
275 args.append('--host-driven-root=%s' % test.host_driven_root)
276 if test.annotation:
277 args.extend(['-A', test.annotation])
278 if test.exclude_annotation:
279 args.extend(['-E', test.exclude_annotation])
280 if test.extra_flags:
281 args.extend(test.extra_flags)
282 if python_only:
283 args.append('-p')
284 if official_build:
285 # The option needs to be assigned 'True' as it does not have an action
286 # associated with it.
287 args.append('--official-build')
289 RunCmd(['build/android/test_runner.py', 'instrumentation'] + args,
290 flunk_on_failure=flunk_on_failure)
293 def RunWebkitLint():
294 """Lint WebKit's TestExpectation files."""
295 bb_annotations.PrintNamedStep('webkit_lint')
296 RunCmd([SrcPath(os.path.join(BLINK_SCRIPTS_DIR, 'lint-test-expectations'))])
299 def RunWebkitLayoutTests(options):
300 """Run layout tests on an actual device."""
301 bb_annotations.PrintNamedStep('webkit_tests')
302 cmd_args = [
303 '--no-show-results',
304 '--no-new-test-results',
305 '--full-results-html',
306 '--clobber-old-results',
307 '--exit-after-n-failures', '5000',
308 '--exit-after-n-crashes-or-timeouts', '100',
309 '--debug-rwt-logging',
310 '--results-directory', '../layout-test-results',
311 '--target', options.target,
312 '--builder-name', options.build_properties.get('buildername', ''),
313 '--build-number', str(options.build_properties.get('buildnumber', '')),
314 '--master-name', 'ChromiumWebkit', # TODO: Get this from the cfg.
315 '--build-name', options.build_properties.get('buildername', ''),
316 '--platform=android']
318 for flag in 'test_results_server', 'driver_name', 'additional_drt_flag':
319 if flag in options.factory_properties:
320 cmd_args.extend(['--%s' % flag.replace('_', '-'),
321 options.factory_properties.get(flag)])
323 for f in options.factory_properties.get('additional_expectations', []):
324 cmd_args.extend(
325 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
327 # TODO(dpranke): Remove this block after
328 # https://codereview.chromium.org/12927002/ lands.
329 for f in options.factory_properties.get('additional_expectations_files', []):
330 cmd_args.extend(
331 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
333 exit_code = RunCmd(
334 [SrcPath(os.path.join(BLINK_SCRIPTS_DIR, 'run-webkit-tests'))] + cmd_args)
335 if exit_code == 255: # test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
336 bb_annotations.PrintMsg('?? (crashed or hung)')
337 elif exit_code == 254: # test_run_results.NO_DEVICES_EXIT_STATUS
338 bb_annotations.PrintMsg('?? (no devices found)')
339 elif exit_code == 253: # test_run_results.NO_TESTS_EXIT_STATUS
340 bb_annotations.PrintMsg('?? (no tests found)')
341 else:
342 full_results_path = os.path.join('..', 'layout-test-results',
343 'full_results.json')
344 if os.path.exists(full_results_path):
345 full_results = json.load(open(full_results_path))
346 unexpected_passes, unexpected_failures, unexpected_flakes = (
347 _ParseLayoutTestResults(full_results))
348 if unexpected_failures:
349 _PrintDashboardLink('failed', unexpected_failures.keys(),
350 max_tests=25)
351 elif unexpected_passes:
352 _PrintDashboardLink('unexpected passes', unexpected_passes.keys(),
353 max_tests=10)
354 if unexpected_flakes:
355 _PrintDashboardLink('unexpected flakes', unexpected_flakes.keys(),
356 max_tests=10)
358 if exit_code == 0 and (unexpected_passes or unexpected_flakes):
359 # If exit_code != 0, RunCmd() will have already printed an error.
360 bb_annotations.PrintWarning()
361 else:
362 bb_annotations.PrintError()
363 bb_annotations.PrintMsg('?? (results missing)')
365 if options.factory_properties.get('archive_webkit_results', False):
366 bb_annotations.PrintNamedStep('archive_webkit_results')
367 base = 'https://storage.googleapis.com/chromium-layout-test-archives'
368 builder_name = options.build_properties.get('buildername', '')
369 build_number = str(options.build_properties.get('buildnumber', ''))
370 results_link = '%s/%s/%s/layout-test-results/results.html' % (
371 base, EscapeBuilderName(builder_name), build_number)
372 bb_annotations.PrintLink('results', results_link)
373 bb_annotations.PrintLink('(zip)', '%s/%s/%s/layout-test-results.zip' % (
374 base, EscapeBuilderName(builder_name), build_number))
375 gs_bucket = 'gs://chromium-layout-test-archives'
376 RunCmd([os.path.join(SLAVE_SCRIPTS_DIR, 'chromium',
377 'archive_layout_test_results.py'),
378 '--results-dir', '../../layout-test-results',
379 '--build-number', build_number,
380 '--builder-name', builder_name,
381 '--gs-bucket', gs_bucket],
382 cwd=DIR_BUILD_ROOT)
385 def _ParseLayoutTestResults(results):
386 """Extract the failures from the test run."""
387 # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
388 tests = _ConvertTrieToFlatPaths(results['tests'])
389 failures = {}
390 flakes = {}
391 passes = {}
392 for (test, result) in tests.iteritems():
393 if result.get('is_unexpected'):
394 actual_results = result['actual'].split()
395 expected_results = result['expected'].split()
396 if len(actual_results) > 1:
397 # We report the first failure type back, even if the second
398 # was more severe.
399 if actual_results[1] in expected_results:
400 flakes[test] = actual_results[0]
401 else:
402 failures[test] = actual_results[0]
403 elif actual_results[0] == 'PASS':
404 passes[test] = result
405 else:
406 failures[test] = actual_results[0]
408 return (passes, failures, flakes)
411 def _ConvertTrieToFlatPaths(trie, prefix=None):
412 """Flatten the trie of failures into a list."""
413 # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
414 result = {}
415 for name, data in trie.iteritems():
416 if prefix:
417 name = prefix + '/' + name
419 if len(data) and 'actual' not in data and 'expected' not in data:
420 result.update(_ConvertTrieToFlatPaths(data, name))
421 else:
422 result[name] = data
424 return result
427 def _PrintDashboardLink(link_text, tests, max_tests):
428 """Add a link to the flakiness dashboard in the step annotations."""
429 if len(tests) > max_tests:
430 test_list_text = ' '.join(tests[:max_tests]) + ' and more'
431 else:
432 test_list_text = ' '.join(tests)
434 dashboard_base = ('http://test-results.appspot.com'
435 '/dashboards/flakiness_dashboard.html#'
436 'master=ChromiumWebkit&tests=')
438 bb_annotations.PrintLink('%d %s: %s' %
439 (len(tests), link_text, test_list_text),
440 dashboard_base + ','.join(tests))
443 def EscapeBuilderName(builder_name):
444 return re.sub('[ ()]', '_', builder_name)
447 def SpawnLogcatMonitor():
448 shutil.rmtree(LOGCAT_DIR, ignore_errors=True)
449 bb_utils.SpawnCmd([
450 os.path.join(CHROME_SRC_DIR, 'build', 'android', 'adb_logcat_monitor.py'),
451 LOGCAT_DIR])
453 # Wait for logcat_monitor to pull existing logcat
454 RunCmd(['sleep', '5'])
457 def ProvisionDevices(options):
458 bb_annotations.PrintNamedStep('provision_devices')
460 if not bb_utils.TESTING:
461 # Restart adb to work around bugs, sleep to wait for usb discovery.
462 device_utils.RestartServer()
463 RunCmd(['sleep', '1'])
464 provision_cmd = ['build/android/provision_devices.py', '-t', options.target]
465 if options.auto_reconnect:
466 provision_cmd.append('--auto-reconnect')
467 if options.skip_wipe:
468 provision_cmd.append('--skip-wipe')
469 if options.disable_location:
470 provision_cmd.append('--disable-location')
471 RunCmd(provision_cmd, halt_on_failure=True)
474 def DeviceStatusCheck(options):
475 bb_annotations.PrintNamedStep('device_status_check')
476 cmd = ['build/android/buildbot/bb_device_status_check.py']
477 if options.restart_usb:
478 cmd.append('--restart-usb')
479 RunCmd(cmd, halt_on_failure=True)
482 def GetDeviceSetupStepCmds():
483 return [
484 ('device_status_check', DeviceStatusCheck),
485 ('provision_devices', ProvisionDevices),
489 def RunUnitTests(options):
490 suites = gtest_config.STABLE_TEST_SUITES
491 if options.asan:
492 suites = [s for s in suites
493 if s not in gtest_config.ASAN_EXCLUDED_TEST_SUITES]
494 RunTestSuites(options, suites)
497 def RunTelemetryUnitTests(options):
498 RunTelemetryTests(options, 'telemetry_unittests', 'tools/telemetry/run_tests')
501 def RunTelemetryPerfUnitTests(options):
502 RunTelemetryTests(options, 'telemetry_perf_unittests', 'tools/perf/run_tests')
505 def RunInstrumentationTests(options):
506 for test in INSTRUMENTATION_TESTS.itervalues():
507 RunInstrumentationSuite(options, test)
510 def RunWebkitTests(options):
511 RunTestSuites(options, ['webkit_unit_tests', 'blink_heap_unittests'])
512 RunWebkitLint()
515 def RunGPUTests(options):
516 revision = _GetRevision(options)
517 builder_name = options.build_properties.get('buildername', 'noname')
519 bb_annotations.PrintNamedStep('pixel_tests')
520 RunCmd(['content/test/gpu/run_gpu_test.py',
521 'pixel',
522 '--browser',
523 'android-content-shell',
524 '--build-revision',
525 str(revision),
526 '--upload-refimg-to-cloud-storage',
527 '--refimg-cloud-storage-bucket',
528 'chromium-gpu-archive/reference-images',
529 '--os-type',
530 'android',
531 '--test-machine-name',
532 EscapeBuilderName(builder_name)])
534 bb_annotations.PrintNamedStep('webgl_conformance_tests')
535 RunCmd(['content/test/gpu/run_gpu_test.py',
536 '--browser=android-content-shell', 'webgl_conformance',
537 '--webgl-conformance-version=1.0.1'])
539 bb_annotations.PrintNamedStep('gpu_rasterization_tests')
540 RunCmd(['content/test/gpu/run_gpu_test.py',
541 'gpu_rasterization',
542 '--browser',
543 'android-content-shell',
544 '--build-revision',
545 str(revision),
546 '--test-machine-name',
547 EscapeBuilderName(builder_name)])
550 def RunPythonUnitTests(_options):
551 for suite in constants.PYTHON_UNIT_TEST_SUITES:
552 bb_annotations.PrintNamedStep(suite)
553 RunCmd(['build/android/test_runner.py', 'python', '-s', suite])
556 def GetTestStepCmds():
557 return [
558 ('chromedriver', RunChromeDriverTests),
559 ('chrome_proxy', RunChromeProxyTests),
560 ('gpu', RunGPUTests),
561 ('python_unittests', RunPythonUnitTests),
562 ('telemetry_unittests', RunTelemetryUnitTests),
563 ('telemetry_perf_unittests', RunTelemetryPerfUnitTests),
564 ('ui', RunInstrumentationTests),
565 ('unit', RunUnitTests),
566 ('webkit', RunWebkitTests),
567 ('webkit_layout', RunWebkitLayoutTests),
571 def MakeGSPath(options, gs_base_dir):
572 revision = _GetRevision(options)
573 bot_id = options.build_properties.get('buildername', 'testing')
574 randhash = hashlib.sha1(str(random.random())).hexdigest()
575 gs_path = '%s/%s/%s/%s' % (gs_base_dir, bot_id, revision, randhash)
576 # remove double slashes, happens with blank revisions and confuses gsutil
577 gs_path = re.sub('/+', '/', gs_path)
578 return gs_path
580 def UploadHTML(options, gs_base_dir, dir_to_upload, link_text,
581 link_rel_path='index.html', gs_url=GS_URL):
582 """Uploads directory at |dir_to_upload| to Google Storage and output a link.
584 Args:
585 options: Command line options.
586 gs_base_dir: The Google Storage base directory (e.g.
587 'chromium-code-coverage/java')
588 dir_to_upload: Absolute path to the directory to be uploaded.
589 link_text: Link text to be displayed on the step.
590 link_rel_path: Link path relative to |dir_to_upload|.
591 gs_url: Google storage URL.
593 gs_path = MakeGSPath(options, gs_base_dir)
594 RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-R', dir_to_upload, 'gs://%s' % gs_path])
595 bb_annotations.PrintLink(link_text,
596 '%s/%s/%s' % (gs_url, gs_path, link_rel_path))
599 def GenerateJavaCoverageReport(options):
600 """Generates an HTML coverage report using EMMA and uploads it."""
601 bb_annotations.PrintNamedStep('java_coverage_report')
603 coverage_html = os.path.join(options.coverage_dir, 'coverage_html')
604 RunCmd(['build/android/generate_emma_html.py',
605 '--coverage-dir', options.coverage_dir,
606 '--metadata-dir', os.path.join(CHROME_OUT_DIR, options.target),
607 '--cleanup',
608 '--output', os.path.join(coverage_html, 'index.html')])
609 return coverage_html
612 def LogcatDump(options):
613 # Print logcat, kill logcat monitor
614 bb_annotations.PrintNamedStep('logcat_dump')
615 logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log.txt')
616 RunCmd([SrcPath('build', 'android', 'adb_logcat_printer.py'),
617 '--output-path', logcat_file, LOGCAT_DIR])
618 gs_path = MakeGSPath(options, 'chromium-android/logcat_dumps')
619 RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-z', 'txt', logcat_file,
620 'gs://%s' % gs_path])
621 bb_annotations.PrintLink('logcat dump', '%s/%s' % (GS_AUTH_URL, gs_path))
624 def RunStackToolSteps(options):
625 """Run stack tool steps.
627 Stack tool is run for logcat dump, optionally for ASAN.
629 bb_annotations.PrintNamedStep('Run stack tool with logcat dump')
630 logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log.txt')
631 RunCmd([os.path.join(CHROME_SRC_DIR, 'third_party', 'android_platform',
632 'development', 'scripts', 'stack'),
633 '--more-info', logcat_file])
634 if options.asan_symbolize:
635 bb_annotations.PrintNamedStep('Run stack tool for ASAN')
636 RunCmd([
637 os.path.join(CHROME_SRC_DIR, 'build', 'android', 'asan_symbolize.py'),
638 '-l', logcat_file])
641 def GenerateTestReport(options):
642 bb_annotations.PrintNamedStep('test_report')
643 for report in glob.glob(
644 os.path.join(CHROME_OUT_DIR, options.target, 'test_logs', '*.log')):
645 RunCmd(['cat', report])
646 os.remove(report)
649 def MainTestWrapper(options):
650 try:
651 # Spawn logcat monitor
652 SpawnLogcatMonitor()
654 # Run all device setup steps
655 for _, cmd in GetDeviceSetupStepCmds():
656 cmd(options)
658 if options.install:
659 for i in options.install:
660 install_obj = INSTALLABLE_PACKAGES[i]
661 InstallApk(options, install_obj, print_step=True)
663 if options.test_filter:
664 bb_utils.RunSteps(options.test_filter, GetTestStepCmds(), options)
666 if options.coverage_bucket:
667 coverage_html = GenerateJavaCoverageReport(options)
668 UploadHTML(options, '%s/java' % options.coverage_bucket, coverage_html,
669 'Coverage Report')
670 shutil.rmtree(coverage_html, ignore_errors=True)
672 if options.experimental:
673 RunTestSuites(options, gtest_config.EXPERIMENTAL_TEST_SUITES)
675 finally:
676 # Run all post test steps
677 LogcatDump(options)
678 if not options.disable_stack_tool:
679 RunStackToolSteps(options)
680 GenerateTestReport(options)
681 # KillHostHeartbeat() has logic to check if heartbeat process is running,
682 # and kills only if it finds the process is running on the host.
683 provision_devices.KillHostHeartbeat()
684 if options.cleanup:
685 shutil.rmtree(os.path.join(CHROME_OUT_DIR, options.target),
686 ignore_errors=True)
689 def GetDeviceStepsOptParser():
690 parser = bb_utils.GetParser()
691 parser.add_option('--experimental', action='store_true',
692 help='Run experiemental tests')
693 parser.add_option('-f', '--test-filter', metavar='<filter>', default=[],
694 action='append',
695 help=('Run a test suite. Test suites: "%s"' %
696 '", "'.join(VALID_TESTS)))
697 parser.add_option('--gtest-filter',
698 help='Filter for running a subset of tests of a gtest test')
699 parser.add_option('--asan', action='store_true', help='Run tests with asan.')
700 parser.add_option('--install', metavar='<apk name>', action="append",
701 help='Install an apk by name')
702 parser.add_option('--no-reboot', action='store_true',
703 help='Do not reboot devices during provisioning.')
704 parser.add_option('--coverage-bucket',
705 help=('Bucket name to store coverage results. Coverage is '
706 'only run if this is set.'))
707 parser.add_option('--restart-usb', action='store_true',
708 help='Restart usb ports before device status check.')
709 parser.add_option(
710 '--flakiness-server',
711 help=('The flakiness dashboard server to which the results should be '
712 'uploaded.'))
713 parser.add_option(
714 '--auto-reconnect', action='store_true',
715 help='Push script to device which restarts adbd on disconnections.')
716 parser.add_option('--skip-wipe', action='store_true',
717 help='Do not wipe devices during provisioning.')
718 parser.add_option('--disable-location', action='store_true',
719 help='Disable location settings.')
720 parser.add_option(
721 '--logcat-dump-output',
722 help='The logcat dump output will be "tee"-ed into this file')
723 # During processing perf bisects, a seperate working directory created under
724 # which builds are produced. Therefore we should look for relevent output
725 # file under this directory.(/b/build/slave/<slave_name>/build/bisect/src/out)
726 parser.add_option(
727 '--chrome-output-dir',
728 help='Chrome output directory to be used while bisecting.')
730 parser.add_option('--disable-stack-tool', action='store_true',
731 help='Do not run stack tool.')
732 parser.add_option('--asan-symbolize', action='store_true',
733 help='Run stack tool for ASAN')
734 parser.add_option('--cleanup', action='store_true',
735 help='Delete out/<target> directory at the end of the run.')
736 return parser
739 def main(argv):
740 parser = GetDeviceStepsOptParser()
741 options, args = parser.parse_args(argv[1:])
743 if args:
744 return sys.exit('Unused args %s' % args)
746 unknown_tests = set(options.test_filter) - VALID_TESTS
747 if unknown_tests:
748 return sys.exit('Unknown tests %s' % list(unknown_tests))
750 setattr(options, 'target', options.factory_properties.get('target', 'Debug'))
752 if options.chrome_output_dir:
753 global CHROME_OUT_DIR
754 global LOGCAT_DIR
755 CHROME_OUT_DIR = options.chrome_output_dir
756 LOGCAT_DIR = os.path.join(CHROME_OUT_DIR, 'logcat')
758 if options.coverage_bucket:
759 setattr(options, 'coverage_dir',
760 os.path.join(CHROME_OUT_DIR, options.target, 'coverage'))
762 MainTestWrapper(options)
765 if __name__ == '__main__':
766 sys.exit(main(sys.argv))