1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // The purpose of this file is to generate Google Test output under
31 // various conditions. The output will then be verified by
32 // googletest-output-test.py to ensure that Google Test generates the
33 // desired messages. Therefore, most tests in this file are MEANT TO
36 #include "gtest/gtest-spi.h"
37 #include "gtest/gtest.h"
38 #include "src/gtest-internal-inl.h"
43 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
46 #if GTEST_IS_THREADSAFE
47 using testing::ScopedFakeTestPartResultReporter;
48 using testing::TestPartResultArray;
50 using testing::internal::Notification;
51 using testing::internal::ThreadWithParam;
54 namespace posix = ::testing::internal::posix;
56 // Tests catching fatal failures.
58 // A subroutine used by the following test.
63 // This function calls a test subroutine, catches the fatal failure it
64 // generates, and then returns early.
65 void TryTestSubroutine() {
66 // Calls a subrountine that yields a fatal failure.
69 // Catches the fatal failure and aborts the test.
71 // The testing::Test:: prefix is necessary when calling
72 // HasFatalFailure() outside of a TEST, TEST_F, or test fixture.
73 if (testing::Test::HasFatalFailure()) return;
75 // If we get here, something is wrong.
76 FAIL() << "This should never be reached.";
79 TEST(PassingTest, PassingTest1) {
82 TEST(PassingTest, PassingTest2) {
85 // Tests that parameters of failing parameterized tests are printed in the
86 // failing test summary.
87 class FailingParamTest : public testing::TestWithParam<int> {};
89 TEST_P(FailingParamTest, Fails) {
90 EXPECT_EQ(1, GetParam());
93 // This generates a test which will fail. Google Test is expected to print
94 // its parameter when it outputs the list of all failed tests.
95 INSTANTIATE_TEST_SUITE_P(PrintingFailingParams,
99 // Tests that an empty value for the test suite basename yields just
100 // the test name without any prior /
101 class EmptyBasenameParamInst : public testing::TestWithParam<int> {};
103 TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); }
105 INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1));
107 static const char kGoldenString[] = "\"Line\0 1\"\nLine 2";
109 TEST(NonfatalFailureTest, EscapesStringOperands) {
110 std::string actual = "actual \"string\"";
111 EXPECT_EQ(kGoldenString, actual);
113 const char* golden = kGoldenString;
114 EXPECT_EQ(golden, actual);
117 TEST(NonfatalFailureTest, DiffForLongStrings) {
118 std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1);
119 EXPECT_EQ(golden_str, "Line 2");
122 // Tests catching a fatal failure in a subroutine.
123 TEST(FatalFailureTest, FatalFailureInSubroutine) {
124 printf("(expecting a failure that x should be 1)\n");
129 // Tests catching a fatal failure in a nested subroutine.
130 TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
131 printf("(expecting a failure that x should be 1)\n");
133 // Calls a subrountine that yields a fatal failure.
136 // Catches the fatal failure and aborts the test.
138 // When calling HasFatalFailure() inside a TEST, TEST_F, or test
139 // fixture, the testing::Test:: prefix is not needed.
140 if (HasFatalFailure()) return;
142 // If we get here, something is wrong.
143 FAIL() << "This should never be reached.";
146 // Tests HasFatalFailure() after a failed EXPECT check.
147 TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
148 printf("(expecting a failure on false)\n");
149 EXPECT_TRUE(false); // Generates a nonfatal failure
150 ASSERT_FALSE(HasFatalFailure()); // This should succeed.
153 // Tests interleaving user logging and Google Test assertions.
154 TEST(LoggingTest, InterleavingLoggingAndAssertions) {
155 static const int a[4] = {
159 printf("(expecting 2 failures on (3) >= (a[i]))\n");
160 for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) {
161 printf("i == %d\n", i);
166 // Tests the SCOPED_TRACE macro.
168 // A helper function for testing SCOPED_TRACE.
169 void SubWithoutTrace(int n) {
174 // Another helper function for testing SCOPED_TRACE.
175 void SubWithTrace(int n) {
176 SCOPED_TRACE(testing::Message() << "n = " << n);
181 TEST(SCOPED_TRACETest, AcceptedValues) {
182 SCOPED_TRACE("literal string");
183 SCOPED_TRACE(std::string("std::string"));
184 SCOPED_TRACE(1337); // streamable type
185 const char* null_value = nullptr;
186 SCOPED_TRACE(null_value);
188 ADD_FAILURE() << "Just checking that all these values work fine.";
191 // Tests that SCOPED_TRACE() obeys lexical scopes.
192 TEST(SCOPED_TRACETest, ObeysScopes) {
193 printf("(expected to fail)\n");
195 // There should be no trace before SCOPED_TRACE() is invoked.
196 ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
199 SCOPED_TRACE("Expected trace");
200 // After SCOPED_TRACE(), a failure in the current scope should contain
202 ADD_FAILURE() << "This failure is expected, and should have a trace.";
205 // Once the control leaves the scope of the SCOPED_TRACE(), there
206 // should be no trace again.
207 ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
210 // Tests that SCOPED_TRACE works inside a loop.
211 TEST(SCOPED_TRACETest, WorksInLoop) {
212 printf("(expected to fail)\n");
214 for (int i = 1; i <= 2; i++) {
215 SCOPED_TRACE(testing::Message() << "i = " << i);
221 // Tests that SCOPED_TRACE works in a subroutine.
222 TEST(SCOPED_TRACETest, WorksInSubroutine) {
223 printf("(expected to fail)\n");
229 // Tests that SCOPED_TRACE can be nested.
230 TEST(SCOPED_TRACETest, CanBeNested) {
231 printf("(expected to fail)\n");
233 SCOPED_TRACE(""); // A trace without a message.
238 // Tests that multiple SCOPED_TRACEs can be used in the same scope.
239 TEST(SCOPED_TRACETest, CanBeRepeated) {
240 printf("(expected to fail)\n");
244 << "This failure is expected, and should contain trace point A.";
248 << "This failure is expected, and should contain trace point A and B.";
252 ADD_FAILURE() << "This failure is expected, and should "
253 << "contain trace point A, B, and C.";
257 ADD_FAILURE() << "This failure is expected, and should "
258 << "contain trace point A, B, and D.";
261 #if GTEST_IS_THREADSAFE
262 // Tests that SCOPED_TRACE()s can be used concurrently from multiple
263 // threads. Namely, an assertion should be affected by
264 // SCOPED_TRACE()s in its own thread only.
266 // Here's the sequence of actions that happen in the test:
268 // Thread A (main) | Thread B (spawned)
269 // ===============================|================================
271 // -------------------------------+--------------------------------
272 // waits for n1 | SCOPED_TRACE("Trace B");
273 // | generates failure #1
275 // -------------------------------+--------------------------------
276 // SCOPED_TRACE("Trace A"); | waits for n2
277 // generates failure #2 |
279 // -------------------------------|--------------------------------
280 // waits for n3 | generates failure #3
282 // | generates failure #4
284 // -------------------------------|--------------------------------
285 // generates failure #5 | finishes
287 // generates failure #6 |
288 // -------------------------------|--------------------------------
289 // waits for thread B to finish |
297 static void ThreadWithScopedTrace(CheckPoints* check_points) {
299 SCOPED_TRACE("Trace B");
301 << "Expected failure #1 (in thread B, only trace B alive).";
302 check_points->n1.Notify();
303 check_points->n2.WaitForNotification();
306 << "Expected failure #3 (in thread B, trace A & B both alive).";
307 } // Trace B dies here.
309 << "Expected failure #4 (in thread B, only trace A alive).";
310 check_points->n3.Notify();
313 TEST(SCOPED_TRACETest, WorksConcurrently) {
314 printf("(expecting 6 failures)\n");
316 CheckPoints check_points;
317 ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace, &check_points,
319 check_points.n1.WaitForNotification();
322 SCOPED_TRACE("Trace A");
324 << "Expected failure #2 (in thread A, trace A & B both alive).";
325 check_points.n2.Notify();
326 check_points.n3.WaitForNotification();
329 << "Expected failure #5 (in thread A, only trace A alive).";
330 } // Trace A dies here.
332 << "Expected failure #6 (in thread A, no trace alive).";
335 #endif // GTEST_IS_THREADSAFE
337 // Tests basic functionality of the ScopedTrace utility (most of its features
338 // are already tested in SCOPED_TRACETest).
339 TEST(ScopedTraceTest, WithExplicitFileAndLine) {
340 testing::ScopedTrace trace("explicit_file.cc", 123, "expected trace message");
341 ADD_FAILURE() << "Check that the trace is attached to a particular location.";
344 TEST(DisabledTestsWarningTest,
345 DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {
346 // This test body is intentionally empty. Its sole purpose is for
347 // verifying that the --gtest_also_run_disabled_tests flag
348 // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of
352 // Tests using assertions outside of TEST and TEST_F.
354 // This function creates two failures intentionally.
356 printf("The non-test part of the code is expected to have 2 failures.\n\n");
361 // Runs all TESTs, all TEST_Fs, and the ad hoc test.
364 return RUN_ALL_TESTS();
367 // Tests non-fatal failures in the fixture constructor.
368 class NonFatalFailureInFixtureConstructorTest : public testing::Test {
370 NonFatalFailureInFixtureConstructorTest() {
371 printf("(expecting 5 failures)\n");
372 ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
375 ~NonFatalFailureInFixtureConstructorTest() override {
376 ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
379 void SetUp() override { ADD_FAILURE() << "Expected failure #2, in SetUp()."; }
381 void TearDown() override {
382 ADD_FAILURE() << "Expected failure #4, in TearDown.";
386 TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
387 ADD_FAILURE() << "Expected failure #3, in the test body.";
390 // Tests fatal failures in the fixture constructor.
391 class FatalFailureInFixtureConstructorTest : public testing::Test {
393 FatalFailureInFixtureConstructorTest() {
394 printf("(expecting 2 failures)\n");
398 ~FatalFailureInFixtureConstructorTest() override {
399 ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
402 void SetUp() override {
403 ADD_FAILURE() << "UNEXPECTED failure in SetUp(). "
404 << "We should never get here, as the test fixture c'tor "
405 << "had a fatal failure.";
408 void TearDown() override {
409 ADD_FAILURE() << "UNEXPECTED failure in TearDown(). "
410 << "We should never get here, as the test fixture c'tor "
411 << "had a fatal failure.";
416 FAIL() << "Expected failure #1, in the test fixture c'tor.";
420 TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
421 ADD_FAILURE() << "UNEXPECTED failure in the test body. "
422 << "We should never get here, as the test fixture c'tor "
423 << "had a fatal failure.";
426 // Tests non-fatal failures in SetUp().
427 class NonFatalFailureInSetUpTest : public testing::Test {
429 ~NonFatalFailureInSetUpTest() override { Deinit(); }
431 void SetUp() override {
432 printf("(expecting 4 failures)\n");
433 ADD_FAILURE() << "Expected failure #1, in SetUp().";
436 void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
440 FAIL() << "Expected failure #4, in the test fixture d'tor.";
444 TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
445 FAIL() << "Expected failure #2, in the test function.";
448 // Tests fatal failures in SetUp().
449 class FatalFailureInSetUpTest : public testing::Test {
451 ~FatalFailureInSetUpTest() override { Deinit(); }
453 void SetUp() override {
454 printf("(expecting 3 failures)\n");
455 FAIL() << "Expected failure #1, in SetUp().";
458 void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
462 FAIL() << "Expected failure #3, in the test fixture d'tor.";
466 TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
467 FAIL() << "UNEXPECTED failure in the test function. "
468 << "We should never get here, as SetUp() failed.";
471 TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {
472 ADD_FAILURE_AT("foo.cc", 42) << "Expected nonfatal failure in foo.cc";
475 TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
476 GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc";
479 #if GTEST_IS_THREADSAFE
481 // A unary function that may die.
482 void DieIf(bool should_die) {
483 GTEST_CHECK_(!should_die) << " - death inside DieIf().";
486 // Tests running death tests in a multi-threaded context.
488 // Used for coordination between the main and the spawn thread.
489 struct SpawnThreadNotifications {
490 SpawnThreadNotifications() {}
492 Notification spawn_thread_started;
493 Notification spawn_thread_ok_to_terminate;
496 GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
499 // The function to be executed in the thread spawn by the
500 // MultipleThreads test (below).
501 static void ThreadRoutine(SpawnThreadNotifications* notifications) {
502 // Signals the main thread that this thread has started.
503 notifications->spawn_thread_started.Notify();
505 // Waits for permission to finish from the main thread.
506 notifications->spawn_thread_ok_to_terminate.WaitForNotification();
509 // This is a death-test test, but it's not named with a DeathTest
510 // suffix. It starts threads which might interfere with later
511 // death tests, so it must run after all other death tests.
512 class DeathTestAndMultiThreadsTest : public testing::Test {
514 // Starts a thread and waits for it to begin.
515 void SetUp() override {
516 thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
517 &ThreadRoutine, ¬ifications_, nullptr));
518 notifications_.spawn_thread_started.WaitForNotification();
520 // Tells the thread to finish, and reaps it.
521 // Depending on the version of the thread library in use,
522 // a manager thread might still be left running that will interfere
523 // with later death tests. This is unfortunate, but this class
524 // cleans up after itself as best it can.
525 void TearDown() override {
526 notifications_.spawn_thread_ok_to_terminate.Notify();
530 SpawnThreadNotifications notifications_;
531 std::unique_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
534 #endif // GTEST_IS_THREADSAFE
536 // The MixedUpTestSuiteTest test case verifies that Google Test will fail a
537 // test if it uses a different fixture class than what other tests in
538 // the same test case use. It deliberately contains two fixture
539 // classes with the same name but defined in different namespaces.
541 // The MixedUpTestSuiteWithSameTestNameTest test case verifies that
542 // when the user defines two tests with the same test case name AND
543 // same test name (but in different namespaces), the second test will
548 class MixedUpTestSuiteTest : public testing::Test {
551 TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
552 TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
554 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {
557 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
558 TheSecondTestWithThisNameShouldFail) {}
564 class MixedUpTestSuiteTest : public testing::Test {
567 // The following two tests are expected to fail. We rely on the
568 // golden file to check that Google Test generates the right error message.
569 TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}
570 TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {}
572 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {
575 // Expected to fail. We rely on the golden file to check that Google Test
576 // generates the right error message.
577 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
578 TheSecondTestWithThisNameShouldFail) {}
582 // The following two test cases verify that Google Test catches the user
583 // error of mixing TEST and TEST_F in the same test case. The first
584 // test case checks the scenario where TEST_F appears before TEST, and
585 // the second one checks where TEST appears before TEST_F.
587 class TEST_F_before_TEST_in_same_test_case : public testing::Test {
590 TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
592 // Expected to fail. We rely on the golden file to check that Google Test
593 // generates the right error message.
594 TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
596 class TEST_before_TEST_F_in_same_test_case : public testing::Test {
599 TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
601 // Expected to fail. We rely on the golden file to check that Google Test
602 // generates the right error message.
603 TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {
606 // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
607 int global_integer = 0;
609 // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
610 TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
612 EXPECT_NONFATAL_FAILURE({
613 EXPECT_EQ(1, global_integer) << "Expected non-fatal failure.";
614 }, "Expected non-fatal failure.");
617 // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
619 TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
623 EXPECT_NONFATAL_FAILURE({
624 EXPECT_EQ(m, n) << "Expected non-fatal failure.";
625 }, "Expected non-fatal failure.");
628 // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
629 // one non-fatal failure and no fatal failure.
630 TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
631 EXPECT_NONFATAL_FAILURE({
632 ADD_FAILURE() << "Expected non-fatal failure.";
633 }, "Expected non-fatal failure.");
636 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
637 // non-fatal failure.
638 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
639 printf("(expecting a failure)\n");
640 EXPECT_NONFATAL_FAILURE({
644 // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
645 // non-fatal failures.
646 TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
647 printf("(expecting a failure)\n");
648 EXPECT_NONFATAL_FAILURE({
649 ADD_FAILURE() << "Expected non-fatal failure 1.";
650 ADD_FAILURE() << "Expected non-fatal failure 2.";
654 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
656 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
657 printf("(expecting a failure)\n");
658 EXPECT_NONFATAL_FAILURE({
659 FAIL() << "Expected fatal failure.";
663 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
665 TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
666 printf("(expecting a failure)\n");
667 EXPECT_NONFATAL_FAILURE({
672 #if GTEST_HAS_EXCEPTIONS
674 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
676 TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
677 printf("(expecting a failure)\n");
679 EXPECT_NONFATAL_FAILURE({
682 } catch(int) { // NOLINT
686 #endif // GTEST_HAS_EXCEPTIONS
688 // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
689 TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
691 EXPECT_FATAL_FAILURE({
692 ASSERT_EQ(1, global_integer) << "Expected fatal failure.";
693 }, "Expected fatal failure.");
696 // Tests that EXPECT_FATAL_FAILURE() can reference local static
698 TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
701 EXPECT_FATAL_FAILURE({
702 ASSERT_EQ(0, n) << "Expected fatal failure.";
703 }, "Expected fatal failure.");
706 // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
707 // one fatal failure and no non-fatal failure.
708 TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
709 EXPECT_FATAL_FAILURE({
710 FAIL() << "Expected fatal failure.";
711 }, "Expected fatal failure.");
714 // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
716 TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
717 printf("(expecting a failure)\n");
718 EXPECT_FATAL_FAILURE({
722 // A helper for generating a fatal failure.
723 void FatalFailure() {
724 FAIL() << "Expected fatal failure.";
727 // Tests that EXPECT_FATAL_FAILURE() fails when there are two
729 TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
730 printf("(expecting a failure)\n");
731 EXPECT_FATAL_FAILURE({
737 // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
739 TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
740 printf("(expecting a failure)\n");
741 EXPECT_FATAL_FAILURE({
742 ADD_FAILURE() << "Expected non-fatal failure.";
746 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
748 TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
749 printf("(expecting a failure)\n");
750 EXPECT_FATAL_FAILURE({
755 #if GTEST_HAS_EXCEPTIONS
757 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
759 TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
760 printf("(expecting a failure)\n");
762 EXPECT_FATAL_FAILURE({
765 } catch(int) { // NOLINT
769 #endif // GTEST_HAS_EXCEPTIONS
771 // This #ifdef block tests the output of value-parameterized tests.
773 std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
777 class ParamTest : public testing::TestWithParam<std::string> {
780 TEST_P(ParamTest, Success) {
781 EXPECT_EQ("a", GetParam());
784 TEST_P(ParamTest, Failure) {
785 EXPECT_EQ("b", GetParam()) << "Expected failure";
788 INSTANTIATE_TEST_SUITE_P(PrintingStrings,
790 testing::Values(std::string("a")),
793 // This #ifdef block tests the output of typed tests.
794 #if GTEST_HAS_TYPED_TEST
796 template <typename T>
797 class TypedTest : public testing::Test {
800 TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
802 TYPED_TEST(TypedTest, Success) {
803 EXPECT_EQ(0, TypeParam());
806 TYPED_TEST(TypedTest, Failure) {
807 EXPECT_EQ(1, TypeParam()) << "Expected failure";
810 typedef testing::Types<char, int> TypesForTestWithNames;
812 template <typename T>
813 class TypedTestWithNames : public testing::Test {};
815 class TypedTestNames {
817 template <typename T>
818 static std::string GetName(int i) {
819 if (std::is_same<T, char>::value)
820 return std::string("char") + ::testing::PrintToString(i);
821 if (std::is_same<T, int>::value)
822 return std::string("int") + ::testing::PrintToString(i);
826 TYPED_TEST_SUITE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames);
828 TYPED_TEST(TypedTestWithNames, Success) {}
830 TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
832 #endif // GTEST_HAS_TYPED_TEST
834 // This #ifdef block tests the output of type-parameterized tests.
835 #if GTEST_HAS_TYPED_TEST_P
837 template <typename T>
838 class TypedTestP : public testing::Test {
841 TYPED_TEST_SUITE_P(TypedTestP);
843 TYPED_TEST_P(TypedTestP, Success) {
844 EXPECT_EQ(0U, TypeParam());
847 TYPED_TEST_P(TypedTestP, Failure) {
848 EXPECT_EQ(1U, TypeParam()) << "Expected failure";
851 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, Success, Failure);
853 typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
854 INSTANTIATE_TYPED_TEST_SUITE_P(Unsigned, TypedTestP, UnsignedTypes);
856 class TypedTestPNames {
858 template <typename T>
859 static std::string GetName(int i) {
860 if (std::is_same<T, unsigned char>::value) {
861 return std::string("unsignedChar") + ::testing::PrintToString(i);
863 if (std::is_same<T, unsigned int>::value) {
864 return std::string("unsignedInt") + ::testing::PrintToString(i);
869 INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
872 #endif // GTEST_HAS_TYPED_TEST_P
874 #if GTEST_HAS_DEATH_TEST
876 // We rely on the golden file to verify that tests whose test case
877 // name ends with DeathTest are run first.
879 TEST(ADeathTest, ShouldRunFirst) {
882 # if GTEST_HAS_TYPED_TEST
884 // We rely on the golden file to verify that typed tests whose test
885 // case name ends with DeathTest are run first.
887 template <typename T>
888 class ATypedDeathTest : public testing::Test {
891 typedef testing::Types<int, double> NumericTypes;
892 TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
894 TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {
897 # endif // GTEST_HAS_TYPED_TEST
899 # if GTEST_HAS_TYPED_TEST_P
902 // We rely on the golden file to verify that type-parameterized tests
903 // whose test case name ends with DeathTest are run first.
905 template <typename T>
906 class ATypeParamDeathTest : public testing::Test {
909 TYPED_TEST_SUITE_P(ATypeParamDeathTest);
911 TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {
914 REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
916 INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
918 # endif // GTEST_HAS_TYPED_TEST_P
920 #endif // GTEST_HAS_DEATH_TEST
922 // Tests various failure conditions of
923 // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
924 class ExpectFailureTest : public testing::Test {
925 public: // Must be public and not protected due to a bug in g++ 3.4.2.
930 static void AddFailure(FailureMode failure) {
931 if (failure == FATAL_FAILURE) {
932 FAIL() << "Expected fatal failure.";
934 ADD_FAILURE() << "Expected non-fatal failure.";
939 TEST_F(ExpectFailureTest, ExpectFatalFailure) {
940 // Expected fatal failure, but succeeds.
941 printf("(expecting 1 failure)\n");
942 EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
943 // Expected fatal failure, but got a non-fatal failure.
944 printf("(expecting 1 failure)\n");
945 EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal "
948 printf("(expecting 1 failure)\n");
949 EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure "
953 TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
954 // Expected non-fatal failure, but succeeds.
955 printf("(expecting 1 failure)\n");
956 EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
957 // Expected non-fatal failure, but got a fatal failure.
958 printf("(expecting 1 failure)\n");
959 EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
961 printf("(expecting 1 failure)\n");
962 EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal "
966 #if GTEST_IS_THREADSAFE
968 class ExpectFailureWithThreadsTest : public ExpectFailureTest {
970 static void AddFailureInOtherThread(FailureMode failure) {
971 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
976 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {
977 // We only intercept the current thread.
978 printf("(expecting 2 failures)\n");
979 EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),
980 "Expected fatal failure.");
983 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {
984 // We only intercept the current thread.
985 printf("(expecting 2 failures)\n");
986 EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),
987 "Expected non-fatal failure.");
990 typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
992 // Tests that the ScopedFakeTestPartResultReporter only catches failures from
993 // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
994 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {
995 printf("(expecting 2 failures)\n");
996 TestPartResultArray results;
998 ScopedFakeTestPartResultReporter reporter(
999 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
1001 AddFailureInOtherThread(FATAL_FAILURE);
1002 AddFailureInOtherThread(NONFATAL_FAILURE);
1004 // The two failures should not have been intercepted.
1005 EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
1008 #endif // GTEST_IS_THREADSAFE
1010 TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
1011 // Expected fatal failure, but succeeds.
1012 printf("(expecting 1 failure)\n");
1013 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
1014 // Expected fatal failure, but got a non-fatal failure.
1015 printf("(expecting 1 failure)\n");
1016 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
1017 "Expected non-fatal failure.");
1019 printf("(expecting 1 failure)\n");
1020 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
1021 "Some other fatal failure expected.");
1024 TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
1025 // Expected non-fatal failure, but succeeds.
1026 printf("(expecting 1 failure)\n");
1027 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal "
1029 // Expected non-fatal failure, but got a fatal failure.
1030 printf("(expecting 1 failure)\n");
1031 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
1032 "Expected fatal failure.");
1034 printf("(expecting 1 failure)\n");
1035 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
1036 "Some other non-fatal failure.");
1039 class DynamicFixture : public testing::Test {
1041 DynamicFixture() { printf("DynamicFixture()\n"); }
1042 ~DynamicFixture() override { printf("~DynamicFixture()\n"); }
1043 void SetUp() override { printf("DynamicFixture::SetUp\n"); }
1044 void TearDown() override { printf("DynamicFixture::TearDown\n"); }
1046 static void SetUpTestSuite() { printf("DynamicFixture::SetUpTestSuite\n"); }
1047 static void TearDownTestSuite() {
1048 printf("DynamicFixture::TearDownTestSuite\n");
1052 template <bool Pass>
1053 class DynamicTest : public DynamicFixture {
1055 void TestBody() override { EXPECT_TRUE(Pass); }
1058 auto dynamic_test = (
1059 // Register two tests with the same fixture correctly.
1060 testing::RegisterTest(
1061 "DynamicFixture", "DynamicTestPass", nullptr, nullptr, __FILE__,
1062 __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
1063 testing::RegisterTest(
1064 "DynamicFixture", "DynamicTestFail", nullptr, nullptr, __FILE__,
1065 __LINE__, []() -> DynamicFixture* { return new DynamicTest<false>; }),
1067 // Register the same fixture with another name. That's fine.
1068 testing::RegisterTest(
1069 "DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr,
1071 []() -> DynamicFixture* { return new DynamicTest<true>; }),
1073 // Register two tests with the same fixture incorrectly.
1074 testing::RegisterTest(
1075 "BadDynamicFixture1", "FixtureBase", nullptr, nullptr, __FILE__,
1076 __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
1077 testing::RegisterTest(
1078 "BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__,
1079 []() -> testing::Test* { return new DynamicTest<true>; }),
1081 // Register two tests with the same fixture incorrectly by ommiting the
1083 testing::RegisterTest(
1084 "BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__,
1085 __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
1086 testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr,
1088 []() { return new DynamicTest<true>; }));
1090 // Two test environments for testing testing::AddGlobalTestEnvironment().
1092 class FooEnvironment : public testing::Environment {
1094 void SetUp() override { printf("%s", "FooEnvironment::SetUp() called.\n"); }
1096 void TearDown() override {
1097 printf("%s", "FooEnvironment::TearDown() called.\n");
1098 FAIL() << "Expected fatal failure.";
1102 class BarEnvironment : public testing::Environment {
1104 void SetUp() override { printf("%s", "BarEnvironment::SetUp() called.\n"); }
1106 void TearDown() override {
1107 printf("%s", "BarEnvironment::TearDown() called.\n");
1108 ADD_FAILURE() << "Expected non-fatal failure.";
1112 // The main function.
1114 // The idea is to use Google Test to run all the tests we have defined (some
1115 // of them are intended to fail), and then compare the test results
1116 // with the "golden" file.
1117 int main(int argc, char **argv) {
1118 testing::GTEST_FLAG(print_time) = false;
1120 // We just run the tests, knowing some of them are intended to fail.
1121 // We will use a separate Python script to compare the output of
1122 // this program with the golden file.
1124 // It's hard to test InitGoogleTest() directly, as it has many
1125 // global side effects. The following line serves as a sanity test
1127 testing::InitGoogleTest(&argc, argv);
1128 bool internal_skip_environment_and_ad_hoc_tests =
1129 std::count(argv, argv + argc,
1130 std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
1132 #if GTEST_HAS_DEATH_TEST
1133 if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
1134 // Skip the usual output capturing if we're running as the child
1135 // process of an threadsafe-style death test.
1136 # if GTEST_OS_WINDOWS
1137 posix::FReopen("nul:", "w", stdout);
1139 posix::FReopen("/dev/null", "w", stdout);
1140 # endif // GTEST_OS_WINDOWS
1141 return RUN_ALL_TESTS();
1143 #endif // GTEST_HAS_DEATH_TEST
1145 if (internal_skip_environment_and_ad_hoc_tests)
1146 return RUN_ALL_TESTS();
1148 // Registers two global test environments.
1149 // The golden file verifies that they are set up in the order they
1150 // are registered, and torn down in the reverse order.
1151 testing::AddGlobalTestEnvironment(new FooEnvironment);
1152 testing::AddGlobalTestEnvironment(new BarEnvironment);
1154 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
1156 return RunAllTests();