2 # Copyright 2018, Google Inc.
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
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
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.
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.
31 """Unit test for the gtest_json_output module."""
40 import gtest_json_test_utils
41 import gtest_test_utils
43 GTEST_FILTER_FLAG = '--gtest_filter'
44 GTEST_LIST_TESTS_FLAG = '--gtest_list_tests'
45 GTEST_OUTPUT_FLAG = '--gtest_output'
46 GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.json'
47 GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_'
49 # The flag indicating stacktraces are not supported
50 NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support'
52 SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv
54 if SUPPORTS_STACK_TRACES:
55 STACK_TRACE_TEMPLATE = '\nStack trace:\n*'
57 STACK_TRACE_TEMPLATE = ''
59 EXPECTED_NON_EMPTY = {
66 u'ad_hoc_property': u'42',
70 u'name': u'SuccessfulTest',
81 u'classname': u'SuccessfulTest'
86 u'name': u'FailedTest',
97 u'classname': u'FailedTest',
101 u'gtest_xml_output_unittest_.cc:*\n'
102 u'Expected equality of these values:\n'
103 u' 1\n 2' + STACK_TRACE_TEMPLATE,
111 u'name': u'DisabledTest',
119 u'name': u'DISABLED_test_not_run',
120 u'status': u'NOTRUN',
122 u'classname': u'DisabledTest'
127 u'name': u'MixedResultTest',
135 u'name': u'Succeeds',
138 u'classname': u'MixedResultTest'
144 u'classname': u'MixedResultTest',
148 u'gtest_xml_output_unittest_.cc:*\n'
149 u'Expected equality of these values:\n'
150 u' 1\n 2' + STACK_TRACE_TEMPLATE,
155 u'gtest_xml_output_unittest_.cc:*\n'
156 u'Expected equality of these values:\n'
157 u' 2\n 3' + STACK_TRACE_TEMPLATE,
163 u'name': u'DISABLED_test',
164 u'status': u'NOTRUN',
166 u'classname': u'MixedResultTest'
171 u'name': u'XmlQuotingTest',
179 u'name': u'OutputsCData',
182 u'classname': u'XmlQuotingTest',
186 u'gtest_xml_output_unittest_.cc:*\n'
187 u'Failed\nXML output: <?xml encoding="utf-8">'
188 u'<top><![CDATA[cdata text]]></top>' +
189 STACK_TRACE_TEMPLATE,
197 u'name': u'InvalidCharactersTest',
205 u'name': u'InvalidCharactersInMessage',
208 u'classname': u'InvalidCharactersTest',
212 u'gtest_xml_output_unittest_.cc:*\n'
213 u'Failed\nInvalid characters in brackets'
214 u' [\x01\x02]' + STACK_TRACE_TEMPLATE,
222 u'name': u'PropertyRecordingTest',
228 u'SetUpTestCase': u'yes',
229 u'TearDownTestCase': u'aye',
232 u'name': u'OneProperty',
235 u'classname': u'PropertyRecordingTest',
239 u'name': u'IntValuedProperty',
242 u'classname': u'PropertyRecordingTest',
246 u'name': u'ThreeProperties',
249 u'classname': u'PropertyRecordingTest',
255 u'name': u'TwoValuesForOneKeyUsesLastValue',
258 u'classname': u'PropertyRecordingTest',
264 u'name': u'NoFixtureTest',
272 u'name': u'RecordProperty',
275 u'classname': u'NoFixtureTest',
279 u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
282 u'classname': u'NoFixtureTest',
283 u'key_for_utility_int': u'1'
287 u'ExternalUtilityThatCallsRecordStringValuedProperty',
290 u'classname': u'NoFixtureTest',
291 u'key_for_utility_string': u'1'
296 u'name': u'TypedTest/0',
304 u'name': u'HasTypeParamAttribute',
305 u'type_param': u'int',
308 u'classname': u'TypedTest/0'
313 u'name': u'TypedTest/1',
321 u'name': u'HasTypeParamAttribute',
322 u'type_param': u'long',
325 u'classname': u'TypedTest/1'
330 u'name': u'Single/TypeParameterizedTestCase/0',
338 u'name': u'HasTypeParamAttribute',
339 u'type_param': u'int',
342 u'classname': u'Single/TypeParameterizedTestCase/0'
347 u'name': u'Single/TypeParameterizedTestCase/1',
355 u'name': u'HasTypeParamAttribute',
356 u'type_param': u'long',
359 u'classname': u'Single/TypeParameterizedTestCase/1'
364 u'name': u'Single/ValueParamTest',
372 u'name': u'HasValueParamAttribute/0',
373 u'value_param': u'33',
376 u'classname': u'Single/ValueParamTest'
379 u'name': u'HasValueParamAttribute/1',
380 u'value_param': u'42',
383 u'classname': u'Single/ValueParamTest'
386 u'name': u'AnotherTestThatHasValueParamAttribute/0',
387 u'value_param': u'33',
390 u'classname': u'Single/ValueParamTest'
393 u'name': u'AnotherTestThatHasValueParamAttribute/1',
394 u'value_param': u'42',
397 u'classname': u'Single/ValueParamTest'
404 EXPECTED_FILTERED = {
411 u'name': u'AllTests',
412 u'ad_hoc_property': u'42',
414 u'name': u'SuccessfulTest',
421 u'name': u'Succeeds',
424 u'classname': u'SuccessfulTest',
436 u'name': u'AllTests',
440 GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
442 SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
443 [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
446 class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
447 """Unit test for Google Test's JSON output functionality.
450 # This test currently breaks on platforms that do not support typed and
451 # type-parameterized tests, so we don't run it under them.
452 if SUPPORTS_TYPED_TESTS:
454 def testNonEmptyJsonOutput(self):
455 """Verifies JSON output for a Google Test binary with non-empty output.
457 Runs a test program that generates a non-empty JSON output, and
458 tests that the JSON output is expected.
460 self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1)
462 def testEmptyJsonOutput(self):
463 """Verifies JSON output for a Google Test binary without actual tests.
465 Runs a test program that generates an empty JSON output, and
466 tests that the JSON output is expected.
469 self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0)
471 def testTimestampValue(self):
472 """Checks whether the timestamp attribute in the JSON output is valid.
474 Runs a test program that generates an empty JSON output, and checks if
475 the timestamp attribute in the testsuites tag is valid.
477 actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0)
478 date_time_str = actual['timestamp']
479 # datetime.strptime() is only available in Python 2.5+ so we have to
480 # parse the expected datetime manually.
481 match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
484 'JSON datettime string %s has incorrect format' % date_time_str)
485 date_time_from_json = datetime.datetime(
486 year=int(match.group(1)), month=int(match.group(2)),
487 day=int(match.group(3)), hour=int(match.group(4)),
488 minute=int(match.group(5)), second=int(match.group(6)))
490 time_delta = abs(datetime.datetime.now() - date_time_from_json)
491 # timestamp value should be near the current local time
492 self.assertTrue(time_delta < datetime.timedelta(seconds=600),
493 'time_delta is %s' % time_delta)
495 def testDefaultOutputFile(self):
496 """Verifies the default output file name.
498 Confirms that Google Test produces an JSON output file with the expected
499 default name if no name is explicitly specified.
501 output_file = os.path.join(gtest_test_utils.GetTempDir(),
502 GTEST_DEFAULT_OUTPUT_FILE)
503 gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
504 'gtest_no_test_unittest')
506 os.remove(output_file)
508 e = sys.exc_info()[1]
509 if e.errno != errno.ENOENT:
512 p = gtest_test_utils.Subprocess(
513 [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG],
514 working_dir=gtest_test_utils.GetTempDir())
515 self.assert_(p.exited)
516 self.assertEquals(0, p.exit_code)
517 self.assert_(os.path.isfile(output_file))
519 def testSuppressedJsonOutput(self):
520 """Verifies that no JSON output is generated.
522 Tests that no JSON file is generated if the default JSON listener is
523 shut down before RUN_ALL_TESTS is invoked.
526 json_path = os.path.join(gtest_test_utils.GetTempDir(),
527 GTEST_PROGRAM_NAME + 'out.json')
528 if os.path.isfile(json_path):
531 command = [GTEST_PROGRAM_PATH,
532 '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path),
534 p = gtest_test_utils.Subprocess(command)
535 if p.terminated_by_signal:
536 # p.signal is available only if p.terminated_by_signal is True.
538 p.terminated_by_signal,
539 '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
541 self.assert_(p.exited)
542 self.assertEquals(1, p.exit_code,
543 "'%s' exited with code %s, which doesn't match "
544 'the expected exit code %s.'
545 % (command, p.exit_code, 1))
547 self.assert_(not os.path.isfile(json_path))
549 def testFilteredTestJsonOutput(self):
550 """Verifies JSON output when a filter is applied.
552 Runs a test program that executes only some tests and verifies that
553 non-selected tests do not show up in the JSON output.
556 self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0,
557 extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
559 def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code):
560 """Returns the JSON output generated by running the program gtest_prog_name.
562 Furthermore, the program's exit code must be expected_exit_code.
565 gtest_prog_name: Google Test binary name.
566 extra_args: extra arguments to binary invocation.
567 expected_exit_code: program's exit code.
569 json_path = os.path.join(gtest_test_utils.GetTempDir(),
570 gtest_prog_name + 'out.json')
571 gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
574 [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] +
577 p = gtest_test_utils.Subprocess(command)
578 if p.terminated_by_signal:
580 '%s was killed by signal %d' % (gtest_prog_name, p.signal))
582 self.assert_(p.exited)
583 self.assertEquals(expected_exit_code, p.exit_code,
584 "'%s' exited with code %s, which doesn't match "
585 'the expected exit code %s.'
586 % (command, p.exit_code, expected_exit_code))
587 with open(json_path) as f:
588 actual = json.load(f)
591 def _TestJsonOutput(self, gtest_prog_name, expected,
592 expected_exit_code, extra_args=None):
593 """Checks the JSON output generated by the Google Test binary.
595 Asserts that the JSON document generated by running the program
596 gtest_prog_name matches expected_json, a string containing another
597 JSON document. Furthermore, the program's exit code must be
601 gtest_prog_name: Google Test binary name.
602 expected: expected output.
603 expected_exit_code: program's exit code.
604 extra_args: extra arguments to binary invocation.
607 actual = self._GetJsonOutput(gtest_prog_name, extra_args or [],
609 self.assertEqual(expected, gtest_json_test_utils.normalize(actual))
612 if __name__ == '__main__':
613 if NO_STACKTRACE_SUPPORT_FLAG in sys.argv:
614 # unittest.main() can't handle unknown flags
615 sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
617 os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
618 gtest_test_utils.Main()