OpenCores
URL https://opencores.org/ocsvn/s80186/s80186/trunk

Subversion Repositories s80186

[/] [s80186/] [trunk/] [vendor/] [googletest/] [googletest/] [test/] [gtest_output_test.py] - Blame information for rev 2

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 jamieiles
#!/usr/bin/env python
2
#
3
# Copyright 2008, 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
"""Tests the text output of Google C++ Testing Framework.
33
 
34
SYNOPSIS
35
       gtest_output_test.py --build_dir=BUILD/DIR --gengolden
36
         # where BUILD/DIR contains the built gtest_output_test_ file.
37
       gtest_output_test.py --gengolden
38
       gtest_output_test.py
39
"""
40
 
41
__author__ = 'wan@google.com (Zhanyong Wan)'
42
 
43
import difflib
44
import os
45
import re
46
import sys
47
import gtest_test_utils
48
 
49
 
50
# The flag for generating the golden file
51
GENGOLDEN_FLAG = '--gengolden'
52
CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS'
53
 
54
IS_WINDOWS = os.name == 'nt'
55
 
56
# TODO(vladl@google.com): remove the _lin suffix.
57
GOLDEN_NAME = 'gtest_output_test_golden_lin.txt'
58
 
59
PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_output_test_')
60
 
61
# At least one command we exercise must not have the
62
# 'internal_skip_environment_and_ad_hoc_tests' argument.
63
COMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])
64
COMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])
65
COMMAND_WITH_TIME = ({}, [PROGRAM_PATH,
66
                          '--gtest_print_time',
67
                          'internal_skip_environment_and_ad_hoc_tests',
68
                          '--gtest_filter=FatalFailureTest.*:LoggingTest.*'])
69
COMMAND_WITH_DISABLED = (
70
    {}, [PROGRAM_PATH,
71
         '--gtest_also_run_disabled_tests',
72
         'internal_skip_environment_and_ad_hoc_tests',
73
         '--gtest_filter=*DISABLED_*'])
74
COMMAND_WITH_SHARDING = (
75
    {'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},
76
    [PROGRAM_PATH,
77
     'internal_skip_environment_and_ad_hoc_tests',
78
     '--gtest_filter=PassingTest.*'])
79
 
80
GOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)
81
 
82
 
83
def ToUnixLineEnding(s):
84
  """Changes all Windows/Mac line endings in s to UNIX line endings."""
85
 
86
  return s.replace('\r\n', '\n').replace('\r', '\n')
87
 
88
 
89
def RemoveLocations(test_output):
90
  """Removes all file location info from a Google Test program's output.
91
 
92
  Args:
93
       test_output:  the output of a Google Test program.
94
 
95
  Returns:
96
       output with all file location info (in the form of
97
       'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
98
       'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
99
       'FILE_NAME:#: '.
100
  """
101
 
102
  return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\: ', r'\1:#: ', test_output)
103
 
104
 
105
def RemoveStackTraceDetails(output):
106
  """Removes all stack traces from a Google Test program's output."""
107
 
108
  # *? means "find the shortest string that matches".
109
  return re.sub(r'Stack trace:(.|\n)*?\n\n',
110
                'Stack trace: (omitted)\n\n', output)
111
 
112
 
113
def RemoveStackTraces(output):
114
  """Removes all traces of stack traces from a Google Test program's output."""
115
 
116
  # *? means "find the shortest string that matches".
117
  return re.sub(r'Stack trace:(.|\n)*?\n\n', '', output)
118
 
119
 
120
def RemoveTime(output):
121
  """Removes all time information from a Google Test program's output."""
122
 
123
  return re.sub(r'\(\d+ ms', '(? ms', output)
124
 
125
 
126
def RemoveTypeInfoDetails(test_output):
127
  """Removes compiler-specific type info from Google Test program's output.
128
 
129
  Args:
130
       test_output:  the output of a Google Test program.
131
 
132
  Returns:
133
       output with type information normalized to canonical form.
134
  """
135
 
136
  # some compilers output the name of type 'unsigned int' as 'unsigned'
137
  return re.sub(r'unsigned int', 'unsigned', test_output)
138
 
