Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / build / android / pylib / instrumentation / test_runner.py
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.
4
5 """Class for running instrumentation tests on a single device."""
6
7 import logging
8 import os
9 import re
10 import sys
11 import time
12
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
22
23 sys.path.append(os.path.join(sys.path[0],
24                              os.pardir, os.pardir, 'build', 'util', 'lib',
25                              'common'))
26 import perf_tests_results_helper # pylint: disable=F0401
27
28
29 _PERF_TEST_ANNOTATION = 'PerfTest'
30
31
32 def _GetDataFilesForTestSuite(suite_basename):
33   """Returns a list of data files/dirs needed by the test suite.
34
35   Args:
36     suite_basename: The test suite basename for which to return file paths.
37
38   Returns:
39     A list of test file and directory paths.
40   """
41   test_files = []
42   if suite_basename in ['ChromeTest', 'ContentShellTest']:
43     test_files += [
44         'net/data/ssl/certificates/',
45     ]
46   return test_files
47
48
49 class TestRunner(base_test_runner.BaseTestRunner):
50   """Responsible for running a series of tests connected to a single device."""
51
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 +
56                                        '/chrome-profile*')
57   _DEVICE_HAS_TEST_FILES = {}
58
59   def __init__(self, test_options, device, shard_index, test_pkg,
60                additional_flags=None):
61     """Create a new TestRunner.
62
63     Args:
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.
69     """
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
74
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])
86       if additional_flags:
87         self.flags.AddFlags(additional_flags)
88     else:
89       self.flags = None
90
91   #override
92   def InstallTestPackage(self):
93     self.test_pkg.Install(self.device)
94
95   #override
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())
102       return
103
104     test_data = _GetDataFilesForTestSuite(self.test_pkg.GetApkName())
105     if test_data:
106       # Make sure SD card is ready.
107       self.device.old_interface.WaitForSdCardReady(20)
108       for p in test_data:
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))
112
113     # TODO(frankf): Specify test data in this file as opposed to passing
114     # as command-line.
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,
123             '%s/%s/%s' % (
124                 self.device.old_interface.GetExternalStorage(),
125                 TestRunner._DEVICE_DATA_DIR,
126                 dst_layer))
127     self.tool.CopyFiles()
128     TestRunner._DEVICE_HAS_TEST_FILES[
129         self.device.old_interface.GetDevice()] = True
130
131   def _GetInstrumentationArgs(self):
132     ret = {}
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
138
139     return ret
140
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)
146
147   def SetUp(self):
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',
152                       str(self.device))
153     else:
154       if self.device.old_interface.SetJavaAssertsEnabled(True):
155         self.device.old_interface.Reboot(full_reboot=False)
156
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)
162     if self.flags:
163       self.flags.AddFlags(['--disable-fre', '--enable-test-intents'])
164
165   def TearDown(self):
166     """Cleans up the test harness and saves outstanding data from test run."""
167     if self.flags:
168       self.flags.Restore()
169     super(TestRunner, self).TearDown()
170
171   def TestSetup(self, test):
172     """Sets up the test harness for running a particular test.
173
174     Args:
175       test: The name of the test that will be run.
176     """
177     self.SetupPerfMonitoringIfNeeded(test)
178     self._SetupIndividualTestTimeoutScale(test)
179     self.tool.SetupEnvironment()
180
181     # Make sure the forwarder is still running.
182     self._RestartHttpServerForwarderIfNecessary()
183
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)
191
192   def _IsPerfTest(self, test):
193     """Determines whether a test is a performance test.
194
195     Args:
196       test: The name of the test to be checked.
197
198     Returns:
199       Whether the test is annotated as a performance test.
200     """
201     return _PERF_TEST_ANNOTATION in self.test_pkg.GetTestAnnotations(test)
202
203   def SetupPerfMonitoringIfNeeded(self, test):
204     """Sets up performance monitoring if the specified test requires it.
205
206     Args:
207       test: The name of the test to be run.
208     """
209     if not self._IsPerfTest(test):
210       return
211     self.device.old_interface.Adb().SendCommand(
212         'shell rm ' + TestRunner._DEVICE_PERF_OUTPUT_SEARCH_PREFIX)
213     self.device.old_interface.StartMonitoringLogcat()
214
215   def TestTeardown(self, test, raw_result):
216     """Cleans up the test harness after running a particular test.
217
218     Depending on the options of this TestRunner this might handle performance
219     tracking.  This method will only be called if the test passed.
220
221     Args:
222       test: The name of the test that was just run.
223       raw_result: result for this test.
224     """
225
226     self.tool.CleanUpEnvironment()
227
228     # The logic below relies on the test passing.
229     if not raw_result or raw_result.GetStatusCode():
230       return
231
232     self.TearDownPerfMonitoring(test)
233
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)
239
240   def TearDownPerfMonitoring(self, test):
241     """Cleans up performance monitoring if the specified test required it.
242
243     Args:
244       test: The name of the test that was just run.
245     Raises:
246       Exception: if there's anything wrong with the perf data.
247     """
248     if not self._IsPerfTest(test):
249       return
250     raw_test_name = test.split('#')[1]
251
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)
255
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--':
263
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')
268
269       if json_string:
270         json_string = '\n'.join(json_string)
271       else:
272         raise Exception('Perf file does not exist or is empty')
273
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:
277           f.write(json_string)
278         logging.info('Saving Perf UI JSON from test ' +
279                      test + ' to ' + json_local_file)
280
281       raw_perf_data = regex.group(1).split(';')
282
283       for raw_perf_set in raw_perf_data:
284         if raw_perf_set:
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)
289
290           # Process the performance data
291           result = json_perf_parser.GetAverageRunInfoFromJSONString(json_string,
292                                                                     perf_set[0])
293           perf_tests_results_helper.PrintPerfResult(perf_set[1], perf_set[2],
294                                                     [result['average']],
295                                                     result['units'])
296
297   def _SetupIndividualTestTimeoutScale(self, test):
298     timeout_scale = self._GetIndividualTestTimeoutScale(test)
299     valgrind_tools.SetChromeTimeoutScale(self.device, timeout_scale)
300
301   def _GetIndividualTestTimeoutScale(self, test):
302     """Returns the timeout scale for the given |test|."""
303     annotations = self.test_pkg.GetTestAnnotations(test)
304     timeout_scale = 1
305     if 'TimeoutScale' in annotations:
306       for annotation in annotations:
307         scale_match = re.match('TimeoutScale:([0-9]+)', annotation)
308         if scale_match:
309           timeout_scale = int(scale_match.group(1))
310     if self.options.wait_for_debugger:
311       timeout_scale *= 100
312     return timeout_scale
313
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:
318       return 600 * 60
319     if 'External' in annotations:
320       return 10 * 60
321     if 'LargeTest' in annotations or _PERF_TEST_ANNOTATION in annotations:
322       return 5 * 60
323     if 'MediumTest' in annotations:
324       return 3 * 60
325     return 1 * 60
326
327   def _RunTest(self, test, timeout):
328     try:
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)
337       raise
338
339   #override
340   def RunTest(self, test):
341     raw_result = None
342     start_date_ms = None
343     results = base_test_result.TestRunResults()
344     timeout = (self._GetIndividualTestTimeoutSecs(test) *
345                self._GetIndividualTestTimeoutScale(test) *
346                self.tool.GetTimeoutScale())
347     try:
348       self.TestSetup(test)
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()
353       if status_code:
354         if self.options.screenshot_failures:
355           self._TakeScreenshot(test)
356         log = raw_result.GetFailureReason()
357         if not log:
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)
366       else:
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:
379       if start_date_ms:
380         duration_ms = int(time.time()) * 1000 - start_date_ms
381       else:
382         start_date_ms = int(time.time()) * 1000
383         duration_ms = 0
384       message = str(e)
385       if not message:
386         message = 'No information.'
387       results.AddResult(test_result.InstrumentationTestResult(
388           test, base_test_result.ResultType.CRASH, start_date_ms, duration_ms,
389           log=message))
390       raw_result = None
391     self.TestTeardown(test, raw_result)
392     return (results, None if results.DidRunPass() else test)