googletest-json-output-unittest.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. #!/usr/bin/env python
  2. # Copyright 2018, Google Inc.
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Unit test for the gtest_json_output module."""
  31. import datetime
  32. import errno
  33. import json
  34. import os
  35. import re
  36. import sys
  37. import gtest_json_test_utils
  38. import gtest_test_utils
  39. GTEST_FILTER_FLAG = '--gtest_filter'
  40. GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
  41. GTEST_OUTPUT_FLAG = '--gtest_output'
  42. GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.json'
  43. GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_'
  44. # The flag indicating stacktraces are not supported
  45. NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support'
  46. SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv
  47. if SUPPORTS_STACK_TRACES:
  48. STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
  49. else:
  50. STACK_TRACE_TEMPLATE = ''
  51. EXPECTED_NON_EMPTY = {
  52. u'tests': 23,
  53. u'failures': 4,
  54. u'disabled': 2,
  55. u'errors': 0,
  56. u'timestamp': u'*',
  57. u'time': u'*',
  58. u'ad_hoc_property': u'42',
  59. u'name': u'AllTests',
  60. u'testsuites': [
  61. {
  62. u'name': u'SuccessfulTest',
  63. u'tests': 1,
  64. u'failures': 0,
  65. u'disabled': 0,
  66. u'errors': 0,
  67. u'time': u'*',
  68. u'testsuite': [
  69. {
  70. u'name': u'Succeeds',
  71. u'status': u'RUN',
  72. u'time': u'*',
  73. u'classname': u'SuccessfulTest'
  74. }
  75. ]
  76. },
  77. {
  78. u'name': u'FailedTest',
  79. u'tests': 1,
  80. u'failures': 1,
  81. u'disabled': 0,
  82. u'errors': 0,
  83. u'time': u'*',
  84. u'testsuite': [
  85. {
  86. u'name': u'Fails',
  87. u'status': u'RUN',
  88. u'time': u'*',
  89. u'classname': u'FailedTest',
  90. u'failures': [
  91. {
  92. u'failure':
  93. u'gtest_xml_output_unittest_.cc:*\n'
  94. u'Expected equality of these values:\n'
  95. u' 1\n 2' + STACK_TRACE_TEMPLATE,
  96. u'type': u''
  97. }
  98. ]
  99. }
  100. ]
  101. },
  102. {
  103. u'name': u'DisabledTest',
  104. u'tests': 1,
  105. u'failures': 0,
  106. u'disabled': 1,
  107. u'errors': 0,
  108. u'time': u'*',
  109. u'testsuite': [
  110. {
  111. u'name': u'DISABLED_test_not_run',
  112. u'status': u'NOTRUN',
  113. u'time': u'*',
  114. u'classname': u'DisabledTest'
  115. }
  116. ]
  117. },
  118. {
  119. u'name': u'MixedResultTest',
  120. u'tests': 3,
  121. u'failures': 1,
  122. u'disabled': 1,
  123. u'errors': 0,
  124. u'time': u'*',
  125. u'testsuite': [
  126. {
  127. u'name': u'Succeeds',
  128. u'status': u'RUN',
  129. u'time': u'*',
  130. u'classname': u'MixedResultTest'
  131. },
  132. {
  133. u'name': u'Fails',
  134. u'status': u'RUN',
  135. u'time': u'*',
  136. u'classname': u'MixedResultTest',
  137. u'failures': [
  138. {
  139. u'failure':
  140. u'gtest_xml_output_unittest_.cc:*\n'
  141. u'Expected equality of these values:\n'
  142. u' 1\n 2' + STACK_TRACE_TEMPLATE,
  143. u'type': u''
  144. },
  145. {
  146. u'failure':
  147. u'gtest_xml_output_unittest_.cc:*\n'
  148. u'Expected equality of these values:\n'
  149. u' 2\n 3' + STACK_TRACE_TEMPLATE,
  150. u'type': u''
  151. }
  152. ]
  153. },
  154. {
  155. u'name': u'DISABLED_test',
  156. u'status': u'NOTRUN',
  157. u'time': u'*',
  158. u'classname': u'MixedResultTest'
  159. }
  160. ]
  161. },
  162. {
  163. u'name': u'XmlQuotingTest',
  164. u'tests': 1,
  165. u'failures': 1,
  166. u'disabled': 0,
  167. u'errors': 0,
  168. u'time': u'*',
  169. u'testsuite': [
  170. {
  171. u'name': u'OutputsCData',
  172. u'status': u'RUN',
  173. u'time': u'*',
  174. u'classname': u'XmlQuotingTest',
  175. u'failures': [
  176. {
  177. u'failure':
  178. u'gtest_xml_output_unittest_.cc:*\n'
  179. u'Failed\nXML output: <?xml encoding="utf-8">'
  180. u'<top><![CDATA[cdata text]]></top>' +
  181. STACK_TRACE_TEMPLATE,
  182. u'type': u''
  183. }
  184. ]
  185. }
  186. ]
  187. },
  188. {
  189. u'name': u'InvalidCharactersTest',
  190. u'tests': 1,
  191. u'failures': 1,
  192. u'disabled': 0,
  193. u'errors': 0,
  194. u'time': u'*',
  195. u'testsuite': [
  196. {
  197. u'name': u'InvalidCharactersInMessage',
  198. u'status': u'RUN',
  199. u'time': u'*',
  200. u'classname': u'InvalidCharactersTest',
  201. u'failures': [
  202. {
  203. u'failure':
  204. u'gtest_xml_output_unittest_.cc:*\n'
  205. u'Failed\nInvalid characters in brackets'
  206. u' [\x01\x02]' + STACK_TRACE_TEMPLATE,
  207. u'type': u''
  208. }
  209. ]
  210. }
  211. ]
  212. },
  213. {
  214. u'name': u'PropertyRecordingTest',
  215. u'tests': 4,
  216. u'failures': 0,
  217. u'disabled': 0,
  218. u'errors': 0,
  219. u'time': u'*',
  220. u'SetUpTestCase': u'yes',
  221. u'TearDownTestCase': u'aye',
  222. u'testsuite': [
  223. {
  224. u'name': u'OneProperty',
  225. u'status': u'RUN',
  226. u'time': u'*',
  227. u'classname': u'PropertyRecordingTest',
  228. u'key_1': u'1'
  229. },
  230. {
  231. u'name': u'IntValuedProperty',
  232. u'status': u'RUN',
  233. u'time': u'*',
  234. u'classname': u'PropertyRecordingTest',
  235. u'key_int': u'1'
  236. },
  237. {
  238. u'name': u'ThreeProperties',
  239. u'status': u'RUN',
  240. u'time': u'*',
  241. u'classname': u'PropertyRecordingTest',
  242. u'key_1': u'1',
  243. u'key_2': u'2',
  244. u'key_3': u'3'
  245. },
  246. {
  247. u'name': u'TwoValuesForOneKeyUsesLastValue',
  248. u'status': u'RUN',
  249. u'time': u'*',
  250. u'classname': u'PropertyRecordingTest',
  251. u'key_1': u'2'
  252. }
  253. ]
  254. },
  255. {
  256. u'name': u'NoFixtureTest',
  257. u'tests': 3,
  258. u'failures': 0,
  259. u'disabled': 0,
  260. u'errors': 0,
  261. u'time': u'*',
  262. u'testsuite': [
  263. {
  264. u'name': u'RecordProperty',
  265. u'status': u'RUN',
  266. u'time': u'*',
  267. u'classname': u'NoFixtureTest',
  268. u'key': u'1'
  269. },
  270. {
  271. u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
  272. u'status': u'RUN',
  273. u'time': u'*',
  274. u'classname': u'NoFixtureTest',
  275. u'key_for_utility_int': u'1'
  276. },
  277. {
  278. u'name':
  279. u'ExternalUtilityThatCallsRecordStringValuedProperty',
  280. u'status': u'RUN',
  281. u'time': u'*',
  282. u'classname': u'NoFixtureTest',
  283. u'key_for_utility_string': u'1'
  284. }
  285. ]
  286. },
  287. {
  288. u'name': u'TypedTest/0',
  289. u'tests': 1,
  290. u'failures': 0,
  291. u'disabled': 0,
  292. u'errors': 0,
  293. u'time': u'*',
  294. u'testsuite': [
  295. {
  296. u'name': u'HasTypeParamAttribute',
  297. u'type_param': u'int',
  298. u'status': u'RUN',
  299. u'time': u'*',
  300. u'classname': u'TypedTest/0'
  301. }
  302. ]
  303. },
  304. {
  305. u'name': u'TypedTest/1',
  306. u'tests': 1,
  307. u'failures': 0,
  308. u'disabled': 0,
  309. u'errors': 0,
  310. u'time': u'*',
  311. u'testsuite': [
  312. {
  313. u'name': u'HasTypeParamAttribute',
  314. u'type_param': u'long',
  315. u'status': u'RUN',
  316. u'time': u'*',
  317. u'classname': u'TypedTest/1'
  318. }
  319. ]
  320. },
  321. {
  322. u'name': u'Single/TypeParameterizedTestCase/0',
  323. u'tests': 1,
  324. u'failures': 0,
  325. u'disabled': 0,
  326. u'errors': 0,
  327. u'time': u'*',
  328. u'testsuite': [
  329. {
  330. u'name': u'HasTypeParamAttribute',
  331. u'type_param': u'int',
  332. u'status': u'RUN',
  333. u'time': u'*',
  334. u'classname': u'Single/TypeParameterizedTestCase/0'
  335. }
  336. ]
  337. },
  338. {
  339. u'name': u'Single/TypeParameterizedTestCase/1',
  340. u'tests': 1,
  341. u'failures': 0,
  342. u'disabled': 0,
  343. u'errors': 0,
  344. u'time': u'*',
  345. u'testsuite': [
  346. {
  347. u'name': u'HasTypeParamAttribute',
  348. u'type_param': u'long',
  349. u'status': u'RUN',
  350. u'time': u'*',
  351. u'classname': u'Single/TypeParameterizedTestCase/1'
  352. }
  353. ]
  354. },
  355. {
  356. u'name': u'Single/ValueParamTest',
  357. u'tests': 4,
  358. u'failures': 0,
  359. u'disabled': 0,
  360. u'errors': 0,
  361. u'time': u'*',
  362. u'testsuite': [
  363. {
  364. u'name': u'HasValueParamAttribute/0',
  365. u'value_param': u'33',
  366. u'status': u'RUN',
  367. u'time': u'*',
  368. u'classname': u'Single/ValueParamTest'
  369. },
  370. {
  371. u'name': u'HasValueParamAttribute/1',
  372. u'value_param': u'42',
  373. u'status': u'RUN',
  374. u'time': u'*',
  375. u'classname': u'Single/ValueParamTest'
  376. },
  377. {
  378. u'name': u'AnotherTestThatHasValueParamAttribute/0',
  379. u'value_param': u'33',
  380. u'status': u'RUN',
  381. u'time': u'*',
  382. u'classname': u'Single/ValueParamTest'
  383. },
  384. {
  385. u'name': u'AnotherTestThatHasValueParamAttribute/1',
  386. u'value_param': u'42',
  387. u'status': u'RUN',
  388. u'time': u'*',
  389. u'classname': u'Single/ValueParamTest'
  390. }
  391. ]
  392. }
  393. ]
  394. }
  395. EXPECTED_FILTERED = {
  396. u'tests': 1,
  397. u'failures': 0,
  398. u'disabled': 0,
  399. u'errors': 0,
  400. u'time': u'*',
  401. u'timestamp': u'*',
  402. u'name': u'AllTests',
  403. u'ad_hoc_property': u'42',
  404. u'testsuites': [{
  405. u'name': u'SuccessfulTest',
  406. u'tests': 1,
  407. u'failures': 0,
  408. u'disabled': 0,
  409. u'errors': 0,
  410. u'time': u'*',
  411. u'testsuite': [{
  412. u'name': u'Succeeds',
  413. u'status': u'RUN',
  414. u'time': u'*',
  415. u'classname': u'SuccessfulTest',
  416. }]
  417. }],
  418. }
  419. EXPECTED_EMPTY = {
  420. u'tests': 0,
  421. u'failures': 0,
  422. u'disabled': 0,
  423. u'errors': 0,
  424. u'time': u'*',
  425. u'timestamp': u'*',
  426. u'name': u'AllTests',
  427. u'testsuites': [],
  428. }
  429. GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
  430. SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
  431. [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
  432. class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
  433. """Unit test for Google Test's JSON output functionality.
  434. """
  435. # This test currently breaks on platforms that do not support typed and
  436. # type-parameterized tests, so we don't run it under them.
  437. if SUPPORTS_TYPED_TESTS:
  438. def testNonEmptyJsonOutput(self):
  439. """Verifies JSON output for a Google Test binary with non-empty output.
  440. Runs a test program that generates a non-empty JSON output, and
  441. tests that the JSON output is expected.
  442. """
  443. self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1)
  444. def testEmptyJsonOutput(self):
  445. """Verifies JSON output for a Google Test binary without actual tests.
  446. Runs a test program that generates an empty JSON output, and
  447. tests that the JSON output is expected.
  448. """
  449. self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0)
  450. def testTimestampValue(self):
  451. """Checks whether the timestamp attribute in the JSON output is valid.
  452. Runs a test program that generates an empty JSON output, and checks if
  453. the timestamp attribute in the testsuites tag is valid.
  454. """
  455. actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0)
  456. date_time_str = actual['timestamp']
  457. # datetime.strptime() is only available in Python 2.5+ so we have to
  458. # parse the expected datetime manually.
  459. match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
  460. self.assertTrue(
  461. re.match,
  462. 'JSON datettime string %s has incorrect format' % date_time_str)
  463. date_time_from_json = datetime.datetime(
  464. year=int(match.group(1)), month=int(match.group(2)),
  465. day=int(match.group(3)), hour=int(match.group(4)),
  466. minute=int(match.group(5)), second=int(match.group(6)))
  467. time_delta = abs(datetime.datetime.now() - date_time_from_json)
  468. # timestamp value should be near the current local time
  469. self.assertTrue(time_delta < datetime.timedelta(seconds=600),
  470. 'time_delta is %s' % time_delta)
  471. def testDefaultOutputFile(self):
  472. """Verifies the default output file name.
  473. Confirms that Google Test produces an JSON output file with the expected
  474. default name if no name is explicitly specified.
  475. """
  476. output_file = os.path.join(gtest_test_utils.GetTempDir(),
  477. GTEST_DEFAULT_OUTPUT_FILE)
  478. gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
  479. 'gtest_no_test_unittest')
  480. try:
  481. os.remove(output_file)
  482. except OSError:
  483. e = sys.exc_info()[1]
  484. if e.errno != errno.ENOENT:
  485. raise
  486. p = gtest_test_utils.Subprocess(
  487. [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG],
  488. working_dir=gtest_test_utils.GetTempDir())
  489. self.assert_(p.exited)
  490. self.assertEquals(0, p.exit_code)
  491. self.assert_(os.path.isfile(output_file))
  492. def testSuppressedJsonOutput(self):
  493. """Verifies that no JSON output is generated.
  494. Tests that no JSON file is generated if the default JSON listener is
  495. shut down before RUN_ALL_TESTS is invoked.
  496. """
  497. json_path = os.path.join(gtest_test_utils.GetTempDir(),
  498. GTEST_PROGRAM_NAME + 'out.json')
  499. if os.path.isfile(json_path):
  500. os.remove(json_path)
  501. command = [GTEST_PROGRAM_PATH,
  502. '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path),
  503. '--shut_down_xml']
  504. p = gtest_test_utils.Subprocess(command)
  505. if p.terminated_by_signal:
  506. # p.signal is available only if p.terminated_by_signal is True.
  507. self.assertFalse(
  508. p.terminated_by_signal,
  509. '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
  510. else:
  511. self.assert_(p.exited)
  512. self.assertEquals(1, p.exit_code,
  513. "'%s' exited with code %s, which doesn't match "
  514. 'the expected exit code %s.'
  515. % (command, p.exit_code, 1))
  516. self.assert_(not os.path.isfile(json_path))
  517. def testFilteredTestJsonOutput(self):
  518. """Verifies JSON output when a filter is applied.
  519. Runs a test program that executes only some tests and verifies that
  520. non-selected tests do not show up in the JSON output.
  521. """
  522. self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0,
  523. extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
  524. def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code):
  525. """Returns the JSON output generated by running the program gtest_prog_name.
  526. Furthermore, the program's exit code must be expected_exit_code.
  527. Args:
  528. gtest_prog_name: Google Test binary name.
  529. extra_args: extra arguments to binary invocation.
  530. expected_exit_code: program's exit code.
  531. """
  532. json_path = os.path.join(gtest_test_utils.GetTempDir(),
  533. gtest_prog_name + 'out.json')
  534. gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
  535. command = (
  536. [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] +
  537. extra_args
  538. )
  539. p = gtest_test_utils.Subprocess(command)
  540. if p.terminated_by_signal:
  541. self.assert_(False,
  542. '%s was killed by signal %d' % (gtest_prog_name, p.signal))
  543. else:
  544. self.assert_(p.exited)
  545. self.assertEquals(expected_exit_code, p.exit_code,
  546. "'%s' exited with code %s, which doesn't match "
  547. 'the expected exit code %s.'
  548. % (command, p.exit_code, expected_exit_code))
  549. with open(json_path) as f:
  550. actual = json.load(f)
  551. return actual
  552. def _TestJsonOutput(self, gtest_prog_name, expected,
  553. expected_exit_code, extra_args=None):
  554. """Checks the JSON output generated by the Google Test binary.
  555. Asserts that the JSON document generated by running the program
  556. gtest_prog_name matches expected_json, a string containing another
  557. JSON document. Furthermore, the program's exit code must be
  558. expected_exit_code.
  559. Args:
  560. gtest_prog_name: Google Test binary name.
  561. expected: expected output.
  562. expected_exit_code: program's exit code.
  563. extra_args: extra arguments to binary invocation.
  564. """
  565. actual = self._GetJsonOutput(gtest_prog_name, extra_args or [],
  566. expected_exit_code)
  567. self.assertEqual(expected, gtest_json_test_utils.normalize(actual))
  568. if __name__ == '__main__':
  569. if NO_STACKTRACE_SUPPORT_FLAG in sys.argv:
  570. # unittest.main() can't handle unknown flags
  571. sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
  572. os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
  573. gtest_test_utils.Main()