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.
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
30 SLAVE_SCRIPTS_DIR = os.path.join(bb_utils.BB_BUILD_DIR, 'scripts', 'slave')
31 LOGCAT_DIR = os.path.join(bb_utils.CHROME_OUT_DIR, 'logcat')
32 GS_URL = 'https://storage.googleapis.com'
33 GS_AUTH_URL = 'https://storage.cloud.google.com'
35 # Describes an instrumation test suite:
36 # test: Name of test we're running.
37 # apk: apk to be installed.
38 # apk_package: package for the apk to be installed.
39 # test_apk: apk to run tests on.
40 # test_data: data folder in format destination:source.
41 # host_driven_root: The host-driven test root directory.
42 # annotation: Annotation of the tests to include.
43 # exclude_annotation: The annotation of the tests to exclude.
44 I_TEST = collections.namedtuple('InstrumentationTest', [
45 'name', 'apk', 'apk_package', 'test_apk', 'test_data', 'host_driven_root',
46 'annotation', 'exclude_annotation', 'extra_flags'])
50 return os.path.join(CHROME_SRC_DIR, *path)
53 def I(name, apk, apk_package, test_apk, test_data, host_driven_root=None,
54 annotation=None, exclude_annotation=None, extra_flags=None):
55 return I_TEST(name, apk, apk_package, test_apk, test_data, host_driven_root,
56 annotation, exclude_annotation, extra_flags)
58 INSTRUMENTATION_TESTS = dict((suite.name, suite) for suite in [
61 'org.chromium.content_shell_apk',
63 'content:content/test/data/android/device_files'),
66 'org.chromium.chrome.shell',
68 'chrome:chrome/test/data/android/device_files',
69 constants.CHROME_SHELL_HOST_DRIVEN_DIR),
72 'org.chromium.android_webview.shell',
74 'webview:android_webview/test/data/device_files'),
77 VALID_TESTS = set(['chromedriver', 'gpu', 'mojo', 'telemetry_perf_unittests',
78 'ui', 'unit', 'webkit', 'webkit_layout', 'webrtc_chromium',
81 RunCmd = bb_utils.RunCmd
84 def _GetRevision(options):
85 """Get the SVN revision number.
88 options: options object.
93 revision = options.build_properties.get('got_revision')
95 revision = options.build_properties.get('revision', 'testing')
99 def RunTestSuites(options, suites):
100 """Manages an invocation of test_runner.py for gtests.
103 options: options object.
104 suites: List of suite names to run.
107 if options.target == 'Release':
108 args.append('--release')
110 args.append('--tool=asan')
111 if options.gtest_filter:
112 args.append('--gtest-filter=%s' % options.gtest_filter)
114 bb_annotations.PrintNamedStep(suite)
115 cmd = ['build/android/test_runner.py', 'gtest', '-s', suite] + args
116 if suite == 'content_browsertests':
117 cmd.append('--num_retries=1')
121 def RunChromeDriverTests(options):
122 """Run all the steps for running chromedriver tests."""
123 bb_annotations.PrintNamedStep('chromedriver_annotation')
124 RunCmd(['chrome/test/chromedriver/run_buildbot_steps.py',
125 '--android-packages=%s,%s,%s,%s' %
129 'chromedriver_webview_shell'),
130 '--revision=%s' % _GetRevision(options),
134 def RunTelemetryPerfUnitTests(options):
135 """Runs the telemetry perf unit tests.
138 options: options object.
140 InstallApk(options, INSTRUMENTATION_TESTS['ChromeShell'], False)
141 args = ['--browser', 'android-chromium-testshell']
142 devices = android_commands.GetAttachedDevices()
144 args = args + ['--device', devices[0]]
145 bb_annotations.PrintNamedStep('telemetry_perf_unittests')
146 RunCmd(['tools/perf/run_tests'] + args)
149 def RunMojoTests(options):
150 """Runs the mojo unit tests.
153 options: options object.
157 'org.chromium.mojo.tests',
160 RunInstrumentationSuite(options, test)
163 def InstallApk(options, test, print_step=False):
164 """Install an apk to all phones.
167 options: options object
168 test: An I_TEST namedtuple
169 print_step: Print a buildbot step
172 bb_annotations.PrintNamedStep('install_%s' % test.name.lower())
174 args = ['--apk', test.apk, '--apk_package', test.apk_package]
175 if options.target == 'Release':
176 args.append('--release')
178 RunCmd(['build/android/adb_install_apk.py'] + args, halt_on_failure=True)
181 def RunInstrumentationSuite(options, test, flunk_on_failure=True,
182 python_only=False, official_build=False):
183 """Manages an invocation of test_runner.py for instrumentation tests.
186 options: options object
187 test: An I_TEST namedtuple
188 flunk_on_failure: Flunk the step if tests fail.
189 Python: Run only host driven Python tests.
190 official_build: Run official-build tests.
192 bb_annotations.PrintNamedStep('%s_instrumentation_tests' % test.name.lower())
195 InstallApk(options, test)
196 args = ['--test-apk', test.test_apk, '--verbose']
198 args.extend(['--test_data', test.test_data])
199 if options.target == 'Release':
200 args.append('--release')
202 args.append('--tool=asan')
203 if options.flakiness_server:
204 args.append('--flakiness-dashboard-server=%s' %
205 options.flakiness_server)
206 if options.coverage_bucket:
207 args.append('--coverage-dir=%s' % options.coverage_dir)
208 if test.host_driven_root:
209 args.append('--host-driven-root=%s' % test.host_driven_root)
211 args.extend(['-A', test.annotation])
212 if test.exclude_annotation:
213 args.extend(['-E', test.exclude_annotation])
215 args.extend(test.extra_flags)
219 # The option needs to be assigned 'True' as it does not have an action
220 # associated with it.
221 args.append('--official-build')
223 RunCmd(['build/android/test_runner.py', 'instrumentation'] + args,
224 flunk_on_failure=flunk_on_failure)
227 def RunWebkitLint(target):
228 """Lint WebKit's TestExpectation files."""
229 bb_annotations.PrintNamedStep('webkit_lint')
230 RunCmd([SrcPath('webkit/tools/layout_tests/run_webkit_tests.py'),
236 def RunWebkitLayoutTests(options):
237 """Run layout tests on an actual device."""
238 bb_annotations.PrintNamedStep('webkit_tests')
241 '--no-new-test-results',
242 '--full-results-html',
243 '--clobber-old-results',
244 '--exit-after-n-failures', '5000',
245 '--exit-after-n-crashes-or-timeouts', '100',
246 '--debug-rwt-logging',
247 '--results-directory', '../layout-test-results',
248 '--target', options.target,
249 '--builder-name', options.build_properties.get('buildername', ''),
250 '--build-number', str(options.build_properties.get('buildnumber', '')),
251 '--master-name', 'ChromiumWebkit', # TODO: Get this from the cfg.
252 '--build-name', options.build_properties.get('buildername', ''),
253 '--platform=android']
255 for flag in 'test_results_server', 'driver_name', 'additional_drt_flag':
256 if flag in options.factory_properties:
257 cmd_args.extend(['--%s' % flag.replace('_', '-'),
258 options.factory_properties.get(flag)])
260 for f in options.factory_properties.get('additional_expectations', []):
262 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
264 # TODO(dpranke): Remove this block after
265 # https://codereview.chromium.org/12927002/ lands.
266 for f in options.factory_properties.get('additional_expectations_files', []):
268 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
270 exit_code = RunCmd([SrcPath('webkit/tools/layout_tests/run_webkit_tests.py')]
272 if exit_code == 255: # test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
273 bb_annotations.PrintMsg('?? (crashed or hung)')
274 elif exit_code == 254: # test_run_results.NO_DEVICES_EXIT_STATUS
275 bb_annotations.PrintMsg('?? (no devices found)')
276 elif exit_code == 253: # test_run_results.NO_TESTS_EXIT_STATUS
277 bb_annotations.PrintMsg('?? (no tests found)')
279 full_results_path = os.path.join('..', 'layout-test-results',
281 if os.path.exists(full_results_path):
282 full_results = json.load(open(full_results_path))
283 unexpected_passes, unexpected_failures, unexpected_flakes = (
284 _ParseLayoutTestResults(full_results))
285 if unexpected_failures:
286 _PrintDashboardLink('failed', unexpected_failures,
288 elif unexpected_passes:
289 _PrintDashboardLink('unexpected passes', unexpected_passes,
291 if unexpected_flakes:
292 _PrintDashboardLink('unexpected flakes', unexpected_flakes,
295 if exit_code == 0 and (unexpected_passes or unexpected_flakes):
296 # If exit_code != 0, RunCmd() will have already printed an error.
297 bb_annotations.PrintWarning()
299 bb_annotations.PrintError()
300 bb_annotations.PrintMsg('?? (results missing)')
302 if options.factory_properties.get('archive_webkit_results', False):
303 bb_annotations.PrintNamedStep('archive_webkit_results')
304 base = 'https://storage.googleapis.com/chromium-layout-test-archives'
305 builder_name = options.build_properties.get('buildername', '')
306 build_number = str(options.build_properties.get('buildnumber', ''))
307 results_link = '%s/%s/%s/layout-test-results/results.html' % (
308 base, EscapeBuilderName(builder_name), build_number)
309 bb_annotations.PrintLink('results', results_link)
310 bb_annotations.PrintLink('(zip)', '%s/%s/%s/layout-test-results.zip' % (
311 base, EscapeBuilderName(builder_name), build_number))
312 gs_bucket = 'gs://chromium-layout-test-archives'
313 RunCmd([os.path.join(SLAVE_SCRIPTS_DIR, 'chromium',
314 'archive_layout_test_results.py'),
315 '--results-dir', '../../layout-test-results',
316 '--build-number', build_number,
317 '--builder-name', builder_name,
318 '--gs-bucket', gs_bucket],
322 def _ParseLayoutTestResults(results):
323 """Extract the failures from the test run."""
324 # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
325 tests = _ConvertTrieToFlatPaths(results['tests'])
329 for (test, result) in tests.iteritems():
330 if result.get('is_unexpected'):
331 actual_results = result['actual'].split()
332 expected_results = result['expected'].split()
333 if len(actual_results) > 1:
334 # We report the first failure type back, even if the second
336 if actual_results[1] in expected_results:
337 flakes[test] = actual_results[0]
339 failures[test] = actual_results[0]
340 elif actual_results[0] == 'PASS':
341 passes[test] = result
343 failures[test] = actual_results[0]
345 return (passes, failures, flakes)
348 def _ConvertTrieToFlatPaths(trie, prefix=None):
349 """Flatten the trie of failures into a list."""
350 # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
352 for name, data in trie.iteritems():
354 name = prefix + '/' + name
356 if len(data) and 'actual' not in data and 'expected' not in data:
357 result.update(_ConvertTrieToFlatPaths(data, name))
364 def _PrintDashboardLink(link_text, tests, max_tests):
365 """Add a link to the flakiness dashboard in the step annotations."""
366 if len(tests) > max_tests:
367 test_list_text = ' '.join(tests[:max_tests]) + ' and more'
369 test_list_text = ' '.join(tests)
371 dashboard_base = ('http://test-results.appspot.com'
372 '/dashboards/flakiness_dashboard.html#'
373 'master=ChromiumWebkit&tests=')
375 bb_annotations.PrintLink('%d %s: %s' %
376 (len(tests), link_text, test_list_text),
377 dashboard_base + ','.join(tests))
380 def EscapeBuilderName(builder_name):
381 return re.sub('[ ()]', '_', builder_name)
384 def SpawnLogcatMonitor():
385 shutil.rmtree(LOGCAT_DIR, ignore_errors=True)
387 os.path.join(CHROME_SRC_DIR, 'build', 'android', 'adb_logcat_monitor.py'),
390 # Wait for logcat_monitor to pull existing logcat
391 RunCmd(['sleep', '5'])
394 def ProvisionDevices(options):
395 bb_annotations.PrintNamedStep('provision_devices')
397 if not bb_utils.TESTING:
398 # Restart adb to work around bugs, sleep to wait for usb discovery.
399 device_utils.DeviceUtils(None).old_interface.RestartAdbServer()
400 RunCmd(['sleep', '1'])
401 provision_cmd = ['build/android/provision_devices.py', '-t', options.target]
402 if options.auto_reconnect:
403 provision_cmd.append('--auto-reconnect')
404 RunCmd(provision_cmd)
407 def DeviceStatusCheck(options):
408 bb_annotations.PrintNamedStep('device_status_check')
409 cmd = ['build/android/buildbot/bb_device_status_check.py']
410 if options.restart_usb:
411 cmd.append('--restart-usb')
412 RunCmd(cmd, halt_on_failure=True)
415 def GetDeviceSetupStepCmds():
417 ('device_status_check', DeviceStatusCheck),
418 ('provision_devices', ProvisionDevices),
422 def RunUnitTests(options):
423 suites = gtest_config.STABLE_TEST_SUITES
425 suites = [s for s in suites
426 if s not in gtest_config.ASAN_EXCLUDED_TEST_SUITES]
427 RunTestSuites(options, suites)
430 def RunInstrumentationTests(options):
431 for test in INSTRUMENTATION_TESTS.itervalues():
432 RunInstrumentationSuite(options, test)
435 def RunWebkitTests(options):
436 RunTestSuites(options, ['webkit_unit_tests', 'blink_heap_unittests'])
437 RunWebkitLint(options.target)
440 def RunWebRTCChromiumTests(options):
441 RunTestSuites(options, gtest_config.WEBRTC_CHROMIUM_TEST_SUITES)
444 def RunWebRTCNativeTests(options):
445 RunTestSuites(options, gtest_config.WEBRTC_NATIVE_TEST_SUITES)
448 def RunGPUTests(options):
449 InstallApk(options, INSTRUMENTATION_TESTS['ContentShell'], False)
451 bb_annotations.PrintNamedStep('gpu_tests')
452 revision = _GetRevision(options)
453 RunCmd(['content/test/gpu/run_gpu_test.py',
456 'android-content-shell',
459 '--upload-refimg-to-cloud-storage',
460 '--refimg-cloud-storage-bucket',
461 'chromium-gpu-archive/reference-images',
464 '--test-machine-name',
466 options.build_properties.get('buildername', 'noname'))])
468 bb_annotations.PrintNamedStep('webgl_conformance_tests')
469 RunCmd(['content/test/gpu/run_gpu_test.py',
470 '--browser=android-content-shell', 'webgl_conformance',
471 '--webgl-conformance-version=1.0.1'])
474 def GetTestStepCmds():
476 ('chromedriver', RunChromeDriverTests),
477 ('gpu', RunGPUTests),
478 ('mojo', RunMojoTests),
479 ('telemetry_perf_unittests', RunTelemetryPerfUnitTests),
480 ('unit', RunUnitTests),
481 ('ui', RunInstrumentationTests),
482 ('webkit', RunWebkitTests),
483 ('webkit_layout', RunWebkitLayoutTests),
484 ('webrtc_chromium', RunWebRTCChromiumTests),
485 ('webrtc_native', RunWebRTCNativeTests),
489 def MakeGSPath(options, gs_base_dir):
490 revision = _GetRevision(options)
491 bot_id = options.build_properties.get('buildername', 'testing')
492 randhash = hashlib.sha1(str(random.random())).hexdigest()
493 gs_path = '%s/%s/%s/%s' % (gs_base_dir, bot_id, revision, randhash)
494 # remove double slashes, happens with blank revisions and confuses gsutil
495 gs_path = re.sub('/+', '/', gs_path)
498 def UploadHTML(options, gs_base_dir, dir_to_upload, link_text,
499 link_rel_path='index.html', gs_url=GS_URL):
500 """Uploads directory at |dir_to_upload| to Google Storage and output a link.
503 options: Command line options.
504 gs_base_dir: The Google Storage base directory (e.g.
505 'chromium-code-coverage/java')
506 dir_to_upload: Absolute path to the directory to be uploaded.
507 link_text: Link text to be displayed on the step.
508 link_rel_path: Link path relative to |dir_to_upload|.
509 gs_url: Google storage URL.
511 gs_path = MakeGSPath(options, gs_base_dir)
512 RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-R', dir_to_upload, 'gs://%s' % gs_path])
513 bb_annotations.PrintLink(link_text,
514 '%s/%s/%s' % (gs_url, gs_path, link_rel_path))
517 def GenerateJavaCoverageReport(options):
518 """Generates an HTML coverage report using EMMA and uploads it."""
519 bb_annotations.PrintNamedStep('java_coverage_report')
521 coverage_html = os.path.join(options.coverage_dir, 'coverage_html')
522 RunCmd(['build/android/generate_emma_html.py',
523 '--coverage-dir', options.coverage_dir,
524 '--metadata-dir', os.path.join(CHROME_OUT_DIR, options.target),
526 '--output', os.path.join(coverage_html, 'index.html')])
530 def LogcatDump(options):
531 # Print logcat, kill logcat monitor
532 bb_annotations.PrintNamedStep('logcat_dump')
533 logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log.txt')
534 RunCmd([SrcPath('build' , 'android', 'adb_logcat_printer.py'),
535 '--output-path', logcat_file, LOGCAT_DIR])
536 gs_path = MakeGSPath(options, 'chromium-android/logcat_dumps')
537 RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-z', 'txt', logcat_file,
538 'gs://%s' % gs_path])
539 bb_annotations.PrintLink('logcat dump', '%s/%s' % (GS_AUTH_URL, gs_path))
542 def RunStackToolSteps(options):
543 """Run stack tool steps.
545 Stack tool is run for logcat dump, optionally for ASAN.
547 bb_annotations.PrintNamedStep('Run stack tool with logcat dump')
548 logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log.txt')
549 RunCmd([os.path.join(CHROME_SRC_DIR, 'third_party', 'android_platform',
550 'development', 'scripts', 'stack'),
551 '--more-info', logcat_file])
552 if options.asan_symbolize:
553 bb_annotations.PrintNamedStep('Run stack tool for ASAN')
555 os.path.join(CHROME_SRC_DIR, 'build', 'android', 'asan_symbolize.py'),
559 def GenerateTestReport(options):
560 bb_annotations.PrintNamedStep('test_report')
561 for report in glob.glob(
562 os.path.join(CHROME_OUT_DIR, options.target, 'test_logs', '*.log')):
563 RunCmd(['cat', report])
567 def MainTestWrapper(options):
569 # Spawn logcat monitor
572 # Run all device setup steps
573 for _, cmd in GetDeviceSetupStepCmds():
577 test_obj = INSTRUMENTATION_TESTS[options.install]
578 InstallApk(options, test_obj, print_step=True)
580 if options.test_filter:
581 bb_utils.RunSteps(options.test_filter, GetTestStepCmds(), options)
583 if options.coverage_bucket:
584 coverage_html = GenerateJavaCoverageReport(options)
585 UploadHTML(options, '%s/java' % options.coverage_bucket, coverage_html,
587 shutil.rmtree(coverage_html, ignore_errors=True)
589 if options.experimental:
590 RunTestSuites(options, gtest_config.EXPERIMENTAL_TEST_SUITES)
593 # Run all post test steps
595 if not options.disable_stack_tool:
596 RunStackToolSteps(options)
597 GenerateTestReport(options)
598 # KillHostHeartbeat() has logic to check if heartbeat process is running,
599 # and kills only if it finds the process is running on the host.
600 provision_devices.KillHostHeartbeat()
603 def GetDeviceStepsOptParser():
604 parser = bb_utils.GetParser()
605 parser.add_option('--experimental', action='store_true',
606 help='Run experiemental tests')
607 parser.add_option('-f', '--test-filter', metavar='<filter>', default=[],
609 help=('Run a test suite. Test suites: "%s"' %
610 '", "'.join(VALID_TESTS)))
611 parser.add_option('--gtest-filter',
612 help='Filter for running a subset of tests of a gtest test')
613 parser.add_option('--asan', action='store_true', help='Run tests with asan.')
614 parser.add_option('--install', metavar='<apk name>',
615 help='Install an apk by name')
616 parser.add_option('--no-reboot', action='store_true',
617 help='Do not reboot devices during provisioning.')
618 parser.add_option('--coverage-bucket',
619 help=('Bucket name to store coverage results. Coverage is '
620 'only run if this is set.'))
621 parser.add_option('--restart-usb', action='store_true',
622 help='Restart usb ports before device status check.')
624 '--flakiness-server',
625 help=('The flakiness dashboard server to which the results should be '
628 '--auto-reconnect', action='store_true',
629 help='Push script to device which restarts adbd on disconnections.')
631 '--logcat-dump-output',
632 help='The logcat dump output will be "tee"-ed into this file')
633 parser.add_option('--disable-stack-tool', action='store_true',
634 help='Do not run stack tool.')
635 parser.add_option('--asan-symbolize', action='store_true',
636 help='Run stack tool for ASAN')
641 parser = GetDeviceStepsOptParser()
642 options, args = parser.parse_args(argv[1:])
645 return sys.exit('Unused args %s' % args)
647 unknown_tests = set(options.test_filter) - VALID_TESTS
649 return sys.exit('Unknown tests %s' % list(unknown_tests))
651 setattr(options, 'target', options.factory_properties.get('target', 'Debug'))
652 if options.coverage_bucket:
653 setattr(options, 'coverage_dir',
654 os.path.join(CHROME_OUT_DIR, options.target, 'coverage'))
656 MainTestWrapper(options)
659 if __name__ == '__main__':
660 sys.exit(main(sys.argv))