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