139
 
140
def NormalizeToCurrentPlatform(test_output):
141
  """Normalizes platform specific output details for easier comparison."""
142
 
143
  if IS_WINDOWS:
144
    # Removes the color information that is not present on Windows.
145
    test_output = re.sub('\x1b\\[(0;3\d)?m', '', test_output)
146
    # Changes failure message headers into the Windows format.
147
    test_output = re.sub(r': Failure\n', r': error: ', test_output)
148
    # Changes file(line_number) to file:line_number.
149
    test_output = re.sub(r'((\w|\.)+)\((\d+)\):', r'\1:\3:', test_output)
150
 
151
  return test_output
152
 
153
 
154
def RemoveTestCounts(output):
155
  """Removes test counts from a Google Test program's output."""
156
 
157
  output = re.sub(r'\d+ tests?, listed below',
158
                  '? tests, listed below', output)
159
  output = re.sub(r'\d+ FAILED TESTS',
160
                  '? FAILED TESTS', output)
161
  output = re.sub(r'\d+ tests? from \d+ test cases?',
162
                  '? tests from ? test cases', output)
163
  output = re.sub(r'\d+ tests? from ([a-zA-Z_])',
164
                  r'? tests from \1', output)
165
  return re.sub(r'\d+ tests?\.', '? tests.', output)
166
 
167
 
168
def RemoveMatchingTests(test_output, pattern):
169
  """Removes output of specified tests from a Google Test program's output.
170
 
171
  This function strips not only the beginning and the end of a test but also
172
  all output in between.
173
 
174
  Args:
175
    test_output:       A string containing the test output.
176
    pattern:           A regex string that matches names of test cases or
177
                       tests to remove.
178
 
179
  Returns:
180
    Contents of test_output with tests whose names match pattern removed.
181
  """
182
 
183
  test_output = re.sub(
184
      r'.*\[ RUN      \] .*%s(.|\n)*?\[(  FAILED  |       OK )\] .*%s.*\n' % (
185
          pattern, pattern),
186
      '',
187
      test_output)
188
  return re.sub(r'.*%s.*\n' % pattern, '', test_output)
189
 
190
 
191
def NormalizeOutput(output):
192
  """Normalizes output (the output of gtest_output_test_.exe)."""
193
 
194
  output = ToUnixLineEnding(output)
195
  output = RemoveLocations(output)
196
  output = RemoveStackTraceDetails(output)
197
  output = RemoveTime(output)
198
  return output
199
 
200
 
201
def GetShellCommandOutput(env_cmd):
202
  """Runs a command in a sub-process, and returns its output in a string.
203
 
204
  Args:
205
    env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
206
             environment variables to set, and element 1 is a string with
207
             the command and any flags.
208
 
209
  Returns:
210
    A string with the command's combined standard and diagnostic output.
211
  """
212
 
213
  # Spawns cmd in a sub-process, and gets its standard I/O file objects.
214
  # Set and save the environment properly.
215
  environ = os.environ.copy()
216
  environ.update(env_cmd[0])
217
  p = gtest_test_utils.Subprocess(env_cmd[1], env=environ)
218
 
219
  return p.output
220
 
221
 
222
def GetCommandOutput(env_cmd):
223
  """Runs a command and returns its output with all file location
224
  info stripped off.
225
 
226
  Args:
227
    env_cmd:  The shell command. A 2-tuple where element 0 is a dict of extra
228
              environment variables to set, and element 1 is a string with
229
              the command and any flags.
230
  """
231
 
232
  # Disables exception pop-ups on Windows.
233
  environ, cmdline = env_cmd
234
  environ = dict(environ)  # Ensures we are modifying a copy.
235
  environ[CATCH_EXCEPTIONS_ENV_VAR_NAME] = '1'
236
  return NormalizeOutput(GetShellCommandOutput((environ, cmdline)))
237
 
238
 
239
def GetOutputOfAllCommands():
240
  """Returns concatenated output from several representative commands."""
241
 
242
  return (GetCommandOutput(COMMAND_WITH_COLOR) +
243
          GetCommandOutput(COMMAND_WITH_TIME) +
244
          GetCommandOutput(COMMAND_WITH_DISABLED) +
245
          GetCommandOutput(COMMAND_WITH_SHARDING))
