gtest_output_test.py 12 KB

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