Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1456)

Side by Side Diff: build/android/run_all_tests.py

Issue 15942016: Creates a new test running script test_runner.py (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Converts options to command-style format Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « build/android/pylib/utils/test_options_parser.py ('k') | build/android/run_browser_tests.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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 (gtests)
11 Example: ./run_all_tests.py gtests -s android_webview_unittests
12 2. ContentBrowser unit tests (content_browsertests)
13 Example: ./run_all_tests.py content_browsertests
14 3. Instrumentation tests (instrumentation): Both Python host-driven and
15 Java instrumentation tests are run by default. Use --python_only or
16 --java_only to select one or the other.
17 Example: ./run_all_tests.py instrumentation -I
18 --test-apk=ChromiumTestShellTest
19 4. UIAutomator tests (uiautomator): Both Python host-driven and Java
20 UIAutomator tests are run by default. Use --python_only or --java_only to
21 select one or the other.
22 Example: ./run_all_tests.py uiautomator
23 --test-jar=chromium_testshell_uiautomator_tests
24 --package-name=org.chromium.chrome.testshell
25
26 TODO(gkanwar):
27 * Add options to run Monkey tests.
28 """
29
30 import optparse
31 import os
32 import sys
33
34 from pylib import cmd_helper
35 from pylib import constants
36 from pylib import ports
37 from pylib.browsertests import dispatch as browsertests_dispatch
38 from pylib.gtest import dispatch as gtest_dispatch
39 from pylib.host_driven import run_python_tests as python_dispatch
40 from pylib.instrumentation import dispatch as instrumentation_dispatch
41 from pylib.uiautomator import dispatch as uiautomator_dispatch
42 from pylib.utils import emulator
43 from pylib.utils import run_tests_helper
44
45 _SDK_OUT_DIR = os.path.join(constants.DIR_SOURCE_ROOT, 'out')
46
47
48 def AddBuildTypeOption(option_parser):
49 """Adds the build type option to option_parser."""
50 default_build_type = 'Debug'
51 if 'BUILDTYPE' in os.environ:
52 default_build_type = os.environ['BUILDTYPE']
53 option_parser.add_option('--debug', action='store_const', const='Debug',
54 dest='build_type', default=default_build_type,
55 help=('If set, run test suites under out/Debug. '
56 'Default is env var BUILDTYPE or Debug.'))
57 option_parser.add_option('--release', action='store_const',
58 const='Release', dest='build_type',
59 help=('If set, run test suites under out/Release.'
60 ' Default is env var BUILDTYPE or Debug.'))
61
62
63 def AddEmulatorOptions(option_parser):
64 """Adds all emulator-related options to option_parser."""
65
66 # TODO(gkanwar): Figure out what we're doing with the emulator setup
67 # and determine whether these options should be deprecated/removed.
68 option_parser.add_option('-e', '--emulator', dest='use_emulator',
69 action='store_true',
70 help='Run tests in a new instance of emulator.')
71 option_parser.add_option('-n', '--emulator-count',
72 type='int', default=1,
73 help=('Number of emulators to launch for '
74 'running the tests.'))
75 option_parser.add_option('--abi', default='armeabi-v7a',
76 help='Platform of emulators to launch.')
77
78
79 def ProcessEmulatorOptions(options):
80 """Processes emulator options."""
81 if options.use_emulator:
82 emulator.DeleteAllTempAVDs()
83
84
85 def AddCommonOptions(option_parser):
86 """Adds all common options to option_parser."""
87
88 AddBuildTypeOption(option_parser)
89
90 # --gtest_filter is DEPRECATED. Added for backwards compatibility
91 # with the syntax of the old run_tests.py script.
92 option_parser.add_option('-f', '--test_filter', '--gtest_filter',
93 dest='test_filter',
94 help=('Test filter (if not fully qualified, '
95 'will run all matches).'))
96 option_parser.add_option('--out-directory', dest='out_directory',
97 help=('Path to the out/ directory, irrespective of '
98 'the build type. Only for non-Chromium uses.'))
99 option_parser.add_option('-c', dest='cleanup_test_files',
100 help='Cleanup test files on the device after run',
101 action='store_true')
102 option_parser.add_option('--num_retries', dest='num_retries', type='int',
103 default=2,
104 help=('Number of retries for a test before '
105 'giving up.'))
106 option_parser.add_option('-v',
107 '--verbose',
108 dest='verbose_count',
109 default=0,
110 action='count',
111 help='Verbose level (multiple times for more)')
112 profilers = ['devicestatsmonitor', 'chrometrace', 'dumpheap', 'smaps',
113 'traceview']
114 option_parser.add_option('--profiler', dest='profilers', action='append',
115 choices=profilers,
116 help=('Profiling tool to run during test. Pass '
117 'multiple times to run multiple profilers. '
118 'Available profilers: %s' % profilers))
119 option_parser.add_option('--tool',
120 dest='tool',
121 help=('Run the test under a tool '
122 '(use --tool help to list them)'))
123 option_parser.add_option('--flakiness-dashboard-server',
124 dest='flakiness_dashboard_server',
125 help=('Address of the server that is hosting the '
126 'Chrome for Android flakiness dashboard.'))
127 option_parser.add_option('--skip-deps-push', dest='push_deps',
128 action='store_false', default=True,
129 help=('Do not push dependencies to the device. '
130 'Use this at own risk for speeding up test '
131 'execution on local machine.'))
132 # TODO(gkanwar): This option is deprecated. Remove it in the future.
133 option_parser.add_option('--exit-code', action='store_true',
134 help=('(DEPRECATED) If set, the exit code will be '
135 'total number of failures.'))
136 # TODO(gkanwar): This option is deprecated. It is currently used to run tests
137 # with the FlakyTest annotation to prevent the bots going red downstream. See
138 # crbug.com/147176. We should remove this option once FlakyTests are removed
frankf 2013/06/27 23:13:35 We're not removing FlakyTests. The root issue is t
gkanwar 2013/06/28 22:09:45 Ah, that clarifies things. Updated the comment.
139 # from the general test script.
140 option_parser.add_option('--buildbot-step-failure',
141 action='store_true',
142 help=('(DEPRECATED) If present, will set the '
143 'buildbot status as STEP_FAILURE, otherwise '
144 'as STEP_WARNINGS when test(s) fail.'))
145 option_parser.add_option('-d', '--device', dest='test_device',
146 help=('Target device for the test suite '
147 'to run on.'))
148
149
150 def ProcessCommonOptions(options):
151 """Processes and handles all common options."""
152 if options.out_directory:
153 cmd_helper.OutDirectory.set(options.out_directory)
154 run_tests_helper.SetLogLevel(options.verbose_count)
155
156
157 def AddContentBrowserOptions(option_parser):
158 """Adds Content Browser test options to option_parser."""
159
160 option_parser.description = './run_all_tests.py content_browsertests'
161
162 AddCommonOptions(option_parser)
163
164
165 def AddGTestOptions(option_parser, default_timeout=60):
166 """Adds gtest options to option_parser."""
167
168 option_parser.description = ('Example call: %prog gtests -s '
frankf 2013/06/27 23:13:35 You have this as Example usage in other places. Ha
frankf 2013/06/27 23:13:35 prog is shown as ./run_all_tests.py regardless of
frankf 2013/06/27 23:13:35 %s/gtests/gtest/g
gkanwar 2013/06/28 22:09:45 Looks like it shows just "run_all_tests.py" (no ./
gkanwar 2013/06/28 22:09:45 Done.
gkanwar 2013/06/28 22:09:45 Done.
169 'android_webview_unittests')
170
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(
203 '-A', '--annotation', dest='annotation_str',
204 help=('Comma-separated list of annotations. Run only tests with any of '
205 'the given annotations. An annotation can be either a key or a '
206 'key-values pair. A test that has no annotation is considered '
207 '"SmallTest".'))
208 option_parser.add_option(
209 '-E', '--exclude-annotation', dest='exclude_annotation_str',
210 help=('Comma-separated list of annotations. Exclude tests with these '
211 'annotations.'))
212 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('--screenshot', dest='screenshot_failures',
218 action='store_true',
219 help='Capture screenshots of test failures')
220 option_parser.add_option('--save-perf-json', action='store_true',
221 help='Saves the JSON file for each UI Perf test.')
222 # TODO(gkanwar): Remove this option. It is not used anywhere.
223 option_parser.add_option('--shard_retries', type=int, default=1,
224 help=('Number of times to retry each failure when '
225 'sharding.'))
226 option_parser.add_option('--official-build', help='Run official build tests.')
227 option_parser.add_option('--python_test_root',
228 help='Root of the host-driven tests.')
229 option_parser.add_option('--keep_test_server_ports',
230 action='store_true',
231 help=('Indicates the test server ports must be '
232 'kept. When this is run via a sharder '
233 'the test server ports should be kept and '
234 'should not be reset.'))
235 # TODO(gkanwar): This option is deprecated. Remove it in the future.
236 option_parser.add_option('--disable_assertions', action='store_true',
237 help=('(DEPRECATED) Run with java assertions '
238 'disabled.'))
239 option_parser.add_option('--test_data', action='append', default=[],
240 help=('Each instance defines a directory of test '
241 'data that should be copied to the target(s) '
242 'before running the tests. The argument '
243 'should be of the form <target>:<source>, '
244 '<target> is relative to the device data'
245 'directory, and <source> is relative to the '
246 'chromium build directory.'))
247
248
249 def ProcessJavaTestOptions(options, errorf):
250 """Processes options/arguments and populates options with defaults."""
251
252 if options.java_only and options.python_only:
253 errorf('Options java_only (-j) and python_only (-p) '
254 'are mutually exclusive.')
255 options.run_java_tests = True
256 options.run_python_tests = True
257 if options.java_only:
258 options.run_python_tests = False
259 elif options.python_only:
260 options.run_java_tests = False
261
262 if not options.python_test_root:
263 options.run_python_tests = False
264
265 if options.annotation_str:
266 options.annotations = options.annotation_str.split(',')
267 elif options.test_filter:
268 options.annotations = []
269 else:
270 options.annotations = ['Smoke', 'SmallTest', 'MediumTest', 'LargeTest']
271
272 if options.exclude_annotation_str:
273 options.exclude_annotations = options.exclude_annotation_str.split(',')
274 else:
275 options.exclude_annotations = []
276
277 if not options.keep_test_server_ports:
278 if not ports.ResetTestServerPortAllocation():
279 raise Exception('Failed to reset test server port.')
280
281
282 def AddInstrumentationOptions(option_parser):
283 """Adds Instrumentation test options to option_parser."""
284 option_parser.description = (
285 'Example call: ./run_all_tests.py instrumentation -I '
286 '--test-apk=ChromiumTestShellTest')
287
288 option_parser.add_option('-w', '--wait_debugger', dest='wait_for_debugger',
289 action='store_true',
290 help='Wait for debugger.')
291 option_parser.add_option('-I', dest='install_apk', action='store_true',
292 help='Install test APK.')
293 option_parser.add_option(
294 '--test-apk', dest='test_apk',
295 help=('The name of the apk containing the tests '
296 '(without the .apk extension; e.g. "ContentShellTest"). '
297 'Alternatively, this can be a full path to the apk.'))
298
299 AddJavaTestOptions(option_parser)
300 AddCommonOptions(option_parser)
301
302
303 def ProcessInstrumentationOptions(options, errorf):
304 """Processes options/arguments and populate options with defaults."""
305
306 ProcessJavaTestOptions(options, errorf)
307
308 if not options.test_apk:
309 errorf('--test-apk must be specified.')
310
311 if os.path.exists(options.test_apk):
312 # The APK is fully qualified, assume the JAR lives along side.
313 options.test_apk_path = options.test_apk
314 options.test_apk_jar_path = (os.path.splitext(options.test_apk_path)[0] +
315 '.jar')
316 else:
317 options.test_apk_path = os.path.join(_SDK_OUT_DIR,
318 options.build_type,
319 constants.SDK_BUILD_APKS_DIR,
320 '%s.apk' % options.test_apk)
321 options.test_apk_jar_path = os.path.join(
322 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_TEST_JAVALIB_DIR,
323 '%s.jar' % options.test_apk)
324
325
326 def AddUIAutomatorOptions(option_parser):
327 """Adds UI Automator test options to option_parser."""
328 option_parser.description = ('Example usage: ./run_all_tests.py uiautomator '
frankf 2013/06/27 23:13:35 Indent this on the next lien
gkanwar 2013/06/28 22:09:45 There are no newlines here, it is just a continuat
329 '--test-jar=chromium_testshell_uiautomator_tests'
330 ' --package-name=org.chromium.chrome.testshell')
331 option_parser.add_option(
332 '--package-name',
333 help='The package name used by the apk containing the application.')
334 option_parser.add_option(
335 '--test-jar', dest='test_jar',
336 help=('The name of the dexed jar containing the tests (without the '
337 '.dex.jar extension). Alternatively, this can be a full path '
338 'to the jar.'))
339
340 AddJavaTestOptions(option_parser)
341 AddCommonOptions(option_parser)
342
343
344 def ProcessUIAutomatorOptions(options, errorf):
345 """Processes UIAutomator options/arguments."""
346
347 ProcessJavaTestOptions(options, errorf)
348
349 if not options.package_name:
350 errorf('--package-name must be specified.')
351
352 if not options.test_jar:
353 errorf('--test-jar must be specified.')
354
355 if os.path.exists(options.test_jar):
356 # The dexed JAR is fully qualified, assume the info JAR lives along side.
357 options.uiautomator_jar = options.test_jar
358 else:
359 options.uiautomator_jar = os.path.join(
360 _SDK_OUT_DIR, options.build_type, constants.SDK_BUILD_JAVALIB_DIR,
361 '%s.dex.jar' % options.test_jar)
362 options.uiautomator_info_jar = (
363 options.uiautomator_jar[:options.uiautomator_jar.find('.dex.jar')] +
364 '_java.jar')
365
366
367 def RunTestsCommand(command_string, options, args, option_parser):
frankf 2013/06/27 23:13:35 :%s/command_string/command/g
gkanwar 2013/06/28 22:09:45 Done.
368 """Checks test type and dispatches to the appropriate function."""
369
370 ProcessCommonOptions(options)
371
372 total_failed = 0
373 if command_string == 'gtests':
374 # TODO(gkanwar): See the emulator TODO above -- this call should either go
375 # away or become generalized.
376 ProcessEmulatorOptions(options)
377 total_failed = gtest_dispatch.Dispatch(options)
378 elif command_string == 'content_browsertests':
379 total_failed = browsertests_dispatch.Dispatch(options)
380 elif command_string == 'instrumentation':
381 ProcessInstrumentationOptions(options, option_parser.error)
382 if options.run_java_tests:
383 total_failed += instrumentation_dispatch.Dispatch(options)
384 if options.run_python_tests:
385 total_failed += python_dispatch.Dispatch(options)
386 elif command_string == 'uiautomator':
387 ProcessUIAutomatorOptions(options, option_parser.error)
388 if options.run_java_tests:
389 total_failed += uiautomator_dispatch.Dispatch(options)
390 if options.run_python_tests:
391 total_failed += python_dispatch.Dispatch(options)
392 else:
393 raise Exception('Unknown test type state')
394
395 return total_failed
396
397
398 def HelpCommand(command_string, options, args, option_parser):
399 """Display help for a certain command, or overall help."""
400 # If we don't have any args, display overall help
401 if len(args) < 3:
402 option_parser.print_help()
403 return
404
405 command = args[2]
406 if command not in COMMANDS:
407 option_parser.error('Unrecognized command.')
408 COMMANDS[command][1](option_parser) # Call the function to add options for
409 # this command
410 option_parser.usage = '%prog ' + command + ' [options]'
411 option_parser.command_list = None
412 option_parser.print_help()
413
414 return 0
415
416
417 # Define COMMANDS after all the command functions have been defined
418 # COMMANDS is a dictionary from the command string to a tuple. The first element
419 # of the tuple is the command function, and the second element is a function to
420 # add all options relating to that test.
frankf 2013/06/27 23:13:35 Shorten this comment to (test type, list of funct
gkanwar 2013/06/28 22:09:45 I added a namedtuple for cleaning up the COMMANDS
421 COMMANDS = {
frankf 2013/06/27 23:13:35 Defien all constants at the top. Follow the naming
gkanwar 2013/06/28 22:09:45 The reason it's defined down here is because it ne
422 'gtests': (RunTestsCommand, AddGTestOptions),
frankf 2013/06/27 23:13:35 I would reverse the ordering of these two.
gkanwar 2013/06/28 22:09:45 Done.
423 'content_browsertests': (RunTestsCommand,
424 AddContentBrowserOptions),
425 'instrumentation': (RunTestsCommand, AddInstrumentationOptions),
426 'uiautomator': (RunTestsCommand, AddUIAutomatorOptions),
427 'help': (HelpCommand, lambda option_parser: None)
frankf 2013/06/27 23:13:35 "test --help" should be identical to: "help test"
gkanwar 2013/06/28 22:09:45 Done.
428 }
429
430
431 class CommandOptionParser(optparse.OptionParser):
432 """Wrapper class for OptionParser to help with listing commands."""
433
434 def __init__(self, *args, **kwargs):
frankf 2013/06/27 23:13:35 Why do you take arbitrary params?
gkanwar 2013/06/28 22:09:45 To pass through to the OptionParser __init__ comma
435 self.command_list = kwargs.pop('command_list', [])
436 optparse.OptionParser.__init__(self, *args, **kwargs)
437
438 def get_usage(self):
439 normal_usage = optparse.OptionParser.get_usage(self)
440 command_list = self.get_command_list()
441 return normal_usage + '\n' + command_list
442
443 def get_command_list(self):
444 if self.command_list:
445 return 'Commands:\n ' + '\n '.join(sorted(self.command_list)) + '\n\n'
frankf 2013/06/27 23:13:35 Prefer using string formating '%s' % foo
gkanwar 2013/06/28 22:09:45 Done.
446 return ''
447
448
449 def main(argv):
450 option_parser = CommandOptionParser(
451 usage='Usage: %prog command [options]',
frankf 2013/06/27 23:13:35 <command>
gkanwar 2013/06/28 22:09:45 Done.
452 command_list=COMMANDS.keys())
453
454 if len(argv) < 2:
455 option_parser.error('No command specified.')
456
457 command = argv[1]
458 if command not in COMMANDS:
459 option_parser.error('Invalid command.')
frankf 2013/06/27 23:13:35 This shouldn't be thrown if --help is specified.
gkanwar 2013/06/28 22:09:45 Done.
460 COMMANDS[command][1](option_parser) # Call the function to add options for
frankf 2013/06/27 23:13:35 This is pretty unreadable. Think of a better way t
gkanwar 2013/06/28 22:09:45 Replaced tuples with namedtuples to make this clea
461 # this command
462 options, args = option_parser.parse_args(argv)
463 command_func = COMMANDS[command][0] # Get the command function
464 exit_code = command_func(command, options, args, option_parser)
465
466 # Failures of individual test suites are communicated by printing a
467 # STEP_FAILURE message.
468 # Returning a success exit status also prevents the buildbot from incorrectly
469 # marking the last suite as failed if there were failures in other suites in
470 # the batch (this happens because the exit status is a sum of all failures
471 # from all suites, but the buildbot associates the exit status only with the
472 # most recent step).
473 return exit_code
474
475
476 if __name__ == '__main__':
477 sys.exit(main(sys.argv))
OLDNEW
« no previous file with comments | « build/android/pylib/utils/test_options_parser.py ('k') | build/android/run_browser_tests.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698