gtest_test_utils.py 11 KB

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