Add Apps.AppListSearchQueryLength UMA histogram.
[chromium-blink-merge.git] / build / android / pylib / instrumentation / test_runner.py
blobd1c5a4d6bc396e5a83523ca705b4cee57101154d
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."""
7 import logging
8 import os
9 import re
10 import sys
11 import time
13 from pylib import constants
14 from pylib import flag_changer
15 from pylib import valgrind_tools
16 from pylib.base import base_test_result
17 from pylib.base import base_test_runner
18 from pylib.device import device_errors
19 from pylib.instrumentation import instrumentation_test_instance
20 from pylib.instrumentation import json_perf_parser
21 from pylib.instrumentation import test_result
22 from pylib.local.device import local_device_instrumentation_test_run
24 sys.path.append(os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'util', 'lib',
25 'common'))
26 import perf_tests_results_helper # pylint: disable=F0401
29 _PERF_TEST_ANNOTATION = 'PerfTest'
32 class TestRunner(base_test_runner.BaseTestRunner):
33 """Responsible for running a series of tests connected to a single device."""
35 _DEVICE_COVERAGE_DIR = 'chrome/test/coverage'
36 _HOSTMACHINE_PERF_OUTPUT_FILE = '/tmp/chrome-profile'
37 _DEVICE_PERF_OUTPUT_SEARCH_PREFIX = (constants.DEVICE_PERF_OUTPUT_DIR +
38 '/chrome-profile*')
40 def __init__(self, test_options, device, shard_index, test_pkg,
41 additional_flags=None):
42 """Create a new TestRunner.
44 Args:
45 test_options: An InstrumentationOptions object.
46 device: Attached android device.
47 shard_index: Shard index.
48 test_pkg: A TestPackage object.
49 additional_flags: A list of additional flags to add to the command line.
50 """
51 super(TestRunner, self).__init__(device, test_options.tool)
52 self._lighttp_port = constants.LIGHTTPD_RANDOM_PORT_FIRST + shard_index
53 self._logcat_monitor = None
55 self.coverage_device_file = None
56 self.coverage_dir = test_options.coverage_dir
57 self.coverage_host_file = None
58 self.options = test_options
59 self.test_pkg = test_pkg
60 # Use the correct command line file for the package under test.
61 cmdline_file = [a.cmdline_file for a in constants.PACKAGE_INFO.itervalues()
62 if a.test_package == self.test_pkg.GetPackageName()]
63 assert len(cmdline_file) < 2, 'Multiple packages have the same test package'
64 if len(cmdline_file) and cmdline_file[0]:
65 self.flags = flag_changer.FlagChanger(self.device, cmdline_file[0])
66 if additional_flags:
67 self.flags.AddFlags(additional_flags)
68 else:
69 self.flags = None
71 #override
72 def InstallTestPackage(self):
73 self.test_pkg.Install(self.device)
75 def _GetInstrumentationArgs(self):
76 ret = {}
77 if self.options.wait_for_debugger:
78 ret['debug'] = 'true'
79 if self.coverage_dir:
80 ret['coverage'] = 'true'
81 ret['coverageFile'] = self.coverage_device_file
83 return ret
85 def _TakeScreenshot(self, test):
86 """Takes a screenshot from the device."""
87 screenshot_name = os.path.join(constants.SCREENSHOTS_DIR, '%s.png' % test)
88 logging.info('Taking screenshot named %s', screenshot_name)
89 self.device.TakeScreenshot(screenshot_name)
91 def SetUp(self):
92 """Sets up the test harness and device before all tests are run."""
93 super(TestRunner, self).SetUp()
94 if not self.device.HasRoot():
95 logging.warning('Unable to enable java asserts for %s, non rooted device',
96 str(self.device))
97 else:
98 if self.device.SetJavaAsserts(self.options.set_asserts):
99 # TODO(jbudorick) How to best do shell restart after the
100 # android_commands refactor?
101 self.device.RunShellCommand('stop')
102 self.device.RunShellCommand('start')
104 # We give different default value to launch HTTP server based on shard index
105 # because it may have race condition when multiple processes are trying to
106 # launch lighttpd with same port at same time.
107 self.LaunchTestHttpServer(
108 os.path.join(constants.DIR_SOURCE_ROOT), self._lighttp_port)
109 if self.flags:
110 self.flags.AddFlags(['--disable-fre', '--enable-test-intents'])
111 if self.options.device_flags:
112 with open(self.options.device_flags) as device_flags_file:
113 stripped_flags = (l.strip() for l in device_flags_file)
114 self.flags.AddFlags([flag for flag in stripped_flags if flag])
116 def TearDown(self):
117 """Cleans up the test harness and saves outstanding data from test run."""
118 if self.flags:
119 self.flags.Restore()
120 super(TestRunner, self).TearDown()
122 def TestSetup(self, test):
123 """Sets up the test harness for running a particular test.
125 Args:
126 test: The name of the test that will be run.
128 self.SetupPerfMonitoringIfNeeded(test)
129 self._SetupIndividualTestTimeoutScale(test)
130 self.tool.SetupEnvironment()
132 if self.flags and self._IsFreTest(test):
133 self.flags.RemoveFlags(['--disable-fre'])
135 # Make sure the forwarder is still running.
136 self._RestartHttpServerForwarderIfNecessary()
138 if self.coverage_dir:
139 coverage_basename = '%s.ec' % test
140 self.coverage_device_file = '%s/%s/%s' % (
141 self.device.GetExternalStoragePath(),
142 TestRunner._DEVICE_COVERAGE_DIR, coverage_basename)
143 self.coverage_host_file = os.path.join(
144 self.coverage_dir, coverage_basename)
146 def _IsFreTest(self, test):
147 """Determines whether a test is a first run experience test.
149 Args:
150 test: The name of the test to be checked.
152 Returns:
153 Whether the feature being tested is FirstRunExperience.
155 annotations = self.test_pkg.GetTestAnnotations(test)
156 return 'FirstRunExperience' == annotations.get('Feature', None)
158 def _IsPerfTest(self, test):
159 """Determines whether a test is a performance test.
161 Args:
162 test: The name of the test to be checked.
164 Returns:
165 Whether the test is annotated as a performance test.
167 return _PERF_TEST_ANNOTATION in self.test_pkg.GetTestAnnotations(test)
169 def SetupPerfMonitoringIfNeeded(self, test):
170 """Sets up performance monitoring if the specified test requires it.
172 Args:
173 test: The name of the test to be run.
175 if not self._IsPerfTest(test):
176 return
177 self.device.RunShellCommand(
178 ['rm', TestRunner._DEVICE_PERF_OUTPUT_SEARCH_PREFIX])
179 self._logcat_monitor = self.device.GetLogcatMonitor()
180 self._logcat_monitor.Start()
182 def TestTeardown(self, test, result):
183 """Cleans up the test harness after running a particular test.
185 Depending on the options of this TestRunner this might handle performance
186 tracking. This method will only be called if the test passed.
188 Args:
189 test: The name of the test that was just run.
190 result: result for this test.
193 self.tool.CleanUpEnvironment()
195 # The logic below relies on the test passing.
196 if not result or not result.DidRunPass():
197 return
199 self.TearDownPerfMonitoring(test)
201 if self.flags and self._IsFreTest(test):
202 self.flags.AddFlags(['--disable-fre'])
204 if self.coverage_dir:
205 self.device.PullFile(
206 self.coverage_device_file, self.coverage_host_file)
207 self.device.RunShellCommand(
208 'rm -f %s' % self.coverage_device_file)
210 def TearDownPerfMonitoring(self, test):
211 """Cleans up performance monitoring if the specified test required it.
213 Args:
214 test: The name of the test that was just run.
215 Raises:
216 Exception: if there's anything wrong with the perf data.
218 if not self._IsPerfTest(test):
219 return
220 raw_test_name = test.split('#')[1]
222 # Wait and grab annotation data so we can figure out which traces to parse
223 regex = self._logcat_monitor.WaitFor(
224 re.compile(r'\*\*PERFANNOTATION\(' + raw_test_name + r'\)\:(.*)'))
226 # If the test is set to run on a specific device type only (IE: only
227 # tablet or phone) and it is being run on the wrong device, the test
228 # just quits and does not do anything. The java test harness will still
229 # print the appropriate annotation for us, but will add --NORUN-- for
230 # us so we know to ignore the results.
231 # The --NORUN-- tag is managed by ChromeTabbedActivityTestBase.java
232 if regex.group(1) != '--NORUN--':
234 # Obtain the relevant perf data. The data is dumped to a
235 # JSON formatted file.
236 json_string = self.device.ReadFile(
237 '/data/data/com.google.android.apps.chrome/files/PerfTestData.txt',
238 as_root=True)
240 if not json_string:
241 raise Exception('Perf file is empty')
243 if self.options.save_perf_json:
244 json_local_file = '/tmp/chromium-android-perf-json-' + raw_test_name
245 with open(json_local_file, 'w') as f:
246 f.write(json_string)
247 logging.info('Saving Perf UI JSON from test ' +
248 test + ' to ' + json_local_file)
250 raw_perf_data = regex.group(1).split(';')
252 for raw_perf_set in raw_perf_data:
253 if raw_perf_set:
254 perf_set = raw_perf_set.split(',')
255 if len(perf_set) != 3:
256 raise Exception('Unexpected number of tokens in perf annotation '
257 'string: ' + raw_perf_set)
259 # Process the performance data
260 result = json_perf_parser.GetAverageRunInfoFromJSONString(json_string,
261 perf_set[0])
262 perf_tests_results_helper.PrintPerfResult(perf_set[1], perf_set[2],
263 [result['average']],
264 result['units'])
266 def _SetupIndividualTestTimeoutScale(self, test):
267 timeout_scale = self._GetIndividualTestTimeoutScale(test)
268 valgrind_tools.SetChromeTimeoutScale(self.device, timeout_scale)
270 def _GetIndividualTestTimeoutScale(self, test):
271 """Returns the timeout scale for the given |test|."""
272 annotations = self.test_pkg.GetTestAnnotations(test)
273 timeout_scale = 1
274 if 'TimeoutScale' in annotations:
275 try:
276 timeout_scale = int(annotations['TimeoutScale'])
277 except ValueError:
278 logging.warning('Non-integer value of TimeoutScale ignored. (%s)'
279 % annotations['TimeoutScale'])
280 if self.options.wait_for_debugger:
281 timeout_scale *= 100
282 return timeout_scale
284 def _GetIndividualTestTimeoutSecs(self, test):
285 """Returns the timeout in seconds for the given |test|."""
286 annotations = self.test_pkg.GetTestAnnotations(test)
287 if 'Manual' in annotations:
288 return 10 * 60 * 60
289 if 'IntegrationTest' in annotations:
290 return 30 * 60
291 if 'External' in annotations:
292 return 10 * 60
293 if 'EnormousTest' in annotations:
294 return 10 * 60
295 if 'LargeTest' in annotations or _PERF_TEST_ANNOTATION in annotations:
296 return 5 * 60
297 if 'MediumTest' in annotations:
298 return 3 * 60
299 if 'SmallTest' in annotations:
300 return 1 * 60
302 logging.warn(("Test size not found in annotations for test '%s', using " +
303 "1 minute for timeout.") % test)
304 return 1 * 60
306 def _RunTest(self, test, timeout):
307 """Runs a single instrumentation test.
309 Args:
310 test: Test class/method.
311 timeout: Timeout time in seconds.
313 Returns:
314 The raw output of am instrument as a list of lines.
316 extras = self._GetInstrumentationArgs()
317 extras['class'] = test
318 return self.device.StartInstrumentation(
319 '%s/%s' % (self.test_pkg.GetPackageName(), self.options.test_runner),
320 raw=True, extras=extras, timeout=timeout, retries=3)
322 def _GenerateTestResult(self, test, instr_result_code, instr_result_bundle,
323 statuses, start_ms, duration_ms):
324 results = instrumentation_test_instance.GenerateTestResults(
325 instr_result_code, instr_result_bundle, statuses, start_ms, duration_ms)
326 for r in results:
327 if r.GetName() == test:
328 return r
329 logging.error('Could not find result for test: %s', test)
330 return test_result.InstrumentationTestResult(
331 test, base_test_result.ResultType.UNKNOWN, start_ms, duration_ms)
333 #override
334 def RunTest(self, test):
335 results = base_test_result.TestRunResults()
336 timeout = (self._GetIndividualTestTimeoutSecs(test) *
337 self._GetIndividualTestTimeoutScale(test) *
338 self.tool.GetTimeoutScale())
340 start_ms = 0
341 duration_ms = 0
342 try:
343 self.TestSetup(test)
345 time_ms = lambda: int(time.time() * 1000)
346 start_ms = time_ms()
347 raw_output = self._RunTest(test, timeout)
348 duration_ms = time_ms() - start_ms
350 # Parse the test output
351 result_code, result_bundle, statuses = (
352 instrumentation_test_instance.ParseAmInstrumentRawOutput(raw_output))
353 result = self._GenerateTestResult(
354 test, result_code, result_bundle, statuses, start_ms, duration_ms)
355 if local_device_instrumentation_test_run.DidPackageCrashOnDevice(
356 self.test_pkg.GetPackageName(), self.device):
357 result.SetType(base_test_result.ResultType.CRASH)
358 results.AddResult(result)
359 except device_errors.CommandTimeoutError as e:
360 results.AddResult(test_result.InstrumentationTestResult(
361 test, base_test_result.ResultType.TIMEOUT, start_ms, duration_ms,
362 log=str(e) or 'No information'))
363 except device_errors.DeviceUnreachableError as e:
364 results.AddResult(test_result.InstrumentationTestResult(
365 test, base_test_result.ResultType.CRASH, start_ms, duration_ms,
366 log=str(e) or 'No information'))
367 self.TestTeardown(test, results)
368 return (results, None if results.DidRunPass() else test)