googletest-output-test.py 12 KB

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