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 // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
794 using NoTests
= ParamTest
;
795 INSTANTIATE_TEST_SUITE_P(ThisIsOdd
, NoTests
, ::testing::Values("Hello"));
797 // fails under kErrorOnUninstantiatedParameterizedTest=true
798 class DetectNotInstantiatedTest
: public testing::TestWithParam
<int> {};
799 TEST_P(DetectNotInstantiatedTest
, Used
) { }
801 // This would make the test failure from the above go away.
802 // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
804 // This #ifdef block tests the output of typed tests.
805 #if GTEST_HAS_TYPED_TEST
807 template <typename T
>
808 class TypedTest
: public testing::Test
{
811 TYPED_TEST_SUITE(TypedTest
, testing::Types
<int>);
813 TYPED_TEST(TypedTest
, Success
) {
814 EXPECT_EQ(0, TypeParam());
817 TYPED_TEST(TypedTest
, Failure
) {
818 EXPECT_EQ(1, TypeParam()) << "Expected failure";
821 typedef testing::Types
<char, int> TypesForTestWithNames
;
823 template <typename T
>
824 class TypedTestWithNames
: public testing::Test
{};
826 class TypedTestNames
{
828 template <typename T
>
829 static std::string
GetName(int i
) {
830 if (std::is_same
<T
, char>::value
)
831 return std::string("char") + ::testing::PrintToString(i
);
832 if (std::is_same
<T
, int>::value
)
833 return std::string("int") + ::testing::PrintToString(i
);
837 TYPED_TEST_SUITE(TypedTestWithNames
, TypesForTestWithNames
, TypedTestNames
);
839 TYPED_TEST(TypedTestWithNames
, Success
) {}
841 TYPED_TEST(TypedTestWithNames
, Failure
) { FAIL(); }
843 #endif // GTEST_HAS_TYPED_TEST
845 // This #ifdef block tests the output of type-parameterized tests.
846 #if GTEST_HAS_TYPED_TEST_P
848 template <typename T
>
849 class TypedTestP
: public testing::Test
{
852 TYPED_TEST_SUITE_P(TypedTestP
);
854 TYPED_TEST_P(TypedTestP
, Success
) {
855 EXPECT_EQ(0U, TypeParam());
858 TYPED_TEST_P(TypedTestP
, Failure
) {
859 EXPECT_EQ(1U, TypeParam()) << "Expected failure";
862 REGISTER_TYPED_TEST_SUITE_P(TypedTestP
, Success
, Failure
);
864 typedef testing::Types
<unsigned char, unsigned int> UnsignedTypes
;
865 INSTANTIATE_TYPED_TEST_SUITE_P(Unsigned
, TypedTestP
, UnsignedTypes
);
867 class TypedTestPNames
{
869 template <typename T
>
870 static std::string
GetName(int i
) {
871 if (std::is_same
<T
, unsigned char>::value
) {
872 return std::string("unsignedChar") + ::testing::PrintToString(i
);
874 if (std::is_same
<T
, unsigned int>::value
) {
875 return std::string("unsignedInt") + ::testing::PrintToString(i
);
880 INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName
, TypedTestP
, UnsignedTypes
,
883 template <typename T
>
884 class DetectNotInstantiatedTypesTest
: public testing::Test
{};
885 TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest
);
886 TYPED_TEST_P(DetectNotInstantiatedTypesTest
, Used
) {
887 TypeParam instantiate
;
890 REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest
, Used
);
892 // kErrorOnUninstantiatedTypeParameterizedTest=true would make the above fail.
893 // Adding the following would make that test failure go away.
895 // typedef ::testing::Types<char, int, unsigned int> MyTypes;
896 // INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);
898 #endif // GTEST_HAS_TYPED_TEST_P
900 #if GTEST_HAS_DEATH_TEST
902 // We rely on the golden file to verify that tests whose test case
903 // name ends with DeathTest are run first.
905 TEST(ADeathTest
, ShouldRunFirst
) {
908 # if GTEST_HAS_TYPED_TEST
910 // We rely on the golden file to verify that typed tests whose test
911 // case name ends with DeathTest are run first.
913 template <typename T
>
914 class ATypedDeathTest
: public testing::Test
{
917 typedef testing::Types
<int, double> NumericTypes
;
918 TYPED_TEST_SUITE(ATypedDeathTest
, NumericTypes
);
920 TYPED_TEST(ATypedDeathTest
, ShouldRunFirst
) {
923 # endif // GTEST_HAS_TYPED_TEST
925 # if GTEST_HAS_TYPED_TEST_P
928 // We rely on the golden file to verify that type-parameterized tests
929 // whose test case name ends with DeathTest are run first.
931 template <typename T
>
932 class ATypeParamDeathTest
: public testing::Test
{
935 TYPED_TEST_SUITE_P(ATypeParamDeathTest
);
937 TYPED_TEST_P(ATypeParamDeathTest
, ShouldRunFirst
) {
940 REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest
, ShouldRunFirst
);
942 INSTANTIATE_TYPED_TEST_SUITE_P(My
, ATypeParamDeathTest
, NumericTypes
);
944 # endif // GTEST_HAS_TYPED_TEST_P
946 #endif // GTEST_HAS_DEATH_TEST
948 // Tests various failure conditions of
949 // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
950 class ExpectFailureTest
: public testing::Test
{
951 public: // Must be public and not protected due to a bug in g++ 3.4.2.
956 static void AddFailure(FailureMode failure
) {
957 if (failure
== FATAL_FAILURE
) {
958 FAIL() << "Expected fatal failure.";
960 ADD_FAILURE() << "Expected non-fatal failure.";
965 TEST_F(ExpectFailureTest
, ExpectFatalFailure
) {
966 // Expected fatal failure, but succeeds.
967 printf("(expecting 1 failure)\n");
968 EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
969 // Expected fatal failure, but got a non-fatal failure.
970 printf("(expecting 1 failure)\n");
971 EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE
), "Expected non-fatal "
974 printf("(expecting 1 failure)\n");
975 EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE
), "Some other fatal failure "
979 TEST_F(ExpectFailureTest
, ExpectNonFatalFailure
) {
980 // Expected non-fatal failure, but succeeds.
981 printf("(expecting 1 failure)\n");
982 EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
983 // Expected non-fatal failure, but got a fatal failure.
984 printf("(expecting 1 failure)\n");
985 EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE
), "Expected fatal failure.");
987 printf("(expecting 1 failure)\n");
988 EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE
), "Some other non-fatal "
992 #if GTEST_IS_THREADSAFE
994 class ExpectFailureWithThreadsTest
: public ExpectFailureTest
{
996 static void AddFailureInOtherThread(FailureMode failure
) {
997 ThreadWithParam
<FailureMode
> thread(&AddFailure
, failure
, nullptr);
1002 TEST_F(ExpectFailureWithThreadsTest
, ExpectFatalFailure
) {
1003 // We only intercept the current thread.
1004 printf("(expecting 2 failures)\n");
1005 EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE
),
1006 "Expected fatal failure.");
1009 TEST_F(ExpectFailureWithThreadsTest
, ExpectNonFatalFailure
) {
1010 // We only intercept the current thread.
1011 printf("(expecting 2 failures)\n");
1012 EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE
),
1013 "Expected non-fatal failure.");
1016 typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest
;
1018 // Tests that the ScopedFakeTestPartResultReporter only catches failures from
1019 // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
1020 TEST_F(ScopedFakeTestPartResultReporterTest
, InterceptOnlyCurrentThread
) {
1021 printf("(expecting 2 failures)\n");
1022 TestPartResultArray results
;
1024 ScopedFakeTestPartResultReporter
reporter(
1025 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD
,
1027 AddFailureInOtherThread(FATAL_FAILURE
);
1028 AddFailureInOtherThread(NONFATAL_FAILURE
);
1030 // The two failures should not have been intercepted.
1031 EXPECT_EQ(0, results
.size()) << "This shouldn't fail.";
1034 #endif // GTEST_IS_THREADSAFE
1036 TEST_F(ExpectFailureTest
, ExpectFatalFailureOnAllThreads
) {
1037 // Expected fatal failure, but succeeds.
1038 printf("(expecting 1 failure)\n");
1039 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
1040 // Expected fatal failure, but got a non-fatal failure.
1041 printf("(expecting 1 failure)\n");
1042 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE
),
1043 "Expected non-fatal failure.");
1045 printf("(expecting 1 failure)\n");
1046 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE
),
1047 "Some other fatal failure expected.");
1050 TEST_F(ExpectFailureTest
, ExpectNonFatalFailureOnAllThreads
) {
1051 // Expected non-fatal failure, but succeeds.
1052 printf("(expecting 1 failure)\n");
1053 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal "
1055 // Expected non-fatal failure, but got a fatal failure.
1056 printf("(expecting 1 failure)\n");
1057 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE
),
1058 "Expected fatal failure.");
1060 printf("(expecting 1 failure)\n");
1061 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE
),
1062 "Some other non-fatal failure.");
1065 class DynamicFixture
: public testing::Test
{
1067 DynamicFixture() { printf("DynamicFixture()\n"); }
1068 ~DynamicFixture() override
{ printf("~DynamicFixture()\n"); }
1069 void SetUp() override
{ printf("DynamicFixture::SetUp\n"); }
1070 void TearDown() override
{ printf("DynamicFixture::TearDown\n"); }
1072 static void SetUpTestSuite() { printf("DynamicFixture::SetUpTestSuite\n"); }
1073 static void TearDownTestSuite() {
1074 printf("DynamicFixture::TearDownTestSuite\n");
1078 template <bool Pass
>
1079 class DynamicTest
: public DynamicFixture
{
1081 void TestBody() override
{ EXPECT_TRUE(Pass
); }
1084 auto dynamic_test
= (
1085 // Register two tests with the same fixture correctly.
1086 testing::RegisterTest(
1087 "DynamicFixture", "DynamicTestPass", nullptr, nullptr, __FILE__
,
1088 __LINE__
, []() -> DynamicFixture
* { return new DynamicTest
<true>; }),
1089 testing::RegisterTest(
1090 "DynamicFixture", "DynamicTestFail", nullptr, nullptr, __FILE__
,
1091 __LINE__
, []() -> DynamicFixture
* { return new DynamicTest
<false>; }),
1093 // Register the same fixture with another name. That's fine.
1094 testing::RegisterTest(
1095 "DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr,
1097 []() -> DynamicFixture
* { return new DynamicTest
<true>; }),
1099 // Register two tests with the same fixture incorrectly.
1100 testing::RegisterTest(
1101 "BadDynamicFixture1", "FixtureBase", nullptr, nullptr, __FILE__
,
1102 __LINE__
, []() -> DynamicFixture
* { return new DynamicTest
<true>; }),
1103 testing::RegisterTest(
1104 "BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__
, __LINE__
,
1105 []() -> testing::Test
* { return new DynamicTest
<true>; }),
1107 // Register two tests with the same fixture incorrectly by ommiting the
1109 testing::RegisterTest(
1110 "BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__
,
1111 __LINE__
, []() -> DynamicFixture
* { return new DynamicTest
<true>; }),
1112 testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr,
1114 []() { return new DynamicTest
<true>; }));
1116 // Two test environments for testing testing::AddGlobalTestEnvironment().
1118 class FooEnvironment
: public testing::Environment
{
1120 void SetUp() override
{ printf("%s", "FooEnvironment::SetUp() called.\n"); }
1122 void TearDown() override
{
1123 printf("%s", "FooEnvironment::TearDown() called.\n");
1124 FAIL() << "Expected fatal failure.";
1128 class BarEnvironment
: public testing::Environment
{
1130 void SetUp() override
{ printf("%s", "BarEnvironment::SetUp() called.\n"); }
1132 void TearDown() override
{
1133 printf("%s", "BarEnvironment::TearDown() called.\n");
1134 ADD_FAILURE() << "Expected non-fatal failure.";
1138 // The main function.
1140 // The idea is to use Google Test to run all the tests we have defined (some
1141 // of them are intended to fail), and then compare the test results
1142 // with the "golden" file.
1143 int main(int argc
, char **argv
) {
1144 testing::GTEST_FLAG(print_time
) = false;
1146 // We just run the tests, knowing some of them are intended to fail.
1147 // We will use a separate Python script to compare the output of
1148 // this program with the golden file.
1150 // It's hard to test InitGoogleTest() directly, as it has many
1151 // global side effects. The following line serves as a sanity test
1153 testing::InitGoogleTest(&argc
, argv
);
1154 bool internal_skip_environment_and_ad_hoc_tests
=
1155 std::count(argv
, argv
+ argc
,
1156 std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
1158 #if GTEST_HAS_DEATH_TEST
1159 if (testing::internal::GTEST_FLAG(internal_run_death_test
) != "") {
1160 // Skip the usual output capturing if we're running as the child
1161 // process of an threadsafe-style death test.
1162 # if GTEST_OS_WINDOWS
1163 posix::FReopen("nul:", "w", stdout
);
1165 posix::FReopen("/dev/null", "w", stdout
);
1166 # endif // GTEST_OS_WINDOWS
1167 return RUN_ALL_TESTS();
1169 #endif // GTEST_HAS_DEATH_TEST
1171 if (internal_skip_environment_and_ad_hoc_tests
)
1172 return RUN_ALL_TESTS();
1174 // Registers two global test environments.
1175 // The golden file verifies that they are set up in the order they
1176 // are registered, and torn down in the reverse order.
1177 testing::AddGlobalTestEnvironment(new FooEnvironment
);
1178 testing::AddGlobalTestEnvironment(new BarEnvironment
);
1180 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
1182 return RunAllTests();