gtest_output_test.py 12 KB

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