Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / build / android / pylib / gtest / test_package_exe.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 """Defines TestPackageExecutable to help run stand-alone executables."""
6
7 import logging
8 import os
9 import sys
10 import tempfile
11
12 from pylib import cmd_helper
13 from pylib import constants
14 from pylib import pexpect
15 from pylib.gtest.test_package import TestPackage
16
17
18 class TestPackageExecutable(TestPackage):
19   """A helper class for running stand-alone executables."""
20
21   _TEST_RUNNER_RET_VAL_FILE = 'gtest_retval'
22
23   def __init__(self, suite_name):
24     """
25     Args:
26       suite_name: Name of the test suite (e.g. base_unittests).
27     """
28     TestPackage.__init__(self, suite_name)
29     self.suite_path = os.path.join(constants.GetOutDirectory(), suite_name)
30     self._symbols_dir = os.path.join(constants.GetOutDirectory(),
31                                      'lib.target')
32
33   #override
34   def GetGTestReturnCode(self, adb):
35     ret = None
36     ret_code = 1  # Assume failure if we can't find it
37     ret_code_file = tempfile.NamedTemporaryFile()
38     try:
39       if not adb.Adb().Pull(
40           constants.TEST_EXECUTABLE_DIR + '/' +
41           TestPackageExecutable._TEST_RUNNER_RET_VAL_FILE,
42           ret_code_file.name):
43         logging.critical('Unable to pull gtest ret val file %s',
44                          ret_code_file.name)
45         raise ValueError
46       ret_code = file(ret_code_file.name).read()
47       ret = int(ret_code)
48     except ValueError:
49       logging.critical('Error reading gtest ret val file %s [%s]',
50                        ret_code_file.name, ret_code)
51       ret = 1
52     return ret
53
54   @staticmethod
55   def _AddNativeCoverageExports(adb):
56     # export GCOV_PREFIX set the path for native coverage results
57     # export GCOV_PREFIX_STRIP indicates how many initial directory
58     #                          names to strip off the hardwired absolute paths.
59     #                          This value is calculated in buildbot.sh and
60     #                          depends on where the tree is built.
61     # Ex: /usr/local/google/code/chrome will become
62     #     /code/chrome if GCOV_PREFIX_STRIP=3
63     try:
64       depth = os.environ['NATIVE_COVERAGE_DEPTH_STRIP']
65     except KeyError:
66       logging.info('NATIVE_COVERAGE_DEPTH_STRIP is not defined: '
67                    'No native coverage.')
68       return ''
69     export_string = ('export GCOV_PREFIX="%s/gcov"\n' %
70                      adb.GetExternalStorage())
71     export_string += 'export GCOV_PREFIX_STRIP=%s\n' % depth
72     return export_string
73
74   #override
75   def ClearApplicationState(self, adb):
76     adb.KillAllBlocking(self.suite_name, 30)
77
78   #override
79   def CreateCommandLineFileOnDevice(self, adb, test_filter, test_arguments):
80     tool_wrapper = self.tool.GetTestWrapper()
81     sh_script_file = tempfile.NamedTemporaryFile()
82     # We need to capture the exit status from the script since adb shell won't
83     # propagate to us.
84     sh_script_file.write('cd %s\n'
85                          '%s'
86                          '%s %s/%s --gtest_filter=%s %s\n'
87                          'echo $? > %s' %
88                          (constants.TEST_EXECUTABLE_DIR,
89                           self._AddNativeCoverageExports(adb),
90                           tool_wrapper, constants.TEST_EXECUTABLE_DIR,
91                           self.suite_name,
92                           test_filter, test_arguments,
93                           TestPackageExecutable._TEST_RUNNER_RET_VAL_FILE))
94     sh_script_file.flush()
95     cmd_helper.RunCmd(['chmod', '+x', sh_script_file.name])
96     adb.PushIfNeeded(
97         sh_script_file.name,
98         constants.TEST_EXECUTABLE_DIR + '/chrome_test_runner.sh')
99     logging.info('Conents of the test runner script: ')
100     for line in open(sh_script_file.name).readlines():
101       logging.info('  ' + line.rstrip())
102
103   #override
104   def GetAllTests(self, adb):
105     all_tests = adb.RunShellCommand(
106         '%s %s/%s --gtest_list_tests' %
107         (self.tool.GetTestWrapper(),
108          constants.TEST_EXECUTABLE_DIR,
109          self.suite_name))
110     return self._ParseGTestListTests(all_tests)
111
112   #override
113   def SpawnTestProcess(self, adb):
114     args = ['adb', '-s', adb.GetDevice(), 'shell', 'sh',
115             constants.TEST_EXECUTABLE_DIR + '/chrome_test_runner.sh']
116     logging.info(args)
117     return pexpect.spawn(args[0], args[1:], logfile=sys.stdout)
118
119   #override
120   def Install(self, adb):
121     if self.tool.NeedsDebugInfo():
122       target_name = self.suite_path
123     else:
124       target_name = self.suite_path + '_stripped'
125       if not os.path.isfile(target_name):
126         raise Exception('Did not find %s, build target %s' %
127                         (target_name, self.suite_name + '_stripped'))
128
129       target_mtime = os.stat(target_name).st_mtime
130       source_mtime = os.stat(self.suite_path).st_mtime
131       if target_mtime < source_mtime:
132         raise Exception(
133             'stripped binary (%s, timestamp %d) older than '
134             'source binary (%s, timestamp %d), build target %s' %
135             (target_name, target_mtime, self.suite_path, source_mtime,
136              self.suite_name + '_stripped'))
137
138     test_binary = constants.TEST_EXECUTABLE_DIR + '/' + self.suite_name
139     adb.PushIfNeeded(target_name, test_binary)