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