blob: fde67adf74d6e4710ef7ee5550d79235f670f66e [file] [log] [blame]
The Android Open Source Project6ffae012009-03-18 17:39:43 -07001#!/usr/bin/python2.4
2#
3# Copyright 2008, The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Command line utility for running a pre-defined test.
18
19Based on previous <androidroot>/development/tools/runtest shell script.
20"""
21
22# Python imports
23import glob
24import optparse
25import os
Niko Catania2e990b92009-04-02 16:52:26 -070026import re
The Android Open Source Project6ffae012009-03-18 17:39:43 -070027from sets import Set
28import sys
29
30# local imports
31import adb_interface
32import android_build
33import coverage
34import errors
35import logger
36import run_command
37import test_defs
38
39
40class TestRunner(object):
41 """Command line utility class for running pre-defined Android test(s)."""
42
Brett Chabotf61f43e2009-04-02 11:52:48 -070043 _TEST_FILE_NAME = "test_defs.xml"
44
The Android Open Source Project6ffae012009-03-18 17:39:43 -070045 # file path to android core platform tests, relative to android build root
46 # TODO move these test data files to another directory
Nicolas Catania97b24c42009-04-22 11:08:32 -070047 _CORE_TEST_PATH = os.path.join("development", "testrunner",
Brett Chabotf61f43e2009-04-02 11:52:48 -070048 _TEST_FILE_NAME)
The Android Open Source Project6ffae012009-03-18 17:39:43 -070049
50 # vendor glob file path patterns to tests, relative to android
51 # build root
52 _VENDOR_TEST_PATH = os.path.join("vendor", "*", "tests", "testinfo",
Brett Chabotf61f43e2009-04-02 11:52:48 -070053 _TEST_FILE_NAME)
The Android Open Source Project6ffae012009-03-18 17:39:43 -070054
55 _RUNTEST_USAGE = (
56 "usage: runtest.py [options] short-test-name[s]\n\n"
57 "The runtest script works in two ways. You can query it "
58 "for a list of tests, or you can launch one or more tests.")
59
Brett Chabot72731f32009-03-31 11:14:05 -070060 def __init__(self):
61 # disable logging of timestamp
Niko Catania2e990b92009-04-02 16:52:26 -070062 self._root_path = android_build.GetTop()
Nicolas Catania97b24c42009-04-22 11:08:32 -070063 logger.SetTimestampLogging(False)
Brett Chabot72731f32009-03-31 11:14:05 -070064
The Android Open Source Project6ffae012009-03-18 17:39:43 -070065 def _ProcessOptions(self):
66 """Processes command-line options."""
67 # TODO error messages on once-only or mutually-exclusive options.
68 user_test_default = os.path.join(os.environ.get("HOME"), ".android",
Brett Chabotf61f43e2009-04-02 11:52:48 -070069 self._TEST_FILE_NAME)
The Android Open Source Project6ffae012009-03-18 17:39:43 -070070
71 parser = optparse.OptionParser(usage=self._RUNTEST_USAGE)
72
73 parser.add_option("-l", "--list-tests", dest="only_list_tests",
74 default=False, action="store_true",
75 help="To view the list of tests")
76 parser.add_option("-b", "--skip-build", dest="skip_build", default=False,
77 action="store_true", help="Skip build - just launch")
78 parser.add_option("-n", "--skip_execute", dest="preview", default=False,
79 action="store_true",
80 help="Do not execute, just preview commands")
81 parser.add_option("-r", "--raw-mode", dest="raw_mode", default=False,
82 action="store_true",
83 help="Raw mode (for output to other tools)")
84 parser.add_option("-a", "--suite-assign", dest="suite_assign_mode",
85 default=False, action="store_true",
86 help="Suite assignment (for details & usage see "
87 "InstrumentationTestRunner)")
88 parser.add_option("-v", "--verbose", dest="verbose", default=False,
89 action="store_true",
90 help="Increase verbosity of %s" % sys.argv[0])
91 parser.add_option("-w", "--wait-for-debugger", dest="wait_for_debugger",
92 default=False, action="store_true",
93 help="Wait for debugger before launching tests")
94 parser.add_option("-c", "--test-class", dest="test_class",
95 help="Restrict test to a specific class")
96 parser.add_option("-m", "--test-method", dest="test_method",
97 help="Restrict test to a specific method")
Brett Chabot8a101cb2009-05-05 12:56:39 -070098 parser.add_option("-p", "--test-package", dest="test_package",
99 help="Restrict test to a specific java package")
100 parser.add_option("-z", "--size", dest="test_size",
101 help="Restrict test to a specific test size")
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700102 parser.add_option("-u", "--user-tests-file", dest="user_tests_file",
103 metavar="FILE", default=user_test_default,
104 help="Alternate source of user test definitions")
105 parser.add_option("-o", "--coverage", dest="coverage",
106 default=False, action="store_true",
107 help="Generate code coverage metrics for test(s)")
108 parser.add_option("-t", "--all-tests", dest="all_tests",
109 default=False, action="store_true",
110 help="Run all defined tests")
111 parser.add_option("--continuous", dest="continuous_tests",
112 default=False, action="store_true",
113 help="Run all tests defined as part of the continuous "
114 "test set")
115
116 group = optparse.OptionGroup(
117 parser, "Targets", "Use these options to direct tests to a specific "
118 "Android target")
119 group.add_option("-e", "--emulator", dest="emulator", default=False,
120 action="store_true", help="use emulator")
121 group.add_option("-d", "--device", dest="device", default=False,
122 action="store_true", help="use device")
123 group.add_option("-s", "--serial", dest="serial",
124 help="use specific serial")
125 parser.add_option_group(group)
126
127 self._options, self._test_args = parser.parse_args()
128
129 if (not self._options.only_list_tests and not self._options.all_tests
130 and not self._options.continuous_tests and len(self._test_args) < 1):
131 parser.print_help()
132 logger.SilentLog("at least one test name must be specified")
133 raise errors.AbortError
134
135 self._adb = adb_interface.AdbInterface()
136 if self._options.emulator:
137 self._adb.SetEmulatorTarget()
138 elif self._options.device:
139 self._adb.SetDeviceTarget()
140 elif self._options.serial is not None:
141 self._adb.SetTargetSerial(self._options.serial)
142
143 if self._options.verbose:
144 logger.SetVerbose(True)
145
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700146 self._known_tests = self._ReadTests()
147
148 self._coverage_gen = coverage.CoverageGenerator(
149 android_root_path=self._root_path, adb_interface=self._adb)
150
151 def _ReadTests(self):
152 """Parses the set of test definition data.
153
154 Returns:
155 A TestDefinitions object that contains the set of parsed tests.
156 Raises:
157 AbortError: If a fatal error occurred when parsing the tests.
158 """
159 core_test_path = os.path.join(self._root_path, self._CORE_TEST_PATH)
160 try:
161 known_tests = test_defs.TestDefinitions()
162 known_tests.Parse(core_test_path)
Brett Chabot2d85c0e2009-03-31 15:19:13 -0700163 # read all <android root>/vendor/*/tests/testinfo/test_defs.xml paths
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700164 vendor_tests_pattern = os.path.join(self._root_path,
165 self._VENDOR_TEST_PATH)
166 test_file_paths = glob.glob(vendor_tests_pattern)
167 for test_file_path in test_file_paths:
168 known_tests.Parse(test_file_path)
169 if os.path.isfile(self._options.user_tests_file):
170 known_tests.Parse(self._options.user_tests_file)
171 return known_tests
172 except errors.ParseError:
173 raise errors.AbortError
174
175 def _DumpTests(self):
176 """Prints out set of defined tests."""
177 print "The following tests are currently defined:"
178 for test in self._known_tests:
Niko Catania2e990b92009-04-02 16:52:26 -0700179 print "%-15s %s" % (test.GetName(), test.GetDescription())
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700180
181 def _DoBuild(self):
182 logger.SilentLog("Building tests...")
183 target_set = Set()
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700184 extra_args_set = Set()
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700185 for test_suite in self._GetTestsToRun():
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700186 self._AddBuildTarget(test_suite, target_set, extra_args_set)
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700187
188 if target_set:
189 if self._options.coverage:
190 self._coverage_gen.EnableCoverageBuild()
Brett Chabot2b6643b2009-04-07 18:35:27 -0700191 self._AddBuildTargetPath(self._coverage_gen.GetEmmaBuildPath(),
192 target_set)
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700193 target_build_string = " ".join(list(target_set))
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700194 extra_args_string = " ".join(list(extra_args_set))
Brett Chabot2b6643b2009-04-07 18:35:27 -0700195 # log the user-friendly equivalent make command, so developers can
196 # replicate this step
197 logger.Log("mmm %s %s" % (target_build_string, extra_args_string))
198 # mmm cannot be used from python, so perform a similiar operation using
199 # ONE_SHOT_MAKEFILE
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700200 cmd = 'ONE_SHOT_MAKEFILE="%s" make -C "%s" files %s' % (
201 target_build_string, self._root_path, extra_args_string)
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700202
Brett Chabot72731f32009-03-31 11:14:05 -0700203 if self._options.preview:
204 # in preview mode, just display to the user what command would have been
205 # run
206 logger.Log("adb sync")
207 else:
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700208 run_command.RunCommand(cmd, return_output=False)
209 logger.Log("Syncing to device...")
210 self._adb.Sync()
211
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700212 def _AddBuildTarget(self, test_suite, target_set, extra_args_set):
213 build_dir = test_suite.GetBuildPath()
Brett Chabot2b6643b2009-04-07 18:35:27 -0700214 if self._AddBuildTargetPath(build_dir, target_set):
215 extra_args_set.add(test_suite.GetExtraMakeArgs())
216
217 def _AddBuildTargetPath(self, build_dir, target_set):
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700218 if build_dir is not None:
219 build_file_path = os.path.join(build_dir, "Android.mk")
220 if os.path.isfile(os.path.join(self._root_path, build_file_path)):
221 target_set.add(build_file_path)
Brett Chabot2b6643b2009-04-07 18:35:27 -0700222 return True
223 return False
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700224
225 def _GetTestsToRun(self):
226 """Get a list of TestSuite objects to run, based on command line args."""
227 if self._options.all_tests:
228 return self._known_tests.GetTests()
229 if self._options.continuous_tests:
230 return self._known_tests.GetContinuousTests()
231 tests = []
232 for name in self._test_args:
233 test = self._known_tests.GetTest(name)
234 if test is None:
235 logger.Log("Error: Could not find test %s" % name)
236 self._DumpTests()
237 raise errors.AbortError
238 tests.append(test)
239 return tests
240
241 def _RunTest(self, test_suite):
242 """Run the provided test suite.
243
244 Builds up an adb instrument command using provided input arguments.
245
246 Args:
247 test_suite: TestSuite to run
248 """
249
250 test_class = test_suite.GetClassName()
251 if self._options.test_class is not None:
252 test_class = self._options.test_class
253 if self._options.test_method is not None:
254 test_class = "%s#%s" % (test_class, self._options.test_method)
255
256 instrumentation_args = {}
257 if test_class is not None:
258 instrumentation_args["class"] = test_class
Brett Chabot8a101cb2009-05-05 12:56:39 -0700259 if self._options.test_package:
260 instrumentation_args["package"] = self._options.test_package
261 if self._options.test_size:
262 instrumentation_args["size"] = self._options.test_size
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700263 if self._options.wait_for_debugger:
264 instrumentation_args["debug"] = "true"
265 if self._options.suite_assign_mode:
266 instrumentation_args["suiteAssignment"] = "true"
267 if self._options.coverage:
268 instrumentation_args["coverage"] = "true"
269 if self._options.preview:
270 adb_cmd = self._adb.PreviewInstrumentationCommand(
271 package_name=test_suite.GetPackageName(),
272 runner_name=test_suite.GetRunnerName(),
273 raw_mode=self._options.raw_mode,
274 instrumentation_args=instrumentation_args)
275 logger.Log(adb_cmd)
276 else:
277 self._adb.StartInstrumentationNoResults(
278 package_name=test_suite.GetPackageName(),
279 runner_name=test_suite.GetRunnerName(),
280 raw_mode=self._options.raw_mode,
281 instrumentation_args=instrumentation_args)
282 if self._options.coverage and test_suite.GetTargetName() is not None:
283 coverage_file = self._coverage_gen.ExtractReport(test_suite)
284 if coverage_file is not None:
285 logger.Log("Coverage report generated at %s" % coverage_file)
286
Nicolas Cataniaff096c12009-05-01 11:55:36 -0700287 def _CollectTestSources(self, test_list, dirname, files):
288 """For each directory, find tests source file and add them to the list.
289
290 Test files must match one of the following pattern:
291 - test_*.[cc|cpp]
292 - *_test.[cc|cpp]
293 - *_unittest.[cc|cpp]
294
295 This method is a callback for os.path.walk.
296
297 Args:
298 test_list: Where new tests should be inserted.
299 dirname: Current directory.
300 files: List of files in the current directory.
301 """
302 for f in files:
303 (name, ext) = os.path.splitext(f)
304 if ext == ".cc" or ext == ".cpp":
305 if re.search("_test$|_test_$|_unittest$|_unittest_$|^test_", name):
306 logger.SilentLog("Found %s" % f)
307 test_list.append(str(os.path.join(dirname, f)))
308
309 def _FilterOutMissing(self, path, sources):
310 """Filter out from the sources list missing tests.
311
312 Sometimes some test source are not built for the target, i.e there
313 is no binary corresponding to the source file. We need to filter
314 these out.
315
316 Args:
317 path: Where the binaries should be.
318 sources: List of tests source path.
319 Returns:
320 A list of test binaries built from the sources.
321 """
322 binaries = []
323 for f in sources:
324 binary = os.path.basename(f)
325 binary = os.path.splitext(binary)[0]
326 full_path = os.path.join(path, binary)
327 if os.path.exists(full_path):
328 binaries.append(binary)
329 return binaries
330
Niko Catania2e990b92009-04-02 16:52:26 -0700331 def _RunNativeTest(self, test_suite):
332 """Run the provided *native* test suite.
333
Nicolas Cataniaff096c12009-05-01 11:55:36 -0700334 The test_suite must contain a build path where the native test
335 files are. Subdirectories are automatically scanned as well.
336
337 Each test's name must have a .cc or .cpp extension and match one
338 of the following patterns:
339 - test_*
340 - *_test.[cc|cpp]
341 - *_unittest.[cc|cpp]
Niko Catania2e990b92009-04-02 16:52:26 -0700342 A successful test must return 0. Any other value will be considered
343 as an error.
344
345 Args:
346 test_suite: TestSuite to run
347 """
348 # find all test files, convert unicode names to ascii, take the basename
349 # and drop the .cc/.cpp extension.
Nicolas Cataniaff096c12009-05-01 11:55:36 -0700350 source_list = []
351 build_path = test_suite.GetBuildPath()
352 os.path.walk(build_path, self._CollectTestSources, source_list)
353 logger.SilentLog("Tests source %s" % source_list)
354
355 # Host tests are under out/host/<os>-<arch>/bin.
356 host_list = self._FilterOutMissing(android_build.GetHostBin(), source_list)
357 logger.SilentLog("Host tests %s" % host_list)
358
359 # Target tests are under $ANDROID_PRODUCT_OUT/system/bin.
360 target_list = self._FilterOutMissing(android_build.GetTargetSystemBin(),
361 source_list)
362 logger.SilentLog("Target tests %s" % target_list)
Niko Catania2e990b92009-04-02 16:52:26 -0700363
Nicolas Catania97b24c42009-04-22 11:08:32 -0700364 # Run on the host
365 logger.Log("\nRunning on host")
Nicolas Cataniaff096c12009-05-01 11:55:36 -0700366 for f in host_list:
Nicolas Catania97b24c42009-04-22 11:08:32 -0700367 if run_command.RunHostCommand(f) != 0:
368 logger.Log("%s... failed" % f)
369 else:
370 if run_command.RunHostCommand(f, valgrind=True) == 0:
371 logger.Log("%s... ok\t\t[valgrind: ok]" % f)
372 else:
373 logger.Log("%s... ok\t\t[valgrind: failed]" % f)
374
375 # Run on the device
376 logger.Log("\nRunning on target")
Nicolas Cataniaff096c12009-05-01 11:55:36 -0700377 for f in target_list:
378 full_path = os.path.join(os.sep, "system", "bin", f)
Niko Catania2e990b92009-04-02 16:52:26 -0700379
Niko Cataniafa14bd52009-04-09 16:50:54 -0700380 # Single quotes are needed to prevent the shell splitting it.
381 status = self._adb.SendShellCommand("'%s >/dev/null 2>&1;echo -n $?'" %
Niko Catania2e990b92009-04-02 16:52:26 -0700382 full_path)
383 logger.Log("%s... %s" % (f, status == "0" and "ok" or "failed"))
384
385 # Cleanup
386 self._adb.SendShellCommand("rm %s" % full_path)
387
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700388 def RunTests(self):
389 """Main entry method - executes the tests according to command line args."""
390 try:
391 run_command.SetAbortOnError()
392 self._ProcessOptions()
393 if self._options.only_list_tests:
394 self._DumpTests()
395 return
396
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700397 if not self._options.skip_build:
398 self._DoBuild()
399
400 for test_suite in self._GetTestsToRun():
Niko Catania2e990b92009-04-02 16:52:26 -0700401 if test_suite.IsNative():
402 self._RunNativeTest(test_suite)
403 else:
404 self._RunTest(test_suite)
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700405 except KeyboardInterrupt:
406 logger.Log("Exiting...")
Brett Chabot8a101cb2009-05-05 12:56:39 -0700407 except errors.AbortError, e:
408 logger.Log(e.msg)
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700409 logger.SilentLog("Exiting due to AbortError...")
410 except errors.WaitForResponseTimedOutError:
411 logger.Log("Timed out waiting for response")
412
413
414def RunTests():
415 runner = TestRunner()
416 runner.RunTests()
417
418if __name__ == "__main__":
419 RunTests()