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@google.com (Zhanyong Wan)'
35
36import atexit
37import os
38import shutil
39import sys
40import tempfile
41import unittest
42_test_module = unittest
43
44# Suppresses the 'Import not at the top of the file' lint complaint.
45# pylint: disable-msg=C6204
46try:
47  import subprocess
48  _SUBPROCESS_MODULE_AVAILABLE = True
49except:
50  import popen2
51  _SUBPROCESS_MODULE_AVAILABLE = False
52# pylint: enable-msg=C6204
53
54
55IS_WINDOWS = os.name == 'nt'
56IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]
57
58# Here we expose a class from a particular module, depending on the
59# environment. The comment suppresses the 'Invalid variable name' lint
60# complaint.
61TestCase = _test_module.TestCase  # pylint: disable-msg=C6409
62
63# Initially maps a flag to its default value. After
64# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.
65_flag_map = {'gtest_source_dir': os.path.dirname(sys.argv[0]),
66             'gtest_build_dir': os.path.dirname(sys.argv[0])}
67_gtest_flags_are_parsed = False
68
69
70def _ParseAndStripGTestFlags(argv):
71  """Parses and strips Google Test flags from argv.  This is idempotent."""
72
73  # Suppresses the lint complaint about a global variable since we need it
74  # here to maintain module-wide state.
75  global _gtest_flags_are_parsed  # pylint: disable-msg=W0603
76  if _gtest_flags_are_parsed:
77    return
78
79  _gtest_flags_are_parsed = True
80  for flag in _flag_map:
81    # The environment variable overrides the default value.
82    if flag.upper() in os.environ:
83      _flag_map[flag] = os.environ[flag.upper()]
84
85    # The command line flag overrides the environment variable.
86    i = 1  # Skips the program name.
87    while i < len(argv):
88      prefix = '--' + flag + '='
89      if argv[i].startswith(prefix):
90        _flag_map[flag] = argv[i][len(prefix):]
91        del argv[i]
92        break
93      else:
94        # We don't increment i in case we just found a --gtest_* flag
95        # and removed it from argv.
96        i += 1
97
98
99def GetFlag(flag):
100  """Returns the value of the given flag."""
101
102  # In case GetFlag() is called before Main(), we always call
103  # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
104  # are parsed.
105  _ParseAndStripGTestFlags(sys.argv)
106
107  return _flag_map[flag]
108
109
110def GetSourceDir():
111  """Returns the absolute path of the directory where the .py files are."""
112
113  return os.path.abspath(GetFlag('gtest_source_dir'))
114
115
116def GetBuildDir():
117  """Returns the absolute path of the directory where the test binaries are."""
118
119  return os.path.abspath(GetFlag('gtest_build_dir'))
120
121
122_temp_dir = None
123
124def _RemoveTempDir():
125  if _temp_dir:
126    shutil.rmtree(_temp_dir, ignore_errors=True)
127
128atexit.register(_RemoveTempDir)
129
130
131def GetTempDir():
132  """Returns a directory for temporary files."""
133
134  global _temp_dir
135  if not _temp_dir:
136    _temp_dir = tempfile.mkdtemp()
137  return _temp_dir
138
139
140def GetTestExecutablePath(executable_name):
141  """Returns the absolute path of the test binary given its name.
142
143  The function will print a message and abort the program if the resulting file
144  doesn't exist.
145
146  Args:
147    executable_name: name of the test binary that the test script runs.
148
149  Returns:
150    The absolute path of the test binary.
151  """
152
153  path = os.path.abspath(os.path.join(GetBuildDir(), executable_name))
154  if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'):
155    path += '.exe'
156
157  if not os.path.exists(path):
158    message = (
159        'Unable to find the test binary. Please make sure to provide path\n'
160        'to the binary via the --gtest_build_dir flag or the GTEST_BUILD_DIR\n'
161        'environment variable. For convenient use, invoke this script via\n'
162        'mk_test.py.\n'
163        # TODO(vladl@google.com): change mk_test.py to test.py after renaming
164        # the file.
165        'Please run mk_test.py -h for help.')
166    print >> sys.stderr, message
167    sys.exit(1)
168
169  return path
170
171
172def GetExitStatus(exit_code):
173  """Returns the argument to exit(), or -1 if exit() wasn't called.
174
175  Args:
176    exit_code: the result value of os.system(command).
177  """
178
179  if os.name == 'nt':
180    # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
181    # the argument to exit() directly.
182    return exit_code
183  else:
184    # On Unix, os.WEXITSTATUS() must be used to extract the exit status
185    # from the result of os.system().
186    if os.WIFEXITED(exit_code):
187      return os.WEXITSTATUS(exit_code)
188    else:
189      return -1
190
191
192class Subprocess:
193  def __init__(self, command, working_dir=None, capture_stderr=True):
194    """Changes into a specified directory, if provided, and executes a command.
195    Restores the old directory afterwards. Execution results are returned
196    via the following attributes:
197      terminated_by_sygnal   True iff the child process has been terminated
198                             by a signal.
199      signal                 Sygnal that terminated the child process.
200      exited                 True iff the child process exited normally.
201      exit_code              The code with which the child proces exited.
202      output                 Child process's stdout and stderr output
203                             combined in a string.
204
205    Args:
206      command:        The command to run, in the form of sys.argv.
207      working_dir:    The directory to change into.
208      capture_stderr: Determines whether to capture stderr in the output member
209                      or to discard it.
210    """
211
212    # The subprocess module is the preferrable way of running programs
213    # since it is available and behaves consistently on all platforms,
214    # including Windows. But it is only available starting in python 2.4.
215    # In earlier python versions, we revert to the popen2 module, which is
216    # available in python 2.0 and later but doesn't provide required
217    # functionality (Popen4) under Windows. This allows us to support Mac
218    # OS X 10.4 Tiger, which has python 2.3 installed.
219    if _SUBPROCESS_MODULE_AVAILABLE:
220      if capture_stderr:
221        stderr = subprocess.STDOUT
222      else:
223        stderr = subprocess.PIPE
224
225      p = subprocess.Popen(command,
226                           stdout=subprocess.PIPE, stderr=stderr,
227                           cwd=working_dir, universal_newlines=True)
228      # communicate returns a tuple with the file obect for the child's
229      # output.
230      self.output = p.communicate()[0]
231      self._return_code = p.returncode
232    else:
233      old_dir = os.getcwd()
234      try:
235        if working_dir is not None:
236          os.chdir(working_dir)
237        if capture_stderr:
238          p = popen2.Popen4(command)
239        else:
240          p = popen2.Popen3(command)
241        p.tochild.close()
242        self.output = p.fromchild.read()
243        ret_code = p.wait()
244      finally:
245        os.chdir(old_dir)
246      # Converts ret_code to match the semantics of
247      # subprocess.Popen.returncode.
248      if os.WIFSIGNALED(ret_code):
249        self._return_code = -os.WTERMSIG(ret_code)
250      else:  # os.WIFEXITED(ret_code) should return True here.
251        self._return_code = os.WEXITSTATUS(ret_code)
252
253    if self._return_code < 0:
254      self.terminated_by_signal = True
255      self.exited = False
256      self.signal = -self._return_code
257    else:
258      self.terminated_by_signal = False
259      self.exited = True
260      self.exit_code = self._return_code
261
262
263def Main():
264  """Runs the unit test."""
265
266  # We must call _ParseAndStripGTestFlags() before calling
267  # unittest.main().  Otherwise the latter will be confused by the
268  # --gtest_* flags.
269  _ParseAndStripGTestFlags(sys.argv)
270  _test_module.main()
271