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 = {
94 u'result': u'COMPLETED',
97 u'classname': u'SuccessfulTest'
128 u'failure': u'gtest_xml_output_unittest_.cc:*\n'
129 u'Expected equality of these values:\n'
130 u' 1\n 2' + STACK_TRACE_TEMPLATE,
150 u'name': u'DISABLED_test_not_run',
151 u'status': u'NOTRUN',
152 u'result': u'SUPPRESSED',
155 u'classname': u'DisabledTest'
175 u'result': u'SKIPPED',
178 u'classname': u'SkippedTest'
180 u'name': u'SkippedWithMessage',
182 u'result': u'SKIPPED',
185 u'classname': u'SkippedTest'
188 u'SkippedAfterFailure',
200 u'failure': u'gtest_xml_output_unittest_.cc:*\n'
201 u'Expected equality of these values:\n'
202 u' 1\n 2' + STACK_TRACE_TEMPLATE,
222 u'name': u'Succeeds',
224 u'result': u'COMPLETED',
227 u'classname': u'MixedResultTest'
242 u'failure': u'gtest_xml_output_unittest_.cc:*\n'
243 u'Expected equality of these values:\n'
244 u' 1\n 2' + STACK_TRACE_TEMPLATE,
247 u'failure': u'gtest_xml_output_unittest_.cc:*\n'
248 u'Expected equality of these values:\n'
249 u' 2\n 3' + STACK_TRACE_TEMPLATE,
253 u'name': u'DISABLED_test',
254 u'status': u'NOTRUN',
255 u'result': u'SUPPRESSED',
258 u'classname': u'MixedResultTest'
289 u'failure': u'gtest_xml_output_unittest_.cc:*\n'
290 u'Failed\nXML output: <?xml encoding="utf-8">'
291 u'<top><![CDATA[cdata text]]></top>' +
292 STACK_TRACE_TEMPLATE,
298 u'InvalidCharactersTest',
313 u'InvalidCharactersInMessage',
323 u'InvalidCharactersTest',
325 u'failure': u'gtest_xml_output_unittest_.cc:*\n'
326 u'Failed\nInvalid characters in brackets'
327 u' [\x01\x02]' + STACK_TRACE_TEMPLATE,
333 u'PropertyRecordingTest',
348 u'TearDownTestSuite':
351 u'name': u'OneProperty',
353 u'result': u'COMPLETED',
356 u'classname': u'PropertyRecordingTest',
359 u'name': u'IntValuedProperty',
361 u'result': u'COMPLETED',
364 u'classname': u'PropertyRecordingTest',
367 u'name': u'ThreeProperties',
369 u'result': u'COMPLETED',
372 u'classname': u'PropertyRecordingTest',
377 u'name': u'TwoValuesForOneKeyUsesLastValue',
379 u'result': u'COMPLETED',
382 u'classname': u'PropertyRecordingTest',
401 u'name': u'RecordProperty',
403 u'result': u'COMPLETED',
406 u'classname': u'NoFixtureTest',
409 u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',
411 u'result': u'COMPLETED',
414 u'classname': u'NoFixtureTest',
415 u'key_for_utility_int': u'1'
417 u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty',
419 u'result': u'COMPLETED',
422 u'classname': u'NoFixtureTest',
423 u'key_for_utility_string': u'1'
441 u'name': u'HasTypeParamAttribute',
442 u'type_param': u'int',
444 u'result': u'COMPLETED',
447 u'classname': u'TypedTest/0'
465 u'name': u'HasTypeParamAttribute',
466 u'type_param': u'long',
468 u'result': u'COMPLETED',
471 u'classname': u'TypedTest/1'
475 u'Single/TypeParameterizedTestSuite/0',
489 u'name': u'HasTypeParamAttribute',
490 u'type_param': u'int',
492 u'result': u'COMPLETED',
495 u'classname': u'Single/TypeParameterizedTestSuite/0'
499 u'Single/TypeParameterizedTestSuite/1',
513 u'name': u'HasTypeParamAttribute',
514 u'type_param': u'long',
516 u'result': u'COMPLETED',
519 u'classname': u'Single/TypeParameterizedTestSuite/1'
523 u'Single/ValueParamTest',
537 u'name': u'HasValueParamAttribute/0',
538 u'value_param': u'33',
540 u'result': u'COMPLETED',
543 u'classname': u'Single/ValueParamTest'
545 u'name': u'HasValueParamAttribute/1',
546 u'value_param': u'42',
548 u'result': u'COMPLETED',
551 u'classname': u'Single/ValueParamTest'
553 u'name': u'AnotherTestThatHasValueParamAttribute/0',
554 u'value_param': u'33',
556 u'result': u'COMPLETED',
559 u'classname': u'Single/ValueParamTest'
561 u'name': u'AnotherTestThatHasValueParamAttribute/1',
562 u'value_param': u'42',
564 u'result': u'COMPLETED',
567 u'classname': u'Single/ValueParamTest'
572 EXPECTED_FILTERED = {
605 u'name': u'Succeeds',
607 u'result': u'COMPLETED',
610 u'classname': u'SuccessfulTest',
632 u'NonTestSuiteFailure',
661 u'failure': u'gtest_no_test_unittest.cc:*\n'
662 u'Expected equality of these values:\n'
663 u' 1\n 2' + STACK_TRACE_TEMPLATE,
670 GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)
672 SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(
673 [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output
676 class GTestJsonOutputUnitTest(gtest_test_utils.TestCase):
677 """Unit test for Google Test's JSON output functionality.
680 # This test currently breaks on platforms that do not support typed and
681 # type-parameterized tests, so we don't run it under them.
682 if SUPPORTS_TYPED_TESTS:
684 def testNonEmptyJsonOutput(self):
685 """Verifies JSON output for a Google Test binary with non-empty output.
687 Runs a test program that generates a non-empty JSON output, and
688 tests that the JSON output is expected.
690 self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1)
692 def testNoTestJsonOutput(self):
693 """Verifies JSON output for a Google Test binary without actual tests.
695 Runs a test program that generates an JSON output for a binary with no
696 tests, and tests that the JSON output is expected.
699 self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_NO_TEST, 0)
701 def testTimestampValue(self):
702 """Checks whether the timestamp attribute in the JSON output is valid.
704 Runs a test program that generates an empty JSON output, and checks if
705 the timestamp attribute in the testsuites tag is valid.
707 actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0)
708 date_time_str = actual['timestamp']
709 # datetime.strptime() is only available in Python 2.5+ so we have to
710 # parse the expected datetime manually.
711 match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
714 'JSON datettime string %s has incorrect format' % date_time_str)
715 date_time_from_json = datetime.datetime(
716 year=int(match.group(1)), month=int(match.group(2)),
717 day=int(match.group(3)), hour=int(match.group(4)),
718 minute=int(match.group(5)), second=int(match.group(6)))
720 time_delta = abs(datetime.datetime.now() - date_time_from_json)
721 # timestamp value should be near the current local time
722 self.assertTrue(time_delta < datetime.timedelta(seconds=600),
723 'time_delta is %s' % time_delta)
725 def testDefaultOutputFile(self):
726 """Verifies the default output file name.
728 Confirms that Google Test produces an JSON output file with the expected
729 default name if no name is explicitly specified.
731 output_file = os.path.join(gtest_test_utils.GetTempDir(),
732 GTEST_DEFAULT_OUTPUT_FILE)
733 gtest_prog_path = gtest_test_utils.GetTestExecutablePath(
734 'gtest_no_test_unittest')
736 os.remove(output_file)
738 e = sys.exc_info()[1]
739 if e.errno != errno.ENOENT:
742 p = gtest_test_utils.Subprocess(
743 [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG],
744 working_dir=gtest_test_utils.GetTempDir())
745 self.assert_(p.exited)
746 self.assertEquals(0, p.exit_code)
747 self.assert_(os.path.isfile(output_file))
749 def testSuppressedJsonOutput(self):
750 """Verifies that no JSON output is generated.
752 Tests that no JSON file is generated if the default JSON listener is
753 shut down before RUN_ALL_TESTS is invoked.
756 json_path = os.path.join(gtest_test_utils.GetTempDir(),
757 GTEST_PROGRAM_NAME + 'out.json')
758 if os.path.isfile(json_path):
761 command = [GTEST_PROGRAM_PATH,
762 '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path),
764 p = gtest_test_utils.Subprocess(command)
765 if p.terminated_by_signal:
766 # p.signal is available only if p.terminated_by_signal is True.
768 p.terminated_by_signal,
769 '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))
771 self.assert_(p.exited)
772 self.assertEquals(1, p.exit_code,
773 "'%s' exited with code %s, which doesn't match "
774 'the expected exit code %s.'
775 % (command, p.exit_code, 1))
777 self.assert_(not os.path.isfile(json_path))
779 def testFilteredTestJsonOutput(self):
780 """Verifies JSON output when a filter is applied.
782 Runs a test program that executes only some tests and verifies that
783 non-selected tests do not show up in the JSON output.
786 self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0,
787 extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])
789 def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code):
790 """Returns the JSON output generated by running the program gtest_prog_name.
792 Furthermore, the program's exit code must be expected_exit_code.
795 gtest_prog_name: Google Test binary name.
796 extra_args: extra arguments to binary invocation.
797 expected_exit_code: program's exit code.
799 json_path = os.path.join(gtest_test_utils.GetTempDir(),
800 gtest_prog_name + 'out.json')
801 gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)
804 [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] +
807 p = gtest_test_utils.Subprocess(command)
808 if p.terminated_by_signal:
810 '%s was killed by signal %d' % (gtest_prog_name, p.signal))
812 self.assert_(p.exited)
813 self.assertEquals(expected_exit_code, p.exit_code,
814 "'%s' exited with code %s, which doesn't match "
815 'the expected exit code %s.'
816 % (command, p.exit_code, expected_exit_code))
817 with open(json_path) as f:
818 actual = json.load(f)
821 def _TestJsonOutput(self, gtest_prog_name, expected,
822 expected_exit_code, extra_args=None):
823 """Checks the JSON output generated by the Google Test binary.
825 Asserts that the JSON document generated by running the program
826 gtest_prog_name matches expected_json, a string containing another
827 JSON document. Furthermore, the program's exit code must be
831 gtest_prog_name: Google Test binary name.
832 expected: expected output.
833 expected_exit_code: program's exit code.
834 extra_args: extra arguments to binary invocation.
837 actual = self._GetJsonOutput(gtest_prog_name, extra_args or [],
839 self.assertEqual(expected, gtest_json_test_utils.normalize(actual))
842 if __name__ == '__main__':
843 if NO_STACKTRACE_SUPPORT_FLAG in sys.argv:
844 # unittest.main() can't handle unknown flags
845 sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
847 os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'
848 gtest_test_utils.Main()