gtest_test_utils.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. import atexit
  37. import shutil
  38. import tempfile
  39. import unittest as _test_module
  40. try:
  41. import subprocess
  42. _SUBPROCESS_MODULE_AVAILABLE = True
  43. except:
  44. import popen2
  45. _SUBPROCESS_MODULE_AVAILABLE = False
  46. # pylint: enable-msg=C6204
  47. GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
  48. # The environment variable for specifying the path to the premature-exit file.
  49. PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE'
  50. environ = os.environ.copy()
  51. def SetEnvVar(env_var, value):
  52. """Sets/unsets an environment variable to a given value."""
  53. if value is not None:
  54. environ[env_var] = value
  55. elif env_var in environ:
  56. del environ[env_var]
  57. # Here we expose a class from a particular module, depending on the
  58. # environment. The comment suppresses the 'Invalid variable name' lint
  59. # complaint.
  60. TestCase = _test_module.TestCase # pylint: disable=C6409
  61. # Initially maps a flag to its default value. After
  62. # _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
  63. _flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
  64. 'build_dir': os.path.dirname(sys.argv[0])}
  65. _gtest_flags_are_parsed = False
  66. def _ParseAndStripGTestFlags(argv):
  67. """Parses and strips Google Test flags from argv. This is idempotent."""
  68. # Suppresses the lint complaint about a global variable since we need it
  69. # here to maintain module-wide state.
  70. global _gtest_flags_are_parsed # pylint: disable=W0603
  71. if _gtest_flags_are_parsed:
  72. return
  73. _gtest_flags_are_parsed = True
  74. for flag in _flag_map:
  75. # The environment variable overrides the default value.
  76. if flag.upper() in os.environ:
  77. _flag_map[flag] = os.environ[flag.upper()]
  78. # The command line flag overrides the environment variable.
  79. i = 1 # Skips the program name.
  80. while i < len(argv):
  81. prefix = '--' + flag + '='
  82. if argv[i].startswith(prefix):
  83. _flag_map[flag] = argv[i][len(prefix):]
  84. del argv[i]
  85. break
  86. else:
  87. # We don't increment i in case we just found a --gtest_* flag
  88. # and removed it from argv.
  89. i += 1
  90. def GetFlag(flag):
  91. """Returns the value of the given flag."""
  92. # In case GetFlag() is called before Main(), we always call
  93. # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
  94. # are parsed.
  95. _ParseAndStripGTestFlags(sys.argv)
  96. return _flag_map[flag]
  97. def GetSourceDir():
  98. """Returns the absolute path of the directory where the .py files are."""
  99. return os.path.abspath(GetFlag('source_dir'))
  100. def GetBuildDir():
  101. """Returns the absolute path of the directory where the test binaries are."""
  102. return os.path.abspath(GetFlag('build_dir'))
  103. _temp_dir = None
  104. def _RemoveTempDir():
  105. if _temp_dir:
  106. shutil.rmtree(_temp_dir, ignore_errors=True)
  107. atexit.register(_RemoveTempDir)
  108. def GetTempDir():
  109. global _temp_dir
  110. if not _temp_dir:
  111. _temp_dir = tempfile.mkdtemp()
  112. return _temp_dir
  113. def GetTestExecutablePath(executable_name, build_dir=None):
  114. """Returns the absolute path of the test binary given its name.
  115. The function will print a message and abort the program if the resulting file
  116. doesn't exist.
  117. Args:
  118. executable_name: name of the test binary that the test script runs.
  119. build_dir: directory where to look for executables, by default
  120. the result of GetBuildDir().
  121. Returns:
  122. The absolute path of the test binary.
  123. """
  124. path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
  125. executable_name))
  126. if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
  127. path += '.exe'
  128. if not os.path.exists(path):
  129. message = (
  130. 'Unable to find the test binary "%s". Please make sure to provide\n'
  131. 'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
  132. 'environment variable.' % path)
  133. print >> sys.stderr, message
  134. sys.exit(1)
  135. return path
  136. def GetExitStatus(exit_code):
  137. """Returns the argument to exit(), or -1 if exit() wasn't called.
  138. Args:
  139. exit_code: the result value of os.system(command).
  140. """
  141. if os.name == 'nt':
  142. # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
  143. # the argument to exit() directly.
  144. return exit_code
  145. else:
  146. # On Unix, os.WEXITSTATUS() must be used to extract the exit status
  147. # from the result of os.system().
  148. if os.WIFEXITED(exit_code):
  149. return os.WEXITSTATUS(exit_code)
  150. else:
  151. return -1
  152. class Subprocess:
  153. def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
  154. """Changes into a specified directory, if provided, and executes a command.
  155. Restores the old directory afterwards.
  156. Args:
  157. command: The command to run, in the form of sys.argv.
  158. working_dir: The directory to change into.
  159. capture_stderr: Determines whether to capture stderr in the output member
  160. or to discard it.
  161. env: Dictionary with environment to pass to the subprocess.
  162. Returns:
  163. An object that represents outcome of the executed process. It has the
  164. following attributes:
  165. terminated_by_signal True iff the child process has been terminated
  166. by a signal.
  167. signal Sygnal that terminated the child process.
  168. exited True iff the child process exited normally.
  169. exit_code The code with which the child process exited.
  170. output Child process's stdout and stderr output
  171. combined in a string.
  172. """
  173. # The subprocess module is the preferrable way of running programs
  174. # since it is available and behaves consistently on all platforms,
  175. # including Windows. But it is only available starting in python 2.4.
  176. # In earlier python versions, we revert to the popen2 module, which is
  177. # available in python 2.0 and later but doesn't provide required
  178. # functionality (Popen4) under Windows. This allows us to support Mac
  179. # OS X 10.4 Tiger, which has python 2.3 installed.
  180. if _SUBPROCESS_MODULE_AVAILABLE:
  181. if capture_stderr:
  182. stderr = subprocess.STDOUT
  183. else:
  184. stderr = subprocess.PIPE
  185. p = subprocess.Popen(command,
  186. stdout=subprocess.PIPE, stderr=stderr,
  187. cwd=working_dir, universal_newlines=True, env=env)
  188. # communicate returns a tuple with the file object for the child's
  189. # output.
  190. self.output = p.communicate()[0]
  191. self._return_code = p.returncode
  192. else:
  193. old_dir = os.getcwd()
  194. def _ReplaceEnvDict(dest, src):
  195. # Changes made by os.environ.clear are not inheritable by child
  196. # processes until Python 2.6. To produce inheritable changes we have
  197. # to delete environment items with the del statement.
  198. for key in dest.keys():
  199. del dest[key]
  200. dest.update(src)
  201. # When 'env' is not None, backup the environment variables and replace
  202. # them with the passed 'env'. When 'env' is None, we simply use the
  203. # current 'os.environ' for compatibility with the subprocess.Popen
  204. # semantics used above.
  205. if env is not None:
  206. old_environ = os.environ.copy()
  207. _ReplaceEnvDict(os.environ, env)
  208. try:
  209. if working_dir is not None:
  210. os.chdir(working_dir)
  211. if capture_stderr:
  212. p = popen2.Popen4(command)
  213. else:
  214. p = popen2.Popen3(command)
  215. p.tochild.close()
  216. self.output = p.fromchild.read()
  217. ret_code = p.wait()
  218. finally:
  219. os.chdir(old_dir)
  220. # Restore the old environment variables
  221. # if they were replaced.
  222. if env is not None:
  223. _ReplaceEnvDict(os.environ, old_environ)
  224. # Converts ret_code to match the semantics of
  225. # subprocess.Popen.returncode.
  226. if os.WIFSIGNALED(ret_code):
  227. self._return_code = -os.WTERMSIG(ret_code)
  228. else: # os.WIFEXITED(ret_code) should return True here.
  229. self._return_code = os.WEXITSTATUS(ret_code)
  230. if self._return_code < 0:
  231. self.terminated_by_signal = True
  232. self.exited = False
  233. self.signal = -self._return_code
  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. # FIXME: Move this into Subprocess when we implement
  247. # passing environment into it as a parameter.
  248. if GTEST_OUTPUT_VAR_NAME in os.environ:
  249. del os.environ[GTEST_OUTPUT_VAR_NAME]
  250. _test_module.main()