gtest_test_utils.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 subprocess
  34. import sys
  35. IS_WINDOWS = os.name == 'nt'
  36. IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
  37. IS_OS2 = os.name == 'os2'
  38. import atexit
  39. import shutil
  40. import tempfile
  41. import unittest as _test_module
  42. # pylint: enable-msg=C6204
  43. GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
  44. # The environment variable for specifying the path to the premature-exit file.
  45. PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE'
  46. environ = os.environ.copy()
  47. def SetEnvVar(env_var, value):
  48. """Sets/unsets an environment variable to a given value."""
  49. if value is not None:
  50. environ[env_var] = value
  51. elif env_var in environ:
  52. del environ[env_var]
  53. # Here we expose a class from a particular module, depending on the
  54. # environment. The comment suppresses the 'Invalid variable name' lint
  55. # complaint.
  56. TestCase = _test_module.TestCase # pylint: disable=C6409
  57. # Initially maps a flag to its default value. After
  58. # _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
  59. _flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
  60. 'build_dir': os.path.dirname(sys.argv[0])}
  61. _gtest_flags_are_parsed = False
  62. def _ParseAndStripGTestFlags(argv):
  63. """Parses and strips Google Test flags from argv. This is idempotent."""
  64. # Suppresses the lint complaint about a global variable since we need it
  65. # here to maintain module-wide state.
  66. global _gtest_flags_are_parsed # pylint: disable=W0603
  67. if _gtest_flags_are_parsed:
  68. return
  69. _gtest_flags_are_parsed = True
  70. for flag in _flag_map:
  71. # The environment variable overrides the default value.
  72. if flag.upper() in os.environ:
  73. _flag_map[flag] = os.environ[flag.upper()]
  74. # The command line flag overrides the environment variable.
  75. i = 1 # Skips the program name.
  76. while i < len(argv):
  77. prefix = '--' + flag + '='
  78. if argv[i].startswith(prefix):
  79. _flag_map[flag] = argv[i][len(prefix):]
  80. del argv[i]
  81. break
  82. else:
  83. # We don't increment i in case we just found a --gtest_* flag
  84. # and removed it from argv.
  85. i += 1
  86. def GetFlag(flag):
  87. """Returns the value of the given flag."""
  88. # In case GetFlag() is called before Main(), we always call
  89. # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
  90. # are parsed.
  91. _ParseAndStripGTestFlags(sys.argv)
  92. return _flag_map[flag]
  93. def GetSourceDir():
  94. """Returns the absolute path of the directory where the .py files are."""
  95. return os.path.abspath(GetFlag('source_dir'))
  96. def GetBuildDir():
  97. """Returns the absolute path of the directory where the test binaries are."""
  98. return os.path.abspath(GetFlag('build_dir'))
  99. _temp_dir = None
  100. def _RemoveTempDir():
  101. if _temp_dir:
  102. shutil.rmtree(_temp_dir, ignore_errors=True)
  103. atexit.register(_RemoveTempDir)
  104. def GetTempDir():
  105. global _temp_dir
  106. if not _temp_dir:
  107. _temp_dir = tempfile.mkdtemp()
  108. return _temp_dir
  109. def GetTestExecutablePath(executable_name, build_dir=None):
  110. """Returns the absolute path of the test binary given its name.
  111. The function will print a message and abort the program if the resulting file
  112. doesn't exist.
  113. Args:
  114. executable_name: name of the test binary that the test script runs.
  115. build_dir: directory where to look for executables, by default
  116. the result of GetBuildDir().
  117. Returns:
  118. The absolute path of the test binary.
  119. """
  120. path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
  121. executable_name))
  122. if (IS_WINDOWS or IS_CYGWIN or IS_OS2) and not path.endswith('.exe'):
  123. path += '.exe'
  124. if not os.path.exists(path):
  125. message = (
  126. 'Unable to find the test binary "%s". Please make sure to provide\n'
  127. 'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
  128. 'environment variable.' % path)
  129. print(message, file=sys.stderr)
  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, env=None):
  150. """Changes into a specified directory, if provided, and executes a command.
  151. Restores the old directory afterwards.
  152. Args:
  153. command: The command to run, in the form of sys.argv.
  154. working_dir: The directory to change into.
  155. capture_stderr: Determines whether to capture stderr in the output member
  156. or to discard it.
  157. env: Dictionary with environment to pass to the subprocess.
  158. Returns:
  159. An object that represents outcome of the executed process. It has the
  160. following attributes:
  161. terminated_by_signal True if and only if the child process has been
  162. terminated by a signal.
  163. exited True if and only if the child process exited
  164. normally.
  165. exit_code The code with which the child process exited.
  166. output Child process's stdout and stderr output
  167. combined in a string.
  168. """
  169. if capture_stderr:
  170. stderr = subprocess.STDOUT
  171. else:
  172. stderr = subprocess.PIPE
  173. p = subprocess.Popen(command,
  174. stdout=subprocess.PIPE, stderr=stderr,
  175. cwd=working_dir, universal_newlines=True, env=env)
  176. # communicate returns a tuple with the file object for the child's
  177. # output.
  178. self.output = p.communicate()[0]
  179. self._return_code = p.returncode
  180. if bool(self._return_code & 0x80000000):
  181. self.terminated_by_signal = True
  182. self.exited = False
  183. else:
  184. self.terminated_by_signal = False
  185. self.exited = True
  186. self.exit_code = self._return_code
  187. def Main():
  188. """Runs the unit test."""
  189. # We must call _ParseAndStripGTestFlags() before calling
  190. # unittest.main(). Otherwise the latter will be confused by the
  191. # --gtest_* flags.
  192. _ParseAndStripGTestFlags(sys.argv)
  193. # The tested binaries should not be writing XML output files unless the
  194. # script explicitly instructs them to.
  195. if GTEST_OUTPUT_VAR_NAME in os.environ:
  196. del os.environ[GTEST_OUTPUT_VAR_NAME]
  197. _test_module.main()