gmock_output_test.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. r"""Tests the text output of Google C++ Mocking Framework.
  32. To update the golden file:
  33. gmock_output_test.py --build_dir=BUILD/DIR --gengolden
  34. where BUILD/DIR contains the built gmock_output_test_ file.
  35. gmock_output_test.py --gengolden
  36. gmock_output_test.py
  37. """
  38. import os
  39. import re
  40. import sys
  41. import gmock_test_utils
  42. # The flag for generating the golden file
  43. GENGOLDEN_FLAG = '--gengolden'
  44. PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_output_test_')
  45. COMMAND = [PROGRAM_PATH, '--gtest_stack_trace_depth=0', '--gtest_print_time=0']
  46. GOLDEN_NAME = 'gmock_output_test_golden.txt'
  47. GOLDEN_PATH = os.path.join(gmock_test_utils.GetSourceDir(), GOLDEN_NAME)
  48. def ToUnixLineEnding(s):
  49. """Changes all Windows/Mac line endings in s to UNIX line endings."""
  50. return s.replace('\r\n', '\n').replace('\r', '\n')
  51. def RemoveReportHeaderAndFooter(output):
  52. """Removes Google Test result report's header and footer from the output."""
  53. output = re.sub(r'.*gtest_main.*\n', '', output)
  54. output = re.sub(r'\[.*\d+ tests.*\n', '', output)
  55. output = re.sub(r'\[.* test environment .*\n', '', output)
  56. output = re.sub(r'\[=+\] \d+ tests .* ran.*', '', output)
  57. output = re.sub(r'.* FAILED TESTS\n', '', output)
  58. return output
  59. def RemoveLocations(output):
  60. """Removes all file location info from a Google Test program's output.
  61. Args:
  62. output: the output of a Google Test program.
  63. Returns:
  64. output with all file location info (in the form of
  65. 'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
  66. 'DIRECTORY\\FILE_NAME(LINE_NUMBER): ') replaced by
  67. 'FILE:#: '.
  68. """
  69. return re.sub(r'.*[/\\](.+)(\:\d+|\(\d+\))\:', 'FILE:#:', output)
  70. def NormalizeErrorMarker(output):
  71. """Normalizes the error marker, which is different on Windows vs on Linux."""
  72. return re.sub(r' error: ', ' Failure\n', output)
  73. def RemoveMemoryAddresses(output):
  74. """Removes memory addresses from the test output."""
  75. return re.sub(r'@\w+', '@0x#', output)
  76. def RemoveTestNamesOfLeakedMocks(output):
  77. """Removes the test names of leaked mock objects from the test output."""
  78. return re.sub(r'\(used in test .+\) ', '', output)
  79. def GetLeakyTests(output):
  80. """Returns a list of test names that leak mock objects."""
  81. # findall() returns a list of all matches of the regex in output.
  82. # For example, if '(used in test FooTest.Bar)' is in output, the
  83. # list will contain 'FooTest.Bar'.
  84. return re.findall(r'\(used in test (.+)\)', output)
  85. def GetNormalizedOutputAndLeakyTests(output):
  86. """Normalizes the output of gmock_output_test_.
  87. Args:
  88. output: The test output.
  89. Returns:
  90. A tuple (the normalized test output, the list of test names that have
  91. leaked mocks).
  92. """
  93. output = ToUnixLineEnding(output)
  94. output = RemoveReportHeaderAndFooter(output)
  95. output = NormalizeErrorMarker(output)
  96. output = RemoveLocations(output)
  97. output = RemoveMemoryAddresses(output)
  98. return (RemoveTestNamesOfLeakedMocks(output), GetLeakyTests(output))
  99. def GetShellCommandOutput(cmd):
  100. """Runs a command in a sub-process, and returns its STDOUT in a string."""
  101. return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output
  102. def GetNormalizedCommandOutputAndLeakyTests(cmd):
  103. """Runs a command and returns its normalized output and a list of leaky tests.
  104. Args:
  105. cmd: the shell command.
  106. """
  107. # Disables exception pop-ups on Windows.
  108. os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'
  109. return GetNormalizedOutputAndLeakyTests(GetShellCommandOutput(cmd))
  110. class GMockOutputTest(gmock_test_utils.TestCase):
  111. def testOutput(self):
  112. (output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
  113. golden_file = open(GOLDEN_PATH, 'rb')
  114. golden = golden_file.read()
  115. golden_file.close()
  116. # The normalized output should match the golden file.
  117. self.assertEquals(golden, output)
  118. # The raw output should contain 2 leaked mock object errors for
  119. # test GMockOutputTest.CatchesLeakedMocks.
  120. self.assertEquals(['GMockOutputTest.CatchesLeakedMocks',
  121. 'GMockOutputTest.CatchesLeakedMocks'],
  122. leaky_tests)
  123. if __name__ == '__main__':
  124. if sys.argv[1:] == [GENGOLDEN_FLAG]:
  125. (output, _) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)
  126. golden_file = open(GOLDEN_PATH, 'wb')
  127. golden_file.write(output)
  128. golden_file.close()
  129. # Suppress the error "googletest was imported but a call to its main()
  130. # was never detected."
  131. os._exit(0)
  132. else:
  133. gmock_test_utils.Main()