/Unittests/googletest/test/gtest_test_utils.py

http://unladen-swallow.googlecode.com/ · Python · 270 lines · 139 code · 43 blank · 88 comment · 31 complexity · 0611eca2af1ea691e571f6b6d0be1750 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. IS_WINDOWS = os.name == 'nt'
  50. IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
  51. # Here we expose a class from a particular module, depending on the
  52. # environment. The comment suppresses the 'Invalid variable name' lint
  53. # complaint.
  54. TestCase = _test_module.TestCase # pylint: disable-msg=C6409
  55. # Initially maps a flag to its default value. After
  56. # _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
  57. _flag_map = {'gtest_source_dir': os.path.dirname(sys.argv[0]),
  58. 'gtest_build_dir': os.path.dirname(sys.argv[0])}
  59. _gtest_flags_are_parsed = False
  60. def _ParseAndStripGTestFlags(argv):
  61. """Parses and strips Google Test flags from argv. This is idempotent."""
  62. # Suppresses the lint complaint about a global variable since we need it
  63. # here to maintain module-wide state.
  64. global _gtest_flags_are_parsed # pylint: disable-msg=W0603
  65. if _gtest_flags_are_parsed:
  66. return
  67. _gtest_flags_are_parsed = True
  68. for flag in _flag_map:
  69. # The environment variable overrides the default value.
  70. if flag.upper() in os.environ:
  71. _flag_map[flag] = os.environ[flag.upper()]
  72. # The command line flag overrides the environment variable.
  73. i = 1 # Skips the program name.
  74. while i < len(argv):
  75. prefix = '--' + flag + '='
  76. if argv[i].startswith(prefix):
  77. _flag_map[flag] = argv[i][len(prefix):]
  78. del argv[i]
  79. break
  80. else:
  81. # We don't increment i in case we just found a --gtest_* flag
  82. # and removed it from argv.
  83. i += 1
  84. def GetFlag(flag):
  85. """Returns the value of the given flag."""
  86. # In case GetFlag() is called before Main(), we always call
  87. # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
  88. # are parsed.
  89. _ParseAndStripGTestFlags(sys.argv)
  90. return _flag_map[flag]
  91. def GetSourceDir():
  92. """Returns the absolute path of the directory where the .py files are."""
  93. return os.path.abspath(GetFlag('gtest_source_dir'))
  94. def GetBuildDir():
  95. """Returns the absolute path of the directory where the test binaries are."""
  96. return os.path.abspath(GetFlag('gtest_build_dir'))
  97. _temp_dir = None
  98. def _RemoveTempDir():
  99. if _temp_dir:
  100. shutil.rmtree(_temp_dir, ignore_errors=True)
  101. atexit.register(_RemoveTempDir)
  102. def GetTempDir():
  103. """Returns a directory for temporary files."""
  104. global _temp_dir
  105. if not _temp_dir:
  106. _temp_dir = tempfile.mkdtemp()
  107. return _temp_dir
  108. def GetTestExecutablePath(executable_name):
  109. """Returns the absolute path of the test binary given its name.
  110. The function will print a message and abort the program if the resulting file
  111. doesn't exist.
  112. Args:
  113. executable_name: name of the test binary that the test script runs.
  114. Returns:
  115. The absolute path of the test binary.
  116. """
  117. path = os.path.abspath(os.path.join(GetBuildDir(), executable_name))
  118. if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
  119. path += '.exe'
  120. if not os.path.exists(path):
  121. message = (
  122. 'Unable to find the test binary. Please make sure to provide path\n'
  123. 'to the binary via the --gtest_build_dir flag or the GTEST_BUILD_DIR\n'
  124. 'environment variable. For convenient use, invoke this script via\n'
  125. 'mk_test.py.\n'
  126. # TODO(vladl@google.com): change mk_test.py to test.py after renaming
  127. # the file.
  128. 'Please run mk_test.py -h for help.')
  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):
  150. """Changes into a specified directory, if provided, and executes a command.
  151. Restores the old directory afterwards. Execution results are returned
  152. via the following attributes:
  153. terminated_by_sygnal True iff the child process has been terminated
  154. by a signal.
  155. signal Sygnal that terminated the child process.
  156. exited True iff the child process exited normally.
  157. exit_code The code with which the child proces exited.
  158. output Child process's stdout and stderr output
  159. combined in a string.
  160. Args:
  161. command: The command to run, in the form of sys.argv.
  162. working_dir: The directory to change into.
  163. capture_stderr: Determines whether to capture stderr in the output member
  164. or to discard it.
  165. """
  166. # The subprocess module is the preferrable way of running programs
  167. # since it is available and behaves consistently on all platforms,
  168. # including Windows. But it is only available starting in python 2.4.
  169. # In earlier python versions, we revert to the popen2 module, which is
  170. # available in python 2.0 and later but doesn't provide required
  171. # functionality (Popen4) under Windows. This allows us to support Mac
  172. # OS X 10.4 Tiger, which has python 2.3 installed.
  173. if _SUBPROCESS_MODULE_AVAILABLE:
  174. if capture_stderr:
  175. stderr = subprocess.STDOUT
  176. else:
  177. stderr = subprocess.PIPE
  178. p = subprocess.Popen(command,
  179. stdout=subprocess.PIPE, stderr=stderr,
  180. cwd=working_dir, universal_newlines=True)
  181. # communicate returns a tuple with the file obect for the child's
  182. # output.
  183. self.output = p.communicate()[0]
  184. self._return_code = p.returncode
  185. else:
  186. old_dir = os.getcwd()
  187. try:
  188. if working_dir is not None:
  189. os.chdir(working_dir)
  190. if capture_stderr:
  191. p = popen2.Popen4(command)
  192. else:
  193. p = popen2.Popen3(command)
  194. p.tochild.close()
  195. self.output = p.fromchild.read()
  196. ret_code = p.wait()
  197. finally:
  198. os.chdir(old_dir)
  199. # Converts ret_code to match the semantics of
  200. # subprocess.Popen.returncode.
  201. if os.WIFSIGNALED(ret_code):
  202. self._return_code = -os.WTERMSIG(ret_code)
  203. else: # os.WIFEXITED(ret_code) should return True here.
  204. self._return_code = os.WEXITSTATUS(ret_code)
  205. if self._return_code < 0:
  206. self.terminated_by_signal = True
  207. self.exited = False
  208. self.signal = -self._return_code
  209. else:
  210. self.terminated_by_signal = False
  211. self.exited = True
  212. self.exit_code = self._return_code
  213. def Main():
  214. """Runs the unit test."""
  215. # We must call _ParseAndStripGTestFlags() before calling
  216. # unittest.main(). Otherwise the latter will be confused by the
  217. # --gtest_* flags.
  218. _ParseAndStripGTestFlags(sys.argv)
  219. _test_module.main()