Home | History | Annotate | Download | only in test
      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 
     34 SYNOPSIS
     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 (at] google.com (Zhanyong Wan)'
     42 
     43 import os
     44 import re
     45 import sys
     46 import gtest_test_utils
     47 
     48 
     49 # The flag for generating the golden file
     50 GENGOLDEN_FLAG = '--gengolden'
     51 
     52 IS_WINDOWS = os.name == 'nt'
     53 
     54 if IS_WINDOWS:
     55   GOLDEN_NAME = 'gtest_output_test_golden_win.txt'
     56 else:
     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 # --gtest_internal_skip_environment_and_ad_hoc_tests flag.
     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                           '--gtest_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          '--gtest_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      '--gtest_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 RemoveTestCounts(output):
    127   """Removes test counts from a Google Test program's output."""
    128 
    129   output = re.sub(r'\d+ tests, listed below',
    130                   '? tests, listed below', output)
    131   output = re.sub(r'\d+ FAILED TESTS',
    132                   '? 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   This function strips not only the beginning and the end of a test but also
    144   all output in between.
    145 
    146   Args:
    147     test_output:       A string containing the test output.
    148     pattern:           A regex string that matches names of test cases or
    149                        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           pattern, pattern),
    158       '',
    159       test_output)
    160   return re.sub(r'.*%s.*\n' % pattern, '', test_output)
    161 
    162 
    163 def NormalizeOutput(output):
    164   """Normalizes output (the output of gtest_output_test_.exe)."""
    165 
    166   output = ToUnixLineEnding(output)
    167   output = RemoveLocations(output)
    168   output = RemoveStackTraceDetails(output)
    169   output = RemoveTime(output)
    170   return output
    171 
    172 
    173 def GetShellCommandOutput(env_cmd):
    174   """Runs a command in a sub-process, and returns its output in a string.
    175 
    176   Args:
    177     env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra
    178              environment variables to set, and element 1 is a string with
    179              the command and any flags.
    180 
    181   Returns:
    182     A string with the command's combined standard and diagnostic output.
    183   """
    184 
    185   # Spawns cmd in a sub-process, and gets its standard I/O file objects.
    186   # Set and save the environment properly.
    187   old_env_vars = dict(os.environ)
    188   os.environ.update(env_cmd[0])
    189   p = gtest_test_utils.Subprocess(env_cmd[1])
    190 
    191   # Changes made by os.environ.clear are not inheritable by child processes
    192   # until Python 2.6. To produce inheritable changes we have to delete
    193   # environment items with the del statement.
    194   for key in os.environ.keys():
    195     del os.environ[key]
    196   os.environ.update(old_env_vars)
    197 
    198   return p.output
    199 
    200 
    201 def GetCommandOutput(env_cmd):
    202   """Runs a command and returns its output with all file location
    203   info stripped off.
    204 
    205   Args:
    206     env_cmd:  The shell command. A 2-tuple where element 0 is a dict of extra
    207               environment variables to set, and element 1 is a string with
    208               the command and any flags.
    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 def GetOutputOfAllCommands():
    217   """Returns concatenated output from several representative commands."""
    218 
    219   return (GetCommandOutput(COMMAND_WITH_COLOR) +
    220           GetCommandOutput(COMMAND_WITH_TIME) +
    221           GetCommandOutput(COMMAND_WITH_DISABLED) +
    222           GetCommandOutput(COMMAND_WITH_SHARDING))
    223 
    224 
    225 test_list = GetShellCommandOutput(COMMAND_LIST_TESTS)
    226 SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list
    227 SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list
    228 SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list
    229 SUPPORTS_STACK_TRACES = False
    230 
    231 CAN_GENERATE_GOLDEN_FILE = SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS
    232 
    233 
    234 class GTestOutputTest(gtest_test_utils.TestCase):
    235   def RemoveUnsupportedTests(self, test_output):
    236     if not SUPPORTS_DEATH_TESTS:
    237       test_output = RemoveMatchingTests(test_output, 'DeathTest')
    238     if not SUPPORTS_TYPED_TESTS:
    239       test_output = RemoveMatchingTests(test_output, 'TypedTest')
    240     if not SUPPORTS_THREADS:
    241       test_output = RemoveMatchingTests(test_output,
    242                                         'ExpectFailureWithThreadsTest')
    243       test_output = RemoveMatchingTests(test_output,
    244                                         'ScopedFakeTestPartResultReporterTest')
    245       test_output = RemoveMatchingTests(test_output,
    246                                         'WorksConcurrently')
    247     if not SUPPORTS_STACK_TRACES:
    248       test_output = RemoveStackTraces(test_output)
    249 
    250     return test_output
    251 
    252   def testOutput(self):
    253     output = GetOutputOfAllCommands()
    254 
    255     golden_file = open(GOLDEN_PATH, 'rb')
    256     # A mis-configured source control system can cause \r appear in EOL
    257     # sequences when we read the golden file irrespective of an operating
    258     # system used. Therefore, we need to strip those \r's from newlines
    259     # unconditionally.
    260     golden = ToUnixLineEnding(golden_file.read())
    261     golden_file.close()
    262 
    263     # We want the test to pass regardless of certain features being
    264     # supported or not.
    265     if CAN_GENERATE_GOLDEN_FILE:
    266       self.assert_(golden == output)
    267     else:
    268       normalized_actual = RemoveTestCounts(output)
    269       normalized_golden = RemoveTestCounts(self.RemoveUnsupportedTests(golden))
    270 
    271       # This code is very handy when debugging test differences so I left it
    272       # here, commented.
    273       # open(os.path.join(
    274       #     gtest_test_utils.GetSourceDir(),
    275       #     '_gtest_output_test_normalized_actual.txt'), 'wb').write(
    276       #         normalized_actual)
    277       # open(os.path.join(
    278       #     gtest_test_utils.GetSourceDir(),
    279       #     '_gtest_output_test_normalized_golden.txt'), 'wb').write(
    280       #         normalized_golden)
    281 
    282       self.assert_(normalized_golden == normalized_actual)
    283 
    284 
    285 if __name__ == '__main__':
    286   if sys.argv[1:] == [GENGOLDEN_FLAG]:
    287     if CAN_GENERATE_GOLDEN_FILE:
    288       output = GetOutputOfAllCommands()
    289       golden_file = open(GOLDEN_PATH, 'wb')
    290       golden_file.write(output)
    291       golden_file.close()
    292     else:
    293       message = (
    294           """Unable to write a golden file when compiled in an environment
    295 that does not support all the required features (death tests""")
    296       if IS_WINDOWS:
    297         message += (
    298             """\nand typed tests). Please check that you are using VC++ 8.0 SP1
    299 or higher as your compiler.""")
    300       else:
    301         message += """\nand typed tests).  Please generate the golden file
    302 using a binary built with those features enabled."""
    303 
    304       sys.stderr.write(message)
    305       sys.exit(1)
    306   else:
    307     gtest_test_utils.Main()
    308