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