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."""
13 from pylib import android_commands
14 from pylib import constants
15 from pylib import flag_changer
16 from pylib import valgrind_tools
17 from pylib.base import base_test_result
18 from pylib.base import base_test_runner
19 from pylib.device import adb_wrapper
20 from pylib.instrumentation import json_perf_parser
21 from pylib.instrumentation import test_result
23 sys.path.append(os.path.join(sys.path[0],
24 os.pardir, os.pardir, 'build', 'util', 'lib',
26 import perf_tests_results_helper # pylint: disable=F0401
29 _PERF_TEST_ANNOTATION = 'PerfTest'
32 def _GetDataFilesForTestSuite(suite_basename):
33 """Returns a list of data files/dirs needed by the test suite.
36 suite_basename: The test suite basename for which to return file paths.
39 A list of test file and directory paths.
42 if suite_basename in ['ChromeTest', 'ContentShellTest']:
44 'net/data/ssl/certificates/',
49 class TestRunner(base_test_runner.BaseTestRunner):
50 """Responsible for running a series of tests connected to a single device."""
52 _DEVICE_DATA_DIR = 'chrome/test/data'
53 _DEVICE_COVERAGE_DIR = 'chrome/test/coverage'
54 _HOSTMACHINE_PERF_OUTPUT_FILE = '/tmp/chrome-profile'
55 _DEVICE_PERF_OUTPUT_SEARCH_PREFIX = (constants.DEVICE_PERF_OUTPUT_DIR +
57 _DEVICE_HAS_TEST_FILES = {}
59 def __init__(self, test_options, device, shard_index, test_pkg,
60 additional_flags=None):
61 """Create a new TestRunner.
64 test_options: An InstrumentationOptions object.
65 device: Attached android device.
66 shard_index: Shard index.
67 test_pkg: A TestPackage object.
68 additional_flags: A list of additional flags to add to the command line.
70 super(TestRunner, self).__init__(device, test_options.tool,
71 test_options.push_deps,
72 test_options.cleanup_test_files)
73 self._lighttp_port = constants.LIGHTTPD_RANDOM_PORT_FIRST + shard_index
75 self.coverage_device_file = None
76 self.coverage_dir = test_options.coverage_dir
77 self.coverage_host_file = None
78 self.options = test_options
79 self.test_pkg = test_pkg
80 # Use the correct command line file for the package under test.
81 cmdline_file = [a.cmdline_file for a in constants.PACKAGE_INFO.itervalues()
82 if a.test_package == self.test_pkg.GetPackageName()]
83 assert len(cmdline_file) < 2, 'Multiple packages have the same test package'
84 if len(cmdline_file) and cmdline_file[0]:
85 self.flags = flag_changer.FlagChanger(self.device, cmdline_file[0])
87 self.flags.AddFlags(additional_flags)
92 def InstallTestPackage(self):
93 self.test_pkg.Install(self.device)
96 def PushDataDeps(self):
97 # TODO(frankf): Implement a general approach for copying/installing
98 # once across test runners.
99 if TestRunner._DEVICE_HAS_TEST_FILES.get(self.device, False):
100 logging.warning('Already copied test files to device %s, skipping.',
101 self.device.old_interface.GetDevice())
104 test_data = _GetDataFilesForTestSuite(self.test_pkg.GetApkName())
106 # Make sure SD card is ready.
107 self.device.old_interface.WaitForSdCardReady(20)
109 self.device.old_interface.PushIfNeeded(
110 os.path.join(constants.DIR_SOURCE_ROOT, p),
111 os.path.join(self.device.old_interface.GetExternalStorage(), p))
113 # TODO(frankf): Specify test data in this file as opposed to passing
115 for dest_host_pair in self.options.test_data:
116 dst_src = dest_host_pair.split(':', 1)
117 dst_layer = dst_src[0]
118 host_src = dst_src[1]
119 host_test_files_path = '%s/%s' % (constants.DIR_SOURCE_ROOT, host_src)
120 if os.path.exists(host_test_files_path):
121 self.device.old_interface.PushIfNeeded(
122 host_test_files_path,
124 self.device.old_interface.GetExternalStorage(),
125 TestRunner._DEVICE_DATA_DIR,
127 self.tool.CopyFiles()
128 TestRunner._DEVICE_HAS_TEST_FILES[
129 self.device.old_interface.GetDevice()] = True
131 def _GetInstrumentationArgs(self):
133 if self.options.wait_for_debugger:
134 ret['debug'] = 'true'
135 if self.coverage_dir:
136 ret['coverage'] = 'true'
137 ret['coverageFile'] = self.coverage_device_file
141 def _TakeScreenshot(self, test):
142 """Takes a screenshot from the device."""
143 screenshot_name = os.path.join(constants.SCREENSHOTS_DIR, '%s.png' % test)
144 logging.info('Taking screenshot named %s', screenshot_name)
145 self.device.old_interface.TakeScreenshot(screenshot_name)
148 """Sets up the test harness and device before all tests are run."""
149 super(TestRunner, self).SetUp()
150 if not self.device.old_interface.IsRootEnabled():
151 logging.warning('Unable to enable java asserts for %s, non rooted device',
154 if self.device.old_interface.SetJavaAssertsEnabled(True):
155 self.device.old_interface.Reboot(full_reboot=False)
157 # We give different default value to launch HTTP server based on shard index
158 # because it may have race condition when multiple processes are trying to
159 # launch lighttpd with same port at same time.
160 self.LaunchTestHttpServer(
161 os.path.join(constants.DIR_SOURCE_ROOT), self._lighttp_port)
163 self.flags.AddFlags(['--disable-fre', '--enable-test-intents'])
166 """Cleans up the test harness and saves outstanding data from test run."""
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' % (
187 self.device.old_interface.GetExternalStorage(),
188 TestRunner._DEVICE_COVERAGE_DIR, coverage_basename)
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.device.old_interface.Adb().SendCommand(
212 'shell rm ' + TestRunner._DEVICE_PERF_OUTPUT_SEARCH_PREFIX)
213 self.device.old_interface.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.device.old_interface.Adb().Pull(
236 self.coverage_device_file, self.coverage_host_file)
237 self.device.old_interface.RunShellCommand(
238 'rm -f %s' % self.coverage_device_file)
240 def TearDownPerfMonitoring(self, test):
241 """Cleans up performance monitoring if the specified test required it.
244 test: The name of the test that was just run.
246 Exception: if there's anything wrong with the perf data.
248 if not self._IsPerfTest(test):
250 raw_test_name = test.split('#')[1]
252 # Wait and grab annotation data so we can figure out which traces to parse
253 regex = self.device.old_interface.WaitForLogMatch(
254 re.compile('\*\*PERFANNOTATION\(' + raw_test_name + '\)\:(.*)'), None)
256 # If the test is set to run on a specific device type only (IE: only
257 # tablet or phone) and it is being run on the wrong device, the test
258 # just quits and does not do anything. The java test harness will still
259 # print the appropriate annotation for us, but will add --NORUN-- for
260 # us so we know to ignore the results.
261 # The --NORUN-- tag is managed by MainActivityTestBase.java
262 if regex.group(1) != '--NORUN--':
264 # Obtain the relevant perf data. The data is dumped to a
265 # JSON formatted file.
266 json_string = self.device.old_interface.GetProtectedFileContents(
267 '/data/data/com.google.android.apps.chrome/files/PerfTestData.txt')
270 json_string = '\n'.join(json_string)
272 raise Exception('Perf file does not exist or is empty')
274 if self.options.save_perf_json:
275 json_local_file = '/tmp/chromium-android-perf-json-' + raw_test_name
276 with open(json_local_file, 'w') as f:
278 logging.info('Saving Perf UI JSON from test ' +
279 test + ' to ' + json_local_file)
281 raw_perf_data = regex.group(1).split(';')
283 for raw_perf_set in raw_perf_data:
285 perf_set = raw_perf_set.split(',')
286 if len(perf_set) != 3:
287 raise Exception('Unexpected number of tokens in perf annotation '
288 'string: ' + raw_perf_set)
290 # Process the performance data
291 result = json_perf_parser.GetAverageRunInfoFromJSONString(json_string,
293 perf_tests_results_helper.PrintPerfResult(perf_set[1], perf_set[2],
297 def _SetupIndividualTestTimeoutScale(self, test):
298 timeout_scale = self._GetIndividualTestTimeoutScale(test)
299 valgrind_tools.SetChromeTimeoutScale(self.device, timeout_scale)
301 def _GetIndividualTestTimeoutScale(self, test):
302 """Returns the timeout scale for the given |test|."""
303 annotations = self.test_pkg.GetTestAnnotations(test)
305 if 'TimeoutScale' in annotations:
306 for annotation in annotations:
307 scale_match = re.match('TimeoutScale:([0-9]+)', annotation)
309 timeout_scale = int(scale_match.group(1))
310 if self.options.wait_for_debugger:
314 def _GetIndividualTestTimeoutSecs(self, test):
315 """Returns the timeout in seconds for the given |test|."""
316 annotations = self.test_pkg.GetTestAnnotations(test)
317 if 'Manual' in annotations:
319 if 'External' in annotations:
321 if 'LargeTest' in annotations or _PERF_TEST_ANNOTATION in annotations:
323 if 'MediumTest' in annotations:
327 def _RunTest(self, test, timeout):
329 return self.device.old_interface.RunInstrumentationTest(
330 test, self.test_pkg.GetPackageName(),
331 self._GetInstrumentationArgs(), timeout)
332 except (adb_wrapper.CommandTimeoutError,
333 # TODO(jbudorick) Remove this once the underlying implementations
334 # for the above are switched or wrapped.
335 android_commands.errors.WaitForResponseTimedOutError):
336 logging.info('Ran the test with timeout of %ds.' % timeout)
340 def RunTest(self, test):
343 results = base_test_result.TestRunResults()
344 timeout = (self._GetIndividualTestTimeoutSecs(test) *
345 self._GetIndividualTestTimeoutScale(test) *
346 self.tool.GetTimeoutScale())
349 start_date_ms = int(time.time()) * 1000
350 raw_result = self._RunTest(test, timeout)
351 duration_ms = int(time.time()) * 1000 - start_date_ms
352 status_code = raw_result.GetStatusCode()
354 if self.options.screenshot_failures:
355 self._TakeScreenshot(test)
356 log = raw_result.GetFailureReason()
358 log = 'No information.'
359 result_type = base_test_result.ResultType.FAIL
360 package = self.device.old_interface.DismissCrashDialogIfNeeded()
361 # Assume test package convention of ".test" suffix
362 if package and package in self.test_pkg.GetPackageName():
363 result_type = base_test_result.ResultType.CRASH
364 result = test_result.InstrumentationTestResult(
365 test, result_type, start_date_ms, duration_ms, log=log)
367 result = test_result.InstrumentationTestResult(
368 test, base_test_result.ResultType.PASS, start_date_ms, duration_ms)
369 results.AddResult(result)
370 # Catch exceptions thrown by StartInstrumentation().
371 # See ../../third_party/android/testrunner/adb_interface.py
372 except (adb_wrapper.CommandTimeoutError,
373 adb_wrapper.DeviceUnreachableError,
374 # TODO(jbudorick) Remove these once the underlying implementations
375 # for the above are switched or wrapped.
376 android_commands.errors.WaitForResponseTimedOutError,
377 android_commands.errors.DeviceUnresponsiveError,
378 android_commands.errors.InstrumentationError), e:
380 duration_ms = int(time.time()) * 1000 - start_date_ms
382 start_date_ms = int(time.time()) * 1000
386 message = 'No information.'
387 results.AddResult(test_result.InstrumentationTestResult(
388 test, base_test_result.ResultType.CRASH, start_date_ms, duration_ms,
391 self.TestTeardown(test, raw_result)
392 return (results, None if results.DidRunPass() else test)