gtest_output_test.py 10.6 KB
Newer Older
shiqian's avatar
shiqian committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Tests the text output of Google C++ Testing Framework.

SYNOPSIS
35
36
       gtest_output_test.py --gtest_build_dir=BUILD/DIR --gengolden
         # where BUILD/DIR contains the built gtest_output_test_ file.
shiqian's avatar
shiqian committed
37
38
39
40
41
42
43
44
45
       gtest_output_test.py --gengolden
       gtest_output_test.py
"""

__author__ = 'wan@google.com (Zhanyong Wan)'

import os
import re
import sys
46
import gtest_test_utils
shiqian's avatar
shiqian committed
47
48
49
50
51
52
53
54
55
56
57
58


# The flag for generating the golden file
GENGOLDEN_FLAG = '--gengolden'

IS_WINDOWS = os.name == 'nt'

if IS_WINDOWS:
  GOLDEN_NAME = 'gtest_output_test_golden_win.txt'
else:
  GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'

59
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
60
61
62

# At least one command we exercise must not have the
# --gtest_internal_skip_environment_and_ad_hoc_tests flag.
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
                          '--gtest_print_time',
                          '--gtest_internal_skip_environment_and_ad_hoc_tests',
                          '--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
COMMAND_WITH_DISABLED = (
    {}, [PROGRAM_PATH,
         '--gtest_also_run_disabled_tests',
         '--gtest_internal_skip_environment_and_ad_hoc_tests',
         '--gtest_filter=*DISABLED_*'])
COMMAND_WITH_SHARDING = (
    {'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
    [PROGRAM_PATH,
     '--gtest_internal_skip_environment_and_ad_hoc_tests',
     '--gtest_filter=PassingTest.*'])
shiqian's avatar
shiqian committed
79

80
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
shiqian's avatar
shiqian committed
81

82

shiqian's avatar
shiqian committed
83
84
85
86
87
88
def ToUnixLineEnding(s):
  """Changes all Windows/Mac line endings in s to UNIX line endings."""

  return s.replace('\r\n', '\n').replace('\r', '\n')


89
def RemoveLocations(test_output):
shiqian's avatar
shiqian committed
90
91
92
  """Removes all file location info from a Google Test program's output.

  Args:
93
       test_output:  the output of a Google Test program.
shiqian's avatar
shiqian committed
94
95
96

  Returns:
       output with all file location info (in the form of
97
98
       'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
       'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
shiqian's avatar
shiqian committed
99
100
101
       'FILE_NAME:#: '.
  """

102
  return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
shiqian's avatar
shiqian committed
103
104


105
def RemoveStackTraceDetails(output):
shiqian's avatar
shiqian committed
106
107
108
109
110
111
112
  """Removes all stack traces from a Google Test program's output."""

  # *? means "find the shortest string that matches".
  return re.sub(r'Stack trace:(.|\n)*?\n\n',
                'Stack trace: (omitted)\n\n', output)


113
114
115
116
117
118
119
def RemoveStackTraces(output):
  """Removes all traces of stack traces from a Google Test program's output."""

  # *? means "find the shortest string that matches".
  return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)


120
121
122
123
124
125
def RemoveTime(output):
  """Removes all time information from a Google Test program's output."""

  return re.sub(r'\(\d+ ms', '(? ms', output)


126
127
128
def RemoveTestCounts(output):
  """Removes test counts from a Google Test program's output."""

129
  output = re.sub(r'\d+ tests?, listed below',
130
131
132
                  '? tests, listed below', output)
  output = re.sub(r'\d+ FAILED TESTS',
                  '? FAILED TESTS', output)
133
  output = re.sub(r'\d+ tests? from \d+ test cases?',
134
                  '? tests from ? test cases', output)
135
  output = re.sub(r'\d+ tests? from ([a-zA-Z_])',
136
                  r'? tests from \1', output)
137
  return re.sub(r'\d+ tests?\.', '? tests.', output)
138
139


140
def RemoveMatchingTests(test_output, pattern):
141
  """Removes output of specified tests from a Google Test program's output.
142

143
144
  This function strips not only the beginning and the end of a test but also
  all output in between.
145
146
147

  Args:
    test_output:       A string containing the test output.
148
149
    pattern:           A regex string that matches names of test cases or
                       tests to remove.
150
151

  Returns:
152
    Contents of test_output with tests whose names match pattern removed.
153
154
155
  """

  test_output = re.sub(
156
      r'.*\[ RUN      \] .*%s(.|\n)*?\[(  FAILED  |       OK )\] .*%s.*\n' % (
157
158
159
160
          pattern, pattern),
      '',
      test_output)
  return re.sub(r'.*%s.*\n' % pattern, '', test_output)
161
162


shiqian's avatar
shiqian committed
163
164
165
166
167
def NormalizeOutput(output):
  """Normalizes output (the output of gtest_output_test_.exe)."""

  output = ToUnixLineEnding(output)
  output = RemoveLocations(output)
168
  output = RemoveStackTraceDetails(output)
169
  output = RemoveTime(output)
shiqian's avatar
shiqian committed
170
171
172
  return output


173
174
def GetShellCommandOutput(env_cmd):
  """Runs a command in a sub-process, and returns its output in a string.
shiqian's avatar
shiqian committed
175
176

  Args:
177
178
179
    env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
             environment variables to set, and element 1 is a string with
             the command and any flags.
shiqian's avatar
shiqian committed
180

181
182
  Returns:
    A string with the command's combined standard and diagnostic output.
shiqian's avatar
shiqian committed
183
184
185
  """

  # Spawns cmd in a sub-process, and gets its standard I/O file objects.
