You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

314 lines
10 KiB

  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. signal Sygnal that terminated the child process.
  169. exited True if and only if the child process exited
  170. normally.
  171. exit_code The code with which the child process exited.
  172. output Child process's stdout and stderr output
  173. combined in a string.
  174. """
  175. # The subprocess module is the preferrable way of running programs
  176. # since it is available and behaves consistently on all platforms,
  177. # including Windows. But it is only available starting in python 2.4.
  178. # In earlier python versions, we revert to the popen2 module, which is
  179. # available in python 2.0 and later but doesn't provide required
  180. # functionality (Popen4) under Windows. This allows us to support Mac
  181. # OS X 10.4 Tiger, which has python 2.3 installed.
  182. if _SUBPROCESS_MODULE_AVAILABLE:
  183. if capture_stderr:
  184. stderr = subprocess.STDOUT
  185. else:
  186. stderr = subprocess.PIPE
  187. p = subprocess.Popen(command,
  188. stdout=subprocess.PIPE, stderr=stderr,
  189. cwd=working_dir, universal_newlines=True, env=env)
  190. # communicate returns a tuple with the file object for the child's
  191. # output.
  192. self.output = p.communicate()[0]
  193. self._return_code = p.returncode
  194. else:
  195. old_dir = os.getcwd()
  196. def _ReplaceEnvDict(dest, src):
  197. # Changes made by os.environ.clear are not inheritable by child
  198. # processes until Python 2.6. To produce inheritable changes we have
  199. # to delete environment items with the del statement.
  200. for key in dest.keys():
  201. del dest[key]
  202. dest.update(src)
  203. # When 'env' is not None, backup the environment variables and replace
  204. # them with the passed 'env'. When 'env' is None, we simply use the
  205. # current 'os.environ' for compatibility with the subprocess.Popen
  206. # semantics used above.
  207. if env is not None:
  208. old_environ = os.environ.copy()
  209. _ReplaceEnvDict(os.environ, env)
  210. try:
  211. if working_dir is not None:
  212. os.chdir(working_dir)
  213. if capture_stderr:
  214. p = popen2.Popen4(command)
  215. else:
  216. p = popen2.Popen3(command)
  217. p.tochild.close()
  218. self.output = p.fromchild.read()
  219. ret_code = p.wait()
  220. finally:
  221. os.chdir(old_dir)
  222. # Restore the old environment variables
  223. # if they were replaced.
  224. if env is not None:
  225. _ReplaceEnvDict(os.environ, old_environ)
  226. # Converts ret_code to match the semantics of
  227. # subprocess.Popen.returncode.
  228. if os.WIFSIGNALED(ret_code):
  229. self._return_code = -os.WTERMSIG(ret_code)
  230. else: # os.WIFEXITED(ret_code) should return True here.
  231. self._return_code = os.WEXITSTATUS(ret_code)
  232. if self._return_code < 0:
  233. self.terminated_by_signal = True
  234. self.exited = False
  235. self.signal = -self._return_code
  236. else:
  237. self.terminated_by_signal = False
  238. self.exited = True
  239. self.exit_code = self._return_code
  240. def Main():
  241. """Runs the unit test."""
  242. # We must call _ParseAndStripGTestFlags() before calling
  243. # unittest.main(). Otherwise the latter will be confused by the
  244. # --gtest_* flags.
  245. _ParseAndStripGTestFlags(sys.argv)
  246. # The tested binaries should not be writing XML output files unless the
  247. # script explicitly instructs them to.
  248. if GTEST_OUTPUT_VAR_NAME in os.environ:
  249. del os.environ[GTEST_OUTPUT_VAR_NAME]
  250. _test_module.main()