diff options
Diffstat (limited to 'googletest/test')
56 files changed, 2881 insertions, 3075 deletions
diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index a930d65e0440..156d5d4b423c 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -32,24 +32,12 @@ # # Bazel BUILD for The Google C++ Testing Framework (Google Test) -licenses(["notice"]) - -config_setting( - name = "windows", - values = {"cpu": "x64_windows"}, -) +load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test") +load("@rules_python//python:defs.bzl", "py_library", "py_test") -config_setting( - name = "windows_msvc", - values = {"cpu": "x64_windows_msvc"}, -) - -config_setting( - name = "has_absl", - values = {"define": "absl=1"}, -) +licenses(["notice"]) -#on windows exclude gtest-tuple.h and googletest-tuple-test.cc +#on windows exclude gtest-tuple.h cc_test( name = "gtest_all_test", size = "small", @@ -62,7 +50,6 @@ cc_test( ], exclude = [ "gtest-unittest-api_test.cc", - "googletest-tuple-test.cc", "googletest/src/gtest-all.cc", "gtest_all_test.cc", "gtest-death-test_ex_test.cc", @@ -74,28 +61,23 @@ cc_test( "googletest-env-var-test_.cc", "googletest-filter-unittest_.cc", "googletest-break-on-failure-unittest_.cc", - "googletest-listener-test.cc", - "googletest-output-test_.cc", - "googletest-list-tests-unittest_.cc", - "googletest-shuffle-test_.cc", - "googletest-uninitialized-test_.cc", - "googletest-death-test_ex_test.cc", - "googletest-param-test-test", - "googletest-throw-on-failure-test_.cc", - "googletest-param-test-invalid-name1-test_.cc", - "googletest-param-test-invalid-name2-test_.cc", - + "googletest-listener-test.cc", + "googletest-output-test_.cc", + "googletest-list-tests-unittest_.cc", + "googletest-shuffle-test_.cc", + "googletest-uninitialized-test_.cc", + "googletest-death-test_ex_test.cc", + "googletest-param-test-test", + "googletest-throw-on-failure-test_.cc", + "googletest-param-test-invalid-name1-test_.cc", + "googletest-param-test-invalid-name2-test_.cc", ], ) + select({ "//:windows": [], - "//:windows_msvc": [], - "//conditions:default": [ - "googletest-tuple-test.cc", - ], + "//conditions:default": [], }), copts = select({ "//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], - "//:windows_msvc": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], "//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"], }), includes = [ @@ -106,15 +88,11 @@ cc_test( ], linkopts = select({ "//:windows": [], - "//:windows_msvc": [], - "//conditions:default": [ - "-pthread", - ], + "//conditions:default": ["-pthread"], }), deps = ["//:gtest_main"], ) - # Tests death tests. cc_test( name = "googletest-death-test-test", @@ -199,13 +177,12 @@ cc_binary( deps = ["//:gtest"], ) - py_test( name = "googletest-output-test", size = "small", srcs = ["googletest-output-test.py"], args = select({ - ":has_absl": [], + "//:has_absl": [], "//conditions:default": ["--no_stacktrace_support"], }), data = [ @@ -260,7 +237,6 @@ py_test( deps = [":gtest_test_utils"], ) - cc_binary( name = "googletest-break-on-failure-unittest_", testonly = 1, @@ -268,8 +244,6 @@ cc_binary( deps = ["//:gtest"], ) - - py_test( name = "googletest-break-on-failure-unittest", size = "small", @@ -278,7 +252,6 @@ py_test( deps = [":gtest_test_utils"], ) - cc_test( name = "gtest_assert_by_exception_test", size = "small", @@ -286,8 +259,6 @@ cc_test( deps = ["//:gtest"], ) - - cc_binary( name = "googletest-throw-on-failure-test_", testonly = 1, @@ -303,7 +274,6 @@ py_test( deps = [":gtest_test_utils"], ) - cc_binary( name = "googletest-list-tests-unittest_", testonly = 1, @@ -311,6 +281,30 @@ cc_binary( deps = ["//:gtest"], ) +cc_test( + name = "gtest_skip_test", + size = "small", + srcs = ["gtest_skip_test.cc"], + deps = ["//:gtest_main"], +) + +cc_test( + name = "gtest_skip_in_environment_setup_test", + size = "small", + srcs = ["gtest_skip_in_environment_setup_test.cc"], + deps = ["//:gtest_main"], +) + +py_test( + name = "gtest_skip_environment_check_output_test", + size = "small", + srcs = ["gtest_skip_environment_check_output_test.py"], + data = [ + ":gtest_skip_in_environment_setup_test", + ], + deps = [":gtest_test_utils"], +) + py_test( name = "googletest-list-tests-unittest", size = "small", @@ -381,7 +375,7 @@ py_test( "gtest_xml_test_utils.py", ], args = select({ - ":has_absl": [], + "//:has_absl": [], "//conditions:default": ["--no_stacktrace_support"], }), data = [ @@ -452,7 +446,6 @@ py_test( deps = [":gtest_test_utils"], ) - py_test( name = "googletest-json-outfiles-test", size = "small", @@ -474,18 +467,19 @@ py_test( "googletest-json-output-unittest.py", "gtest_json_test_utils.py", ], + args = select({ + "//:has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), data = [ # We invoke gtest_no_test_unittest to verify the JSON output # when the test program contains no test definition. ":gtest_no_test_unittest", ":gtest_xml_output_unittest_", ], - args = select({ - ":has_absl": [], - "//conditions:default": ["--no_stacktrace_support"], - }), deps = [":gtest_test_utils"], ) + # Verifies interaction of death tests and exceptions. cc_test( name = "googletest-death-test_ex_catch_test", diff --git a/googletest/test/googletest-catch-exceptions-test.py b/googletest/test/googletest-catch-exceptions-test.py index 5d49c1023c50..94a5b33f2305 100755 --- a/googletest/test/googletest-catch-exceptions-test.py +++ b/googletest/test/googletest-catch-exceptions-test.py @@ -89,9 +89,9 @@ if SUPPORTS_SEH_EXCEPTIONS: self.assert_('SEH exception with code 0x2a thrown ' 'in the test fixture\'s destructor' in test_output) - self.assert_('SEH exception with code 0x2a thrown in SetUpTestCase()' + self.assert_('SEH exception with code 0x2a thrown in SetUpTestSuite()' in test_output) - self.assert_('SEH exception with code 0x2a thrown in TearDownTestCase()' + self.assert_('SEH exception with code 0x2a thrown in TearDownTestSuite()' in test_output) self.assert_('SEH exception with code 0x2a thrown in SetUp()' in test_output) @@ -117,10 +117,11 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase): """ def testCatchesCxxExceptionsInFixtureConstructor(self): - self.assert_('C++ exception with description ' - '"Standard C++ exception" thrown ' - 'in the test fixture\'s constructor' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'C++ exception with description ' + '"Standard C++ exception" thrown ' + 'in the test fixture\'s constructor' in EX_BINARY_OUTPUT, + EX_BINARY_OUTPUT) self.assert_('unexpected' not in EX_BINARY_OUTPUT, 'This failure belongs in this test only if ' '"CxxExceptionInConstructorTest" (no quotes) ' @@ -130,88 +131,90 @@ class CatchCxxExceptionsTest(gtest_test_utils.TestCase): EX_BINARY_OUTPUT): def testCatchesCxxExceptionsInFixtureDestructor(self): - self.assert_('C++ exception with description ' - '"Standard C++ exception" thrown ' - 'in the test fixture\'s destructor' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInDestructorTest::TearDownTestCase() ' - 'called as expected.' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'C++ exception with description ' + '"Standard C++ exception" thrown ' + 'in the test fixture\'s destructor' in EX_BINARY_OUTPUT, + EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInDestructorTest::TearDownTestSuite() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInSetUpTestCase(self): - self.assert_('C++ exception with description "Standard C++ exception"' - ' thrown in SetUpTestCase()' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInConstructorTest::TearDownTestCase() ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTestCaseTest constructor ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTestCaseTest destructor ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTestCaseTest::SetUp() ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTestCaseTest::TearDown() ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTestCaseTest test body ' - 'called as expected.' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'C++ exception with description "Standard C++ exception"' + ' thrown in SetUpTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInConstructorTest::TearDownTestSuite() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTestSuiteTest constructor ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTestSuiteTest destructor ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTestSuiteTest::SetUp() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTestSuiteTest::TearDown() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTestSuiteTest test body ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInTearDownTestCase(self): - self.assert_('C++ exception with description "Standard C++ exception"' - ' thrown in TearDownTestCase()' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'C++ exception with description "Standard C++ exception"' + ' thrown in TearDownTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInSetUp(self): - self.assert_('C++ exception with description "Standard C++ exception"' - ' thrown in SetUp()' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTest::TearDownTestCase() ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTest destructor ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInSetUpTest::TearDown() ' - 'called as expected.' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'C++ exception with description "Standard C++ exception"' + ' thrown in SetUp()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTest::TearDownTestSuite() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTest destructor ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInSetUpTest::TearDown() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) self.assert_('unexpected' not in EX_BINARY_OUTPUT, 'This failure belongs in this test only if ' '"CxxExceptionInSetUpTest" (no quotes) ' 'appears on the same line as words "called unexpectedly"') def testCatchesCxxExceptionsInTearDown(self): - self.assert_('C++ exception with description "Standard C++ exception"' - ' thrown in TearDown()' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInTearDownTest::TearDownTestCase() ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInTearDownTest destructor ' - 'called as expected.' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'C++ exception with description "Standard C++ exception"' + ' thrown in TearDown()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInTearDownTest::TearDownTestSuite() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInTearDownTest destructor ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesCxxExceptionsInTestBody(self): - self.assert_('C++ exception with description "Standard C++ exception"' - ' thrown in the test body' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInTestBodyTest::TearDownTestCase() ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInTestBodyTest destructor ' - 'called as expected.' - in EX_BINARY_OUTPUT) - self.assert_('CxxExceptionInTestBodyTest::TearDown() ' - 'called as expected.' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'C++ exception with description "Standard C++ exception"' + ' thrown in the test body' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInTestBodyTest::TearDownTestSuite() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInTestBodyTest destructor ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) + self.assertTrue( + 'CxxExceptionInTestBodyTest::TearDown() ' + 'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT) def testCatchesNonStdCxxExceptions(self): - self.assert_('Unknown C++ exception thrown in the test body' - in EX_BINARY_OUTPUT) + self.assertTrue( + 'Unknown C++ exception thrown in the test body' in EX_BINARY_OUTPUT, + EX_BINARY_OUTPUT) def testUnhandledCxxExceptionsAbortTheProgram(self): # Filters out SEH exception tests on Windows. Unhandled SEH exceptions diff --git a/googletest/test/googletest-catch-exceptions-test_.cc b/googletest/test/googletest-catch-exceptions-test_.cc index 09dae70030a3..8c127d40b11d 100644 --- a/googletest/test/googletest-catch-exceptions-test_.cc +++ b/googletest/test/googletest-catch-exceptions-test_.cc @@ -64,19 +64,20 @@ class SehExceptionInDestructorTest : public Test { TEST_F(SehExceptionInDestructorTest, ThrowsExceptionInDestructor) {} -class SehExceptionInSetUpTestCaseTest : public Test { +class SehExceptionInSetUpTestSuiteTest : public Test { public: - static void SetUpTestCase() { RaiseException(42, 0, 0, NULL); } + static void SetUpTestSuite() { RaiseException(42, 0, 0, NULL); } }; -TEST_F(SehExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) {} +TEST_F(SehExceptionInSetUpTestSuiteTest, ThrowsExceptionInSetUpTestSuite) {} -class SehExceptionInTearDownTestCaseTest : public Test { +class SehExceptionInTearDownTestSuiteTest : public Test { public: - static void TearDownTestCase() { RaiseException(42, 0, 0, NULL); } + static void TearDownTestSuite() { RaiseException(42, 0, 0, NULL); } }; -TEST_F(SehExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {} +TEST_F(SehExceptionInTearDownTestSuiteTest, + ThrowsExceptionInTearDownTestSuite) {} class SehExceptionInSetUpTest : public Test { protected: @@ -109,24 +110,24 @@ class CxxExceptionInConstructorTest : public Test { throw std::runtime_error("Standard C++ exception")); } - static void TearDownTestCase() { + static void TearDownTestSuite() { printf("%s", - "CxxExceptionInConstructorTest::TearDownTestCase() " + "CxxExceptionInConstructorTest::TearDownTestSuite() " "called as expected.\n"); } protected: - ~CxxExceptionInConstructorTest() { + ~CxxExceptionInConstructorTest() override { ADD_FAILURE() << "CxxExceptionInConstructorTest destructor " << "called unexpectedly."; } - virtual void SetUp() { + void SetUp() override { ADD_FAILURE() << "CxxExceptionInConstructorTest::SetUp() " << "called unexpectedly."; } - virtual void TearDown() { + void TearDown() override { ADD_FAILURE() << "CxxExceptionInConstructorTest::TearDown() " << "called unexpectedly."; } @@ -137,97 +138,78 @@ TEST_F(CxxExceptionInConstructorTest, ThrowsExceptionInConstructor) { << "called unexpectedly."; } -// Exceptions in destructors are not supported in C++11. -#if !GTEST_LANG_CXX11 -class CxxExceptionInDestructorTest : public Test { +class CxxExceptionInSetUpTestSuiteTest : public Test { public: - static void TearDownTestCase() { + CxxExceptionInSetUpTestSuiteTest() { printf("%s", - "CxxExceptionInDestructorTest::TearDownTestCase() " + "CxxExceptionInSetUpTestSuiteTest constructor " "called as expected.\n"); } - protected: - ~CxxExceptionInDestructorTest() { - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_( - throw std::runtime_error("Standard C++ exception")); - } -}; - -TEST_F(CxxExceptionInDestructorTest, ThrowsExceptionInDestructor) {} -#endif // C++11 mode - -class CxxExceptionInSetUpTestCaseTest : public Test { - public: - CxxExceptionInSetUpTestCaseTest() { - printf("%s", - "CxxExceptionInSetUpTestCaseTest constructor " - "called as expected.\n"); - } - - static void SetUpTestCase() { + static void SetUpTestSuite() { throw std::runtime_error("Standard C++ exception"); } - static void TearDownTestCase() { + static void TearDownTestSuite() { printf("%s", - "CxxExceptionInSetUpTestCaseTest::TearDownTestCase() " + "CxxExceptionInSetUpTestSuiteTest::TearDownTestSuite() " "called as expected.\n"); } protected: - ~CxxExceptionInSetUpTestCaseTest() { + ~CxxExceptionInSetUpTestSuiteTest() override { printf("%s", - "CxxExceptionInSetUpTestCaseTest destructor " + "CxxExceptionInSetUpTestSuiteTest destructor " "called as expected.\n"); } - virtual void SetUp() { + void SetUp() override { printf("%s", - "CxxExceptionInSetUpTestCaseTest::SetUp() " + "CxxExceptionInSetUpTestSuiteTest::SetUp() " "called as expected.\n"); } - virtual void TearDown() { + void TearDown() override { printf("%s", - "CxxExceptionInSetUpTestCaseTest::TearDown() " + "CxxExceptionInSetUpTestSuiteTest::TearDown() " "called as expected.\n"); } }; -TEST_F(CxxExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) { +TEST_F(CxxExceptionInSetUpTestSuiteTest, ThrowsExceptionInSetUpTestSuite) { printf("%s", - "CxxExceptionInSetUpTestCaseTest test body " + "CxxExceptionInSetUpTestSuiteTest test body " "called as expected.\n"); } -class CxxExceptionInTearDownTestCaseTest : public Test { +class CxxExceptionInTearDownTestSuiteTest : public Test { public: - static void TearDownTestCase() { + static void TearDownTestSuite() { throw std::runtime_error("Standard C++ exception"); } }; -TEST_F(CxxExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {} +TEST_F(CxxExceptionInTearDownTestSuiteTest, + ThrowsExceptionInTearDownTestSuite) {} class CxxExceptionInSetUpTest : public Test { public: - static void TearDownTestCase() { + static void TearDownTestSuite() { printf("%s", - "CxxExceptionInSetUpTest::TearDownTestCase() " + "CxxExceptionInSetUpTest::TearDownTestSuite() " "called as expected.\n"); } protected: - ~CxxExceptionInSetUpTest() { + ~CxxExceptionInSetUpTest() override { printf("%s", "CxxExceptionInSetUpTest destructor " "called as expected.\n"); } - virtual void SetUp() { throw std::runtime_error("Standard C++ exception"); } + void SetUp() override { throw std::runtime_error("Standard C++ exception"); } - virtual void TearDown() { + void TearDown() override { printf("%s", "CxxExceptionInSetUpTest::TearDown() " "called as expected.\n"); @@ -241,20 +223,20 @@ TEST_F(CxxExceptionInSetUpTest, ThrowsExceptionInSetUp) { class CxxExceptionInTearDownTest : public Test { public: - static void TearDownTestCase() { + static void TearDownTestSuite() { printf("%s", - "CxxExceptionInTearDownTest::TearDownTestCase() " + "CxxExceptionInTearDownTest::TearDownTestSuite() " "called as expected.\n"); } protected: - ~CxxExceptionInTearDownTest() { + ~CxxExceptionInTearDownTest() override { printf("%s", "CxxExceptionInTearDownTest destructor " "called as expected.\n"); } - virtual void TearDown() { + void TearDown() override { throw std::runtime_error("Standard C++ exception"); } }; @@ -263,20 +245,20 @@ TEST_F(CxxExceptionInTearDownTest, ThrowsExceptionInTearDown) {} class CxxExceptionInTestBodyTest : public Test { public: - static void TearDownTestCase() { + static void TearDownTestSuite() { printf("%s", - "CxxExceptionInTestBodyTest::TearDownTestCase() " + "CxxExceptionInTestBodyTest::TearDownTestSuite() " "called as expected.\n"); } protected: - ~CxxExceptionInTestBodyTest() { + ~CxxExceptionInTestBodyTest() override { printf("%s", "CxxExceptionInTestBodyTest destructor " "called as expected.\n"); } - virtual void TearDown() { + void TearDown() override { printf("%s", "CxxExceptionInTestBodyTest::TearDown() " "called as expected.\n"); @@ -296,7 +278,7 @@ TEST(CxxExceptionTest, ThrowsNonStdCxxException) { // ones. void TerminateHandler() { fprintf(stderr, "%s\n", "Unhandled C++ exception terminating the program."); - fflush(NULL); + fflush(nullptr); exit(3); } diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc index c0c3026fb589..cba906ccd861 100644 --- a/googletest/test/googletest-death-test-test.cc +++ b/googletest/test/googletest-death-test-test.cc @@ -31,6 +31,7 @@ // Tests for death tests. #include "gtest/gtest-death-test.h" + #include "gtest/gtest.h" #include "gtest/internal/gtest-filepath.h" @@ -40,7 +41,9 @@ using testing::internal::AlwaysTrue; #if GTEST_HAS_DEATH_TEST # if GTEST_OS_WINDOWS +# include <fcntl.h> // For O_BINARY # include <direct.h> // For chdir(). +# include <io.h> # else # include <unistd.h> # include <sys/wait.h> // For waitpid. @@ -59,6 +62,8 @@ using testing::internal::AlwaysTrue; namespace posix = ::testing::internal::posix; +using testing::ContainsRegex; +using testing::Matcher; using testing::Message; using testing::internal::DeathTest; using testing::internal::DeathTestFactory; @@ -97,6 +102,8 @@ class ReplaceDeathTestFactory { } // namespace internal } // namespace testing +namespace { + void DieWithMessage(const ::std::string& message) { fprintf(stderr, "%s", message.c_str()); fflush(stderr); // Make sure the text is printed before the process exits. @@ -123,9 +130,7 @@ class TestForDeathTest : public testing::Test { protected: TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {} - virtual ~TestForDeathTest() { - posix::ChDir(original_dir_.c_str()); - } + ~TestForDeathTest() override { posix::ChDir(original_dir_.c_str()); } // A static member function that's expected to die. static void StaticMemberFunction() { DieInside("StaticMemberFunction"); } @@ -136,7 +141,7 @@ class TestForDeathTest : public testing::Test { DieInside("MemberFunction"); } - // True iff MemberFunction() should die. + // True if and only if MemberFunction() should die. bool should_die_; const FilePath original_dir_; }; @@ -153,7 +158,7 @@ class MayDie { } private: - // True iff MemberFunction() should die. + // True if and only if MemberFunction() should die. bool should_die_; }; @@ -199,6 +204,26 @@ int DieInDebugElse12(int* sideeffect) { return 12; } +# if GTEST_OS_WINDOWS + +// Death in dbg due to Windows CRT assertion failure, not opt. +int DieInCRTDebugElse12(int* sideeffect) { + if (sideeffect) *sideeffect = 12; + + // Create an invalid fd by closing a valid one + int fdpipe[2]; + EXPECT_EQ(_pipe(fdpipe, 256, O_BINARY), 0); + EXPECT_EQ(_close(fdpipe[0]), 0); + EXPECT_EQ(_close(fdpipe[1]), 0); + + // _dup() should crash in debug mode + EXPECT_EQ(_dup(fdpipe[0]), -1); + + return 12; +} + +#endif // GTEST_OS_WINDOWS + # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA // Tests the ExitedWithCode predicate. @@ -297,14 +322,14 @@ TEST_F(TestForDeathTest, SingleStatement) { EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3; } +# if GTEST_USES_PCRE + void DieWithEmbeddedNul() { fprintf(stderr, "Hello%cmy null world.\n", '\0'); fflush(stderr); _exit(1); } -# if GTEST_USES_PCRE - // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error // message has a NUL character in it. TEST_F(TestForDeathTest, EmbeddedNulInMessage) { @@ -370,13 +395,13 @@ void SetSigprofActionAndTimer() { timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 1; timer.it_value = timer.it_interval; - ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL)); + ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr)); struct sigaction signal_action; memset(&signal_action, 0, sizeof(signal_action)); sigemptyset(&signal_action.sa_mask); signal_action.sa_sigaction = SigprofAction; signal_action.sa_flags = SA_RESTART | SA_SIGINFO; - ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL)); + ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr)); } // Disables ITIMER_PROF timer and ignores SIGPROF signal. @@ -385,7 +410,7 @@ void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) { timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 0; timer.it_value = timer.it_interval; - ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL)); + ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr)); struct sigaction signal_action; memset(&signal_action, 0, sizeof(signal_action)); sigemptyset(&signal_action.sa_mask); @@ -452,21 +477,17 @@ TEST_F(TestForDeathTest, MixedStyles) { # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD -namespace { - bool pthread_flag; void SetPthreadFlag() { pthread_flag = true; } -} // namespace - TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { if (!testing::GTEST_FLAG(death_test_use_fork)) { testing::GTEST_FLAG(death_test_style) = "threadsafe"; pthread_flag = false; - ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL)); + ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr)); ASSERT_DEATH(_exit(1), ""); ASSERT_FALSE(pthread_flag); } @@ -494,18 +515,15 @@ TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { const testing::internal::RE regex(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex); -# if GTEST_HAS_GLOBAL_STRING - - const ::string regex_str(regex_c_str); - EXPECT_DEATH(GlobalFunction(), regex_str); - -# endif // GTEST_HAS_GLOBAL_STRING - # if !GTEST_USES_PCRE const ::std::string regex_std_str(regex_c_str); EXPECT_DEATH(GlobalFunction(), regex_std_str); + // This one is tricky; a temporary pointer into another temporary. Reference + // lifetime extension of the pointer is not sufficient. + EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str()); + # endif // !GTEST_USES_PCRE } @@ -555,8 +573,8 @@ TEST_F(TestForDeathTest, ErrorMessageMismatch) { }, "died but not with expected error"); } -// On exit, *aborted will be true iff the EXPECT_DEATH() statement -// aborted the function. +// On exit, *aborted will be true if and only if the EXPECT_DEATH() +// statement aborted the function. void ExpectDeathTestHelper(bool* aborted) { *aborted = true; EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. @@ -636,6 +654,40 @@ TEST_F(TestForDeathTest, TestExpectDebugDeath) { # endif } +# if GTEST_OS_WINDOWS + +// Tests that EXPECT_DEBUG_DEATH works as expected when in debug mode +// the Windows CRT crashes the process with an assertion failure. +// 1. Asserts on death. +// 2. Has no side effect (doesn't pop up a window or wait for user input). +// +// And in opt mode, it: +// 1. Has side effects but does not assert. +TEST_F(TestForDeathTest, CRTDebugDeath) { + int sideeffect = 0; + + // Put the regex in a local variable to make sure we don't get an "unused" + // warning in opt mode. + const char* regex = "dup.* : Assertion failed"; + + EXPECT_DEBUG_DEATH(DieInCRTDebugElse12(&sideeffect), regex) + << "Must accept a streamed message"; + +# ifdef NDEBUG + + // Checks that the assignment occurs in opt mode (sideeffect). + EXPECT_EQ(12, sideeffect); + +# else + + // Checks that the assignment does not occur in dbg mode (no sideeffect). + EXPECT_EQ(0, sideeffect); + +# endif +} + +# endif // GTEST_OS_WINDOWS + // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a // message to it, and in debug mode it: // 1. Asserts on death. @@ -876,9 +928,9 @@ TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) { class MockDeathTestFactory : public DeathTestFactory { public: MockDeathTestFactory(); - virtual bool Create(const char* statement, - const ::testing::internal::RE* regex, - const char* file, int line, DeathTest** test); + bool Create(const char* statement, + testing::Matcher<const std::string&> matcher, const char* file, + int line, DeathTest** test) override; // Sets the parameters for subsequent calls to Create. void SetParameters(bool create, DeathTest::TestRole role, @@ -888,10 +940,12 @@ class MockDeathTestFactory : public DeathTestFactory { int AssumeRoleCalls() const { return assume_role_calls_; } int WaitCalls() const { return wait_calls_; } size_t PassedCalls() const { return passed_args_.size(); } - bool PassedArgument(int n) const { return passed_args_[n]; } + bool PassedArgument(int n) const { + return passed_args_[static_cast<size_t>(n)]; + } size_t AbortCalls() const { return abort_args_.size(); } DeathTest::AbortReason AbortArgument(int n) const { - return abort_args_[n]; + return abort_args_[static_cast<size_t>(n)]; } bool TestDeleted() const { return test_deleted_; } @@ -933,22 +987,20 @@ class MockDeathTest : public DeathTest { TestRole role, int status, bool passed) : parent_(parent), role_(role), status_(status), passed_(passed) { } - virtual ~MockDeathTest() { - parent_->test_deleted_ = true; - } - virtual TestRole AssumeRole() { + ~MockDeathTest() override { parent_->test_deleted_ = true; } + TestRole AssumeRole() override { ++parent_->assume_role_calls_; return role_; } - virtual int Wait() { + int Wait() override { ++parent_->wait_calls_; return status_; } - virtual bool Passed(bool exit_status_ok) { + bool Passed(bool exit_status_ok) override { parent_->passed_args_.push_back(exit_status_ok); return passed_; } - virtual void Abort(AbortReason reason) { + void Abort(AbortReason reason) override { parent_->abort_args_.push_back(reason); } @@ -992,16 +1044,14 @@ void MockDeathTestFactory::SetParameters(bool create, // Sets test to NULL (if create_ is false) or to the address of a new // MockDeathTest object with parameters taken from the last call // to SetParameters (if create_ is true). Always returns true. -bool MockDeathTestFactory::Create(const char* /*statement*/, - const ::testing::internal::RE* /*regex*/, - const char* /*file*/, - int /*line*/, - DeathTest** test) { +bool MockDeathTestFactory::Create( + const char* /*statement*/, testing::Matcher<const std::string&> /*matcher*/, + const char* /*file*/, int /*line*/, DeathTest** test) { test_deleted_ = false; if (create_) { *test = new MockDeathTest(this, role_, status_, passed_); } else { - *test = NULL; + *test = nullptr; } return true; } @@ -1014,16 +1064,16 @@ class MacroLogicDeathTest : public testing::Test { static testing::internal::ReplaceDeathTestFactory* replacer_; static MockDeathTestFactory* factory_; - static void SetUpTestCase() { + static void SetUpTestSuite() { factory_ = new MockDeathTestFactory; replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_); } - static void TearDownTestCase() { + static void TearDownTestSuite() { delete replacer_; - replacer_ = NULL; + replacer_ = nullptr; delete factory_; - factory_ = NULL; + factory_ = nullptr; } // Runs a death test that breaks the rules by returning. Such a death @@ -1037,10 +1087,9 @@ class MacroLogicDeathTest : public testing::Test { } }; -testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ - = NULL; -MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL; - +testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ = + nullptr; +MockDeathTestFactory* MacroLogicDeathTest::factory_ = nullptr; // Test that nothing happens when the factory doesn't return a DeathTest: TEST_F(MacroLogicDeathTest, NothingHappens) { @@ -1279,9 +1328,6 @@ TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { # if GTEST_OS_WINDOWS TEST(EnvironmentTest, HandleFitsIntoSizeT) { - // FIXME: Remove this test after this condition is verified - // in a static assertion in gtest-death-test.cc in the function - // GetStatusFileDescriptor. ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); } # endif // GTEST_OS_WINDOWS @@ -1319,8 +1365,49 @@ TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { }, "Inside"); } +void DieWithMessage(const char* message) { + fputs(message, stderr); + fflush(stderr); // Make sure the text is printed before the process exits. + _exit(1); +} + +TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) { + // googletest tests this, of course; here we ensure that including googlemock + // has not broken it. + EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e"); +} + +TEST(MatcherDeathTest, MonomorphicMatcherMatches) { + EXPECT_DEATH(DieWithMessage("Behind O, I am slain!"), + Matcher<const std::string&>(ContainsRegex("I am slain"))); +} + +TEST(MatcherDeathTest, MonomorphicMatcherDoesNotMatch) { + EXPECT_NONFATAL_FAILURE( + EXPECT_DEATH( + DieWithMessage("Behind O, I am slain!"), + Matcher<const std::string&>(ContainsRegex("Ow, I am slain"))), + "Expected: contains regular expression \"Ow, I am slain\""); +} + +TEST(MatcherDeathTest, PolymorphicMatcherMatches) { + EXPECT_DEATH(DieWithMessage("The rest is silence."), + ContainsRegex("rest is silence")); +} + +TEST(MatcherDeathTest, PolymorphicMatcherDoesNotMatch) { + EXPECT_NONFATAL_FAILURE( + EXPECT_DEATH(DieWithMessage("The rest is silence."), + ContainsRegex("rest is science")), + "Expected: contains regular expression \"rest is science\""); +} + +} // namespace + #else // !GTEST_HAS_DEATH_TEST follows +namespace { + using testing::internal::CaptureStderr; using testing::internal::GetCapturedStderr; @@ -1369,8 +1456,12 @@ TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) { EXPECT_EQ(1, n); } +} // namespace + #endif // !GTEST_HAS_DEATH_TEST +namespace { + // Tests that the death test macros expand to code which may or may not // be followed by operator<<, and that in either case the complete text // comprises only a single C++ statement. @@ -1421,3 +1512,5 @@ TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { TEST(NotADeathTest, Test) { SUCCEED(); } + +} // namespace diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc index b8b9470fc88a..7ea5b9468e3b 100644 --- a/googletest/test/googletest-death-test_ex_test.cc +++ b/googletest/test/googletest-death-test_ex_test.cc @@ -59,7 +59,7 @@ TEST(CxxExceptionDeathTest, ExceptionIsFailure) { class TestException : public std::exception { public: - virtual const char* what() const throw() { return "exceptional message"; } + const char* what() const throw() override { return "exceptional message"; } }; TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { @@ -68,7 +68,7 @@ TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) { "exceptional message"); // Verifies that the location is mentioned in the failure text. EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""), - "googletest-death-test_ex_test.cc"); + __FILE__); } # endif // GTEST_HAS_EXCEPTIONS diff --git a/googletest/test/googletest-env-var-test.py b/googletest/test/googletest-env-var-test.py index e1efeee1eab8..2f0e406afcfc 100755 --- a/googletest/test/googletest-env-var-test.py +++ b/googletest/test/googletest-env-var-test.py @@ -45,8 +45,8 @@ environ = os.environ.copy() def AssertEq(expected, actual): if expected != actual: - print 'Expected: %s' % (expected,) - print ' Actual: %s' % (actual,) + print('Expected: %s' % (expected,)) + print(' Actual: %s' % (actual,)) raise AssertionError diff --git a/googletest/test/googletest-filepath-test.cc b/googletest/test/googletest-filepath-test.cc index 37f02fb4bd77..aafad36f3fef 100644 --- a/googletest/test/googletest-filepath-test.cc +++ b/googletest/test/googletest-filepath-test.cc @@ -50,8 +50,6 @@ namespace internal { namespace { #if GTEST_OS_WINDOWS_MOBILE -// FIXME: Move these to the POSIX adapter section in -// gtest-port.h. // Windows CE doesn't have the remove C function. int remove(const char* path) { @@ -80,7 +78,7 @@ TEST(GetCurrentDirTest, ReturnsCurrentDir) { const FilePath cwd = FilePath::GetCurrentDir(); posix::ChDir(original_dir.c_str()); -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS || GTEST_OS_OS2 // Skips the ":". const char* const cwd_without_drive = strchr(cwd.c_str(), ':'); @@ -479,7 +477,7 @@ TEST(AssignmentOperatorTest, ConstAssignedToNonConst) { class DirectoryCreationTest : public Test { protected: - virtual void SetUp() { + void SetUp() override { testdata_path_.Set(FilePath( TempDir() + GetCurrentExecutableName().string() + "_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_)); @@ -496,7 +494,7 @@ class DirectoryCreationTest : public Test { posix::RmDir(testdata_path_.c_str()); } - virtual void TearDown() { + void TearDown() override { remove(testdata_file_.c_str()); remove(unique_file0_.c_str()); remove(unique_file1_.c_str()); diff --git a/googletest/test/googletest-filter-unittest.py b/googletest/test/googletest-filter-unittest.py index dc0b5bd9a5cf..6b32f2d21997 100755 --- a/googletest/test/googletest-filter-unittest.py +++ b/googletest/test/googletest-filter-unittest.py @@ -42,7 +42,10 @@ we test that here also. import os import re -import sets +try: + from sets import Set as set # For Python 2.3 compatibility +except ImportError: + pass import sys import gtest_test_utils @@ -57,7 +60,7 @@ CAN_PASS_EMPTY_ENV = False if sys.executable: os.environ['EMPTY_VAR'] = '' child = gtest_test_utils.Subprocess( - [sys.executable, '-c', 'import os; print \'EMPTY_VAR\' in os.environ']) + [sys.executable, '-c', 'import os; print(\'EMPTY_VAR\' in os.environ)']) CAN_PASS_EMPTY_ENV = eval(child.output) @@ -72,7 +75,7 @@ if sys.executable: os.environ['UNSET_VAR'] = 'X' del os.environ['UNSET_VAR'] child = gtest_test_utils.Subprocess( - [sys.executable, '-c', 'import os; print \'UNSET_VAR\' not in os.environ' + [sys.executable, '-c', 'import os; print(\'UNSET_VAR\' not in os.environ)' ]) CAN_UNSET_ENV = eval(child.output) @@ -245,14 +248,14 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): for slice_var in list_of_sets: full_partition.extend(slice_var) self.assertEqual(len(set_var), len(full_partition)) - self.assertEqual(sets.Set(set_var), sets.Set(full_partition)) + self.assertEqual(set(set_var), set(full_partition)) def AdjustForParameterizedTests(self, tests_to_run): """Adjust tests_to_run in case value parameterized tests are disabled.""" global param_tests_present if not param_tests_present: - return list(sets.Set(tests_to_run) - sets.Set(PARAM_TESTS)) + return list(set(tests_to_run) - set(PARAM_TESTS)) else: return tests_to_run diff --git a/googletest/test/googletest-filter-unittest_.cc b/googletest/test/googletest-filter-unittest_.cc index d335b60391d1..d30ec9c78b56 100644 --- a/googletest/test/googletest-filter-unittest_.cc +++ b/googletest/test/googletest-filter-unittest_.cc @@ -125,8 +125,8 @@ TEST_P(ParamTest, TestX) { TEST_P(ParamTest, TestY) { } -INSTANTIATE_TEST_CASE_P(SeqP, ParamTest, testing::Values(1, 2)); -INSTANTIATE_TEST_CASE_P(SeqQ, ParamTest, testing::Values(5, 6)); +INSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2)); +INSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6)); } // namespace diff --git a/googletest/test/googletest-json-outfiles-test.py b/googletest/test/googletest-json-outfiles-test.py index c99be48e8ac3..8ef47b8f9746 100644 --- a/googletest/test/googletest-json-outfiles-test.py +++ b/googletest/test/googletest-json-outfiles-test.py @@ -40,24 +40,41 @@ GTEST_OUTPUT_1_TEST = 'gtest_xml_outfile1_test_' GTEST_OUTPUT_2_TEST = 'gtest_xml_outfile2_test_' EXPECTED_1 = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'name': + u'AllTests', u'testsuites': [{ - u'name': u'PropertyOne', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', + u'name': + u'PropertyOne', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', u'testsuite': [{ u'name': u'TestSomeProperties', u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', + u'timestamp': u'*', u'classname': u'PropertyOne', u'SetUpProp': u'1', u'TestSomeProperty': u'1', @@ -67,23 +84,40 @@ EXPECTED_1 = { } EXPECTED_2 = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'name': + u'AllTests', u'testsuites': [{ - u'name': u'PropertyTwo', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', + u'name': + u'PropertyTwo', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', u'testsuite': [{ u'name': u'TestSomeProperties', u'status': u'RUN', + u'result': u'COMPLETED', + u'timestamp': u'*', u'time': u'*', u'classname': u'PropertyTwo', u'SetUpProp': u'2', @@ -136,11 +170,6 @@ class GTestJsonOutFilesTest(gtest_test_utils.TestCase): self.assert_(p.exited) self.assertEquals(0, p.exit_code) - # FIXME: libtool causes the built test binary to be - # named lt-gtest_xml_outfiles_test_ instead of - # gtest_xml_outfiles_test_. To account for this possibility, we - # allow both names in the following code. We should remove this - # when libtool replacement tool is ready. output_file_name1 = test_name + '.json' output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py index 57dcd5fa1c46..15861f75cbe8 100644 --- a/googletest/test/googletest-json-output-unittest.py +++ b/googletest/test/googletest-json-output-unittest.py @@ -57,370 +57,530 @@ else: STACK_TRACE_TEMPLATE = '' EXPECTED_NON_EMPTY = { - u'tests': 23, - u'failures': 4, - u'disabled': 2, - u'errors': 0, - u'timestamp': u'*', - u'time': u'*', - u'ad_hoc_property': u'42', - u'name': u'AllTests', - u'testsuites': [ - { - u'name': u'SuccessfulTest', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'tests': + 24, + u'failures': + 4, + u'disabled': + 2, + u'errors': + 0, + u'timestamp': + u'*', + u'time': + u'*', + u'ad_hoc_property': + u'42', + u'name': + u'AllTests', + u'testsuites': [{ + u'name': + u'SuccessfulTest', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'Succeeds', + u'status': u'RUN', + u'result': u'COMPLETED', + u'time': u'*', + u'timestamp': u'*', + u'classname': u'SuccessfulTest' + }] + }, { + u'name': + u'FailedTest', + u'tests': + 1, + u'failures': + 1, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': + u'Fails', + u'status': + u'RUN', + u'result': + u'COMPLETED', + u'time': + u'*', + u'timestamp': + u'*', + u'classname': + u'FailedTest', + u'failures': [{ + u'failure': u'gtest_xml_output_unittest_.cc:*\n' + u'Expected equality of these values:\n' + u' 1\n 2' + STACK_TRACE_TEMPLATE, + u'type': u'' + }] + }] + }, { + u'name': + u'DisabledTest', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 1, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'DISABLED_test_not_run', + u'status': u'NOTRUN', + u'result': u'SUPPRESSED', + u'time': u'*', + u'timestamp': u'*', + u'classname': u'DisabledTest' + }] + }, { + u'name': + u'SkippedTest', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'Skipped', + u'status': u'RUN', + u'result': u'SKIPPED', + u'time': u'*', + u'timestamp': u'*', + u'classname': u'SkippedTest' + }] + }, { + u'name': + u'MixedResultTest', + u'tests': + 3, + u'failures': + 1, + u'disabled': + 1, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'Succeeds', + u'status': u'RUN', + u'result': u'COMPLETED', + u'time': u'*', + u'timestamp': u'*', + u'classname': u'MixedResultTest' + }, { + u'name': + u'Fails', + u'status': + u'RUN', + u'result': + u'COMPLETED', + u'time': + u'*', + u'timestamp': + u'*', + u'classname': + u'MixedResultTest', + u'failures': [{ + u'failure': u'gtest_xml_output_unittest_.cc:*\n' + u'Expected equality of these values:\n' + u' 1\n 2' + STACK_TRACE_TEMPLATE, + u'type': u'' + }, { + u'failure': u'gtest_xml_output_unittest_.cc:*\n' + u'Expected equality of these values:\n' + u' 2\n 3' + STACK_TRACE_TEMPLATE, + u'type': u'' + }] + }, { + u'name': u'DISABLED_test', + u'status': u'NOTRUN', + u'result': u'SUPPRESSED', + u'time': u'*', + u'timestamp': u'*', + u'classname': u'MixedResultTest' + }] + }, { + u'name': + u'XmlQuotingTest', + u'tests': + 1, + u'failures': + 1, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': + u'OutputsCData', + u'status': + u'RUN', + u'result': + u'COMPLETED', + u'time': + u'*', + u'timestamp': + u'*', + u'classname': + u'XmlQuotingTest', + u'failures': [{ + u'failure': u'gtest_xml_output_unittest_.cc:*\n' + u'Failed\nXML output: <?xml encoding="utf-8">' + u'<top><![CDATA[cdata text]]></top>' + + STACK_TRACE_TEMPLATE, + u'type': u'' + }] + }] + }, { + u'name': + u'InvalidCharactersTest', + u'tests': + 1, + u'failures': + 1, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': + u'InvalidCharactersInMessage', + u'status': + u'RUN', + u'result': + u'COMPLETED', + u'time': + u'*', + u'timestamp': + u'*', + u'classname': + u'InvalidCharactersTest', + u'failures': [{ + u'failure': u'gtest_xml_output_unittest_.cc:*\n' + u'Failed\nInvalid characters in brackets' + u' [\x01\x02]' + STACK_TRACE_TEMPLATE, + u'type': u'' + }] + }] + }, { + u'name': + u'PropertyRecordingTest', + u'tests': + 4, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'SetUpTestSuite': + u'yes', + u'TearDownTestSuite': + u'aye', + u'testsuite': [{ + u'name': u'OneProperty', + u'status': u'RUN', + u'result': u'COMPLETED', + u'time': u'*', + u'timestamp': u'*', + u'classname': u'PropertyRecordingTest', + u'key_1': u'1' + }, { + u'name': u'IntValuedProperty', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'SuccessfulTest' - } - ] - }, - { - u'name': u'FailedTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'PropertyRecordingTest', + u'key_int': u'1' + }, { + u'name': u'ThreeProperties', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'Fails', - u'status': u'RUN', - u'time': u'*', - u'classname': u'FailedTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'DisabledTest', - u'tests': 1, - u'failures': 0, - u'disabled': 1, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'PropertyRecordingTest', + u'key_1': u'1', + u'key_2': u'2', + u'key_3': u'3' + }, { + u'name': u'TwoValuesForOneKeyUsesLastValue', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'DISABLED_test_not_run', - u'status': u'NOTRUN', - u'time': u'*', - u'classname': u'DisabledTest' - } - ] - }, - { - u'name': u'MixedResultTest', - u'tests': 3, - u'failures': 1, - u'disabled': 1, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'PropertyRecordingTest', + u'key_1': u'2' + }] + }, { + u'name': + u'NoFixtureTest', + u'tests': + 3, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'RecordProperty', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'Succeeds', - u'status': u'RUN', - u'time': u'*', - u'classname': u'MixedResultTest' - }, - { - u'name': u'Fails', - u'status': u'RUN', - u'time': u'*', - u'classname': u'MixedResultTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - }, - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 2\n 3' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - }, - { - u'name': u'DISABLED_test', - u'status': u'NOTRUN', - u'time': u'*', - u'classname': u'MixedResultTest' - } - ] - }, - { - u'name': u'XmlQuotingTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'NoFixtureTest', + u'key': u'1' + }, { + u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'OutputsCData', - u'status': u'RUN', - u'time': u'*', - u'classname': u'XmlQuotingTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nXML output: <?xml encoding="utf-8">' - u'<top><![CDATA[cdata text]]></top>' + - STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'InvalidCharactersTest', - u'tests': 1, - u'failures': 1, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'NoFixtureTest', + u'key_for_utility_int': u'1' + }, { + u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'InvalidCharactersInMessage', - u'status': u'RUN', - u'time': u'*', - u'classname': u'InvalidCharactersTest', - u'failures': [ - { - u'failure': - u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nInvalid characters in brackets' - u' [\x01\x02]' + STACK_TRACE_TEMPLATE, - u'type': u'' - } - ] - } - ] - }, - { - u'name': u'PropertyRecordingTest', - u'tests': 4, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'NoFixtureTest', + u'key_for_utility_string': u'1' + }] + }, { + u'name': + u'TypedTest/0', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'HasTypeParamAttribute', + u'type_param': u'int', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'SetUpTestCase': u'yes', - u'TearDownTestCase': u'aye', - u'testsuite': [ - { - u'name': u'OneProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1' - }, - { - u'name': u'IntValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_int': u'1' - }, - { - u'name': u'ThreeProperties', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1', - u'key_2': u'2', - u'key_3': u'3' - }, - { - u'name': u'TwoValuesForOneKeyUsesLastValue', - u'status': u'RUN', - u'time': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'2' - } - ] - }, - { - u'name': u'NoFixtureTest', - u'tests': 3, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'TypedTest/0' + }] + }, { + u'name': + u'TypedTest/1', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'HasTypeParamAttribute', + u'type_param': u'long', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'RecordProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key': u'1' - }, - { - u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_int': u'1' - }, - { - u'name': - u'ExternalUtilityThatCallsRecordStringValuedProperty', - u'status': u'RUN', - u'time': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_string': u'1' - } - ] - }, - { - u'name': u'TypedTest/0', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'TypedTest/1' + }] + }, { + u'name': + u'Single/TypeParameterizedTestSuite/0', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'HasTypeParamAttribute', + u'type_param': u'int', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'time': u'*', - u'classname': u'TypedTest/0' - } - ] - }, - { - u'name': u'TypedTest/1', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'Single/TypeParameterizedTestSuite/0' + }] + }, { + u'name': + u'Single/TypeParameterizedTestSuite/1', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'HasTypeParamAttribute', + u'type_param': u'long', + u'status': u'RUN', + u'result': u'COMPLETED', + u'time': u'*', + u'timestamp': u'*', + u'classname': u'Single/TypeParameterizedTestSuite/1' + }] + }, { + u'name': + u'Single/ValueParamTest', + u'tests': + 4, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'testsuite': [{ + u'name': u'HasValueParamAttribute/0', + u'value_param': u'33', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'time': u'*', - u'classname': u'TypedTest/1' - } - ] - }, - { - u'name': u'Single/TypeParameterizedTestCase/0', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'Single/ValueParamTest' + }, { + u'name': u'HasValueParamAttribute/1', + u'value_param': u'42', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/TypeParameterizedTestCase/0' - } - ] - }, - { - u'name': u'Single/TypeParameterizedTestCase/1', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'Single/ValueParamTest' + }, { + u'name': u'AnotherTestThatHasValueParamAttribute/0', + u'value_param': u'33', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/TypeParameterizedTestCase/1' - } - ] - }, - { - u'name': u'Single/ValueParamTest', - u'tests': 4, - u'failures': 0, - u'disabled': 0, - u'errors': 0, + u'timestamp': u'*', + u'classname': u'Single/ValueParamTest' + }, { + u'name': u'AnotherTestThatHasValueParamAttribute/1', + u'value_param': u'42', + u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', - u'testsuite': [ - { - u'name': u'HasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'HasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'AnotherTestThatHasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - }, - { - u'name': u'AnotherTestThatHasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'time': u'*', - u'classname': u'Single/ValueParamTest' - } - ] - } - ] + u'timestamp': u'*', + u'classname': u'Single/ValueParamTest' + }] + }] } EXPECTED_FILTERED = { - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'ad_hoc_property': u'42', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', + u'name': + u'AllTests', + u'ad_hoc_property': + u'42', u'testsuites': [{ - u'name': u'SuccessfulTest', - u'tests': 1, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', + u'name': + u'SuccessfulTest', + u'tests': + 1, + u'failures': + 0, + u'disabled': + 0, + u'errors': + 0, + u'time': + u'*', + u'timestamp': + u'*', u'testsuite': [{ u'name': u'Succeeds', u'status': u'RUN', + u'result': u'COMPLETED', u'time': u'*', + u'timestamp': u'*', u'classname': u'SuccessfulTest', }] }], diff --git a/googletest/test/googletest-linked-ptr-test.cc b/googletest/test/googletest-linked-ptr-test.cc deleted file mode 100644 index fa00f34296bd..000000000000 --- a/googletest/test/googletest-linked-ptr-test.cc +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2003, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include <stdlib.h> - -#include "gtest/internal/gtest-linked_ptr.h" -#include "gtest/gtest.h" - -namespace { - -using testing::Message; -using testing::internal::linked_ptr; - -int num; -Message* history = NULL; - -// Class which tracks allocation/deallocation -class A { - public: - A(): mynum(num++) { *history << "A" << mynum << " ctor\n"; } - virtual ~A() { *history << "A" << mynum << " dtor\n"; } - virtual void Use() { *history << "A" << mynum << " use\n"; } - protected: - int mynum; -}; - -// Subclass -class B : public A { - public: - B() { *history << "B" << mynum << " ctor\n"; } - ~B() { *history << "B" << mynum << " dtor\n"; } - virtual void Use() { *history << "B" << mynum << " use\n"; } -}; - -class LinkedPtrTest : public testing::Test { - public: - LinkedPtrTest() { - num = 0; - history = new Message; - } - - virtual ~LinkedPtrTest() { - delete history; - history = NULL; - } -}; - -TEST_F(LinkedPtrTest, GeneralTest) { - { - linked_ptr<A> a0, a1, a2; - // Use explicit function call notation here to suppress self-assign warning. - a0.operator=(a0); - a1 = a2; - ASSERT_EQ(a0.get(), static_cast<A*>(NULL)); - ASSERT_EQ(a1.get(), static_cast<A*>(NULL)); - ASSERT_EQ(a2.get(), static_cast<A*>(NULL)); - ASSERT_TRUE(a0 == NULL); - ASSERT_TRUE(a1 == NULL); - ASSERT_TRUE(a2 == NULL); - - { - linked_ptr<A> a3(new A); - a0 = a3; - ASSERT_TRUE(a0 == a3); - ASSERT_TRUE(a0 != NULL); - ASSERT_TRUE(a0.get() == a3); - ASSERT_TRUE(a0 == a3.get()); - linked_ptr<A> a4(a0); - a1 = a4; - linked_ptr<A> a5(new A); - ASSERT_TRUE(a5.get() != a3); - ASSERT_TRUE(a5 != a3.get()); - a2 = a5; - linked_ptr<B> b0(new B); - linked_ptr<A> a6(b0); - ASSERT_TRUE(b0 == a6); - ASSERT_TRUE(a6 == b0); - ASSERT_TRUE(b0 != NULL); - a5 = b0; - a5 = b0; - a3->Use(); - a4->Use(); - a5->Use(); - a6->Use(); - b0->Use(); - (*b0).Use(); - b0.get()->Use(); - } - - a0->Use(); - a1->Use(); - a2->Use(); - - a1 = a2; - a2.reset(new A); - a0.reset(); - - linked_ptr<A> a7; - } - - ASSERT_STREQ( - "A0 ctor\n" - "A1 ctor\n" - "A2 ctor\n" - "B2 ctor\n" - "A0 use\n" - "A0 use\n" - "B2 use\n" - "B2 use\n" - "B2 use\n" - "B2 use\n" - "B2 use\n" - "B2 dtor\n" - "A2 dtor\n" - "A0 use\n" - "A0 use\n" - "A1 use\n" - "A3 ctor\n" - "A0 dtor\n" - "A3 dtor\n" - "A1 dtor\n", - history->GetString().c_str()); -} - -} // Unnamed namespace diff --git a/googletest/test/googletest-list-tests-unittest_.cc b/googletest/test/googletest-list-tests-unittest_.cc index f473c7d1a45f..493c6f00464a 100644 --- a/googletest/test/googletest-list-tests-unittest_.cc +++ b/googletest/test/googletest-list-tests-unittest_.cc @@ -99,7 +99,7 @@ TEST_P(ValueParamTest, TestA) { TEST_P(ValueParamTest, TestB) { } -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( MyInstantiation, ValueParamTest, testing::Values(MyType("one line"), MyType("two\nlines"), @@ -123,7 +123,7 @@ class MyArray { typedef testing::Types<VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName, // NOLINT int*, MyArray<bool, 42> > MyTypes; -TYPED_TEST_CASE(TypedTest, MyTypes); +TYPED_TEST_SUITE(TypedTest, MyTypes); TYPED_TEST(TypedTest, TestA) { } @@ -137,7 +137,7 @@ template <typename T> class TypeParamTest : public testing::Test { }; -TYPED_TEST_CASE_P(TypeParamTest); +TYPED_TEST_SUITE_P(TypeParamTest); TYPED_TEST_P(TypeParamTest, TestA) { } @@ -145,9 +145,9 @@ TYPED_TEST_P(TypeParamTest, TestA) { TYPED_TEST_P(TypeParamTest, TestB) { } -REGISTER_TYPED_TEST_CASE_P(TypeParamTest, TestA, TestB); +REGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB); -INSTANTIATE_TYPED_TEST_CASE_P(My, TypeParamTest, MyTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes); int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); diff --git a/googletest/test/googletest-listener-test.cc b/googletest/test/googletest-listener-test.cc index 8355597151d0..10457afe39a7 100644 --- a/googletest/test/googletest-listener-test.cc +++ b/googletest/test/googletest-listener-test.cc @@ -35,19 +35,20 @@ #include <vector> #include "gtest/gtest.h" +#include "gtest/internal/custom/gtest.h" using ::testing::AddGlobalTestEnvironment; using ::testing::Environment; using ::testing::InitGoogleTest; using ::testing::Test; -using ::testing::TestCase; +using ::testing::TestSuite; using ::testing::TestEventListener; using ::testing::TestInfo; using ::testing::TestPartResult; using ::testing::UnitTest; // Used by tests to register their events. -std::vector<std::string>* g_events = NULL; +std::vector<std::string>* g_events = nullptr; namespace testing { namespace internal { @@ -57,63 +58,66 @@ class EventRecordingListener : public TestEventListener { explicit EventRecordingListener(const char* name) : name_(name) {} protected: - virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { + void OnTestProgramStart(const UnitTest& /*unit_test*/) override { g_events->push_back(GetFullMethodName("OnTestProgramStart")); } - virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, - int iteration) { + void OnTestIterationStart(const UnitTest& /*unit_test*/, + int iteration) override { Message message; message << GetFullMethodName("OnTestIterationStart") << "(" << iteration << ")"; g_events->push_back(message.GetString()); } - virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) { + void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override { g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart")); } - virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) { + void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override { g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd")); } - - virtual void OnTestCaseStart(const TestCase& /*test_case*/) { +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + void OnTestCaseStart(const TestCase& /*test_case*/) override { g_events->push_back(GetFullMethodName("OnTestCaseStart")); } +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - virtual void OnTestStart(const TestInfo& /*test_info*/) { + void OnTestStart(const TestInfo& /*test_info*/) override { g_events->push_back(GetFullMethodName("OnTestStart")); } - virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) { + void OnTestPartResult(const TestPartResult& /*test_part_result*/) override { g_events->push_back(GetFullMethodName("OnTestPartResult")); } - virtual void OnTestEnd(const TestInfo& /*test_info*/) { + void OnTestEnd(const TestInfo& /*test_info*/) override { g_events->push_back(GetFullMethodName("OnTestEnd")); } - virtual void OnTestCaseEnd(const TestCase& /*test_case*/) { +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + void OnTestCaseEnd(const TestCase& /*test_case*/) override { g_events->push_back(GetFullMethodName("OnTestCaseEnd")); } +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) { + void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override { g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart")); } - virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) { + void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override { g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd")); } - virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, - int iteration) { + void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int iteration) override { Message message; message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration << ")"; g_events->push_back(message.GetString()); } - virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { + void OnTestProgramEnd(const UnitTest& /*unit_test*/) override { g_events->push_back(GetFullMethodName("OnTestProgramEnd")); } @@ -125,34 +129,98 @@ class EventRecordingListener : public TestEventListener { std::string name_; }; -class EnvironmentInvocationCatcher : public Environment { +// This listener is using OnTestSuiteStart, OnTestSuiteEnd API +class EventRecordingListener2 : public TestEventListener { + public: + explicit EventRecordingListener2(const char* name) : name_(name) {} + protected: - virtual void SetUp() { - g_events->push_back("Environment::SetUp"); + void OnTestProgramStart(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnTestProgramStart")); + } + + void OnTestIterationStart(const UnitTest& /*unit_test*/, + int iteration) override { + Message message; + message << GetFullMethodName("OnTestIterationStart") << "(" << iteration + << ")"; + g_events->push_back(message.GetString()); + } + + void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart")); + } + + void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd")); + } + + void OnTestSuiteStart(const TestSuite& /*test_suite*/) override { + g_events->push_back(GetFullMethodName("OnTestSuiteStart")); + } + + void OnTestStart(const TestInfo& /*test_info*/) override { + g_events->push_back(GetFullMethodName("OnTestStart")); + } + + void OnTestPartResult(const TestPartResult& /*test_part_result*/) override { + g_events->push_back(GetFullMethodName("OnTestPartResult")); + } + + void OnTestEnd(const TestInfo& /*test_info*/) override { + g_events->push_back(GetFullMethodName("OnTestEnd")); } - virtual void TearDown() { - g_events->push_back("Environment::TearDown"); + void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override { + g_events->push_back(GetFullMethodName("OnTestSuiteEnd")); } + + void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart")); + } + + void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd")); + } + + void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int iteration) override { + Message message; + message << GetFullMethodName("OnTestIterationEnd") << "(" << iteration + << ")"; + g_events->push_back(message.GetString()); + } + + void OnTestProgramEnd(const UnitTest& /*unit_test*/) override { + g_events->push_back(GetFullMethodName("OnTestProgramEnd")); + } + + private: + std::string GetFullMethodName(const char* name) { return name_ + "." + name; } + + std::string name_; +}; + +class EnvironmentInvocationCatcher : public Environment { + protected: + void SetUp() override { g_events->push_back("Environment::SetUp"); } + + void TearDown() override { g_events->push_back("Environment::TearDown"); } }; class ListenerTest : public Test { protected: - static void SetUpTestCase() { - g_events->push_back("ListenerTest::SetUpTestCase"); + static void SetUpTestSuite() { + g_events->push_back("ListenerTest::SetUpTestSuite"); } - static void TearDownTestCase() { - g_events->push_back("ListenerTest::TearDownTestCase"); + static void TearDownTestSuite() { + g_events->push_back("ListenerTest::TearDownTestSuite"); } - virtual void SetUp() { - g_events->push_back("ListenerTest::SetUp"); - } + void SetUp() override { g_events->push_back("ListenerTest::SetUp"); } - virtual void TearDown() { - g_events->push_back("ListenerTest::TearDown"); - } + void TearDown() override { g_events->push_back("ListenerTest::TearDown"); } }; TEST_F(ListenerTest, DoesFoo) { @@ -173,6 +241,7 @@ TEST_F(ListenerTest, DoesBar) { using ::testing::internal::EnvironmentInvocationCatcher; using ::testing::internal::EventRecordingListener; +using ::testing::internal::EventRecordingListener2; void VerifyResults(const std::vector<std::string>& data, const char* const* expected_data, @@ -207,6 +276,8 @@ int main(int argc, char **argv) { new EventRecordingListener("1st")); UnitTest::GetInstance()->listeners().Append( new EventRecordingListener("2nd")); + UnitTest::GetInstance()->listeners().Append( + new EventRecordingListener2("3rd")); AddGlobalTestEnvironment(new EnvironmentInvocationCatcher); @@ -216,88 +287,224 @@ int main(int argc, char **argv) { ::testing::GTEST_FLAG(repeat) = 2; int ret_val = RUN_ALL_TESTS(); - const char* const expected_events[] = { - "1st.OnTestProgramStart", - "2nd.OnTestProgramStart", - "1st.OnTestIterationStart(0)", - "2nd.OnTestIterationStart(0)", - "1st.OnEnvironmentsSetUpStart", - "2nd.OnEnvironmentsSetUpStart", - "Environment::SetUp", - "2nd.OnEnvironmentsSetUpEnd", - "1st.OnEnvironmentsSetUpEnd", - "1st.OnTestCaseStart", - "2nd.OnTestCaseStart", - "ListenerTest::SetUpTestCase", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "ListenerTest::TearDownTestCase", - "2nd.OnTestCaseEnd", - "1st.OnTestCaseEnd", - "1st.OnEnvironmentsTearDownStart", - "2nd.OnEnvironmentsTearDownStart", - "Environment::TearDown", - "2nd.OnEnvironmentsTearDownEnd", - "1st.OnEnvironmentsTearDownEnd", - "2nd.OnTestIterationEnd(0)", - "1st.OnTestIterationEnd(0)", - "1st.OnTestIterationStart(1)", - "2nd.OnTestIterationStart(1)", - "1st.OnEnvironmentsSetUpStart", - "2nd.OnEnvironmentsSetUpStart", - "Environment::SetUp", - "2nd.OnEnvironmentsSetUpEnd", - "1st.OnEnvironmentsSetUpEnd", - "1st.OnTestCaseStart", - "2nd.OnTestCaseStart", - "ListenerTest::SetUpTestCase", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "1st.OnTestStart", - "2nd.OnTestStart", - "ListenerTest::SetUp", - "ListenerTest::* Test Body", - "1st.OnTestPartResult", - "2nd.OnTestPartResult", - "ListenerTest::TearDown", - "2nd.OnTestEnd", - "1st.OnTestEnd", - "ListenerTest::TearDownTestCase", - "2nd.OnTestCaseEnd", - "1st.OnTestCaseEnd", - "1st.OnEnvironmentsTearDownStart", - "2nd.OnEnvironmentsTearDownStart", - "Environment::TearDown", - "2nd.OnEnvironmentsTearDownEnd", - "1st.OnEnvironmentsTearDownEnd", - "2nd.OnTestIterationEnd(1)", - "1st.OnTestIterationEnd(1)", - "2nd.OnTestProgramEnd", - "1st.OnTestProgramEnd" - }; +#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + + // The deprecated OnTestSuiteStart/OnTestCaseStart events are included + const char* const expected_events[] = {"1st.OnTestProgramStart", + "2nd.OnTestProgramStart", + "3rd.OnTestProgramStart", + "1st.OnTestIterationStart(0)", + "2nd.OnTestIterationStart(0)", + "3rd.OnTestIterationStart(0)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "3rd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "3rd.OnEnvironmentsSetUpEnd", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "3rd.OnTestSuiteStart", + "1st.OnTestCaseStart", + "2nd.OnTestCaseStart", + "ListenerTest::SetUpTestSuite", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestSuite", + "3rd.OnTestSuiteEnd", + "2nd.OnTestCaseEnd", + "1st.OnTestCaseEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "3rd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "3rd.OnEnvironmentsTearDownEnd", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "3rd.OnTestIterationEnd(0)", + "2nd.OnTestIterationEnd(0)", + "1st.OnTestIterationEnd(0)", + "1st.OnTestIterationStart(1)", + "2nd.OnTestIterationStart(1)", + "3rd.OnTestIterationStart(1)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "3rd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "3rd.OnEnvironmentsSetUpEnd", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "3rd.OnTestSuiteStart", + "1st.OnTestCaseStart", + "2nd.OnTestCaseStart", + "ListenerTest::SetUpTestSuite", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestSuite", + "3rd.OnTestSuiteEnd", + "2nd.OnTestCaseEnd", + "1st.OnTestCaseEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "3rd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "3rd.OnEnvironmentsTearDownEnd", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "3rd.OnTestIterationEnd(1)", + "2nd.OnTestIterationEnd(1)", + "1st.OnTestIterationEnd(1)", + "3rd.OnTestProgramEnd", + "2nd.OnTestProgramEnd", + "1st.OnTestProgramEnd"}; +#else + const char* const expected_events[] = {"1st.OnTestProgramStart", + "2nd.OnTestProgramStart", + "3rd.OnTestProgramStart", + "1st.OnTestIterationStart(0)", + "2nd.OnTestIterationStart(0)", + "3rd.OnTestIterationStart(0)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "3rd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "3rd.OnEnvironmentsSetUpEnd", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "3rd.OnTestSuiteStart", + "ListenerTest::SetUpTestSuite", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestSuite", + "3rd.OnTestSuiteEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "3rd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "3rd.OnEnvironmentsTearDownEnd", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "3rd.OnTestIterationEnd(0)", + "2nd.OnTestIterationEnd(0)", + "1st.OnTestIterationEnd(0)", + "1st.OnTestIterationStart(1)", + "2nd.OnTestIterationStart(1)", + "3rd.OnTestIterationStart(1)", + "1st.OnEnvironmentsSetUpStart", + "2nd.OnEnvironmentsSetUpStart", + "3rd.OnEnvironmentsSetUpStart", + "Environment::SetUp", + "3rd.OnEnvironmentsSetUpEnd", + "2nd.OnEnvironmentsSetUpEnd", + "1st.OnEnvironmentsSetUpEnd", + "3rd.OnTestSuiteStart", + "ListenerTest::SetUpTestSuite", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "1st.OnTestStart", + "2nd.OnTestStart", + "3rd.OnTestStart", + "ListenerTest::SetUp", + "ListenerTest::* Test Body", + "1st.OnTestPartResult", + "2nd.OnTestPartResult", + "3rd.OnTestPartResult", + "ListenerTest::TearDown", + "3rd.OnTestEnd", + "2nd.OnTestEnd", + "1st.OnTestEnd", + "ListenerTest::TearDownTestSuite", + "3rd.OnTestSuiteEnd", + "1st.OnEnvironmentsTearDownStart", + "2nd.OnEnvironmentsTearDownStart", + "3rd.OnEnvironmentsTearDownStart", + "Environment::TearDown", + "3rd.OnEnvironmentsTearDownEnd", + "2nd.OnEnvironmentsTearDownEnd", + "1st.OnEnvironmentsTearDownEnd", + "3rd.OnTestIterationEnd(1)", + "2nd.OnTestIterationEnd(1)", + "1st.OnTestIterationEnd(1)", + "3rd.OnTestProgramEnd", + "2nd.OnTestProgramEnd", + "1st.OnTestProgramEnd"}; +#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ + VerifyResults(events, expected_events, sizeof(expected_events)/sizeof(expected_events[0])); diff --git a/googletest/test/googletest-message-test.cc b/googletest/test/googletest-message-test.cc index c6445853e433..962d519114e6 100644 --- a/googletest/test/googletest-message-test.cc +++ b/googletest/test/googletest-message-test.cc @@ -85,7 +85,7 @@ TEST(MessageTest, StreamsPointer) { // Tests streaming a NULL non-char pointer. TEST(MessageTest, StreamsNullPointer) { - int* p = NULL; + int* p = nullptr; EXPECT_EQ("(null)", (Message() << p).GetString()); } @@ -96,7 +96,7 @@ TEST(MessageTest, StreamsCString) { // Tests streaming a NULL C string. TEST(MessageTest, StreamsNullCString) { - char* p = NULL; + char* p = nullptr; EXPECT_EQ("(null)", (Message() << p).GetString()); } diff --git a/googletest/test/googletest-options-test.cc b/googletest/test/googletest-options-test.cc index edd4eba3bd31..f07b316db3b9 100644 --- a/googletest/test/googletest-options-test.cc +++ b/googletest/test/googletest-options-test.cc @@ -102,10 +102,15 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { _strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 || _strcmpi("gtest_all_test", exe_str.c_str()) == 0 || _strcmpi("gtest_dll_test", exe_str.c_str()) == 0; +#elif GTEST_OS_OS2 + const bool success = + strcasecmp("googletest-options-test", exe_str.c_str()) == 0 || + strcasecmp("gtest-options-ex_test", exe_str.c_str()) == 0 || + strcasecmp("gtest_all_test", exe_str.c_str()) == 0 || + strcasecmp("gtest_dll_test", exe_str.c_str()) == 0; #elif GTEST_OS_FUCHSIA const bool success = exe_str == "app"; #else - // FIXME: remove the hard-coded "lt-" prefix when libtool replacement is ready const bool success = exe_str == "googletest-options-test" || exe_str == "gtest_all_test" || @@ -120,7 +125,7 @@ TEST(OutputFileHelpersTest, GetCurrentExecutableName) { class XmlOutputChangeDirTest : public Test { protected: - virtual void SetUp() { + void SetUp() override { original_working_dir_ = FilePath::GetCurrentDir(); posix::ChDir(".."); // This will make the test fail if run from the root directory. @@ -128,7 +133,7 @@ class XmlOutputChangeDirTest : public Test { FilePath::GetCurrentDir().string()); } - virtual void TearDown() { + void TearDown() override { posix::ChDir(original_working_dir_.string().c_str()); } diff --git a/googletest/test/googletest-output-test-golden-lin.txt b/googletest/test/googletest-output-test-golden-lin.txt index 86da845b7d04..038de921baba 100644 --- a/googletest/test/googletest-output-test-golden-lin.txt +++ b/googletest/test/googletest-output-test-golden-lin.txt @@ -12,7 +12,7 @@ Expected equality of these values: 3 Stack trace: (omitted) -[0;32m[==========] [mRunning 76 tests from 34 test cases. +[0;32m[==========] [mRunning 85 tests from 40 test suites. [0;32m[----------] [mGlobal test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -380,66 +380,74 @@ Stack trace: (omitted) [0;32m[ RUN ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber foo.cc:42: Failure Failed -Expected failure in foo.cc +Expected nonfatal failure in foo.cc Stack trace: (omitted) [0;31m[ FAILED ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber -[0;32m[----------] [m4 tests from MixedUpTestCaseTest -[0;32m[ RUN ] [mMixedUpTestCaseTest.FirstTestFromNamespaceFoo -[0;32m[ OK ] [mMixedUpTestCaseTest.FirstTestFromNamespaceFoo -[0;32m[ RUN ] [mMixedUpTestCaseTest.SecondTestFromNamespaceFoo -[0;32m[ OK ] [mMixedUpTestCaseTest.SecondTestFromNamespaceFoo -[0;32m[ RUN ] [mMixedUpTestCaseTest.ThisShouldFail +[0;32m[----------] [m1 test from GtestFailAtTest +[0;32m[ RUN ] [mGtestFailAtTest.MessageContainsSpecifiedFileAndLineNumber +foo.cc:42: Failure +Failed +Expected fatal failure in foo.cc +Stack trace: (omitted) + +[0;31m[ FAILED ] [mGtestFailAtTest.MessageContainsSpecifiedFileAndLineNumber +[0;32m[----------] [m4 tests from MixedUpTestSuiteTest +[0;32m[ RUN ] [mMixedUpTestSuiteTest.FirstTestFromNamespaceFoo +[0;32m[ OK ] [mMixedUpTestSuiteTest.FirstTestFromNamespaceFoo +[0;32m[ RUN ] [mMixedUpTestSuiteTest.SecondTestFromNamespaceFoo +[0;32m[ OK ] [mMixedUpTestSuiteTest.SecondTestFromNamespaceFoo +[0;32m[ RUN ] [mMixedUpTestSuiteTest.ThisShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseTest, +All tests in the same test suite must use the same test fixture +class. However, in test suite MixedUpTestSuiteTest, you defined test FirstTestFromNamespaceFoo and test ThisShouldFail using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. +of the classes to put the tests into different test suites. Stack trace: (omitted) -[0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFail -[0;32m[ RUN ] [mMixedUpTestCaseTest.ThisShouldFailToo +[0;31m[ FAILED ] [mMixedUpTestSuiteTest.ThisShouldFail +[0;32m[ RUN ] [mMixedUpTestSuiteTest.ThisShouldFailToo gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseTest, +All tests in the same test suite must use the same test fixture +class. However, in test suite MixedUpTestSuiteTest, you defined test FirstTestFromNamespaceFoo and test ThisShouldFailToo using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. +of the classes to put the tests into different test suites. Stack trace: (omitted) -[0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFailToo -[0;32m[----------] [m2 tests from MixedUpTestCaseWithSameTestNameTest -[0;32m[ RUN ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[0;32m[ OK ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail -[0;32m[ RUN ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +[0;31m[ FAILED ] [mMixedUpTestSuiteTest.ThisShouldFailToo +[0;32m[----------] [m2 tests from MixedUpTestSuiteWithSameTestNameTest +[0;32m[ RUN ] [mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +[0;32m[ OK ] [mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +[0;32m[ RUN ] [mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class. However, in test case MixedUpTestCaseWithSameTestNameTest, +All tests in the same test suite must use the same test fixture +class. However, in test suite MixedUpTestSuiteWithSameTestNameTest, you defined test TheSecondTestWithThisNameShouldFail and test TheSecondTestWithThisNameShouldFail using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one -of the classes to put the tests into different test cases. +of the classes to put the tests into different test suites. Stack trace: (omitted) -[0;31m[ FAILED ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +[0;31m[ FAILED ] [mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail [0;32m[----------] [m2 tests from TEST_F_before_TEST_in_same_test_case [0;32m[ RUN ] [mTEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F [0;32m[ OK ] [mTEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F [0;32m[ RUN ] [mTEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class, so mixing TEST_F and TEST in the same test case is -illegal. In test case TEST_F_before_TEST_in_same_test_case, +All tests in the same test suite must use the same test fixture +class, so mixing TEST_F and TEST in the same test suite is +illegal. In test suite TEST_F_before_TEST_in_same_test_case, test DefinedUsingTEST_F is defined using TEST_F but test DefinedUsingTESTAndShouldFail is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test @@ -453,9 +461,9 @@ Stack trace: (omitted) [0;32m[ RUN ] [mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail gtest.cc:#: Failure Failed -All tests in the same test case must use the same test fixture -class, so mixing TEST_F and TEST in the same test case is -illegal. In test case TEST_before_TEST_F_in_same_test_case, +All tests in the same test suite must use the same test fixture +class, so mixing TEST_F and TEST in the same test suite is +illegal. In test suite TEST_before_TEST_F_in_same_test_case, test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but test DefinedUsingTEST is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test @@ -870,6 +878,84 @@ Expected non-fatal failure. Stack trace: (omitted) [0;31m[ FAILED ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[0;32m[----------] [m2 tests from DynamicFixture +DynamicFixture::SetUpTestSuite +[0;32m[ RUN ] [mDynamicFixture.DynamicTestPass +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[0;32m[ OK ] [mDynamicFixture.DynamicTestPass +[0;32m[ RUN ] [mDynamicFixture.DynamicTestFail +DynamicFixture() +DynamicFixture::SetUp +googletest-output-test_.cc:#: Failure +Value of: Pass + Actual: false +Expected: true +Stack trace: (omitted) + +DynamicFixture::TearDown +~DynamicFixture() +[0;31m[ FAILED ] [mDynamicFixture.DynamicTestFail +DynamicFixture::TearDownTestSuite +[0;32m[----------] [m1 test from DynamicFixtureAnotherName +DynamicFixture::SetUpTestSuite +[0;32m[ RUN ] [mDynamicFixtureAnotherName.DynamicTestPass +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[0;32m[ OK ] [mDynamicFixtureAnotherName.DynamicTestPass +DynamicFixture::TearDownTestSuite +[0;32m[----------] [m2 tests from BadDynamicFixture1 +DynamicFixture::SetUpTestSuite +[0;32m[ RUN ] [mBadDynamicFixture1.FixtureBase +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[0;32m[ OK ] [mBadDynamicFixture1.FixtureBase +[0;32m[ RUN ] [mBadDynamicFixture1.TestBase +DynamicFixture() +gtest.cc:#: Failure +Failed +All tests in the same test suite must use the same test fixture +class, so mixing TEST_F and TEST in the same test suite is +illegal. In test suite BadDynamicFixture1, +test FixtureBase is defined using TEST_F but +test TestBase is defined using TEST. You probably +want to change the TEST to TEST_F or move it to another test +case. +Stack trace: (omitted) + +~DynamicFixture() +[0;31m[ FAILED ] [mBadDynamicFixture1.TestBase +DynamicFixture::TearDownTestSuite +[0;32m[----------] [m2 tests from BadDynamicFixture2 +DynamicFixture::SetUpTestSuite +[0;32m[ RUN ] [mBadDynamicFixture2.FixtureBase +DynamicFixture() +DynamicFixture::SetUp +DynamicFixture::TearDown +~DynamicFixture() +[0;32m[ OK ] [mBadDynamicFixture2.FixtureBase +[0;32m[ RUN ] [mBadDynamicFixture2.Derived +DynamicFixture() +gtest.cc:#: Failure +Failed +All tests in the same test suite must use the same test fixture +class. However, in test suite BadDynamicFixture2, +you defined test FixtureBase and test Derived +using two different test fixture classes. This can happen if +the two classes are from different namespaces or translation +units and have the same name. You should probably rename one +of the classes to put the tests into different test suites. +Stack trace: (omitted) + +~DynamicFixture() +[0;31m[ FAILED ] [mBadDynamicFixture2.Derived +DynamicFixture::TearDownTestSuite [0;32m[----------] [m1 test from PrintingFailingParams/FailingParamTest [0;32m[ RUN ] [mPrintingFailingParams/FailingParamTest.Fails/0 googletest-output-test_.cc:#: Failure @@ -880,6 +966,9 @@ Expected equality of these values: Stack trace: (omitted) [0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 +[0;32m[----------] [m1 test from EmptyBasenameParamInst +[0;32m[ RUN ] [mEmptyBasenameParamInst.Passes/0 +[0;32m[ OK ] [mEmptyBasenameParamInst.Passes/0 [0;32m[----------] [m2 tests from PrintingStrings/ParamTest [0;32m[ RUN ] [mPrintingStrings/ParamTest.Success/a [0;32m[ OK ] [mPrintingStrings/ParamTest.Success/a @@ -906,9 +995,9 @@ Failed Expected fatal failure. Stack trace: (omitted) -[0;32m[==========] [m76 tests from 34 test cases ran. -[0;32m[ PASSED ] [m26 tests. -[0;31m[ FAILED ] [m50 tests, listed below: +[0;32m[==========] [m85 tests from 40 test suites ran. +[0;32m[ PASSED ] [m31 tests. +[0;31m[ FAILED ] [m54 tests, listed below: [0;31m[ FAILED ] [mNonfatalFailureTest.EscapesStringOperands [0;31m[ FAILED ] [mNonfatalFailureTest.DiffForLongStrings [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInSubroutine @@ -928,9 +1017,10 @@ Stack trace: (omitted) [0;31m[ FAILED ] [mNonFatalFailureInSetUpTest.FailureInSetUp [0;31m[ FAILED ] [mFatalFailureInSetUpTest.FailureInSetUp [0;31m[ FAILED ] [mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber -[0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFail -[0;31m[ FAILED ] [mMixedUpTestCaseTest.ThisShouldFailToo -[0;31m[ FAILED ] [mMixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail +[0;31m[ FAILED ] [mGtestFailAtTest.MessageContainsSpecifiedFileAndLineNumber +[0;31m[ FAILED ] [mMixedUpTestSuiteTest.ThisShouldFail +[0;31m[ FAILED ] [mMixedUpTestSuiteTest.ThisShouldFailToo +[0;31m[ FAILED ] [mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail [0;31m[ FAILED ] [mTEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail [0;31m[ FAILED ] [mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail [0;31m[ FAILED ] [mExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure @@ -957,14 +1047,17 @@ Stack trace: (omitted) [0;31m[ FAILED ] [mExpectFailureWithThreadsTest.ExpectFatalFailure [0;31m[ FAILED ] [mExpectFailureWithThreadsTest.ExpectNonFatalFailure [0;31m[ FAILED ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[0;31m[ FAILED ] [mDynamicFixture.DynamicTestFail +[0;31m[ FAILED ] [mBadDynamicFixture1.TestBase +[0;31m[ FAILED ] [mBadDynamicFixture2.Derived [0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [0;31m[ FAILED ] [mPrintingStrings/ParamTest.Failure/a, where GetParam() = "a" -50 FAILED TESTS +54 FAILED TESTS [0;33m YOU HAVE 1 DISABLED TEST [mNote: Google Test filter = FatalFailureTest.*:LoggingTest.* -[==========] Running 4 tests from 2 test cases. +[==========] Running 4 tests from 2 test suites. [----------] Global test environment set-up. [----------] 3 tests from FatalFailureTest [ RUN ] FatalFailureTest.FatalFailureInSubroutine @@ -1017,7 +1110,7 @@ Stack trace: (omitted) [----------] 1 test from LoggingTest (? ms total) [----------] Global test environment tear-down -[==========] 4 tests from 2 test cases ran. (? ms total) +[==========] 4 tests from 2 test suites ran. (? ms total) [ PASSED ] 0 tests. [ FAILED ] 4 tests, listed below: [ FAILED ] FatalFailureTest.FatalFailureInSubroutine @@ -1027,21 +1120,21 @@ Stack trace: (omitted) 4 FAILED TESTS Note: Google Test filter = *DISABLED_* -[==========] Running 1 test from 1 test case. +[==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from DisabledTestsWarningTest [ RUN ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning [ OK ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning [----------] Global test environment tear-down -[==========] 1 test from 1 test case ran. +[==========] 1 test from 1 test suite ran. [ PASSED ] 1 test. Note: Google Test filter = PassingTest.* Note: This is test shard 2 of 2. -[==========] Running 1 test from 1 test case. +[==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from PassingTest [ RUN ] PassingTest.PassingTest2 [ OK ] PassingTest.PassingTest2 [----------] Global test environment tear-down -[==========] 1 test from 1 test case ran. +[==========] 1 test from 1 test suite ran. [ PASSED ] 1 test. diff --git a/googletest/test/googletest-output-test.py b/googletest/test/googletest-output-test.py index 2d69e353a19e..c727f17a4963 100755 --- a/googletest/test/googletest-output-test.py +++ b/googletest/test/googletest-output-test.py @@ -55,7 +55,6 @@ NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' -# FIXME: remove the _lin suffix. GOLDEN_NAME = 'googletest-output-test-golden-lin.txt' PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_') @@ -287,7 +286,7 @@ class GTestOutputTest(gtest_test_utils.TestCase): # sequences when we read the golden file irrespective of an operating # system used. Therefore, we need to strip those \r's from newlines # unconditionally. - golden = ToUnixLineEnding(golden_file.read()) + golden = ToUnixLineEnding(golden_file.read().decode()) golden_file.close() # We want the test to pass regardless of certain features being diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc index f6525ec970de..4f716d843b12 100644 --- a/googletest/test/googletest-output-test_.cc +++ b/googletest/test/googletest-output-test_.cc @@ -92,9 +92,17 @@ TEST_P(FailingParamTest, Fails) { // This generates a test which will fail. Google Test is expected to print // its parameter when it outputs the list of all failed tests. -INSTANTIATE_TEST_CASE_P(PrintingFailingParams, - FailingParamTest, - testing::Values(2)); +INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, + FailingParamTest, + testing::Values(2)); + +// Tests that an empty value for the test suite basename yields just +// the test name without any prior / +class EmptyBasenameParamInst : public testing::TestWithParam<int> {}; + +TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); } + +INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1)); static const char kGoldenString[] = "\"Line\0 1\"\nLine 2"; @@ -174,7 +182,7 @@ TEST(SCOPED_TRACETest, AcceptedValues) { SCOPED_TRACE("literal string"); SCOPED_TRACE(std::string("std::string")); SCOPED_TRACE(1337); // streamable type - const char* null_value = NULL; + const char* null_value = nullptr; SCOPED_TRACE(null_value); ADD_FAILURE() << "Just checking that all these values work fine."; @@ -306,9 +314,8 @@ TEST(SCOPED_TRACETest, WorksConcurrently) { printf("(expecting 6 failures)\n"); CheckPoints check_points; - ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace, - &check_points, - NULL); + ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace, &check_points, + nullptr); check_points.n1.WaitForNotification(); { @@ -365,15 +372,13 @@ class NonFatalFailureInFixtureConstructorTest : public testing::Test { ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor."; } - ~NonFatalFailureInFixtureConstructorTest() { + ~NonFatalFailureInFixtureConstructorTest() override { ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor."; } - virtual void SetUp() { - ADD_FAILURE() << "Expected failure #2, in SetUp()."; - } + void SetUp() override { ADD_FAILURE() << "Expected failure #2, in SetUp()."; } - virtual void TearDown() { + void TearDown() override { ADD_FAILURE() << "Expected failure #4, in TearDown."; } }; @@ -390,17 +395,17 @@ class FatalFailureInFixtureConstructorTest : public testing::Test { Init(); } - ~FatalFailureInFixtureConstructorTest() { + ~FatalFailureInFixtureConstructorTest() override { ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor."; } - virtual void SetUp() { + void SetUp() override { ADD_FAILURE() << "UNEXPECTED failure in SetUp(). " << "We should never get here, as the test fixture c'tor " << "had a fatal failure."; } - virtual void TearDown() { + void TearDown() override { ADD_FAILURE() << "UNEXPECTED failure in TearDown(). " << "We should never get here, as the test fixture c'tor " << "had a fatal failure."; @@ -421,18 +426,15 @@ TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) { // Tests non-fatal failures in SetUp(). class NonFatalFailureInSetUpTest : public testing::Test { protected: - virtual ~NonFatalFailureInSetUpTest() { - Deinit(); - } + ~NonFatalFailureInSetUpTest() override { Deinit(); } - virtual void SetUp() { + void SetUp() override { printf("(expecting 4 failures)\n"); ADD_FAILURE() << "Expected failure #1, in SetUp()."; } - virtual void TearDown() { - FAIL() << "Expected failure #3, in TearDown()."; - } + void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; } + private: void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; @@ -446,18 +448,15 @@ TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) { // Tests fatal failures in SetUp(). class FatalFailureInSetUpTest : public testing::Test { protected: - virtual ~FatalFailureInSetUpTest() { - Deinit(); - } + ~FatalFailureInSetUpTest() override { Deinit(); } - virtual void SetUp() { + void SetUp() override { printf("(expecting 3 failures)\n"); FAIL() << "Expected failure #1, in SetUp()."; } - virtual void TearDown() { - FAIL() << "Expected failure #2, in TearDown()."; - } + void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; } + private: void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; @@ -470,7 +469,11 @@ TEST_F(FatalFailureInSetUpTest, FailureInSetUp) { } TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) { - ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc"; + ADD_FAILURE_AT("foo.cc", 42) << "Expected nonfatal failure in foo.cc"; +} + +TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) { + GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc"; } #if GTEST_IS_THREADSAFE @@ -509,9 +512,9 @@ static void ThreadRoutine(SpawnThreadNotifications* notifications) { class DeathTestAndMultiThreadsTest : public testing::Test { protected: // Starts a thread and waits for it to begin. - virtual void SetUp() { + void SetUp() override { thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>( - &ThreadRoutine, ¬ifications_, NULL)); + &ThreadRoutine, ¬ifications_, nullptr)); notifications_.spawn_thread_started.WaitForNotification(); } // Tells the thread to finish, and reaps it. @@ -519,60 +522,59 @@ class DeathTestAndMultiThreadsTest : public testing::Test { // a manager thread might still be left running that will interfere // with later death tests. This is unfortunate, but this class // cleans up after itself as best it can. - virtual void TearDown() { + void TearDown() override { notifications_.spawn_thread_ok_to_terminate.Notify(); } private: SpawnThreadNotifications notifications_; - testing::internal::scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> > - thread_; + std::unique_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_; }; #endif // GTEST_IS_THREADSAFE -// The MixedUpTestCaseTest test case verifies that Google Test will fail a +// The MixedUpTestSuiteTest test case verifies that Google Test will fail a // test if it uses a different fixture class than what other tests in // the same test case use. It deliberately contains two fixture // classes with the same name but defined in different namespaces. -// The MixedUpTestCaseWithSameTestNameTest test case verifies that +// The MixedUpTestSuiteWithSameTestNameTest test case verifies that // when the user defines two tests with the same test case name AND // same test name (but in different namespaces), the second test will // fail. namespace foo { -class MixedUpTestCaseTest : public testing::Test { +class MixedUpTestSuiteTest : public testing::Test { }; -TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {} -TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {} +TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {} +TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {} -class MixedUpTestCaseWithSameTestNameTest : public testing::Test { +class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { }; -TEST_F(MixedUpTestCaseWithSameTestNameTest, +TEST_F(MixedUpTestSuiteWithSameTestNameTest, TheSecondTestWithThisNameShouldFail) {} } // namespace foo namespace bar { -class MixedUpTestCaseTest : public testing::Test { +class MixedUpTestSuiteTest : public testing::Test { }; // The following two tests are expected to fail. We rely on the // golden file to check that Google Test generates the right error message. -TEST_F(MixedUpTestCaseTest, ThisShouldFail) {} -TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {} +TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {} +TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {} -class MixedUpTestCaseWithSameTestNameTest : public testing::Test { +class MixedUpTestSuiteWithSameTestNameTest : public testing::Test { }; // Expected to fail. We rely on the golden file to check that Google Test // generates the right error message. -TEST_F(MixedUpTestCaseWithSameTestNameTest, +TEST_F(MixedUpTestSuiteWithSameTestNameTest, TheSecondTestWithThisNameShouldFail) {} } // namespace bar @@ -783,10 +785,10 @@ TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; } -INSTANTIATE_TEST_CASE_P(PrintingStrings, - ParamTest, - testing::Values(std::string("a")), - ParamNameFunc); +INSTANTIATE_TEST_SUITE_P(PrintingStrings, + ParamTest, + testing::Values(std::string("a")), + ParamNameFunc); // This #ifdef block tests the output of typed tests. #if GTEST_HAS_TYPED_TEST @@ -795,7 +797,7 @@ template <typename T> class TypedTest : public testing::Test { }; -TYPED_TEST_CASE(TypedTest, testing::Types<int>); +TYPED_TEST_SUITE(TypedTest, testing::Types<int>); TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); @@ -814,14 +816,14 @@ class TypedTestNames { public: template <typename T> static std::string GetName(int i) { - if (testing::internal::IsSame<T, char>::value) + if (std::is_same<T, char>::value) return std::string("char") + ::testing::PrintToString(i); - if (testing::internal::IsSame<T, int>::value) + if (std::is_same<T, int>::value) return std::string("int") + ::testing::PrintToString(i); } }; -TYPED_TEST_CASE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames); +TYPED_TEST_SUITE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames); TYPED_TEST(TypedTestWithNames, Success) {} @@ -836,7 +838,7 @@ template <typename T> class TypedTestP : public testing::Test { }; -TYPED_TEST_CASE_P(TypedTestP); +TYPED_TEST_SUITE_P(TypedTestP); TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); @@ -846,25 +848,25 @@ TYPED_TEST_P(TypedTestP, Failure) { EXPECT_EQ(1U, TypeParam()) << "Expected failure"; } -REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure); +REGISTER_TYPED_TEST_SUITE_P(TypedTestP, Success, Failure); typedef testing::Types<unsigned char, unsigned int> UnsignedTypes; -INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(Unsigned, TypedTestP, UnsignedTypes); class TypedTestPNames { public: template <typename T> static std::string GetName(int i) { - if (testing::internal::IsSame<T, unsigned char>::value) { + if (std::is_same<T, unsigned char>::value) { return std::string("unsignedChar") + ::testing::PrintToString(i); } - if (testing::internal::IsSame<T, unsigned int>::value) { + if (std::is_same<T, unsigned int>::value) { return std::string("unsignedInt") + ::testing::PrintToString(i); } } }; -INSTANTIATE_TYPED_TEST_CASE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, +INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes, TypedTestPNames); #endif // GTEST_HAS_TYPED_TEST_P @@ -887,7 +889,7 @@ class ATypedDeathTest : public testing::Test { }; typedef testing::Types<int, double> NumericTypes; -TYPED_TEST_CASE(ATypedDeathTest, NumericTypes); +TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes); TYPED_TEST(ATypedDeathTest, ShouldRunFirst) { } @@ -904,14 +906,14 @@ template <typename T> class ATypeParamDeathTest : public testing::Test { }; -TYPED_TEST_CASE_P(ATypeParamDeathTest); +TYPED_TEST_SUITE_P(ATypeParamDeathTest); TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) { } -REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst); +REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst); -INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes); # endif // GTEST_HAS_TYPED_TEST_P @@ -966,7 +968,7 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailure) { class ExpectFailureWithThreadsTest : public ExpectFailureTest { protected: static void AddFailureInOtherThread(FailureMode failure) { - ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL); + ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr); thread.Join(); } }; @@ -1034,16 +1036,64 @@ TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) { "Some other non-fatal failure."); } +class DynamicFixture : public testing::Test { + protected: + DynamicFixture() { printf("DynamicFixture()\n"); } + ~DynamicFixture() override { printf("~DynamicFixture()\n"); } + void SetUp() override { printf("DynamicFixture::SetUp\n"); } + void TearDown() override { printf("DynamicFixture::TearDown\n"); } + + static void SetUpTestSuite() { printf("DynamicFixture::SetUpTestSuite\n"); } + static void TearDownTestSuite() { + printf("DynamicFixture::TearDownTestSuite\n"); + } +}; + +template <bool Pass> +class DynamicTest : public DynamicFixture { + public: + void TestBody() override { EXPECT_TRUE(Pass); } +}; + +auto dynamic_test = ( + // Register two tests with the same fixture correctly. + testing::RegisterTest( + "DynamicFixture", "DynamicTestPass", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }), + testing::RegisterTest( + "DynamicFixture", "DynamicTestFail", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest<false>; }), + + // Register the same fixture with another name. That's fine. + testing::RegisterTest( + "DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr, + __FILE__, __LINE__, + []() -> DynamicFixture* { return new DynamicTest<true>; }), + + // Register two tests with the same fixture incorrectly. + testing::RegisterTest( + "BadDynamicFixture1", "FixtureBase", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }), + testing::RegisterTest( + "BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__, + []() -> testing::Test* { return new DynamicTest<true>; }), + + // Register two tests with the same fixture incorrectly by ommiting the + // return type. + testing::RegisterTest( + "BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__, + __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }), + testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr, + __FILE__, __LINE__, + []() { return new DynamicTest<true>; })); // Two test environments for testing testing::AddGlobalTestEnvironment(). class FooEnvironment : public testing::Environment { public: - virtual void SetUp() { - printf("%s", "FooEnvironment::SetUp() called.\n"); - } + void SetUp() override { printf("%s", "FooEnvironment::SetUp() called.\n"); } - virtual void TearDown() { + void TearDown() override { printf("%s", "FooEnvironment::TearDown() called.\n"); FAIL() << "Expected fatal failure."; } @@ -1051,11 +1101,9 @@ class FooEnvironment : public testing::Environment { class BarEnvironment : public testing::Environment { public: - virtual void SetUp() { - printf("%s", "BarEnvironment::SetUp() called.\n"); - } + void SetUp() override { printf("%s", "BarEnvironment::SetUp() called.\n"); } - virtual void TearDown() { + void TearDown() override { printf("%s", "BarEnvironment::TearDown() called.\n"); ADD_FAILURE() << "Expected non-fatal failure."; } diff --git a/googletest/test/googletest-param-test-invalid-name1-test_.cc b/googletest/test/googletest-param-test-invalid-name1-test_.cc index 5a95155b23a7..955d699900d8 100644 --- a/googletest/test/googletest-param-test-invalid-name1-test_.cc +++ b/googletest/test/googletest-param-test-invalid-name1-test_.cc @@ -36,10 +36,10 @@ class DummyTest : public ::testing::TestWithParam<const char *> {}; TEST_P(DummyTest, Dummy) { } -INSTANTIATE_TEST_CASE_P(InvalidTestName, - DummyTest, - ::testing::Values("InvalidWithQuotes"), - ::testing::PrintToStringParamName()); +INSTANTIATE_TEST_SUITE_P(InvalidTestName, + DummyTest, + ::testing::Values("InvalidWithQuotes"), + ::testing::PrintToStringParamName()); } // namespace diff --git a/googletest/test/googletest-param-test-invalid-name2-test_.cc b/googletest/test/googletest-param-test-invalid-name2-test_.cc index ef093490e9da..76371df54f0b 100644 --- a/googletest/test/googletest-param-test-invalid-name2-test_.cc +++ b/googletest/test/googletest-param-test-invalid-name2-test_.cc @@ -41,10 +41,10 @@ std::string StringParamTestSuffix( TEST_P(DummyTest, Dummy) { } -INSTANTIATE_TEST_CASE_P(DuplicateTestNames, - DummyTest, - ::testing::Values("a", "b", "a", "c"), - StringParamTestSuffix); +INSTANTIATE_TEST_SUITE_P(DuplicateTestNames, + DummyTest, + ::testing::Values("a", "b", "a", "c"), + StringParamTestSuffix); } // namespace int main(int argc, char *argv[]) { diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc index f789cab27074..6c187dfff0c1 100644 --- a/googletest/test/googletest-param-test-test.cc +++ b/googletest/test/googletest-param-test-test.cc @@ -49,19 +49,13 @@ using ::std::sort; using ::testing::AddGlobalTestEnvironment; using ::testing::Bool; +using ::testing::Combine; using ::testing::Message; using ::testing::Range; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; -# if GTEST_HAS_COMBINE -using ::testing::Combine; -using ::testing::get; -using ::testing::make_tuple; -using ::testing::tuple; -# endif // GTEST_HAS_COMBINE - using ::testing::internal::ParamGenerator; using ::testing::internal::UnitTestOptions; @@ -73,49 +67,9 @@ using ::testing::internal::UnitTestOptions; // EXPECT_THAT() and the matchers know how to print tuples. template <typename T> ::std::string PrintValue(const T& value) { - ::std::stringstream stream; - stream << value; - return stream.str(); -} - -# if GTEST_HAS_COMBINE - -// These overloads allow printing tuples in our tests. We cannot -// define an operator<< for tuples, as that definition needs to be in -// the std namespace in order to be picked up by Google Test via -// Argument-Dependent Lookup, yet defining anything in the std -// namespace in non-STL code is undefined behavior. - -template <typename T1, typename T2> -::std::string PrintValue(const tuple<T1, T2>& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) << ")"; - return stream.str(); -} - -template <typename T1, typename T2, typename T3> -::std::string PrintValue(const tuple<T1, T2, T3>& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) - << ", "<< get<2>(value) << ")"; - return stream.str(); + return testing::PrintToString(value); } -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8, typename T9, typename T10> -::std::string PrintValue( - const tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& value) { - ::std::stringstream stream; - stream << "(" << get<0>(value) << ", " << get<1>(value) - << ", "<< get<2>(value) << ", " << get<3>(value) - << ", "<< get<4>(value) << ", " << get<5>(value) - << ", "<< get<6>(value) << ", " << get<7>(value) - << ", "<< get<8>(value) << ", " << get<9>(value) << ")"; - return stream.str(); -} - -# endif // GTEST_HAS_COMBINE - // Verifies that a sequence generated by the generator and accessed // via the iterator object matches the expected one using Google Test // assertions. @@ -450,31 +404,28 @@ TEST(BoolTest, BoolWorks) { VerifyGenerator(gen, expected_values); } -# if GTEST_HAS_COMBINE - // Tests that Combine() with two parameters generates the expected sequence. TEST(CombineTest, CombineWithTwoParameters) { const char* foo = "foo"; const char* bar = "bar"; - const ParamGenerator<tuple<const char*, int> > gen = + const ParamGenerator<std::tuple<const char*, int> > gen = Combine(Values(foo, bar), Values(3, 4)); - tuple<const char*, int> expected_values[] = { - make_tuple(foo, 3), make_tuple(foo, 4), - make_tuple(bar, 3), make_tuple(bar, 4)}; + std::tuple<const char*, int> expected_values[] = { + std::make_tuple(foo, 3), std::make_tuple(foo, 4), std::make_tuple(bar, 3), + std::make_tuple(bar, 4)}; VerifyGenerator(gen, expected_values); } // Tests that Combine() with three parameters generates the expected sequence. TEST(CombineTest, CombineWithThreeParameters) { - const ParamGenerator<tuple<int, int, int> > gen = Combine(Values(0, 1), - Values(3, 4), - Values(5, 6)); - tuple<int, int, int> expected_values[] = { - make_tuple(0, 3, 5), make_tuple(0, 3, 6), - make_tuple(0, 4, 5), make_tuple(0, 4, 6), - make_tuple(1, 3, 5), make_tuple(1, 3, 6), - make_tuple(1, 4, 5), make_tuple(1, 4, 6)}; + const ParamGenerator<std::tuple<int, int, int> > gen = + Combine(Values(0, 1), Values(3, 4), Values(5, 6)); + std::tuple<int, int, int> expected_values[] = { + std::make_tuple(0, 3, 5), std::make_tuple(0, 3, 6), + std::make_tuple(0, 4, 5), std::make_tuple(0, 4, 6), + std::make_tuple(1, 3, 5), std::make_tuple(1, 3, 6), + std::make_tuple(1, 4, 5), std::make_tuple(1, 4, 6)}; VerifyGenerator(gen, expected_values); } @@ -482,10 +433,11 @@ TEST(CombineTest, CombineWithThreeParameters) { // sequence generates a sequence with the number of elements equal to the // number of elements in the sequence generated by the second parameter. TEST(CombineTest, CombineWithFirstParameterSingleValue) { - const ParamGenerator<tuple<int, int> > gen = Combine(Values(42), - Values(0, 1)); + const ParamGenerator<std::tuple<int, int> > gen = + Combine(Values(42), Values(0, 1)); - tuple<int, int> expected_values[] = {make_tuple(42, 0), make_tuple(42, 1)}; + std::tuple<int, int> expected_values[] = {std::make_tuple(42, 0), + std::make_tuple(42, 1)}; VerifyGenerator(gen, expected_values); } @@ -493,26 +445,27 @@ TEST(CombineTest, CombineWithFirstParameterSingleValue) { // sequence generates a sequence with the number of elements equal to the // number of elements in the sequence generated by the first parameter. TEST(CombineTest, CombineWithSecondParameterSingleValue) { - const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1), - Values(42)); + const ParamGenerator<std::tuple<int, int> > gen = + Combine(Values(0, 1), Values(42)); - tuple<int, int> expected_values[] = {make_tuple(0, 42), make_tuple(1, 42)}; + std::tuple<int, int> expected_values[] = {std::make_tuple(0, 42), + std::make_tuple(1, 42)}; VerifyGenerator(gen, expected_values); } // Tests that when the first parameter produces an empty sequence, // Combine() produces an empty sequence, too. TEST(CombineTest, CombineWithFirstParameterEmptyRange) { - const ParamGenerator<tuple<int, int> > gen = Combine(Range(0, 0), - Values(0, 1)); + const ParamGenerator<std::tuple<int, int> > gen = + Combine(Range(0, 0), Values(0, 1)); VerifyGeneratorIsEmpty(gen); } // Tests that when the second parameter produces an empty sequence, // Combine() produces an empty sequence, too. TEST(CombineTest, CombineWithSecondParameterEmptyRange) { - const ParamGenerator<tuple<int, int> > gen = Combine(Values(0, 1), - Range(1, 1)); + const ParamGenerator<std::tuple<int, int> > gen = + Combine(Values(0, 1), Range(1, 1)); VerifyGeneratorIsEmpty(gen); } @@ -521,22 +474,18 @@ TEST(CombineTest, CombineWithSecondParameterEmptyRange) { TEST(CombineTest, CombineWithMaxNumberOfParameters) { const char* foo = "foo"; const char* bar = "bar"; - const ParamGenerator<tuple<const char*, int, int, int, int, int, int, int, - int, int> > gen = Combine(Values(foo, bar), - Values(1), Values(2), - Values(3), Values(4), - Values(5), Values(6), - Values(7), Values(8), - Values(9)); - - tuple<const char*, int, int, int, int, int, int, int, int, int> - expected_values[] = {make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9), - make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)}; + const ParamGenerator< + std::tuple<const char*, int, int, int, int, int, int, int, int, int> > + gen = + Combine(Values(foo, bar), Values(1), Values(2), Values(3), Values(4), + Values(5), Values(6), Values(7), Values(8), Values(9)); + + std::tuple<const char*, int, int, int, int, int, int, int, int, int> + expected_values[] = {std::make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9), + std::make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)}; VerifyGenerator(gen, expected_values); } -#if GTEST_LANG_CXX11 - class NonDefaultConstructAssignString { public: NonDefaultConstructAssignString(const std::string& s) : str_(s) {} @@ -553,12 +502,12 @@ class NonDefaultConstructAssignString { }; TEST(CombineTest, NonDefaultConstructAssign) { - const ParamGenerator<tuple<int, NonDefaultConstructAssignString> > gen = + const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> > gen = Combine(Values(0, 1), Values(NonDefaultConstructAssignString("A"), NonDefaultConstructAssignString("B"))); - ParamGenerator<tuple<int, NonDefaultConstructAssignString> >::iterator it = - gen.begin(); + ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> >::iterator + it = gen.begin(); EXPECT_EQ(0, std::get<0>(*it)); EXPECT_EQ("A", std::get<1>(*it).str()); @@ -579,8 +528,6 @@ TEST(CombineTest, NonDefaultConstructAssign) { EXPECT_TRUE(it == gen.end()); } -#endif // GTEST_LANG_CXX11 -# endif // GTEST_HAS_COMBINE // Tests that an generator produces correct sequence after being // assigned from another generator. @@ -595,12 +542,12 @@ TEST(ParamGeneratorTest, AssignmentWorks) { // This test verifies that the tests are expanded and run as specified: // one test per element from the sequence produced by the generator -// specified in INSTANTIATE_TEST_CASE_P. It also verifies that the test's +// specified in INSTANTIATE_TEST_SUITE_P. It also verifies that the test's // fixture constructor, SetUp(), and TearDown() have run and have been // supplied with the correct parameters. // The use of environment object allows detection of the case where no test -// case functionality is run at all. In this case TestCaseTearDown will not +// case functionality is run at all. In this case TearDownTestSuite will not // be able to detect missing tests, naturally. template <int kExpectedCalls> class TestGenerationEnvironment : public ::testing::Environment { @@ -615,7 +562,7 @@ class TestGenerationEnvironment : public ::testing::Environment { void TearDownExecuted() { tear_down_count_++; } void TestBodyExecuted() { test_body_count_++; } - virtual void TearDown() { + void TearDown() override { // If all MultipleTestGenerationTest tests have been de-selected // by the filter flag, the following checks make no sense. bool perform_check = false; @@ -672,16 +619,16 @@ class TestGenerationTest : public TestWithParam<int> { Environment::Instance()->FixtureConstructorExecuted(); current_parameter_ = GetParam(); } - virtual void SetUp() { + void SetUp() override { Environment::Instance()->SetUpExecuted(); EXPECT_EQ(current_parameter_, GetParam()); } - virtual void TearDown() { + void TearDown() override { Environment::Instance()->TearDownExecuted(); EXPECT_EQ(current_parameter_, GetParam()); } - static void SetUpTestCase() { + static void SetUpTestSuite() { bool all_tests_in_test_case_selected = true; for (int i = 0; i < PARAMETER_COUNT; ++i) { @@ -702,7 +649,7 @@ class TestGenerationTest : public TestWithParam<int> { collected_parameters_.clear(); } - static void TearDownTestCase() { + static void TearDownTestSuite() { vector<int> expected_values(test_generation_params, test_generation_params + PARAMETER_COUNT); // Test execution order is not guaranteed by Google Test, @@ -728,17 +675,17 @@ TEST_P(TestGenerationTest, TestsExpandedAndRun) { EXPECT_EQ(current_parameter_, GetParam()); collected_parameters_.push_back(GetParam()); } -INSTANTIATE_TEST_CASE_P(TestExpansionModule, TestGenerationTest, - ValuesIn(test_generation_params)); +INSTANTIATE_TEST_SUITE_P(TestExpansionModule, TestGenerationTest, + ValuesIn(test_generation_params)); // This test verifies that the element sequence (third parameter of -// INSTANTIATE_TEST_CASE_P) is evaluated in InitGoogleTest() and neither at -// the call site of INSTANTIATE_TEST_CASE_P nor in RUN_ALL_TESTS(). For +// INSTANTIATE_TEST_SUITE_P) is evaluated in InitGoogleTest() and neither at +// the call site of INSTANTIATE_TEST_SUITE_P nor in RUN_ALL_TESTS(). For // that, we declare param_value_ to be a static member of // GeneratorEvaluationTest and initialize it to 0. We set it to 1 in // main(), just before invocation of InitGoogleTest(). After calling // InitGoogleTest(), we set the value to 2. If the sequence is evaluated -// before or after InitGoogleTest, INSTANTIATE_TEST_CASE_P will create a +// before or after InitGoogleTest, INSTANTIATE_TEST_SUITE_P will create a // test with parameter other than 1, and the test body will fail the // assertion. class GeneratorEvaluationTest : public TestWithParam<int> { @@ -754,9 +701,8 @@ int GeneratorEvaluationTest::param_value_ = 0; TEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) { EXPECT_EQ(1, GetParam()); } -INSTANTIATE_TEST_CASE_P(GenEvalModule, - GeneratorEvaluationTest, - Values(GeneratorEvaluationTest::param_value())); +INSTANTIATE_TEST_SUITE_P(GenEvalModule, GeneratorEvaluationTest, + Values(GeneratorEvaluationTest::param_value())); // Tests that generators defined in a different translation unit are // functional. Generator extern_gen is defined in gtest-param-test_test2.cc. @@ -767,9 +713,8 @@ TEST_P(ExternalGeneratorTest, ExternalGenerator) { // which we verify here. EXPECT_EQ(GetParam(), 33); } -INSTANTIATE_TEST_CASE_P(ExternalGeneratorModule, - ExternalGeneratorTest, - extern_gen); +INSTANTIATE_TEST_SUITE_P(ExternalGeneratorModule, ExternalGeneratorTest, + extern_gen); // Tests that a parameterized test case can be defined in one translation // unit and instantiated in another. This test will be instantiated in @@ -784,20 +729,19 @@ TEST_P(ExternalInstantiationTest, IsMultipleOf33) { class MultipleInstantiationTest : public TestWithParam<int> {}; TEST_P(MultipleInstantiationTest, AllowsMultipleInstances) { } -INSTANTIATE_TEST_CASE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); -INSTANTIATE_TEST_CASE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); +INSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2)); +INSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5)); // Tests that a parameterized test case can be instantiated // in multiple translation units. This test will be instantiated // here and in gtest-param-test_test2.cc. // InstantiationInMultipleTranslationUnitsTest fixture class // is defined in gtest-param-test_test.h. -TEST_P(InstantiationInMultipleTranslaionUnitsTest, IsMultipleOf42) { +TEST_P(InstantiationInMultipleTranslationUnitsTest, IsMultipleOf42) { EXPECT_EQ(0, GetParam() % 42); } -INSTANTIATE_TEST_CASE_P(Sequence1, - InstantiationInMultipleTranslaionUnitsTest, - Values(42, 42*2)); +INSTANTIATE_TEST_SUITE_P(Sequence1, InstantiationInMultipleTranslationUnitsTest, + Values(42, 42 * 2)); // Tests that each iteration of parameterized test runs in a separate test // object. @@ -805,7 +749,7 @@ class SeparateInstanceTest : public TestWithParam<int> { public: SeparateInstanceTest() : count_(0) {} - static void TearDownTestCase() { + static void TearDownTestSuite() { EXPECT_GE(global_count_, 2) << "If some (but not all) SeparateInstanceTest tests have been " << "filtered out this test will fail. Make sure that all " @@ -823,20 +767,20 @@ TEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) { EXPECT_EQ(0, count_++); global_count_++; } -INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4)); +INSTANTIATE_TEST_SUITE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4)); // Tests that all instantiations of a test have named appropriately. Test -// defined with TEST_P(TestCaseName, TestName) and instantiated with -// INSTANTIATE_TEST_CASE_P(SequenceName, TestCaseName, generator) must be named -// SequenceName/TestCaseName.TestName/i, where i is the 0-based index of the -// sequence element used to instantiate the test. +// defined with TEST_P(TestSuiteName, TestName) and instantiated with +// INSTANTIATE_TEST_SUITE_P(SequenceName, TestSuiteName, generator) must be +// named SequenceName/TestSuiteName.TestName/i, where i is the 0-based index of +// the sequence element used to instantiate the test. class NamingTest : public TestWithParam<int> {}; TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); - EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name()); + EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_suite_name()); Message index_stream; index_stream << "TestsReportCorrectNamesAndParameters/" << GetParam(); @@ -845,7 +789,7 @@ TEST_P(NamingTest, TestsReportCorrectNamesAndParameters) { EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); } -INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); +INSTANTIATE_TEST_SUITE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); // Tests that macros in test names are expanded correctly. class MacroNamingTest : public TestWithParam<int> {}; @@ -857,11 +801,11 @@ TEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); - EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_case_name()); + EXPECT_STREQ("FortyTwo/MacroNamingTest", test_info->test_suite_name()); EXPECT_STREQ("FooSomeTestName", test_info->name()); } -INSTANTIATE_TEST_CASE_P(FortyTwo, MacroNamingTest, Values(42)); +INSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42)); // Tests the same thing for non-parametrized tests. class MacroNamingTestNonParametrized : public ::testing::Test {}; @@ -871,7 +815,7 @@ TEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized), const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); - EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_case_name()); + EXPECT_STREQ("MacroNamingTestNonParametrized", test_info->test_suite_name()); EXPECT_STREQ("FooSomeTestName", test_info->name()); } @@ -888,17 +832,14 @@ struct CustomParamNameFunctor { } }; -INSTANTIATE_TEST_CASE_P(CustomParamNameFunctor, - CustomFunctorNamingTest, - Values(std::string("FunctorName")), - CustomParamNameFunctor()); +INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctor, CustomFunctorNamingTest, + Values(std::string("FunctorName")), + CustomParamNameFunctor()); -INSTANTIATE_TEST_CASE_P(AllAllowedCharacters, - CustomFunctorNamingTest, - Values("abcdefghijklmnopqrstuvwxyz", - "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - "01234567890_"), - CustomParamNameFunctor()); +INSTANTIATE_TEST_SUITE_P(AllAllowedCharacters, CustomFunctorNamingTest, + Values("abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "01234567890_"), + CustomParamNameFunctor()); inline std::string CustomParamNameFunction( const ::testing::TestParamInfo<std::string>& inf) { @@ -908,45 +849,41 @@ inline std::string CustomParamNameFunction( class CustomFunctionNamingTest : public TestWithParam<std::string> {}; TEST_P(CustomFunctionNamingTest, CustomTestNames) {} -INSTANTIATE_TEST_CASE_P(CustomParamNameFunction, - CustomFunctionNamingTest, - Values(std::string("FunctionName")), - CustomParamNameFunction); +INSTANTIATE_TEST_SUITE_P(CustomParamNameFunction, CustomFunctionNamingTest, + Values(std::string("FunctionName")), + CustomParamNameFunction); -#if GTEST_LANG_CXX11 +INSTANTIATE_TEST_SUITE_P(CustomParamNameFunctionP, CustomFunctionNamingTest, + Values(std::string("FunctionNameP")), + &CustomParamNameFunction); // Test custom naming with a lambda class CustomLambdaNamingTest : public TestWithParam<std::string> {}; TEST_P(CustomLambdaNamingTest, CustomTestNames) {} -INSTANTIATE_TEST_CASE_P(CustomParamNameLambda, CustomLambdaNamingTest, - Values(std::string("LambdaName")), - [](const ::testing::TestParamInfo<std::string>& inf) { - return inf.param; - }); - -#endif // GTEST_LANG_CXX11 +INSTANTIATE_TEST_SUITE_P(CustomParamNameLambda, CustomLambdaNamingTest, + Values(std::string("LambdaName")), + [](const ::testing::TestParamInfo<std::string>& inf) { + return inf.param; + }); TEST(CustomNamingTest, CheckNameRegistry) { ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance(); std::set<std::string> test_names; - for (int case_num = 0; - case_num < unit_test->total_test_case_count(); - ++case_num) { - const ::testing::TestCase* test_case = unit_test->GetTestCase(case_num); - for (int test_num = 0; - test_num < test_case->total_test_count(); + for (int suite_num = 0; suite_num < unit_test->total_test_suite_count(); + ++suite_num) { + const ::testing::TestSuite* test_suite = unit_test->GetTestSuite(suite_num); + for (int test_num = 0; test_num < test_suite->total_test_count(); ++test_num) { - const ::testing::TestInfo* test_info = test_case->GetTestInfo(test_num); + const ::testing::TestInfo* test_info = test_suite->GetTestInfo(test_num); test_names.insert(std::string(test_info->name())); } } EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctorName")); EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionName")); -#if GTEST_LANG_CXX11 + EXPECT_EQ(1u, test_names.count("CustomTestNames/FunctionNameP")); EXPECT_EQ(1u, test_names.count("CustomTestNames/LambdaName")); -#endif // GTEST_LANG_CXX11 } // Test a numeric name to ensure PrintToStringParamName works correctly. @@ -961,10 +898,8 @@ TEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) { EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); } -INSTANTIATE_TEST_CASE_P(PrintToString, - CustomIntegerNamingTest, - Range(0, 5), - ::testing::PrintToStringParamName()); +INSTANTIATE_TEST_SUITE_P(PrintToString, CustomIntegerNamingTest, Range(0, 5), + ::testing::PrintToStringParamName()); // Test a custom struct with PrintToString. @@ -988,10 +923,9 @@ TEST_P(CustomStructNamingTest, TestsReportCorrectNames) { EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); } -INSTANTIATE_TEST_CASE_P(PrintToString, - CustomStructNamingTest, - Values(CustomStruct(0), CustomStruct(1)), - ::testing::PrintToStringParamName()); +INSTANTIATE_TEST_SUITE_P(PrintToString, CustomStructNamingTest, + Values(CustomStruct(0), CustomStruct(1)), + ::testing::PrintToStringParamName()); // Test that using a stateful parameter naming function works as expected. @@ -1020,10 +954,8 @@ TEST_P(StatefulNamingTest, TestsReportCorrectNames) { EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name()); } -INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor, - StatefulNamingTest, - Range(0, 5), - StatefulNamingFunctor()); +INSTANTIATE_TEST_SUITE_P(StatefulNamingFunctor, StatefulNamingTest, Range(0, 5), + StatefulNamingFunctor()); // Class that cannot be streamed into an ostream. It needs to be copyable // (and, in case of MSVC, also assignable) in order to be a test parameter @@ -1032,6 +964,8 @@ INSTANTIATE_TEST_CASE_P(StatefulNamingFunctor, class Unstreamable { public: explicit Unstreamable(int value) : value_(value) {} + // -Wunused-private-field: dummy accessor for `value_`. + const int& dummy_value() const { return value_; } private: int value_; @@ -1046,9 +980,8 @@ TEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) { EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param()); } -INSTANTIATE_TEST_CASE_P(InstantiationWithComments, - CommentTest, - Values(Unstreamable(1))); +INSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest, + Values(Unstreamable(1))); // Verify that we can create a hierarchy of test fixtures, where the base // class fixture is not parameterized and the derived class is. In this case @@ -1088,19 +1021,32 @@ TEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) { ".* value-parameterized test .*"); } -INSTANTIATE_TEST_CASE_P(RangeZeroToFive, ParameterizedDerivedTest, Range(0, 5)); +INSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest, + Range(0, 5)); + +// Tests param generator working with Enums +enum MyEnums { + ENUM1 = 1, + ENUM2 = 3, + ENUM3 = 8, +}; + +class MyEnumTest : public testing::TestWithParam<MyEnums> {}; +TEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); } +INSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest, + ::testing::Values(ENUM1, ENUM2, 0)); int main(int argc, char **argv) { - // Used in TestGenerationTest test case. + // Used in TestGenerationTest test suite. AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance()); - // Used in GeneratorEvaluationTest test case. Tests that the updated value + // Used in GeneratorEvaluationTest test suite. Tests that the updated value // will be picked up for instantiating tests in GeneratorEvaluationTest. GeneratorEvaluationTest::set_param_value(1); ::testing::InitGoogleTest(&argc, argv); - // Used in GeneratorEvaluationTest test case. Tests that value updated + // Used in GeneratorEvaluationTest test suite. Tests that value updated // here will NOT be used for instantiating tests in // GeneratorEvaluationTest. GeneratorEvaluationTest::set_param_value(2); diff --git a/googletest/test/googletest-param-test-test.h b/googletest/test/googletest-param-test-test.h index 632a61f4926b..648057017e84 100644 --- a/googletest/test/googletest-param-test-test.h +++ b/googletest/test/googletest-param-test-test.h @@ -44,7 +44,7 @@ class ExternalInstantiationTest : public ::testing::TestWithParam<int> { // Test fixture for testing instantiation of a test in multiple // translation units. -class InstantiationInMultipleTranslaionUnitsTest +class InstantiationInMultipleTranslationUnitsTest : public ::testing::TestWithParam<int> { }; diff --git a/googletest/test/googletest-param-test2-test.cc b/googletest/test/googletest-param-test2-test.cc index 25bb945c2f8e..2a29fb1d0686 100644 --- a/googletest/test/googletest-param-test2-test.cc +++ b/googletest/test/googletest-param-test2-test.cc @@ -46,16 +46,16 @@ ParamGenerator<int> extern_gen = Values(33); // and instantiated in another. The test is defined in // googletest-param-test-test.cc and ExternalInstantiationTest fixture class is // defined in gtest-param-test_test.h. -INSTANTIATE_TEST_CASE_P(MultiplesOf33, - ExternalInstantiationTest, - Values(33, 66)); +INSTANTIATE_TEST_SUITE_P(MultiplesOf33, + ExternalInstantiationTest, + Values(33, 66)); // Tests that a parameterized test case can be instantiated // in multiple translation units. Another instantiation is defined // in googletest-param-test-test.cc and -// InstantiationInMultipleTranslaionUnitsTest fixture is defined in +// InstantiationInMultipleTranslationUnitsTest fixture is defined in // gtest-param-test_test.h -INSTANTIATE_TEST_CASE_P(Sequence2, - InstantiationInMultipleTranslaionUnitsTest, - Values(42*3, 42*4, 42*5)); +INSTANTIATE_TEST_SUITE_P(Sequence2, + InstantiationInMultipleTranslationUnitsTest, + Values(42*3, 42*4, 42*5)); diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc index 399316f95b63..60d637c32f63 100644 --- a/googletest/test/googletest-port-test.cc +++ b/googletest/test/googletest-port-test.cc @@ -37,6 +37,7 @@ #endif // GTEST_OS_MAC #include <list> +#include <memory> #include <utility> // For std::pair and std::make_pair. #include <vector> @@ -200,32 +201,6 @@ TEST(ImplicitCastTest, CanUseImplicitConstructor) { EXPECT_TRUE(converted); } -TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { - StaticAssertTypeEq<int, - IteratorTraits< ::std::vector<int>::const_iterator>::value_type>(); - StaticAssertTypeEq<bool, - IteratorTraits< ::std::list<bool>::iterator>::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToNonConst) { - StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>(); - StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>(); -} - -TEST(IteratorTraitsTest, WorksForPointerToConst) { - StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>(); - StaticAssertTypeEq<const void*, - IteratorTraits<const void* const*>::value_type>(); -} - -// Tests that the element_type typedef is available in scoped_ptr and refers -// to the parameter type. -TEST(ScopedPtrTest, DefinesElementType) { - StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>(); -} - -// FIXME: Implement THE REST of scoped_ptr tests. - TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { if (AlwaysFalse()) GTEST_CHECK_(false) << "This should never be executed; " @@ -262,9 +237,9 @@ TEST(FormatFileLocationTest, FormatsFileLocation) { } TEST(FormatFileLocationTest, FormatsUnknownFile) { - EXPECT_PRED_FORMAT2( - IsSubstring, "unknown file", FormatFileLocation(NULL, 42)); - EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42)); + EXPECT_PRED_FORMAT2(IsSubstring, "unknown file", + FormatFileLocation(nullptr, 42)); + EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(nullptr, 42)); } TEST(FormatFileLocationTest, FormatsUknownLine) { @@ -272,7 +247,7 @@ TEST(FormatFileLocationTest, FormatsUknownLine) { } TEST(FormatFileLocationTest, FormatsUknownFileAndLine) { - EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1)); + EXPECT_EQ("unknown file:", FormatFileLocation(nullptr, -1)); } // Verifies behavior of FormatCompilerIndependentFileLocation. @@ -282,7 +257,7 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) { TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) { EXPECT_EQ("unknown file:42", - FormatCompilerIndependentFileLocation(NULL, 42)); + FormatCompilerIndependentFileLocation(nullptr, 42)); } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { @@ -290,15 +265,17 @@ TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { - EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1)); + EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(nullptr, -1)); } -#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA +#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \ + GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ + GTEST_OS_NETBSD || GTEST_OS_OPENBSD void* ThreadFunc(void* data) { internal::Mutex* mutex = static_cast<internal::Mutex*>(data); mutex->Lock(); mutex->Unlock(); - return NULL; + return nullptr; } TEST(GetThreadCountTest, ReturnsCorrectValue) { @@ -393,14 +370,9 @@ class RETest : public ::testing::Test {}; // Defines StringTypes as the list of all string types that class RE // supports. -typedef testing::Types< - ::std::string, -# if GTEST_HAS_GLOBAL_STRING - ::string, -# endif // GTEST_HAS_GLOBAL_STRING - const char*> StringTypes; +typedef testing::Types< ::std::string, const char*> StringTypes; -TYPED_TEST_CASE(RETest, StringTypes); +TYPED_TEST_SUITE(RETest, StringTypes); // Tests RE's implicit constructors. TYPED_TEST(RETest, ImplicitConstructorWorks) { @@ -965,7 +937,7 @@ TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) { EXPECT_EQ(0, t1.get()); ThreadLocal<void*> t2; - EXPECT_TRUE(t2.get() == NULL); + EXPECT_TRUE(t2.get() == nullptr); } TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) { @@ -1015,7 +987,7 @@ void AddTwo(int* param) { *param += 2; } TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { int i = 40; - ThreadWithParam<int*> thread(&AddTwo, &i, NULL); + ThreadWithParam<int*> thread(&AddTwo, &i, nullptr); thread.Join(); EXPECT_EQ(42, i); } @@ -1055,10 +1027,10 @@ class AtomicCounterWithMutex { // functionality as we are testing them here. pthread_mutex_t memory_barrier_mutex; GTEST_CHECK_POSIX_SUCCESS_( - pthread_mutex_init(&memory_barrier_mutex, NULL)); + pthread_mutex_init(&memory_barrier_mutex, nullptr)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex)); - SleepMilliseconds(random_.Generate(30)); + SleepMilliseconds(static_cast<int>(random_.Generate(30))); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex)); @@ -1066,7 +1038,7 @@ class AtomicCounterWithMutex { // On Windows, performing an interlocked access puts up a memory barrier. volatile LONG dummy = 0; ::InterlockedIncrement(&dummy); - SleepMilliseconds(random_.Generate(30)); + SleepMilliseconds(static_cast<int>(random_.Generate(30))); ::InterlockedIncrement(&dummy); #else # error "Memory barrier not implemented on this platform." @@ -1095,7 +1067,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType; const int kCycleCount = 20; const int kThreadCount = 7; - scoped_ptr<ThreadType> counting_threads[kThreadCount]; + std::unique_ptr<ThreadType> counting_threads[kThreadCount]; Notification threads_can_start; // Creates and runs kThreadCount threads that increment locked_counter // kCycleCount times each. @@ -1118,7 +1090,7 @@ TEST(MutexTest, OnlyOneThreadCanLockAtATime) { template <typename T> void RunFromThread(void (func)(T), T param) { - ThreadWithParam<T> thread(func, param, NULL); + ThreadWithParam<T> thread(func, param, nullptr); thread.Join(); } @@ -1250,8 +1222,8 @@ TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { ASSERT_EQ(0U, DestructorCall::List().size()); // This creates another DestructorTracker object in the new thread. - ThreadWithParam<ThreadParam> thread( - &CallThreadLocalGet, &thread_local_tracker, NULL); + ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet, + &thread_local_tracker, nullptr); thread.Join(); // The thread has exited, and we should have a DestroyedTracker diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc index ea8369d27e50..4bdc9adde9e0 100644 --- a/googletest/test/googletest-printers-test.cc +++ b/googletest/test/googletest-printers-test.cc @@ -37,29 +37,20 @@ #include <string.h> #include <algorithm> #include <deque> +#include <forward_list> #include <list> #include <map> #include <set> #include <sstream> #include <string> +#include <unordered_map> +#include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-printers.h" #include "gtest/gtest.h" -#if GTEST_HAS_UNORDERED_MAP_ -# include <unordered_map> // NOLINT -#endif // GTEST_HAS_UNORDERED_MAP_ - -#if GTEST_HAS_UNORDERED_SET_ -# include <unordered_set> // NOLINT -#endif // GTEST_HAS_UNORDERED_SET_ - -#if GTEST_HAS_STD_FORWARD_LIST_ -# include <forward_list> // NOLINT -#endif // GTEST_HAS_STD_FORWARD_LIST_ - // Some user-defined types for testing the universal value printer. // An anonymous enum type. @@ -192,8 +183,14 @@ class PathLike { public: struct iterator { typedef PathLike value_type; + + iterator& operator++(); + PathLike& operator*(); }; + using value_type = char; + using const_iterator = iterator; + PathLike() {} iterator begin() const { return iterator(); } @@ -228,9 +225,7 @@ using ::testing::internal::Strings; using ::testing::internal::UniversalPrint; using ::testing::internal::UniversalPrinter; using ::testing::internal::UniversalTersePrint; -#if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; -#endif // Prints a value to a string using the universal value printer. This // is a helper for testing UniversalPrinter<T>::Print() for various types. @@ -405,7 +400,7 @@ TEST(PrintCStringTest, NonConst) { // NULL C string. TEST(PrintCStringTest, Null) { - const char* p = NULL; + const char* p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -440,7 +435,7 @@ TEST(PrintWideCStringTest, NonConst) { // NULL wide C string. TEST(PrintWideCStringTest, Null) { - const wchar_t* p = NULL; + const wchar_t* p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -460,7 +455,7 @@ TEST(PrintWideCStringTest, EscapesProperly) { TEST(PrintCharPointerTest, SignedChar) { signed char* p = reinterpret_cast<signed char*>(0x1234); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -468,7 +463,7 @@ TEST(PrintCharPointerTest, SignedChar) { TEST(PrintCharPointerTest, ConstSignedChar) { signed char* p = reinterpret_cast<signed char*>(0x1234); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -476,7 +471,7 @@ TEST(PrintCharPointerTest, ConstSignedChar) { TEST(PrintCharPointerTest, UnsignedChar) { unsigned char* p = reinterpret_cast<unsigned char*>(0x1234); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -484,7 +479,7 @@ TEST(PrintCharPointerTest, UnsignedChar) { TEST(PrintCharPointerTest, ConstUnsignedChar) { const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -494,7 +489,7 @@ TEST(PrintCharPointerTest, ConstUnsignedChar) { TEST(PrintPointerToBuiltInTypeTest, Bool) { bool* p = reinterpret_cast<bool*>(0xABCD); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -502,7 +497,7 @@ TEST(PrintPointerToBuiltInTypeTest, Bool) { TEST(PrintPointerToBuiltInTypeTest, Void) { void* p = reinterpret_cast<void*>(0xABCD); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -510,7 +505,7 @@ TEST(PrintPointerToBuiltInTypeTest, Void) { TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { const void* p = reinterpret_cast<const void*>(0xABCD); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -518,7 +513,7 @@ TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { TEST(PrintPointerToPointerTest, IntPointerPointer) { int** p = reinterpret_cast<int**>(0xABCD); EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; + p = nullptr; EXPECT_EQ("NULL", Print(p)); } @@ -661,16 +656,6 @@ TEST(PrintArrayTest, BigArray) { // Tests printing ::string and ::std::string. -#if GTEST_HAS_GLOBAL_STRING -// ::string. -TEST(PrintStringTest, StringInGlobalNamespace) { - const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_STRING - // ::std::string. TEST(PrintStringTest, StringInStdNamespace) { const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; @@ -693,19 +678,7 @@ TEST(PrintStringTest, StringAmbiguousHex) { EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!"))); } -// Tests printing ::wstring and ::std::wstring. - -#if GTEST_HAS_GLOBAL_WSTRING -// ::wstring. -TEST(PrintWideStringTest, StringInGlobalNamespace) { - const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - +// Tests printing ::std::wstring. #if GTEST_HAS_STD_WSTRING // ::std::wstring. TEST(PrintWideStringTest, StringInStdNamespace) { @@ -816,7 +789,6 @@ TEST(PrintStlContainerTest, NonEmptyDeque) { EXPECT_EQ("{ 1, 3 }", Print(non_empty)); } -#if GTEST_HAS_UNORDERED_MAP_ TEST(PrintStlContainerTest, OneElementHashMap) { ::std::unordered_map<int, char> map1; @@ -836,9 +808,7 @@ TEST(PrintStlContainerTest, HashMultiMap) { << " where Print(map1) returns \"" << result << "\"."; } -#endif // GTEST_HAS_UNORDERED_MAP_ -#if GTEST_HAS_UNORDERED_SET_ TEST(PrintStlContainerTest, HashSet) { ::std::unordered_set<int> set1; @@ -875,7 +845,6 @@ TEST(PrintStlContainerTest, HashMultiSet) { EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); } -#endif // GTEST_HAS_UNORDERED_SET_ TEST(PrintStlContainerTest, List) { const std::string a[] = {"hello", "world"}; @@ -917,14 +886,12 @@ TEST(PrintStlContainerTest, MultiSet) { EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); } -#if GTEST_HAS_STD_FORWARD_LIST_ TEST(PrintStlContainerTest, SinglyLinkedList) { int a[] = { 9, 2, 8 }; const std::forward_list<int> ints(a, a + 3); EXPECT_EQ("{ 9, 2, 8 }", Print(ints)); } -#endif // GTEST_HAS_STD_FORWARD_LIST_ TEST(PrintStlContainerTest, Pair) { pair<const bool, int> p(true, 5); @@ -991,67 +958,6 @@ TEST(PrintStlContainerTest, ConstIterator) { EXPECT_EQ("1-byte object <00>", Print(it)); } -#if GTEST_HAS_TR1_TUPLE -// Tests printing ::std::tr1::tuples. - -// Tuples of various arities. -TEST(PrintTr1TupleTest, VariousSizes) { - ::std::tr1::tuple<> t0; - EXPECT_EQ("()", Print(t0)); - - ::std::tr1::tuple<int> t1(5); - EXPECT_EQ("(5)", Print(t1)); - - ::std::tr1::tuple<char, bool> t2('a', true); - EXPECT_EQ("('a' (97, 0x61), true)", Print(t2)); - - ::std::tr1::tuple<bool, int, int> t3(false, 2, 3); - EXPECT_EQ("(false, 2, 3)", Print(t3)); - - ::std::tr1::tuple<bool, int, int, int> t4(false, 2, 3, 4); - EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - - ::std::tr1::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - ::std::tr1::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - ::std::tr1::tuple<bool, int, int, int, bool, int, int> t7( - false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool> t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - ::std::tr1::tuple<bool, int, int, int, bool, int, int, bool, int> t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - - const char* const str = "8"; - // VC++ 2010's implementation of tuple of C++0x is deficient, requiring - // an explicit type cast of NULL to be used. - ::std::tr1::tuple<bool, char, short, testing::internal::Int32, // NOLINT - testing::internal::Int64, float, double, const char*, void*, - std::string> - t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT - ImplicitCast_<void*>(NULL), "10"); - EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", - Print(t10)); -} - -// Nested tuples. -TEST(PrintTr1TupleTest, NestedTuple) { - ::std::tr1::tuple< ::std::tr1::tuple<int, bool>, char> nested( - ::std::tr1::make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); -} - -#endif // GTEST_HAS_TR1_TUPLE - -#if GTEST_HAS_STD_TUPLE_ // Tests printing ::std::tuples. // Tuples of various arities. @@ -1071,32 +977,12 @@ TEST(PrintStdTupleTest, VariousSizes) { ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4); EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - ::std::tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - ::std::tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - ::std::tuple<bool, int, int, int, bool, int, int> t7( - false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - ::std::tuple<bool, int, int, int, bool, int, int, bool> t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - ::std::tuple<bool, int, int, int, bool, int, int, bool, int> t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - const char* const str = "8"; - // VC++ 2010's implementation of tuple of C++0x is deficient, requiring - // an explicit type cast of NULL to be used. ::std::tuple<bool, char, short, testing::internal::Int32, // NOLINT testing::internal::Int64, float, double, const char*, void*, std::string> t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str, // NOLINT - ImplicitCast_<void*>(NULL), "10"); + nullptr, "10"); EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + " pointing to \"8\", NULL, \"10\")", Print(t10)); @@ -1109,13 +995,27 @@ TEST(PrintStdTupleTest, NestedTuple) { EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested)); } -#endif // GTEST_LANG_CXX11 - -#if GTEST_LANG_CXX11 TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); } -#endif // GTEST_LANG_CXX11 + +TEST(PrintReferenceWrapper, Printable) { + int x = 5; + EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x))); + EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x))); +} + +TEST(PrintReferenceWrapper, Unprintable) { + ::foo::UnprintableInFoo up; + EXPECT_EQ( + "@" + PrintPointer(&up) + + " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", + Print(std::ref(up))); + EXPECT_EQ( + "@" + PrintPointer(&up) + + " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>", + Print(std::cref(up))); +} // Tests printing user-defined unprintable types. @@ -1321,21 +1221,6 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) { // Tests formatting a char pointer when it's compared to a string object. // In this case we want to print the char pointer as a C string. -#if GTEST_HAS_GLOBAL_STRING -// char pointer vs ::string -TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsString) { - const char* s = "hello \"world"; - EXPECT_STREQ("\"hello \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::string()).c_str()); - - // char* - char str[] = "hi\1"; - char* p = str; - EXPECT_STREQ("\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::string()).c_str()); -} -#endif - // char pointer vs std::string TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) { const char* s = "hello \"world"; @@ -1349,21 +1234,6 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) { FormatForComparisonFailureMessage(p, ::std::string()).c_str()); } -#if GTEST_HAS_GLOBAL_WSTRING -// wchar_t pointer vs ::wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsWString) { - const wchar_t* s = L"hi \"world"; - EXPECT_STREQ("L\"hi \\\"world\"", // The string content should be escaped. - FormatForComparisonFailureMessage(s, ::wstring()).c_str()); - - // wchar_t* - wchar_t str[] = L"hi\1"; - wchar_t* p = str; - EXPECT_STREQ("L\"hi\\x1\"", // The string content should be escaped. - FormatForComparisonFailureMessage(p, ::wstring()).c_str()); -} -#endif - #if GTEST_HAS_STD_WSTRING // wchar_t pointer vs std::wstring TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) { @@ -1386,7 +1256,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) { // char array vs pointer TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) { char str[] = "hi \"world\""; - char* p = NULL; + char* p = nullptr; EXPECT_EQ(PrintPointer(str), FormatForComparisonFailureMessage(str, p).c_str()); } @@ -1401,7 +1271,7 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) { // wchar_t array vs pointer TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) { wchar_t str[] = L"hi \"world\""; - wchar_t* p = NULL; + wchar_t* p = nullptr; EXPECT_EQ(PrintPointer(str), FormatForComparisonFailureMessage(str, p).c_str()); } @@ -1416,16 +1286,6 @@ TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) { // Tests formatting a char array when it's compared with a string object. // In this case we want to print the array as a C string. -#if GTEST_HAS_GLOBAL_STRING -// char array vs string -TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsString) { - const char str[] = "hi \"w\0rld\""; - EXPECT_STREQ("\"hi \\\"w\"", // The content should be escaped. - // Embedded NUL terminates the string. - FormatForComparisonFailureMessage(str, ::string()).c_str()); -} -#endif - // char array vs std::string TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) { const char str[] = "hi \"world\""; @@ -1433,15 +1293,6 @@ TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) { FormatForComparisonFailureMessage(str, ::std::string()).c_str()); } -#if GTEST_HAS_GLOBAL_WSTRING -// wchar_t array vs wstring -TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWString) { - const wchar_t str[] = L"hi \"world\""; - EXPECT_STREQ("L\"hi \\\"world\\\"\"", // The content should be escaped. - FormatForComparisonFailureMessage(str, ::wstring()).c_str()); -} -#endif - #if GTEST_HAS_STD_WSTRING // wchar_t array vs std::wstring TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) { @@ -1602,7 +1453,7 @@ TEST(UniversalTersePrintTest, WorksForCString) { UniversalTersePrint(s2, &ss2); EXPECT_EQ("\"abc\"", ss2.str()); - const char* s3 = NULL; + const char* s3 = nullptr; ::std::stringstream ss3; UniversalTersePrint(s3, &ss3); EXPECT_EQ("NULL", ss3.str()); @@ -1632,7 +1483,7 @@ TEST(UniversalPrintTest, WorksForCString) { UniversalPrint(s2, &ss2); EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str())); - const char* s3 = NULL; + const char* s3 = nullptr; ::std::stringstream ss3; UniversalPrint(s3, &ss3); EXPECT_EQ("NULL", ss3.str()); @@ -1650,42 +1501,6 @@ TEST(UniversalPrintTest, WorksForCharArray) { EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str()); } -#if GTEST_HAS_TR1_TUPLE - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsEmptyTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple()); - EXPECT_EQ(0u, result.size()); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsOneTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple(1)); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ("1", result[0]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTwoTuple) { - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::make_tuple(1, 'a')); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("'a' (97, 0x61)", result[1]); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTestWithTr1, PrintsTersely) { - const int n = 1; - Strings result = UniversalTersePrintTupleFieldsToStrings( - ::std::tr1::tuple<const int&, const char*>(n, "a")); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ("1", result[0]); - EXPECT_EQ("\"a\"", result[1]); -} - -#endif // GTEST_HAS_TR1_TUPLE - -#if GTEST_HAS_STD_TUPLE_ - TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) { Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple()); EXPECT_EQ(0u, result.size()); @@ -1715,8 +1530,6 @@ TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) { EXPECT_EQ("\"a\"", result[1]); } -#endif // GTEST_HAS_STD_TUPLE_ - #if GTEST_HAS_ABSL TEST(PrintOptionalTest, Basic) { @@ -1743,6 +1556,65 @@ TEST(PrintOneofTest, Basic) { PrintToString(Type(NonPrintable{}))); } #endif // GTEST_HAS_ABSL +namespace { +class string_ref; + +/** + * This is a synthetic pointer to a fixed size string. + */ +class string_ptr { + public: + string_ptr(const char* data, size_t size) : data_(data), size_(size) {} + + string_ptr& operator++() noexcept { + data_ += size_; + return *this; + } + + string_ref operator*() const noexcept; + + private: + const char* data_; + size_t size_; +}; + +/** + * This is a synthetic reference of a fixed size string. + */ +class string_ref { + public: + string_ref(const char* data, size_t size) : data_(data), size_(size) {} + + string_ptr operator&() const noexcept { return {data_, size_}; } // NOLINT + + bool operator==(const char* s) const noexcept { + if (size_ > 0 && data_[size_ - 1] != 0) { + return std::string(data_, size_) == std::string(s); + } else { + return std::string(data_) == std::string(s); + } + } + + private: + const char* data_; + size_t size_; +}; + +string_ref string_ptr::operator*() const noexcept { return {data_, size_}; } + +TEST(string_ref, compare) { + const char* s = "alex\0davidjohn\0"; + string_ptr ptr(s, 5); + EXPECT_EQ(*ptr, "alex"); + EXPECT_TRUE(*ptr == "alex"); + ++ptr; + EXPECT_EQ(*ptr, "david"); + EXPECT_TRUE(*ptr == "david"); + ++ptr; + EXPECT_EQ(*ptr, "john"); +} + +} // namespace } // namespace gtest_printers_test } // namespace testing diff --git a/googletest/test/googletest-shuffle-test_.cc b/googletest/test/googletest-shuffle-test_.cc index 1fe5f6aba2a5..c1fc106686e2 100644 --- a/googletest/test/googletest-shuffle-test_.cc +++ b/googletest/test/googletest-shuffle-test_.cc @@ -41,7 +41,6 @@ using ::testing::Test; using ::testing::TestEventListeners; using ::testing::TestInfo; using ::testing::UnitTest; -using ::testing::internal::scoped_ptr; // The test methods are empty, as the sole purpose of this program is // to print the test names before/after shuffling. @@ -77,12 +76,12 @@ TEST(DISABLED_D, DISABLED_B) {} // iteration with a "----" marker. class TestNamePrinter : public EmptyTestEventListener { public: - virtual void OnTestIterationStart(const UnitTest& /* unit_test */, - int /* iteration */) { + void OnTestIterationStart(const UnitTest& /* unit_test */, + int /* iteration */) override { printf("----\n"); } - virtual void OnTestStart(const TestInfo& test_info) { + void OnTestStart(const TestInfo& test_info) override { printf("%s.%s\n", test_info.test_case_name(), test_info.name()); } }; diff --git a/googletest/test/googletest-test-part-test.cc b/googletest/test/googletest-test-part-test.cc index cd2d6f9e858f..44cf7ca044b8 100644 --- a/googletest/test/googletest-test-part-test.cc +++ b/googletest/test/googletest-test-part-test.cc @@ -46,9 +46,10 @@ class TestPartResultTest : public Test { TestPartResultTest() : r1_(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"), r2_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure!"), - r3_(TestPartResult::kFatalFailure, NULL, -1, "Failure!") {} + r3_(TestPartResult::kFatalFailure, nullptr, -1, "Failure!"), + r4_(TestPartResult::kSkip, "foo/bar.cc", 2, "Skipped!") {} - TestPartResult r1_, r2_, r3_; + TestPartResult r1_, r2_, r3_, r4_; }; @@ -79,6 +80,7 @@ TEST_F(TestPartResultTest, ResultAccessorsWork) { EXPECT_FALSE(success.failed()); EXPECT_FALSE(success.nonfatally_failed()); EXPECT_FALSE(success.fatally_failed()); + EXPECT_FALSE(success.skipped()); const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure, "file.cc", @@ -88,6 +90,7 @@ TEST_F(TestPartResultTest, ResultAccessorsWork) { EXPECT_TRUE(nonfatal_failure.failed()); EXPECT_TRUE(nonfatal_failure.nonfatally_failed()); EXPECT_FALSE(nonfatal_failure.fatally_failed()); + EXPECT_FALSE(nonfatal_failure.skipped()); const TestPartResult fatal_failure(TestPartResult::kFatalFailure, "file.cc", @@ -97,6 +100,14 @@ TEST_F(TestPartResultTest, ResultAccessorsWork) { EXPECT_TRUE(fatal_failure.failed()); EXPECT_FALSE(fatal_failure.nonfatally_failed()); EXPECT_TRUE(fatal_failure.fatally_failed()); + EXPECT_FALSE(fatal_failure.skipped()); + + const TestPartResult skip(TestPartResult::kSkip, "file.cc", 42, "message"); + EXPECT_FALSE(skip.passed()); + EXPECT_FALSE(skip.failed()); + EXPECT_FALSE(skip.nonfatally_failed()); + EXPECT_FALSE(skip.fatally_failed()); + EXPECT_TRUE(skip.skipped()); } // Tests TestPartResult::type(). @@ -104,23 +115,27 @@ TEST_F(TestPartResultTest, type) { EXPECT_EQ(TestPartResult::kSuccess, r1_.type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type()); EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type()); + EXPECT_EQ(TestPartResult::kSkip, r4_.type()); } // Tests TestPartResult::file_name(). TEST_F(TestPartResultTest, file_name) { EXPECT_STREQ("foo/bar.cc", r1_.file_name()); - EXPECT_STREQ(NULL, r3_.file_name()); + EXPECT_STREQ(nullptr, r3_.file_name()); + EXPECT_STREQ("foo/bar.cc", r4_.file_name()); } // Tests TestPartResult::line_number(). TEST_F(TestPartResultTest, line_number) { EXPECT_EQ(10, r1_.line_number()); EXPECT_EQ(-1, r2_.line_number()); + EXPECT_EQ(2, r4_.line_number()); } // Tests TestPartResult::message(). TEST_F(TestPartResultTest, message) { EXPECT_STREQ("Success!", r1_.message()); + EXPECT_STREQ("Skipped!", r4_.message()); } // Tests TestPartResult::passed(). @@ -128,6 +143,7 @@ TEST_F(TestPartResultTest, Passed) { EXPECT_TRUE(r1_.passed()); EXPECT_FALSE(r2_.passed()); EXPECT_FALSE(r3_.passed()); + EXPECT_FALSE(r4_.passed()); } // Tests TestPartResult::failed(). @@ -135,6 +151,15 @@ TEST_F(TestPartResultTest, Failed) { EXPECT_FALSE(r1_.failed()); EXPECT_TRUE(r2_.failed()); EXPECT_TRUE(r3_.failed()); + EXPECT_FALSE(r4_.failed()); +} + +// Tests TestPartResult::failed(). +TEST_F(TestPartResultTest, Skipped) { + EXPECT_FALSE(r1_.skipped()); + EXPECT_FALSE(r2_.skipped()); + EXPECT_FALSE(r3_.skipped()); + EXPECT_TRUE(r4_.skipped()); } // Tests TestPartResult::fatally_failed(). @@ -142,6 +167,7 @@ TEST_F(TestPartResultTest, FatallyFailed) { EXPECT_FALSE(r1_.fatally_failed()); EXPECT_FALSE(r2_.fatally_failed()); EXPECT_TRUE(r3_.fatally_failed()); + EXPECT_FALSE(r4_.fatally_failed()); } // Tests TestPartResult::nonfatally_failed(). @@ -149,6 +175,7 @@ TEST_F(TestPartResultTest, NonfatallyFailed) { EXPECT_FALSE(r1_.nonfatally_failed()); EXPECT_TRUE(r2_.nonfatally_failed()); EXPECT_FALSE(r3_.nonfatally_failed()); + EXPECT_FALSE(r4_.nonfatally_failed()); } // Tests the TestPartResultArray class. @@ -200,6 +227,4 @@ TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) { EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), ""); } -// FIXME: Add a test for the class HasNewFatalFailureHelper. - } // namespace diff --git a/googletest/test/googletest-test2_test.cc b/googletest/test/googletest-test2_test.cc index c2f98dc7d1c3..2e425daebab6 100644 --- a/googletest/test/googletest-test2_test.cc +++ b/googletest/test/googletest-test2_test.cc @@ -46,16 +46,16 @@ ParamGenerator<int> extern_gen_2 = Values(33); // and instantiated in another. The test is defined in // googletest-param-test-test.cc and ExternalInstantiationTest fixture class is // defined in gtest-param-test_test.h. -INSTANTIATE_TEST_CASE_P(MultiplesOf33, - ExternalInstantiationTest, - Values(33, 66)); +INSTANTIATE_TEST_SUITE_P(MultiplesOf33, + ExternalInstantiationTest, + Values(33, 66)); // Tests that a parameterized test case can be instantiated // in multiple translation units. Another instantiation is defined // in googletest-param-test-test.cc and -// InstantiationInMultipleTranslaionUnitsTest fixture is defined in +// InstantiationInMultipleTranslationUnitsTest fixture is defined in // gtest-param-test_test.h -INSTANTIATE_TEST_CASE_P(Sequence2, - InstantiationInMultipleTranslaionUnitsTest, - Values(42*3, 42*4, 42*5)); +INSTANTIATE_TEST_SUITE_P(Sequence2, + InstantiationInMultipleTranslationUnitsTest, + Values(42*3, 42*4, 42*5)); diff --git a/googletest/test/googletest-throw-on-failure-test.py b/googletest/test/googletest-throw-on-failure-test.py index 46cb9f6da31d..ea627c479d5b 100755 --- a/googletest/test/googletest-throw-on-failure-test.py +++ b/googletest/test/googletest-throw-on-failure-test.py @@ -68,13 +68,12 @@ def SetEnvVar(env_var, value): def Run(command): """Runs a command; returns True/False if its exit code is/isn't 0.""" - print 'Running "%s". . .' % ' '.join(command) + print('Running "%s". . .' % ' '.join(command)) p = gtest_test_utils.Subprocess(command) return p.exited and p.exit_code == 0 -# The tests. FIXME: refactor the class to share common -# logic with code in googletest-break-on-failure-unittest.py. +# The tests. class ThrowOnFailureTest(gtest_test_utils.TestCase): """Tests the throw-on-failure mode.""" @@ -87,7 +86,7 @@ class ThrowOnFailureTest(gtest_test_utils.TestCase): variable; None if the variable should be unset. flag_value: value of the --gtest_break_on_failure flag; None if the flag should not be present. - should_fail: True iff the program is expected to fail. + should_fail: True if and only if the program is expected to fail. """ SetEnvVar(THROW_ON_FAILURE, env_var_value) diff --git a/googletest/test/googletest-throw-on-failure-test_.cc b/googletest/test/googletest-throw-on-failure-test_.cc index f9a2c6448a29..83bb914c7e47 100644 --- a/googletest/test/googletest-throw-on-failure-test_.cc +++ b/googletest/test/googletest-throw-on-failure-test_.cc @@ -45,7 +45,7 @@ // ones. void TerminateHandler() { fprintf(stderr, "%s\n", "Unhandled C++ exception terminating the program."); - fflush(NULL); + fflush(nullptr); exit(1); } diff --git a/googletest/test/googletest-tuple-test.cc b/googletest/test/googletest-tuple-test.cc deleted file mode 100644 index dd82c160f177..000000000000 --- a/googletest/test/googletest-tuple-test.cc +++ /dev/null @@ -1,319 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -#include "gtest/internal/gtest-tuple.h" -#include <utility> -#include "gtest/gtest.h" - -namespace { - -using ::std::tr1::get; -using ::std::tr1::make_tuple; -using ::std::tr1::tuple; -using ::std::tr1::tuple_element; -using ::std::tr1::tuple_size; -using ::testing::StaticAssertTypeEq; - -// Tests that tuple_element<K, tuple<T0, T1, ..., TN> >::type returns TK. -TEST(tuple_element_Test, ReturnsElementType) { - StaticAssertTypeEq<int, tuple_element<0, tuple<int, char> >::type>(); - StaticAssertTypeEq<int&, tuple_element<1, tuple<double, int&> >::type>(); - StaticAssertTypeEq<bool, tuple_element<2, tuple<double, int, bool> >::type>(); -} - -// Tests that tuple_size<T>::value gives the number of fields in tuple -// type T. -TEST(tuple_size_Test, ReturnsNumberOfFields) { - EXPECT_EQ(0, +tuple_size<tuple<> >::value); - EXPECT_EQ(1, +tuple_size<tuple<void*> >::value); - EXPECT_EQ(1, +tuple_size<tuple<char> >::value); - EXPECT_EQ(1, +(tuple_size<tuple<tuple<int, double> > >::value)); - EXPECT_EQ(2, +(tuple_size<tuple<int&, const char> >::value)); - EXPECT_EQ(3, +(tuple_size<tuple<char*, void, const bool&> >::value)); -} - -// Tests comparing a tuple with itself. -TEST(ComparisonTest, ComparesWithSelf) { - const tuple<int, char, bool> a(5, 'a', false); - - EXPECT_TRUE(a == a); - EXPECT_FALSE(a != a); -} - -// Tests comparing two tuples with the same value. -TEST(ComparisonTest, ComparesEqualTuples) { - const tuple<int, bool> a(5, true), b(5, true); - - EXPECT_TRUE(a == b); - EXPECT_FALSE(a != b); -} - -// Tests comparing two different tuples that have no reference fields. -TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) { - typedef tuple<const int, char> FooTuple; - - const FooTuple a(0, 'x'); - const FooTuple b(1, 'a'); - - EXPECT_TRUE(a != b); - EXPECT_FALSE(a == b); - - const FooTuple c(1, 'b'); - - EXPECT_TRUE(b != c); - EXPECT_FALSE(b == c); -} - -// Tests comparing two different tuples that have reference fields. -TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) { - typedef tuple<int&, const char&> FooTuple; - - int i = 5; - const char ch = 'a'; - const FooTuple a(i, ch); - - int j = 6; - const FooTuple b(j, ch); - - EXPECT_TRUE(a != b); - EXPECT_FALSE(a == b); - - j = 5; - const char ch2 = 'b'; - const FooTuple c(j, ch2); - - EXPECT_TRUE(b != c); - EXPECT_FALSE(b == c); -} - -// Tests that a tuple field with a reference type is an alias of the -// variable it's supposed to reference. -TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) { - int n = 0; - tuple<bool, int&> t(true, n); - - n = 1; - EXPECT_EQ(n, get<1>(t)) - << "Changing a underlying variable should update the reference field."; - - // Makes sure that the implementation doesn't do anything funny with - // the & operator for the return type of get<>(). - EXPECT_EQ(&n, &(get<1>(t))) - << "The address of a reference field should equal the address of " - << "the underlying variable."; - - get<1>(t) = 2; - EXPECT_EQ(2, n) - << "Changing a reference field should update the underlying variable."; -} - -// Tests that tuple's default constructor default initializes each field. -// This test needs to compile without generating warnings. -TEST(TupleConstructorTest, DefaultConstructorDefaultInitializesEachField) { - // The TR1 report requires that tuple's default constructor default - // initializes each field, even if it's a primitive type. If the - // implementation forgets to do this, this test will catch it by - // generating warnings about using uninitialized variables (assuming - // a decent compiler). - - tuple<> empty; - - tuple<int> a1, b1; - b1 = a1; - EXPECT_EQ(0, get<0>(b1)); - - tuple<int, double> a2, b2; - b2 = a2; - EXPECT_EQ(0, get<0>(b2)); - EXPECT_EQ(0.0, get<1>(b2)); - - tuple<double, char, bool*> a3, b3; - b3 = a3; - EXPECT_EQ(0.0, get<0>(b3)); - EXPECT_EQ('\0', get<1>(b3)); - EXPECT_TRUE(get<2>(b3) == NULL); - - tuple<int, int, int, int, int, int, int, int, int, int> a10, b10; - b10 = a10; - EXPECT_EQ(0, get<0>(b10)); - EXPECT_EQ(0, get<1>(b10)); - EXPECT_EQ(0, get<2>(b10)); - EXPECT_EQ(0, get<3>(b10)); - EXPECT_EQ(0, get<4>(b10)); - EXPECT_EQ(0, get<5>(b10)); - EXPECT_EQ(0, get<6>(b10)); - EXPECT_EQ(0, get<7>(b10)); - EXPECT_EQ(0, get<8>(b10)); - EXPECT_EQ(0, get<9>(b10)); -} - -// Tests constructing a tuple from its fields. -TEST(TupleConstructorTest, ConstructsFromFields) { - int n = 1; - // Reference field. - tuple<int&> a(n); - EXPECT_EQ(&n, &(get<0>(a))); - - // Non-reference fields. - tuple<int, char> b(5, 'a'); - EXPECT_EQ(5, get<0>(b)); - EXPECT_EQ('a', get<1>(b)); - - // Const reference field. - const int m = 2; - tuple<bool, const int&> c(true, m); - EXPECT_TRUE(get<0>(c)); - EXPECT_EQ(&m, &(get<1>(c))); -} - -// Tests tuple's copy constructor. -TEST(TupleConstructorTest, CopyConstructor) { - tuple<double, bool> a(0.0, true); - tuple<double, bool> b(a); - - EXPECT_DOUBLE_EQ(0.0, get<0>(b)); - EXPECT_TRUE(get<1>(b)); -} - -// Tests constructing a tuple from another tuple that has a compatible -// but different type. -TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) { - tuple<int, int, char> a(0, 1, 'a'); - tuple<double, long, int> b(a); - - EXPECT_DOUBLE_EQ(0.0, get<0>(b)); - EXPECT_EQ(1, get<1>(b)); - EXPECT_EQ('a', get<2>(b)); -} - -// Tests constructing a 2-tuple from an std::pair. -TEST(TupleConstructorTest, ConstructsFromPair) { - ::std::pair<int, char> a(1, 'a'); - tuple<int, char> b(a); - tuple<int, const char&> c(a); -} - -// Tests assigning a tuple to another tuple with the same type. -TEST(TupleAssignmentTest, AssignsToSameTupleType) { - const tuple<int, long> a(5, 7L); - tuple<int, long> b; - b = a; - EXPECT_EQ(5, get<0>(b)); - EXPECT_EQ(7L, get<1>(b)); -} - -// Tests assigning a tuple to another tuple with a different but -// compatible type. -TEST(TupleAssignmentTest, AssignsToDifferentTupleType) { - const tuple<int, long, bool> a(1, 7L, true); - tuple<long, int, bool> b; - b = a; - EXPECT_EQ(1L, get<0>(b)); - EXPECT_EQ(7, get<1>(b)); - EXPECT_TRUE(get<2>(b)); -} - -// Tests assigning an std::pair to a 2-tuple. -TEST(TupleAssignmentTest, AssignsFromPair) { - const ::std::pair<int, bool> a(5, true); - tuple<int, bool> b; - b = a; - EXPECT_EQ(5, get<0>(b)); - EXPECT_TRUE(get<1>(b)); - - tuple<long, bool> c; - c = a; - EXPECT_EQ(5L, get<0>(c)); - EXPECT_TRUE(get<1>(c)); -} - -// A fixture for testing big tuples. -class BigTupleTest : public testing::Test { - protected: - typedef tuple<int, int, int, int, int, int, int, int, int, int> BigTuple; - - BigTupleTest() : - a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2), - b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {} - - BigTuple a_, b_; -}; - -// Tests constructing big tuples. -TEST_F(BigTupleTest, Construction) { - BigTuple a; - BigTuple b(b_); -} - -// Tests that get<N>(t) returns the N-th (0-based) field of tuple t. -TEST_F(BigTupleTest, get) { - EXPECT_EQ(1, get<0>(a_)); - EXPECT_EQ(2, get<9>(a_)); - - // Tests that get() works on a const tuple too. - const BigTuple a(a_); - EXPECT_EQ(1, get<0>(a)); - EXPECT_EQ(2, get<9>(a)); -} - -// Tests comparing big tuples. -TEST_F(BigTupleTest, Comparisons) { - EXPECT_TRUE(a_ == a_); - EXPECT_FALSE(a_ != a_); - - EXPECT_TRUE(a_ != b_); - EXPECT_FALSE(a_ == b_); -} - -TEST(MakeTupleTest, WorksForScalarTypes) { - tuple<bool, int> a; - a = make_tuple(true, 5); - EXPECT_TRUE(get<0>(a)); - EXPECT_EQ(5, get<1>(a)); - - tuple<char, int, long> b; - b = make_tuple('a', 'b', 5); - EXPECT_EQ('a', get<0>(b)); - EXPECT_EQ('b', get<1>(b)); - EXPECT_EQ(5, get<2>(b)); -} - -TEST(MakeTupleTest, WorksForPointers) { - int a[] = { 1, 2, 3, 4 }; - const char* const str = "hi"; - int* const p = a; - - tuple<const char*, int*> t; - t = make_tuple(str, p); - EXPECT_EQ(str, get<0>(t)); - EXPECT_EQ(p, get<1>(t)); -} - -} // namespace diff --git a/googletest/test/googletest-uninitialized-test.py b/googletest/test/googletest-uninitialized-test.py index 5b7d1e74f67f..69595a0ddede 100755 --- a/googletest/test/googletest-uninitialized-test.py +++ b/googletest/test/googletest-uninitialized-test.py @@ -43,8 +43,8 @@ def Assert(condition): def AssertEq(expected, actual): if expected != actual: - print 'Expected: %s' % (expected,) - print ' Actual: %s' % (actual,) + print('Expected: %s' % (expected,)) + print(' Actual: %s' % (actual,)) raise AssertionError diff --git a/googletest/test/gtest-typed-test2_test.cc b/googletest/test/gtest-typed-test2_test.cc index ed96421c67ca..70001604ca06 100644 --- a/googletest/test/gtest-typed-test2_test.cc +++ b/googletest/test/gtest-typed-test2_test.cc @@ -38,7 +38,7 @@ // Tests that the same type-parameterized test case can be // instantiated in different translation units linked together. // (ContainerTest is also instantiated in gtest-typed-test_test.cc.) -INSTANTIATE_TYPED_TEST_CASE_P(Vector, ContainerTest, - testing::Types<std::vector<int> >); +INSTANTIATE_TYPED_TEST_SUITE_P(Vector, ContainerTest, + testing::Types<std::vector<int> >); #endif // GTEST_HAS_TYPED_TEST_P diff --git a/googletest/test/gtest-typed-test_test.cc b/googletest/test/gtest-typed-test_test.cc index 4e398697d6d8..5411832ab269 100644 --- a/googletest/test/gtest-typed-test_test.cc +++ b/googletest/test/gtest-typed-test_test.cc @@ -31,6 +31,7 @@ #include "test/gtest-typed-test_test.h" #include <set> +#include <type_traits> #include <vector> #include "gtest/gtest.h" @@ -41,21 +42,21 @@ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */) using testing::Test; -// Used for testing that SetUpTestCase()/TearDownTestCase(), fixture +// Used for testing that SetUpTestSuite()/TearDownTestSuite(), fixture // ctor/dtor, and SetUp()/TearDown() work correctly in typed tests and // type-parameterized test. template <typename T> class CommonTest : public Test { - // For some technical reason, SetUpTestCase() and TearDownTestCase() + // For some technical reason, SetUpTestSuite() and TearDownTestSuite() // must be public. public: - static void SetUpTestCase() { + static void SetUpTestSuite() { shared_ = new T(5); } - static void TearDownTestCase() { + static void TearDownTestSuite() { delete shared_; - shared_ = NULL; + shared_ = nullptr; } // This 'protected:' is optional. There's no harm in making all @@ -68,14 +69,14 @@ class CommonTest : public Test { CommonTest() : value_(1) {} - virtual ~CommonTest() { EXPECT_EQ(3, value_); } + ~CommonTest() override { EXPECT_EQ(3, value_); } - virtual void SetUp() { + void SetUp() override { EXPECT_EQ(1, value_); value_++; } - virtual void TearDown() { + void TearDown() override { EXPECT_EQ(2, value_); value_++; } @@ -85,18 +86,18 @@ class CommonTest : public Test { }; template <typename T> -T* CommonTest<T>::shared_ = NULL; +T* CommonTest<T>::shared_ = nullptr; // This #ifdef block tests typed tests. #if GTEST_HAS_TYPED_TEST using testing::Types; -// Tests that SetUpTestCase()/TearDownTestCase(), fixture ctor/dtor, +// Tests that SetUpTestSuite()/TearDownTestSuite(), fixture ctor/dtor, // and SetUp()/TearDown() work correctly in typed tests typedef Types<char, int> TwoTypes; -TYPED_TEST_CASE(CommonTest, TwoTypes); +TYPED_TEST_SUITE(CommonTest, TwoTypes); TYPED_TEST(CommonTest, ValuesAreCorrect) { // Static members of the fixture class template can be visited via @@ -121,32 +122,32 @@ TYPED_TEST(CommonTest, ValuesAreCorrect) { TYPED_TEST(CommonTest, ValuesAreStillCorrect) { // Static members of the fixture class template can also be visited // via 'this'. - ASSERT_TRUE(this->shared_ != NULL); + ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); // TypeParam can be used to refer to the type parameter. EXPECT_EQ(static_cast<TypeParam>(2), this->value_); } -// Tests that multiple TYPED_TEST_CASE's can be defined in the same +// Tests that multiple TYPED_TEST_SUITE's can be defined in the same // translation unit. template <typename T> class TypedTest1 : public Test { }; -// Verifies that the second argument of TYPED_TEST_CASE can be a +// Verifies that the second argument of TYPED_TEST_SUITE can be a // single type. -TYPED_TEST_CASE(TypedTest1, int); +TYPED_TEST_SUITE(TypedTest1, int); TYPED_TEST(TypedTest1, A) {} template <typename T> class TypedTest2 : public Test { }; -// Verifies that the second argument of TYPED_TEST_CASE can be a +// Verifies that the second argument of TYPED_TEST_SUITE can be a // Types<...> type list. -TYPED_TEST_CASE(TypedTest2, Types<int>); +TYPED_TEST_SUITE(TypedTest2, Types<int>); // This also verifies that tests from different typed test cases can // share the same name. @@ -161,7 +162,7 @@ class NumericTest : public Test { }; typedef Types<int, long> NumericTypes; -TYPED_TEST_CASE(NumericTest, NumericTypes); +TYPED_TEST_SUITE(NumericTest, NumericTypes); TYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); @@ -177,25 +178,25 @@ class TypedTestNames { public: template <typename T> static std::string GetName(int i) { - if (testing::internal::IsSame<T, char>::value) { + if (std::is_same<T, char>::value) { return std::string("char") + ::testing::PrintToString(i); } - if (testing::internal::IsSame<T, int>::value) { + if (std::is_same<T, int>::value) { return std::string("int") + ::testing::PrintToString(i); } } }; -TYPED_TEST_CASE(TypedTestWithNames, TwoTypes, TypedTestNames); +TYPED_TEST_SUITE(TypedTestWithNames, TwoTypes, TypedTestNames); -TYPED_TEST(TypedTestWithNames, TestCaseName) { - if (testing::internal::IsSame<TypeParam, char>::value) { +TYPED_TEST(TypedTestWithNames, TestSuiteName) { + if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_case_name(), "TypedTestWithNames/char0"); } - if (testing::internal::IsSame<TypeParam, int>::value) { + if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_case_name(), @@ -209,22 +210,22 @@ TYPED_TEST(TypedTestWithNames, TestCaseName) { #if GTEST_HAS_TYPED_TEST_P using testing::Types; -using testing::internal::TypedTestCasePState; +using testing::internal::TypedTestSuitePState; -// Tests TypedTestCasePState. +// Tests TypedTestSuitePState. -class TypedTestCasePStateTest : public Test { +class TypedTestSuitePStateTest : public Test { protected: - virtual void SetUp() { + void SetUp() override { state_.AddTestName("foo.cc", 0, "FooTest", "A"); state_.AddTestName("foo.cc", 0, "FooTest", "B"); state_.AddTestName("foo.cc", 0, "FooTest", "C"); } - TypedTestCasePState state_; + TypedTestSuitePState state_; }; -TEST_F(TypedTestCasePStateTest, SucceedsForMatchingList) { +TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) { const char* tests = "A, B, C"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("foo.cc", 1, tests)); @@ -232,27 +233,27 @@ TEST_F(TypedTestCasePStateTest, SucceedsForMatchingList) { // Makes sure that the order of the tests and spaces around the names // don't matter. -TEST_F(TypedTestCasePStateTest, IgnoresOrderAndSpaces) { +TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) { const char* tests = "A,C, B"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("foo.cc", 1, tests)); } -typedef TypedTestCasePStateTest TypedTestCasePStateDeathTest; +using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest; -TEST_F(TypedTestCasePStateDeathTest, DetectsDuplicates) { +TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, A, C"), "foo\\.cc.1.?: Test A is listed more than once\\."); } -TEST_F(TypedTestCasePStateDeathTest, DetectsExtraTest) { +TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C, D"), - "foo\\.cc.1.?: No test named D can be found in this test case\\."); + "foo\\.cc.1.?: No test named D can be found in this test suite\\."); } -TEST_F(TypedTestCasePStateDeathTest, DetectsMissedTest) { +TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("foo.cc", 1, "A, C"), "foo\\.cc.1.?: You forgot to list test B\\."); @@ -260,22 +261,22 @@ TEST_F(TypedTestCasePStateDeathTest, DetectsMissedTest) { // Tests that defining a test for a parameterized test case generates // a run-time error if the test case has been registered. -TEST_F(TypedTestCasePStateDeathTest, DetectsTestAfterRegistration) { +TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C"); EXPECT_DEATH_IF_SUPPORTED( state_.AddTestName("foo.cc", 2, "FooTest", "D"), - "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_CASE_P" + "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P" "\\(FooTest, \\.\\.\\.\\)\\."); } -// Tests that SetUpTestCase()/TearDownTestCase(), fixture ctor/dtor, +// Tests that SetUpTestSuite()/TearDownTestSuite(), fixture ctor/dtor, // and SetUp()/TearDown() work correctly in type-parameterized tests. template <typename T> class DerivedTest : public CommonTest<T> { }; -TYPED_TEST_CASE_P(DerivedTest); +TYPED_TEST_SUITE_P(DerivedTest); TYPED_TEST_P(DerivedTest, ValuesAreCorrect) { // Static members of the fixture class template can be visited via @@ -292,32 +293,32 @@ TYPED_TEST_P(DerivedTest, ValuesAreCorrect) { TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) { // Static members of the fixture class template can also be visited // via 'this'. - ASSERT_TRUE(this->shared_ != NULL); + ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); EXPECT_EQ(2, this->value_); } -REGISTER_TYPED_TEST_CASE_P(DerivedTest, +REGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect, ValuesAreStillCorrect); typedef Types<short, long> MyTwoTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, DerivedTest, MyTwoTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes); // Tests that custom names work with type parametrized tests. We reuse the // TwoTypes from above here. template <typename T> class TypeParametrizedTestWithNames : public Test {}; -TYPED_TEST_CASE_P(TypeParametrizedTestWithNames); +TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames); -TYPED_TEST_P(TypeParametrizedTestWithNames, TestCaseName) { - if (testing::internal::IsSame<TypeParam, char>::value) { +TYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) { + if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_case_name(), "CustomName/TypeParametrizedTestWithNames/parChar0"); } - if (testing::internal::IsSame<TypeParam, int>::value) { + if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_case_name(), @@ -325,77 +326,77 @@ TYPED_TEST_P(TypeParametrizedTestWithNames, TestCaseName) { } } -REGISTER_TYPED_TEST_CASE_P(TypeParametrizedTestWithNames, TestCaseName); +REGISTER_TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames, TestSuiteName); class TypeParametrizedTestNames { public: template <typename T> static std::string GetName(int i) { - if (testing::internal::IsSame<T, char>::value) { + if (std::is_same<T, char>::value) { return std::string("parChar") + ::testing::PrintToString(i); } - if (testing::internal::IsSame<T, int>::value) { + if (std::is_same<T, int>::value) { return std::string("parInt") + ::testing::PrintToString(i); } } }; -INSTANTIATE_TYPED_TEST_CASE_P(CustomName, TypeParametrizedTestWithNames, +INSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames, TwoTypes, TypeParametrizedTestNames); -// Tests that multiple TYPED_TEST_CASE_P's can be defined in the same +// Tests that multiple TYPED_TEST_SUITE_P's can be defined in the same // translation unit. template <typename T> class TypedTestP1 : public Test { }; -TYPED_TEST_CASE_P(TypedTestP1); +TYPED_TEST_SUITE_P(TypedTestP1); -// For testing that the code between TYPED_TEST_CASE_P() and +// For testing that the code between TYPED_TEST_SUITE_P() and // TYPED_TEST_P() is not enclosed in a namespace. -typedef int IntAfterTypedTestCaseP; +using IntAfterTypedTestSuiteP = int; TYPED_TEST_P(TypedTestP1, A) {} TYPED_TEST_P(TypedTestP1, B) {} // For testing that the code between TYPED_TEST_P() and -// REGISTER_TYPED_TEST_CASE_P() is not enclosed in a namespace. -typedef int IntBeforeRegisterTypedTestCaseP; +// REGISTER_TYPED_TEST_SUITE_P() is not enclosed in a namespace. +using IntBeforeRegisterTypedTestSuiteP = int; -REGISTER_TYPED_TEST_CASE_P(TypedTestP1, A, B); +REGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B); template <typename T> class TypedTestP2 : public Test { }; -TYPED_TEST_CASE_P(TypedTestP2); +TYPED_TEST_SUITE_P(TypedTestP2); // This also verifies that tests from different type-parameterized // test cases can share the same name. TYPED_TEST_P(TypedTestP2, A) {} -REGISTER_TYPED_TEST_CASE_P(TypedTestP2, A); +REGISTER_TYPED_TEST_SUITE_P(TypedTestP2, A); -// Verifies that the code between TYPED_TEST_CASE_P() and -// REGISTER_TYPED_TEST_CASE_P() is not enclosed in a namespace. -IntAfterTypedTestCaseP after = 0; -IntBeforeRegisterTypedTestCaseP before = 0; +// Verifies that the code between TYPED_TEST_SUITE_P() and +// REGISTER_TYPED_TEST_SUITE_P() is not enclosed in a namespace. +IntAfterTypedTestSuiteP after = 0; +IntBeforeRegisterTypedTestSuiteP before = 0; -// Verifies that the last argument of INSTANTIATE_TYPED_TEST_CASE_P() +// Verifies that the last argument of INSTANTIATE_TYPED_TEST_SUITE_P() // can be either a single type or a Types<...> type list. -INSTANTIATE_TYPED_TEST_CASE_P(Int, TypedTestP1, int); -INSTANTIATE_TYPED_TEST_CASE_P(Int, TypedTestP2, Types<int>); +INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP1, int); +INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP2, Types<int>); // Tests that the same type-parameterized test case can be // instantiated more than once in the same translation unit. -INSTANTIATE_TYPED_TEST_CASE_P(Double, TypedTestP2, Types<double>); +INSTANTIATE_TYPED_TEST_SUITE_P(Double, TypedTestP2, Types<double>); // Tests that the same type-parameterized test case can be // instantiated in different translation units linked together. // (ContainerTest is also instantiated in gtest-typed-test_test.cc.) typedef Types<std::vector<double>, std::set<char> > MyContainers; -INSTANTIATE_TYPED_TEST_CASE_P(My, ContainerTest, MyContainers); +INSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers); // Tests that a type-parameterized test case can be defined and // instantiated in a namespace. @@ -406,7 +407,7 @@ template <typename T> class NumericTest : public Test { }; -TYPED_TEST_CASE_P(NumericTest); +TYPED_TEST_SUITE_P(NumericTest); TYPED_TEST_P(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); @@ -416,29 +417,29 @@ TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) { EXPECT_LT(TypeParam(0), TypeParam(1)); } -REGISTER_TYPED_TEST_CASE_P(NumericTest, +REGISTER_TYPED_TEST_SUITE_P(NumericTest, DefaultIsZero, ZeroIsLessThanOne); typedef Types<int, double> NumericTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, NumericTest, NumericTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes); static const char* GetTestName() { return testing::UnitTest::GetInstance()->current_test_info()->name(); } // Test the stripping of space from test names template <typename T> class TrimmedTest : public Test { }; -TYPED_TEST_CASE_P(TrimmedTest); +TYPED_TEST_SUITE_P(TrimmedTest); TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); } -REGISTER_TYPED_TEST_CASE_P( +REGISTER_TYPED_TEST_SUITE_P( TrimmedTest, Test1, Test2,Test3 , Test4 ,Test5 ); // NOLINT template <typename T1, typename T2> struct MyPair {}; // Be sure to try a type with a comma in its name just in case it matters. typedef Types<int, double, MyPair<int, int> > TrimTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, TrimmedTest, TrimTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes); } // namespace library2 diff --git a/googletest/test/gtest-typed-test_test.h b/googletest/test/gtest-typed-test_test.h index 2cce67c825a6..23137b7ef798 100644 --- a/googletest/test/gtest-typed-test_test.h +++ b/googletest/test/gtest-typed-test_test.h @@ -46,7 +46,7 @@ template <typename T> class ContainerTest : public Test { }; -TYPED_TEST_CASE_P(ContainerTest); +TYPED_TEST_SUITE_P(ContainerTest); TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { TypeParam container; @@ -57,8 +57,8 @@ TYPED_TEST_P(ContainerTest, InitialSizeIsZero) { EXPECT_EQ(0U, container.size()); } -REGISTER_TYPED_TEST_CASE_P(ContainerTest, - CanBeDefaultConstructed, InitialSizeIsZero); +REGISTER_TYPED_TEST_SUITE_P(ContainerTest, + CanBeDefaultConstructed, InitialSizeIsZero); #endif // GTEST_HAS_TYPED_TEST_P diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc index f3ea03a596d0..480a41fb42ee 100644 --- a/googletest/test/gtest-unittest-api_test.cc +++ b/googletest/test/gtest-unittest-api_test.cc @@ -51,59 +51,59 @@ struct LessByName { class UnitTestHelper { public: - // Returns the array of pointers to all test cases sorted by the test case + // Returns the array of pointers to all test suites sorted by the test suite // name. The caller is responsible for deleting the array. - static TestCase const** GetSortedTestCases() { + static TestSuite const** GetSortedTestSuites() { UnitTest& unit_test = *UnitTest::GetInstance(); - TestCase const** const test_cases = - new const TestCase*[unit_test.total_test_case_count()]; + auto const** const test_suites = + new const TestSuite*[unit_test.total_test_suite_count()]; - for (int i = 0; i < unit_test.total_test_case_count(); ++i) - test_cases[i] = unit_test.GetTestCase(i); + for (int i = 0; i < unit_test.total_test_suite_count(); ++i) + test_suites[i] = unit_test.GetTestSuite(i); - std::sort(test_cases, - test_cases + unit_test.total_test_case_count(), - LessByName<TestCase>()); - return test_cases; + std::sort(test_suites, + test_suites + unit_test.total_test_suite_count(), + LessByName<TestSuite>()); + return test_suites; } - // Returns the test case by its name. The caller doesn't own the returned + // Returns the test suite by its name. The caller doesn't own the returned // pointer. - static const TestCase* FindTestCase(const char* name) { + static const TestSuite* FindTestSuite(const char* name) { UnitTest& unit_test = *UnitTest::GetInstance(); - for (int i = 0; i < unit_test.total_test_case_count(); ++i) { - const TestCase* test_case = unit_test.GetTestCase(i); - if (0 == strcmp(test_case->name(), name)) - return test_case; + for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { + const TestSuite* test_suite = unit_test.GetTestSuite(i); + if (0 == strcmp(test_suite->name(), name)) + return test_suite; } - return NULL; + return nullptr; } - // Returns the array of pointers to all tests in a particular test case + // Returns the array of pointers to all tests in a particular test suite // sorted by the test name. The caller is responsible for deleting the // array. - static TestInfo const** GetSortedTests(const TestCase* test_case) { + static TestInfo const** GetSortedTests(const TestSuite* test_suite) { TestInfo const** const tests = - new const TestInfo*[test_case->total_test_count()]; + new const TestInfo*[test_suite->total_test_count()]; - for (int i = 0; i < test_case->total_test_count(); ++i) - tests[i] = test_case->GetTestInfo(i); + for (int i = 0; i < test_suite->total_test_count(); ++i) + tests[i] = test_suite->GetTestInfo(i); - std::sort(tests, tests + test_case->total_test_count(), + std::sort(tests, tests + test_suite->total_test_count(), LessByName<TestInfo>()); return tests; } }; #if GTEST_HAS_TYPED_TEST -template <typename T> class TestCaseWithCommentTest : public Test {}; -TYPED_TEST_CASE(TestCaseWithCommentTest, Types<int>); -TYPED_TEST(TestCaseWithCommentTest, Dummy) {} +template <typename T> class TestSuiteWithCommentTest : public Test {}; +TYPED_TEST_SUITE(TestSuiteWithCommentTest, Types<int>); +TYPED_TEST(TestSuiteWithCommentTest, Dummy) {} -const int kTypedTestCases = 1; +const int kTypedTestSuites = 1; const int kTypedTests = 1; #else -const int kTypedTestCases = 0; +const int kTypedTestSuites = 0; const int kTypedTests = 0; #endif // GTEST_HAS_TYPED_TEST @@ -113,21 +113,21 @@ const int kTypedTests = 0; TEST(ApiTest, UnitTestImmutableAccessorsWork) { UnitTest* unit_test = UnitTest::GetInstance(); - ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count()); - EXPECT_EQ(1 + kTypedTestCases, unit_test->test_case_to_run_count()); + ASSERT_EQ(2 + kTypedTestSuites, unit_test->total_test_suite_count()); + EXPECT_EQ(1 + kTypedTestSuites, unit_test->test_suite_to_run_count()); EXPECT_EQ(2, unit_test->disabled_test_count()); EXPECT_EQ(5 + kTypedTests, unit_test->total_test_count()); EXPECT_EQ(3 + kTypedTests, unit_test->test_to_run_count()); - const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases(); + const TestSuite** const test_suites = UnitTestHelper::GetSortedTestSuites(); - EXPECT_STREQ("ApiTest", test_cases[0]->name()); - EXPECT_STREQ("DISABLED_Test", test_cases[1]->name()); + EXPECT_STREQ("ApiTest", test_suites[0]->name()); + EXPECT_STREQ("DISABLED_Test", test_suites[1]->name()); #if GTEST_HAS_TYPED_TEST - EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name()); + EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suites[2]->name()); #endif // GTEST_HAS_TYPED_TEST - delete[] test_cases; + delete[] test_suites; // The following lines initiate actions to verify certain methods in // FinalSuccessChecker::TearDown. @@ -137,67 +137,67 @@ TEST(ApiTest, UnitTestImmutableAccessorsWork) { } AssertionResult IsNull(const char* str) { - if (str != NULL) { + if (str != nullptr) { return testing::AssertionFailure() << "argument is " << str; } return AssertionSuccess(); } -TEST(ApiTest, TestCaseImmutableAccessorsWork) { - const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest"); - ASSERT_TRUE(test_case != NULL); +TEST(ApiTest, TestSuiteImmutableAccessorsWork) { + const TestSuite* test_suite = UnitTestHelper::FindTestSuite("ApiTest"); + ASSERT_TRUE(test_suite != nullptr); - EXPECT_STREQ("ApiTest", test_case->name()); - EXPECT_TRUE(IsNull(test_case->type_param())); - EXPECT_TRUE(test_case->should_run()); - EXPECT_EQ(1, test_case->disabled_test_count()); - EXPECT_EQ(3, test_case->test_to_run_count()); - ASSERT_EQ(4, test_case->total_test_count()); + EXPECT_STREQ("ApiTest", test_suite->name()); + EXPECT_TRUE(IsNull(test_suite->type_param())); + EXPECT_TRUE(test_suite->should_run()); + EXPECT_EQ(1, test_suite->disabled_test_count()); + EXPECT_EQ(3, test_suite->test_to_run_count()); + ASSERT_EQ(4, test_suite->total_test_count()); - const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case); + const TestInfo** tests = UnitTestHelper::GetSortedTests(test_suite); EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name()); - EXPECT_STREQ("ApiTest", tests[0]->test_case_name()); + EXPECT_STREQ("ApiTest", tests[0]->test_suite_name()); EXPECT_TRUE(IsNull(tests[0]->value_param())); EXPECT_TRUE(IsNull(tests[0]->type_param())); EXPECT_FALSE(tests[0]->should_run()); - EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name()); - EXPECT_STREQ("ApiTest", tests[1]->test_case_name()); + EXPECT_STREQ("TestSuiteDisabledAccessorsWork", tests[1]->name()); + EXPECT_STREQ("ApiTest", tests[1]->test_suite_name()); EXPECT_TRUE(IsNull(tests[1]->value_param())); EXPECT_TRUE(IsNull(tests[1]->type_param())); EXPECT_TRUE(tests[1]->should_run()); - EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name()); - EXPECT_STREQ("ApiTest", tests[2]->test_case_name()); + EXPECT_STREQ("TestSuiteImmutableAccessorsWork", tests[2]->name()); + EXPECT_STREQ("ApiTest", tests[2]->test_suite_name()); EXPECT_TRUE(IsNull(tests[2]->value_param())); EXPECT_TRUE(IsNull(tests[2]->type_param())); EXPECT_TRUE(tests[2]->should_run()); EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name()); - EXPECT_STREQ("ApiTest", tests[3]->test_case_name()); + EXPECT_STREQ("ApiTest", tests[3]->test_suite_name()); EXPECT_TRUE(IsNull(tests[3]->value_param())); EXPECT_TRUE(IsNull(tests[3]->type_param())); EXPECT_TRUE(tests[3]->should_run()); delete[] tests; - tests = NULL; + tests = nullptr; #if GTEST_HAS_TYPED_TEST - test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0"); - ASSERT_TRUE(test_case != NULL); + test_suite = UnitTestHelper::FindTestSuite("TestSuiteWithCommentTest/0"); + ASSERT_TRUE(test_suite != nullptr); - EXPECT_STREQ("TestCaseWithCommentTest/0", test_case->name()); - EXPECT_STREQ(GetTypeName<int>().c_str(), test_case->type_param()); - EXPECT_TRUE(test_case->should_run()); - EXPECT_EQ(0, test_case->disabled_test_count()); - EXPECT_EQ(1, test_case->test_to_run_count()); - ASSERT_EQ(1, test_case->total_test_count()); + EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suite->name()); + EXPECT_STREQ(GetTypeName<int>().c_str(), test_suite->type_param()); + EXPECT_TRUE(test_suite->should_run()); + EXPECT_EQ(0, test_suite->disabled_test_count()); + EXPECT_EQ(1, test_suite->test_to_run_count()); + ASSERT_EQ(1, test_suite->total_test_count()); - tests = UnitTestHelper::GetSortedTests(test_case); + tests = UnitTestHelper::GetSortedTests(test_suite); EXPECT_STREQ("Dummy", tests[0]->name()); - EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name()); + EXPECT_STREQ("TestSuiteWithCommentTest/0", tests[0]->test_suite_name()); EXPECT_TRUE(IsNull(tests[0]->value_param())); EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param()); EXPECT_TRUE(tests[0]->should_run()); @@ -206,91 +206,91 @@ TEST(ApiTest, TestCaseImmutableAccessorsWork) { #endif // GTEST_HAS_TYPED_TEST } -TEST(ApiTest, TestCaseDisabledAccessorsWork) { - const TestCase* test_case = UnitTestHelper::FindTestCase("DISABLED_Test"); - ASSERT_TRUE(test_case != NULL); +TEST(ApiTest, TestSuiteDisabledAccessorsWork) { + const TestSuite* test_suite = UnitTestHelper::FindTestSuite("DISABLED_Test"); + ASSERT_TRUE(test_suite != nullptr); - EXPECT_STREQ("DISABLED_Test", test_case->name()); - EXPECT_TRUE(IsNull(test_case->type_param())); - EXPECT_FALSE(test_case->should_run()); - EXPECT_EQ(1, test_case->disabled_test_count()); - EXPECT_EQ(0, test_case->test_to_run_count()); - ASSERT_EQ(1, test_case->total_test_count()); + EXPECT_STREQ("DISABLED_Test", test_suite->name()); + EXPECT_TRUE(IsNull(test_suite->type_param())); + EXPECT_FALSE(test_suite->should_run()); + EXPECT_EQ(1, test_suite->disabled_test_count()); + EXPECT_EQ(0, test_suite->test_to_run_count()); + ASSERT_EQ(1, test_suite->total_test_count()); - const TestInfo* const test_info = test_case->GetTestInfo(0); + const TestInfo* const test_info = test_suite->GetTestInfo(0); EXPECT_STREQ("Dummy2", test_info->name()); - EXPECT_STREQ("DISABLED_Test", test_info->test_case_name()); + EXPECT_STREQ("DISABLED_Test", test_info->test_suite_name()); EXPECT_TRUE(IsNull(test_info->value_param())); EXPECT_TRUE(IsNull(test_info->type_param())); EXPECT_FALSE(test_info->should_run()); } // These two tests are here to provide support for testing -// test_case_to_run_count, disabled_test_count, and test_to_run_count. +// test_suite_to_run_count, disabled_test_count, and test_to_run_count. TEST(ApiTest, DISABLED_Dummy1) {} TEST(DISABLED_Test, Dummy2) {} class FinalSuccessChecker : public Environment { protected: - virtual void TearDown() { + void TearDown() override { UnitTest* unit_test = UnitTest::GetInstance(); - EXPECT_EQ(1 + kTypedTestCases, unit_test->successful_test_case_count()); + EXPECT_EQ(1 + kTypedTestSuites, unit_test->successful_test_suite_count()); EXPECT_EQ(3 + kTypedTests, unit_test->successful_test_count()); - EXPECT_EQ(0, unit_test->failed_test_case_count()); + EXPECT_EQ(0, unit_test->failed_test_suite_count()); EXPECT_EQ(0, unit_test->failed_test_count()); EXPECT_TRUE(unit_test->Passed()); EXPECT_FALSE(unit_test->Failed()); - ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count()); - - const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases(); - - EXPECT_STREQ("ApiTest", test_cases[0]->name()); - EXPECT_TRUE(IsNull(test_cases[0]->type_param())); - EXPECT_TRUE(test_cases[0]->should_run()); - EXPECT_EQ(1, test_cases[0]->disabled_test_count()); - ASSERT_EQ(4, test_cases[0]->total_test_count()); - EXPECT_EQ(3, test_cases[0]->successful_test_count()); - EXPECT_EQ(0, test_cases[0]->failed_test_count()); - EXPECT_TRUE(test_cases[0]->Passed()); - EXPECT_FALSE(test_cases[0]->Failed()); - - EXPECT_STREQ("DISABLED_Test", test_cases[1]->name()); - EXPECT_TRUE(IsNull(test_cases[1]->type_param())); - EXPECT_FALSE(test_cases[1]->should_run()); - EXPECT_EQ(1, test_cases[1]->disabled_test_count()); - ASSERT_EQ(1, test_cases[1]->total_test_count()); - EXPECT_EQ(0, test_cases[1]->successful_test_count()); - EXPECT_EQ(0, test_cases[1]->failed_test_count()); + ASSERT_EQ(2 + kTypedTestSuites, unit_test->total_test_suite_count()); + + const TestSuite** const test_suites = UnitTestHelper::GetSortedTestSuites(); + + EXPECT_STREQ("ApiTest", test_suites[0]->name()); + EXPECT_TRUE(IsNull(test_suites[0]->type_param())); + EXPECT_TRUE(test_suites[0]->should_run()); + EXPECT_EQ(1, test_suites[0]->disabled_test_count()); + ASSERT_EQ(4, test_suites[0]->total_test_count()); + EXPECT_EQ(3, test_suites[0]->successful_test_count()); + EXPECT_EQ(0, test_suites[0]->failed_test_count()); + EXPECT_TRUE(test_suites[0]->Passed()); + EXPECT_FALSE(test_suites[0]->Failed()); + + EXPECT_STREQ("DISABLED_Test", test_suites[1]->name()); + EXPECT_TRUE(IsNull(test_suites[1]->type_param())); + EXPECT_FALSE(test_suites[1]->should_run()); + EXPECT_EQ(1, test_suites[1]->disabled_test_count()); + ASSERT_EQ(1, test_suites[1]->total_test_count()); + EXPECT_EQ(0, test_suites[1]->successful_test_count()); + EXPECT_EQ(0, test_suites[1]->failed_test_count()); #if GTEST_HAS_TYPED_TEST - EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name()); - EXPECT_STREQ(GetTypeName<int>().c_str(), test_cases[2]->type_param()); - EXPECT_TRUE(test_cases[2]->should_run()); - EXPECT_EQ(0, test_cases[2]->disabled_test_count()); - ASSERT_EQ(1, test_cases[2]->total_test_count()); - EXPECT_EQ(1, test_cases[2]->successful_test_count()); - EXPECT_EQ(0, test_cases[2]->failed_test_count()); - EXPECT_TRUE(test_cases[2]->Passed()); - EXPECT_FALSE(test_cases[2]->Failed()); + EXPECT_STREQ("TestSuiteWithCommentTest/0", test_suites[2]->name()); + EXPECT_STREQ(GetTypeName<int>().c_str(), test_suites[2]->type_param()); + EXPECT_TRUE(test_suites[2]->should_run()); + EXPECT_EQ(0, test_suites[2]->disabled_test_count()); + ASSERT_EQ(1, test_suites[2]->total_test_count()); + EXPECT_EQ(1, test_suites[2]->successful_test_count()); + EXPECT_EQ(0, test_suites[2]->failed_test_count()); + EXPECT_TRUE(test_suites[2]->Passed()); + EXPECT_FALSE(test_suites[2]->Failed()); #endif // GTEST_HAS_TYPED_TEST - const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest"); - const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case); + const TestSuite* test_suite = UnitTestHelper::FindTestSuite("ApiTest"); + const TestInfo** tests = UnitTestHelper::GetSortedTests(test_suite); EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name()); - EXPECT_STREQ("ApiTest", tests[0]->test_case_name()); + EXPECT_STREQ("ApiTest", tests[0]->test_suite_name()); EXPECT_FALSE(tests[0]->should_run()); - EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name()); - EXPECT_STREQ("ApiTest", tests[1]->test_case_name()); + EXPECT_STREQ("TestSuiteDisabledAccessorsWork", tests[1]->name()); + EXPECT_STREQ("ApiTest", tests[1]->test_suite_name()); EXPECT_TRUE(IsNull(tests[1]->value_param())); EXPECT_TRUE(IsNull(tests[1]->type_param())); EXPECT_TRUE(tests[1]->should_run()); EXPECT_TRUE(tests[1]->result()->Passed()); EXPECT_EQ(0, tests[1]->result()->test_property_count()); - EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name()); - EXPECT_STREQ("ApiTest", tests[2]->test_case_name()); + EXPECT_STREQ("TestSuiteImmutableAccessorsWork", tests[2]->name()); + EXPECT_STREQ("ApiTest", tests[2]->test_suite_name()); EXPECT_TRUE(IsNull(tests[2]->value_param())); EXPECT_TRUE(IsNull(tests[2]->type_param())); EXPECT_TRUE(tests[2]->should_run()); @@ -298,7 +298,7 @@ class FinalSuccessChecker : public Environment { EXPECT_EQ(0, tests[2]->result()->test_property_count()); EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name()); - EXPECT_STREQ("ApiTest", tests[3]->test_case_name()); + EXPECT_STREQ("ApiTest", tests[3]->test_suite_name()); EXPECT_TRUE(IsNull(tests[3]->value_param())); EXPECT_TRUE(IsNull(tests[3]->type_param())); EXPECT_TRUE(tests[3]->should_run()); @@ -311,11 +311,11 @@ class FinalSuccessChecker : public Environment { delete[] tests; #if GTEST_HAS_TYPED_TEST - test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0"); - tests = UnitTestHelper::GetSortedTests(test_case); + test_suite = UnitTestHelper::FindTestSuite("TestSuiteWithCommentTest/0"); + tests = UnitTestHelper::GetSortedTests(test_suite); EXPECT_STREQ("Dummy", tests[0]->name()); - EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name()); + EXPECT_STREQ("TestSuiteWithCommentTest/0", tests[0]->test_suite_name()); EXPECT_TRUE(IsNull(tests[0]->value_param())); EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param()); EXPECT_TRUE(tests[0]->should_run()); @@ -324,7 +324,7 @@ class FinalSuccessChecker : public Environment { delete[] tests; #endif // GTEST_HAS_TYPED_TEST - delete[] test_cases; + delete[] test_suites; } }; diff --git a/googletest/test/gtest_all_test.cc b/googletest/test/gtest_all_test.cc index e61e36b1dfe8..615b29b70651 100644 --- a/googletest/test/gtest_all_test.cc +++ b/googletest/test/gtest_all_test.cc @@ -33,14 +33,14 @@ // Sometimes it's desirable to build most of Google Test's own tests // by compiling a single file. This file serves this purpose. #include "test/googletest-filepath-test.cc" -#include "test/googletest-linked-ptr-test.cc" #include "test/googletest-message-test.cc" #include "test/googletest-options-test.cc" #include "test/googletest-port-test.cc" -#include "test/gtest_pred_impl_unittest.cc" -#include "test/gtest_prod_test.cc" #include "test/googletest-test-part-test.cc" -#include "test/gtest-typed-test_test.cc" #include "test/gtest-typed-test2_test.cc" +#include "test/gtest-typed-test_test.cc" +#include "test/gtest_pred_impl_unittest.cc" +#include "test/gtest_prod_test.cc" +#include "test/gtest_skip_test.cc" #include "test/gtest_unittest.cc" #include "test/production.cc" diff --git a/googletest/test/gtest_assert_by_exception_test.cc b/googletest/test/gtest_assert_by_exception_test.cc index 0eae8575f3fe..ada4cb30ef68 100644 --- a/googletest/test/gtest_assert_by_exception_test.cc +++ b/googletest/test/gtest_assert_by_exception_test.cc @@ -80,8 +80,7 @@ TEST(Test, Test) { try { AssertFalse(); } catch(const testing::AssertionException& e) { - if (strstr(e.what(), "Expected failure") != NULL) - throw; + if (strstr(e.what(), "Expected failure") != nullptr) throw; printf("%s", "A failed assertion did throw an exception of the right type, " @@ -97,7 +96,6 @@ TEST(Test, Test) { int kTestForContinuingTest = 0; TEST(Test, Test2) { - // FIXME: how to force Test2 to be after Test? kTestForContinuingTest = 1; } diff --git a/googletest/test/gtest_environment_test.cc b/googletest/test/gtest_environment_test.cc index bc9524d66373..064bfc50b918 100644 --- a/googletest/test/gtest_environment_test.cc +++ b/googletest/test/gtest_environment_test.cc @@ -53,7 +53,7 @@ class MyEnvironment : public testing::Environment { // Depending on the value of failure_in_set_up_, SetUp() will // generate a non-fatal failure, generate a fatal failure, or // succeed. - virtual void SetUp() { + void SetUp() override { set_up_was_run_ = true; switch (failure_in_set_up_) { @@ -69,7 +69,7 @@ class MyEnvironment : public testing::Environment { } // Generates a non-fatal failure. - virtual void TearDown() { + void TearDown() override { tear_down_was_run_ = true; ADD_FAILURE() << "Expected non-fatal failure in global tear-down."; } @@ -116,7 +116,7 @@ void Check(bool condition, const char* msg) { } } -// Runs the tests. Return true iff successful. +// Runs the tests. Return true if and only if successful. // // The 'failure' parameter specifies the type of failure that should // be generated by the global set-up. diff --git a/googletest/test/gtest_pred_impl_unittest.cc b/googletest/test/gtest_pred_impl_unittest.cc index b466c150aedc..1afe5e2da7fe 100644 --- a/googletest/test/gtest_pred_impl_unittest.cc +++ b/googletest/test/gtest_pred_impl_unittest.cc @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// This file is AUTOMATICALLY GENERATED on 01/02/2018 by command +// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // Regression test for gtest_pred_impl.h @@ -122,13 +122,13 @@ struct PredFormatFunctor1 { class Predicate1Test : public testing::Test { protected: - virtual void SetUp() { + void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = 0; } - virtual void TearDown() { + void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. EXPECT_EQ(1, n1_) << @@ -144,10 +144,10 @@ class Predicate1Test : public testing::Test { } } - // true iff the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true iff the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -514,13 +514,13 @@ struct PredFormatFunctor2 { class Predicate2Test : public testing::Test { protected: - virtual void SetUp() { + void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = 0; } - virtual void TearDown() { + void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. EXPECT_EQ(1, n1_) << @@ -539,10 +539,10 @@ class Predicate2Test : public testing::Test { } } - // true iff the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true iff the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -948,13 +948,13 @@ struct PredFormatFunctor3 { class Predicate3Test : public testing::Test { protected: - virtual void SetUp() { + void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = n3_ = 0; } - virtual void TearDown() { + void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. EXPECT_EQ(1, n1_) << @@ -976,10 +976,10 @@ class Predicate3Test : public testing::Test { } } - // true iff the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true iff the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -1424,13 +1424,13 @@ struct PredFormatFunctor4 { class Predicate4Test : public testing::Test { protected: - virtual void SetUp() { + void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = n3_ = n4_ = 0; } - virtual void TearDown() { + void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. EXPECT_EQ(1, n1_) << @@ -1455,10 +1455,10 @@ class Predicate4Test : public testing::Test { } } - // true iff the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true iff the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; @@ -1942,13 +1942,13 @@ struct PredFormatFunctor5 { class Predicate5Test : public testing::Test { protected: - virtual void SetUp() { + void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = n3_ = n4_ = n5_ = 0; } - virtual void TearDown() { + void TearDown() override { // Verifies that each of the predicate's arguments was evaluated // exactly once. EXPECT_EQ(1, n1_) << @@ -1976,10 +1976,10 @@ class Predicate5Test : public testing::Test { } } - // true iff the test function is expected to run to finish. + // true if and only if the test function is expected to run to finish. static bool expected_to_finish_; - // true iff the test function did run to finish. + // true if and only if the test function did run to finish. static bool finished_; static int n1_; diff --git a/googletest/test/gtest_premature_exit_test.cc b/googletest/test/gtest_premature_exit_test.cc index c1e93056d8b5..1d1187eff006 100644 --- a/googletest/test/gtest_premature_exit_test.cc +++ b/googletest/test/gtest_premature_exit_test.cc @@ -45,7 +45,7 @@ namespace { class PrematureExitTest : public Test { public: - // Returns true iff the given file exists. + // Returns true if and only if the given file exists. static bool FileExists(const char* filepath) { StatStruct stat; return Stat(filepath, &stat) == 0; @@ -56,12 +56,12 @@ class PrematureExitTest : public Test { premature_exit_file_path_ = GetEnv("TEST_PREMATURE_EXIT_FILE"); // Normalize NULL to "" for ease of handling. - if (premature_exit_file_path_ == NULL) { + if (premature_exit_file_path_ == nullptr) { premature_exit_file_path_ = ""; } } - // Returns true iff the premature-exit file exists. + // Returns true if and only if the premature-exit file exists. bool PrematureExitFileExists() const { return FileExists(premature_exit_file_path_); } @@ -113,7 +113,7 @@ int main(int argc, char **argv) { // Test that the premature-exit file is deleted upon return from // RUN_ALL_TESTS(). const char* const filepath = GetEnv("TEST_PREMATURE_EXIT_FILE"); - if (filepath != NULL && *filepath != '\0') { + if (filepath != nullptr && *filepath != '\0') { if (PrematureExitTest::FileExists(filepath)) { printf( "File %s shouldn't exist after the test program finishes, but does.", diff --git a/googletest/test/gtest_repeat_test.cc b/googletest/test/gtest_repeat_test.cc index 1e8f499bb9de..7da4a15ea141 100644 --- a/googletest/test/gtest_repeat_test.cc +++ b/googletest/test/gtest_repeat_test.cc @@ -74,8 +74,8 @@ int g_environment_tear_down_count = 0; class MyEnvironment : public testing::Environment { public: MyEnvironment() {} - virtual void SetUp() { g_environment_set_up_count++; } - virtual void TearDown() { g_environment_tear_down_count++; } + void SetUp() override { g_environment_set_up_count++; } + void TearDown() override { g_environment_tear_down_count++; } }; // A test that should fail. @@ -117,13 +117,12 @@ const int kNumberOfParamTests = 10; class MyParamTest : public testing::TestWithParam<int> {}; TEST_P(MyParamTest, ShouldPass) { - // FIXME: Make parameter value checking robust WRT order of tests. GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam()); g_param_test_count++; } -INSTANTIATE_TEST_CASE_P(MyParamSequence, - MyParamTest, - testing::Range(0, kNumberOfParamTests)); +INSTANTIATE_TEST_SUITE_P(MyParamSequence, + MyParamTest, + testing::Range(0, kNumberOfParamTests)); // Resets the count for each test. void ResetCounts() { diff --git a/googletest/test/gtest_skip_environment_check_output_test.py b/googletest/test/gtest_skip_environment_check_output_test.py new file mode 100755 index 000000000000..6e791556aa71 --- /dev/null +++ b/googletest/test/gtest_skip_environment_check_output_test.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC. All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +"""Tests Google Test's gtest skip in environment setup behavior. + +This script invokes gtest_skip_in_environment_setup_test_ and verifies its +output. +""" + +import gtest_test_utils + +# Path to the gtest_skip_in_environment_setup_test binary +EXE_PATH = gtest_test_utils.GetTestExecutablePath( + 'gtest_skip_in_environment_setup_test') + +OUTPUT = gtest_test_utils.Subprocess([EXE_PATH]).output + + +# Test. +class SkipEntireEnvironmentTest(gtest_test_utils.TestCase): + + def testSkipEntireEnvironmentTest(self): + self.assertIn('Skipping the entire environment', OUTPUT) + self.assertNotIn('FAILED', OUTPUT) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/gtest_skip_in_environment_setup_test.cc b/googletest/test/gtest_skip_in_environment_setup_test.cc new file mode 100644 index 000000000000..937231063816 --- /dev/null +++ b/googletest/test/gtest_skip_in_environment_setup_test.cc @@ -0,0 +1,49 @@ +// Copyright 2019, Google LLC. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google LLC. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// This test verifies that skipping in the environment results in the +// testcases being skipped. + +#include <iostream> +#include "gtest/gtest.h" + +class SetupEnvironment : public testing::Environment { + public: + void SetUp() override { GTEST_SKIP() << "Skipping the entire environment"; } +}; + +TEST(Test, AlwaysFails) { EXPECT_EQ(true, false); } + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + + testing::AddGlobalTestEnvironment(new SetupEnvironment()); + + return RUN_ALL_TESTS(); +} diff --git a/googletest/test/gtest_skip_test.cc b/googletest/test/gtest_skip_test.cc new file mode 100644 index 000000000000..717e105e2e07 --- /dev/null +++ b/googletest/test/gtest_skip_test.cc @@ -0,0 +1,55 @@ +// Copyright 2008 Google Inc. +// All Rights Reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: arseny.aprelev@gmail.com (Arseny Aprelev) +// + +#include "gtest/gtest.h" + +using ::testing::Test; + +TEST(SkipTest, DoesSkip) { + GTEST_SKIP(); + EXPECT_EQ(0, 1); +} + +class Fixture : public Test { + protected: + void SetUp() override { + GTEST_SKIP() << "skipping all tests for this fixture"; + } +}; + +TEST_F(Fixture, SkipsOneTest) { + EXPECT_EQ(5, 7); +} + +TEST_F(Fixture, SkipsAnotherTest) { + EXPECT_EQ(99, 100); +} diff --git a/googletest/test/gtest_stress_test.cc b/googletest/test/gtest_stress_test.cc index 95ada39c337d..843481910f03 100644 --- a/googletest/test/gtest_stress_test.cc +++ b/googletest/test/gtest_stress_test.cc @@ -45,7 +45,6 @@ namespace { using internal::Notification; using internal::TestPropertyKeyIs; using internal::ThreadWithParam; -using internal::scoped_ptr; // In order to run tests in this file, for platforms where Google Test is // thread safe, implement ThreadWithParam. See the description of its API @@ -119,7 +118,7 @@ void CheckTestFailureCount(int expected_failures) { // concurrently. TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) { { - scoped_ptr<ThreadWithParam<int> > threads[kThreadCount]; + std::unique_ptr<ThreadWithParam<int> > threads[kThreadCount]; Notification threads_can_start; for (int i = 0; i != kThreadCount; i++) threads[i].reset(new ThreadWithParam<int>(&ManyAsserts, @@ -163,7 +162,7 @@ void FailingThread(bool is_fatal) { } void GenerateFatalFailureInAnotherThread(bool is_fatal) { - ThreadWithParam<bool> thread(&FailingThread, is_fatal, NULL); + ThreadWithParam<bool> thread(&FailingThread, is_fatal, nullptr); thread.Join(); } diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py index 43cba8f4cd61..ef9363c36945 100755 --- a/googletest/test/gtest_test_utils.py +++ b/googletest/test/gtest_test_utils.py @@ -36,6 +36,7 @@ import sys IS_WINDOWS = os.name == 'nt' IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0] +IS_OS2 = os.name == 'os2' import atexit import shutil @@ -164,7 +165,7 @@ def GetTestExecutablePath(executable_name, build_dir=None): path = os.path.abspath(os.path.join(build_dir or GetBuildDir(), executable_name)) - if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'): + if (IS_WINDOWS or IS_CYGWIN or IS_OS2) and not path.endswith('.exe'): path += '.exe' if not os.path.exists(path): @@ -214,10 +215,11 @@ class Subprocess: Returns: An object that represents outcome of the executed process. It has the following attributes: - terminated_by_signal True iff the child process has been terminated - by a signal. + terminated_by_signal True if and only if the child process has been + terminated by a signal. signal Sygnal that terminated the child process. - exited True iff the child process exited normally. + exited True if and only if the child process exited + normally. exit_code The code with which the child process exited. output Child process's stdout and stderr output combined in a string. @@ -306,8 +308,6 @@ def Main(): _ParseAndStripGTestFlags(sys.argv) # The tested binaries should not be writing XML output files unless the # script explicitly instructs them to. - # FIXME: Move this into Subprocess when we implement - # passing environment into it as a parameter. if GTEST_OUTPUT_VAR_NAME in os.environ: del os.environ[GTEST_OUTPUT_VAR_NAME] diff --git a/googletest/test/gtest_throw_on_failure_ex_test.cc b/googletest/test/gtest_throw_on_failure_ex_test.cc index 93f59d49cfdb..1d95adbf537b 100644 --- a/googletest/test/gtest_throw_on_failure_ex_test.cc +++ b/googletest/test/gtest_throw_on_failure_ex_test.cc @@ -63,8 +63,7 @@ void TestFailureThrowsRuntimeError() { try { EXPECT_EQ(2, 3) << "Expected failure"; } catch(const std::runtime_error& e) { - if (strstr(e.what(), "Expected failure") != NULL) - return; + if (strstr(e.what(), "Expected failure") != nullptr) return; printf("%s", "A failed assertion did throw an exception of the right type, " diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index f7213fbf3e5e..39749b7b19f8 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -61,11 +61,10 @@ TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { #include <time.h> #include <map> -#include <vector> #include <ostream> -#if GTEST_LANG_CXX11 +#include <type_traits> #include <unordered_set> -#endif // GTEST_LANG_CXX11 +#include <vector> #include "gtest/gtest-spi.h" #include "src/gtest-internal-inl.h" @@ -80,7 +79,7 @@ class StreamingListenerTest : public Test { class FakeSocketWriter : public StreamingListener::AbstractSocketWriter { public: // Sends a string to the socket. - virtual void Send(const std::string& message) { output_ += message; } + void Send(const std::string& message) override { output_ += message; } std::string output_; }; @@ -88,8 +87,8 @@ class StreamingListenerTest : public Test { StreamingListenerTest() : fake_sock_writer_(new FakeSocketWriter), streamer_(fake_sock_writer_), - test_info_obj_("FooTest", "Bar", NULL, NULL, - CodeLocation(__FILE__, __LINE__), 0, NULL) {} + test_info_obj_("FooTest", "Bar", nullptr, nullptr, + CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {} protected: std::string* output() { return &(fake_sock_writer_->output_); } @@ -114,13 +113,13 @@ TEST_F(StreamingListenerTest, OnTestIterationEnd) { TEST_F(StreamingListenerTest, OnTestCaseStart) { *output() = ""; - streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL)); + streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output()); } TEST_F(StreamingListenerTest, OnTestCaseEnd) { *output() = ""; - streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL)); + streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output()); } @@ -228,14 +227,12 @@ using testing::TestProperty; using testing::TestResult; using testing::TimeInMillis; using testing::UnitTest; -using testing::internal::AddReference; using testing::internal::AlwaysFalse; using testing::internal::AlwaysTrue; using testing::internal::AppendUserMessage; using testing::internal::ArrayAwareFind; using testing::internal::ArrayEq; using testing::internal::CodePointToUtf8; -using testing::internal::CompileAssertTypesEqual; using testing::internal::CopyArray; using testing::internal::CountIf; using testing::internal::EqFailure; @@ -252,7 +249,6 @@ using testing::internal::GetTestTypeId; using testing::internal::GetTimeInMillis; using testing::internal::GetTypeId; using testing::internal::GetUnitTestImpl; -using testing::internal::ImplicitlyConvertible; using testing::internal::Int32; using testing::internal::Int32FromEnvOrDie; using testing::internal::IsAProtocolMessage; @@ -265,8 +261,6 @@ using testing::internal::OsStackTraceGetterInterface; using testing::internal::ParseInt32Flag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; -using testing::internal::RemoveConst; -using testing::internal::RemoveReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; @@ -440,8 +434,8 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { static const TimeInMillis kMillisPerSec = 1000; private: - virtual void SetUp() { - saved_tz_ = NULL; + void SetUp() override { + saved_tz_ = nullptr; GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */) if (getenv("TZ")) @@ -454,10 +448,10 @@ class FormatEpochTimeInMillisAsIso8601Test : public Test { SetTimeZone("UTC+00"); } - virtual void TearDown() { + void TearDown() override { SetTimeZone(saved_tz_); free(const_cast<char*>(saved_tz_)); - saved_tz_ = NULL; + saved_tz_ = nullptr; } static void SetTimeZone(const char* time_zone) { @@ -513,37 +507,88 @@ TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0)); } -#if GTEST_CAN_COMPARE_NULL - # ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch # endif -// Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null -// pointer literal. -TEST(NullLiteralTest, IsTrueForNullLiterals) { - EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL)); - EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0)); - EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U)); - EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L)); +// Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal +// when the RHS is a pointer type. +TEST(NullLiteralTest, LHSAllowsNullLiterals) { + EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT + ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT + EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT + ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT + EXPECT_EQ(nullptr, static_cast<void*>(nullptr)); + ASSERT_EQ(nullptr, static_cast<void*>(nullptr)); + + const int* const p = nullptr; + EXPECT_EQ(0, p); // NOLINT + ASSERT_EQ(0, p); // NOLINT + EXPECT_EQ(NULL, p); // NOLINT + ASSERT_EQ(NULL, p); // NOLINT + EXPECT_EQ(nullptr, p); + ASSERT_EQ(nullptr, p); +} + +struct ConvertToAll { + template <typename T> + operator T() const { // NOLINT + return T(); + } +}; + +struct ConvertToPointer { + template <class T> + operator T*() const { // NOLINT + return nullptr; + } +}; + +struct ConvertToAllButNoPointers { + template <typename T, + typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0> + operator T() const { // NOLINT + return T(); + } +}; + +struct MyType {}; +inline bool operator==(MyType const&, MyType const&) { return true; } + +TEST(NullLiteralTest, ImplicitConversion) { + EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr)); +#if !defined(__GNUC__) || defined(__clang__) + // Disabled due to GCC bug gcc.gnu.org/PR89580 + EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr)); +#endif + EXPECT_EQ(ConvertToAll{}, MyType{}); + EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{}); } -// Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null -// pointer literal. -TEST(NullLiteralTest, IsFalseForNonNullLiterals) { - EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1)); - EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0)); - EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a')); - EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL))); +#ifdef __clang__ +#pragma clang diagnostic push +#if __has_warning("-Wzero-as-null-pointer-constant") +#pragma clang diagnostic error "-Wzero-as-null-pointer-constant" +#endif +#endif + +TEST(NullLiteralTest, NoConversionNoWarning) { + // Test that gtests detection and handling of null pointer constants + // doesn't trigger a warning when '0' isn't actually used as null. + EXPECT_EQ(0, 0); + ASSERT_EQ(0, 0); } +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + # ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them. # pragma option pop # endif -#endif // GTEST_CAN_COMPARE_NULL // // Tests CodePointToUtf8(). @@ -588,7 +633,7 @@ TEST(CodePointToUtf8Test, CanEncode12To16Bits) { #if !GTEST_WIDE_STRING_USES_UTF16_ // Tests in this group require a wchar_t to hold > 16 bits, and thus -// are skipped on Windows, Cygwin, and Symbian, where a wchar_t is +// are skipped on Windows, and Cygwin, where a wchar_t is // 16-bit wide. This code may not compile on those systems. // Tests that Unicode code-points that have 17 to 21 bits are encoded @@ -851,23 +896,23 @@ TEST(ContainerUtilityDeathTest, ShuffleRange) { class VectorShuffleTest : public Test { protected: - static const int kVectorSize = 20; + static const size_t kVectorSize = 20; VectorShuffleTest() : random_(1) { - for (int i = 0; i < kVectorSize; i++) { + for (int i = 0; i < static_cast<int>(kVectorSize); i++) { vector_.push_back(i); } } static bool VectorIsCorrupt(const TestingVector& vector) { - if (kVectorSize != static_cast<int>(vector.size())) { + if (kVectorSize != vector.size()) { return true; } bool found_in_vector[kVectorSize] = { false }; for (size_t i = 0; i < vector.size(); i++) { const int e = vector[i]; - if (e < 0 || e >= kVectorSize || found_in_vector[e]) { + if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) { return true; } found_in_vector[e] = true; @@ -884,7 +929,7 @@ class VectorShuffleTest : public Test { static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) { for (int i = begin; i < end; i++) { - if (i != vector[i]) { + if (i != vector[static_cast<size_t>(i)]) { return true; } } @@ -908,7 +953,7 @@ class VectorShuffleTest : public Test { TestingVector vector_; }; // class VectorShuffleTest -const int VectorShuffleTest::kVectorSize; +const size_t VectorShuffleTest::kVectorSize; TEST_F(VectorShuffleTest, HandlesEmptyRange) { // Tests an empty range at the beginning... @@ -960,7 +1005,7 @@ TEST_F(VectorShuffleTest, ShufflesEntireVector) { // Tests the first and last elements in particular to ensure that // there are no off-by-one problems in our shuffle algorithm. EXPECT_NE(0, vector_[0]); - EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]); + EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]); } TEST_F(VectorShuffleTest, ShufflesStartOfVector) { @@ -970,7 +1015,8 @@ TEST_F(VectorShuffleTest, ShufflesStartOfVector) { ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize); - EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize); + EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, + static_cast<int>(kVectorSize)); } TEST_F(VectorShuffleTest, ShufflesEndOfVector) { @@ -979,23 +1025,25 @@ TEST_F(VectorShuffleTest, ShufflesEndOfVector) { ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); - EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize); + EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, + static_cast<int>(kVectorSize)); } TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { - int kRangeSize = kVectorSize/3; + const int kRangeSize = static_cast<int>(kVectorSize) / 3; ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize); - EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize); + EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize, + static_cast<int>(kVectorSize)); } TEST_F(VectorShuffleTest, ShufflesRepeatably) { TestingVector vector2; - for (int i = 0; i < kVectorSize; i++) { - vector2.push_back(i); + for (size_t i = 0; i < kVectorSize; i++) { + vector2.push_back(static_cast<int>(i)); } random_.Reseed(1234); @@ -1006,7 +1054,7 @@ TEST_F(VectorShuffleTest, ShufflesRepeatably) { ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector2); - for (int i = 0; i < kVectorSize; i++) { + for (size_t i = 0; i < kVectorSize; i++) { EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i; } } @@ -1034,11 +1082,11 @@ TEST(StringTest, EndsWithCaseInsensitive) { // C++Builder's preprocessor is buggy; it fails to expand macros that // appear in macro parameters after wide char literals. Provide an alias // for NULL as a workaround. -static const wchar_t* const kNull = NULL; +static const wchar_t* const kNull = nullptr; // Tests String::CaseInsensitiveWideCStringEquals TEST(StringTest, CaseInsensitiveWideCStringEquals) { - EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL)); + EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"")); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar")); @@ -1159,7 +1207,7 @@ class ScopedFakeTestPartResultReporterWithThreadsTest : public ScopedFakeTestPartResultReporterTest { protected: static void AddFailureInOtherThread(FailureMode failure) { - ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL); + ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr); thread.Join(); } }; @@ -1195,12 +1243,6 @@ TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure."); } -#if GTEST_HAS_GLOBAL_STRING -TEST_F(ExpectFatalFailureTest, AcceptsStringObject) { - EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure.")); -} -#endif - TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) { EXPECT_FATAL_FAILURE(AddFatalFailure(), ::std::string("Expected fatal failure.")); @@ -1283,13 +1325,6 @@ TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { "Expected non-fatal failure."); } -#if GTEST_HAS_GLOBAL_STRING -TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) { - EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), - ::string("Expected non-fatal failure.")); -} -#endif - TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), ::std::string("Expected non-fatal failure.")); @@ -1363,7 +1398,7 @@ class TestResultTest : public Test { // ... and 3 TestResult objects. TestResult * r0, * r1, * r2; - virtual void SetUp() { + void SetUp() override { // pr1 is for success. pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", @@ -1400,7 +1435,7 @@ class TestResultTest : public Test { results2->push_back(*pr2); } - virtual void TearDown() { + void TearDown() override { delete pr1; delete pr2; @@ -1556,7 +1591,7 @@ class GTestFlagSaverTest : public Test { // Saves the Google Test flags such that we can restore them later, and // then sets them to their default values. This will be called // before the first test in this test case is run. - static void SetUpTestCase() { + static void SetUpTestSuite() { saver_ = new GTestFlagSaver; GTEST_FLAG(also_run_disabled_tests) = false; @@ -1578,9 +1613,9 @@ class GTestFlagSaverTest : public Test { // Restores the Google Test flags that the tests have modified. This will // be called after the last test in this test case is run. - static void TearDownTestCase() { + static void TearDownTestSuite() { delete saver_; - saver_ = NULL; + saver_ = nullptr; } // Verifies that the Google Test flags have their default values, and then @@ -1624,7 +1659,7 @@ class GTestFlagSaverTest : public Test { static GTestFlagSaver* saver_; }; -GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL; +GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr; // Google Test doesn't guarantee the order of tests. The following two // tests are designed to work regardless of their order. @@ -1828,12 +1863,12 @@ TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { class ShouldShardTest : public testing::Test { protected: - virtual void SetUp() { + void SetUp() override { index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX"; total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL"; } - virtual void TearDown() { + void TearDown() override { SetEnv(index_var_, ""); SetEnv(total_var_, ""); } @@ -1942,14 +1977,14 @@ TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { // Test class, there are no separate tests for the following classes // (except for some trivial cases): // -// TestCase, UnitTest, UnitTestResultPrinter. +// TestSuite, UnitTest, UnitTestResultPrinter. // // Similarly, there are no separate tests for the following macros: // // TEST, TEST_F, RUN_ALL_TESTS TEST(UnitTestTest, CanGetOriginalWorkingDir) { - ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL); + ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr); EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), ""); } @@ -1971,20 +2006,21 @@ void ExpectNonFatalFailureRecordingPropertyWithReservedKey( void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( const char* key) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); - ASSERT_TRUE(test_info != NULL); + ASSERT_TRUE(test_info != nullptr); ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(), key); } -void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( +void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( const char* key) { - const TestCase* test_case = UnitTest::GetInstance()->current_test_case(); - ASSERT_TRUE(test_case != NULL); + const testing::TestSuite* test_suite = + UnitTest::GetInstance()->current_test_suite(); + ASSERT_TRUE(test_suite != nullptr); ExpectNonFatalFailureRecordingPropertyWithReservedKey( - test_case->ad_hoc_test_result(), key); + test_suite->ad_hoc_test_result(), key); } -void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( +void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( const char* key) { ExpectNonFatalFailureRecordingPropertyWithReservedKey( UnitTest::GetInstance()->ad_hoc_test_result(), key); @@ -1996,29 +2032,32 @@ void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( class UnitTestRecordPropertyTest : public testing::internal::UnitTestRecordPropertyTestHelper { public: - static void SetUpTestCase() { - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( + static void SetUpTestSuite() { + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "disabled"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "errors"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "failures"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "name"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "tests"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "time"); Test::RecordProperty("test_case_key_1", "1"); - const TestCase* test_case = UnitTest::GetInstance()->current_test_case(); - ASSERT_TRUE(test_case != NULL); - ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count()); + const testing::TestSuite* test_suite = + UnitTest::GetInstance()->current_test_suite(); + + ASSERT_TRUE(test_suite != nullptr); + + ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count()); EXPECT_STREQ("test_case_key_1", - test_case->ad_hoc_test_result().GetTestProperty(0).key()); + test_suite->ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("1", - test_case->ad_hoc_test_result().GetTestProperty(0).value()); + test_suite->ad_hoc_test_result().GetTestProperty(0).value()); } }; @@ -2071,7 +2110,7 @@ TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) { } TEST_F(UnitTestRecordPropertyTest, - AddFailureInsideTestsWhenUsingTestCaseReservedKeys) { + AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) { ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( @@ -2096,28 +2135,28 @@ TEST_F(UnitTestRecordPropertyTest, class UnitTestRecordPropertyTestEnvironment : public Environment { public: - virtual void TearDown() { - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + void TearDown() override { + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "tests"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "failures"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "disabled"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "errors"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "name"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "timestamp"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "time"); - ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( + ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "random_seed"); } }; // This will test property recording outside of any test or test case. -static Environment* record_property_env = +static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ = AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment); // This group of tests is for predicate assertions (ASSERT_PRED*, etc) @@ -2128,12 +2167,12 @@ static Environment* record_property_env = // First, some predicates and predicate-formatters needed by the tests. -// Returns true iff the argument is an even number. +// Returns true if and only if the argument is an even number. bool IsEven(int n) { return (n % 2) == 0; } -// A functor that returns true iff the argument is an even number. +// A functor that returns true if and only if the argument is an even number. struct IsEvenFunctor { bool operator()(int n) { return IsEven(n); } }; @@ -2177,13 +2216,13 @@ struct AssertIsEvenFunctor { } }; -// Returns true iff the sum of the arguments is an even number. +// Returns true if and only if the sum of the arguments is an even number. bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); } -// A functor that returns true iff the sum of the arguments is an even -// number. +// A functor that returns true if and only if the sum of the arguments is an +// even number. struct SumIsEven3Functor { bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); @@ -2362,6 +2401,16 @@ TEST(PredTest, SingleEvaluationOnFailure) { EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; } +// Test predicate assertions for sets +TEST(PredTest, ExpectPredEvalFailure) { + std::set<int> set_a = {2, 1, 3, 4, 5}; + std::set<int> set_b = {0, 4, 8}; + const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; }; + EXPECT_NONFATAL_FAILURE( + EXPECT_PRED2(compare_sets, set_a, set_b), + "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates " + "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }"); +} // Some helper functions for testing using overloaded/template // functions with ASSERT_PREDn and EXPECT_PREDn. @@ -2456,24 +2505,22 @@ TEST(StringAssertionTest, ASSERT_STREQ) { // Tests ASSERT_STREQ with NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ_Null) { - ASSERT_STREQ(static_cast<const char *>(NULL), NULL); - EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"), - "non-null"); + ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr); + EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null"); } // Tests ASSERT_STREQ with NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ_Null2) { - EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL), - "non-null"); + EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null"); } // Tests ASSERT_STRNE. TEST(StringAssertionTest, ASSERT_STRNE) { ASSERT_STRNE("hi", "Hi"); - ASSERT_STRNE("Hi", NULL); - ASSERT_STRNE(NULL, "Hi"); - ASSERT_STRNE("", NULL); - ASSERT_STRNE(NULL, ""); + ASSERT_STRNE("Hi", nullptr); + ASSERT_STRNE(nullptr, "Hi"); + ASSERT_STRNE("", nullptr); + ASSERT_STRNE(nullptr, ""); ASSERT_STRNE("", "Hi"); ASSERT_STRNE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), @@ -2483,7 +2530,7 @@ TEST(StringAssertionTest, ASSERT_STRNE) { // Tests ASSERT_STRCASEEQ. TEST(StringAssertionTest, ASSERT_STRCASEEQ) { ASSERT_STRCASEEQ("hi", "Hi"); - ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL); + ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr); ASSERT_STRCASEEQ("", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), @@ -2493,10 +2540,10 @@ TEST(StringAssertionTest, ASSERT_STRCASEEQ) { // Tests ASSERT_STRCASENE. TEST(StringAssertionTest, ASSERT_STRCASENE) { ASSERT_STRCASENE("hi1", "Hi2"); - ASSERT_STRCASENE("Hi", NULL); - ASSERT_STRCASENE(NULL, "Hi"); - ASSERT_STRCASENE("", NULL); - ASSERT_STRCASENE(NULL, ""); + ASSERT_STRCASENE("Hi", nullptr); + ASSERT_STRCASENE(nullptr, "Hi"); + ASSERT_STRCASENE("", nullptr); + ASSERT_STRCASENE(nullptr, ""); ASSERT_STRCASENE("", "Hi"); ASSERT_STRCASENE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), @@ -2506,14 +2553,13 @@ TEST(StringAssertionTest, ASSERT_STRCASENE) { // Tests *_STREQ on wide strings. TEST(StringAssertionTest, STREQ_Wide) { // NULL strings. - ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL); + ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr); // Empty strings. ASSERT_STREQ(L"", L""); // Non-null vs NULL. - EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL), - "non-null"); + EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null"); // Equal strings. EXPECT_STREQ(L"Hi", L"Hi"); @@ -2535,16 +2581,18 @@ TEST(StringAssertionTest, STREQ_Wide) { // Tests *_STRNE on wide strings. TEST(StringAssertionTest, STRNE_Wide) { // NULL strings. - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL); - }, ""); + EXPECT_NONFATAL_FAILURE( + { // NOLINT + EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr); + }, + ""); // Empty strings. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\""); // Non-null vs NULL. - ASSERT_STRNE(L"non-null", NULL); + ASSERT_STRNE(L"non-null", nullptr); // Equal strings. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), @@ -2566,11 +2614,11 @@ TEST(StringAssertionTest, STRNE_Wide) { // Tests that IsSubstring() returns the correct result when the input // argument type is const char*. TEST(IsSubstringTest, ReturnsCorrectResultForCString) { - EXPECT_FALSE(IsSubstring("", "", NULL, "a")); - EXPECT_FALSE(IsSubstring("", "", "b", NULL)); + EXPECT_FALSE(IsSubstring("", "", nullptr, "a")); + EXPECT_FALSE(IsSubstring("", "", "b", nullptr)); EXPECT_FALSE(IsSubstring("", "", "needle", "haystack")); - EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL)); + EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr)); EXPECT_TRUE(IsSubstring("", "", "needle", "two needles")); } @@ -2581,7 +2629,8 @@ TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { EXPECT_FALSE(IsSubstring("", "", L"b", kNull)); EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); - EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL)); + EXPECT_TRUE( + IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr)); EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); } @@ -2709,7 +2758,7 @@ class FloatingPointTest : public Test { typedef typename testing::internal::FloatingPoint<RawType> Floating; typedef typename Floating::Bits Bits; - virtual void SetUp() { + void SetUp() override { const size_t max_ulps = Floating::kMaxUlps; // The bits that represent 0.0. @@ -2824,8 +2873,6 @@ TEST_F(FloatTest, LargeDiff) { TEST_F(FloatTest, Infinity) { EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); -#if !GTEST_OS_SYMBIAN - // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); @@ -2833,14 +2880,10 @@ TEST_F(FloatTest, Infinity) { // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1), "values_.nan1"); -#endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(FloatTest, NaN) { -#if !GTEST_OS_SYMBIAN -// Nokia's STLport crashes if we try to output infinity or NaN. - // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. @@ -2858,7 +2901,6 @@ TEST_F(FloatTest, NaN) { EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity"); -#endif // !GTEST_OS_SYMBIAN } // Tests that *_FLOAT_EQ are reflexive. @@ -2920,10 +2962,6 @@ TEST_F(FloatTest, FloatLEFails) { EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); }, "(values_.further_from_one) <= (1.0f)"); -#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) - // Nokia's STLport crashes if we try to output infinity or NaN. - // C++Builder gives bad results for ordered comparisons involving NaNs - // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); @@ -2933,7 +2971,6 @@ TEST_F(FloatTest, FloatLEFails) { EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); -#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } // Instantiates FloatingPointTest for testing *_DOUBLE_EQ. @@ -2997,8 +3034,6 @@ TEST_F(DoubleTest, LargeDiff) { TEST_F(DoubleTest, Infinity) { EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); -#if !GTEST_OS_SYMBIAN - // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); @@ -3006,18 +3041,10 @@ TEST_F(DoubleTest, Infinity) { // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), "values_.nan1"); -#endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(DoubleTest, NaN) { -#if !GTEST_OS_SYMBIAN - // In C++Builder, names within local classes (such as used by - // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the - // scoping class. Use a static local alias as a workaround. - // We use the assignment syntax since some compilers, like Sun Studio, - // don't allow initializing references using construction syntax - // (parentheses). static const DoubleTest::TestValues& v = this->values_; // Nokia's STLport crashes if we try to output infinity or NaN. @@ -3027,17 +3054,13 @@ TEST_F(DoubleTest, NaN) { EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity"); -#endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are reflexive. TEST_F(DoubleTest, Reflexive) { EXPECT_DOUBLE_EQ(0.0, 0.0); EXPECT_DOUBLE_EQ(1.0, 1.0); -#if !GTEST_OS_SYMBIAN - // Nokia's STLport crashes if we try to output infinity or NaN. ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); -#endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are commutative. @@ -3092,10 +3115,6 @@ TEST_F(DoubleTest, DoubleLEFails) { EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); }, "(values_.further_from_one) <= (1.0)"); -#if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) - // Nokia's STLport crashes if we try to output infinity or NaN. - // C++Builder gives bad results for ordered comparisons involving NaNs - // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); @@ -3105,7 +3124,6 @@ TEST_F(DoubleTest, DoubleLEFails) { EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); -#endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } @@ -3126,28 +3144,28 @@ TEST(DisabledTest, NotDISABLED_TestShouldRun) { // A test case whose name starts with DISABLED_. // Should not run. -TEST(DISABLED_TestCase, TestShouldNotRun) { +TEST(DISABLED_TestSuite, TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } // A test case and test whose names start with DISABLED_. // Should not run. -TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) { +TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } -// Check that when all tests in a test case are disabled, SetUpTestCase() and -// TearDownTestCase() are not called. +// Check that when all tests in a test case are disabled, SetUpTestSuite() and +// TearDownTestSuite() are not called. class DisabledTestsTest : public Test { protected: - static void SetUpTestCase() { + static void SetUpTestSuite() { FAIL() << "Unexpected failure: All tests disabled in test case. " - "SetUpTestCase() should not be called."; + "SetUpTestSuite() should not be called."; } - static void TearDownTestCase() { + static void TearDownTestSuite() { FAIL() << "Unexpected failure: All tests disabled in test case. " - "TearDownTestCase() should not be called."; + "TearDownTestSuite() should not be called."; } }; @@ -3168,7 +3186,7 @@ class TypedTest : public Test { }; typedef testing::Types<int, double> NumericTypes; -TYPED_TEST_CASE(TypedTest, NumericTypes); +TYPED_TEST_SUITE(TypedTest, NumericTypes); TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; @@ -3178,7 +3196,7 @@ template <typename T> class DISABLED_TypedTest : public Test { }; -TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes); +TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes); TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; @@ -3194,31 +3212,31 @@ template <typename T> class TypedTestP : public Test { }; -TYPED_TEST_CASE_P(TypedTestP); +TYPED_TEST_SUITE_P(TypedTestP); TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } -REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun); +REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun); -INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes); template <typename T> class DISABLED_TypedTestP : public Test { }; -TYPED_TEST_CASE_P(DISABLED_TypedTestP); +TYPED_TEST_SUITE_P(DISABLED_TypedTestP); TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } -REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun); +REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun); -INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes); +INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes); #endif // GTEST_HAS_TYPED_TEST_P @@ -3481,7 +3499,7 @@ std::string EditsToString(const std::vector<EditType>& edits) { std::vector<size_t> CharsToIndices(const std::string& str) { std::vector<size_t> out; for (size_t i = 0; i < str.size(); ++i) { - out.push_back(str[i]); + out.push_back(static_cast<size_t>(str[i])); } return out; } @@ -3494,7 +3512,7 @@ std::vector<std::string> CharsToLines(const std::string& str) { return out; } -TEST(EditDistance, TestCases) { +TEST(EditDistance, TestSuites) { struct Case { int line; const char* left; @@ -3713,22 +3731,19 @@ TEST(AssertionTest, ASSERT_EQ) { } // Tests ASSERT_EQ(NULL, pointer). -#if GTEST_CAN_COMPARE_NULL TEST(AssertionTest, ASSERT_EQ_NULL) { // A success. - const char* p = NULL; + const char* p = nullptr; // Some older GCC versions may issue a spurious warning in this or the next // assertion statement. This warning should not be suppressed with // static_cast since the test verifies the ability to use bare NULL as the // expected parameter to the macro. - ASSERT_EQ(NULL, p); + ASSERT_EQ(nullptr, p); // A failure. static int n = 0; - EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n), - " &n\n Which is:"); + EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:"); } -#endif // GTEST_CAN_COMPARE_NULL // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure @@ -3919,11 +3934,8 @@ TEST(AssertionTest, NamedEnum) { EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1"); } -// The version of gcc used in XCode 2.2 has a bug and doesn't allow -// anonymous enums in assertions. Therefore the following test is not -// done on Mac. -// Sun Studio and HP aCC also reject this code. -#if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC) +// Sun Studio and HP aCC2reject this code. +#if !defined(__SUNPRO_CC) && !defined(__HP_aCC) // Tests using assertions with anonymous enums. enum { @@ -4332,10 +4344,12 @@ TEST(AssertionWithMessageTest, SUCCEED) { TEST(AssertionWithMessageTest, ASSERT_TRUE) { ASSERT_TRUE(true) << "This should succeed."; ASSERT_TRUE(true) << true; - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_TRUE(false) << static_cast<const char *>(NULL) - << static_cast<char *>(NULL); - }, "(null)(null)"); + EXPECT_FATAL_FAILURE( + { // NOLINT + ASSERT_TRUE(false) << static_cast<const char*>(nullptr) + << static_cast<char*>(nullptr); + }, + "(null)(null)"); } #if GTEST_OS_WINDOWS @@ -4440,23 +4454,20 @@ TEST(ExpectTest, EXPECT_EQ_Double) { "5.1"); } -#if GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(NULL, pointer). TEST(ExpectTest, EXPECT_EQ_NULL) { // A success. - const char* p = NULL; + const char* p = nullptr; // Some older GCC versions may issue a spurious warning in this or the next // assertion statement. This warning should not be suppressed with // static_cast since the test verifies the ability to use bare NULL as the // expected parameter to the macro. - EXPECT_EQ(NULL, p); + EXPECT_EQ(nullptr, p); // A failure. int n = 0; - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n), - " &n\n Which is:"); + EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:"); } -#endif // GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure @@ -4482,7 +4493,7 @@ TEST(ExpectTest, EXPECT_NE) { "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2"); - char* const p0 = NULL; + char* const p0 = nullptr; EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0"); // Only way to get the Nokia compiler to compile the cast @@ -4590,7 +4601,7 @@ TEST(StreamableToStringTest, Pointer) { // Tests using StreamableToString() on a NULL non-char pointer. TEST(StreamableToStringTest, NullPointer) { - int* p = NULL; + int* p = nullptr; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } @@ -4601,7 +4612,7 @@ TEST(StreamableToStringTest, CString) { // Tests using StreamableToString() on a NULL C string. TEST(StreamableToStringTest, NullCString) { - char* p = NULL; + char* p = nullptr; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } @@ -4646,8 +4657,7 @@ TEST(StreamableTest, int) { // implemented a workaround (substituting "(null)" for NULL). This // tests whether the workaround works. TEST(StreamableTest, NullCharPtr) { - EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL), - "(null)"); + EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)"); } // Tests that basic IO manipulators (endl, ends, and flush) can be @@ -4698,6 +4708,19 @@ TEST(MacroTest, FAIL) { "Intentional failure."); } +// Tests GTEST_FAIL_AT. +TEST(MacroTest, GTEST_FAIL_AT) { + // Verifies that GTEST_FAIL_AT does generate a fatal failure and + // the failure message contains the user-streamed part. + EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!"); + + // Verifies that the user-streamed part is optional. + EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed"); + + // See the ADD_FAIL_AT test above to see how we test that the failure message + // contains the right filename and line number -- the same applies here. +} + // Tests SUCCEED TEST(MacroTest, SUCCEED) { SUCCEED(); @@ -4832,75 +4855,9 @@ TEST(EqAssertionTest, StdWideString) { #endif // GTEST_HAS_STD_WSTRING -#if GTEST_HAS_GLOBAL_STRING -// Tests using ::string values in {EXPECT|ASSERT}_EQ. -TEST(EqAssertionTest, GlobalString) { - // Compares a const char* to a ::string that has identical content. - EXPECT_EQ("Test", ::string("Test")); - - // Compares two identical ::strings. - const ::string str1("A * in the middle"); - const ::string str2(str1); - ASSERT_EQ(str1, str2); - - // Compares a ::string to a const char* that has different content. - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"), - "test"); - - // Compares two ::strings that have different contents, one of which - // having a NUL character in the middle. - ::string str3(str1); - str3.at(2) = '\0'; - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3), - "str3"); - - // Compares a ::string to a char* that has different content. - EXPECT_FATAL_FAILURE({ // NOLINT - ASSERT_EQ(::string("bar"), const_cast<char*>("foo")); - }, ""); -} - -#endif // GTEST_HAS_GLOBAL_STRING - -#if GTEST_HAS_GLOBAL_WSTRING - -// Tests using ::wstring values in {EXPECT|ASSERT}_EQ. -TEST(EqAssertionTest, GlobalWideString) { - // Compares two identical ::wstrings. - static const ::wstring wstr1(L"A * in the middle"); - static const ::wstring wstr2(wstr1); - EXPECT_EQ(wstr1, wstr2); - - // Compares a const wchar_t* to a ::wstring that has identical content. - const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; - ASSERT_EQ(kTestX8119, ::wstring(kTestX8119)); - - // Compares a const wchar_t* to a ::wstring that has different - // content. - const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; - EXPECT_NONFATAL_FAILURE({ // NOLINT - EXPECT_EQ(kTestX8120, ::wstring(kTestX8119)); - }, "Test\\x8119"); - - // Compares a wchar_t* to a ::wstring that has different content. - wchar_t* const p1 = const_cast<wchar_t*>(L"foo"); - EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")), - "bar"); - - // Compares two ::wstrings that have different contents, one of which - // having a NUL character in the middle. - static ::wstring wstr3; - wstr3 = wstr1; - wstr3.at(2) = L'\0'; - EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3), - "wstr3"); -} - -#endif // GTEST_HAS_GLOBAL_WSTRING - // Tests using char pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, CharPointer) { - char* const p0 = NULL; + char* const p0 = nullptr; // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does @@ -4922,7 +4879,7 @@ TEST(EqAssertionTest, CharPointer) { // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, WideCharPointer) { - wchar_t* const p0 = NULL; + wchar_t* const p0 = nullptr; // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does @@ -4947,9 +4904,8 @@ TEST(EqAssertionTest, WideCharPointer) { // Tests using other types of pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, OtherPointer) { - ASSERT_EQ(static_cast<const int*>(NULL), - static_cast<const int*>(NULL)); - EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL), + ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr)); + EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr), reinterpret_cast<const int*>(0x1234)), "0x1234"); } @@ -5065,7 +5021,7 @@ class TestLifeCycleTest : public Test { // Destructor. Decrements the number of test objects that uses this // fixture. - ~TestLifeCycleTest() { count_--; } + ~TestLifeCycleTest() override { count_--; } // Returns the number of live test objects that uses this fixture. int count() const { return count_; } @@ -5156,8 +5112,7 @@ TEST(AssertionResultTest, CanStreamOstreamManipulators) { EXPECT_STREQ("Data\n\\0Will be visible", r.message()); } -// The next test uses explicit conversion operators -- a C++11 feature. -#if GTEST_LANG_CXX11 +// The next test uses explicit conversion operators TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) { struct ExplicitlyConvertibleToBool { @@ -5170,8 +5125,6 @@ TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) { EXPECT_TRUE(v2); } -#endif // GTEST_LANG_CXX11 - struct ConvertibleToAssertionResult { operator AssertionResult() const { return AssertionResult(true); } }; @@ -5285,12 +5238,12 @@ TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) { // Tests streaming NULL pointers to testing::Message. TEST(MessageTest, NullPointers) { Message msg; - char* const p1 = NULL; - unsigned char* const p2 = NULL; - int* p3 = NULL; - double* p4 = NULL; - bool* p5 = NULL; - Message* p6 = NULL; + char* const p1 = nullptr; + unsigned char* const p2 = nullptr; + int* p3 = nullptr; + double* p4 = nullptr; + bool* p5 = nullptr; + Message* p6 = nullptr; msg << p1 << p2 << p3 << p4 << p5 << p6; ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", @@ -5300,12 +5253,12 @@ TEST(MessageTest, NullPointers) { // Tests streaming wide strings to testing::Message. TEST(MessageTest, WideStrings) { // Streams a NULL of type const wchar_t*. - const wchar_t* const_wstr = NULL; + const wchar_t* const_wstr = nullptr; EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str()); // Streams a NULL of type wchar_t*. - wchar_t* wstr = NULL; + wchar_t* wstr = nullptr; EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str()); @@ -5329,15 +5282,15 @@ namespace testing { class TestInfoTest : public Test { protected: static const TestInfo* GetTestInfo(const char* test_name) { - const TestCase* const test_case = GetUnitTestImpl()-> - GetTestCase("TestInfoTest", "", NULL, NULL); + const TestSuite* const test_suite = + GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr); - for (int i = 0; i < test_case->total_test_count(); ++i) { - const TestInfo* const test_info = test_case->GetTestInfo(i); + for (int i = 0; i < test_suite->total_test_count(); ++i) { + const TestInfo* const test_info = test_suite->GetTestInfo(i); if (strcmp(test_name, test_info->name()) == 0) return test_info; } - return NULL; + return nullptr; } static const TestResult* GetTestResult( @@ -5390,13 +5343,13 @@ TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; } -INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0)); +INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); template <typename T> class CodeLocationForTYPEDTEST : public Test { }; -TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int); +TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int); TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { VERIFY_CODE_LOCATION; @@ -5406,20 +5359,21 @@ template <typename T> class CodeLocationForTYPEDTESTP : public Test { }; -TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP); +TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP); TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) { VERIFY_CODE_LOCATION; } -REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify); +REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify); -INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int); +INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int); #undef VERIFY_CODE_LOCATION // Tests setting up and tearing down a test case. - +// Legacy API is deprecated but still available +#ifndef REMOVE_LEGACY_TEST_CASEAPI class SetUpTestCaseTest : public Test { protected: // This will be called once before the first test in this test case @@ -5451,11 +5405,11 @@ class SetUpTestCaseTest : public Test { EXPECT_EQ(0, counter_); // Cleans up the shared resource. - shared_resource_ = NULL; + shared_resource_ = nullptr; } // This will be called before each test in this test case. - virtual void SetUp() { + void SetUp() override { // SetUpTestCase() should be called only once, so counter_ should // always be 1. EXPECT_EQ(1, counter_); @@ -5469,18 +5423,78 @@ class SetUpTestCaseTest : public Test { }; int SetUpTestCaseTest::counter_ = 0; -const char* SetUpTestCaseTest::shared_resource_ = NULL; +const char* SetUpTestCaseTest::shared_resource_ = nullptr; // A test that uses the shared resource. -TEST_F(SetUpTestCaseTest, Test1) { - EXPECT_STRNE(NULL, shared_resource_); -} +TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); } // Another test that uses the shared resource. TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } +#endif // REMOVE_LEGACY_TEST_CASEAPI + +// Tests SetupTestSuite/TearDown TestSuite +class SetUpTestSuiteTest : public Test { + protected: + // This will be called once before the first test in this test case + // is run. + static void SetUpTestSuite() { + printf("Setting up the test suite . . .\n"); + + // Initializes some shared resource. In this simple example, we + // just create a C string. More complex stuff can be done if + // desired. + shared_resource_ = "123"; + + // Increments the number of test cases that have been set up. + counter_++; + + // SetUpTestSuite() should be called only once. + EXPECT_EQ(1, counter_); + } + + // This will be called once after the last test in this test case is + // run. + static void TearDownTestSuite() { + printf("Tearing down the test suite . . .\n"); + // Decrements the number of test suites that have been set up. + counter_--; + + // TearDownTestSuite() should be called only once. + EXPECT_EQ(0, counter_); + + // Cleans up the shared resource. + shared_resource_ = nullptr; + } + + // This will be called before each test in this test case. + void SetUp() override { + // SetUpTestSuite() should be called only once, so counter_ should + // always be 1. + EXPECT_EQ(1, counter_); + } + + // Number of test suites that have been set up. + static int counter_; + + // Some resource to be shared by all tests in this test case. + static const char* shared_resource_; +}; + +int SetUpTestSuiteTest::counter_ = 0; +const char* SetUpTestSuiteTest::shared_resource_ = nullptr; + +// A test that uses the shared resource. +TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) { + EXPECT_STRNE(nullptr, shared_resource_); +} + +// Another test that uses the shared resource. +TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) { + EXPECT_STREQ("123", shared_resource_); +} // The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly. @@ -5637,7 +5651,7 @@ struct Flags { class ParseFlagsTest : public Test { protected: // Clears the flags before each test. - virtual void SetUp() { + void SetUp() override { GTEST_FLAG(also_run_disabled_tests) = false; GTEST_FLAG(break_on_failure) = false; GTEST_FLAG(catch_exceptions) = false; @@ -5656,11 +5670,11 @@ class ParseFlagsTest : public Test { // Asserts that two narrow or wide string arrays are equal. template <typename CharType> - static void AssertStringArrayEq(size_t size1, CharType** array1, - size_t size2, CharType** array2) { + static void AssertStringArrayEq(int size1, CharType** array1, int size2, + CharType** array2) { ASSERT_EQ(size1, size2) << " Array sizes different."; - for (size_t i = 0; i != size1; i++) { + for (int i = 0; i != size1; i++) { ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; } } @@ -5742,141 +5756,81 @@ class ParseFlagsTest : public Test { // Tests parsing an empty command line. TEST_F(ParseFlagsTest, Empty) { - const char* argv[] = { - NULL - }; + const char* argv[] = {nullptr}; - const char* argv2[] = { - NULL - }; + const char* argv2[] = {nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } // Tests parsing a command line that has no flag. TEST_F(ParseFlagsTest, NoFlag) { - const char* argv[] = { - "foo.exe", - NULL - }; + const char* argv[] = {"foo.exe", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } // Tests parsing a bad --gtest_filter flag. TEST_F(ParseFlagsTest, FilterBad) { - const char* argv[] = { - "foo.exe", - "--gtest_filter", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_filter", nullptr}; - const char* argv2[] = { - "foo.exe", - "--gtest_filter", - NULL - }; + const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); } // Tests parsing an empty --gtest_filter flag. TEST_F(ParseFlagsTest, FilterEmpty) { - const char* argv[] = { - "foo.exe", - "--gtest_filter=", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false); } // Tests parsing a non-empty --gtest_filter flag. TEST_F(ParseFlagsTest, FilterNonEmpty) { - const char* argv[] = { - "foo.exe", - "--gtest_filter=abc", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); } // Tests parsing --gtest_break_on_failure. TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) { - const char* argv[] = { - "foo.exe", - "--gtest_break_on_failure", - NULL -}; + const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } // Tests parsing --gtest_break_on_failure=0. TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) { - const char* argv[] = { - "foo.exe", - "--gtest_break_on_failure=0", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing --gtest_break_on_failure=f. TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) { - const char* argv[] = { - "foo.exe", - "--gtest_break_on_failure=f", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing --gtest_break_on_failure=F. TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) { - const char* argv[] = { - "foo.exe", - "--gtest_break_on_failure=F", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } @@ -5884,48 +5838,27 @@ TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) { // Tests parsing a --gtest_break_on_failure flag that has a "true" // definition. TEST_F(ParseFlagsTest, BreakOnFailureTrue) { - const char* argv[] = { - "foo.exe", - "--gtest_break_on_failure=1", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } // Tests parsing --gtest_catch_exceptions. TEST_F(ParseFlagsTest, CatchExceptions) { - const char* argv[] = { - "foo.exe", - "--gtest_catch_exceptions", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false); } // Tests parsing --gtest_death_test_use_fork. TEST_F(ParseFlagsTest, DeathTestUseFork) { - const char* argv[] = { - "foo.exe", - "--gtest_death_test_use_fork", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false); } @@ -5933,36 +5866,21 @@ TEST_F(ParseFlagsTest, DeathTestUseFork) { // Tests having the same flag twice with different values. The // expected behavior is that the one coming last takes precedence. TEST_F(ParseFlagsTest, DuplicatedFlags) { - const char* argv[] = { - "foo.exe", - "--gtest_filter=a", - "--gtest_filter=b", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b", + nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false); } // Tests having an unrecognized flag on the command line. TEST_F(ParseFlagsTest, UnrecognizedFlag) { - const char* argv[] = { - "foo.exe", - "--gtest_break_on_failure", - "bar", // Unrecognized by Google Test. - "--gtest_filter=b", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_break_on_failure", + "bar", // Unrecognized by Google Test. + "--gtest_filter=b", nullptr}; - const char* argv2[] = { - "foo.exe", - "bar", - NULL - }; + const char* argv2[] = {"foo.exe", "bar", nullptr}; Flags flags; flags.break_on_failure = true; @@ -5972,145 +5890,82 @@ TEST_F(ParseFlagsTest, UnrecognizedFlag) { // Tests having a --gtest_list_tests flag TEST_F(ParseFlagsTest, ListTestsFlag) { - const char* argv[] = { - "foo.exe", - "--gtest_list_tests", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } // Tests having a --gtest_list_tests flag with a "true" value TEST_F(ParseFlagsTest, ListTestsTrue) { - const char* argv[] = { - "foo.exe", - "--gtest_list_tests=1", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } // Tests having a --gtest_list_tests flag with a "false" value TEST_F(ParseFlagsTest, ListTestsFalse) { - const char* argv[] = { - "foo.exe", - "--gtest_list_tests=0", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_list_tests=f. TEST_F(ParseFlagsTest, ListTestsFalse_f) { - const char* argv[] = { - "foo.exe", - "--gtest_list_tests=f", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_list_tests=F. TEST_F(ParseFlagsTest, ListTestsFalse_F) { - const char* argv[] = { - "foo.exe", - "--gtest_list_tests=F", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_output (invalid). TEST_F(ParseFlagsTest, OutputEmpty) { - const char* argv[] = { - "foo.exe", - "--gtest_output", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_output", nullptr}; - const char* argv2[] = { - "foo.exe", - "--gtest_output", - NULL - }; + const char* argv2[] = {"foo.exe", "--gtest_output", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true); } // Tests parsing --gtest_output=xml TEST_F(ParseFlagsTest, OutputXml) { - const char* argv[] = { - "foo.exe", - "--gtest_output=xml", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false); } // Tests parsing --gtest_output=xml:file TEST_F(ParseFlagsTest, OutputXmlFile) { - const char* argv[] = { - "foo.exe", - "--gtest_output=xml:file", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false); } // Tests parsing --gtest_output=xml:directory/path/ TEST_F(ParseFlagsTest, OutputXmlDirectory) { - const char* argv[] = { - "foo.exe", - "--gtest_output=xml:directory/path/", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/", + nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"), false); @@ -6118,242 +5973,140 @@ TEST_F(ParseFlagsTest, OutputXmlDirectory) { // Tests having a --gtest_print_time flag TEST_F(ParseFlagsTest, PrintTimeFlag) { - const char* argv[] = { - "foo.exe", - "--gtest_print_time", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } // Tests having a --gtest_print_time flag with a "true" value TEST_F(ParseFlagsTest, PrintTimeTrue) { - const char* argv[] = { - "foo.exe", - "--gtest_print_time=1", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } // Tests having a --gtest_print_time flag with a "false" value TEST_F(ParseFlagsTest, PrintTimeFalse) { - const char* argv[] = { - "foo.exe", - "--gtest_print_time=0", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_print_time=f. TEST_F(ParseFlagsTest, PrintTimeFalse_f) { - const char* argv[] = { - "foo.exe", - "--gtest_print_time=f", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_print_time=F. TEST_F(ParseFlagsTest, PrintTimeFalse_F) { - const char* argv[] = { - "foo.exe", - "--gtest_print_time=F", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_random_seed=number TEST_F(ParseFlagsTest, RandomSeed) { - const char* argv[] = { - "foo.exe", - "--gtest_random_seed=1000", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false); } // Tests parsing --gtest_repeat=number TEST_F(ParseFlagsTest, Repeat) { - const char* argv[] = { - "foo.exe", - "--gtest_repeat=1000", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); } // Tests having a --gtest_also_run_disabled_tests flag TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) { - const char* argv[] = { - "foo.exe", - "--gtest_also_run_disabled_tests", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, - Flags::AlsoRunDisabledTests(true), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), + false); } // Tests having a --gtest_also_run_disabled_tests flag with a "true" value TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) { - const char* argv[] = { - "foo.exe", - "--gtest_also_run_disabled_tests=1", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1", + nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, - Flags::AlsoRunDisabledTests(true), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), + false); } // Tests having a --gtest_also_run_disabled_tests flag with a "false" value TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) { - const char* argv[] = { - "foo.exe", - "--gtest_also_run_disabled_tests=0", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0", + nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; - GTEST_TEST_PARSING_FLAGS_(argv, argv2, - Flags::AlsoRunDisabledTests(false), false); + GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false), + false); } // Tests parsing --gtest_shuffle. TEST_F(ParseFlagsTest, ShuffleWithoutValue) { - const char* argv[] = { - "foo.exe", - "--gtest_shuffle", - NULL -}; + const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } // Tests parsing --gtest_shuffle=0. TEST_F(ParseFlagsTest, ShuffleFalse_0) { - const char* argv[] = { - "foo.exe", - "--gtest_shuffle=0", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false); } // Tests parsing a --gtest_shuffle flag that has a "true" definition. TEST_F(ParseFlagsTest, ShuffleTrue) { - const char* argv[] = { - "foo.exe", - "--gtest_shuffle=1", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } // Tests parsing --gtest_stack_trace_depth=number. TEST_F(ParseFlagsTest, StackTraceDepth) { - const char* argv[] = { - "foo.exe", - "--gtest_stack_trace_depth=5", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); } TEST_F(ParseFlagsTest, StreamResultTo) { - const char* argv[] = { - "foo.exe", - "--gtest_stream_result_to=localhost:1234", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234", + nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_( argv, argv2, Flags::StreamResultTo("localhost:1234"), false); @@ -6361,32 +6114,18 @@ TEST_F(ParseFlagsTest, StreamResultTo) { // Tests parsing --gtest_throw_on_failure. TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) { - const char* argv[] = { - "foo.exe", - "--gtest_throw_on_failure", - NULL -}; + const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } // Tests parsing --gtest_throw_on_failure=0. TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) { - const char* argv[] = { - "foo.exe", - "--gtest_throw_on_failure=0", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false); } @@ -6394,16 +6133,9 @@ TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) { // Tests parsing a --gtest_throw_on_failure flag that has a "true" // definition. TEST_F(ParseFlagsTest, ThrowOnFailureTrue) { - const char* argv[] = { - "foo.exe", - "--gtest_throw_on_failure=1", - NULL - }; + const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } @@ -6472,16 +6204,9 @@ TEST_F(FlagfileTest, Empty) { std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); - const char* argv[] = { - "foo.exe", - flagfile_flag.c_str(), - NULL - }; + const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } @@ -6493,16 +6218,9 @@ TEST_F(FlagfileTest, FilterNonEmpty) { std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); - const char* argv[] = { - "foo.exe", - flagfile_flag.c_str(), - NULL - }; + const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); } @@ -6516,16 +6234,9 @@ TEST_F(FlagfileTest, SeveralFlags) { std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); - const char* argv[] = { - "foo.exe", - flagfile_flag.c_str(), - NULL - }; + const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; - const char* argv2[] = { - "foo.exe", - NULL - }; + const char* argv2[] = {"foo.exe", nullptr}; Flags expected_flags; expected_flags.break_on_failure = true; @@ -6541,34 +6252,34 @@ class CurrentTestInfoTest : public Test { protected: // Tests that current_test_info() returns NULL before the first test in // the test case is run. - static void SetUpTestCase() { + static void SetUpTestSuite() { // There should be no tests running at this point. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); - EXPECT_TRUE(test_info == NULL) + EXPECT_TRUE(test_info == nullptr) << "There should be no tests running at this point."; } // Tests that current_test_info() returns NULL after the last test in // the test case has run. - static void TearDownTestCase() { + static void TearDownTestSuite() { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); - EXPECT_TRUE(test_info == NULL) + EXPECT_TRUE(test_info == nullptr) << "There should be no tests running at this point."; } }; // Tests that current_test_info() returns TestInfo for currently running // test by checking the expected test name against the actual one. -TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) { +TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); - ASSERT_TRUE(NULL != test_info) + ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) << "Expected the name of the currently running test case."; - EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name()) + EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name()) << "Expected the name of the currently running test."; } @@ -6576,14 +6287,14 @@ TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) { // test by checking the expected test name against the actual one. We // use this test to see that the TestInfo object actually changed from // the previous invocation. -TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) { +TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); - ASSERT_TRUE(NULL != test_info) + ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) << "Expected the name of the currently running test case."; - EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name()) + EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name()) << "Expected the name of the currently running test."; } @@ -6628,12 +6339,8 @@ TEST(NestedTestingNamespaceTest, Failure) { // successfully. class ProtectedFixtureMethodsTest : public Test { protected: - virtual void SetUp() { - Test::SetUp(); - } - virtual void TearDown() { - Test::TearDown(); - } + void SetUp() override { Test::SetUp(); } + void TearDown() override { Test::TearDown(); } }; // StreamingAssertionsTest tests the streaming versions of a representative @@ -6831,7 +6538,7 @@ TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { GTEST_FLAG(color) = "auto"; -#if GTEST_OS_WINDOWS +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW // On Windows, we ignore the TERM variable as it's usually not set. SetEnv("TERM", "dumb"); @@ -7006,20 +6713,19 @@ TEST(HasFailureTest, WorksOutsideOfTestBody2) { class TestListener : public EmptyTestEventListener { public: - TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {} + TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {} TestListener(int* on_start_counter, bool* is_destroyed) : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {} - virtual ~TestListener() { + ~TestListener() override { if (is_destroyed_) *is_destroyed_ = true; } protected: - virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { - if (on_start_counter_ != NULL) - (*on_start_counter_)++; + void OnTestProgramStart(const UnitTest& /*unit_test*/) override { + if (on_start_counter_ != nullptr) (*on_start_counter_)++; } private: @@ -7031,9 +6737,9 @@ class TestListener : public EmptyTestEventListener { TEST(TestEventListenersTest, ConstructionWorks) { TestEventListeners listeners; - EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL); - EXPECT_TRUE(listeners.default_result_printer() == NULL); - EXPECT_TRUE(listeners.default_xml_generator() == NULL); + EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr); + EXPECT_TRUE(listeners.default_result_printer() == nullptr); + EXPECT_TRUE(listeners.default_xml_generator() == nullptr); } // Tests that the TestEventListeners destructor deletes all the listeners it @@ -7042,12 +6748,12 @@ TEST(TestEventListenersTest, DestructionWorks) { bool default_result_printer_is_destroyed = false; bool default_xml_printer_is_destroyed = false; bool extra_listener_is_destroyed = false; - TestListener* default_result_printer = new TestListener( - NULL, &default_result_printer_is_destroyed); - TestListener* default_xml_printer = new TestListener( - NULL, &default_xml_printer_is_destroyed); - TestListener* extra_listener = new TestListener( - NULL, &extra_listener_is_destroyed); + TestListener* default_result_printer = + new TestListener(nullptr, &default_result_printer_is_destroyed); + TestListener* default_xml_printer = + new TestListener(nullptr, &default_xml_printer_is_destroyed); + TestListener* extra_listener = + new TestListener(nullptr, &extra_listener_is_destroyed); { TestEventListeners listeners; @@ -7087,21 +6793,21 @@ class SequenceTestingListener : public EmptyTestEventListener { : vector_(vector), id_(id) {} protected: - virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { + void OnTestProgramStart(const UnitTest& /*unit_test*/) override { vector_->push_back(GetEventDescription("OnTestProgramStart")); } - virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { + void OnTestProgramEnd(const UnitTest& /*unit_test*/) override { vector_->push_back(GetEventDescription("OnTestProgramEnd")); } - virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, - int /*iteration*/) { + void OnTestIterationStart(const UnitTest& /*unit_test*/, + int /*iteration*/) override { vector_->push_back(GetEventDescription("OnTestIterationStart")); } - virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, - int /*iteration*/) { + void OnTestIterationEnd(const UnitTest& /*unit_test*/, + int /*iteration*/) override { vector_->push_back(GetEventDescription("OnTestIterationEnd")); } @@ -7172,7 +6878,7 @@ TEST(TestEventListenersTest, Release) { EXPECT_EQ(listener, listeners.Release(listener)); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); - EXPECT_TRUE(listeners.Release(listener) == NULL); + EXPECT_TRUE(listeners.Release(listener) == nullptr); } EXPECT_EQ(0, on_start_counter); EXPECT_FALSE(is_destroyed); @@ -7182,7 +6888,7 @@ TEST(TestEventListenersTest, Release) { // Tests that no events are forwarded when event forwarding is disabled. TEST(EventListenerTest, SuppressEventForwarding) { int on_start_counter = 0; - TestListener* listener = new TestListener(&on_start_counter, NULL); + TestListener* listener = new TestListener(&on_start_counter, nullptr); TestEventListeners listeners; listeners.Append(listener); @@ -7223,9 +6929,9 @@ TEST(EventListenerTest, default_result_printer) { // Replacing default_result_printer with something else should remove it // from the list and destroy it. - TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL); + TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr); - EXPECT_TRUE(listeners.default_result_printer() == NULL); + EXPECT_TRUE(listeners.default_result_printer() == nullptr); EXPECT_TRUE(is_destroyed); // After broadcasting an event the counter is still the same, indicating @@ -7249,7 +6955,7 @@ TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); - EXPECT_TRUE(listeners.default_result_printer() == NULL); + EXPECT_TRUE(listeners.default_result_printer() == nullptr); EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_result_printer. @@ -7282,9 +6988,9 @@ TEST(EventListenerTest, default_xml_generator) { // Replacing default_xml_generator with something else should remove it // from the list and destroy it. - TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL); + TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr); - EXPECT_TRUE(listeners.default_xml_generator() == NULL); + EXPECT_TRUE(listeners.default_xml_generator() == nullptr); EXPECT_TRUE(is_destroyed); // After broadcasting an event the counter is still the same, indicating @@ -7308,7 +7014,7 @@ TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); - EXPECT_TRUE(listeners.default_xml_generator() == NULL); + EXPECT_TRUE(listeners.default_xml_generator() == nullptr); EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_xml_generator. @@ -7371,14 +7077,13 @@ GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. // Tests for internal utilities necessary for implementation of the universal // printing. -// FIXME: Find a better home for them. class ConversionHelperBase {}; class ConversionHelperDerived : public ConversionHelperBase {}; // Tests that IsAProtocolMessage<T>::value is a compile-time constant. TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { - GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value, + GTEST_COMPILE_ASSERT_(IsAProtocolMessage<::proto2::Message>::value, const_true); GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false); } @@ -7387,79 +7092,21 @@ TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { // proto2::Message or a sub-class of it. TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); - EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value); } // Tests that IsAProtocolMessage<T>::value is false when T is neither -// ProtocolMessage nor a sub-class of it. +// ::proto2::Message nor a sub-class of it. TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) { EXPECT_FALSE(IsAProtocolMessage<int>::value); EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value); } -// Tests that CompileAssertTypesEqual compiles when the type arguments are -// equal. -TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) { - CompileAssertTypesEqual<void, void>(); - CompileAssertTypesEqual<int*, int*>(); -} - -// Tests that RemoveReference does not affect non-reference types. -TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) { - CompileAssertTypesEqual<int, RemoveReference<int>::type>(); - CompileAssertTypesEqual<const char, RemoveReference<const char>::type>(); -} - -// Tests that RemoveReference removes reference from reference types. -TEST(RemoveReferenceTest, RemovesReference) { - CompileAssertTypesEqual<int, RemoveReference<int&>::type>(); - CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>(); -} - -// Tests GTEST_REMOVE_REFERENCE_. - -template <typename T1, typename T2> -void TestGTestRemoveReference() { - CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>(); -} - -TEST(RemoveReferenceTest, MacroVersion) { - TestGTestRemoveReference<int, int>(); - TestGTestRemoveReference<const char, const char&>(); -} - - -// Tests that RemoveConst does not affect non-const types. -TEST(RemoveConstTest, DoesNotAffectNonConstType) { - CompileAssertTypesEqual<int, RemoveConst<int>::type>(); - CompileAssertTypesEqual<char&, RemoveConst<char&>::type>(); -} - -// Tests that RemoveConst removes const from const types. -TEST(RemoveConstTest, RemovesConst) { - CompileAssertTypesEqual<int, RemoveConst<const int>::type>(); - CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>(); - CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>(); -} - -// Tests GTEST_REMOVE_CONST_. - -template <typename T1, typename T2> -void TestGTestRemoveConst() { - CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>(); -} - -TEST(RemoveConstTest, MacroVersion) { - TestGTestRemoveConst<int, int>(); - TestGTestRemoveConst<double&, double&>(); - TestGTestRemoveConst<char, const char>(); -} - // Tests GTEST_REMOVE_REFERENCE_AND_CONST_. template <typename T1, typename T2> void TestGTestRemoveReferenceAndConst() { - CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>(); + static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value, + "GTEST_REMOVE_REFERENCE_AND_CONST_ failed."); } TEST(RemoveReferenceToConstTest, Works) { @@ -7470,35 +7117,12 @@ TEST(RemoveReferenceToConstTest, Works) { TestGTestRemoveReferenceAndConst<const char*, const char*>(); } -// Tests that AddReference does not affect reference types. -TEST(AddReferenceTest, DoesNotAffectReferenceType) { - CompileAssertTypesEqual<int&, AddReference<int&>::type>(); - CompileAssertTypesEqual<const char&, AddReference<const char&>::type>(); -} - -// Tests that AddReference adds reference to non-reference types. -TEST(AddReferenceTest, AddsReference) { - CompileAssertTypesEqual<int&, AddReference<int>::type>(); - CompileAssertTypesEqual<const char&, AddReference<const char>::type>(); -} - -// Tests GTEST_ADD_REFERENCE_. - -template <typename T1, typename T2> -void TestGTestAddReference() { - CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>(); -} - -TEST(AddReferenceTest, MacroVersion) { - TestGTestAddReference<int&, int>(); - TestGTestAddReference<const char&, const char&>(); -} - // Tests GTEST_REFERENCE_TO_CONST_. template <typename T1, typename T2> void TestGTestReferenceToConst() { - CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>(); + static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value, + "GTEST_REFERENCE_TO_CONST_ failed."); } TEST(GTestReferenceToConstTest, Works) { @@ -7508,35 +7132,6 @@ TEST(GTestReferenceToConstTest, Works) { TestGTestReferenceToConst<const std::string&, const std::string&>(); } -// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant. -TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) { - GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true); - GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value), - const_false); -} - -// Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can -// be implicitly converted to T2. -TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) { - EXPECT_TRUE((ImplicitlyConvertible<int, double>::value)); - EXPECT_TRUE((ImplicitlyConvertible<double, int>::value)); - EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value)); - EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value)); - EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&, - const ConversionHelperBase&>::value)); - EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase, - ConversionHelperBase>::value)); -} - -// Tests that ImplicitlyConvertible<T1, T2>::value is false when T1 -// cannot be implicitly converted to T2. -TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) { - EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value)); - EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value)); - EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value)); - EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&, - ConversionHelperDerived&>::value)); -} // Tests IsContainerTest. @@ -7555,7 +7150,6 @@ TEST(IsContainerTestTest, WorksForContainer) { sizeof(IsContainerTest<std::map<int, double> >(0))); } -#if GTEST_LANG_CXX11 struct ConstOnlyContainerWithPointerIterator { using const_iterator = int*; const_iterator begin() const; @@ -7577,7 +7171,6 @@ TEST(IsContainerTestTest, ConstOnlyContainer) { EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0))); } -#endif // GTEST_LANG_CXX11 // Tests IsHashTable. struct AHashTable { @@ -7590,13 +7183,8 @@ struct NotReallyAHashTable { TEST(IsHashTable, Basic) { EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value); EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value); -#if GTEST_LANG_CXX11 EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value); EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value); -#endif // GTEST_LANG_CXX11 -#if GTEST_HAS_HASH_SET_ - EXPECT_TRUE(testing::internal::IsHashTable<__gnu_cxx::hash_set<int>>::value); -#endif // GTEST_HAS_HASH_SET_ } // Tests ArrayEq(). @@ -7746,6 +7334,84 @@ TEST(NativeArrayTest, WorksForTwoDimensionalArray) { EXPECT_EQ(a, na.begin()); } +// IndexSequence +TEST(IndexSequence, MakeIndexSequence) { + using testing::internal::IndexSequence; + using testing::internal::MakeIndexSequence; + EXPECT_TRUE( + (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value)); + EXPECT_TRUE( + (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value)); + EXPECT_TRUE( + (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value)); + EXPECT_TRUE(( + std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value)); + EXPECT_TRUE( + (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value)); +} + +// ElemFromList +TEST(ElemFromList, Basic) { + using testing::internal::ElemFromList; + using Idx = testing::internal::MakeIndexSequence<3>::type; + EXPECT_TRUE(( + std::is_same<int, ElemFromList<0, Idx, int, double, char>::type>::value)); + EXPECT_TRUE( + (std::is_same<double, + ElemFromList<1, Idx, int, double, char>::type>::value)); + EXPECT_TRUE( + (std::is_same<char, + ElemFromList<2, Idx, int, double, char>::type>::value)); + EXPECT_TRUE( + (std::is_same< + char, ElemFromList<7, testing::internal::MakeIndexSequence<12>::type, + int, int, int, int, int, int, int, char, int, int, + int, int>::type>::value)); +} + +// FlatTuple +TEST(FlatTuple, Basic) { + using testing::internal::FlatTuple; + + FlatTuple<int, double, const char*> tuple = {}; + EXPECT_EQ(0, tuple.Get<0>()); + EXPECT_EQ(0.0, tuple.Get<1>()); + EXPECT_EQ(nullptr, tuple.Get<2>()); + + tuple = FlatTuple<int, double, const char*>(7, 3.2, "Foo"); + EXPECT_EQ(7, tuple.Get<0>()); + EXPECT_EQ(3.2, tuple.Get<1>()); + EXPECT_EQ(std::string("Foo"), tuple.Get<2>()); + + tuple.Get<1>() = 5.1; + EXPECT_EQ(5.1, tuple.Get<1>()); +} + +TEST(FlatTuple, ManyTypes) { + using testing::internal::FlatTuple; + + // Instantiate FlatTuple with 257 ints. + // Tests show that we can do it with thousands of elements, but very long + // compile times makes it unusuitable for this test. +#define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int, +#define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8 +#define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16 +#define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32 +#define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64 +#define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128 + + // Let's make sure that we can have a very long list of types without blowing + // up the template instantiation depth. + FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple; + + tuple.Get<0>() = 7; + tuple.Get<99>() = 17; + tuple.Get<256>() = 1000; + EXPECT_EQ(7, tuple.Get<0>()); + EXPECT_EQ(17, tuple.Get<99>()); + EXPECT_EQ(1000, tuple.Get<256>()); +} + // Tests SkipPrefix(). TEST(SkipPrefixTest, SkipsWhenPrefixMatches) { @@ -7776,14 +7442,14 @@ TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { class AdHocTestResultTest : public testing::Test { protected: - static void SetUpTestCase() { - FAIL() << "A failure happened inside SetUpTestCase()."; + static void SetUpTestSuite() { + FAIL() << "A failure happened inside SetUpTestSuite()."; } }; -TEST_F(AdHocTestResultTest, AdHocTestResultForTestCaseShowsFailure) { +TEST_F(AdHocTestResultTest, AdHocTestResultForTestSuiteShowsFailure) { const testing::TestResult& test_result = testing::UnitTest::GetInstance() - ->current_test_case() + ->current_test_suite() ->ad_hoc_test_result(); EXPECT_TRUE(test_result.Failed()); } @@ -7793,3 +7459,30 @@ TEST_F(AdHocTestResultTest, AdHocTestResultTestForUnitTestDoesNotShowFailure) { testing::UnitTest::GetInstance()->ad_hoc_test_result(); EXPECT_FALSE(test_result.Failed()); } + +class DynamicUnitTestFixture : public testing::Test {}; + +class DynamicTest : public DynamicUnitTestFixture { + void TestBody() override { EXPECT_TRUE(true); } +}; + +auto* dynamic_test = testing::RegisterTest( + "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__, + __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; }); + +TEST(RegisterTest, WasRegistered) { + auto* unittest = testing::UnitTest::GetInstance(); + for (int i = 0; i < unittest->total_test_suite_count(); ++i) { + auto* tests = unittest->GetTestSuite(i); + if (tests->name() != std::string("DynamicUnitTestFixture")) continue; + for (int j = 0; j < tests->total_test_count(); ++j) { + if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue; + // Found it. + EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE"); + EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE"); + return; + } + } + + FAIL() << "Didn't find the test!"; +} diff --git a/googletest/test/gtest_xml_outfile1_test_.cc b/googletest/test/gtest_xml_outfile1_test_.cc index a38ebac839f7..19aa252a3010 100644 --- a/googletest/test/gtest_xml_outfile1_test_.cc +++ b/googletest/test/gtest_xml_outfile1_test_.cc @@ -34,12 +34,8 @@ class PropertyOne : public testing::Test { protected: - virtual void SetUp() { - RecordProperty("SetUpProp", 1); - } - virtual void TearDown() { - RecordProperty("TearDownProp", 1); - } + void SetUp() override { RecordProperty("SetUpProp", 1); } + void TearDown() override { RecordProperty("TearDownProp", 1); } }; TEST_F(PropertyOne, TestSomeProperties) { diff --git a/googletest/test/gtest_xml_outfile2_test_.cc b/googletest/test/gtest_xml_outfile2_test_.cc index afaf15a5dc32..f9a2a6e9846d 100644 --- a/googletest/test/gtest_xml_outfile2_test_.cc +++ b/googletest/test/gtest_xml_outfile2_test_.cc @@ -34,12 +34,8 @@ class PropertyTwo : public testing::Test { protected: - virtual void SetUp() { - RecordProperty("SetUpProp", 2); - } - virtual void TearDown() { - RecordProperty("TearDownProp", 2); - } + void SetUp() override { RecordProperty("SetUpProp", 2); } + void TearDown() override { RecordProperty("TearDownProp", 2); } }; TEST_F(PropertyTwo, TestSomeProperties) { diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py index 2c031ff8dba5..e093f6f05e3e 100755 --- a/googletest/test/gtest_xml_outfiles_test.py +++ b/googletest/test/gtest_xml_outfiles_test.py @@ -42,8 +42,8 @@ GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_" EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> - <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne"> + <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne"> <properties> <property name="SetUpProp" value="1"/> <property name="TestSomeProperty" value="1"/> @@ -56,8 +56,8 @@ EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> - <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo"> + <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo"> <properties> <property name="SetUpProp" value="2"/> <property name="TestSomeProperty" value="2"/> @@ -111,11 +111,6 @@ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase): self.assert_(p.exited) self.assertEquals(0, p.exit_code) - # FIXME: libtool causes the built test binary to be - # named lt-gtest_xml_outfiles_test_ instead of - # gtest_xml_outfiles_test_. To account for this possibility, we - # allow both names in the following code. We should remove this - # when libtool replacement tool is ready. output_file_name1 = test_name + ".xml" output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py index faedd4e6ce72..63b1af0b6c10 100755 --- a/googletest/test/gtest_xml_output_unittest.py +++ b/googletest/test/gtest_xml_output_unittest.py @@ -65,21 +65,21 @@ else: sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> -<testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> - <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> +<testsuites tests="24" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> + <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> </testsuite> - <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*"> - <testcase name="Fails" status="run" time="*" classname="FailedTest"> + <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="FailedTest"> <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected equality of these values: 1 2%(stack)s]]></failure> </testcase> </testsuite> - <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*"> - <testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/> - <testcase name="Fails" status="run" time="*" classname="MixedResultTest"> + <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*" timestamp="*"> + <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/> + <testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"> <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected equality of these values: 1 @@ -89,109 +89,114 @@ Expected equality of these values: 2 3%(stack)s]]></failure> </testcase> - <testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/> + <testcase name="DISABLED_test" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/> </testsuite> - <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*"> - <testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest"> + <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="OutputsCData" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest"> <failure message="gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure> </testcase> </testsuite> - <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*"> - <testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest"> + <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="InvalidCharactersInMessage" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest"> <failure message="gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed Invalid characters in brackets []%(stack)s]]></failure> </testcase> </testsuite> - <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*"> - <testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/> + <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*" timestamp="*"> + <testcase name="DISABLED_test_not_run" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/> </testsuite> - <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" SetUpTestCase="yes" TearDownTestCase="aye"> - <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest"> + <testsuite name="SkippedTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"/> + </testsuite> + <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye"> + <testcase name="OneProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_1" value="1"/> </properties> </testcase> - <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest"> + <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_int" value="1"/> </properties> </testcase> - <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest"> + <testcase name="ThreeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_1" value="1"/> <property name="key_2" value="2"/> <property name="key_3" value="3"/> </properties> </testcase> - <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest"> + <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> <properties> <property name="key_1" value="2"/> </properties> </testcase> </testsuite> - <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*"> - <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest"> + <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="RecordProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> <properties> <property name="key" value="1"/> </properties> </testcase> - <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest"> + <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> <properties> <property name="key_for_utility_int" value="1"/> </properties> </testcase> - <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest"> + <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest"> <properties> <property name="key_for_utility_string" value="1"/> </properties> </testcase> </testsuite> - <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*"> - <testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> - <testcase name="HasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> - <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> - <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> + <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="HasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> + <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> </testsuite> - <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/0" /> + <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" /> </testsuite> - <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/1" /> + <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" /> </testsuite> - <testsuite name="Single/TypeParameterizedTestCase/0" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/0" /> + <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" /> </testsuite> - <testsuite name="Single/TypeParameterizedTestCase/1" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/1" /> + <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" /> </testsuite> -</testsuites>""" % {'stack': STACK_TRACE_TEMPLATE} +</testsuites>""" % { + 'stack': STACK_TRACE_TEMPLATE +} EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" - errors="0" time="*"> - <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> + errors="0" time="*" timestamp="*"> + <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> </testsuite> </testsuites>""" EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> - <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> + <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/> </testsuite> - <testsuite name="NoFixtureTest" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest"> - <properties> - <property name="key" value="1"/> - </properties> - </testcase> + <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye"> + <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest"> + <properties> + <property name="key_1" value="2"/> + </properties> + </testcase> </testsuite> - <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*"> - <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> + <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*"> + <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" /> </testsuite> </testsuites>""" @@ -266,7 +271,8 @@ class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): 'gtest_no_test_unittest') try: os.remove(output_file) - except OSError, e: + except OSError: + e = sys.exc_info()[1] if e.errno != errno.ENOENT: raise diff --git a/googletest/test/gtest_xml_output_unittest_.cc b/googletest/test/gtest_xml_output_unittest_.cc index 2ee8838005ee..c95fd66cfaef 100644 --- a/googletest/test/gtest_xml_output_unittest_.cc +++ b/googletest/test/gtest_xml_output_unittest_.cc @@ -67,6 +67,13 @@ TEST_F(DisabledTest, DISABLED_test_not_run) { FAIL() << "Unexpected failure: Disabled test should not be run"; } +class SkippedTest : public Test { +}; + +TEST_F(SkippedTest, Skipped) { + GTEST_SKIP(); +} + TEST(MixedResultTest, Succeeds) { EXPECT_EQ(1, 1); ASSERT_EQ(1, 1); @@ -94,8 +101,10 @@ TEST(InvalidCharactersTest, InvalidCharactersInMessage) { class PropertyRecordingTest : public Test { public: - static void SetUpTestCase() { RecordProperty("SetUpTestCase", "yes"); } - static void TearDownTestCase() { RecordProperty("TearDownTestCase", "aye"); } + static void SetUpTestSuite() { RecordProperty("SetUpTestSuite", "yes"); } + static void TearDownTestSuite() { + RecordProperty("TearDownTestSuite", "aye"); + } }; TEST_F(PropertyRecordingTest, OneProperty) { @@ -143,28 +152,28 @@ TEST(NoFixtureTest, ExternalUtilityThatCallsRecordStringValuedProperty) { class ValueParamTest : public TestWithParam<int> {}; TEST_P(ValueParamTest, HasValueParamAttribute) {} TEST_P(ValueParamTest, AnotherTestThatHasValueParamAttribute) {} -INSTANTIATE_TEST_CASE_P(Single, ValueParamTest, Values(33, 42)); +INSTANTIATE_TEST_SUITE_P(Single, ValueParamTest, Values(33, 42)); #if GTEST_HAS_TYPED_TEST // Verifies that the type parameter name is output in the 'type_param' // XML attribute for typed tests. template <typename T> class TypedTest : public Test {}; typedef testing::Types<int, long> TypedTestTypes; -TYPED_TEST_CASE(TypedTest, TypedTestTypes); +TYPED_TEST_SUITE(TypedTest, TypedTestTypes); TYPED_TEST(TypedTest, HasTypeParamAttribute) {} #endif #if GTEST_HAS_TYPED_TEST_P // Verifies that the type parameter name is output in the 'type_param' // XML attribute for type-parameterized tests. -template <typename T> class TypeParameterizedTestCase : public Test {}; -TYPED_TEST_CASE_P(TypeParameterizedTestCase); -TYPED_TEST_P(TypeParameterizedTestCase, HasTypeParamAttribute) {} -REGISTER_TYPED_TEST_CASE_P(TypeParameterizedTestCase, HasTypeParamAttribute); -typedef testing::Types<int, long> TypeParameterizedTestCaseTypes; -INSTANTIATE_TYPED_TEST_CASE_P(Single, - TypeParameterizedTestCase, - TypeParameterizedTestCaseTypes); +template <typename T> +class TypeParameterizedTestSuite : public Test {}; +TYPED_TEST_SUITE_P(TypeParameterizedTestSuite); +TYPED_TEST_P(TypeParameterizedTestSuite, HasTypeParamAttribute) {} +REGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, HasTypeParamAttribute); +typedef testing::Types<int, long> TypeParameterizedTestSuiteTypes; // NOLINT +INSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite, + TypeParameterizedTestSuiteTypes); #endif int main(int argc, char** argv) { diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py index 1e0358592fb0..9914a49ec188 100755 --- a/googletest/test/gtest_xml_test_utils.py +++ b/googletest/test/gtest_xml_test_utils.py @@ -94,7 +94,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): self.assertEquals( len(expected_children), len(actual_children), 'number of child elements differ in element ' + actual_node.tagName) - for child_id, child in expected_children.iteritems(): + for child_id, child in expected_children.items(): self.assert_(child_id in actual_children, '<%s> is not in <%s> (in element %s)' % (child_id, actual_children, actual_node.tagName)) @@ -169,7 +169,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): * The stack traces are removed. """ - if element.tagName == 'testsuites': + if element.tagName in ('testsuites', 'testsuite', 'testcase'): timestamp = element.getAttributeNode('timestamp') timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$', '*', timestamp.value) |