OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/env python | |
2 # | |
3 # Copyright (c) 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 | |
9 Types of tests supported: | |
10 1. GTest native unit tests (gtest) | |
11 2. ContentBrowser unit tests (content_browsertests) | |
12 3. Instrumentation tests (instrumentation): Both Python host-driven and | |
13 Java instrumentation tests are run by default. Use --python_only or | |
14 --java_only to select one or the other. | |
15 4. UIAutomator tests (uiautomator): Both Python host-driven and Java | |
16 UIAutomator tests are run by default. Use --python_only or --java_only to | |
17 select one or the other. | |
18 | |
19 TODO(gkanwar): | |
20 * Add options to run Monkey tests. | |
21 """ | |
22 | |
23 import collections | |
24 import optparse | |
25 import os | |
26 import sys | |
27 | |
28 from pylib import cmd_helper | |
29 from pylib import constants | |
30 from pylib import ports | |
31 from pylib.browsertests import dispatch as browsertests_dispatch | |
32 from pylib.gtest import dispatch as gtest_dispatch | |
33 from pylib.host_driven import run_python_tests as python_dispatch | |
34 from pylib.instrumentation import dispatch as instrumentation_dispatch | |
35 from pylib.uiautomator import dispatch as uiautomator_dispatch | |
36 from pylib.utils import emulator | |
37 from pylib.utils import run_tests_helper | |
38 | |
39 _SDK_OUT_DIR = os.path.join(constants.DIR_SOURCE_ROOT, 'out') | |
40 | |
41 | |
42 def AddBuildTypeOption(option_parser): | |
43 """Adds the build type option to option_parser.""" | |
44 default_build_type = 'Debug' | |
45 if 'BUILDTYPE' in os.environ: | |
46 default_build_type = os.environ['BUILDTYPE'] | |
47 option_parser.add_option('--debug', action='store_const', const='Debug', | |
48 dest='build_type', default=default_build_type, | |
49 help=('If set, run test suites under out/Debug. ' | |
50 'Default is env var BUILDTYPE or Debug.')) | |
51 option_parser.add_option('--release', action='store_const', | |
52 const='Release', dest='build_type', | |
53 help=('If set, run test suites under out/Release.' | |
54 ' Default is env var BUILDTYPE or Debug.')) | |
55 | |
56 | |
57 def AddEmulatorOptions(option_parser): | |
58 """Adds all emulator-related options to option_parser.""" | |
59 | |
60 # TODO(gkanwar): Figure out what we're doing with the emulator setup | |
61 # and determine whether these options should be deprecated/removed. | |
62 option_parser.add_option('-e', '--emulator', dest='use_emulator', | |
63 action='store_true', | |
64 help='Run tests in a new instance of emulator.') | |
65 option_parser.add_option('-n', '--emulator-count', | |
66 type='int', default=1, | |
67 help=('Number of emulators to launch for ' | |
68 'running the tests.')) | |
69 option_parser.add_option('--abi', default='armeabi-v7a', | |
70 help='Platform of emulators to launch.') | |
71 | |
72 | |
73 def ProcessEmulatorOptions(options): | |
74 """Processes emulator options.""" | |
75 if options.use_emulator: | |
76 emulator.DeleteAllTempAVDs() | |
77 | |
78 | |
79 def AddCommonOptions(option_parser): | |
80 """Adds all common options to option_parser.""" | |
81 | |
82 AddBuildTypeOption(option_parser) | |
83 | |
84 option_parser.add_option('--out-directory', dest='out_directory', | |
85 help=('Path to the out/ directory, irrespective of ' | |
86 'the build type. Only for non-Chromium uses.')) | |
87 option_parser.add_option('-c', dest='cleanup_test_files', | |
88 help='Cleanup test files on the device after run', | |
89 action='store_true') | |
90 option_parser.add_option('--num_retries', dest='num_retries', type='int', | |
91 default=2, | |
92 help=('Number of retries for a test before ' | |
93 'giving up.')) | |
94 option_parser.add_option('-v', | |
95 '--verbose', | |
96 dest='verbose_count', | |
97 default=0, | |
98 action='count', | |
99 help='Verbose level (multiple times for more)') | |
100 profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps', | |
101 'traceview'] | |
102 option_parser.add_option('--profiler', dest='profilers', action='append', | |
103 choices=profilers, | |
104 help=('Profiling tool to run during test. Pass ' | |
105 'multiple times to run multiple profilers. ' | |
106 'Available profilers: %s' % profilers)) | |
107 option_parser.add_option('--tool', | |
108 dest='tool', | |
109 help=('Run the test under a tool ' | |
110 '(use --tool help to list them)')) | |
111 option_parser.add_option('--flakiness-dashboard-server', | |
112 dest='flakiness_dashboard_server', | |
113 help=('Address of the server that is hosting the ' | |
114 'Chrome for Android flakiness dashboard.')) | |
115 option_parser.add_option('--skip-deps-push', dest='push_deps', | |
116 action='store_false', default=True, | |
117 help=('Do not push dependencies to the device. ' | |
118 'Use this at own risk for speeding up test ' | |
119 'execution on local machine.')) | |
120 # TODO(gkanwar): This option is deprecated. Remove it in the future. | |
121 option_parser.add_option('--exit-code', action='store_true', | |
122 help=('(DEPRECATED) If set, the exit code will be ' | |
123 'total number of failures.')) | |
124 # TODO(gkanwar): This option is deprecated. It is currently used to run tests | |
125 # with the FlakyTest annotation to prevent the bots going red downstream. We | |
126 # should instead use exit codes and let the Buildbot scripts deal with test | |
127 # failures appropriately. See crbug.com/170477. | |
128 option_parser.add_option('--buildbot-step-failure', | |
129 action='store_true', | |
130 help=('(DEPRECATED) If present, will set the ' | |
131 'buildbot status as STEP_FAILURE, otherwise ' | |
132 'as STEP_WARNINGS when test(s) fail.')) | |
133 option_parser.add_option('-d', '--device', dest='test_device', | |
134 help=('Target device for the test suite ' | |
135 'to run on.')) | |
136 | |
137 | |
138 def ProcessCommonOptions(options): | |
139 """Processes and handles all common options.""" | |
140 if options.out_directory: | |
141 cmd_helper.OutDirectory.set(options.out_directory) | |
142 run_tests_helper.SetLogLevel(options.verbose_count) | |
143 | |
144 | |
145 def AddContentBrowserTestOptions(option_parser): | |
146 """Adds Content Browser test options to option_parser.""" | |
147 | |
148 option_parser.usage = '%prog content_browsertests [options]' | |
149 option_parser.command_list = [] | |
150 option_parser.example = '%prog content_browsertests' | |
151 | |
152 # TODO(gkanwar): Consolidate and clean up test filtering for gtests and | |
153 # content_browsertests. | |
154 option_parser.add_option('--gtest_filter', dest='test_filter', | |
155 help='Filter GTests by name.') | |
156 | |
157 AddCommonOptions(option_parser) | |
158 | |
159 | |
160 def AddGTestOptions(option_parser, default_timeout=60): | |
161 """Adds gtest options to option_parser.""" | |
162 | |
163 option_parser.usage = '%prog gtest [options]' | |
164 option_parser.command_list = [] | |
165 option_parser.example = '%prog gtest -s android_webview_unittests' | |
frankf
2013/07/01 22:36:21
use base_unittests
gkanwar
2013/07/01 23:46:37
Done.
| |
166 | |
167 # TODO(gkanwar): Consolidate and clean up test filtering for gtests and | |
168 # content_browsertests. | |
169 option_parser.add_option('--gtest_filter', dest='test_filter', | |
170 help='Filter GTests by name.') | |
171 option_parser.add_option('-s', '--suite', dest='test_suite', | |
172 help=('Executable name of the test suite to run ' | |
173 '(use -s help to list them).')) | |
174 option_parser.add_option('-a', '--test_arguments', dest='test_arguments', | |
175 help='Additional arguments to pass to the test.') | |
176 # TODO(gkanwar): Most likely deprecate/remove this option once we've pinned | |
177 # down what we're doing with the emulator setup. | |
178 option_parser.add_option('-x', '--xvfb', dest='use_xvfb', | |
179 action='store_true', | |
180 help='Use Xvfb around tests (ignored if not Linux).') | |
181 # TODO(gkanwar): Possible deprecate this flag. Waiting on word from Peter | |
182 # Beverloo. | |
183 option_parser.add_option('--webkit', action='store_true', | |
184 help='Run the tests from a WebKit checkout.') | |
185 option_parser.add_option('--exe', action='store_true', | |
186 help='If set, use the exe test runner instead of ' | |
187 'the APK.') | |
188 option_parser.add_option('-t', dest='timeout', | |
189 help='Timeout to wait for each test', | |
190 type='int', | |
191 default=default_timeout) | |
192 | |
193 # TODO(gkanwar): Move these to Common Options once we have the plumbing | |
194 # in our other test types to handle these commands | |
195 AddEmulatorOptions(option_parser) | |
196 AddCommonOptions(option_parser) | |
197 | |
198 | |
199 def AddJavaTestOptions(option_parser): | |
200 """Adds the Java test options to option_parser.""" | |
201 | |
202 option_parser.add_option('-f', '--test_filter', dest='test_filter', | |
203 help=('Test filter (if not fully qualified, ' | |
204 'will run all matches).')) | |
205 option_parser.add_option( | |
206 '-A', '--annotation', dest='annotation_str', | |
207 help=('Comma-separated list of annotations. Run only tests with any of ' | |
208 'the given annotations. An annotation can be either a key or a ' | |
209 'key-values pair. A test that has no annotation is considered ' | |
210 '"SmallTest".')) | |
211 option_parser.add_option( | |
212 '-E', '--exclude-annotation', dest='exclude_annotation_str', | |
213 help=('Comma-separated list of annotations. Exclude tests with these ' | |
214 'annotations.')) | |
215 option_parser.add_option('-j', '--java_only', action='store_true', | |
216 default=False, help='Run only the Java tests.') | |
217 option_parser.add_option('-p', '--python_only', action='store_true', | |
218 default=False, | |
219 help='Run only the host-driven tests.') | |
220 option_parser.add_option('--screenshot', dest='screenshot_failures', | |
221 action='store_true', | |
222 help='Capture screenshots of test failures') | |
223 option_parser.add_option('--save-perf-json', action='store_true', | |
224 help='Saves the JSON file for each UI Perf test.') | |
225 # TODO(gkanwar): Remove this option. It is not used anywhere. | |
226 option_parser.add_option('--shard_retries', type=int, default=1, | |
227 help=('Number of times to retry each failure when ' | |
228 'sharding.')) | |
229 option_parser.add_option('--official-build', help='Run official build tests.') | |
230 option_parser.add_option('--python_test_root', | |
231 help='Root of the host-driven tests.') | |
232 option_parser.add_option('--keep_test_server_ports', | |
233 action='store_true', | |
234 help=('Indicates the test server ports must be ' | |
235 'kept. When this is run via a sharder ' | |
236 'the test server ports should be kept and ' | |
237 'should not be reset.')) | |
238 # TODO(gkanwar): This option is deprecated. Remove it in the future. | |
239 option_parser.add_option('--disable_assertions', action='store_true', | |
240 help=('(DEPRECATED) Run with java assertions ' | |
241 'disabled.')) | |
242 option_parser.add_option('--test_data', action='append', default=[], | |
243 help=('Each instance defines a directory of test ' | |
244 'data that should be copied to the target(s) ' | |
245 'before running the tests. The argument ' | |
246 'should be of the form <target>:<source>, ' | |
247 '<target> is relative to the device data' | |
248 'directory, and <source> is relative to the ' | |
249 'chromium build directory.')) | |
250 | |
251 | |
252 def ProcessJavaTestOptions(options, error_func): | |
253 """Processes options/arguments and populates options with defaults.""" | |
254 | |
255 if options.java_only and options.python_only: | |
256 error_func('Options java_only (-j) and python_only (-p) ' | |
257 'are mutually exclusive.') | |
258 options.run_java_tests = True | |
259 options.run_python_tests = True | |
260 if options.java_only: | |
261 options.run_python_tests = False | |
262 elif options.python_only: | |
263 options.run_java_tests = False | |
264 | |
265 if not options.python_test_root: | |
266 options.run_python_tests = False | |
267 | |
268 if options.annotation_str: | |
269 options.annotations = options.annotation_str.split(',') | |
270 elif options.test_filter: | |
271 options.annotations = [] | |
272 else: | |
273 options.annotations = ['Smoke', 'SmallTest', 'MediumTest', 'LargeTest'] | |
274 | |
275 if options.exclude_annotation_str: | |
276 options.exclude_annotations = options.exclude_annotation_str.split(',') | |
277 else: | |
278 options.exclude_annotations = [] | |
279 | |
280 if not options.keep_test_server_ports: | |
281 if not ports.ResetTestServerPortAllocation(): | |
282 raise Exception('Failed to reset test server port.') | |
283 | |
284 | |
285 def AddInstrumentationTestOptions(option_parser): | |
286 """Adds Instrumentation test options to option_parser.""" | |
287 | |
288 option_parser.usage = '%prog instrumentation [options]' | |
289 option_parser.command_list = [] | |
290 option_parser.example = ('%prog instrumentation -I ' | |
291 '--test-apk=ChromiumTestShellTest') | |
292 | |
293 option_parser.add_option('-w', '--wait_debugger', dest='wait_for_debugger', | |
294 action='store_true', | |
295 help='Wait for debugger.') | |
296 option_parser.add_option('-I', dest='install_apk', action='store_true', | |
297 help='Install test APK.') | |
298 option_parser.add_option( | |
299 '--test-apk', dest='test_apk', | |
300 help=('The name of the apk containing the tests ' | |
301 '(without the .apk extension; e.g. "ContentShellTest"). ' | |
302 'Alternatively, this can be a full path to the apk.')) | |
303 | |
304 AddJavaTestOptions(option_parser) | |
305 AddCommonOptions(option_parser) | |
306 | |
307 | |
308 def ProcessInstrumentationOptions(options, error_func): | |
309 """Processes options/arguments and populate options with defaults.""" | |
310 | |
311 ProcessJavaTestOptions(options, error_func) | |
312 | |
313 if not options.test_apk: | |
314 error_func('--test-apk must be specified.') | |
315 | |
316 if os.path.exists(options.test_apk): | |
317 # The APK is fully qualified, assume the JAR lives along side. | |
318 options.test_apk_path = options.test_apk | |
319 options.test_apk_jar_path = (os.path.splitext(options.test_apk_path)[0] + | |
320 '.jar') | |
321 else: | |
322 options.test_apk_path = os.path.join(_SDK_OUT_DIR, | |
323 options.build_type, | |
324 constants.SDK_BUILD_APKS_DIR, | |
325 '%s.apk' % options.test_apk) | |
326 options.test_apk_jar_path = os.path.join( | |
327 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_TEST_JAVALIB_DIR, | |
328 '%s.jar' % options.test_apk) | |
329 | |
330 | |
331 def AddUIAutomatorTestOptions(option_parser): | |
332 """Adds UI Automator test options to option_parser.""" | |
333 | |
334 option_parser.usage = '%prog uiautomator [options]' | |
335 option_parser.command_list = [] | |
336 option_parser.example = ( | |
337 '%prog uiautomator --test-jar=chromium_testshell_uiautomator_tests' | |
338 ' --package-name=org.chromium.chrome.testshell') | |
339 option_parser.add_option( | |
340 '--package-name', | |
341 help='The package name used by the apk containing the application.') | |
342 option_parser.add_option( | |
343 '--test-jar', dest='test_jar', | |
344 help=('The name of the dexed jar containing the tests (without the ' | |
345 '.dex.jar extension). Alternatively, this can be a full path ' | |
346 'to the jar.')) | |
347 | |
348 AddJavaTestOptions(option_parser) | |
349 AddCommonOptions(option_parser) | |
350 | |
351 | |
352 def ProcessUIAutomatorOptions(options, error_func): | |
353 """Processes UIAutomator options/arguments.""" | |
354 | |
355 ProcessJavaTestOptions(options, error_func) | |
356 | |
357 if not options.package_name: | |
358 error_func('--package-name must be specified.') | |
359 | |
360 if not options.test_jar: | |
361 error_func('--test-jar must be specified.') | |
362 | |
363 if os.path.exists(options.test_jar): | |
364 # The dexed JAR is fully qualified, assume the info JAR lives along side. | |
365 options.uiautomator_jar = options.test_jar | |
366 else: | |
367 options.uiautomator_jar = os.path.join( | |
368 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_JAVALIB_DIR, | |
369 '%s.dex.jar' % options.test_jar) | |
370 options.uiautomator_info_jar = ( | |
371 options.uiautomator_jar[:options.uiautomator_jar.find('.dex.jar')] + | |
372 '_java.jar') | |
373 | |
374 | |
375 def RunTestsCommand(command, options, args, option_parser): | |
376 """Checks test type and dispatches to the appropriate function. | |
377 | |
378 Args: | |
379 command: String indicating the command that was received to trigger | |
380 this function. | |
381 options: optparse options dictionary. | |
382 args: List of extra args from optparse. | |
383 option_parser: optparse.OptionParser object. | |
384 | |
385 Returns: | |
386 Integer indicated exit code. | |
387 """ | |
388 | |
389 ProcessCommonOptions(options) | |
390 | |
391 total_failed = 0 | |
392 if command == 'gtest': | |
393 # TODO(gkanwar): See the emulator TODO above -- this call should either go | |
394 # away or become generalized. | |
395 ProcessEmulatorOptions(options) | |
396 total_failed = gtest_dispatch.Dispatch(options) | |
397 elif command == 'content_browsertests': | |
398 total_failed = browsertests_dispatch.Dispatch(options) | |
399 elif command == 'instrumentation': | |
400 ProcessInstrumentationOptions(options, option_parser.error) | |
401 if options.run_java_tests: | |
402 total_failed += instrumentation_dispatch.Dispatch(options) | |
403 if options.run_python_tests: | |
404 total_failed += python_dispatch.Dispatch(options) | |
405 elif command == 'uiautomator': | |
406 ProcessUIAutomatorOptions(options, option_parser.error) | |
407 if options.run_java_tests: | |
408 total_failed += uiautomator_dispatch.Dispatch(options) | |
409 if options.run_python_tests: | |
410 total_failed += python_dispatch.Dispatch(options) | |
411 else: | |
412 raise Exception('Unknown test type state') | |
413 | |
414 return total_failed | |
415 | |
416 | |
417 def HelpCommand(command, options, args, option_parser): | |
418 """Display help for a certain command, or overall help. | |
419 | |
420 Args: | |
421 command: String indicating the command that was received to trigger | |
422 this function. | |
423 options: optparse options dictionary. | |
424 args: List of extra args from optparse. | |
425 option_parser: optparse.OptionParser object. | |
426 | |
427 Returns: | |
428 Integer indicated exit code. | |
429 """ | |
430 # If we don't have any args, display overall help | |
431 if len(args) < 3: | |
432 option_parser.print_help() | |
433 return 0 | |
434 | |
435 command = args[2] | |
436 | |
437 if command not in VALID_COMMANDS: | |
438 option_parser.error('Unrecognized command.') | |
439 | |
440 # Treat the help command as a special case. We don't care about showing a | |
441 # specific help page for itself. | |
442 if command == 'help': | |
443 option_parser.print_help() | |
444 return 0 | |
445 | |
446 VALID_COMMANDS[command].add_options_func(option_parser) | |
447 option_parser.usage = '%prog ' + command + ' [options]' | |
448 option_parser.command_list = None | |
449 option_parser.print_help() | |
450 | |
451 return 0 | |
452 | |
453 | |
454 # Define a named tuple for the values in the VALID_COMMANDS dictionary so the | |
455 # syntax is a bit prettier. The tuple is two functions: (add options, run | |
456 # command). | |
457 CommandFunctionTuple = collections.namedtuple( | |
458 'CommandFunctionTuple', ['add_options_func', 'run_command_func']) | |
459 VALID_COMMANDS = { | |
460 'gtest': CommandFunctionTuple(AddGTestOptions, RunTestsCommand), | |
461 'content_browsertests': CommandFunctionTuple( | |
462 AddContentBrowserTestOptions, RunTestsCommand), | |
463 'instrumentation': CommandFunctionTuple( | |
464 AddInstrumentationTestOptions, RunTestsCommand), | |
465 'uiautomator': CommandFunctionTuple( | |
466 AddUIAutomatorTestOptions, RunTestsCommand), | |
467 'help': CommandFunctionTuple(lambda option_parser: None, HelpCommand) | |
468 } | |
469 | |
470 | |
471 class CommandOptionParser(optparse.OptionParser): | |
472 """Wrapper class for OptionParser to help with listing commands.""" | |
473 | |
474 def __init__(self, *args, **kwargs): | |
475 self.command_list = kwargs.pop('command_list', []) | |
476 self.example = kwargs.pop('example', '') | |
477 optparse.OptionParser.__init__(self, *args, **kwargs) | |
478 | |
479 #override | |
480 def get_usage(self): | |
481 normal_usage = optparse.OptionParser.get_usage(self) | |
482 command_list = self.get_command_list() | |
483 example = self.get_example() | |
484 return self.expand_prog_name(normal_usage + example + command_list) | |
485 | |
486 #override | |
487 def get_command_list(self): | |
488 if self.command_list: | |
489 return '\nCommands:\n %s\n\n' % '\n '.join(sorted(self.command_list)) | |
490 return '' | |
491 | |
492 def get_example(self): | |
493 if self.example: | |
494 return '\nExample:\n %s\n\n' % self.example | |
frankf
2013/07/01 22:36:21
Why two blank lines here and above?
gkanwar
2013/07/01 23:46:37
I wanted to separate Usage and Example from Option
| |
495 return '' | |
496 | |
497 def main(argv): | |
498 option_parser = CommandOptionParser( | |
499 usage='Usage: %prog <command> [options]', | |
500 command_list=VALID_COMMANDS.keys()) | |
501 | |
502 if len(argv) < 2 or argv[1] not in VALID_COMMANDS: | |
503 option_parser.print_help() | |
504 return 0 | |
505 command = argv[1] | |
506 VALID_COMMANDS[command].add_options_func(option_parser) | |
507 options, args = option_parser.parse_args(argv) | |
508 exit_code = VALID_COMMANDS[command].run_command_func( | |
509 command, options, args, option_parser) | |
510 | |
511 # Failures of individual test suites are communicated by printing a | |
512 # STEP_FAILURE message. | |
513 # Returning a success exit status also prevents the buildbot from incorrectly | |
514 # marking the last suite as failed if there were failures in other suites in | |
515 # the batch (this happens because the exit status is a sum of all failures | |
516 # from all suites, but the buildbot associates the exit status only with the | |
517 # most recent step). | |
518 return exit_code | |
519 | |
520 | |
521 if __name__ == '__main__': | |
522 sys.exit(main(sys.argv)) | |
OLD | NEW |