gtest_xml_output_unittest.py 17 KB

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