gtest_test_utils.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 #
00003 # Copyright 2006, Google Inc.
00004 # All rights reserved.
00005 #
00006 # Redistribution and use in source and binary forms, with or without
00007 # modification, are permitted provided that the following conditions are
00008 # met:
00009 #
00010 #     * Redistributions of source code must retain the above copyright
00011 # notice, this list of conditions and the following disclaimer.
00012 #     * Redistributions in binary form must reproduce the above
00013 # copyright notice, this list of conditions and the following disclaimer
00014 # in the documentation and/or other materials provided with the
00015 # distribution.
00016 #     * Neither the name of Google Inc. nor the names of its
00017 # contributors may be used to endorse or promote products derived from
00018 # this software without specific prior written permission.
00019 #
00020 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00021 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00022 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00023 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00024 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00025 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00026 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00027 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00028 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00029 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00030 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00031 
00032 """Unit test utilities for Google C++ Testing Framework."""
00033 
00034 __author__ = 'wan@google.com (Zhanyong Wan)'
00035 
00036 import atexit
00037 import os
00038 import shutil
00039 import sys
00040 import tempfile
00041 import unittest
00042 _test_module = unittest
00043 
00044 # Suppresses the 'Import not at the top of the file' lint complaint.
00045 # pylint: disable-msg=C6204
00046 try:
00047   import subprocess
00048   _SUBPROCESS_MODULE_AVAILABLE = True
00049 except:
00050   import popen2
00051   _SUBPROCESS_MODULE_AVAILABLE = False
00052 # pylint: enable-msg=C6204
00053 
00054 GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'
00055 
00056 IS_WINDOWS = os.name == 'nt'
00057 IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
00058 
00059 # The environment variable for specifying the path to the premature-exit file.
00060 PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE'
00061 
00062 environ = os.environ.copy()
00063 
00064 
00065 def SetEnvVar(env_var, value):
00066   """Sets/unsets an environment variable to a given value."""
00067 
00068   if value is not None:
00069     environ[env_var] = value
00070   elif env_var in environ:
00071     del environ[env_var]
00072 
00073 
00074 # Here we expose a class from a particular module, depending on the
00075 # environment. The comment suppresses the 'Invalid variable name' lint
00076 # complaint.
00077 TestCase = _test_module.TestCase  # pylint: disable-msg=C6409
00078 
00079 # Initially maps a flag to its default value. After
00080 # _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
00081 _flag_map = {'source_dir': os.path.dirname(sys.argv[0]),
00082              'build_dir': os.path.dirname(sys.argv[0])}
00083 _gtest_flags_are_parsed = False
00084 
00085 
00086 def _ParseAndStripGTestFlags(argv):
00087   """Parses and strips Google Test flags from argv.  This is idempotent."""
00088 
00089   # Suppresses the lint complaint about a global variable since we need it
00090   # here to maintain module-wide state.
00091   global _gtest_flags_are_parsed  # pylint: disable-msg=W0603
00092   if _gtest_flags_are_parsed:
00093     return
00094 
00095   _gtest_flags_are_parsed = True
00096   for flag in _flag_map:
00097     # The environment variable overrides the default value.
00098     if flag.upper() in os.environ:
00099       _flag_map[flag] = os.environ[flag.upper()]
00100 
00101     # The command line flag overrides the environment variable.
00102     i = 1  # Skips the program name.
00103     while i < len(argv):
00104       prefix = '--' + flag + '='
00105       if argv[i].startswith(prefix):
00106         _flag_map[flag] = argv[i][len(prefix):]
00107         del argv[i]
00108         break
00109       else:
00110         # We don't increment i in case we just found a --gtest_* flag
00111         # and removed it from argv.
00112         i += 1
00113 
00114 
00115 def GetFlag(flag):
00116   """Returns the value of the given flag."""
00117 
00118   # In case GetFlag() is called before Main(), we always call
00119   # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
00120   # are parsed.
00121   _ParseAndStripGTestFlags(sys.argv)
00122 
00123   return _flag_map[flag]
00124 
00125 
00126 def GetSourceDir():
00127   """Returns the absolute path of the directory where the .py files are."""
00128 
00129   return os.path.abspath(GetFlag('source_dir'))
00130 
00131 
00132 def GetBuildDir():
00133   """Returns the absolute path of the directory where the test binaries are."""
00134 
00135   return os.path.abspath(GetFlag('build_dir'))
00136 
00137 
00138 _temp_dir = None
00139 
00140 def _RemoveTempDir():
00141   if _temp_dir:
00142     shutil.rmtree(_temp_dir, ignore_errors=True)
00143 
00144 atexit.register(_RemoveTempDir)
00145 
00146 
00147 def GetTempDir():
00148   """Returns a directory for temporary files."""
00149 
00150   global _temp_dir
00151   if not _temp_dir:
00152     _temp_dir = tempfile.mkdtemp()
00153   return _temp_dir
00154 
00155 
00156 def GetTestExecutablePath(executable_name, build_dir=None):
00157   """Returns the absolute path of the test binary given its name.
00158 
00159   The function will print a message and abort the program if the resulting file
00160   doesn't exist.
00161 
00162   Args:
00163     executable_name: name of the test binary that the test script runs.
00164     build_dir:       directory where to look for executables, by default
00165                      the result of GetBuildDir().
00166 
00167   Returns:
00168     The absolute path of the test binary.
00169   """
00170 
00171   path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),
00172                                       executable_name))
00173   if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
00174     path += '.exe'
00175 
00176   if not os.path.exists(path):
00177     message = (
00178         'Unable to find the test binary "%s". Please make sure to provide\n'
00179         'a path to the binary via the --build_dir flag or the BUILD_DIR\n'
00180         'environment variable.' % path)
00181     print >> sys.stderr, message
00182     sys.exit(1)
00183 
00184   return path
00185 
00186 
00187 def GetExitStatus(exit_code):
00188   """Returns the argument to exit(), or -1 if exit() wasn't called.
00189 
00190   Args:
00191     exit_code: the result value of os.system(command).
00192   """
00193 
00194   if os.name == 'nt':
00195     # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
00196     # the argument to exit() directly.
00197     return exit_code
00198   else:
00199     # On Unix, os.WEXITSTATUS() must be used to extract the exit status
00200     # from the result of os.system().
00201     if os.WIFEXITED(exit_code):
00202       return os.WEXITSTATUS(exit_code)
00203     else:
00204       return -1
00205 
00206 
00207 class Subprocess:
00208   def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
00209     """Changes into a specified directory, if provided, and executes a command.
00210 
00211     Restores the old directory afterwards.
00212 
00213     Args:
00214       command:        The command to run, in the form of sys.argv.
00215       working_dir:    The directory to change into.
00216       capture_stderr: Determines whether to capture stderr in the output member
00217                       or to discard it.
00218       env:            Dictionary with environment to pass to the subprocess.
00219 
00220     Returns:
00221       An object that represents outcome of the executed process. It has the
00222       following attributes:
00223         terminated_by_signal   True iff the child process has been terminated
00224                                by a signal.
00225         signal                 Sygnal that terminated the child process.
00226         exited                 True iff the child process exited normally.
00227         exit_code              The code with which the child process exited.
00228         output                 Child process's stdout and stderr output
00229                                combined in a string.
00230     """
00231 
00232     # The subprocess module is the preferrable way of running programs
00233     # since it is available and behaves consistently on all platforms,
00234     # including Windows. But it is only available starting in python 2.4.
00235     # In earlier python versions, we revert to the popen2 module, which is
00236     # available in python 2.0 and later but doesn't provide required
00237     # functionality (Popen4) under Windows. This allows us to support Mac
00238     # OS X 10.4 Tiger, which has python 2.3 installed.
00239     if _SUBPROCESS_MODULE_AVAILABLE:
00240       if capture_stderr:
00241         stderr = subprocess.STDOUT
00242       else:
00243         stderr = subprocess.PIPE
00244 
00245       p = subprocess.Popen(command,
00246                            stdout=subprocess.PIPE, stderr=stderr,
00247                            cwd=working_dir, universal_newlines=True, env=env)
00248       # communicate returns a tuple with the file obect for the child's
00249       # output.
00250       self.output = p.communicate()[0]
00251       self._return_code = p.returncode
00252     else:
00253       old_dir = os.getcwd()
00254 
00255       def _ReplaceEnvDict(dest, src):
00256         # Changes made by os.environ.clear are not inheritable by child
00257         # processes until Python 2.6. To produce inheritable changes we have
00258         # to delete environment items with the del statement.
00259         for key in dest.keys():
00260           del dest[key]
00261         dest.update(src)
00262 
00263       # When 'env' is not None, backup the environment variables and replace
00264       # them with the passed 'env'. When 'env' is None, we simply use the
00265       # current 'os.environ' for compatibility with the subprocess.Popen
00266       # semantics used above.
00267       if env is not None:
00268         old_environ = os.environ.copy()
00269         _ReplaceEnvDict(os.environ, env)
00270 
00271       try:
00272         if working_dir is not None:
00273           os.chdir(working_dir)
00274         if capture_stderr:
00275           p = popen2.Popen4(command)
00276         else:
00277           p = popen2.Popen3(command)
00278         p.tochild.close()
00279         self.output = p.fromchild.read()
00280         ret_code = p.wait()
00281       finally:
00282         os.chdir(old_dir)
00283 
00284         # Restore the old environment variables
00285         # if they were replaced.
00286         if env is not None:
00287           _ReplaceEnvDict(os.environ, old_environ)
00288 
00289       # Converts ret_code to match the semantics of
00290       # subprocess.Popen.returncode.
00291       if os.WIFSIGNALED(ret_code):
00292         self._return_code = -os.WTERMSIG(ret_code)
00293       else:  # os.WIFEXITED(ret_code) should return True here.
00294         self._return_code = os.WEXITSTATUS(ret_code)
00295 
00296     if self._return_code < 0:
00297       self.terminated_by_signal = True
00298       self.exited = False
00299       self.signal = -self._return_code
00300     else:
00301       self.terminated_by_signal = False
00302       self.exited = True
00303       self.exit_code = self._return_code
00304 
00305 
00306 def Main():
00307   """Runs the unit test."""
00308 
00309   # We must call _ParseAndStripGTestFlags() before calling
00310   # unittest.main().  Otherwise the latter will be confused by the
00311   # --gtest_* flags.
00312   _ParseAndStripGTestFlags(sys.argv)
00313   # The tested binaries should not be writing XML output files unless the
00314   # script explicitly instructs them to.
00315   # TODO(vladl@google.com): Move this into Subprocess when we implement
00316   # passing environment into it as a parameter.
00317   if GTEST_OUTPUT_VAR_NAME in os.environ:
00318     del os.environ[GTEST_OUTPUT_VAR_NAME]
00319 
00320   _test_module.main()


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:04