Prevent app list doodle from being pinch-to-zoomed.
[chromium-blink-merge.git] / build / android / buildbot / bb_device_steps.py
blobd7975a398a24c6cbe810f8f30e8c16c4b13d289b
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', 'components_browsertests',
98 'gpu', 'python_unittests', 'telemetry_unittests',
99 'telemetry_perf_unittests', 'ui', 'unit', 'webkit',
100 'webkit_layout'])
102 RunCmd = bb_utils.RunCmd
105 def _GetRevision(options):
106 """Get the SVN revision number.
108 Args:
109 options: options object.
111 Returns:
112 The revision number.
114 revision = options.build_properties.get('got_revision')
115 if not revision:
116 revision = options.build_properties.get('revision', 'testing')
117 return revision
120 def _RunTest(options, cmd, suite):
121 """Run test command with runtest.py.
123 Args:
124 options: options object.
125 cmd: the command to run.
126 suite: test name.
128 property_args = bb_utils.EncodeProperties(options)
129 args = [os.path.join(SLAVE_SCRIPTS_DIR, 'runtest.py')] + property_args
130 args += ['--test-platform', 'android']
131 if options.factory_properties.get('generate_gtest_json'):
132 args.append('--generate-json-file')
133 args += ['-o', 'gtest-results/%s' % suite,
134 '--annotate', 'gtest',
135 '--build-number', str(options.build_properties.get('buildnumber',
136 '')),
137 '--builder-name', options.build_properties.get('buildername', '')]
138 if options.target == 'Release':
139 args += ['--target', 'Release']
140 else:
141 args += ['--target', 'Debug']
142 if options.flakiness_server:
143 args += ['--flakiness-dashboard-server=%s' %
144 options.flakiness_server]
145 args += cmd
146 RunCmd(args, cwd=DIR_BUILD_ROOT)
149 def RunTestSuites(options, suites, suites_options=None):
150 """Manages an invocation of test_runner.py for gtests.
152 Args:
153 options: options object.
154 suites: List of suite names to run.
155 suites_options: Command line options dictionary for particular suites.
156 For example,
157 {'content_browsertests', ['--num_retries=1', '--release']}
158 will add the options only to content_browsertests.
161 if not suites_options:
162 suites_options = {}
164 args = ['--verbose']
165 if options.target == 'Release':
166 args.append('--release')
167 if options.asan:
168 args.append('--tool=asan')
169 if options.gtest_filter:
170 args.append('--gtest-filter=%s' % options.gtest_filter)
172 for suite in suites:
173 bb_annotations.PrintNamedStep(suite)
174 cmd = [suite] + args
175 cmd += suites_options.get(suite, [])
176 if suite == 'content_browsertests' or suite == 'components_browsertests':
177 cmd.append('--num_retries=1')
178 _RunTest(options, cmd, suite)
181 def RunChromeDriverTests(options):
182 """Run all the steps for running chromedriver tests."""
183 bb_annotations.PrintNamedStep('chromedriver_annotation')
184 RunCmd(['chrome/test/chromedriver/run_buildbot_steps.py',
185 '--android-packages=%s,%s,%s,%s' %
186 ('chrome_shell',
187 'chrome_stable',
188 'chrome_beta',
189 'chromedriver_webview_shell'),
190 '--revision=%s' % _GetRevision(options),
191 '--update-log'])
193 def RunChromeProxyTests(options):
194 """Run the chrome_proxy tests.
196 Args:
197 options: options object.
199 InstallApk(options, INSTRUMENTATION_TESTS['ChromeShell'], False)
200 args = ['--browser', 'android-chrome-shell']
201 devices = android_commands.GetAttachedDevices()
202 if devices:
203 args = args + ['--device', devices[0]]
204 bb_annotations.PrintNamedStep('chrome_proxy')
205 RunCmd(['tools/chrome_proxy/run_tests'] + args)
208 def RunTelemetryTests(options, step_name, run_tests_path):
209 """Runs either telemetry_perf_unittests or telemetry_unittests.
211 Args:
212 options: options object.
213 step_name: either 'telemetry_unittests' or 'telemetry_perf_unittests'
214 run_tests_path: path to run_tests script (tools/perf/run_tests for
215 perf_unittests and tools/telemetry/run_tests for
216 telemetry_unittests)
218 InstallApk(options, INSTRUMENTATION_TESTS['ChromeShell'], False)
219 args = ['--browser', 'android-chrome-shell']
220 devices = android_commands.GetAttachedDevices()
221 if devices:
222 args = args + ['--device', 'android']
223 bb_annotations.PrintNamedStep(step_name)
224 RunCmd([run_tests_path] + args)
227 def InstallApk(options, test, print_step=False):
228 """Install an apk to all phones.
230 Args:
231 options: options object
232 test: An I_TEST namedtuple
233 print_step: Print a buildbot step
235 if print_step:
236 bb_annotations.PrintNamedStep('install_%s' % test.name.lower())
238 args = ['--apk_package', test.apk_package]
239 if options.target == 'Release':
240 args.append('--release')
241 args.append(test.apk)
243 RunCmd(['build/android/adb_install_apk.py'] + args, halt_on_failure=True)
246 def RunInstrumentationSuite(options, test, flunk_on_failure=True,
247 python_only=False, official_build=False):
248 """Manages an invocation of test_runner.py for instrumentation tests.
250 Args:
251 options: options object
252 test: An I_TEST namedtuple
253 flunk_on_failure: Flunk the step if tests fail.
254 Python: Run only host driven Python tests.
255 official_build: Run official-build tests.
257 bb_annotations.PrintNamedStep('%s_instrumentation_tests' % test.name.lower())
259 if test.apk:
260 InstallApk(options, test)
261 args = ['--test-apk', test.test_apk, '--verbose']
262 if test.test_data:
263 args.extend(['--test_data', test.test_data])
264 if options.target == 'Release':
265 args.append('--release')
266 if options.asan:
267 args.append('--tool=asan')
268 if options.flakiness_server:
269 args.append('--flakiness-dashboard-server=%s' %
270 options.flakiness_server)
271 if options.coverage_bucket:
272 args.append('--coverage-dir=%s' % options.coverage_dir)
273 if test.isolate_file_path:
274 args.append('--isolate-file-path=%s' % test.isolate_file_path)
275 if test.host_driven_root:
276 args.append('--host-driven-root=%s' % test.host_driven_root)
277 if test.annotation:
278 args.extend(['-A', test.annotation])
279 if test.exclude_annotation:
280 args.extend(['-E', test.exclude_annotation])
281 if test.extra_flags:
282 args.extend(test.extra_flags)
283 if python_only:
284 args.append('-p')
285 if official_build:
286 # The option needs to be assigned 'True' as it does not have an action
287 # associated with it.
288 args.append('--official-build')
290 RunCmd(['build/android/test_runner.py', 'instrumentation'] + args,
291 flunk_on_failure=flunk_on_failure)
294 def RunWebkitLint():
295 """Lint WebKit's TestExpectation files."""
296 bb_annotations.PrintNamedStep('webkit_lint')
297 RunCmd([SrcPath(os.path.join(BLINK_SCRIPTS_DIR, 'lint-test-expectations'))])
300 def RunWebkitLayoutTests(options):
301 """Run layout tests on an actual device."""
302 bb_annotations.PrintNamedStep('webkit_tests')
303 cmd_args = [
304 '--no-show-results',
305 '--no-new-test-results',
306 '--full-results-html',
307 '--clobber-old-results',
308 '--exit-after-n-failures', '5000',
309 '--exit-after-n-crashes-or-timeouts', '100',
310 '--debug-rwt-logging',
311 '--results-directory', '../layout-test-results',
312 '--target', options.target,
313 '--builder-name', options.build_properties.get('buildername', ''),
314 '--build-number', str(options.build_properties.get('buildnumber', '')),
315 '--master-name', 'ChromiumWebkit', # TODO: Get this from the cfg.
316 '--build-name', options.build_properties.get('buildername', ''),
317 '--platform=android']
319 for flag in 'test_results_server', 'driver_name', 'additional_driver_flag':
320 if flag in options.factory_properties:
321 cmd_args.extend(['--%s' % flag.replace('_', '-'),
322 options.factory_properties.get(flag)])
324 for f in options.factory_properties.get('additional_expectations', []):
325 cmd_args.extend(
326 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
328 # TODO(dpranke): Remove this block after
329 # https://codereview.chromium.org/12927002/ lands.
330 for f in options.factory_properties.get('additional_expectations_files', []):
331 cmd_args.extend(
332 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
334 exit_code = RunCmd(
335 [SrcPath(os.path.join(BLINK_SCRIPTS_DIR, 'run-webkit-tests'))] + cmd_args)
336 if exit_code == 255: # test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
337 bb_annotations.PrintMsg('?? (crashed or hung)')
338 elif exit_code == 254: # test_run_results.NO_DEVICES_EXIT_STATUS
339 bb_annotations.PrintMsg('?? (no devices found)')
340 elif exit_code == 253: # test_run_results.NO_TESTS_EXIT_STATUS
341 bb_annotations.PrintMsg('?? (no tests found)')
342 else:
343 full_results_path = os.path.join('..', 'layout-test-results',
344 'full_results.json')
345 if os.path.exists(full_results_path):
346 full_results = json.load(open(full_results_path))
347 unexpected_passes, unexpected_failures, unexpected_flakes = (
348 _ParseLayoutTestResults(full_results))
349 if unexpected_failures:
350 _PrintDashboardLink('failed', unexpected_failures.keys(),
351 max_tests=25)
352 elif unexpected_passes:
353 _PrintDashboardLink('unexpected passes', unexpected_passes.keys(),
354 max_tests=10)
355 if unexpected_flakes:
356 _PrintDashboardLink('unexpected flakes', unexpected_flakes.keys(),
357 max_tests=10)
359 if exit_code == 0 and (unexpected_passes or unexpected_flakes):
360 # If exit_code != 0, RunCmd() will have already printed an error.
361 bb_annotations.PrintWarning()
362 else:
363 bb_annotations.PrintError()
364 bb_annotations.PrintMsg('?? (results missing)')
366 if options.factory_properties.get('archive_webkit_results', False):
367 bb_annotations.PrintNamedStep('archive_webkit_results')
368 base = 'https://storage.googleapis.com/chromium-layout-test-archives'
369 builder_name = options.build_properties.get('buildername', '')
370 build_number = str(options.build_properties.get('buildnumber', ''))
371 results_link = '%s/%s/%s/layout-test-results/results.html' % (
372 base, EscapeBuilderName(builder_name), build_number)
373 bb_annotations.PrintLink('results', results_link)
374 bb_annotations.PrintLink('(zip)', '%s/%s/%s/layout-test-results.zip' % (
375 base, EscapeBuilderName(builder_name), build_number))
376 gs_bucket = 'gs://chromium-layout-test-archives'
377 RunCmd([os.path.join(SLAVE_SCRIPTS_DIR, 'chromium',
378 'archive_layout_test_results.py'),
379 '--results-dir', '../../layout-test-results',
380 '--build-number', build_number,
381 '--builder-name', builder_name,
382 '--gs-bucket', gs_bucket],
383 cwd=DIR_BUILD_ROOT)
386 def _ParseLayoutTestResults(results):
387 """Extract the failures from the test run."""
388 # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
389 tests = _ConvertTrieToFlatPaths(results['tests'])
390 failures = {}
391 flakes = {}
392 passes = {}
393 for (test, result) in tests.iteritems():
394 if result.get('is_unexpected'):
395 actual_results = result['actual'].split()
396 expected_results = result['expected'].split()
397 if len(actual_results) > 1:
398 # We report the first failure type back, even if the second
399 # was more severe.
400 if actual_results[1] in expected_results:
401 flakes[test] = actual_results[0]
402 else:
403 failures[test] = actual_results[0]
404 elif actual_results[0] == 'PASS':
405 passes[test] = result
406 else:
407 failures[test] = actual_results[0]
409 return (passes, failures, flakes)
412 def _ConvertTrieToFlatPaths(trie, prefix=None):
413 """Flatten the trie of failures into a list."""
414 # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
415 result = {}
416 for name, data in trie.iteritems():
417 if prefix:
418 name = prefix + '/' + name
420 if len(data) and 'actual' not in data and 'expected' not in data:
421 result.update(_ConvertTrieToFlatPaths(data, name))
422 else:
423 result[name] = data
425 return result
428 def _PrintDashboardLink(link_text, tests, max_tests):
429 """Add a link to the flakiness dashboard in the step annotations."""
430 if len(tests) > max_tests:
431 test_list_text = ' '.join(tests[:max_tests]) + ' and more'
432 else:
433 test_list_text = ' '.join(tests)
435 dashboard_base = ('http://test-results.appspot.com'
436 '/dashboards/flakiness_dashboard.html#'
437 'master=ChromiumWebkit&tests=')
439 bb_annotations.PrintLink('%d %s: %s' %
440 (len(tests), link_text, test_list_text),
441 dashboard_base + ','.join(tests))
444 def EscapeBuilderName(builder_name):
445 return re.sub('[ ()]', '_', builder_name)
448 def SpawnLogcatMonitor():
449 shutil.rmtree(LOGCAT_DIR, ignore_errors=True)
450 bb_utils.SpawnCmd([
451 os.path.join(CHROME_SRC_DIR, 'build', 'android', 'adb_logcat_monitor.py'),
452 LOGCAT_DIR])
454 # Wait for logcat_monitor to pull existing logcat
455 RunCmd(['sleep', '5'])
458 def ProvisionDevices(options):
459 bb_annotations.PrintNamedStep('provision_devices')
461 if not bb_utils.TESTING:
462 # Restart adb to work around bugs, sleep to wait for usb discovery.
463 device_utils.RestartServer()
464 RunCmd(['sleep', '1'])
465 provision_cmd = ['build/android/provision_devices.py', '-t', options.target]
466 if options.auto_reconnect:
467 provision_cmd.append('--auto-reconnect')
468 if options.skip_wipe:
469 provision_cmd.append('--skip-wipe')
470 if options.disable_location:
471 provision_cmd.append('--disable-location')
472 RunCmd(provision_cmd, halt_on_failure=True)
475 def DeviceStatusCheck(options):
476 bb_annotations.PrintNamedStep('device_status_check')
477 cmd = ['build/android/buildbot/bb_device_status_check.py']
478 if options.restart_usb:
479 cmd.append('--restart-usb')
480 RunCmd(cmd, halt_on_failure=True)
483 def GetDeviceSetupStepCmds():
484 return [
485 ('device_status_check', DeviceStatusCheck),
486 ('provision_devices', ProvisionDevices),
490 def RunUnitTests(options):
491 suites = gtest_config.STABLE_TEST_SUITES
492 if options.asan:
493 suites = [s for s in suites
494 if s not in gtest_config.ASAN_EXCLUDED_TEST_SUITES]
495 RunTestSuites(options, suites)
498 def RunTelemetryUnitTests(options):
499 RunTelemetryTests(options, 'telemetry_unittests', 'tools/telemetry/run_tests')
502 def RunTelemetryPerfUnitTests(options):
503 RunTelemetryTests(options, 'telemetry_perf_unittests', 'tools/perf/run_tests')
506 def RunInstrumentationTests(options):
507 for test in INSTRUMENTATION_TESTS.itervalues():
508 RunInstrumentationSuite(options, test)
511 def RunWebkitTests(options):
512 RunTestSuites(options, ['webkit_unit_tests', 'blink_heap_unittests'])
513 RunWebkitLint()
516 def RunGPUTests(options):
517 revision = _GetRevision(options)
518 builder_name = options.build_properties.get('buildername', 'noname')
520 bb_annotations.PrintNamedStep('pixel_tests')
521 RunCmd(['content/test/gpu/run_gpu_test.py',
522 'pixel',
523 '--browser',
524 'android-content-shell',
525 '--build-revision',
526 str(revision),
527 '--upload-refimg-to-cloud-storage',
528 '--refimg-cloud-storage-bucket',
529 'chromium-gpu-archive/reference-images',
530 '--os-type',
531 'android',
532 '--test-machine-name',
533 EscapeBuilderName(builder_name)])
535 bb_annotations.PrintNamedStep('webgl_conformance_tests')
536 RunCmd(['content/test/gpu/run_gpu_test.py',
537 '--browser=android-content-shell', 'webgl_conformance',
538 '--webgl-conformance-version=1.0.1'])
540 bb_annotations.PrintNamedStep('android_webview_webgl_conformance_tests')
541 RunCmd(['content/test/gpu/run_gpu_test.py',
542 '--browser=android-webview-shell', 'webgl_conformance',
543 '--webgl-conformance-version=1.0.1'])
545 bb_annotations.PrintNamedStep('gpu_rasterization_tests')
546 RunCmd(['content/test/gpu/run_gpu_test.py',
547 'gpu_rasterization',
548 '--browser',
549 'android-content-shell',
550 '--build-revision',
551 str(revision),
552 '--test-machine-name',
553 EscapeBuilderName(builder_name)])
556 def RunPythonUnitTests(_options):
557 for suite in constants.PYTHON_UNIT_TEST_SUITES:
558 bb_annotations.PrintNamedStep(suite)
559 RunCmd(['build/android/test_runner.py', 'python', '-s', suite])
562 def GetTestStepCmds():
563 return [
564 ('chromedriver', RunChromeDriverTests),
565 ('chrome_proxy', RunChromeProxyTests),
566 ('components_browsertests',
567 lambda options: RunTestSuites(options, ['components_browsertests'])),
568 ('gpu', RunGPUTests),
569 ('python_unittests', RunPythonUnitTests),
570 ('telemetry_unittests', RunTelemetryUnitTests),
571 ('telemetry_perf_unittests', RunTelemetryPerfUnitTests),
572 ('ui', RunInstrumentationTests),
573 ('unit', RunUnitTests),
574 ('webkit', RunWebkitTests),
575 ('webkit_layout', RunWebkitLayoutTests),
579 def MakeGSPath(options, gs_base_dir):
580 revision = _GetRevision(options)
581 bot_id = options.build_properties.get('buildername', 'testing')
582 randhash = hashlib.sha1(str(random.random())).hexdigest()
583 gs_path = '%s/%s/%s/%s' % (gs_base_dir, bot_id, revision, randhash)
584 # remove double slashes, happens with blank revisions and confuses gsutil
585 gs_path = re.sub('/+', '/', gs_path)
586 return gs_path
588 def UploadHTML(options, gs_base_dir, dir_to_upload, link_text,
589 link_rel_path='index.html', gs_url=GS_URL):
590 """Uploads directory at |dir_to_upload| to Google Storage and output a link.
592 Args:
593 options: Command line options.
594 gs_base_dir: The Google Storage base directory (e.g.
595 'chromium-code-coverage/java')
596 dir_to_upload: Absolute path to the directory to be uploaded.
597 link_text: Link text to be displayed on the step.
598 link_rel_path: Link path relative to |dir_to_upload|.
599 gs_url: Google storage URL.
601 gs_path = MakeGSPath(options, gs_base_dir)
602 RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-R', dir_to_upload, 'gs://%s' % gs_path])
603 bb_annotations.PrintLink(link_text,
604 '%s/%s/%s' % (gs_url, gs_path, link_rel_path))
607 def GenerateJavaCoverageReport(options):
608 """Generates an HTML coverage report using EMMA and uploads it."""
609 bb_annotations.PrintNamedStep('java_coverage_report')
611 coverage_html = os.path.join(options.coverage_dir, 'coverage_html')
612 RunCmd(['build/android/generate_emma_html.py',
613 '--coverage-dir', options.coverage_dir,
614 '--metadata-dir', os.path.join(CHROME_OUT_DIR, options.target),
615 '--cleanup',
616 '--output', os.path.join(coverage_html, 'index.html')])
617 return coverage_html
620 def LogcatDump(options):
621 # Print logcat, kill logcat monitor
622 bb_annotations.PrintNamedStep('logcat_dump')
623 logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log.txt')
624 RunCmd([SrcPath('build', 'android', 'adb_logcat_printer.py'),
625 '--output-path', logcat_file, LOGCAT_DIR])
626 gs_path = MakeGSPath(options, 'chromium-android/logcat_dumps')
627 RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-z', 'txt', logcat_file,
628 'gs://%s' % gs_path])
629 bb_annotations.PrintLink('logcat dump', '%s/%s' % (GS_AUTH_URL, gs_path))
632 def RunStackToolSteps(options):
633 """Run stack tool steps.
635 Stack tool is run for logcat dump, optionally for ASAN.
637 bb_annotations.PrintNamedStep('Run stack tool with logcat dump')
638 logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log.txt')
639 RunCmd([os.path.join(CHROME_SRC_DIR, 'third_party', 'android_platform',
640 'development', 'scripts', 'stack'),
641 '--more-info', logcat_file])
642 if options.asan_symbolize:
643 bb_annotations.PrintNamedStep('Run stack tool for ASAN')
644 RunCmd([
645 os.path.join(CHROME_SRC_DIR, 'build', 'android', 'asan_symbolize.py'),
646 '-l', logcat_file])
649 def GenerateTestReport(options):
650 bb_annotations.PrintNamedStep('test_report')
651 for report in glob.glob(
652 os.path.join(CHROME_OUT_DIR, options.target, 'test_logs', '*.log')):
653 RunCmd(['cat', report])
654 os.remove(report)
657 def MainTestWrapper(options):
658 try:
659 # Spawn logcat monitor
660 SpawnLogcatMonitor()
662 # Run all device setup steps
663 for _, cmd in GetDeviceSetupStepCmds():
664 cmd(options)
666 if options.install:
667 for i in options.install:
668 install_obj = INSTALLABLE_PACKAGES[i]
669 InstallApk(options, install_obj, print_step=True)
671 if options.test_filter:
672 bb_utils.RunSteps(options.test_filter, GetTestStepCmds(), options)
674 if options.coverage_bucket:
675 coverage_html = GenerateJavaCoverageReport(options)
676 UploadHTML(options, '%s/java' % options.coverage_bucket, coverage_html,
677 'Coverage Report')
678 shutil.rmtree(coverage_html, ignore_errors=True)
680 if options.experimental:
681 RunTestSuites(options, gtest_config.EXPERIMENTAL_TEST_SUITES)
683 finally:
684 # Run all post test steps
685 LogcatDump(options)
686 if not options.disable_stack_tool:
687 RunStackToolSteps(options)
688 GenerateTestReport(options)
689 # KillHostHeartbeat() has logic to check if heartbeat process is running,
690 # and kills only if it finds the process is running on the host.
691 provision_devices.KillHostHeartbeat()
692 if options.cleanup:
693 shutil.rmtree(os.path.join(CHROME_OUT_DIR, options.target),
694 ignore_errors=True)
697 def GetDeviceStepsOptParser():
698 parser = bb_utils.GetParser()
699 parser.add_option('--experimental', action='store_true',
700 help='Run experiemental tests')
701 parser.add_option('-f', '--test-filter', metavar='<filter>', default=[],
702 action='append',
703 help=('Run a test suite. Test suites: "%s"' %
704 '", "'.join(VALID_TESTS)))
705 parser.add_option('--gtest-filter',
706 help='Filter for running a subset of tests of a gtest test')
707 parser.add_option('--asan', action='store_true', help='Run tests with asan.')
708 parser.add_option('--install', metavar='<apk name>', action="append",
709 help='Install an apk by name')
710 parser.add_option('--no-reboot', action='store_true',
711 help='Do not reboot devices during provisioning.')
712 parser.add_option('--coverage-bucket',
713 help=('Bucket name to store coverage results. Coverage is '
714 'only run if this is set.'))
715 parser.add_option('--restart-usb', action='store_true',
716 help='Restart usb ports before device status check.')
717 parser.add_option(
718 '--flakiness-server',
719 help=('The flakiness dashboard server to which the results should be '
720 'uploaded.'))
721 parser.add_option(
722 '--auto-reconnect', action='store_true',
723 help='Push script to device which restarts adbd on disconnections.')
724 parser.add_option('--skip-wipe', action='store_true',
725 help='Do not wipe devices during provisioning.')
726 parser.add_option('--disable-location', action='store_true',
727 help='Disable location settings.')
728 parser.add_option(
729 '--logcat-dump-output',
730 help='The logcat dump output will be "tee"-ed into this file')
731 # During processing perf bisects, a seperate working directory created under
732 # which builds are produced. Therefore we should look for relevent output
733 # file under this directory.(/b/build/slave/<slave_name>/build/bisect/src/out)
734 parser.add_option(
735 '--chrome-output-dir',
736 help='Chrome output directory to be used while bisecting.')
738 parser.add_option('--disable-stack-tool', action='store_true',
739 help='Do not run stack tool.')
740 parser.add_option('--asan-symbolize', action='store_true',
741 help='Run stack tool for ASAN')
742 parser.add_option('--cleanup', action='store_true',
743 help='Delete out/<target> directory at the end of the run.')
744 return parser
747 def main(argv):
748 parser = GetDeviceStepsOptParser()
749 options, args = parser.parse_args(argv[1:])
751 if args:
752 return sys.exit('Unused args %s' % args)
754 unknown_tests = set(options.test_filter) - VALID_TESTS
755 if unknown_tests:
756 return sys.exit('Unknown tests %s' % list(unknown_tests))
758 setattr(options, 'target', options.factory_properties.get('target', 'Debug'))
760 if options.chrome_output_dir:
761 global CHROME_OUT_DIR
762 global LOGCAT_DIR
763 CHROME_OUT_DIR = options.chrome_output_dir
764 LOGCAT_DIR = os.path.join(CHROME_OUT_DIR, 'logcat')
766 if options.coverage_bucket:
767 setattr(options, 'coverage_dir',
768 os.path.join(CHROME_OUT_DIR, options.target, 'coverage'))
770 MainTestWrapper(options)
773 if __name__ == '__main__':
774 sys.exit(main(sys.argv))