PageRenderTime 79ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 0ms

/external/chromium/testing/gtest/test/gtest_test_utils.py

https://gitlab.com/brian0218/rk3066_r-box_android4.2.2_sdk
Python | 305 lines | 144 code | 48 blank | 113 comment | 34 complexity | 0eb52e06f3ad3c45fd0c94105d631a02 MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2006, Google Inc.
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. #
  10. # * Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # * Redistributions in binary form must reproduce the above
  13. # copyright notice, this list of conditions and the following disclaimer
  14. # in the documentation and/or other materials provided with the
  15. # distribution.
  16. # * Neither the name of Google Inc. nor the names of its
  17. # contributors may be used to endorse or promote products derived from
  18. # this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """Unit test utilities for Google C++ Testing Framework."""
  32. __author__ = 'wan@google.com (Zhanyong Wan)'
  33. import atexit
  34. import os
  35. import shutil
  36. import sys
  37. import tempfile
  38. import unittest
  39. _test_module = unittest
  40. # Suppresses the 'Import not at the top of the file' lint complaint.
  41. # pylint: disable-msg=C6204
  42. try:
  43. import subprocess
  44. _SUBPROCESS_MODULE_AVAILABLE = True
  45. except:
  46. import popen2
  47. _SUBPROCESS_MODULE_AVAILABLE = False
  48. # pylint: enable-msg=C6204
  49. GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
  50. IS_WINDOWS = os.name == 'nt'
  51. IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
  52. # Here we expose a class from a particular module, depending on the
  53. # environment. The comment suppresses the 'Invalid variable name' lint
  54. # complaint.
  55. TestCase = _test_module.TestCase # pylint: disable-msg=C6409
  56. # Initially maps a flag to its default value. After
  57. # _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
  58. _flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
  59. 'build_dir': os.path.dirname(sys.argv[0])}
  60. _gtest_flags_are_parsed = False
  61. def _ParseAndStripGTestFlags(argv):
  62. """Parses and strips Google Test flags from argv. This is idempotent."""
  63. # Suppresses the lint complaint about a global variable since we need it
  64. # here to maintain module-wide state.
  65. global _gtest_flags_are_parsed # pylint: disable-msg=W0603
  66. if _gtest_flags_are_parsed:
  67. return
  68. _gtest_flags_are_parsed = True
  69. for flag in _flag_map:
  70. # The environment variable overrides the default value.
  71. if flag.upper() in os.environ:
  72. _flag_map[flag] = os.environ[flag.upper()]
  73. # The command line flag overrides the environment variable.
  74. i = 1 # Skips the program name.
  75. while i < len(argv):
  76. prefix = '--' + flag + '='
  77. if argv[i].startswith(prefix):
  78. _flag_map[flag] = argv[i][len(prefix):]
  79. del argv[i]
  80. break
  81. else:
  82. # We don't increment i in case we just found a --gtest_* flag
  83. # and removed it from argv.
  84. i += 1
  85. def GetFlag(flag):
  86. """Returns the value of the given flag."""
  87. # In case GetFlag() is called before Main(), we always call
  88. # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
  89. # are parsed.
  90. _ParseAndStripGTestFlags(sys.argv)
  91. return _flag_map[flag]
  92. def GetSourceDir():
  93. """Returns the absolute path of the directory where the .py files are."""
  94. return os.path.abspath(GetFlag('source_dir'))
  95. def GetBuildDir():
  96. """Returns the absolute path of the directory where the test binaries are."""
  97. return os.path.abspath(GetFlag('build_dir'))
  98. _temp_dir = None
  99. def _RemoveTempDir():
  100. if _temp_dir:
  101. shutil.rmtree(_temp_dir, ignore_errors=True)
  102. atexit.register(_RemoveTempDir)
  103. def GetTempDir():
  104. """Returns a directory for temporary files."""
  105. global _temp_dir
  106. if not _temp_dir:
  107. _temp_dir = tempfile.mkdtemp()
  108. return _temp_dir
  109. def GetTestExecutablePath(executable_name, build_dir=None):
  110. """Returns the absolute path of the test binary given its name.
  111. The function will print a message and abort the program if the resulting file
  112. doesn't exist.
  113. Args:
  114. executable_name: name of the test binary that the test script runs.
  115. build_dir: directory where to look for executables, by default
  116. the result of GetBuildDir().
  117. Returns:
  118. The absolute path of the test binary.
  119. """
  120. path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
  121. executable_name))
  122. if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
  123. path += '.exe'
  124. if not os.path.exists(path):
  125. message = (
  126. 'Unable to find the test binary. Please make sure to provide path\n'
  127. 'to the binary via the --build_dir flag or the BUILD_DIR\n'
  128. 'environment variable.')
  129. print >> sys.stderr, message
  130. sys.exit(1)
  131. return path
  132. def GetExitStatus(exit_code):
  133. """Returns the argument to exit(), or -1 if exit() wasn't called.
  134. Args:
  135. exit_code: the result value of os.system(command).
  136. """
  137. if os.name == 'nt':
  138. # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
  139. # the argument to exit() directly.
  140. return exit_code
  141. else:
  142. # On Unix, os.WEXITSTATUS() must be used to extract the exit status
  143. # from the result of os.system().
  144. if os.WIFEXITED(exit_code):
  145. return os.WEXITSTATUS(exit_code)
  146. else:
  147. return -1
  148. class Subprocess:
  149. def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
  150. """Changes into a specified directory, if provided, and executes a command.
  151. Restores the old directory afterwards.
  152. Args:
  153. command: The command to run, in the form of sys.argv.
  154. working_dir: The directory to change into.
  155. capture_stderr: Determines whether to capture stderr in the output member
  156. or to discard it.
  157. env: Dictionary with environment to pass to the subprocess.
  158. Returns:
  159. An object that represents outcome of the executed process. It has the
  160. following attributes:
  161. terminated_by_signal True iff the child process has been terminated
  162. by a signal.
  163. signal Sygnal that terminated the child process.
  164. exited True iff the child process exited normally.
  165. exit_code The code with which the child process exited.
  166. output Child process's stdout and stderr output
  167. combined in a string.
  168. """
  169. # The subprocess module is the preferrable way of running programs
  170. # since it is available and behaves consistently on all platforms,
  171. # including Windows. But it is only available starting in python 2.4.
  172. # In earlier python versions, we revert to the popen2 module, which is
  173. # available in python 2.0 and later but doesn't provide required
  174. # functionality (Popen4) under Windows. This allows us to support Mac
  175. # OS X 10.4 Tiger, which has python 2.3 installed.
  176. if _SUBPROCESS_MODULE_AVAILABLE:
  177. if capture_stderr:
  178. stderr = subprocess.STDOUT
  179. else:
  180. stderr = subprocess.PIPE
  181. p = subprocess.Popen(command,
  182. stdout=subprocess.PIPE, stderr=stderr,
  183. cwd=working_dir, universal_newlines=True, env=env)
  184. # communicate returns a tuple with the file obect for the child's
  185. # output.
  186. self.output = p.communicate()[0]
  187. self._return_code = p.returncode
  188. else:
  189. old_dir = os.getcwd()
  190. def _ReplaceEnvDict(dest, src):
  191. # Changes made by os.environ.clear are not inheritable by child
  192. # processes until Python 2.6. To produce inheritable changes we have
  193. # to delete environment items with the del statement.
  194. for key in dest:
  195. del dest[key]
  196. dest.update(src)
  197. # When 'env' is not None, backup the environment variables and replace
  198. # them with the passed 'env'. When 'env' is None, we simply use the
  199. # current 'os.environ' for compatibility with the subprocess.Popen
  200. # semantics used above.
  201. if env is not None:
  202. old_environ = os.environ.copy()
  203. _ReplaceEnvDict(os.environ, env)
  204. try:
  205. if working_dir is not None:
  206. os.chdir(working_dir)
  207. if capture_stderr:
  208. p = popen2.Popen4(command)
  209. else:
  210. p = popen2.Popen3(command)
  211. p.tochild.close()
  212. self.output = p.fromchild.read()
  213. ret_code = p.wait()
  214. finally:
  215. os.chdir(old_dir)
  216. # Restore the old environment variables
  217. # if they were replaced.
  218. if env is not None:
  219. _ReplaceEnvDict(os.environ, old_environ)
  220. # Converts ret_code to match the semantics of
  221. # subprocess.Popen.returncode.
  222. if os.WIFSIGNALED(ret_code):
  223. self._return_code = -os.WTERMSIG(ret_code)
  224. else: # os.WIFEXITED(ret_code) should return True here.
  225. self._return_code = os.WEXITSTATUS(ret_code)
  226. if self._return_code < 0:
  227. self.terminated_by_signal = True
  228. self.exited = False
  229. self.signal = -self._return_code
  230. else:
  231. self.terminated_by_signal = False
  232. self.exited = True
  233. self.exit_code = self._return_code
  234. def Main():
  235. """Runs the unit test."""
  236. # We must call _ParseAndStripGTestFlags() before calling
  237. # unittest.main(). Otherwise the latter will be confused by the
  238. # --gtest_* flags.
  239. _ParseAndStripGTestFlags(sys.argv)
  240. # The tested binaries should not be writing XML output files unless the
  241. # script explicitly instructs them to.
  242. # TODO(vladl@google.com): Move this into Subprocess when we implement
  243. # passing environment into it as a parameter.
  244. if GTEST_OUTPUT_VAR_NAME in os.environ:
  245. del os.environ[GTEST_OUTPUT_VAR_NAME]
  246. _test_module.main()