/thirdparty/breakpad/third_party/protobuf/protobuf/gtest/test/gtest_output_test.py

http://github.com/tomahawk-player/tomahawk · Python · 327 lines · 215 code · 39 blank · 73 comment · 22 complexity · 4d8339329608619f4ba0abb6da577a8c MD5 · raw file

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