googletest-output-test.py 12 KB

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