246
 
247
 
248
test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
249
SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
250
SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
251
SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
252
SUPPORTS_STACK_TRACES = False
253
 
254
CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and
255
                            SUPPORTS_TYPED_TESTS and
256
                            SUPPORTS_THREADS and
257
                            not IS_WINDOWS)
258
 
259
class GTestOutputTest(gtest_test_utils.TestCase):
260
  def RemoveUnsupportedTests(self, test_output):
261
    if not SUPPORTS_DEATH_TESTS:
262
      test_output = RemoveMatchingTests(test_output, 'DeathTest')
263
    if not SUPPORTS_TYPED_TESTS:
264
      test_output = RemoveMatchingTests(test_output, 'TypedTest')
265
      test_output = RemoveMatchingTests(test_output, 'TypedDeathTest')
266
      test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest')
267
    if not SUPPORTS_THREADS:
268
      test_output = RemoveMatchingTests(test_output,
269
                                        'ExpectFailureWithThreadsTest')
270
      test_output = RemoveMatchingTests(test_output,
271
                                        'ScopedFakeTestPartResultReporterTest')
272
      test_output = RemoveMatchingTests(test_output,
273
                                        'WorksConcurrently')
274
    if not SUPPORTS_STACK_TRACES:
275
      test_output = RemoveStackTraces(test_output)
276
 
277
    return test_output
278
 
279
  def testOutput(self):
280
    output = GetOutputOfAllCommands()
281
 
282
    golden_file = open(GOLDEN_PATH, 'r')
283
    # A mis-configured source control system can cause \r appear in EOL
284
    # sequences when we read the golden file irrespective of an operating
285
    # system used. Therefore, we need to strip those \r's from newlines
286
    # unconditionally.
287
    golden = ToUnixLineEnding(golden_file.read())
288
    golden_file.close()
289
 
290
    # We want the test to pass regardless of certain features being
291
    # supported or not.
292
 
293
    # We still have to remove type name specifics in all cases.
294
    normalized_actual = RemoveTypeInfoDetails(output)
295
    normalized_golden = RemoveTypeInfoDetails(golden)
296
 
297
    if CAN_GENERATE_GOLDEN_FILE:
298
      self.assertEqual(normalized_golden, normalized_actual,
299
                       '\n'.join(difflib.unified_diff(
300
                           normalized_golden.split('\n'),
301
                           normalized_actual.split('\n'),
302
                           'golden', 'actual')))
303
    else:
304
      normalized_actual = NormalizeToCurrentPlatform(
305
          RemoveTestCounts(normalized_actual))
306
      normalized_golden = NormalizeToCurrentPlatform(
307
          RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden)))
308
 
309
      # This code is very handy when debugging golden file differences:
310
      if os.getenv('DEBUG_GTEST_OUTPUT_TEST'):
311
        open(os.path.join(
312
            gtest_test_utils.GetSourceDir(),
313
            '_gtest_output_test_normalized_actual.txt'), 'wb').write(
314
                normalized_actual)
315
        open(os.path.join(
316
            gtest_test_utils.GetSourceDir(),
317
            '_gtest_output_test_normalized_golden.txt'), 'wb').write(
318
                normalized_golden)
319
 
320
      self.assertEqual(normalized_golden, normalized_actual)
321
 
322
 
323
if __name__ == '__main__':
324
  if sys.argv[1:] == [GENGOLDEN_FLAG]:
325
    if CAN_GENERATE_GOLDEN_FILE:
326
      output = GetOutputOfAllCommands()
327
      golden_file = open(GOLDEN_PATH, 'wb')
328
      golden_file.write(output)
329
      golden_file.close()
330
    else:
331
      message = (
332
          """Unable to write a golden file when compiled in an environment
333
that does not support all the required features (death tests, typed tests,
334
and multiple threads).  Please generate the golden file using a binary built
335
with those features enabled.""")
336
 
337
      sys.stderr.write(message)
338
      sys.exit(1)
339
  else:
340
    gtest_test_utils.Main()

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.