You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

389 lines
18 KiB

  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2006, 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. """Unit test for the gtest_xml_output module"""
  32. import datetime
  33. import errno
  34. import os
  35. import re
  36. import sys
  37. from xml.dom import minidom, Node
  38. import gtest_test_utils
  39. import gtest_xml_test_utils
  40. GTEST_FILTER_FLAG = '--gtest_filter'
  41. GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
  42. GTEST_OUTPUT_FLAG = '--gtest_output'
  43. GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'
  44. GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_'
  45. # The flag indicating stacktraces are not supported
  46. NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support'
  47. # The environment variables for test sharding.
  48. TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'
  49. SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'
  50. SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'
  51. SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv
  52. if SUPPORTS_STACK_TRACES:
  53. STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
  54. else:
  55. STACK_TRACE_TEMPLATE = ''
  56. # unittest.main() can't handle unknown flags
  57. sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
  58. EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
  59. <testsuites tests="24" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
  60. <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  61. <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
  62. </testsuite>
  63. <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
  64. <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="FailedTest">
  65. <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
  66. Expected equality of these values:
  67. 1
  68. 2%(stack)s]]></failure>
  69. </testcase>
  70. </testsuite>
  71. <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*" timestamp="*">
  72. <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
  73. <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest">
  74. <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 1&#x0A; 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
  75. Expected equality of these values:
  76. 1
  77. 2%(stack)s]]></failure>
  78. <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A; 2&#x0A; 3" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
  79. Expected equality of these values:
  80. 2
  81. 3%(stack)s]]></failure>
  82. </testcase>
  83. <testcase name="DISABLED_test" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/>
  84. </testsuite>
  85. <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
  86. <testcase name="OutputsCData" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest">
  87. <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
  88. Failed
  89. XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure>
  90. </testcase>
  91. </testsuite>
  92. <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
  93. <testcase name="InvalidCharactersInMessage" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest">
  94. <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
  95. Failed
  96. Invalid characters in brackets []%(stack)s]]></failure>
  97. </testcase>
  98. </testsuite>
  99. <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*" timestamp="*">
  100. <testcase name="DISABLED_test_not_run" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/>
  101. </testsuite>
  102. <testsuite name="SkippedTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  103. <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"/>
  104. </testsuite>
  105. <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
  106. <testcase name="OneProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
  107. <properties>
  108. <property name="key_1" value="1"/>
  109. </properties>
  110. </testcase>
  111. <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
  112. <properties>
  113. <property name="key_int" value="1"/>
  114. </properties>
  115. </testcase>
  116. <testcase name="ThreeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
  117. <properties>
  118. <property name="key_1" value="1"/>
  119. <property name="key_2" value="2"/>
  120. <property name="key_3" value="3"/>
  121. </properties>
  122. </testcase>
  123. <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
  124. <properties>
  125. <property name="key_1" value="2"/>
  126. </properties>
  127. </testcase>
  128. </testsuite>
  129. <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  130. <testcase name="RecordProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
  131. <properties>
  132. <property name="key" value="1"/>
  133. </properties>
  134. </testcase>
  135. <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
  136. <properties>
  137. <property name="key_for_utility_int" value="1"/>
  138. </properties>
  139. </testcase>
  140. <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
  141. <properties>
  142. <property name="key_for_utility_string" value="1"/>
  143. </properties>
  144. </testcase>
  145. </testsuite>
  146. <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  147. <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
  148. <testcase name="HasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
  149. <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
  150. <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
  151. </testsuite>
  152. <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  153. <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
  154. </testsuite>
  155. <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  156. <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
  157. </testsuite>
  158. <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  159. <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
  160. </testsuite>
  161. <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  162. <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
  163. </testsuite>
  164. </testsuites>""" % {
  165. 'stack': STACK_TRACE_TEMPLATE
  166. }
  167. EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
  168. <testsuites tests="1" failures="0" disabled="0" errors="0" time="*"
  169. timestamp="*" name="AllTests" ad_hoc_property="42">
  170. <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0"
  171. errors="0" time="*" timestamp="*">
  172. <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
  173. </testsuite>
  174. </testsuites>"""
  175. EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
  176. <testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
  177. <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  178. <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
  179. </testsuite>
  180. <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
  181. <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
  182. <properties>
  183. <property name="key_1" value="2"/>
  184. </properties>
  185. </testcase>
  186. </testsuite>
  187. <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
  188. <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
  189. </testsuite>
  190. </testsuites>"""
  191. EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
  192. <testsuites tests="0" failures="0" disabled="0" errors="0" time="*"
  193. timestamp="*" name="AllTests">
  194. </testsuites>"""
  195. GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
  196. SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
  197. [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
  198. class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):
  199. """
  200. Unit test for Google Test's XML output functionality.
  201. """
  202. # This test currently breaks on platforms that do not support typed and
  203. # type-parameterized tests, so we don't run it under them.
  204. if SUPPORTS_TYPED_TESTS:
  205. def testNonEmptyXmlOutput(self):
  206. """
  207. Runs a test program that generates a non-empty XML output, and
  208. tests that the XML output is expected.
  209. """
  210. self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)
  211. def testEmptyXmlOutput(self):
  212. """Verifies XML output for a Google Test binary without actual tests.
  213. Runs a test program that generates an empty XML output, and
  214. tests that the XML output is expected.
  215. """
  216. self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0)
  217. def testTimestampValue(self):
  218. """Checks whether the timestamp attribute in the XML output is valid.
  219. Runs a test program that generates an empty XML output, and checks if
  220. the timestamp attribute in the testsuites tag is valid.
  221. """
  222. actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0)
  223. date_time_str = actual.documentElement.getAttributeNode('timestamp').value
  224. # datetime.strptime() is only available in Python 2.5+ so we have to
  225. # parse the expected datetime manually.
  226. match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
  227. self.assertTrue(
  228. re.match,
  229. 'XML datettime string %s has incorrect format' % date_time_str)
  230. date_time_from_xml = datetime.datetime(
  231. year=int(match.group(1)), month=int(match.group(2)),
  232. day=int(match.group(3)), hour=int(match.group(4)),
  233. minute=int(match.group(5)), second=int(match.group(6)))
  234. time_delta = abs(datetime.datetime.now() - date_time_from_xml)
  235. # timestamp value should be near the current local time
  236. self.assertTrue(time_delta < datetime.timedelta(seconds=600),
  237. 'time_delta is %s' % time_delta)
  238. actual.unlink()
  239. def testDefaultOutputFile(self):
  240. """
  241. Confirms that Google Test produces an XML output file with the expected
  242. default name if no name is explicitly specified.
  243. """
  244. output_file = os.path.join(gtest_test_utils.GetTempDir(),
  245. GTEST_DEFAULT_OUTPUT_FILE)
  246. gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
  247. 'gtest_no_test_unittest')
  248. try:
  249. os.remove(output_file)
  250. except OSError:
  251. e = sys.exc_info()[1]
  252. if e.errno != errno.ENOENT:
  253. raise
  254. p = gtest_test_utils.Subprocess(
  255. [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG],
  256. working_dir=gtest_test_utils.GetTempDir())
  257. self.assert_(p.exited)
  258. self.assertEquals(0, p.exit_code)
  259. self.assert_(os.path.isfile(output_file))
  260. def testSuppressedXmlOutput(self):
  261. """
  262. Tests that no XML file is generated if the default XML listener is
  263. shut down before RUN_ALL_TESTS is invoked.
  264. """
  265. xml_path = os.path.join(gtest_test_utils.GetTempDir(),
  266. GTEST_PROGRAM_NAME + 'out.xml')
  267. if os.path.isfile(xml_path):
  268. os.remove(xml_path)
  269. command = [GTEST_PROGRAM_PATH,
  270. '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),
  271. '--shut_down_xml']
  272. p = gtest_test_utils.Subprocess(command)
  273. if p.terminated_by_signal:
  274. # p.signal is available only if p.terminated_by_signal is True.
  275. self.assertFalse(
  276. p.terminated_by_signal,
  277. '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
  278. else:
  279. self.assert_(p.exited)
  280. self.assertEquals(1, p.exit_code,
  281. "'%s' exited with code %s, which doesn't match "
  282. 'the expected exit code %s.'
  283. % (command, p.exit_code, 1))
  284. self.assert_(not os.path.isfile(xml_path))
  285. def testFilteredTestXmlOutput(self):
  286. """Verifies XML output when a filter is applied.
  287. Runs a test program that executes only some tests and verifies that
  288. non-selected tests do not show up in the XML output.
  289. """
  290. self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0,
  291. extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
  292. def testShardedTestXmlOutput(self):
  293. """Verifies XML output when run using multiple shards.
  294. Runs a test program that executes only one shard and verifies that tests
  295. from other shards do not show up in the XML output.
  296. """
  297. self._TestXmlOutput(
  298. GTEST_PROGRAM_NAME,
  299. EXPECTED_SHARDED_TEST_XML,
  300. 0,
  301. extra_env={SHARD_INDEX_ENV_VAR: '0',
  302. TOTAL_SHARDS_ENV_VAR: '10'})
  303. def _GetXmlOutput(self, gtest_prog_name, extra_args, extra_env,
  304. expected_exit_code):
  305. """
  306. Returns the xml output generated by running the program gtest_prog_name.
  307. Furthermore, the program's exit code must be expected_exit_code.
  308. """
  309. xml_path = os.path.join(gtest_test_utils.GetTempDir(),
  310. gtest_prog_name + 'out.xml')
  311. gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
  312. command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] +
  313. extra_args)
  314. environ_copy = os.environ.copy()
  315. if extra_env:
  316. environ_copy.update(extra_env)
  317. p = gtest_test_utils.Subprocess(command, env=environ_copy)
  318. if p.terminated_by_signal:
  319. self.assert_(False,
  320. '%s was killed by signal %d' % (gtest_prog_name, p.signal))
  321. else:
  322. self.assert_(p.exited)
  323. self.assertEquals(expected_exit_code, p.exit_code,
  324. "'%s' exited with code %s, which doesn't match "
  325. 'the expected exit code %s.'
  326. % (command, p.exit_code, expected_exit_code))
  327. actual = minidom.parse(xml_path)
  328. return actual
  329. def _TestXmlOutput(self, gtest_prog_name, expected_xml,
  330. expected_exit_code, extra_args=None, extra_env=None):
  331. """
  332. Asserts that the XML document generated by running the program
  333. gtest_prog_name matches expected_xml, a string containing another
  334. XML document. Furthermore, the program's exit code must be
  335. expected_exit_code.
  336. """
  337. actual = self._GetXmlOutput(gtest_prog_name, extra_args or [],
  338. extra_env or {}, expected_exit_code)
  339. expected = minidom.parseString(expected_xml)
  340. self.NormalizeXml(actual.documentElement)
  341. self.AssertEquivalentNodes(expected.documentElement,
  342. actual.documentElement)
  343. expected.unlink()
  344. actual.unlink()
  345. if __name__ == '__main__':
  346. os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
  347. gtest_test_utils.Main()