blob: 8655720810882b7b9c3d834348890352510315bb [file] [log] [blame]
Ben Murdocheb525c52013-07-10 11:40:50 +01001#!/usr/bin/env python
2#
3# Copyright 2013 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Runs all types of tests from one unified interface.
8
9TODO(gkanwar):
10* Add options to run Monkey tests.
11"""
12
13import collections
14import optparse
15import os
Ben Murdochca12bfa2013-07-23 11:17:05 +010016import shutil
Ben Murdocheb525c52013-07-10 11:40:50 +010017import sys
18
Ben Murdocheb525c52013-07-10 11:40:50 +010019from pylib import constants
20from pylib import ports
21from pylib.base import base_test_result
Ben Murdochca12bfa2013-07-23 11:17:05 +010022from pylib.base import test_dispatcher
Ben Murdochca12bfa2013-07-23 11:17:05 +010023from pylib.gtest import gtest_config
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +010024from pylib.gtest import setup as gtest_setup
25from pylib.gtest import test_options as gtest_test_options
Ben Murdoch32409262013-08-07 11:04:47 +010026from pylib.host_driven import setup as host_driven_setup
Ben Murdochca12bfa2013-07-23 11:17:05 +010027from pylib.instrumentation import setup as instrumentation_setup
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +010028from pylib.instrumentation import test_options as instrumentation_test_options
Ben Murdochbb1529c2013-08-08 10:24:53 +010029from pylib.monkey import setup as monkey_setup
30from pylib.monkey import test_options as monkey_test_options
Ben Murdochca12bfa2013-07-23 11:17:05 +010031from pylib.uiautomator import setup as uiautomator_setup
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +010032from pylib.uiautomator import test_options as uiautomator_test_options
Ben Murdochca12bfa2013-07-23 11:17:05 +010033from pylib.utils import report_results
34from pylib.utils import run_tests_helper
Ben Murdocheb525c52013-07-10 11:40:50 +010035
36
37_SDK_OUT_DIR = os.path.join(constants.DIR_SOURCE_ROOT, 'out')
38
39
40def AddBuildTypeOption(option_parser):
41 """Adds the build type option to |option_parser|."""
42 default_build_type = 'Debug'
43 if 'BUILDTYPE' in os.environ:
44 default_build_type = os.environ['BUILDTYPE']
45 option_parser.add_option('--debug', action='store_const', const='Debug',
46 dest='build_type', default=default_build_type,
47 help=('If set, run test suites under out/Debug. '
48 'Default is env var BUILDTYPE or Debug.'))
49 option_parser.add_option('--release', action='store_const',
50 const='Release', dest='build_type',
51 help=('If set, run test suites under out/Release.'
52 ' Default is env var BUILDTYPE or Debug.'))
53
54
Ben Murdocheb525c52013-07-10 11:40:50 +010055def AddCommonOptions(option_parser):
56 """Adds all common options to |option_parser|."""
57
58 AddBuildTypeOption(option_parser)
59
Ben Murdocheb525c52013-07-10 11:40:50 +010060 option_parser.add_option('-c', dest='cleanup_test_files',
61 help='Cleanup test files on the device after run',
62 action='store_true')
63 option_parser.add_option('--num_retries', dest='num_retries', type='int',
64 default=2,
65 help=('Number of retries for a test before '
66 'giving up.'))
67 option_parser.add_option('-v',
68 '--verbose',
69 dest='verbose_count',
70 default=0,
71 action='count',
72 help='Verbose level (multiple times for more)')
Ben Murdocheb525c52013-07-10 11:40:50 +010073 option_parser.add_option('--tool',
74 dest='tool',
75 help=('Run the test under a tool '
76 '(use --tool help to list them)'))
77 option_parser.add_option('--flakiness-dashboard-server',
78 dest='flakiness_dashboard_server',
79 help=('Address of the server that is hosting the '
80 'Chrome for Android flakiness dashboard.'))
81 option_parser.add_option('--skip-deps-push', dest='push_deps',
82 action='store_false', default=True,
83 help=('Do not push dependencies to the device. '
84 'Use this at own risk for speeding up test '
85 'execution on local machine.'))
Ben Murdocheb525c52013-07-10 11:40:50 +010086 option_parser.add_option('-d', '--device', dest='test_device',
87 help=('Target device for the test suite '
88 'to run on.'))
89
90
91def ProcessCommonOptions(options):
92 """Processes and handles all common options."""
Ben Murdocheb525c52013-07-10 11:40:50 +010093 run_tests_helper.SetLogLevel(options.verbose_count)
94
95
Ben Murdoch7dbb3d52013-07-17 14:55:54 +010096def AddGTestOptions(option_parser):
97 """Adds gtest options to |option_parser|."""
98
99 option_parser.usage = '%prog gtest [options]'
100 option_parser.command_list = []
101 option_parser.example = '%prog gtest -s base_unittests'
102
Ben Murdochca12bfa2013-07-23 11:17:05 +0100103 # TODO(gkanwar): Make this option required
104 option_parser.add_option('-s', '--suite', dest='suite_name',
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100105 help=('Executable name of the test suite to run '
106 '(use -s help to list them).'))
Ben Murdochfb250652013-07-31 11:42:55 +0100107 option_parser.add_option('-f', '--gtest_filter', dest='test_filter',
108 help='googletest-style filter string.')
109 option_parser.add_option('-a', '--test_arguments', dest='test_arguments',
110 help='Additional arguments to pass to the test.')
111 option_parser.add_option('-t', dest='timeout',
112 help='Timeout to wait for each test',
113 type='int',
114 default=60)
Ben Murdocheb525c52013-07-10 11:40:50 +0100115 # TODO(gkanwar): Move these to Common Options once we have the plumbing
116 # in our other test types to handle these commands
Ben Murdocheb525c52013-07-10 11:40:50 +0100117 AddCommonOptions(option_parser)
118
119
Ben Murdochca12bfa2013-07-23 11:17:05 +0100120def ProcessGTestOptions(options):
121 """Intercept test suite help to list test suites.
122
123 Args:
124 options: Command line options.
Ben Murdochca12bfa2013-07-23 11:17:05 +0100125 """
126 if options.suite_name == 'help':
127 print 'Available test suites are:'
Ben Murdochfb250652013-07-31 11:42:55 +0100128 for test_suite in (gtest_config.STABLE_TEST_SUITES +
129 gtest_config.EXPERIMENTAL_TEST_SUITES):
130 print test_suite
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100131 sys.exit(0)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100132
133 # Convert to a list, assuming all test suites if nothing was specified.
134 # TODO(gkanwar): Require having a test suite
135 if options.suite_name:
136 options.suite_name = [options.suite_name]
137 else:
Ben Murdochfb250652013-07-31 11:42:55 +0100138 options.suite_name = [s for s in gtest_config.STABLE_TEST_SUITES]
Ben Murdochca12bfa2013-07-23 11:17:05 +0100139
140
Ben Murdocheb525c52013-07-10 11:40:50 +0100141def AddJavaTestOptions(option_parser):
142 """Adds the Java test options to |option_parser|."""
143
144 option_parser.add_option('-f', '--test_filter', dest='test_filter',
145 help=('Test filter (if not fully qualified, '
146 'will run all matches).'))
147 option_parser.add_option(
148 '-A', '--annotation', dest='annotation_str',
149 help=('Comma-separated list of annotations. Run only tests with any of '
150 'the given annotations. An annotation can be either a key or a '
151 'key-values pair. A test that has no annotation is considered '
152 '"SmallTest".'))
153 option_parser.add_option(
154 '-E', '--exclude-annotation', dest='exclude_annotation_str',
155 help=('Comma-separated list of annotations. Exclude tests with these '
156 'annotations.'))
Ben Murdocheb525c52013-07-10 11:40:50 +0100157 option_parser.add_option('--screenshot', dest='screenshot_failures',
158 action='store_true',
159 help='Capture screenshots of test failures')
160 option_parser.add_option('--save-perf-json', action='store_true',
161 help='Saves the JSON file for each UI Perf test.')
Ben Murdoch32409262013-08-07 11:04:47 +0100162 option_parser.add_option('--official-build', action='store_true',
163 help='Run official build tests.')
Ben Murdocheb525c52013-07-10 11:40:50 +0100164 option_parser.add_option('--keep_test_server_ports',
165 action='store_true',
166 help=('Indicates the test server ports must be '
167 'kept. When this is run via a sharder '
168 'the test server ports should be kept and '
169 'should not be reset.'))
Ben Murdocheb525c52013-07-10 11:40:50 +0100170 option_parser.add_option('--test_data', action='append', default=[],
171 help=('Each instance defines a directory of test '
172 'data that should be copied to the target(s) '
173 'before running the tests. The argument '
174 'should be of the form <target>:<source>, '
175 '<target> is relative to the device data'
176 'directory, and <source> is relative to the '
177 'chromium build directory.'))
178
179
180def ProcessJavaTestOptions(options, error_func):
181 """Processes options/arguments and populates |options| with defaults."""
182
Ben Murdocheb525c52013-07-10 11:40:50 +0100183 if options.annotation_str:
184 options.annotations = options.annotation_str.split(',')
185 elif options.test_filter:
186 options.annotations = []
187 else:
Ben Murdochca12bfa2013-07-23 11:17:05 +0100188 options.annotations = ['Smoke', 'SmallTest', 'MediumTest', 'LargeTest',
189 'EnormousTest']
Ben Murdocheb525c52013-07-10 11:40:50 +0100190
191 if options.exclude_annotation_str:
192 options.exclude_annotations = options.exclude_annotation_str.split(',')
193 else:
194 options.exclude_annotations = []
195
196 if not options.keep_test_server_ports:
197 if not ports.ResetTestServerPortAllocation():
198 raise Exception('Failed to reset test server port.')
199
200
201def AddInstrumentationTestOptions(option_parser):
202 """Adds Instrumentation test options to |option_parser|."""
203
204 option_parser.usage = '%prog instrumentation [options]'
205 option_parser.command_list = []
Ben Murdoch558790d2013-07-30 15:19:42 +0100206 option_parser.example = ('%prog instrumentation '
Ben Murdocheb525c52013-07-10 11:40:50 +0100207 '--test-apk=ChromiumTestShellTest')
208
209 AddJavaTestOptions(option_parser)
210 AddCommonOptions(option_parser)
211
Ben Murdoch32409262013-08-07 11:04:47 +0100212 option_parser.add_option('-j', '--java_only', action='store_true',
213 default=False, help='Run only the Java tests.')
214 option_parser.add_option('-p', '--python_only', action='store_true',
215 default=False,
216 help='Run only the host-driven tests.')
217 option_parser.add_option('--python_test_root',
218 help='Root of the host-driven tests.')
Ben Murdocheb525c52013-07-10 11:40:50 +0100219 option_parser.add_option('-w', '--wait_debugger', dest='wait_for_debugger',
220 action='store_true',
221 help='Wait for debugger.')
Ben Murdocheb525c52013-07-10 11:40:50 +0100222 option_parser.add_option(
223 '--test-apk', dest='test_apk',
224 help=('The name of the apk containing the tests '
225 '(without the .apk extension; e.g. "ContentShellTest"). '
226 'Alternatively, this can be a full path to the apk.'))
227
228
229def ProcessInstrumentationOptions(options, error_func):
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100230 """Processes options/arguments and populate |options| with defaults.
231
232 Args:
233 options: optparse.Options object.
234 error_func: Function to call with the error message in case of an error.
235
236 Returns:
237 An InstrumentationOptions named tuple which contains all options relevant to
238 instrumentation tests.
239 """
Ben Murdocheb525c52013-07-10 11:40:50 +0100240
241 ProcessJavaTestOptions(options, error_func)
242
Ben Murdoch32409262013-08-07 11:04:47 +0100243 if options.java_only and options.python_only:
244 error_func('Options java_only (-j) and python_only (-p) '
245 'are mutually exclusive.')
246 options.run_java_tests = True
247 options.run_python_tests = True
248 if options.java_only:
249 options.run_python_tests = False
250 elif options.python_only:
251 options.run_java_tests = False
252
253 if not options.python_test_root:
254 options.run_python_tests = False
255
Ben Murdocheb525c52013-07-10 11:40:50 +0100256 if not options.test_apk:
257 error_func('--test-apk must be specified.')
258
259 if os.path.exists(options.test_apk):
260 # The APK is fully qualified, assume the JAR lives along side.
261 options.test_apk_path = options.test_apk
262 options.test_apk_jar_path = (os.path.splitext(options.test_apk_path)[0] +
263 '.jar')
264 else:
265 options.test_apk_path = os.path.join(_SDK_OUT_DIR,
266 options.build_type,
267 constants.SDK_BUILD_APKS_DIR,
268 '%s.apk' % options.test_apk)
269 options.test_apk_jar_path = os.path.join(
270 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_TEST_JAVALIB_DIR,
271 '%s.jar' % options.test_apk)
272
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100273 return instrumentation_test_options.InstrumentationOptions(
274 options.build_type,
275 options.tool,
276 options.cleanup_test_files,
277 options.push_deps,
278 options.annotations,
279 options.exclude_annotations,
280 options.test_filter,
281 options.test_data,
282 options.save_perf_json,
283 options.screenshot_failures,
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100284 options.wait_for_debugger,
285 options.test_apk,
286 options.test_apk_path,
287 options.test_apk_jar_path)
288
Ben Murdocheb525c52013-07-10 11:40:50 +0100289
290def AddUIAutomatorTestOptions(option_parser):
291 """Adds UI Automator test options to |option_parser|."""
292
293 option_parser.usage = '%prog uiautomator [options]'
294 option_parser.command_list = []
295 option_parser.example = (
296 '%prog uiautomator --test-jar=chromium_testshell_uiautomator_tests'
297 ' --package-name=org.chromium.chrome.testshell')
298 option_parser.add_option(
299 '--package-name',
300 help='The package name used by the apk containing the application.')
301 option_parser.add_option(
302 '--test-jar', dest='test_jar',
303 help=('The name of the dexed jar containing the tests (without the '
304 '.dex.jar extension). Alternatively, this can be a full path '
305 'to the jar.'))
306
307 AddJavaTestOptions(option_parser)
308 AddCommonOptions(option_parser)
309
310
311def ProcessUIAutomatorOptions(options, error_func):
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100312 """Processes UIAutomator options/arguments.
313
314 Args:
315 options: optparse.Options object.
316 error_func: Function to call with the error message in case of an error.
317
318 Returns:
319 A UIAutomatorOptions named tuple which contains all options relevant to
Ben Murdochbb1529c2013-08-08 10:24:53 +0100320 uiautomator tests.
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100321 """
Ben Murdocheb525c52013-07-10 11:40:50 +0100322
323 ProcessJavaTestOptions(options, error_func)
324
325 if not options.package_name:
326 error_func('--package-name must be specified.')
327
328 if not options.test_jar:
329 error_func('--test-jar must be specified.')
330
331 if os.path.exists(options.test_jar):
332 # The dexed JAR is fully qualified, assume the info JAR lives along side.
333 options.uiautomator_jar = options.test_jar
334 else:
335 options.uiautomator_jar = os.path.join(
336 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_JAVALIB_DIR,
337 '%s.dex.jar' % options.test_jar)
338 options.uiautomator_info_jar = (
339 options.uiautomator_jar[:options.uiautomator_jar.find('.dex.jar')] +
340 '_java.jar')
341
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100342 return uiautomator_test_options.UIAutomatorOptions(
343 options.build_type,
344 options.tool,
345 options.cleanup_test_files,
346 options.push_deps,
347 options.annotations,
348 options.exclude_annotations,
349 options.test_filter,
350 options.test_data,
351 options.save_perf_json,
352 options.screenshot_failures,
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100353 options.uiautomator_jar,
354 options.uiautomator_info_jar,
355 options.package_name)
356
Ben Murdocheb525c52013-07-10 11:40:50 +0100357
Ben Murdochbb1529c2013-08-08 10:24:53 +0100358def AddMonkeyTestOptions(option_parser):
359 """Adds monkey test options to |option_parser|."""
360 option_parser.add_option('--package-name', help='Allowed package.')
361 option_parser.add_option(
362 '--activity-name', default='com.google.android.apps.chrome.Main',
363 help='Name of the activity to start [default: %default].')
364 option_parser.add_option(
365 '--event-count', default=10000, type='int',
366 help='Number of events to generate [default: %default].')
367 option_parser.add_option(
368 '--category', default='',
369 help='A list of allowed categories [default: %default].')
370 option_parser.add_option(
371 '--throttle', default=100, type='int',
372 help='Delay between events (ms) [default: %default]. ')
373 option_parser.add_option(
374 '--seed', type='int',
375 help=('Seed value for pseudo-random generator. Same seed value generates '
376 'the same sequence of events. Seed is randomized by default.'))
377 option_parser.add_option(
378 '--extra-args', default='',
379 help=('String of other args to pass to the command verbatim '
380 '[default: "%default"].'))
381
382 AddCommonOptions(option_parser)
383
384
385def ProcessMonkeyTestOptions(options, error_func):
386 """Processes all monkey test options.
387
388 Args:
389 options: optparse.Options object.
390 error_func: Function to call with the error message in case of an error.
391
392 Returns:
393 A MonkeyOptions named tuple which contains all options relevant to
394 monkey tests.
395 """
396 if not options.package_name:
397 error_func('Package name is required.')
398
399 category = options.category
400 if category:
401 category = options.category.split(',')
402
403 return monkey_test_options.MonkeyOptions(
404 options.build_type,
405 options.verbose_count,
406 options.package_name,
407 options.activity_name,
408 options.event_count,
409 category,
410 options.throttle,
411 options.seed,
412 options.extra_args)
413
414
Ben Murdochca12bfa2013-07-23 11:17:05 +0100415def _RunGTests(options, error_func):
416 """Subcommand of RunTestsCommands which runs gtests."""
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100417 ProcessGTestOptions(options)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100418
419 exit_code = 0
420 for suite_name in options.suite_name:
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100421 # TODO(gkanwar): Move this into ProcessGTestOptions once we require -s for
422 # the gtest command.
423 gtest_options = gtest_test_options.GTestOptions(
424 options.build_type,
425 options.tool,
426 options.cleanup_test_files,
427 options.push_deps,
428 options.test_filter,
429 options.test_arguments,
430 options.timeout,
431 suite_name)
432 runner_factory, tests = gtest_setup.Setup(gtest_options)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100433
434 results, test_exit_code = test_dispatcher.RunTests(
435 tests, runner_factory, False, options.test_device,
436 shard=True,
437 build_type=options.build_type,
438 test_timeout=None,
439 num_retries=options.num_retries)
440
441 if test_exit_code and exit_code != constants.ERROR_EXIT_CODE:
442 exit_code = test_exit_code
443
444 report_results.LogFull(
445 results=results,
446 test_type='Unit test',
447 test_package=suite_name,
448 build_type=options.build_type,
449 flakiness_server=options.flakiness_dashboard_server)
450
451 if os.path.isdir(constants.ISOLATE_DEPS_DIR):
452 shutil.rmtree(constants.ISOLATE_DEPS_DIR)
453
454 return exit_code
455
456
Ben Murdochca12bfa2013-07-23 11:17:05 +0100457def _RunInstrumentationTests(options, error_func):
458 """Subcommand of RunTestsCommands which runs instrumentation tests."""
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100459 instrumentation_options = ProcessInstrumentationOptions(options, error_func)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100460
461 results = base_test_result.TestRunResults()
462 exit_code = 0
463
464 if options.run_java_tests:
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100465 runner_factory, tests = instrumentation_setup.Setup(instrumentation_options)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100466
467 test_results, exit_code = test_dispatcher.RunTests(
468 tests, runner_factory, options.wait_for_debugger,
469 options.test_device,
470 shard=True,
471 build_type=options.build_type,
472 test_timeout=None,
473 num_retries=options.num_retries)
474
475 results.AddTestRunResults(test_results)
476
477 if options.run_python_tests:
Ben Murdoch32409262013-08-07 11:04:47 +0100478 runner_factory, tests = host_driven_setup.InstrumentationSetup(
479 options.python_test_root, options.official_build,
480 instrumentation_options)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100481
Ben Murdoch32409262013-08-07 11:04:47 +0100482 if tests:
483 test_results, test_exit_code = test_dispatcher.RunTests(
484 tests, runner_factory, False,
485 options.test_device,
486 shard=True,
487 build_type=options.build_type,
488 test_timeout=None,
489 num_retries=options.num_retries)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100490
Ben Murdoch32409262013-08-07 11:04:47 +0100491 results.AddTestRunResults(test_results)
492
493 # Only allow exit code escalation
494 if test_exit_code and exit_code != constants.ERROR_EXIT_CODE:
495 exit_code = test_exit_code
Ben Murdochca12bfa2013-07-23 11:17:05 +0100496
497 report_results.LogFull(
498 results=results,
499 test_type='Instrumentation',
500 test_package=os.path.basename(options.test_apk),
501 annotation=options.annotations,
502 build_type=options.build_type,
503 flakiness_server=options.flakiness_dashboard_server)
504
505 return exit_code
506
507
508def _RunUIAutomatorTests(options, error_func):
509 """Subcommand of RunTestsCommands which runs uiautomator tests."""
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100510 uiautomator_options = ProcessUIAutomatorOptions(options, error_func)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100511
Ben Murdoch32409262013-08-07 11:04:47 +0100512 runner_factory, tests = uiautomator_setup.Setup(uiautomator_options)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100513
Ben Murdoch32409262013-08-07 11:04:47 +0100514 results, exit_code = test_dispatcher.RunTests(
515 tests, runner_factory, False, options.test_device,
516 shard=True,
517 build_type=options.build_type,
518 test_timeout=None,
519 num_retries=options.num_retries)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100520
521 report_results.LogFull(
522 results=results,
523 test_type='UIAutomator',
524 test_package=os.path.basename(options.test_jar),
525 annotation=options.annotations,
526 build_type=options.build_type,
527 flakiness_server=options.flakiness_dashboard_server)
528
529 return exit_code
530
531
Ben Murdochbb1529c2013-08-08 10:24:53 +0100532def _RunMonkeyTests(options, error_func):
533 """Subcommand of RunTestsCommands which runs monkey tests."""
534 monkey_options = ProcessMonkeyTestOptions(options, error_func)
535
536 runner_factory, tests = monkey_setup.Setup(monkey_options)
537
538 results, exit_code = test_dispatcher.RunTests(
539 tests, runner_factory, False, None, shard=False)
540
541 report_results.LogFull(
542 results=results,
543 test_type='Monkey',
544 test_package='Monkey',
545 build_type=options.build_type)
546
547 return exit_code
548
549
550
Ben Murdocheb525c52013-07-10 11:40:50 +0100551def RunTestsCommand(command, options, args, option_parser):
552 """Checks test type and dispatches to the appropriate function.
553
554 Args:
555 command: String indicating the command that was received to trigger
556 this function.
557 options: optparse options dictionary.
558 args: List of extra args from optparse.
559 option_parser: optparse.OptionParser object.
560
561 Returns:
562 Integer indicated exit code.
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100563
564 Raises:
565 Exception: Unknown command name passed in, or an exception from an
566 individual test runner.
Ben Murdocheb525c52013-07-10 11:40:50 +0100567 """
568
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100569 # Check for extra arguments
570 if len(args) > 2:
571 option_parser.error('Unrecognized arguments: %s' % (' '.join(args[2:])))
572 return constants.ERROR_EXIT_CODE
573
Ben Murdocheb525c52013-07-10 11:40:50 +0100574 ProcessCommonOptions(options)
575
Ben Murdocheb525c52013-07-10 11:40:50 +0100576 if command == 'gtest':
Ben Murdochca12bfa2013-07-23 11:17:05 +0100577 return _RunGTests(options, option_parser.error)
Ben Murdocheb525c52013-07-10 11:40:50 +0100578 elif command == 'instrumentation':
Ben Murdochca12bfa2013-07-23 11:17:05 +0100579 return _RunInstrumentationTests(options, option_parser.error)
Ben Murdocheb525c52013-07-10 11:40:50 +0100580 elif command == 'uiautomator':
Ben Murdochca12bfa2013-07-23 11:17:05 +0100581 return _RunUIAutomatorTests(options, option_parser.error)
Ben Murdochbb1529c2013-08-08 10:24:53 +0100582 elif command == 'monkey':
583 return _RunMonkeyTests(options, option_parser.error)
Ben Murdocheb525c52013-07-10 11:40:50 +0100584 else:
Ben Murdochca12bfa2013-07-23 11:17:05 +0100585 raise Exception('Unknown test type.')
Ben Murdocheb525c52013-07-10 11:40:50 +0100586
Ben Murdocheb525c52013-07-10 11:40:50 +0100587
588def HelpCommand(command, options, args, option_parser):
589 """Display help for a certain command, or overall help.
590
591 Args:
592 command: String indicating the command that was received to trigger
593 this function.
594 options: optparse options dictionary.
595 args: List of extra args from optparse.
596 option_parser: optparse.OptionParser object.
597
598 Returns:
599 Integer indicated exit code.
600 """
601 # If we don't have any args, display overall help
602 if len(args) < 3:
603 option_parser.print_help()
604 return 0
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100605 # If we have too many args, print an error
606 if len(args) > 3:
607 option_parser.error('Unrecognized arguments: %s' % (' '.join(args[3:])))
608 return constants.ERROR_EXIT_CODE
Ben Murdocheb525c52013-07-10 11:40:50 +0100609
610 command = args[2]
611
612 if command not in VALID_COMMANDS:
613 option_parser.error('Unrecognized command.')
614
615 # Treat the help command as a special case. We don't care about showing a
616 # specific help page for itself.
617 if command == 'help':
618 option_parser.print_help()
619 return 0
620
621 VALID_COMMANDS[command].add_options_func(option_parser)
622 option_parser.usage = '%prog ' + command + ' [options]'
623 option_parser.command_list = None
624 option_parser.print_help()
625
626 return 0
627
628
629# Define a named tuple for the values in the VALID_COMMANDS dictionary so the
630# syntax is a bit prettier. The tuple is two functions: (add options, run
631# command).
632CommandFunctionTuple = collections.namedtuple(
633 'CommandFunctionTuple', ['add_options_func', 'run_command_func'])
634VALID_COMMANDS = {
635 'gtest': CommandFunctionTuple(AddGTestOptions, RunTestsCommand),
Ben Murdocheb525c52013-07-10 11:40:50 +0100636 'instrumentation': CommandFunctionTuple(
637 AddInstrumentationTestOptions, RunTestsCommand),
638 'uiautomator': CommandFunctionTuple(
639 AddUIAutomatorTestOptions, RunTestsCommand),
Ben Murdochbb1529c2013-08-08 10:24:53 +0100640 'monkey': CommandFunctionTuple(
641 AddMonkeyTestOptions, RunTestsCommand),
Ben Murdocheb525c52013-07-10 11:40:50 +0100642 'help': CommandFunctionTuple(lambda option_parser: None, HelpCommand)
643 }
644
645
646class CommandOptionParser(optparse.OptionParser):
647 """Wrapper class for OptionParser to help with listing commands."""
648
649 def __init__(self, *args, **kwargs):
650 self.command_list = kwargs.pop('command_list', [])
651 self.example = kwargs.pop('example', '')
652 optparse.OptionParser.__init__(self, *args, **kwargs)
653
654 #override
655 def get_usage(self):
656 normal_usage = optparse.OptionParser.get_usage(self)
657 command_list = self.get_command_list()
658 example = self.get_example()
659 return self.expand_prog_name(normal_usage + example + command_list)
660
661 #override
662 def get_command_list(self):
663 if self.command_list:
664 return '\nCommands:\n %s\n' % '\n '.join(sorted(self.command_list))
665 return ''
666
667 def get_example(self):
668 if self.example:
669 return '\nExample:\n %s\n' % self.example
670 return ''
671
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100672
Ben Murdocheb525c52013-07-10 11:40:50 +0100673def main(argv):
674 option_parser = CommandOptionParser(
675 usage='Usage: %prog <command> [options]',
676 command_list=VALID_COMMANDS.keys())
677
678 if len(argv) < 2 or argv[1] not in VALID_COMMANDS:
679 option_parser.print_help()
680 return 0
681 command = argv[1]
682 VALID_COMMANDS[command].add_options_func(option_parser)
683 options, args = option_parser.parse_args(argv)
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100684 return VALID_COMMANDS[command].run_command_func(
Ben Murdocheb525c52013-07-10 11:40:50 +0100685 command, options, args, option_parser)
686
Ben Murdocheb525c52013-07-10 11:40:50 +0100687
688if __name__ == '__main__':
689 sys.exit(main(sys.argv))