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.
10 import multiprocessing
20 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
21 import provision_devices
22 from pylib import android_commands
23 from pylib import constants
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 sys.path.append(os.path.join(
30 CHROME_SRC_DIR, 'third_party', 'android_testrunner'))
34 SLAVE_SCRIPTS_DIR = os.path.join(bb_utils.BB_BUILD_DIR, 'scripts', 'slave')
35 LOGCAT_DIR = os.path.join(bb_utils.CHROME_OUT_DIR, 'logcat')
36 GS_URL = 'https://storage.googleapis.com'
38 # Describes an instrumation test suite:
39 # test: Name of test we're running.
40 # apk: apk to be installed.
41 # apk_package: package for the apk to be installed.
42 # test_apk: apk to run tests on.
43 # test_data: data folder in format destination:source.
44 # host_driven_root: The host-driven test root directory.
45 # annotation: Annotation of the tests to include.
46 # exclude_annotation: The annotation of the tests to exclude.
47 I_TEST = collections.namedtuple('InstrumentationTest', [
48 'name', 'apk', 'apk_package', 'test_apk', 'test_data', 'host_driven_root',
49 'annotation', 'exclude_annotation', 'extra_flags'])
53 return os.path.join(CHROME_SRC_DIR, *path)
56 def I(name, apk, apk_package, test_apk, test_data, host_driven_root=None,
57 annotation=None, exclude_annotation=None, extra_flags=None):
58 return I_TEST(name, apk, apk_package, test_apk, test_data, host_driven_root,
59 annotation, exclude_annotation, extra_flags)
61 INSTRUMENTATION_TESTS = dict((suite.name, suite) for suite in [
64 'org.chromium.content_shell_apk',
66 'content:content/test/data/android/device_files'),
67 I('ChromiumTestShell',
68 'ChromiumTestShell.apk',
69 'org.chromium.chrome.testshell',
70 'ChromiumTestShellTest',
71 'chrome:chrome/test/data/android/device_files',
72 constants.CHROMIUM_TEST_SHELL_HOST_DRIVEN_DIR),
75 'org.chromium.android_webview.shell',
77 'webview:android_webview/test/data/device_files'),
80 VALID_TESTS = set(['chromedriver', 'gpu', 'ui', 'unit', 'webkit',
81 'webkit_layout', 'webrtc_chromium', 'webrtc_native'])
83 RunCmd = bb_utils.RunCmd
86 def _GetRevision(options):
87 """Get the SVN revision number.
90 options: options object.
95 revision = options.build_properties.get('got_revision')
97 revision = options.build_properties.get('revision', 'testing')
101 # multiprocessing map_async requires a top-level function for pickle library.
102 def RebootDeviceSafe(device):
103 """Reboot a device, wait for it to start, and squelch timeout exceptions."""
105 android_commands.AndroidCommands(device).Reboot(True)
106 except errors.DeviceUnresponsiveError as e:
111 """Reboot all attached and online devices."""
112 # Early return here to avoid presubmit dependence on adb,
113 # which might not exist in this checkout.
116 devices = android_commands.GetAttachedDevices(emulator=False)
117 print 'Rebooting: %s' % devices
119 pool = multiprocessing.Pool(len(devices))
120 results = pool.map_async(RebootDeviceSafe, devices).get(99999)
122 for device, result in zip(devices, results):
124 print '%s failed to startup.' % device
127 bb_annotations.PrintWarning()
129 print 'Reboots complete.'
132 def RunTestSuites(options, suites):
133 """Manages an invocation of test_runner.py for gtests.
136 options: options object.
137 suites: List of suite names to run.
140 if options.target == 'Release':
141 args.append('--release')
143 args.append('--tool=asan')
145 bb_annotations.PrintNamedStep(suite)
146 cmd = ['build/android/test_runner.py', 'gtest', '-s', suite] + args
147 if suite == 'content_browsertests':
148 cmd.append('--num_retries=1')
152 def RunChromeDriverTests(options):
153 """Run all the steps for running chromedriver tests."""
154 bb_annotations.PrintNamedStep('chromedriver_annotation')
155 RunCmd(['chrome/test/chromedriver/run_buildbot_steps.py',
156 '--android-packages=%s,%s,%s' %
157 (constants.PACKAGE_INFO['chromium_test_shell'].package,
158 constants.PACKAGE_INFO['chrome_stable'].package,
159 constants.PACKAGE_INFO['chrome_beta'].package),
160 '--revision=%s' % _GetRevision(options),
164 def InstallApk(options, test, print_step=False):
165 """Install an apk to all phones.
168 options: options object
169 test: An I_TEST namedtuple
170 print_step: Print a buildbot step
173 bb_annotations.PrintNamedStep('install_%s' % test.name.lower())
175 args = ['--apk', test.apk, '--apk_package', test.apk_package]
176 if options.target == 'Release':
177 args.append('--release')
179 RunCmd(['build/android/adb_install_apk.py'] + args, halt_on_failure=True)
182 def RunInstrumentationSuite(options, test, flunk_on_failure=True,
183 python_only=False, official_build=False):
184 """Manages an invocation of test_runner.py for instrumentation tests.
187 options: options object
188 test: An I_TEST namedtuple
189 flunk_on_failure: Flunk the step if tests fail.
190 Python: Run only host driven Python tests.
191 official_build: Run official-build tests.
193 bb_annotations.PrintNamedStep('%s_instrumentation_tests' % test.name.lower())
195 InstallApk(options, test)
196 args = ['--test-apk', test.test_apk, '--test_data', test.test_data,
198 if options.target == 'Release':
199 args.append('--release')
201 args.append('--tool=asan')
202 if options.flakiness_server:
203 args.append('--flakiness-dashboard-server=%s' %
204 options.flakiness_server)
205 if options.coverage_bucket:
206 args.append('--coverage-dir=%s' % options.coverage_dir)
207 if test.host_driven_root:
208 args.append('--host-driven-root=%s' % test.host_driven_root)
210 args.extend(['-A', test.annotation])
211 if test.exclude_annotation:
212 args.extend(['-E', test.exclude_annotation])
214 args.extend(test.extra_flags)
218 # The option needs to be assigned 'True' as it does not have an action
219 # associated with it.
220 args.append('--official-build')
222 RunCmd(['build/android/test_runner.py', 'instrumentation'] + args,
223 flunk_on_failure=flunk_on_failure)
226 def RunWebkitLint(target):
227 """Lint WebKit's TestExpectation files."""
228 bb_annotations.PrintNamedStep('webkit_lint')
229 RunCmd([SrcPath('webkit/tools/layout_tests/run_webkit_tests.py'),
235 def RunWebkitLayoutTests(options):
236 """Run layout tests on an actual device."""
237 bb_annotations.PrintNamedStep('webkit_tests')
240 '--no-new-test-results',
241 '--full-results-html',
242 '--clobber-old-results',
243 '--exit-after-n-failures', '5000',
244 '--exit-after-n-crashes-or-timeouts', '100',
245 '--debug-rwt-logging',
246 '--results-directory', '../layout-test-results',
247 '--target', options.target,
248 '--builder-name', options.build_properties.get('buildername', ''),
249 '--build-number', str(options.build_properties.get('buildnumber', '')),
250 '--master-name', 'ChromiumWebkit', # TODO: Get this from the cfg.
251 '--build-name', options.build_properties.get('buildername', ''),
252 '--platform=android']
254 for flag in 'test_results_server', 'driver_name', 'additional_drt_flag':
255 if flag in options.factory_properties:
256 cmd_args.extend(['--%s' % flag.replace('_', '-'),
257 options.factory_properties.get(flag)])
259 for f in options.factory_properties.get('additional_expectations', []):
261 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
263 # TODO(dpranke): Remove this block after
264 # https://codereview.chromium.org/12927002/ lands.
265 for f in options.factory_properties.get('additional_expectations_files', []):
267 ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
269 exit_code = RunCmd([SrcPath('webkit/tools/layout_tests/run_webkit_tests.py')]
271 if exit_code == 255: # test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
272 bb_annotations.PrintMsg('?? (crashed or hung)')
273 elif exit_code == 254: # test_run_results.NO_DEVICES_EXIT_STATUS
274 bb_annotations.PrintMsg('?? (no devices found)')
275 elif exit_code == 253: # test_run_results.NO_TESTS_EXIT_STATUS
276 bb_annotations.PrintMsg('?? (no tests found)')
278 full_results_path = os.path.join('..', 'layout-test-results',
280 if os.path.exists(full_results_path):
281 full_results = json.load(open(full_results_path))
282 unexpected_passes, unexpected_failures, unexpected_flakes = (
283 _ParseLayoutTestResults(full_results))
284 if unexpected_failures:
285 _PrintDashboardLink('failed', unexpected_failures,
287 elif unexpected_passes:
288 _PrintDashboardLink('unexpected passes', unexpected_passes,
290 if unexpected_flakes:
291 _PrintDashboardLink('unexpected flakes', unexpected_flakes,
294 if exit_code == 0 and (unexpected_passes or unexpected_flakes):
295 # If exit_code != 0, RunCmd() will have already printed an error.
296 bb_annotations.PrintWarning()
298 bb_annotations.PrintError()
299 bb_annotations.PrintMsg('?? (results missing)')
301 if options.factory_properties.get('archive_webkit_results', False):
302 bb_annotations.PrintNamedStep('archive_webkit_results')
303 base = 'https://storage.googleapis.com/chromium-layout-test-archives'
304 builder_name = options.build_properties.get('buildername', '')
305 build_number = str(options.build_properties.get('buildnumber', ''))
306 results_link = '%s/%s/%s/layout-test-results/results.html' % (
307 base, EscapeBuilderName(builder_name), build_number)
308 bb_annotations.PrintLink('results', results_link)
309 bb_annotations.PrintLink('(zip)', '%s/%s/%s/layout-test-results.zip' % (
310 base, EscapeBuilderName(builder_name), build_number))
311 gs_bucket = 'gs://chromium-layout-test-archives'
312 RunCmd([os.path.join(SLAVE_SCRIPTS_DIR, 'chromium',
313 'archive_layout_test_results.py'),
314 '--results-dir', '../../layout-test-results',
315 '--build-dir', CHROME_OUT_DIR,
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 adb = android_commands.AndroidCommands()
400 adb.RestartAdbServer()
401 RunCmd(['sleep', '1'])
405 provision_cmd = ['build/android/provision_devices.py', '-t', options.target]
406 if options.auto_reconnect:
407 provision_cmd.append('--auto-reconnect')
408 RunCmd(provision_cmd)
411 def DeviceStatusCheck(options):
412 bb_annotations.PrintNamedStep('device_status_check')
413 cmd = ['build/android/buildbot/bb_device_status_check.py']
414 if options.restart_usb:
415 cmd.append('--restart-usb')
416 RunCmd(cmd, halt_on_failure=True)
419 def GetDeviceSetupStepCmds():
421 ('provision_devices', ProvisionDevices),
422 ('device_status_check', DeviceStatusCheck),
426 def RunUnitTests(options):
427 RunTestSuites(options, gtest_config.STABLE_TEST_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'])
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 RunCmd(['content/test/gpu/run_gpu_test',
453 '--browser=android-content-shell', 'pixel'])
455 bb_annotations.PrintNamedStep('webgl_conformance_tests')
456 RunCmd(['content/test/gpu/run_gpu_test',
457 '--browser=android-content-shell', 'webgl_conformance',
458 '--webgl-conformance-version=1.0.1'])
461 def GetTestStepCmds():
463 ('chromedriver', RunChromeDriverTests),
464 ('gpu', RunGPUTests),
465 ('unit', RunUnitTests),
466 ('ui', RunInstrumentationTests),
467 ('webkit', RunWebkitTests),
468 ('webkit_layout', RunWebkitLayoutTests),
469 ('webrtc_chromium', RunWebRTCChromiumTests),
470 ('webrtc_native', RunWebRTCNativeTests),
474 def UploadHTML(options, gs_base_dir, dir_to_upload, link_text,
475 link_rel_path='index.html', gs_url=GS_URL):
476 """Uploads directory at |dir_to_upload| to Google Storage and output a link.
479 options: Command line options.
480 gs_base_dir: The Google Storage base directory (e.g.
481 'chromium-code-coverage/java')
482 dir_to_upload: Absolute path to the directory to be uploaded.
483 link_text: Link text to be displayed on the step.
484 link_rel_path: Link path relative to |dir_to_upload|.
485 gs_url: Google storage URL.
487 revision = _GetRevision(options)
488 bot_id = options.build_properties.get('buildername', 'testing')
489 randhash = hashlib.sha1(str(random.random())).hexdigest()
490 gs_path = '%s/%s/%s/%s' % (gs_base_dir, bot_id, revision, randhash)
491 RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-R', dir_to_upload, 'gs://%s' % gs_path])
492 bb_annotations.PrintLink(link_text,
493 '%s/%s/%s' % (gs_url, gs_path, link_rel_path))
496 def GenerateJavaCoverageReport(options):
497 """Generates an HTML coverage report using EMMA and uploads it."""
498 bb_annotations.PrintNamedStep('java_coverage_report')
500 coverage_html = os.path.join(options.coverage_dir, 'coverage_html')
501 RunCmd(['build/android/generate_emma_html.py',
502 '--coverage-dir', options.coverage_dir,
503 '--metadata-dir', os.path.join(CHROME_OUT_DIR, options.target),
505 '--output', os.path.join(coverage_html, 'index.html')])
509 def LogcatDump(options):
510 # Print logcat, kill logcat monitor
511 bb_annotations.PrintNamedStep('logcat_dump')
512 logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log')
513 with open(logcat_file, 'w') as f:
515 os.path.join(CHROME_SRC_DIR, 'build', 'android',
516 'adb_logcat_printer.py'),
517 LOGCAT_DIR], stdout=f)
518 RunCmd(['cat', logcat_file])
521 def GenerateTestReport(options):
522 bb_annotations.PrintNamedStep('test_report')
523 for report in glob.glob(
524 os.path.join(CHROME_OUT_DIR, options.target, 'test_logs', '*.log')):
525 RunCmd(['cat', report])
529 def MainTestWrapper(options):
531 # Spawn logcat monitor
534 # Run all device setup steps
535 for _, cmd in GetDeviceSetupStepCmds():
539 test_obj = INSTRUMENTATION_TESTS[options.install]
540 InstallApk(options, test_obj, print_step=True)
542 if options.test_filter:
543 bb_utils.RunSteps(options.test_filter, GetTestStepCmds(), options)
545 if options.coverage_bucket:
546 coverage_html = GenerateJavaCoverageReport(options)
547 UploadHTML(options, '%s/java' % options.coverage_bucket, coverage_html,
550 if options.experimental:
551 RunTestSuites(options, gtest_config.EXPERIMENTAL_TEST_SUITES)
554 # Run all post test steps
556 GenerateTestReport(options)
557 # KillHostHeartbeat() has logic to check if heartbeat process is running,
558 # and kills only if it finds the process is running on the host.
559 provision_devices.KillHostHeartbeat()
562 def GetDeviceStepsOptParser():
563 parser = bb_utils.GetParser()
564 parser.add_option('--experimental', action='store_true',
565 help='Run experiemental tests')
566 parser.add_option('-f', '--test-filter', metavar='<filter>', default=[],
568 help=('Run a test suite. Test suites: "%s"' %
569 '", "'.join(VALID_TESTS)))
570 parser.add_option('--asan', action='store_true', help='Run tests with asan.')
571 parser.add_option('--install', metavar='<apk name>',
572 help='Install an apk by name')
573 parser.add_option('--reboot', action='store_true',
574 help='Reboot devices before running tests')
575 parser.add_option('--coverage-bucket',
576 help=('Bucket name to store coverage results. Coverage is '
577 'only run if this is set.'))
578 parser.add_option('--restart-usb', action='store_true',
579 help='Restart usb ports before device status check.')
581 '--flakiness-server',
582 help=('The flakiness dashboard server to which the results should be '
585 '--auto-reconnect', action='store_true',
586 help='Push script to device which restarts adbd on disconnections.')
588 '--logcat-dump-output',
589 help='The logcat dump output will be "tee"-ed into this file')
595 parser = GetDeviceStepsOptParser()
596 options, args = parser.parse_args(argv[1:])
599 return sys.exit('Unused args %s' % args)
601 unknown_tests = set(options.test_filter) - VALID_TESTS
603 return sys.exit('Unknown tests %s' % list(unknown_tests))
605 setattr(options, 'target', options.factory_properties.get('target', 'Debug'))
606 if options.coverage_bucket:
607 setattr(options, 'coverage_dir',
608 os.path.join(CHROME_OUT_DIR, options.target, 'coverage'))
610 MainTestWrapper(options)
613 if __name__ == '__main__':
614 sys.exit(main(sys.argv))