blob: 495b6a746db2e25f7fb8b9a935e742c7afd917e2 [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
Brett Chabot59b47782009-10-21 17:23:01 -070017"""Command line utility for running Android tests
The Android Open Source Project6ffae012009-03-18 17:39:43 -070018
Brett Chabot59b47782009-10-21 17:23:01 -070019runtest helps automate the instructions for building and running tests
20- It builds the corresponding test package for the code you want to test
21- It pushes the test package to your device or emulator
22- It launches InstrumentationTestRunner (or similar) to run the tests you
23specify.
24
25runtest supports running tests whose attributes have been pre-defined in
26_TEST_FILE_NAME files, (runtest <testname>), or by specifying the file
27system path to the test to run (runtest --path <path>).
28
29Do runtest --help to see full list of options.
The Android Open Source Project6ffae012009-03-18 17:39:43 -070030"""
31
32# Python imports
33import glob
34import optparse
35import os
36from sets import Set
37import sys
38
39# local imports
40import adb_interface
41import android_build
42import coverage
43import errors
44import logger
45import run_command
Brett Chabot764d3fa2009-06-25 17:57:31 -070046from test_defs import test_defs
Brett Chabot59b47782009-10-21 17:23:01 -070047from test_defs import test_walker
The Android Open Source Project6ffae012009-03-18 17:39:43 -070048
49
50class TestRunner(object):
51 """Command line utility class for running pre-defined Android test(s)."""
52
Brett Chabotf61f43e2009-04-02 11:52:48 -070053 _TEST_FILE_NAME = "test_defs.xml"
54
The Android Open Source Project6ffae012009-03-18 17:39:43 -070055 # file path to android core platform tests, relative to android build root
56 # TODO move these test data files to another directory
Nicolas Catania97b24c42009-04-22 11:08:32 -070057 _CORE_TEST_PATH = os.path.join("development", "testrunner",
Brett Chabotf61f43e2009-04-02 11:52:48 -070058 _TEST_FILE_NAME)
The Android Open Source Project6ffae012009-03-18 17:39:43 -070059
60 # vendor glob file path patterns to tests, relative to android
61 # build root
62 _VENDOR_TEST_PATH = os.path.join("vendor", "*", "tests", "testinfo",
Brett Chabotf61f43e2009-04-02 11:52:48 -070063 _TEST_FILE_NAME)
The Android Open Source Project6ffae012009-03-18 17:39:43 -070064
65 _RUNTEST_USAGE = (
66 "usage: runtest.py [options] short-test-name[s]\n\n"
67 "The runtest script works in two ways. You can query it "
68 "for a list of tests, or you can launch one or more tests.")
69
Brett Chabot2477b382009-09-23 18:05:28 -070070 # default value for make -jX
Brett Chabot59b47782009-10-21 17:23:01 -070071 _DEFAULT_JOBS = 4
Brett Chabot2477b382009-09-23 18:05:28 -070072
Brett Chabot72731f32009-03-31 11:14:05 -070073 def __init__(self):
74 # disable logging of timestamp
Niko Catania2e990b92009-04-02 16:52:26 -070075 self._root_path = android_build.GetTop()
Nicolas Catania97b24c42009-04-22 11:08:32 -070076 logger.SetTimestampLogging(False)
Brett Chabot3ae5f8a2009-06-28 12:00:47 -070077 self._adb = None
78 self._known_tests = None
79 self._options = None
80 self._test_args = None
Brett Chabot59b47782009-10-21 17:23:01 -070081 self._tests_to_run = None
Brett Chabot72731f32009-03-31 11:14:05 -070082
The Android Open Source Project6ffae012009-03-18 17:39:43 -070083 def _ProcessOptions(self):
84 """Processes command-line options."""
85 # TODO error messages on once-only or mutually-exclusive options.
86 user_test_default = os.path.join(os.environ.get("HOME"), ".android",
Brett Chabotf61f43e2009-04-02 11:52:48 -070087 self._TEST_FILE_NAME)
The Android Open Source Project6ffae012009-03-18 17:39:43 -070088
89 parser = optparse.OptionParser(usage=self._RUNTEST_USAGE)
90
91 parser.add_option("-l", "--list-tests", dest="only_list_tests",
92 default=False, action="store_true",
93 help="To view the list of tests")
94 parser.add_option("-b", "--skip-build", dest="skip_build", default=False,
95 action="store_true", help="Skip build - just launch")
Brett Chabot2477b382009-09-23 18:05:28 -070096 parser.add_option("-j", "--jobs", dest="make_jobs",
97 metavar="X", default=self._DEFAULT_JOBS,
98 help="Number of make jobs to use when building")
The Android Open Source Project6ffae012009-03-18 17:39:43 -070099 parser.add_option("-n", "--skip_execute", dest="preview", default=False,
100 action="store_true",
101 help="Do not execute, just preview commands")
102 parser.add_option("-r", "--raw-mode", dest="raw_mode", default=False,
103 action="store_true",
104 help="Raw mode (for output to other tools)")
105 parser.add_option("-a", "--suite-assign", dest="suite_assign_mode",
106 default=False, action="store_true",
107 help="Suite assignment (for details & usage see "
108 "InstrumentationTestRunner)")
109 parser.add_option("-v", "--verbose", dest="verbose", default=False,
110 action="store_true",
111 help="Increase verbosity of %s" % sys.argv[0])
112 parser.add_option("-w", "--wait-for-debugger", dest="wait_for_debugger",
113 default=False, action="store_true",
114 help="Wait for debugger before launching tests")
115 parser.add_option("-c", "--test-class", dest="test_class",
116 help="Restrict test to a specific class")
117 parser.add_option("-m", "--test-method", dest="test_method",
118 help="Restrict test to a specific method")
Brett Chabot8a101cb2009-05-05 12:56:39 -0700119 parser.add_option("-p", "--test-package", dest="test_package",
120 help="Restrict test to a specific java package")
121 parser.add_option("-z", "--size", dest="test_size",
122 help="Restrict test to a specific test size")
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700123 parser.add_option("-u", "--user-tests-file", dest="user_tests_file",
124 metavar="FILE", default=user_test_default,
125 help="Alternate source of user test definitions")
126 parser.add_option("-o", "--coverage", dest="coverage",
127 default=False, action="store_true",
128 help="Generate code coverage metrics for test(s)")
Brett Chabot59b47782009-10-21 17:23:01 -0700129 parser.add_option("-x", "--path", dest="test_path",
130 help="Run test(s) at given file system path")
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700131 parser.add_option("-t", "--all-tests", dest="all_tests",
132 default=False, action="store_true",
133 help="Run all defined tests")
134 parser.add_option("--continuous", dest="continuous_tests",
135 default=False, action="store_true",
136 help="Run all tests defined as part of the continuous "
137 "test set")
Wei-Ta Chen97752d42009-05-21 16:24:04 -0700138 parser.add_option("--timeout", dest="timeout",
139 default=300, help="Set a timeout limit (in sec) for "
140 "running native tests on a device (default: 300 secs)")
Brett Chabot4a5d9f12010-02-18 20:01:11 -0800141 parser.add_option("--suite", dest="suite",
Brett Chabot49b77112009-06-02 11:46:04 -0700142 help="Run all tests defined as part of the "
Brett Chabot4a5d9f12010-02-18 20:01:11 -0800143 "the given test suite")
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700144 group = optparse.OptionGroup(
145 parser, "Targets", "Use these options to direct tests to a specific "
146 "Android target")
147 group.add_option("-e", "--emulator", dest="emulator", default=False,
148 action="store_true", help="use emulator")
149 group.add_option("-d", "--device", dest="device", default=False,
150 action="store_true", help="use device")
151 group.add_option("-s", "--serial", dest="serial",
152 help="use specific serial")
153 parser.add_option_group(group)
154
155 self._options, self._test_args = parser.parse_args()
156
Brett Chabot49b77112009-06-02 11:46:04 -0700157 if (not self._options.only_list_tests
158 and not self._options.all_tests
159 and not self._options.continuous_tests
Brett Chabot4a5d9f12010-02-18 20:01:11 -0800160 and not self._options.suite
Brett Chabot59b47782009-10-21 17:23:01 -0700161 and not self._options.test_path
Brett Chabot49b77112009-06-02 11:46:04 -0700162 and len(self._test_args) < 1):
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700163 parser.print_help()
164 logger.SilentLog("at least one test name must be specified")
165 raise errors.AbortError
166
167 self._adb = adb_interface.AdbInterface()
168 if self._options.emulator:
169 self._adb.SetEmulatorTarget()
170 elif self._options.device:
171 self._adb.SetDeviceTarget()
172 elif self._options.serial is not None:
173 self._adb.SetTargetSerial(self._options.serial)
174
175 if self._options.verbose:
176 logger.SetVerbose(True)
177
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700178 self._known_tests = self._ReadTests()
179
Brett Chabot764d3fa2009-06-25 17:57:31 -0700180 self._options.host_lib_path = android_build.GetHostLibraryPath()
181 self._options.test_data_path = android_build.GetTestAppPath()
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700182
183 def _ReadTests(self):
184 """Parses the set of test definition data.
185
186 Returns:
187 A TestDefinitions object that contains the set of parsed tests.
188 Raises:
189 AbortError: If a fatal error occurred when parsing the tests.
190 """
191 core_test_path = os.path.join(self._root_path, self._CORE_TEST_PATH)
192 try:
193 known_tests = test_defs.TestDefinitions()
194 known_tests.Parse(core_test_path)
Brett Chabot2d85c0e2009-03-31 15:19:13 -0700195 # read all <android root>/vendor/*/tests/testinfo/test_defs.xml paths
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700196 vendor_tests_pattern = os.path.join(self._root_path,
197 self._VENDOR_TEST_PATH)
198 test_file_paths = glob.glob(vendor_tests_pattern)
199 for test_file_path in test_file_paths:
200 known_tests.Parse(test_file_path)
201 if os.path.isfile(self._options.user_tests_file):
202 known_tests.Parse(self._options.user_tests_file)
203 return known_tests
204 except errors.ParseError:
205 raise errors.AbortError
206
207 def _DumpTests(self):
208 """Prints out set of defined tests."""
Brett Chabotbe659c02009-09-21 17:48:26 -0700209 print "The following tests are currently defined:\n"
210 print "%-25s %-40s %s" % ("name", "build path", "description")
211 print "-" * 80
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700212 for test in self._known_tests:
Brett Chabotbe659c02009-09-21 17:48:26 -0700213 print "%-25s %-40s %s" % (test.GetName(), test.GetBuildPath(),
214 test.GetDescription())
215 print "\nSee %s for more information" % self._TEST_FILE_NAME
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700216
217 def _DoBuild(self):
218 logger.SilentLog("Building tests...")
219 target_set = Set()
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700220 extra_args_set = Set()
Brett Chabot2477b382009-09-23 18:05:28 -0700221 tests = self._GetTestsToRun()
222 for test_suite in tests:
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700223 self._AddBuildTarget(test_suite, target_set, extra_args_set)
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700224
225 if target_set:
226 if self._options.coverage:
Brett Chabot764d3fa2009-06-25 17:57:31 -0700227 coverage.EnableCoverageBuild()
Brett Chabot2477b382009-09-23 18:05:28 -0700228
229 # hack to build cts dependencies
230 # TODO: remove this when build dependency support added to runtest or
231 # cts dependencies are removed
232 if self._IsCtsTests(tests):
233 # need to use make since these fail building with ONE_SHOT_MAKEFILE
Brett Chabot59b47782009-10-21 17:23:01 -0700234 cmd = ('make -j%s CtsTestStubs android.core.tests.runner' %
235 self._options.make_jobs)
Brett Chabot2477b382009-09-23 18:05:28 -0700236 logger.Log(cmd)
237 if not self._options.preview:
Brett Chabote00595b2009-10-21 20:01:31 -0700238 old_dir = os.getcwd()
239 os.chdir(self._root_path)
Brett Chabot2477b382009-09-23 18:05:28 -0700240 run_command.RunCommand(cmd, return_output=False)
Brett Chabote00595b2009-10-21 20:01:31 -0700241 os.chdir(old_dir)
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700242 target_build_string = " ".join(list(target_set))
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700243 extra_args_string = " ".join(list(extra_args_set))
Brett Chabot764d3fa2009-06-25 17:57:31 -0700244 # mmm cannot be used from python, so perform a similar operation using
Brett Chabot2b6643b2009-04-07 18:35:27 -0700245 # ONE_SHOT_MAKEFILE
Brett Chabot2477b382009-09-23 18:05:28 -0700246 cmd = 'ONE_SHOT_MAKEFILE="%s" make -j%s -C "%s" files %s' % (
247 target_build_string, self._options.make_jobs, self._root_path,
248 extra_args_string)
Brett Chabot764d3fa2009-06-25 17:57:31 -0700249 logger.Log(cmd)
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700250
Brett Chabot72731f32009-03-31 11:14:05 -0700251 if self._options.preview:
252 # in preview mode, just display to the user what command would have been
253 # run
254 logger.Log("adb sync")
255 else:
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700256 run_command.RunCommand(cmd, return_output=False)
257 logger.Log("Syncing to device...")
258 self._adb.Sync()
259
Niko Cataniaa6dc2ab2009-04-03 14:12:46 -0700260 def _AddBuildTarget(self, test_suite, target_set, extra_args_set):
261 build_dir = test_suite.GetBuildPath()
Brett Chabot2b6643b2009-04-07 18:35:27 -0700262 if self._AddBuildTargetPath(build_dir, target_set):
Brett Chabot764d3fa2009-06-25 17:57:31 -0700263 extra_args_set.add(test_suite.GetExtraBuildArgs())
264 for path in test_suite.GetBuildDependencies(self._options):
265 self._AddBuildTargetPath(path, target_set)
Brett Chabot2b6643b2009-04-07 18:35:27 -0700266
267 def _AddBuildTargetPath(self, build_dir, target_set):
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700268 if build_dir is not None:
269 build_file_path = os.path.join(build_dir, "Android.mk")
270 if os.path.isfile(os.path.join(self._root_path, build_file_path)):
271 target_set.add(build_file_path)
Brett Chabot2b6643b2009-04-07 18:35:27 -0700272 return True
Brett Chabote00595b2009-10-21 20:01:31 -0700273 else:
274 logger.Log("%s has no Android.mk, skipping" % build_dir)
Brett Chabot2b6643b2009-04-07 18:35:27 -0700275 return False
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700276
277 def _GetTestsToRun(self):
278 """Get a list of TestSuite objects to run, based on command line args."""
Brett Chabot59b47782009-10-21 17:23:01 -0700279 if self._tests_to_run:
280 return self._tests_to_run
281
282 self._tests_to_run = []
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700283 if self._options.all_tests:
Brett Chabot59b47782009-10-21 17:23:01 -0700284 self._tests_to_run = self._known_tests.GetTests()
Brett Chabot49b77112009-06-02 11:46:04 -0700285 elif self._options.continuous_tests:
Brett Chabot59b47782009-10-21 17:23:01 -0700286 self._tests_to_run = self._known_tests.GetContinuousTests()
Brett Chabot4a5d9f12010-02-18 20:01:11 -0800287 elif self._options.suite:
288 self._tests_to_run = \
289 self._known_tests.GetTestsInSuite(self._options.suite)
Brett Chabot59b47782009-10-21 17:23:01 -0700290 elif self._options.test_path:
291 walker = test_walker.TestWalker()
292 self._tests_to_run = walker.FindTests(self._options.test_path)
293
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700294 for name in self._test_args:
295 test = self._known_tests.GetTest(name)
296 if test is None:
297 logger.Log("Error: Could not find test %s" % name)
298 self._DumpTests()
299 raise errors.AbortError
Brett Chabot59b47782009-10-21 17:23:01 -0700300 self._tests_to_run.append(test)
301 return self._tests_to_run
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700302
Brett Chabot2477b382009-09-23 18:05:28 -0700303 def _IsCtsTests(self, test_list):
304 """Check if any cts tests are included in given list of tests to run."""
305 for test in test_list:
Brett Chabot4a5d9f12010-02-18 20:01:11 -0800306 if test.GetSuite() == 'cts':
Brett Chabot2477b382009-09-23 18:05:28 -0700307 return True
308 return False
309
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700310 def RunTests(self):
311 """Main entry method - executes the tests according to command line args."""
312 try:
313 run_command.SetAbortOnError()
314 self._ProcessOptions()
315 if self._options.only_list_tests:
316 self._DumpTests()
317 return
318
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700319 if not self._options.skip_build:
320 self._DoBuild()
321
322 for test_suite in self._GetTestsToRun():
Brett Chabot920e9fe2010-01-21 17:30:47 -0800323 try:
324 test_suite.Run(self._options, self._adb)
325 except errors.WaitForResponseTimedOutError:
326 logger.Log("Timed out waiting for response")
Brett Chabot764d3fa2009-06-25 17:57:31 -0700327
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700328 except KeyboardInterrupt:
329 logger.Log("Exiting...")
Brett Chabot3ae5f8a2009-06-28 12:00:47 -0700330 except errors.AbortError, error:
331 logger.Log(error.msg)
The Android Open Source Project6ffae012009-03-18 17:39:43 -0700332 logger.SilentLog("Exiting due to AbortError...")
333 except errors.WaitForResponseTimedOutError:
334 logger.Log("Timed out waiting for response")
335
336
337def RunTests():
338 runner = TestRunner()
339 runner.RunTests()
340
341if __name__ == "__main__":
342 RunTests()