Home | History | Annotate | Download | only in test
      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 
     32 """Unit test utilities for Google C++ Testing Framework."""
     33 
     34 __author__ = 'wan (at] google.com (Zhanyong Wan)'
     35 
     36 import os
     37 import sys
     38 import unittest
     39 
     40 try:
     41   import subprocess
     42   _SUBPROCESS_MODULE_AVAILABLE = True
     43 except:
     44   import popen2
     45   _SUBPROCESS_MODULE_AVAILABLE = False
     46 
     47 
     48 # Initially maps a flag to its default value.  After
     49 # _ParseAndStripGTestFlags() is called, maps a flag to its actual
     50 # value.
     51 _flag_map = {'gtest_source_dir': os.path.dirname(sys.argv[0]),
     52              'gtest_build_dir': os.path.dirname(sys.argv[0])}
     53 _gtest_flags_are_parsed = False
     54 
     55 
     56 def _ParseAndStripGTestFlags(argv):
     57   """Parses and strips Google Test flags from argv.  This is idempotent."""
     58 
     59   global _gtest_flags_are_parsed
     60   if _gtest_flags_are_parsed:
     61     return
     62 
     63   _gtest_flags_are_parsed = True
     64   for flag in _flag_map:
     65     # The environment variable overrides the default value.
     66     if flag.upper() in os.environ:
     67       _flag_map[flag] = os.environ[flag.upper()]
     68 
     69     # The command line flag overrides the environment variable.
     70     i = 1  # Skips the program name.
     71     while i < len(argv):
     72       prefix = '--' + flag + '='
     73       if argv[i].startswith(prefix):
     74         _flag_map[flag] = argv[i][len(prefix):]
     75         del argv[i]
     76         break
     77       else:
     78         # We don't increment i in case we just found a --gtest_* flag
     79         # and removed it from argv.
     80         i += 1
     81 
     82 
     83 def GetFlag(flag):
     84   """Returns the value of the given flag."""
     85 
     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 
     91   return _flag_map[flag]
     92 
     93 
     94 def GetSourceDir():
     95   """Returns the absolute path of the directory where the .py files are."""
     96 
     97   return os.path.abspath(GetFlag('gtest_source_dir'))
     98 
     99 
    100 def GetBuildDir():
    101   """Returns the absolute path of the directory where the test binaries are."""
    102 
    103   return os.path.abspath(GetFlag('gtest_build_dir'))
    104 
    105 
    106 def GetExitStatus(exit_code):
    107   """Returns the argument to exit(), or -1 if exit() wasn't called.
    108 
    109   Args:
    110     exit_code: the result value of os.system(command).
    111   """
    112 
    113   if os.name == 'nt':
    114     # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
    115     # the argument to exit() directly.
    116     return exit_code
    117   else:
    118     # On Unix, os.WEXITSTATUS() must be used to extract the exit status
    119     # from the result of os.system().
    120     if os.WIFEXITED(exit_code):
    121       return os.WEXITSTATUS(exit_code)
    122     else:
    123       return -1
    124 
    125 
    126 class Subprocess:
    127   def __init__(self, command, working_dir=None):
    128     """Changes into a specified directory, if provided, and executes a command.
    129     Restores the old directory afterwards. Execution results are returned
    130     via the following attributes:
    131       terminated_by_sygnal   True iff the child process has been terminated
    132                              by a signal.
    133       signal                 Sygnal that terminated the child process.
    134       exited                 True iff the child process exited normally.
    135       exit_code              The code with which the child proces exited.
    136       output                 Child process's stdout and stderr output
    137                              combined in a string.
    138 
    139     Args:
    140       command: A command to run, in the form of sys.argv.
    141       working_dir: A directory to change into.
    142     """
    143 
    144     # The subprocess module is the preferrable way of running programs
    145     # since it is available and behaves consistently on all platforms,
    146     # including Windows. But it is only available starting in python 2.4.
    147     # In earlier python versions, we revert to the popen2 module, which is
    148     # available in python 2.0 and later but doesn't provide required
    149     # functionality (Popen4) under Windows. This allows us to support Mac
    150     # OS X 10.4 Tiger, which has python 2.3 installed.
    151     if _SUBPROCESS_MODULE_AVAILABLE:
    152       p = subprocess.Popen(command,
    153                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
    154                            cwd=working_dir, universal_newlines=True)
    155       # communicate returns a tuple with the file obect for the child's
    156       # output.
    157       self.output = p.communicate()[0]
    158       self._return_code = p.returncode
    159     else:
    160       old_dir = os.getcwd()
    161       try:
    162         if working_dir is not None:
    163           os.chdir(working_dir)
    164         p = popen2.Popen4(command)
    165         p.tochild.close()
    166         self.output = p.fromchild.read()
    167         ret_code = p.wait()
    168       finally:
    169         os.chdir(old_dir)
    170       # Converts ret_code to match the semantics of
    171       # subprocess.Popen.returncode.
    172       if os.WIFSIGNALED(ret_code):
    173         self._return_code = -os.WTERMSIG(ret_code)
    174       else:  # os.WIFEXITED(ret_code) should return True here.
    175         self._return_code = os.WEXITSTATUS(ret_code)
    176 
    177     if self._return_code < 0:
    178       self.terminated_by_signal = True
    179       self.exited = False
    180       self.signal = -self._return_code
    181     else:
    182       self.terminated_by_signal = False
    183       self.exited = True
    184       self.exit_code = self._return_code
    185 
    186 
    187 def Main():
    188   """Runs the unit test."""
    189 
    190   # We must call _ParseAndStripGTestFlags() before calling
    191   # unittest.main().  Otherwise the latter will be confused by the
    192   # --gtest_* flags.
    193   _ParseAndStripGTestFlags(sys.argv)
    194   unittest.main()
    195