gtest_test_utils.py 10 KB

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