Upstream version 5.34.104.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.instrumentation import json_perf_parser
20 from pylib.instrumentation import test_result
21
22 sys.path.append(os.path.join(sys.path[0],
23                              os.pardir, os.pardir, 'build', 'util', 'lib',
24                              'common'))
25 import perf_tests_results_helper # pylint: disable=F0401
26
27
28 _PERF_TEST_ANNOTATION = 'PerfTest'
29
30
31 def _GetDataFilesForTestSuite(suite_basename):
32   """Returns a list of data files/dirs needed by the test suite.
33
34   Args:
35     suite_basename: The test suite basename for which to return file paths.
36
37   Returns:
38     A list of test file and directory paths.
39   """
40   test_files = []
41   if suite_basename in ['ChromeTest', 'ContentShellTest']:
42     test_files += [
43         'net/data/ssl/certificates/',
44     ]
45   return test_files
46
47
48 class TestRunner(base_test_runner.BaseTestRunner):
49   """Responsible for running a series of tests connected to a single device."""
50
51   _DEVICE_DATA_DIR = 'chrome/test/data'
52   _DEVICE_COVERAGE_DIR = 'chrome/test/coverage'
53   _HOSTMACHINE_PERF_OUTPUT_FILE = '/tmp/chrome-profile'
54   _DEVICE_PERF_OUTPUT_SEARCH_PREFIX = (constants.DEVICE_PERF_OUTPUT_DIR +
55                                        '/chrome-profile*')
56   _DEVICE_HAS_TEST_FILES = {}
57
58   def __init__(self, test_options, device, shard_index, test_pkg,
59                additional_flags=None):
60     """Create a new TestRunner.
61
62     Args:
63       test_options: An InstrumentationOptions object.
64       device: Attached android device.
65       shard_index: Shard index.
66       test_pkg: A TestPackage object.
67       additional_flags: A list of additional flags to add to the command line.
68     """
69     super(TestRunner, self).__init__(device, test_options.tool,
70                                      test_options.push_deps,
71                                      test_options.cleanup_test_files)
72     self._lighttp_port = constants.LIGHTTPD_RANDOM_PORT_FIRST + shard_index
73
74     self.coverage_device_file = None
75     self.coverage_dir = test_options.coverage_dir
76     self.coverage_host_file = None
77     self.options = test_options
78     self.test_pkg = test_pkg
79     # Use the correct command line file for the package under test.
80     cmdline_file = [a.cmdline_file for a in constants.PACKAGE_INFO.itervalues()
81                     if a.test_package == self.test_pkg.GetPackageName()]
82     assert len(cmdline_file) < 2, 'Multiple packages have the same test package'
83     if len(cmdline_file) and cmdline_file[0]:
84       self.flags = flag_changer.FlagChanger(self.adb, cmdline_file[0])
85       if additional_flags:
86         self.flags.AddFlags(additional_flags)
87     else:
88       self.flags = None
89
90   #override
91   def InstallTestPackage(self):
92     self.test_pkg.Install(self.adb)
93
94   #override
95   def PushDataDeps(self):
96     # TODO(frankf): Implement a general approach for copying/installing
97     # once across test runners.
98     if TestRunner._DEVICE_HAS_TEST_FILES.get(self.device, False):
99       logging.warning('Already copied test files to device %s, skipping.',
100                       self.device)
101       return
102
103     test_data = _GetDataFilesForTestSuite(self.test_pkg.GetApkName())
104     if test_data:
105       # Make sure SD card is ready.
106       self.adb.WaitForSdCardReady(20)
107       for p in test_data:
108         self.adb.PushIfNeeded(
109             os.path.join(constants.DIR_SOURCE_ROOT, p),
110             os.path.join(self.adb.GetExternalStorage(), p))
111
112     # TODO(frankf): Specify test data in this file as opposed to passing
113     # as command-line.
114     for dest_host_pair in self.options.test_data:
115       dst_src = dest_host_pair.split(':', 1)
116       dst_layer = dst_src[0]
117       host_src = dst_src[1]
118       host_test_files_path = '%s/%s' % (constants.DIR_SOURCE_ROOT, host_src)
119       if os.path.exists(host_test_files_path):
120         self.adb.PushIfNeeded(host_test_files_path, '%s/%s/%s' % (
121             self.adb.GetExternalStorage(), TestRunner._DEVICE_DATA_DIR,
122             dst_layer))
123     self.tool.CopyFiles()
124     TestRunner._DEVICE_HAS_TEST_FILES[self.device] = True
125
126   def _GetInstrumentationArgs(self):
127     ret = {}
128     if self.options.wait_for_debugger:
129       ret['debug'] = 'true'
130     if self.coverage_dir:
131       ret['coverage'] = 'true'
132       ret['coverageFile'] = self.coverage_device_file
133
134     return ret
135
136   def _TakeScreenshot(self, test):
137     """Takes a screenshot from the device."""
138     screenshot_name = os.path.join(constants.SCREENSHOTS_DIR, '%s.png' % test)
139     logging.info('Taking screenshot named %s', screenshot_name)
140     self.adb.TakeScreenshot(screenshot_name)
141
142   def SetUp(self):
143     """Sets up the test harness and device before all tests are run."""
144     super(TestRunner, self).SetUp()
145     if not self.adb.IsRootEnabled():
146       logging.warning('Unable to enable java asserts for %s, non rooted device',
147                       self.device)
148     else:
149       if self.adb.SetJavaAssertsEnabled(True):
150         self.adb.Reboot(full_reboot=False)
151
152     # We give different default value to launch HTTP server based on shard index
153     # because it may have race condition when multiple processes are trying to
154     # launch lighttpd with same port at same time.
155     self.LaunchTestHttpServer(
156         os.path.join(constants.DIR_SOURCE_ROOT), self._lighttp_port)
157     if self.flags:
158       self.flags.AddFlags(['--disable-fre', '--enable-test-intents'])
159
160   def TearDown(self):
161     """Cleans up the test harness and saves outstanding data from test run."""
162     if self.flags:
163       self.flags.Restore()
164     super(TestRunner, self).TearDown()
165
166   def TestSetup(self, test):
167     """Sets up the test harness for running a particular test.
168
169     Args:
170       test: The name of the test that will be run.
171     """
172     self.SetupPerfMonitoringIfNeeded(test)
173     self._SetupIndividualTestTimeoutScale(test)
174     self.tool.SetupEnvironment()
175
176     # Make sure the forwarder is still running.
177     self._RestartHttpServerForwarderIfNecessary()
178
179     if self.coverage_dir:
180       coverage_basename = '%s.ec' % test
181       self.coverage_device_file = '%s/%s/%s' % (self.adb.GetExternalStorage(),
182                                                 TestRunner._DEVICE_COVERAGE_DIR,
183                                                 coverage_basename)
184       self.coverage_host_file = os.path.join(
185           self.coverage_dir, coverage_basename)
186
187   def _IsPerfTest(self, test):
188     """Determines whether a test is a performance test.
189
190     Args:
191       test: The name of the test to be checked.
192
193     Returns:
194       Whether the test is annotated as a performance test.
195     """
196     return _PERF_TEST_ANNOTATION in self.test_pkg.GetTestAnnotations(test)
197
198   def SetupPerfMonitoringIfNeeded(self, test):
199     """Sets up performance monitoring if the specified test requires it.
200
201     Args:
202       test: The name of the test to be run.
203     """
204     if not self._IsPerfTest(test):
205       return
206     self.adb.Adb().SendCommand('shell rm ' +
207                                TestRunner._DEVICE_PERF_OUTPUT_SEARCH_PREFIX)
208     self.adb.StartMonitoringLogcat()
209
210   def TestTeardown(self, test, raw_result):
211     """Cleans up the test harness after running a particular test.
212
213     Depending on the options of this TestRunner this might handle performance
214     tracking.  This method will only be called if the test passed.
215
216     Args:
217       test: The name of the test that was just run.
218       raw_result: result for this test.
219     """
220
221     self.tool.CleanUpEnvironment()
222
223     # The logic below relies on the test passing.
224     if not raw_result or raw_result.GetStatusCode():
225       return
226
227     self.TearDownPerfMonitoring(test)
228
229     if self.coverage_dir:
230       self.adb.Adb().Pull(self.coverage_device_file, self.coverage_host_file)
231       self.adb.RunShellCommand('rm -f %s' % self.coverage_device_file)
232
233   def TearDownPerfMonitoring(self, test):
234     """Cleans up performance monitoring if the specified test required it.
235
236     Args:
237       test: The name of the test that was just run.
238     Raises:
239       Exception: if there's anything wrong with the perf data.
240     """
241     if not self._IsPerfTest(test):
242       return
243     raw_test_name = test.split('#')[1]
244
245     # Wait and grab annotation data so we can figure out which traces to parse
246     regex = self.adb.WaitForLogMatch(re.compile('\*\*PERFANNOTATION\(' +
247                                                 raw_test_name +
248                                                 '\)\:(.*)'), None)
249
250     # If the test is set to run on a specific device type only (IE: only
251     # tablet or phone) and it is being run on the wrong device, the test
252     # just quits and does not do anything.  The java test harness will still
253     # print the appropriate annotation for us, but will add --NORUN-- for
254     # us so we know to ignore the results.
255     # The --NORUN-- tag is managed by MainActivityTestBase.java
256     if regex.group(1) != '--NORUN--':
257
258       # Obtain the relevant perf data.  The data is dumped to a
259       # JSON formatted file.
260       json_string = self.adb.GetProtectedFileContents(
261           '/data/data/com.google.android.apps.chrome/files/PerfTestData.txt')
262
263       if json_string:
264         json_string = '\n'.join(json_string)
265       else:
266         raise Exception('Perf file does not exist or is empty')
267
268       if self.options.save_perf_json:
269         json_local_file = '/tmp/chromium-android-perf-json-' + raw_test_name
270         with open(json_local_file, 'w') as f:
271           f.write(json_string)
272         logging.info('Saving Perf UI JSON from test ' +
273                      test + ' to ' + json_local_file)
274
275       raw_perf_data = regex.group(1).split(';')
276
277       for raw_perf_set in raw_perf_data:
278         if raw_perf_set:
279           perf_set = raw_perf_set.split(',')
280           if len(perf_set) != 3:
281             raise Exception('Unexpected number of tokens in perf annotation '
282                             'string: ' + raw_perf_set)
283
284           # Process the performance data
285           result = json_perf_parser.GetAverageRunInfoFromJSONString(json_string,
286                                                                     perf_set[0])
287           perf_tests_results_helper.PrintPerfResult(perf_set[1], perf_set[2],
288                                                     [result['average']],
289                                                     result['units'])
290
291   def _SetupIndividualTestTimeoutScale(self, test):
292     timeout_scale = self._GetIndividualTestTimeoutScale(test)
293     valgrind_tools.SetChromeTimeoutScale(self.adb, timeout_scale)
294
295   def _GetIndividualTestTimeoutScale(self, test):
296     """Returns the timeout scale for the given |test|."""
297     annotations = self.test_pkg.GetTestAnnotations(test)
298     timeout_scale = 1
299     if 'TimeoutScale' in annotations:
300       for annotation in annotations:
301         scale_match = re.match('TimeoutScale:([0-9]+)', annotation)
302         if scale_match:
303           timeout_scale = int(scale_match.group(1))
304     if self.options.wait_for_debugger:
305       timeout_scale *= 100
306     return timeout_scale
307
308   def _GetIndividualTestTimeoutSecs(self, test):
309     """Returns the timeout in seconds for the given |test|."""
310     annotations = self.test_pkg.GetTestAnnotations(test)
311     if 'Manual' in annotations:
312       return 600 * 60
313     if 'External' in annotations:
314       return 10 * 60
315     if 'LargeTest' in annotations or _PERF_TEST_ANNOTATION in annotations:
316       return 5 * 60
317     if 'MediumTest' in annotations:
318       return 3 * 60
319     return 1 * 60
320
321   def _RunTest(self, test, timeout):
322     try:
323       return self.adb.RunInstrumentationTest(
324           test, self.test_pkg.GetPackageName(),
325           self._GetInstrumentationArgs(), timeout)
326     except android_commands.errors.WaitForResponseTimedOutError:
327       logging.info('Ran the test with timeout of %ds.' % timeout)
328       raise
329
330   #override
331   def RunTest(self, test):
332     raw_result = None
333     start_date_ms = None
334     results = base_test_result.TestRunResults()
335     timeout = (self._GetIndividualTestTimeoutSecs(test) *
336                self._GetIndividualTestTimeoutScale(test) *
337                self.tool.GetTimeoutScale())
338     try:
339       self.TestSetup(test)
340       start_date_ms = int(time.time()) * 1000
341       raw_result = self._RunTest(test, timeout)
342       duration_ms = int(time.time()) * 1000 - start_date_ms
343       status_code = raw_result.GetStatusCode()
344       if status_code:
345         if self.options.screenshot_failures:
346           self._TakeScreenshot(test)
347         log = raw_result.GetFailureReason()
348         if not log:
349           log = 'No information.'
350         result_type = base_test_result.ResultType.FAIL
351         package = self.adb.DismissCrashDialogIfNeeded()
352         # Assume test package convention of ".test" suffix
353         if package and package in self.test_pkg.GetPackageName():
354           result_type = base_test_result.ResultType.CRASH
355         result = test_result.InstrumentationTestResult(
356             test, result_type, start_date_ms, duration_ms, log=log)
357       else:
358         result = test_result.InstrumentationTestResult(
359             test, base_test_result.ResultType.PASS, start_date_ms, duration_ms)
360       results.AddResult(result)
361     # Catch exceptions thrown by StartInstrumentation().
362     # See ../../third_party/android/testrunner/adb_interface.py
363     except (android_commands.errors.WaitForResponseTimedOutError,
364             android_commands.errors.DeviceUnresponsiveError,
365             android_commands.errors.InstrumentationError), e:
366       if start_date_ms:
367         duration_ms = int(time.time()) * 1000 - start_date_ms
368       else:
369         start_date_ms = int(time.time()) * 1000
370         duration_ms = 0
371       message = str(e)
372       if not message:
373         message = 'No information.'
374       results.AddResult(test_result.InstrumentationTestResult(
375           test, base_test_result.ResultType.CRASH, start_date_ms, duration_ms,
376           log=message))
377       raw_result = None
378     self.TestTeardown(test, raw_result)
379     return (results, None if results.DidRunPass() else test)