- add sources.
[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
14 sys.path.append(os.path.join(sys.path[0],
15                              os.pardir, os.pardir, 'build', 'util', 'lib',
16                              'common'))
17 import perf_tests_results_helper
18
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
26
27 import test_result
28
29
30 _PERF_TEST_ANNOTATION = 'PerfTest'
31
32
33 def _GetDataFilesForTestSuite(suite_basename):
34   """Returns a list of data files/dirs needed by the test suite.
35
36   Args:
37     suite_basename: The test suite basename for which to return file paths.
38
39   Returns:
40     A list of test file and directory paths.
41   """
42   test_files = []
43   if suite_basename in ['ChromeTest', 'ContentShellTest']:
44     test_files += [
45         'net/data/ssl/certificates/',
46     ]
47   return test_files
48
49
50 class TestRunner(base_test_runner.BaseTestRunner):
51   """Responsible for running a series of tests connected to a single device."""
52
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 +
57                                        '/chrome-profile*')
58   _DEVICE_HAS_TEST_FILES = {}
59
60   def __init__(self, test_options, device, shard_index, test_pkg,
61                ports_to_forward, additional_flags=None):
62     """Create a new TestRunner.
63
64     Args:
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.
72     """
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
77
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])
88     else:
89       self.flags = flag_changer.FlagChanger(self.adb)
90     if additional_flags:
91       self.flags.AddFlags(additional_flags)
92
93   #override
94   def InstallTestPackage(self):
95     self.test_pkg.Install(self.adb)
96
97   #override
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.',
103                       self.device)
104       return
105
106     test_data = _GetDataFilesForTestSuite(self.test_pkg.GetApkName())
107     if test_data:
108       # Make sure SD card is ready.
109       self.adb.WaitForSdCardReady(20)
110       for p in test_data:
111         self.adb.PushIfNeeded(
112             os.path.join(constants.DIR_SOURCE_ROOT, p),
113             os.path.join(self.adb.GetExternalStorage(), p))
114
115     # TODO(frankf): Specify test data in this file as opposed to passing
116     # as command-line.
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,
125             dst_layer))
126     self.tool.CopyFiles()
127     TestRunner._DEVICE_HAS_TEST_FILES[self.device] = True
128
129   def _GetInstrumentationArgs(self):
130     ret = {}
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
136
137     return ret
138
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)
144
145   def SetUp(self):
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',
150                       self.device)
151     else:
152       if self.adb.SetJavaAssertsEnabled(True):
153         self.adb.Reboot(full_reboot=False)
154
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'])
163
164   def TearDown(self):
165     """Cleans up the test harness and saves outstanding data from test run."""
166     self.flags.Restore()
167     if self.ports_to_forward:
168       self._UnmapPorts([(port, port) for port in self.ports_to_forward])
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' % (self.adb.GetExternalStorage(),
187                                                 TestRunner._DEVICE_COVERAGE_DIR,
188                                                 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.adb.Adb().SendCommand('shell rm ' +
212                                TestRunner._DEVICE_PERF_OUTPUT_SEARCH_PREFIX)
213     self.adb.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.adb.Adb().Pull(self.coverage_device_file, self.coverage_host_file)
236       self.adb.RunShellCommand('rm -f %s' % self.coverage_device_file)
237
238   def TearDownPerfMonitoring(self, test):
239     """Cleans up performance monitoring if the specified test required it.
240
241     Args:
242       test: The name of the test that was just run.
243     Raises:
244       Exception: if there's anything wrong with the perf data.
245     """
246     if not self._IsPerfTest(test):
247       return
248     raw_test_name = test.split('#')[1]
249
250     # Wait and grab annotation data so we can figure out which traces to parse
251     regex = self.adb.WaitForLogMatch(re.compile('\*\*PERFANNOTATION\(' +
252                                                 raw_test_name +
253                                                 '\)\:(.*)'), None)
254
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--':
262
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')
267
268       if json_string:
269         json_string = '\n'.join(json_string)
270       else:
271         raise Exception('Perf file does not exist or is empty')
272
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:
276           f.write(json_string)
277         logging.info('Saving Perf UI JSON from test ' +
278                      test + ' to ' + json_local_file)
279
280       raw_perf_data = regex.group(1).split(';')
281
282       for raw_perf_set in raw_perf_data:
283         if raw_perf_set:
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)
288
289           # Process the performance data
290           result = json_perf_parser.GetAverageRunInfoFromJSONString(json_string,
291                                                                     perf_set[0])
292           perf_tests_results_helper.PrintPerfResult(perf_set[1], perf_set[2],
293                                                     [result['average']],
294                                                     result['units'])
295
296   def _SetupIndividualTestTimeoutScale(self, test):
297     timeout_scale = self._GetIndividualTestTimeoutScale(test)
298     valgrind_tools.SetChromeTimeoutScale(self.adb, timeout_scale)
299
300   def _GetIndividualTestTimeoutScale(self, test):
301     """Returns the timeout scale for the given |test|."""
302     annotations = self.test_pkg.GetTestAnnotations(test)
303     timeout_scale = 1
304     if 'TimeoutScale' in annotations:
305       for annotation in annotations:
306         scale_match = re.match('TimeoutScale:([0-9]+)', annotation)
307         if scale_match:
308           timeout_scale = int(scale_match.group(1))
309     if self.options.wait_for_debugger:
310       timeout_scale *= 100
311     return timeout_scale
312
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:
317       return 600 * 60
318     if 'External' in annotations:
319       return 10 * 60
320     if 'LargeTest' in annotations or _PERF_TEST_ANNOTATION in annotations:
321       return 5 * 60
322     if 'MediumTest' in annotations:
323       return 3 * 60
324     return 1 * 60
325
326   def _RunTest(self, test, timeout):
327     try:
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)
333       raise
334
335   #override
336   def RunTest(self, test):
337     raw_result = None
338     start_date_ms = None
339     results = base_test_result.TestRunResults()
340     timeout=(self._GetIndividualTestTimeoutSecs(test) *
341              self._GetIndividualTestTimeoutScale(test) *
342              self.tool.GetTimeoutScale())
343     try:
344       self.TestSetup(test)
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()
349       if status_code:
350         log = raw_result.GetFailureReason()
351         if not log:
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,
358             log=log)
359       else:
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:
368       if start_date_ms:
369         duration_ms = int(time.time()) * 1000 - start_date_ms
370       else:
371         start_date_ms = int(time.time()) * 1000
372         duration_ms = 0
373       message = str(e)
374       if not message:
375         message = 'No information.'
376       results.AddResult(test_result.InstrumentationTestResult(
377           test, base_test_result.ResultType.CRASH, start_date_ms, duration_ms,
378           log=message))
379       raw_result = None
380     self.TestTeardown(test, raw_result)
381     return (results, None if results.DidRunPass() else test)