186
187
188
  # Set and save the environment properly.
  old_env_vars = dict(os.environ)
  os.environ.update(env_cmd[0])
189
190
  p = gtest_test_utils.Subprocess(env_cmd[1])

191
192
193
194
195
  # Changes made by os.environ.clear are not inheritable by child processes
  # until Python 2.6. To produce inheritable changes we have to delete
  # environment items with the del statement.
  for key in os.environ.keys():
    del os.environ[key]
196
  os.environ.update(old_env_vars)
shiqian's avatar
shiqian committed
197

198
  return p.output
shiqian's avatar
shiqian committed
199
200


201
def GetCommandOutput(env_cmd):
shiqian's avatar
shiqian committed
202
203
204
205
  """Runs a command and returns its output with all file location
  info stripped off.

  Args:
206
207
208
    env_cmd:  The shell command. A 2-tuple where element 0 is a dict of extra
              environment variables to set, and element 1 is a string with
              the command and any flags.
shiqian's avatar
shiqian committed
209
210
211
  """

  # Disables exception pop-ups on Windows.
212
  os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'
213
  return NormalizeOutput(GetShellCommandOutput(env_cmd))
214
215
216
217
218
219
220
221
222


def GetOutputOfAllCommands():
  """Returns concatenated output from several representative commands."""

  return (GetCommandOutput(COMMAND_WITH_COLOR) +
          GetCommandOutput(COMMAND_WITH_TIME) +
          GetCommandOutput(COMMAND_WITH_DISABLED) +
          GetCommandOutput(COMMAND_WITH_SHARDING))
shiqian's avatar
shiqian committed
223
224


225
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
226
227
SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
228
229
230
231
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
SUPPORTS_STACK_TRACES = False

CAN_GENERATE_GOLDEN_FILE = SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS
232
233


234
class GTestOutputTest(gtest_test_utils.TestCase):
235
236
237
238
239
  def RemoveUnsupportedTests(self, test_output):
    if not SUPPORTS_DEATH_TESTS:
      test_output = RemoveMatchingTests(test_output, 'DeathTest')
    if not SUPPORTS_TYPED_TESTS:
      test_output = RemoveMatchingTests(test_output, 'TypedTest')
240
241
242
243
244
245
246
247
248
249
    if not SUPPORTS_THREADS:
      test_output = RemoveMatchingTests(test_output,
                                        'ExpectFailureWithThreadsTest')
      test_output = RemoveMatchingTests(test_output,
                                        'ScopedFakeTestPartResultReporterTest')
      test_output = RemoveMatchingTests(test_output,
                                        'WorksConcurrently')
    if not SUPPORTS_STACK_TRACES:
      test_output = RemoveStackTraces(test_output)

250
251
    return test_output

shiqian's avatar
shiqian committed
252
  def testOutput(self):
253
    output = GetOutputOfAllCommands()
254

shiqian's avatar
shiqian committed
255
    golden_file = open(GOLDEN_PATH, 'rb')
256
257
258
259
260
    # A mis-configured source control system can cause \r appear in EOL
    # sequences when we read the golden file irrespective of an operating
    # system used. Therefore, we need to strip those \r's from newlines
    # unconditionally.
    golden = ToUnixLineEnding(golden_file.read())
shiqian's avatar
shiqian committed
261
262
    golden_file.close()

263
    # We want the test to pass regardless of certain features being
264
    # supported or not.
265
    if CAN_GENERATE_GOLDEN_FILE:
266
267
      self.assert_(golden == output)
    else:
268
269
270
      normalized_actual = RemoveTestCounts(output)
      normalized_golden = RemoveTestCounts(self.RemoveUnsupportedTests(golden))

271
272
273
274
275
276
277
278
279
280
      # This code is very handy when debugging golden file differences:
      if os.getenv('DEBUG_GTEST_OUTPUT_TEST'):
        open(os.path.join(
            gtest_test_utils.GetSourceDir(),
            '_gtest_output_test_normalized_actual.txt'), 'wb').write(
                normalized_actual)
        open(os.path.join(
            gtest_test_utils.GetSourceDir(),
            '_gtest_output_test_normalized_golden.txt'), 'wb').write(
                normalized_golden)
281
282

      self.assert_(normalized_golden == normalized_actual)
shiqian's avatar
shiqian committed
283
284
285
286


if __name__ == '__main__':
  if sys.argv[1:] == [GENGOLDEN_FLAG]:
287
    if CAN_GENERATE_GOLDEN_FILE:
288
289
290
291
292
      output = GetOutputOfAllCommands()
      golden_file = open(GOLDEN_PATH, 'wb')
      golden_file.write(output)
      golden_file.close()
    else:
293
294
295
296
297
298
299
300
301
302
303
304
      message = (
          """Unable to write a golden file when compiled in an environment
that does not support all the required features (death tests""")
      if IS_WINDOWS:
        message += (
            """\nand typed tests). Please check that you are using VC++ 8.0 SP1
or higher as your compiler.""")
      else:
        message += """\nand typed tests).  Please generate the golden file
using a binary built with those features enabled."""

      sys.stderr.write(message)
305
      sys.exit(1)
shiqian's avatar
shiqian committed
306
307
  else:
    gtest_test_utils.Main()