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

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

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

Powered by Google App Engine
This is Rietveld 408576698