1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Class for running instrumentation tests on a single device."""
14 sys.path.append(os.path.join(sys.path[0],
15 os.pardir, os.pardir, 'build', 'util', 'lib',
17 import perf_tests_results_helper
19 from pylib import android_commands
20 from pylib import constants
21 from pylib import flag_changer
22 from pylib import valgrind_tools
23 from pylib.base import base_test_result
24 from pylib.base import base_test_runner
25 from pylib.instrumentation import json_perf_parser
30 _PERF_TEST_ANNOTATION = 'PerfTest'
33 def _GetDataFilesForTestSuite(suite_basename):
34 """Returns a list of data files/dirs needed by the test suite.
37 suite_basename: The test suite basename for which to return file paths.
40 A list of test file and directory paths.
43 if suite_basename in ['ChromeTest', 'ContentShellTest']:
45 'net/data/ssl/certificates/',
50 class TestRunner(base_test_runner.BaseTestRunner):
51 """Responsible for running a series of tests connected to a single device."""
53 _DEVICE_DATA_DIR = 'chrome/test/data'
54 _DEVICE_COVERAGE_DIR = 'chrome/test/coverage'
55 _HOSTMACHINE_PERF_OUTPUT_FILE = '/tmp/chrome-profile'
56 _DEVICE_PERF_OUTPUT_SEARCH_PREFIX = (constants.DEVICE_PERF_OUTPUT_DIR +
58 _DEVICE_HAS_TEST_FILES = {}
60 def __init__(self, test_options, device, shard_index, test_pkg,
61 ports_to_forward, additional_flags=None):
62 """Create a new TestRunner.
65 test_options: An InstrumentationOptions object.
66 device: Attached android device.
67 shard_index: Shard index.
68 test_pkg: A TestPackage object.
69 ports_to_forward: A list of port numbers for which to set up forwarders.
70 Can be optionally requested by a test case.
71 additional_flags: A list of additional flags to add to the command line.
73 super(TestRunner, self).__init__(device, test_options.tool,
74 test_options.push_deps,
75 test_options.cleanup_test_files)
76 self._lighttp_port = constants.LIGHTTPD_RANDOM_PORT_FIRST + shard_index
78 self.options = test_options
79 self.test_pkg = test_pkg
80 self.ports_to_forward = ports_to_forward
81 self.coverage_dir = test_options.coverage_dir
82 # Use the correct command line file for the package under test.
83 cmdline_file = [a.cmdline_file for a in constants.PACKAGE_INFO.itervalues()
84 if a.test_package == self.test_pkg.GetPackageName()]
85 assert len(cmdline_file) < 2, 'Multiple packages have the same test package'
86 if len(cmdline_file) and cmdline_file[0]:
87 self.flags = flag_changer.FlagChanger(self.adb, cmdline_file[0])
89 self.flags = flag_changer.FlagChanger(self.adb)
91 self.flags.AddFlags(additional_flags)
94 def InstallTestPackage(self):
95 self.test_pkg.Install(self.adb)
98 def PushDataDeps(self):
99 # TODO(frankf): Implement a general approach for copying/installing
100 # once across test runners.
101 if TestRunner._DEVICE_HAS_TEST_FILES.get(self.device, False):
102 logging.warning('Already copied test files to device %s, skipping.',
106 test_data = _GetDataFilesForTestSuite(self.test_pkg.GetApkName())
108 # Make sure SD card is ready.
109 self.adb.WaitForSdCardReady(20)
111 self.adb.PushIfNeeded(
112 os.path.join(constants.DIR_SOURCE_ROOT, p),
113 os.path.join(self.adb.GetExternalStorage(), p))
115 # TODO(frankf): Specify test data in this file as opposed to passing
117 for dest_host_pair in self.options.test_data:
118 dst_src = dest_host_pair.split(':',1)
119 dst_layer = dst_src[0]
120 host_src = dst_src[1]
121 host_test_files_path = '%s/%s' % (constants.DIR_SOURCE_ROOT, host_src)
122 if os.path.exists(host_test_files_path):
123 self.adb.PushIfNeeded(host_test_files_path, '%s/%s/%s' % (
124 self.adb.GetExternalStorage(), TestRunner._DEVICE_DATA_DIR,
126 self.tool.CopyFiles()
127 TestRunner._DEVICE_HAS_TEST_FILES[self.device] = True
129 def _GetInstrumentationArgs(self):
131 if self.options.wait_for_debugger:
132 ret['debug'] = 'true'
133 if self.coverage_dir:
134 ret['coverage'] = 'true'
135 ret['coverageFile'] = self.coverage_device_file
139 def _TakeScreenshot(self, test):
140 """Takes a screenshot from the device."""
141 screenshot_name = os.path.join(constants.SCREENSHOTS_DIR, '%s.png' % test)
142 logging.info('Taking screenshot named %s', screenshot_name)
143 self.adb.TakeScreenshot(screenshot_name)
146 """Sets up the test harness and device before all tests are run."""
147 super(TestRunner, self).SetUp()
148 if not self.adb.IsRootEnabled():
149 logging.warning('Unable to enable java asserts for %s, non rooted device',
152 if self.adb.SetJavaAssertsEnabled(True):
153 self.adb.Reboot(full_reboot=False)
155 # We give different default value to launch HTTP server based on shard index
156 # because it may have race condition when multiple processes are trying to
157 # launch lighttpd with same port at same time.
158 http_server_ports = self.LaunchTestHttpServer(
159 os.path.join(constants.DIR_SOURCE_ROOT), self._lighttp_port)
160 if self.ports_to_forward:
161 self._ForwardPorts([(port, port) for port in self.ports_to_forward])
162 self.flags.AddFlags(['--disable-fre', '--enable-test-intents'])
165 """Cleans up the test harness and saves outstanding data from test run."""
167 if self.ports_to_forward:
168 self._UnmapPorts([(port, port) for port in self.ports_to_forward])
169 super(TestRunner, self).TearDown()
171 def TestSetup(self, test):
172 """Sets up the test harness for running a particular test.
175 test: The name of the test that will be run.
177 self.SetupPerfMonitoringIfNeeded(test)
178 self._SetupIndividualTestTimeoutScale(test)
179 self.tool.SetupEnvironment()
181 # Make sure the forwarder is still running.
182 self._RestartHttpServerForwarderIfNecessary()
184 if self.coverage_dir:
185 coverage_basename = '%s.ec' % test
186 self.coverage_device_file = '%s/%s/%s' % (self.adb.GetExternalStorage(),
187 TestRunner._DEVICE_COVERAGE_DIR,
189 self.coverage_host_file = os.path.join(
190 self.coverage_dir, coverage_basename)
192 def _IsPerfTest(self, test):
193 """Determines whether a test is a performance test.
196 test: The name of the test to be checked.
199 Whether the test is annotated as a performance test.
201 return _PERF_TEST_ANNOTATION in self.test_pkg.GetTestAnnotations(test)
203 def SetupPerfMonitoringIfNeeded(self, test):
204 """Sets up performance monitoring if the specified test requires it.
207 test: The name of the test to be run.
209 if not self._IsPerfTest(test):
211 self.adb.Adb().SendCommand('shell rm ' +
212 TestRunner._DEVICE_PERF_OUTPUT_SEARCH_PREFIX)
213 self.adb.StartMonitoringLogcat()
215 def TestTeardown(self, test, raw_result):
216 """Cleans up the test harness after running a particular test.
218 Depending on the options of this TestRunner this might handle performance
219 tracking. This method will only be called if the test passed.
222 test: The name of the test that was just run.
223 raw_result: result for this test.
226 self.tool.CleanUpEnvironment()
228 # The logic below relies on the test passing.
229 if not raw_result or raw_result.GetStatusCode():
232 self.TearDownPerfMonitoring(test)
234 if self.coverage_dir:
235 self.adb.Adb().Pull(self.coverage_device_file, self.coverage_host_file)
236 self.adb.RunShellCommand('rm -f %s' % self.coverage_device_file)
238 def TearDownPerfMonitoring(self, test):
239 """Cleans up performance monitoring if the specified test required it.
242 test: The name of the test that was just run.
244 Exception: if there's anything wrong with the perf data.
246 if not self._IsPerfTest(test):
248 raw_test_name = test.split('#')[1]
250 # Wait and grab annotation data so we can figure out which traces to parse
251 regex = self.adb.WaitForLogMatch(re.compile('\*\*PERFANNOTATION\(' +
255 # If the test is set to run on a specific device type only (IE: only
256 # tablet or phone) and it is being run on the wrong device, the test
257 # just quits and does not do anything. The java test harness will still
258 # print the appropriate annotation for us, but will add --NORUN-- for
259 # us so we know to ignore the results.
260 # The --NORUN-- tag is managed by MainActivityTestBase.java
261 if regex.group(1) != '--NORUN--':
263 # Obtain the relevant perf data. The data is dumped to a
264 # JSON formatted file.
265 json_string = self.adb.GetProtectedFileContents(
266 '/data/data/com.google.android.apps.chrome/files/PerfTestData.txt')
269 json_string = '\n'.join(json_string)
271 raise Exception('Perf file does not exist or is empty')
273 if self.options.save_perf_json:
274 json_local_file = '/tmp/chromium-android-perf-json-' + raw_test_name
275 with open(json_local_file, 'w') as f:
277 logging.info('Saving Perf UI JSON from test ' +
278 test + ' to ' + json_local_file)
280 raw_perf_data = regex.group(1).split(';')
282 for raw_perf_set in raw_perf_data:
284 perf_set = raw_perf_set.split(',')
285 if len(perf_set) != 3:
286 raise Exception('Unexpected number of tokens in perf annotation '
287 'string: ' + raw_perf_set)
289 # Process the performance data
290 result = json_perf_parser.GetAverageRunInfoFromJSONString(json_string,
292 perf_tests_results_helper.PrintPerfResult(perf_set[1], perf_set[2],
296 def _SetupIndividualTestTimeoutScale(self, test):
297 timeout_scale = self._GetIndividualTestTimeoutScale(test)
298 valgrind_tools.SetChromeTimeoutScale(self.adb, timeout_scale)
300 def _GetIndividualTestTimeoutScale(self, test):
301 """Returns the timeout scale for the given |test|."""
302 annotations = self.test_pkg.GetTestAnnotations(test)
304 if 'TimeoutScale' in annotations:
305 for annotation in annotations:
306 scale_match = re.match('TimeoutScale:([0-9]+)', annotation)
308 timeout_scale = int(scale_match.group(1))
309 if self.options.wait_for_debugger:
313 def _GetIndividualTestTimeoutSecs(self, test):
314 """Returns the timeout in seconds for the given |test|."""
315 annotations = self.test_pkg.GetTestAnnotations(test)
316 if 'Manual' in annotations:
318 if 'External' in annotations:
320 if 'LargeTest' in annotations or _PERF_TEST_ANNOTATION in annotations:
322 if 'MediumTest' in annotations:
326 def _RunTest(self, test, timeout):
328 return self.adb.RunInstrumentationTest(
329 test, self.test_pkg.GetPackageName(),
330 self._GetInstrumentationArgs(), timeout)
331 except android_commands.errors.WaitForResponseTimedOutError:
332 logging.info('Ran the test with timeout of %ds.' % timeout)
336 def RunTest(self, test):
339 results = base_test_result.TestRunResults()
340 timeout=(self._GetIndividualTestTimeoutSecs(test) *
341 self._GetIndividualTestTimeoutScale(test) *
342 self.tool.GetTimeoutScale())
345 start_date_ms = int(time.time()) * 1000
346 raw_result = self._RunTest(test, timeout)
347 duration_ms = int(time.time()) * 1000 - start_date_ms
348 status_code = raw_result.GetStatusCode()
350 log = raw_result.GetFailureReason()
352 log = 'No information.'
353 if (self.options.screenshot_failures or
354 log.find('INJECT_EVENTS perm') >= 0):
355 self._TakeScreenshot(test)
356 result = test_result.InstrumentationTestResult(
357 test, base_test_result.ResultType.FAIL, start_date_ms, duration_ms,
360 result = test_result.InstrumentationTestResult(
361 test, base_test_result.ResultType.PASS, start_date_ms, duration_ms)
362 results.AddResult(result)
363 # Catch exceptions thrown by StartInstrumentation().
364 # See ../../third_party/android/testrunner/adb_interface.py
365 except (android_commands.errors.WaitForResponseTimedOutError,
366 android_commands.errors.DeviceUnresponsiveError,
367 android_commands.errors.InstrumentationError), e:
369 duration_ms = int(time.time()) * 1000 - start_date_ms
371 start_date_ms = int(time.time()) * 1000
375 message = 'No information.'
376 results.AddResult(test_result.InstrumentationTestResult(
377 test, base_test_result.ResultType.CRASH, start_date_ms, duration_ms,
380 self.TestTeardown(test, raw_result)
381 return (results, None if results.DidRunPass() else test)