Path: blob/main/contrib/googletest/googlemock/test/gmock_output_test.py
48254 views
#!/usr/bin/env python1#2# Copyright 2008, Google Inc.3# All rights reserved.4#5# Redistribution and use in source and binary forms, with or without6# modification, are permitted provided that the following conditions are7# met:8#9# * Redistributions of source code must retain the above copyright10# notice, this list of conditions and the following disclaimer.11# * Redistributions in binary form must reproduce the above12# copyright notice, this list of conditions and the following disclaimer13# in the documentation and/or other materials provided with the14# distribution.15# * Neither the name of Google Inc. nor the names of its16# contributors may be used to endorse or promote products derived from17# this software without specific prior written permission.18#19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.3031r"""Tests the text output of Google C++ Mocking Framework.3233To update the golden file:34gmock_output_test.py --build_dir=BUILD/DIR --gengolden35where BUILD/DIR contains the built gmock_output_test_ file.36gmock_output_test.py --gengolden37gmock_output_test.py3839"""4041from io import open # pylint: disable=redefined-builtin, g-importing-member42import os43import re44import sys45from googlemock.test import gmock_test_utils464748# The flag for generating the golden file49GENGOLDEN_FLAG = '--gengolden'5051PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_output_test_')52COMMAND = [PROGRAM_PATH, '--gtest_stack_trace_depth=0', '--gtest_print_time=0']53GOLDEN_NAME = 'gmock_output_test_golden.txt'54GOLDEN_PATH = os.path.join(gmock_test_utils.GetSourceDir(), GOLDEN_NAME)555657def ToUnixLineEnding(s):58"""Changes all Windows/Mac line endings in s to UNIX line endings."""5960return s.replace('\r\n', '\n').replace('\r', '\n')616263def RemoveReportHeaderAndFooter(output):64"""Removes Google Test result report's header and footer from the output."""6566output = re.sub(r'.*gtest_main.*\n', '', output)67output = re.sub(r'\[.*\d+ tests.*\n', '', output)68output = re.sub(r'\[.* test environment .*\n', '', output)69output = re.sub(r'\[=+\] \d+ tests .* ran.*', '', output)70output = re.sub(r'.* FAILED TESTS\n', '', output)71return output727374def RemoveLocations(output):75"""Removes all file location info from a Google Test program's output.7677Args:78output: the output of a Google Test program.7980Returns:81output with all file location info (in the form of82'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or83'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by84'FILE:#: '.85"""8687return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\:', 'FILE:#:', output)888990def NormalizeErrorMarker(output):91"""Normalizes the error marker, which is different on Windows vs on Linux."""9293return re.sub(r' error: ', ' Failure\n', output)949596def RemoveMemoryAddresses(output):97"""Removes memory addresses from the test output."""9899return re.sub(r'@\w+', '@0x#', output)100101102def RemoveTestNamesOfLeakedMocks(output):103"""Removes the test names of leaked mock objects from the test output."""104105return re.sub(r'\(used in test .+\) ', '', output)106107108def GetLeakyTests(output):109"""Returns a list of test names that leak mock objects."""110111# findall() returns a list of all matches of the regex in output.112# For example, if '(used in test FooTest.Bar)' is in output, the113# list will contain 'FooTest.Bar'.114return re.findall(r'\(used in test (.+)\)', output)115116117def GetNormalizedOutputAndLeakyTests(output):118"""Normalizes the output of gmock_output_test_.119120Args:121output: The test output.122123Returns:124A tuple (the normalized test output, the list of test names that have125leaked mocks).126"""127128output = ToUnixLineEnding(output)129output = RemoveReportHeaderAndFooter(output)130output = NormalizeErrorMarker(output)131output = RemoveLocations(output)132output = RemoveMemoryAddresses(output)133return (RemoveTestNamesOfLeakedMocks(output), GetLeakyTests(output))134135136def GetShellCommandOutput(cmd):137"""Runs a command in a sub-process, and returns its STDOUT in a string."""138139return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output140141142def GetNormalizedCommandOutputAndLeakyTests(cmd):143"""Runs a command and returns its normalized output and a list of leaky tests.144145Args:146cmd: the shell command.147"""148149# Disables exception pop-ups on Windows.150os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'151return GetNormalizedOutputAndLeakyTests(GetShellCommandOutput(cmd))152153154class GMockOutputTest(gmock_test_utils.TestCase):155156def testOutput(self):157(output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)158golden_file = open(GOLDEN_PATH, 'rb')159golden = golden_file.read().decode('utf-8')160golden_file.close()161# On Windows the repository might have been checked out with \r\n line162# endings, so normalize it here.163golden = ToUnixLineEnding(golden)164165# The normalized output should match the golden file.166self.assertEqual(golden, output)167168# The raw output should contain 2 leaked mock object errors for169# test GMockOutputTest.CatchesLeakedMocks.170self.assertEqual(171[172'GMockOutputTest.CatchesLeakedMocks',173'GMockOutputTest.CatchesLeakedMocks',174],175leaky_tests,176)177178179if __name__ == '__main__':180if sys.argv[1:] == [GENGOLDEN_FLAG]:181(output, _) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)182golden_file = open(GOLDEN_PATH, 'wb')183golden_file.write(output)184golden_file.close()185# Suppress the error "googletest was imported but a call to its main()186# was never detected."187os._exit(0)188else:189gmock_test_utils.Main()190191192