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