googletest/googletest/test/gtest_test_utils.py
Go to the documentation of this file.
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 
30 """Unit test utilities for Google C++ Testing and Mocking Framework."""
31 # Suppresses the 'Import not at the top of the file' lint complaint.
32 # pylint: disable-msg=C6204
33 
34 import os
35 import subprocess
36 import sys
37 
38 IS_WINDOWS = os.name == 'nt'
39 IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
40 IS_OS2 = os.name == 'os2'
41 
42 import atexit
43 import shutil
44 import tempfile
45 import unittest as _test_module
46 # pylint: enable-msg=C6204
47 
48 GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
49 
50 # The environment variable for specifying the path to the premature-exit file.
51 PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE'
52 
53 environ = os.environ.copy()
54 
55 
56 def SetEnvVar(env_var, value):
57  """Sets/unsets an environment variable to a given value."""
58 
59  if value is not None:
60  environ[env_var] = value
61  elif env_var in environ:
62  del environ[env_var]
63 
64 
65 # Here we expose a class from a particular module, depending on the
66 # environment. The comment suppresses the 'Invalid variable name' lint
67 # complaint.
68 TestCase = _test_module.TestCase # pylint: disable=C6409
69 
70 # Initially maps a flag to its default value. After
71 # _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
72 _flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
73  'build_dir': os.path.dirname(sys.argv[0])}
74 _gtest_flags_are_parsed = False
75 
76 
77 def _ParseAndStripGTestFlags(argv):
78  """Parses and strips Google Test flags from argv. This is idempotent."""
79 
80  # Suppresses the lint complaint about a global variable since we need it
81  # here to maintain module-wide state.
82  global _gtest_flags_are_parsed # pylint: disable=W0603
83  if _gtest_flags_are_parsed:
84  return
85 
86  _gtest_flags_are_parsed = True
87  for flag in _flag_map:
88  # The environment variable overrides the default value.
89  if flag.upper() in os.environ:
90  _flag_map[flag] = os.environ[flag.upper()]
91 
92  # The command line flag overrides the environment variable.
93  i = 1 # Skips the program name.
94  while i < len(argv):
95  prefix = '--' + flag + '='
96  if argv[i].startswith(prefix):
97  _flag_map[flag] = argv[i][len(prefix):]
98  del argv[i]
99  break
100  else:
101  # We don't increment i in case we just found a --gtest_* flag
102  # and removed it from argv.
103  i += 1
104 
105 
106 def GetFlag(flag):
107  """Returns the value of the given flag."""
108 
109  # In case GetFlag() is called before Main(), we always call
110  # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
111  # are parsed.
112  _ParseAndStripGTestFlags(sys.argv)
113 
114  return _flag_map[flag]
115 
116 
117 def GetSourceDir():
118  """Returns the absolute path of the directory where the .py files are."""
119 
120  return os.path.abspath(GetFlag('source_dir'))
121 
122 
123 def GetBuildDir():
124  """Returns the absolute path of the directory where the test binaries are."""
125 
126  return os.path.abspath(GetFlag('build_dir'))
127 
128 
129 _temp_dir = None
130 
131 def _RemoveTempDir():
132  if _temp_dir:
133  shutil.rmtree(_temp_dir, ignore_errors=True)
134 
135 atexit.register(_RemoveTempDir)
136 
137 
138 def GetTempDir():
139  global _temp_dir
140  if not _temp_dir:
141  _temp_dir = tempfile.mkdtemp()
142  return _temp_dir
143 
144 
145 def GetTestExecutablePath(executable_name, build_dir=None):
146  """Returns the absolute path of the test binary given its name.
147 
148  The function will print a message and abort the program if the resulting file
149  doesn't exist.
150 
151  Args:
152  executable_name: name of the test binary that the test script runs.
153  build_dir: directory where to look for executables, by default
154  the result of GetBuildDir().
155 
156  Returns:
157  The absolute path of the test binary.
158  """
159 
160  path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
161  executable_name))
162  if (IS_WINDOWS or IS_CYGWIN or IS_OS2) and not path.endswith('.exe'):
163  path += '.exe'
164 
165  if not os.path.exists(path):
166  message = (
167  'Unable to find the test binary "%s". Please make sure to provide\n'
168  'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
169  'environment variable.' % path)
170  print(message, file=sys.stderr)
171  sys.exit(1)
172 
173  return path
174 
175 
176 def GetExitStatus(exit_code):
177  """Returns the argument to exit(), or -1 if exit() wasn't called.
178 
179  Args:
180  exit_code: the result value of os.system(command).
181  """
182 
183  if os.name == 'nt':
184  # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
185  # the argument to exit() directly.
186  return exit_code
187  else:
188  # On Unix, os.WEXITSTATUS() must be used to extract the exit status
189  # from the result of os.system().
190  if os.WIFEXITED(exit_code):
191  return os.WEXITSTATUS(exit_code)
192  else:
193  return -1
194 
195 
196 class Subprocess:
197  def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
198  """Changes into a specified directory, if provided, and executes a command.
199 
200  Restores the old directory afterwards.
201 
202  Args:
203  command: The command to run, in the form of sys.argv.
204  working_dir: The directory to change into.
205  capture_stderr: Determines whether to capture stderr in the output member
206  or to discard it.
207  env: Dictionary with environment to pass to the subprocess.
208 
209  Returns:
210  An object that represents outcome of the executed process. It has the
211  following attributes:
212  terminated_by_signal True if and only if the child process has been
213  terminated by a signal.
214  exited True if and only if the child process exited
215  normally.
216  exit_code The code with which the child process exited.
217  output Child process's stdout and stderr output
218  combined in a string.
219  """
220 
221  if capture_stderr:
222  stderr = subprocess.STDOUT
223  else:
224  stderr = subprocess.PIPE
225 
226  p = subprocess.Popen(command,
227  stdout=subprocess.PIPE, stderr=stderr,
228  cwd=working_dir, universal_newlines=True, env=env)
229  # communicate returns a tuple with the file object for the child's
230  # output.
231  self.output = p.communicate()[0]
232  self._return_code = p.returncode
233 
234  if bool(self._return_code & 0x80000000):
235  self.terminated_by_signal = True
236  self.exited = False
237  else:
238  self.terminated_by_signal = False
239  self.exited = True
240  self.exit_code = self._return_code
241 
242 
243 def Main():
244  """Runs the unit test."""
245 
246  # We must call _ParseAndStripGTestFlags() before calling
247  # unittest.main(). Otherwise the latter will be confused by the
248  # --gtest_* flags.
249  _ParseAndStripGTestFlags(sys.argv)
250  # The tested binaries should not be writing XML output files unless the
251  # script explicitly instructs them to.
252  if GTEST_OUTPUT_VAR_NAME in os.environ:
253  del os.environ[GTEST_OUTPUT_VAR_NAME]
254 
255  _test_module.main()
gtest_test_utils.Subprocess.output
output
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:245
Subprocess
Definition: memory_usage_test.cc:39
gtest_test_utils.Subprocess._return_code
_return_code
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:246
gtest_test_utils.GetExitStatus
def GetExitStatus(exit_code)
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:182
gtest_test_utils.Subprocess.__init__
def __init__(self, command, working_dir=None, capture_stderr=True, env=None)
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:203
gtest_test_utils._RemoveTempDir
def _RemoveTempDir()
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:137
gtest_test_utils.GetTempDir
def GetTempDir()
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:144
gtest_test_utils.GetTestExecutablePath
def GetTestExecutablePath(executable_name, build_dir=None)
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:151
gtest_test_utils.Subprocess.terminated_by_signal
terminated_by_signal
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:292
gtest_test_utils.Subprocess.exited
exited
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:293
gtest_test_utils.GetSourceDir
def GetSourceDir()
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:123
gtest_test_utils.SetEnvVar
def SetEnvVar(env_var, value)
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:62
gtest_test_utils.GetBuildDir
def GetBuildDir()
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:129
gtest_test_utils._ParseAndStripGTestFlags
def _ParseAndStripGTestFlags(argv)
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:83
gtest_test_utils.Main
def Main()
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:301
len
int len
Definition: abseil-cpp/absl/base/internal/low_level_alloc_test.cc:46
gtest_test_utils.GetFlag
def GetFlag(flag)
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:112
gtest_test_utils.Subprocess.exit_code
exit_code
Definition: bloaty/third_party/googletest/googletest/test/gtest_test_utils.py:298


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:55