blob: 6e2a1e40664b20d21db175abd904a2c1258e8497 [file] [log] [blame]
[email protected]fbe29322013-07-09 09:03:261#!/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
[email protected]6bc1bda22013-07-19 22:08:3716import shutil
[email protected]fbe29322013-07-09 09:03:2617import sys
18
[email protected]fbe29322013-07-09 09:03:2619from pylib import constants
20from pylib import ports
21from pylib.base import base_test_result
[email protected]6bc1bda22013-07-19 22:08:3722from pylib.base import test_dispatcher
[email protected]6bc1bda22013-07-19 22:08:3723from pylib.gtest import gtest_config
[email protected]2a684222013-08-01 16:59:2224from pylib.gtest import setup as gtest_setup
25from pylib.gtest import test_options as gtest_test_options
[email protected]fbe29322013-07-09 09:03:2626from pylib.host_driven import run_python_tests as python_dispatch
[email protected]6bc1bda22013-07-19 22:08:3727from pylib.instrumentation import setup as instrumentation_setup
[email protected]2a684222013-08-01 16:59:2228from pylib.instrumentation import test_options as instrumentation_test_options
[email protected]6bc1bda22013-07-19 22:08:3729from pylib.uiautomator import setup as uiautomator_setup
[email protected]2a684222013-08-01 16:59:2230from pylib.uiautomator import test_options as uiautomator_test_options
[email protected]6bc1bda22013-07-19 22:08:3731from pylib.utils import report_results
32from pylib.utils import run_tests_helper
[email protected]fbe29322013-07-09 09:03:2633
34
35_SDK_OUT_DIR = os.path.join(constants.DIR_SOURCE_ROOT, 'out')
36
37
38def AddBuildTypeOption(option_parser):
39 """Adds the build type option to |option_parser|."""
40 default_build_type = 'Debug'
41 if 'BUILDTYPE' in os.environ:
42 default_build_type = os.environ['BUILDTYPE']
43 option_parser.add_option('--debug', action='store_const', const='Debug',
44 dest='build_type', default=default_build_type,
45 help=('If set, run test suites under out/Debug. '
46 'Default is env var BUILDTYPE or Debug.'))
47 option_parser.add_option('--release', action='store_const',
48 const='Release', dest='build_type',
49 help=('If set, run test suites under out/Release.'
50 ' Default is env var BUILDTYPE or Debug.'))
51
52
[email protected]fbe29322013-07-09 09:03:2653def AddCommonOptions(option_parser):
54 """Adds all common options to |option_parser|."""
55
56 AddBuildTypeOption(option_parser)
57
[email protected]fbe29322013-07-09 09:03:2658 option_parser.add_option('-c', dest='cleanup_test_files',
59 help='Cleanup test files on the device after run',
60 action='store_true')
61 option_parser.add_option('--num_retries', dest='num_retries', type='int',
62 default=2,
63 help=('Number of retries for a test before '
64 'giving up.'))
65 option_parser.add_option('-v',
66 '--verbose',
67 dest='verbose_count',
68 default=0,
69 action='count',
70 help='Verbose level (multiple times for more)')
71 profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps',
72 'traceview']
73 option_parser.add_option('--profiler', dest='profilers', action='append',
74 choices=profilers,
75 help=('Profiling tool to run during test. Pass '
76 'multiple times to run multiple profilers. '
77 'Available profilers: %s' % profilers))
78 option_parser.add_option('--tool',
79 dest='tool',
80 help=('Run the test under a tool '
81 '(use --tool help to list them)'))
82 option_parser.add_option('--flakiness-dashboard-server',
83 dest='flakiness_dashboard_server',
84 help=('Address of the server that is hosting the '
85 'Chrome for Android flakiness dashboard.'))
86 option_parser.add_option('--skip-deps-push', dest='push_deps',
87 action='store_false', default=True,
88 help=('Do not push dependencies to the device. '
89 'Use this at own risk for speeding up test '
90 'execution on local machine.'))
[email protected]fbe29322013-07-09 09:03:2691 option_parser.add_option('-d', '--device', dest='test_device',
92 help=('Target device for the test suite '
93 'to run on.'))
94
95
96def ProcessCommonOptions(options):
97 """Processes and handles all common options."""
[email protected]fbe29322013-07-09 09:03:2698 run_tests_helper.SetLogLevel(options.verbose_count)
99
100
[email protected]fbe29322013-07-09 09:03:26101def AddGTestOptions(option_parser):
102 """Adds gtest options to |option_parser|."""
103
104 option_parser.usage = '%prog gtest [options]'
105 option_parser.command_list = []
106 option_parser.example = '%prog gtest -s base_unittests'
107
[email protected]6bc1bda22013-07-19 22:08:37108 # TODO(gkanwar): Make this option required
109 option_parser.add_option('-s', '--suite', dest='suite_name',
[email protected]fbe29322013-07-09 09:03:26110 help=('Executable name of the test suite to run '
111 '(use -s help to list them).'))
[email protected]9e689252013-07-30 20:14:36112 option_parser.add_option('-f', '--gtest_filter', dest='test_filter',
113 help='googletest-style filter string.')
114 option_parser.add_option('-a', '--test_arguments', dest='test_arguments',
115 help='Additional arguments to pass to the test.')
116 option_parser.add_option('-t', dest='timeout',
117 help='Timeout to wait for each test',
118 type='int',
119 default=60)
[email protected]fbe29322013-07-09 09:03:26120 # TODO(gkanwar): Move these to Common Options once we have the plumbing
121 # in our other test types to handle these commands
[email protected]fbe29322013-07-09 09:03:26122 AddCommonOptions(option_parser)
123
124
[email protected]6bc1bda22013-07-19 22:08:37125def ProcessGTestOptions(options):
126 """Intercept test suite help to list test suites.
127
128 Args:
129 options: Command line options.
[email protected]6bc1bda22013-07-19 22:08:37130 """
131 if options.suite_name == 'help':
132 print 'Available test suites are:'
[email protected]9e689252013-07-30 20:14:36133 for test_suite in (gtest_config.STABLE_TEST_SUITES +
134 gtest_config.EXPERIMENTAL_TEST_SUITES):
135 print test_suite
[email protected]2a684222013-08-01 16:59:22136 sys.exit(0)
[email protected]6bc1bda22013-07-19 22:08:37137
138 # Convert to a list, assuming all test suites if nothing was specified.
139 # TODO(gkanwar): Require having a test suite
140 if options.suite_name:
141 options.suite_name = [options.suite_name]
142 else:
[email protected]9e689252013-07-30 20:14:36143 options.suite_name = [s for s in gtest_config.STABLE_TEST_SUITES]
[email protected]6bc1bda22013-07-19 22:08:37144
145
[email protected]fbe29322013-07-09 09:03:26146def AddJavaTestOptions(option_parser):
147 """Adds the Java test options to |option_parser|."""
148
149 option_parser.add_option('-f', '--test_filter', dest='test_filter',
150 help=('Test filter (if not fully qualified, '
151 'will run all matches).'))
152 option_parser.add_option(
153 '-A', '--annotation', dest='annotation_str',
154 help=('Comma-separated list of annotations. Run only tests with any of '
155 'the given annotations. An annotation can be either a key or a '
156 'key-values pair. A test that has no annotation is considered '
157 '"SmallTest".'))
158 option_parser.add_option(
159 '-E', '--exclude-annotation', dest='exclude_annotation_str',
160 help=('Comma-separated list of annotations. Exclude tests with these '
161 'annotations.'))
162 option_parser.add_option('-j', '--java_only', action='store_true',
163 default=False, help='Run only the Java tests.')
164 option_parser.add_option('-p', '--python_only', action='store_true',
165 default=False,
166 help='Run only the host-driven tests.')
167 option_parser.add_option('--screenshot', dest='screenshot_failures',
168 action='store_true',
169 help='Capture screenshots of test failures')
170 option_parser.add_option('--save-perf-json', action='store_true',
171 help='Saves the JSON file for each UI Perf test.')
[email protected]fbe29322013-07-09 09:03:26172 option_parser.add_option('--official-build', help='Run official build tests.')
173 option_parser.add_option('--python_test_root',
174 help='Root of the host-driven tests.')
175 option_parser.add_option('--keep_test_server_ports',
176 action='store_true',
177 help=('Indicates the test server ports must be '
178 'kept. When this is run via a sharder '
179 'the test server ports should be kept and '
180 'should not be reset.'))
181 # TODO(gkanwar): This option is deprecated. Remove it in the future.
182 option_parser.add_option('--disable_assertions', action='store_true',
183 help=('(DEPRECATED) Run with java assertions '
184 'disabled.'))
185 option_parser.add_option('--test_data', action='append', default=[],
186 help=('Each instance defines a directory of test '
187 'data that should be copied to the target(s) '
188 'before running the tests. The argument '
189 'should be of the form <target>:<source>, '
190 '<target> is relative to the device data'
191 'directory, and <source> is relative to the '
192 'chromium build directory.'))
193
194
195def ProcessJavaTestOptions(options, error_func):
196 """Processes options/arguments and populates |options| with defaults."""
197
198 if options.java_only and options.python_only:
199 error_func('Options java_only (-j) and python_only (-p) '
200 'are mutually exclusive.')
201 options.run_java_tests = True
202 options.run_python_tests = True
203 if options.java_only:
204 options.run_python_tests = False
205 elif options.python_only:
206 options.run_java_tests = False
207
208 if not options.python_test_root:
209 options.run_python_tests = False
210
211 if options.annotation_str:
212 options.annotations = options.annotation_str.split(',')
213 elif options.test_filter:
214 options.annotations = []
215 else:
[email protected]6bc1bda22013-07-19 22:08:37216 options.annotations = ['Smoke', 'SmallTest', 'MediumTest', 'LargeTest',
217 'EnormousTest']
[email protected]fbe29322013-07-09 09:03:26218
219 if options.exclude_annotation_str:
220 options.exclude_annotations = options.exclude_annotation_str.split(',')
221 else:
222 options.exclude_annotations = []
223
224 if not options.keep_test_server_ports:
225 if not ports.ResetTestServerPortAllocation():
226 raise Exception('Failed to reset test server port.')
227
228
229def AddInstrumentationTestOptions(option_parser):
230 """Adds Instrumentation test options to |option_parser|."""
231
232 option_parser.usage = '%prog instrumentation [options]'
233 option_parser.command_list = []
[email protected]fb7ab5e82013-07-26 18:31:20234 option_parser.example = ('%prog instrumentation '
[email protected]fbe29322013-07-09 09:03:26235 '--test-apk=ChromiumTestShellTest')
236
237 AddJavaTestOptions(option_parser)
238 AddCommonOptions(option_parser)
239
240 option_parser.add_option('-w', '--wait_debugger', dest='wait_for_debugger',
241 action='store_true',
242 help='Wait for debugger.')
[email protected]fb7ab5e82013-07-26 18:31:20243 #TODO(craigdh): Remove option once -I is no longer passed downstream.
[email protected]fbe29322013-07-09 09:03:26244 option_parser.add_option('-I', dest='install_apk', action='store_true',
[email protected]fb7ab5e82013-07-26 18:31:20245 help='(DEPRECATED) Install the test apk.')
[email protected]fbe29322013-07-09 09:03:26246 option_parser.add_option(
247 '--test-apk', dest='test_apk',
248 help=('The name of the apk containing the tests '
249 '(without the .apk extension; e.g. "ContentShellTest"). '
250 'Alternatively, this can be a full path to the apk.'))
251
252
253def ProcessInstrumentationOptions(options, error_func):
[email protected]2a684222013-08-01 16:59:22254 """Processes options/arguments and populate |options| with defaults.
255
256 Args:
257 options: optparse.Options object.
258 error_func: Function to call with the error message in case of an error.
259
260 Returns:
261 An InstrumentationOptions named tuple which contains all options relevant to
262 instrumentation tests.
263 """
[email protected]fbe29322013-07-09 09:03:26264
265 ProcessJavaTestOptions(options, error_func)
266
267 if not options.test_apk:
268 error_func('--test-apk must be specified.')
269
270 if os.path.exists(options.test_apk):
271 # The APK is fully qualified, assume the JAR lives along side.
272 options.test_apk_path = options.test_apk
273 options.test_apk_jar_path = (os.path.splitext(options.test_apk_path)[0] +
274 '.jar')
275 else:
276 options.test_apk_path = os.path.join(_SDK_OUT_DIR,
277 options.build_type,
278 constants.SDK_BUILD_APKS_DIR,
279 '%s.apk' % options.test_apk)
280 options.test_apk_jar_path = os.path.join(
281 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_TEST_JAVALIB_DIR,
282 '%s.jar' % options.test_apk)
283
[email protected]2a684222013-08-01 16:59:22284 return instrumentation_test_options.InstrumentationOptions(
285 options.build_type,
286 options.tool,
287 options.cleanup_test_files,
288 options.push_deps,
289 options.annotations,
290 options.exclude_annotations,
291 options.test_filter,
292 options.test_data,
293 options.save_perf_json,
294 options.screenshot_failures,
295 options.disable_assertions,
296 options.wait_for_debugger,
297 options.test_apk,
298 options.test_apk_path,
299 options.test_apk_jar_path)
300
[email protected]fbe29322013-07-09 09:03:26301
302def AddUIAutomatorTestOptions(option_parser):
303 """Adds UI Automator test options to |option_parser|."""
304
305 option_parser.usage = '%prog uiautomator [options]'
306 option_parser.command_list = []
307 option_parser.example = (
308 '%prog uiautomator --test-jar=chromium_testshell_uiautomator_tests'
309 ' --package-name=org.chromium.chrome.testshell')
310 option_parser.add_option(
311 '--package-name',
312 help='The package name used by the apk containing the application.')
313 option_parser.add_option(
314 '--test-jar', dest='test_jar',
315 help=('The name of the dexed jar containing the tests (without the '
316 '.dex.jar extension). Alternatively, this can be a full path '
317 'to the jar.'))
318
319 AddJavaTestOptions(option_parser)
320 AddCommonOptions(option_parser)
321
322
323def ProcessUIAutomatorOptions(options, error_func):
[email protected]2a684222013-08-01 16:59:22324 """Processes UIAutomator options/arguments.
325
326 Args:
327 options: optparse.Options object.
328 error_func: Function to call with the error message in case of an error.
329
330 Returns:
331 A UIAutomatorOptions named tuple which contains all options relevant to
332 instrumentation tests.
333 """
[email protected]fbe29322013-07-09 09:03:26334
335 ProcessJavaTestOptions(options, error_func)
336
337 if not options.package_name:
338 error_func('--package-name must be specified.')
339
340 if not options.test_jar:
341 error_func('--test-jar must be specified.')
342
343 if os.path.exists(options.test_jar):
344 # The dexed JAR is fully qualified, assume the info JAR lives along side.
345 options.uiautomator_jar = options.test_jar
346 else:
347 options.uiautomator_jar = os.path.join(
348 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_JAVALIB_DIR,
349 '%s.dex.jar' % options.test_jar)
350 options.uiautomator_info_jar = (
351 options.uiautomator_jar[:options.uiautomator_jar.find('.dex.jar')] +
352 '_java.jar')
353
[email protected]2a684222013-08-01 16:59:22354 return uiautomator_test_options.UIAutomatorOptions(
355 options.build_type,
356 options.tool,
357 options.cleanup_test_files,
358 options.push_deps,
359 options.annotations,
360 options.exclude_annotations,
361 options.test_filter,
362 options.test_data,
363 options.save_perf_json,
364 options.screenshot_failures,
365 options.disable_assertions,
366 options.uiautomator_jar,
367 options.uiautomator_info_jar,
368 options.package_name)
369
[email protected]fbe29322013-07-09 09:03:26370
[email protected]6bc1bda22013-07-19 22:08:37371def _RunGTests(options, error_func):
372 """Subcommand of RunTestsCommands which runs gtests."""
[email protected]2a684222013-08-01 16:59:22373 ProcessGTestOptions(options)
[email protected]6bc1bda22013-07-19 22:08:37374
375 exit_code = 0
376 for suite_name in options.suite_name:
[email protected]2a684222013-08-01 16:59:22377 # TODO(gkanwar): Move this into ProcessGTestOptions once we require -s for
378 # the gtest command.
379 gtest_options = gtest_test_options.GTestOptions(
380 options.build_type,
381 options.tool,
382 options.cleanup_test_files,
383 options.push_deps,
384 options.test_filter,
385 options.test_arguments,
386 options.timeout,
387 suite_name)
388 runner_factory, tests = gtest_setup.Setup(gtest_options)
[email protected]6bc1bda22013-07-19 22:08:37389
390 results, test_exit_code = test_dispatcher.RunTests(
391 tests, runner_factory, False, options.test_device,
392 shard=True,
393 build_type=options.build_type,
394 test_timeout=None,
395 num_retries=options.num_retries)
396
397 if test_exit_code and exit_code != constants.ERROR_EXIT_CODE:
398 exit_code = test_exit_code
399
400 report_results.LogFull(
401 results=results,
402 test_type='Unit test',
403 test_package=suite_name,
404 build_type=options.build_type,
405 flakiness_server=options.flakiness_dashboard_server)
406
407 if os.path.isdir(constants.ISOLATE_DEPS_DIR):
408 shutil.rmtree(constants.ISOLATE_DEPS_DIR)
409
410 return exit_code
411
412
[email protected]6bc1bda22013-07-19 22:08:37413def _RunInstrumentationTests(options, error_func):
414 """Subcommand of RunTestsCommands which runs instrumentation tests."""
[email protected]2a684222013-08-01 16:59:22415 instrumentation_options = ProcessInstrumentationOptions(options, error_func)
[email protected]6bc1bda22013-07-19 22:08:37416
417 results = base_test_result.TestRunResults()
418 exit_code = 0
419
420 if options.run_java_tests:
[email protected]2a684222013-08-01 16:59:22421 runner_factory, tests = instrumentation_setup.Setup(instrumentation_options)
[email protected]6bc1bda22013-07-19 22:08:37422
423 test_results, exit_code = test_dispatcher.RunTests(
424 tests, runner_factory, options.wait_for_debugger,
425 options.test_device,
426 shard=True,
427 build_type=options.build_type,
428 test_timeout=None,
429 num_retries=options.num_retries)
430
431 results.AddTestRunResults(test_results)
432
433 if options.run_python_tests:
434 test_results, test_exit_code = (
435 python_dispatch.DispatchPythonTests(options))
436
437 results.AddTestRunResults(test_results)
438
439 # Only allow exit code escalation
440 if test_exit_code and exit_code != constants.ERROR_EXIT_CODE:
441 exit_code = test_exit_code
442
443 report_results.LogFull(
444 results=results,
445 test_type='Instrumentation',
446 test_package=os.path.basename(options.test_apk),
447 annotation=options.annotations,
448 build_type=options.build_type,
449 flakiness_server=options.flakiness_dashboard_server)
450
451 return exit_code
452
453
454def _RunUIAutomatorTests(options, error_func):
455 """Subcommand of RunTestsCommands which runs uiautomator tests."""
[email protected]2a684222013-08-01 16:59:22456 uiautomator_options = ProcessUIAutomatorOptions(options, error_func)
[email protected]6bc1bda22013-07-19 22:08:37457
458 results = base_test_result.TestRunResults()
459 exit_code = 0
460
461 if options.run_java_tests:
[email protected]2a684222013-08-01 16:59:22462 runner_factory, tests = uiautomator_setup.Setup(uiautomator_options)
[email protected]6bc1bda22013-07-19 22:08:37463
464 test_results, exit_code = test_dispatcher.RunTests(
465 tests, runner_factory, False, options.test_device,
466 shard=True,
467 build_type=options.build_type,
468 test_timeout=None,
469 num_retries=options.num_retries)
470
471 results.AddTestRunResults(test_results)
472
473 if options.run_python_tests:
474 test_results, test_exit_code = (
475 python_dispatch.DispatchPythonTests(options))
476
477 results.AddTestRunResults(test_results)
478
479 # Only allow exit code escalation
480 if test_exit_code and exit_code != constants.ERROR_EXIT_CODE:
481 exit_code = test_exit_code
482
483 report_results.LogFull(
484 results=results,
485 test_type='UIAutomator',
486 test_package=os.path.basename(options.test_jar),
487 annotation=options.annotations,
488 build_type=options.build_type,
489 flakiness_server=options.flakiness_dashboard_server)
490
491 return exit_code
492
493
[email protected]fbe29322013-07-09 09:03:26494def RunTestsCommand(command, options, args, option_parser):
495 """Checks test type and dispatches to the appropriate function.
496
497 Args:
498 command: String indicating the command that was received to trigger
499 this function.
500 options: optparse options dictionary.
501 args: List of extra args from optparse.
502 option_parser: optparse.OptionParser object.
503
504 Returns:
505 Integer indicated exit code.
[email protected]b3873892013-07-10 04:57:10506
507 Raises:
508 Exception: Unknown command name passed in, or an exception from an
509 individual test runner.
[email protected]fbe29322013-07-09 09:03:26510 """
511
[email protected]d82f0252013-07-12 23:22:57512 # Check for extra arguments
513 if len(args) > 2:
514 option_parser.error('Unrecognized arguments: %s' % (' '.join(args[2:])))
515 return constants.ERROR_EXIT_CODE
516
[email protected]fbe29322013-07-09 09:03:26517 ProcessCommonOptions(options)
518
[email protected]fbe29322013-07-09 09:03:26519 if command == 'gtest':
[email protected]6bc1bda22013-07-19 22:08:37520 return _RunGTests(options, option_parser.error)
[email protected]fbe29322013-07-09 09:03:26521 elif command == 'instrumentation':
[email protected]6bc1bda22013-07-19 22:08:37522 return _RunInstrumentationTests(options, option_parser.error)
[email protected]fbe29322013-07-09 09:03:26523 elif command == 'uiautomator':
[email protected]6bc1bda22013-07-19 22:08:37524 return _RunUIAutomatorTests(options, option_parser.error)
[email protected]fbe29322013-07-09 09:03:26525 else:
[email protected]6bc1bda22013-07-19 22:08:37526 raise Exception('Unknown test type.')
[email protected]fbe29322013-07-09 09:03:26527
[email protected]b3873892013-07-10 04:57:10528 return exit_code
[email protected]fbe29322013-07-09 09:03:26529
530
531def HelpCommand(command, options, args, option_parser):
532 """Display help for a certain command, or overall help.
533
534 Args:
535 command: String indicating the command that was received to trigger
536 this function.
537 options: optparse options dictionary.
538 args: List of extra args from optparse.
539 option_parser: optparse.OptionParser object.
540
541 Returns:
542 Integer indicated exit code.
543 """
544 # If we don't have any args, display overall help
545 if len(args) < 3:
546 option_parser.print_help()
547 return 0
[email protected]d82f0252013-07-12 23:22:57548 # If we have too many args, print an error
549 if len(args) > 3:
550 option_parser.error('Unrecognized arguments: %s' % (' '.join(args[3:])))
551 return constants.ERROR_EXIT_CODE
[email protected]fbe29322013-07-09 09:03:26552
553 command = args[2]
554
555 if command not in VALID_COMMANDS:
556 option_parser.error('Unrecognized command.')
557
558 # Treat the help command as a special case. We don't care about showing a
559 # specific help page for itself.
560 if command == 'help':
561 option_parser.print_help()
562 return 0
563
564 VALID_COMMANDS[command].add_options_func(option_parser)
565 option_parser.usage = '%prog ' + command + ' [options]'
566 option_parser.command_list = None
567 option_parser.print_help()
568
569 return 0
570
571
572# Define a named tuple for the values in the VALID_COMMANDS dictionary so the
573# syntax is a bit prettier. The tuple is two functions: (add options, run
574# command).
575CommandFunctionTuple = collections.namedtuple(
576 'CommandFunctionTuple', ['add_options_func', 'run_command_func'])
577VALID_COMMANDS = {
578 'gtest': CommandFunctionTuple(AddGTestOptions, RunTestsCommand),
[email protected]fbe29322013-07-09 09:03:26579 'instrumentation': CommandFunctionTuple(
580 AddInstrumentationTestOptions, RunTestsCommand),
581 'uiautomator': CommandFunctionTuple(
582 AddUIAutomatorTestOptions, RunTestsCommand),
583 'help': CommandFunctionTuple(lambda option_parser: None, HelpCommand)
584 }
585
586
587class CommandOptionParser(optparse.OptionParser):
588 """Wrapper class for OptionParser to help with listing commands."""
589
590 def __init__(self, *args, **kwargs):
591 self.command_list = kwargs.pop('command_list', [])
592 self.example = kwargs.pop('example', '')
593 optparse.OptionParser.__init__(self, *args, **kwargs)
594
595 #override
596 def get_usage(self):
597 normal_usage = optparse.OptionParser.get_usage(self)
598 command_list = self.get_command_list()
599 example = self.get_example()
600 return self.expand_prog_name(normal_usage + example + command_list)
601
602 #override
603 def get_command_list(self):
604 if self.command_list:
605 return '\nCommands:\n %s\n' % '\n '.join(sorted(self.command_list))
606 return ''
607
608 def get_example(self):
609 if self.example:
610 return '\nExample:\n %s\n' % self.example
611 return ''
612
[email protected]b3873892013-07-10 04:57:10613
[email protected]fbe29322013-07-09 09:03:26614def main(argv):
615 option_parser = CommandOptionParser(
616 usage='Usage: %prog <command> [options]',
617 command_list=VALID_COMMANDS.keys())
618
619 if len(argv) < 2 or argv[1] not in VALID_COMMANDS:
620 option_parser.print_help()
621 return 0
622 command = argv[1]
623 VALID_COMMANDS[command].add_options_func(option_parser)
624 options, args = option_parser.parse_args(argv)
[email protected]b3873892013-07-10 04:57:10625 return VALID_COMMANDS[command].run_command_func(
[email protected]fbe29322013-07-09 09:03:26626 command, options, args, option_parser)
627
[email protected]fbe29322013-07-09 09:03:26628
629if __name__ == '__main__':
630 sys.exit(main(sys.argv))