Home | History | Annotate | Download | only in test
      1 // Copyright 2005, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      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
     13 // distribution.
     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.
     17 //
     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.
     29 //
     30 // A unit test for Google Test itself.  This verifies that the basic
     31 // constructs of Google Test work.
     32 //
     33 // Author: wan (at) google.com (Zhanyong Wan)
     34 
     35 #include "gtest/gtest-spi.h"
     36 #include "gtest/gtest.h"
     37 
     38 // Indicates that this translation unit is part of Google Test's
     39 // implementation.  It must come before gtest-internal-inl.h is
     40 // included, or there will be a compiler error.  This trick is to
     41 // prevent a user from accidentally including gtest-internal-inl.h in
     42 // his code.
     43 #define GTEST_IMPLEMENTATION_ 1
     44 #include "src/gtest-internal-inl.h"
     45 #undef GTEST_IMPLEMENTATION_
     46 
     47 #include <stdlib.h>
     48 
     49 #if GTEST_IS_THREADSAFE
     50 using testing::ScopedFakeTestPartResultReporter;
     51 using testing::TestPartResultArray;
     52 
     53 using testing::internal::Notification;
     54 using testing::internal::ThreadWithParam;
     55 #endif
     56 
     57 namespace posix = ::testing::internal::posix;
     58 using testing::internal::String;
     59 using testing::internal::scoped_ptr;
     60 
     61 // Tests catching fatal failures.
     62 
     63 // A subroutine used by the following test.
     64 void TestEq1(int x) {
     65   ASSERT_EQ(1, x);
     66 }
     67 
     68 // This function calls a test subroutine, catches the fatal failure it
     69 // generates, and then returns early.
     70 void TryTestSubroutine() {
     71   // Calls a subrountine that yields a fatal failure.
     72   TestEq1(2);
     73 
     74   // Catches the fatal failure and aborts the test.
     75   //
     76   // The testing::Test:: prefix is necessary when calling
     77   // HasFatalFailure() outside of a TEST, TEST_F, or test fixture.
     78   if (testing::Test::HasFatalFailure()) return;
     79 
     80   // If we get here, something is wrong.
     81   FAIL() << "This should never be reached.";
     82 }
     83 
     84 TEST(PassingTest, PassingTest1) {
     85 }
     86 
     87 TEST(PassingTest, PassingTest2) {
     88 }
     89 
     90 // Tests that parameters of failing parameterized tests are printed in the
     91 // failing test summary.
     92 class FailingParamTest : public testing::TestWithParam<int> {};
     93 
     94 TEST_P(FailingParamTest, Fails) {
     95   EXPECT_EQ(1, GetParam());
     96 }
     97 
     98 // This generates a test which will fail. Google Test is expected to print
     99 // its parameter when it outputs the list of all failed tests.
    100 INSTANTIATE_TEST_CASE_P(PrintingFailingParams,
    101                         FailingParamTest,
    102                         testing::Values(2));
    103 
    104 // Tests catching a fatal failure in a subroutine.
    105 TEST(FatalFailureTest, FatalFailureInSubroutine) {
    106   printf("(expecting a failure that x should be 1)\n");
    107 
    108   TryTestSubroutine();
    109 }
    110 
    111 // Tests catching a fatal failure in a nested subroutine.
    112 TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
    113   printf("(expecting a failure that x should be 1)\n");
    114 
    115   // Calls a subrountine that yields a fatal failure.
    116   TryTestSubroutine();
    117 
    118   // Catches the fatal failure and aborts the test.
    119   //
    120   // When calling HasFatalFailure() inside a TEST, TEST_F, or test
    121   // fixture, the testing::Test:: prefix is not needed.
    122   if (HasFatalFailure()) return;
    123 
    124   // If we get here, something is wrong.
    125   FAIL() << "This should never be reached.";
    126 }
    127 
    128 // Tests HasFatalFailure() after a failed EXPECT check.
    129 TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
    130   printf("(expecting a failure on false)\n");
    131   EXPECT_TRUE(false);  // Generates a nonfatal failure
    132   ASSERT_FALSE(HasFatalFailure());  // This should succeed.
    133 }
    134 
    135 // Tests interleaving user logging and Google Test assertions.
    136 TEST(LoggingTest, InterleavingLoggingAndAssertions) {
    137   static const int a[4] = {
    138     3, 9, 2, 6
    139   };
    140 
    141   printf("(expecting 2 failures on (3) >= (a[i]))\n");
    142   for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) {
    143     printf("i == %d\n", i);
    144     EXPECT_GE(3, a[i]);
    145   }
    146 }
    147 
    148 // Tests the SCOPED_TRACE macro.
    149 
    150 // A helper function for testing SCOPED_TRACE.
    151 void SubWithoutTrace(int n) {
    152   EXPECT_EQ(1, n);
    153   ASSERT_EQ(2, n);
    154 }
    155 
    156 // Another helper function for testing SCOPED_TRACE.
    157 void SubWithTrace(int n) {
    158   SCOPED_TRACE(testing::Message() << "n = " << n);
    159 
    160   SubWithoutTrace(n);
    161 }
    162 
    163 // Tests that SCOPED_TRACE() obeys lexical scopes.
    164 TEST(SCOPED_TRACETest, ObeysScopes) {
    165   printf("(expected to fail)\n");
    166 
    167   // There should be no trace before SCOPED_TRACE() is invoked.
    168   ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
    169 
    170   {
    171     SCOPED_TRACE("Expected trace");
    172     // After SCOPED_TRACE(), a failure in the current scope should contain
    173     // the trace.
    174     ADD_FAILURE() << "This failure is expected, and should have a trace.";
    175   }
    176 
    177   // Once the control leaves the scope of the SCOPED_TRACE(), there
    178   // should be no trace again.
    179   ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
    180 }
    181 
    182 // Tests that SCOPED_TRACE works inside a loop.
    183 TEST(SCOPED_TRACETest, WorksInLoop) {
    184   printf("(expected to fail)\n");
    185 
    186   for (int i = 1; i <= 2; i++) {
    187     SCOPED_TRACE(testing::Message() << "i = " << i);
    188 
    189     SubWithoutTrace(i);
    190   }
    191 }
    192 
    193 // Tests that SCOPED_TRACE works in a subroutine.
    194 TEST(SCOPED_TRACETest, WorksInSubroutine) {
    195   printf("(expected to fail)\n");
    196 
    197   SubWithTrace(1);
    198   SubWithTrace(2);
    199 }
    200 
    201 // Tests that SCOPED_TRACE can be nested.
    202 TEST(SCOPED_TRACETest, CanBeNested) {
    203   printf("(expected to fail)\n");
    204 
    205   SCOPED_TRACE("");  // A trace without a message.
    206 
    207   SubWithTrace(2);
    208 }
    209 
    210 // Tests that multiple SCOPED_TRACEs can be used in the same scope.
    211 TEST(SCOPED_TRACETest, CanBeRepeated) {
    212   printf("(expected to fail)\n");
    213 
    214   SCOPED_TRACE("A");
    215   ADD_FAILURE()
    216       << "This failure is expected, and should contain trace point A.";
    217 
    218   SCOPED_TRACE("B");
    219   ADD_FAILURE()
    220       << "This failure is expected, and should contain trace point A and B.";
    221 
    222   {
    223     SCOPED_TRACE("C");
    224     ADD_FAILURE() << "This failure is expected, and should "
    225                   << "contain trace point A, B, and C.";
    226   }
    227 
    228   SCOPED_TRACE("D");
    229   ADD_FAILURE() << "This failure is expected, and should "
    230                 << "contain trace point A, B, and D.";
    231 }
    232 
    233 #if GTEST_IS_THREADSAFE
    234 // Tests that SCOPED_TRACE()s can be used concurrently from multiple
    235 // threads.  Namely, an assertion should be affected by
    236 // SCOPED_TRACE()s in its own thread only.
    237 
    238 // Here's the sequence of actions that happen in the test:
    239 //
    240 //   Thread A (main)                | Thread B (spawned)
    241 //   ===============================|================================
    242 //   spawns thread B                |
    243 //   -------------------------------+--------------------------------
    244 //   waits for n1                   | SCOPED_TRACE("Trace B");
    245 //                                  | generates failure #1
    246 //                                  | notifies n1
    247 //   -------------------------------+--------------------------------
    248 //   SCOPED_TRACE("Trace A");       | waits for n2
    249 //   generates failure #2           |
    250 //   notifies n2                    |
    251 //   -------------------------------|--------------------------------
    252 //   waits for n3                   | generates failure #3
    253 //                                  | trace B dies
    254 //                                  | generates failure #4
    255 //                                  | notifies n3
    256 //   -------------------------------|--------------------------------
    257 //   generates failure #5           | finishes
    258 //   trace A dies                   |
    259 //   generates failure #6           |
    260 //   -------------------------------|--------------------------------
    261 //   waits for thread B to finish   |
    262 
    263 struct CheckPoints {
    264   Notification n1;
    265   Notification n2;
    266   Notification n3;
    267 };
    268 
    269 static void ThreadWithScopedTrace(CheckPoints* check_points) {
    270   {
    271     SCOPED_TRACE("Trace B");
    272     ADD_FAILURE()
    273         << "Expected failure #1 (in thread B, only trace B alive).";
    274     check_points->n1.Notify();
    275     check_points->n2.WaitForNotification();
    276 
    277     ADD_FAILURE()
    278         << "Expected failure #3 (in thread B, trace A & B both alive).";
    279   }  // Trace B dies here.
    280   ADD_FAILURE()
    281       << "Expected failure #4 (in thread B, only trace A alive).";
    282   check_points->n3.Notify();
    283 }
    284 
    285 TEST(SCOPED_TRACETest, WorksConcurrently) {
    286   printf("(expecting 6 failures)\n");
    287 
    288   CheckPoints check_points;
    289   ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace,
    290                                        &check_points,
    291                                        NULL);
    292   check_points.n1.WaitForNotification();
    293 
    294   {
    295     SCOPED_TRACE("Trace A");
    296     ADD_FAILURE()
    297         << "Expected failure #2 (in thread A, trace A & B both alive).";
    298     check_points.n2.Notify();
    299     check_points.n3.WaitForNotification();
    300 
    301     ADD_FAILURE()
    302         << "Expected failure #5 (in thread A, only trace A alive).";
    303   }  // Trace A dies here.
    304   ADD_FAILURE()
    305       << "Expected failure #6 (in thread A, no trace alive).";
    306   thread.Join();
    307 }
    308 #endif  // GTEST_IS_THREADSAFE
    309 
    310 TEST(DisabledTestsWarningTest,
    311      DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {
    312   // This test body is intentionally empty.  Its sole purpose is for
    313   // verifying that the --gtest_also_run_disabled_tests flag
    314   // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of
    315   // the test output.
    316 }
    317 
    318 // Tests using assertions outside of TEST and TEST_F.
    319 //
    320 // This function creates two failures intentionally.
    321 void AdHocTest() {
    322   printf("The non-test part of the code is expected to have 2 failures.\n\n");
    323   EXPECT_TRUE(false);
    324   EXPECT_EQ(2, 3);
    325 }
    326 
    327 // Runs all TESTs, all TEST_Fs, and the ad hoc test.
    328 int RunAllTests() {
    329   AdHocTest();
    330   return RUN_ALL_TESTS();
    331 }
    332 
    333 // Tests non-fatal failures in the fixture constructor.
    334 class NonFatalFailureInFixtureConstructorTest : public testing::Test {
    335  protected:
    336   NonFatalFailureInFixtureConstructorTest() {
    337     printf("(expecting 5 failures)\n");
    338     ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
    339   }
    340 
    341   ~NonFatalFailureInFixtureConstructorTest() {
    342     ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
    343   }
    344 
    345   virtual void SetUp() {
    346     ADD_FAILURE() << "Expected failure #2, in SetUp().";
    347   }
    348 
    349   virtual void TearDown() {
    350     ADD_FAILURE() << "Expected failure #4, in TearDown.";
    351   }
    352 };
    353 
    354 TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
    355   ADD_FAILURE() << "Expected failure #3, in the test body.";
    356 }
    357 
    358 // Tests fatal failures in the fixture constructor.
    359 class FatalFailureInFixtureConstructorTest : public testing::Test {
    360  protected:
    361   FatalFailureInFixtureConstructorTest() {
    362     printf("(expecting 2 failures)\n");
    363     Init();
    364   }
    365 
    366   ~FatalFailureInFixtureConstructorTest() {
    367     ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
    368   }
    369 
    370   virtual void SetUp() {
    371     ADD_FAILURE() << "UNEXPECTED failure in SetUp().  "
    372                   << "We should never get here, as the test fixture c'tor "
    373                   << "had a fatal failure.";
    374   }
    375 
    376   virtual void TearDown() {
    377     ADD_FAILURE() << "UNEXPECTED failure in TearDown().  "
    378                   << "We should never get here, as the test fixture c'tor "
    379                   << "had a fatal failure.";
    380   }
    381 
    382  private:
    383   void Init() {
    384     FAIL() << "Expected failure #1, in the test fixture c'tor.";
    385   }
    386 };
    387 
    388 TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
    389   ADD_FAILURE() << "UNEXPECTED failure in the test body.  "
    390                 << "We should never get here, as the test fixture c'tor "
    391                 << "had a fatal failure.";
    392 }
    393 
    394 // Tests non-fatal failures in SetUp().
    395 class NonFatalFailureInSetUpTest : public testing::Test {
    396  protected:
    397   virtual ~NonFatalFailureInSetUpTest() {
    398     Deinit();
    399   }
    400 
    401   virtual void SetUp() {
    402     printf("(expecting 4 failures)\n");
    403     ADD_FAILURE() << "Expected failure #1, in SetUp().";
    404   }
    405 
    406   virtual void TearDown() {
    407     FAIL() << "Expected failure #3, in TearDown().";
    408   }
    409  private:
    410   void Deinit() {
    411     FAIL() << "Expected failure #4, in the test fixture d'tor.";
    412   }
    413 };
    414 
    415 TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
    416   FAIL() << "Expected failure #2, in the test function.";
    417 }
    418 
    419 // Tests fatal failures in SetUp().
    420 class FatalFailureInSetUpTest : public testing::Test {
    421  protected:
    422   virtual ~FatalFailureInSetUpTest() {
    423     Deinit();
    424   }
    425 
    426   virtual void SetUp() {
    427     printf("(expecting 3 failures)\n");
    428     FAIL() << "Expected failure #1, in SetUp().";
    429   }
    430 
    431   virtual void TearDown() {
    432     FAIL() << "Expected failure #2, in TearDown().";
    433   }
    434  private:
    435   void Deinit() {
    436     FAIL() << "Expected failure #3, in the test fixture d'tor.";
    437   }
    438 };
    439 
    440 TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
    441   FAIL() << "UNEXPECTED failure in the test function.  "
    442          << "We should never get here, as SetUp() failed.";
    443 }
    444 
    445 TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {
    446   ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc";
    447 }
    448 
    449 #if GTEST_IS_THREADSAFE
    450 
    451 // A unary function that may die.
    452 void DieIf(bool should_die) {
    453   GTEST_CHECK_(!should_die) << " - death inside DieIf().";
    454 }
    455 
    456 // Tests running death tests in a multi-threaded context.
    457 
    458 // Used for coordination between the main and the spawn thread.
    459 struct SpawnThreadNotifications {
    460   SpawnThreadNotifications() {}
    461 
    462   Notification spawn_thread_started;
    463   Notification spawn_thread_ok_to_terminate;
    464 
    465  private:
    466   GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
    467 };
    468 
    469 // The function to be executed in the thread spawn by the
    470 // MultipleThreads test (below).
    471 static void ThreadRoutine(SpawnThreadNotifications* notifications) {
    472   // Signals the main thread that this thread has started.
    473   notifications->spawn_thread_started.Notify();
    474 
    475   // Waits for permission to finish from the main thread.
    476   notifications->spawn_thread_ok_to_terminate.WaitForNotification();
    477 }
    478 
    479 // This is a death-test test, but it's not named with a DeathTest
    480 // suffix.  It starts threads which might interfere with later
    481 // death tests, so it must run after all other death tests.
    482 class DeathTestAndMultiThreadsTest : public testing::Test {
    483  protected:
    484   // Starts a thread and waits for it to begin.
    485   virtual void SetUp() {
    486     thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
    487         &ThreadRoutine, &notifications_, NULL));
    488     notifications_.spawn_thread_started.WaitForNotification();
    489   }
    490   // Tells the thread to finish, and reaps it.
    491   // Depending on the version of the thread library in use,
    492   // a manager thread might still be left running that will interfere
    493   // with later death tests.  This is unfortunate, but this class
    494   // cleans up after itself as best it can.
    495   virtual void TearDown() {
    496     notifications_.spawn_thread_ok_to_terminate.Notify();
    497   }
    498 
    499  private:
    500   SpawnThreadNotifications notifications_;
    501   scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
    502 };
    503 
    504 #endif  // GTEST_IS_THREADSAFE
    505 
    506 // The MixedUpTestCaseTest test case verifies that Google Test will fail a
    507 // test if it uses a different fixture class than what other tests in
    508 // the same test case use.  It deliberately contains two fixture
    509 // classes with the same name but defined in different namespaces.
    510 
    511 // The MixedUpTestCaseWithSameTestNameTest test case verifies that
    512 // when the user defines two tests with the same test case name AND
    513 // same test name (but in different namespaces), the second test will
    514 // fail.
    515 
    516 namespace foo {
    517 
    518 class MixedUpTestCaseTest : public testing::Test {
    519 };
    520 
    521 TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {}
    522 TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {}
    523 
    524 class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
    525 };
    526 
    527 TEST_F(MixedUpTestCaseWithSameTestNameTest,
    528        TheSecondTestWithThisNameShouldFail) {}
    529 
    530 }  // namespace foo
    531 
    532 namespace bar {
    533 
    534 class MixedUpTestCaseTest : public testing::Test {
    535 };
    536 
    537 // The following two tests are expected to fail.  We rely on the
    538 // golden file to check that Google Test generates the right error message.
    539 TEST_F(MixedUpTestCaseTest, ThisShouldFail) {}
    540 TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {}
    541 
    542 class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
    543 };
    544 
    545 // Expected to fail.  We rely on the golden file to check that Google Test
    546 // generates the right error message.
    547 TEST_F(MixedUpTestCaseWithSameTestNameTest,
    548        TheSecondTestWithThisNameShouldFail) {}
    549 
    550 }  // namespace bar
    551 
    552 // The following two test cases verify that Google Test catches the user
    553 // error of mixing TEST and TEST_F in the same test case.  The first
    554 // test case checks the scenario where TEST_F appears before TEST, and
    555 // the second one checks where TEST appears before TEST_F.
    556 
    557 class TEST_F_before_TEST_in_same_test_case : public testing::Test {
    558 };
    559 
    560 TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
    561 
    562 // Expected to fail.  We rely on the golden file to check that Google Test
    563 // generates the right error message.
    564 TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
    565 
    566 class TEST_before_TEST_F_in_same_test_case : public testing::Test {
    567 };
    568 
    569 TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
    570 
    571 // Expected to fail.  We rely on the golden file to check that Google Test
    572 // generates the right error message.
    573 TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {
    574 }
    575 
    576 // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
    577 int global_integer = 0;
    578 
    579 // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
    580 TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
    581   global_integer = 0;
    582   EXPECT_NONFATAL_FAILURE({
    583     EXPECT_EQ(1, global_integer) << "Expected non-fatal failure.";
    584   }, "Expected non-fatal failure.");
    585 }
    586 
    587 // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
    588 // (static or not).
    589 TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
    590   int m = 0;
    591   static int n;
    592   n = 1;
    593   EXPECT_NONFATAL_FAILURE({
    594     EXPECT_EQ(m, n) << "Expected non-fatal failure.";
    595   }, "Expected non-fatal failure.");
    596 }
    597 
    598 // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
    599 // one non-fatal failure and no fatal failure.
    600 TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
    601   EXPECT_NONFATAL_FAILURE({
    602     ADD_FAILURE() << "Expected non-fatal failure.";
    603   }, "Expected non-fatal failure.");
    604 }
    605 
    606 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
    607 // non-fatal failure.
    608 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
    609   printf("(expecting a failure)\n");
    610   EXPECT_NONFATAL_FAILURE({
    611   }, "");
    612 }
    613 
    614 // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
    615 // non-fatal failures.
    616 TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
    617   printf("(expecting a failure)\n");
    618   EXPECT_NONFATAL_FAILURE({
    619     ADD_FAILURE() << "Expected non-fatal failure 1.";
    620     ADD_FAILURE() << "Expected non-fatal failure 2.";
    621   }, "");
    622 }
    623 
    624 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
    625 // failure.
    626 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
    627   printf("(expecting a failure)\n");
    628   EXPECT_NONFATAL_FAILURE({
    629     FAIL() << "Expected fatal failure.";
    630   }, "");
    631 }
    632 
    633 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
    634 // tested returns.
    635 TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
    636   printf("(expecting a failure)\n");
    637   EXPECT_NONFATAL_FAILURE({
    638     return;
    639   }, "");
    640 }
    641 
    642 #if GTEST_HAS_EXCEPTIONS
    643 
    644 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
    645 // tested throws.
    646 TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
    647   printf("(expecting a failure)\n");
    648   try {
    649     EXPECT_NONFATAL_FAILURE({
    650       throw 0;
    651     }, "");
    652   } catch(int) {  // NOLINT
    653   }
    654 }
    655 
    656 #endif  // GTEST_HAS_EXCEPTIONS
    657 
    658 // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
    659 TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
    660   global_integer = 0;
    661   EXPECT_FATAL_FAILURE({
    662     ASSERT_EQ(1, global_integer) << "Expected fatal failure.";
    663   }, "Expected fatal failure.");
    664 }
    665 
    666 // Tests that EXPECT_FATAL_FAILURE() can reference local static
    667 // variables.
    668 TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
    669   static int n;
    670   n = 1;
    671   EXPECT_FATAL_FAILURE({
    672     ASSERT_EQ(0, n) << "Expected fatal failure.";
    673   }, "Expected fatal failure.");
    674 }
    675 
    676 // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
    677 // one fatal failure and no non-fatal failure.
    678 TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
    679   EXPECT_FATAL_FAILURE({
    680     FAIL() << "Expected fatal failure.";
    681   }, "Expected fatal failure.");
    682 }
    683 
    684 // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
    685 // failure.
    686 TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
    687   printf("(expecting a failure)\n");
    688   EXPECT_FATAL_FAILURE({
    689   }, "");
    690 }
    691 
    692 // A helper for generating a fatal failure.
    693 void FatalFailure() {
    694   FAIL() << "Expected fatal failure.";
    695 }
    696 
    697 // Tests that EXPECT_FATAL_FAILURE() fails when there are two
    698 // fatal failures.
    699 TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
    700   printf("(expecting a failure)\n");
    701   EXPECT_FATAL_FAILURE({
    702     FatalFailure();
    703     FatalFailure();
    704   }, "");
    705 }
    706 
    707 // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
    708 // failure.
    709 TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
    710   printf("(expecting a failure)\n");
    711   EXPECT_FATAL_FAILURE({
    712     ADD_FAILURE() << "Expected non-fatal failure.";
    713   }, "");
    714 }
    715 
    716 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
    717 // tested returns.
    718 TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
    719   printf("(expecting a failure)\n");
    720   EXPECT_FATAL_FAILURE({
    721     return;
    722   }, "");
    723 }
    724 
    725 #if GTEST_HAS_EXCEPTIONS
    726 
    727 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
    728 // tested throws.
    729 TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
    730   printf("(expecting a failure)\n");
    731   try {
    732     EXPECT_FATAL_FAILURE({
    733       throw 0;
    734     }, "");
    735   } catch(int) {  // NOLINT
    736   }
    737 }
    738 
    739 #endif  // GTEST_HAS_EXCEPTIONS
    740 
    741 // This #ifdef block tests the output of typed tests.
    742 #if GTEST_HAS_TYPED_TEST
    743 
    744 template <typename T>
    745 class TypedTest : public testing::Test {
    746 };
    747 
    748 TYPED_TEST_CASE(TypedTest, testing::Types<int>);
    749 
    750 TYPED_TEST(TypedTest, Success) {
    751   EXPECT_EQ(0, TypeParam());
    752 }
    753 
    754 TYPED_TEST(TypedTest, Failure) {
    755   EXPECT_EQ(1, TypeParam()) << "Expected failure";
    756 }
    757 
    758 #endif  // GTEST_HAS_TYPED_TEST
    759 
    760 // This #ifdef block tests the output of type-parameterized tests.
    761 #if GTEST_HAS_TYPED_TEST_P
    762 
    763 template <typename T>
    764 class TypedTestP : public testing::Test {
    765 };
    766 
    767 TYPED_TEST_CASE_P(TypedTestP);
    768 
    769 TYPED_TEST_P(TypedTestP, Success) {
    770   EXPECT_EQ(0U, TypeParam());
    771 }
    772 
    773 TYPED_TEST_P(TypedTestP, Failure) {
    774   EXPECT_EQ(1U, TypeParam()) << "Expected failure";
    775 }
    776 
    777 REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure);
    778 
    779 typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
    780 INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes);
    781 
    782 #endif  // GTEST_HAS_TYPED_TEST_P
    783 
    784 #if GTEST_HAS_DEATH_TEST
    785 
    786 // We rely on the golden file to verify that tests whose test case
    787 // name ends with DeathTest are run first.
    788 
    789 TEST(ADeathTest, ShouldRunFirst) {
    790 }
    791 
    792 # if GTEST_HAS_TYPED_TEST
    793 
    794 // We rely on the golden file to verify that typed tests whose test
    795 // case name ends with DeathTest are run first.
    796 
    797 template <typename T>
    798 class ATypedDeathTest : public testing::Test {
    799 };
    800 
    801 typedef testing::Types<int, double> NumericTypes;
    802 TYPED_TEST_CASE(ATypedDeathTest, NumericTypes);
    803 
    804 TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {
    805 }
    806 
    807 # endif  // GTEST_HAS_TYPED_TEST
    808 
    809 # if GTEST_HAS_TYPED_TEST_P
    810 
    811 
    812 // We rely on the golden file to verify that type-parameterized tests
    813 // whose test case name ends with DeathTest are run first.
    814 
    815 template <typename T>
    816 class ATypeParamDeathTest : public testing::Test {
    817 };
    818 
    819 TYPED_TEST_CASE_P(ATypeParamDeathTest);
    820 
    821 TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {
    822 }
    823 
    824 REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst);
    825 
    826 INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes);
    827 
    828 # endif  // GTEST_HAS_TYPED_TEST_P
    829 
    830 #endif  // GTEST_HAS_DEATH_TEST
    831 
    832 // Tests various failure conditions of
    833 // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
    834 class ExpectFailureTest : public testing::Test {
    835  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
    836   enum FailureMode {
    837     FATAL_FAILURE,
    838     NONFATAL_FAILURE
    839   };
    840   static void AddFailure(FailureMode failure) {
    841     if (failure == FATAL_FAILURE) {
    842       FAIL() << "Expected fatal failure.";
    843     } else {
    844       ADD_FAILURE() << "Expected non-fatal failure.";
    845     }
    846   }
    847 };
    848 
    849 TEST_F(ExpectFailureTest, ExpectFatalFailure) {
    850   // Expected fatal failure, but succeeds.
    851   printf("(expecting 1 failure)\n");
    852   EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
    853   // Expected fatal failure, but got a non-fatal failure.
    854   printf("(expecting 1 failure)\n");
    855   EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal "
    856                        "failure.");
    857   // Wrong message.
    858   printf("(expecting 1 failure)\n");
    859   EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure "
    860                        "expected.");
    861 }
    862 
    863 TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
    864   // Expected non-fatal failure, but succeeds.
    865   printf("(expecting 1 failure)\n");
    866   EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
    867   // Expected non-fatal failure, but got a fatal failure.
    868   printf("(expecting 1 failure)\n");
    869   EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
    870   // Wrong message.
    871   printf("(expecting 1 failure)\n");
    872   EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal "
    873                           "failure.");
    874 }
    875 
    876 #if GTEST_IS_THREADSAFE
    877 
    878 class ExpectFailureWithThreadsTest : public ExpectFailureTest {
    879  protected:
    880   static void AddFailureInOtherThread(FailureMode failure) {
    881     ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
    882     thread.Join();
    883   }
    884 };
    885 
    886 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {
    887   // We only intercept the current thread.
    888   printf("(expecting 2 failures)\n");
    889   EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),
    890                        "Expected fatal failure.");
    891 }
    892 
    893 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {
    894   // We only intercept the current thread.
    895   printf("(expecting 2 failures)\n");
    896   EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),
    897                           "Expected non-fatal failure.");
    898 }
    899 
    900 typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
    901 
    902 // Tests that the ScopedFakeTestPartResultReporter only catches failures from
    903 // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
    904 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {
    905   printf("(expecting 2 failures)\n");
    906   TestPartResultArray results;
    907   {
    908     ScopedFakeTestPartResultReporter reporter(
    909         ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
    910         &results);
    911     AddFailureInOtherThread(FATAL_FAILURE);
    912     AddFailureInOtherThread(NONFATAL_FAILURE);
    913   }
    914   // The two failures should not have been intercepted.
    915   EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
    916 }
    917 
    918 #endif  // GTEST_IS_THREADSAFE
    919 
    920 TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
    921   // Expected fatal failure, but succeeds.
    922   printf("(expecting 1 failure)\n");
    923   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
    924   // Expected fatal failure, but got a non-fatal failure.
    925   printf("(expecting 1 failure)\n");
    926   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
    927                                       "Expected non-fatal failure.");
    928   // Wrong message.
    929   printf("(expecting 1 failure)\n");
    930   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
    931                                       "Some other fatal failure expected.");
    932 }
    933 
    934 TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
    935   // Expected non-fatal failure, but succeeds.
    936   printf("(expecting 1 failure)\n");
    937   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal "
    938                                          "failure.");
    939   // Expected non-fatal failure, but got a fatal failure.
    940   printf("(expecting 1 failure)\n");
    941   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
    942                                          "Expected fatal failure.");
    943   // Wrong message.
    944   printf("(expecting 1 failure)\n");
    945   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
    946                                          "Some other non-fatal failure.");
    947 }
    948 
    949 
    950 // Two test environments for testing testing::AddGlobalTestEnvironment().
    951 
    952 class FooEnvironment : public testing::Environment {
    953  public:
    954   virtual void SetUp() {
    955     printf("%s", "FooEnvironment::SetUp() called.\n");
    956   }
    957 
    958   virtual void TearDown() {
    959     printf("%s", "FooEnvironment::TearDown() called.\n");
    960     FAIL() << "Expected fatal failure.";
    961   }
    962 };
    963 
    964 class BarEnvironment : public testing::Environment {
    965  public:
    966   virtual void SetUp() {
    967     printf("%s", "BarEnvironment::SetUp() called.\n");
    968   }
    969 
    970   virtual void TearDown() {
    971     printf("%s", "BarEnvironment::TearDown() called.\n");
    972     ADD_FAILURE() << "Expected non-fatal failure.";
    973   }
    974 };
    975 
    976 bool GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = false;
    977 
    978 // The main function.
    979 //
    980 // The idea is to use Google Test to run all the tests we have defined (some
    981 // of them are intended to fail), and then compare the test results
    982 // with the "golden" file.
    983 int main(int argc, char **argv) {
    984   testing::GTEST_FLAG(print_time) = false;
    985 
    986   // We just run the tests, knowing some of them are intended to fail.
    987   // We will use a separate Python script to compare the output of
    988   // this program with the golden file.
    989 
    990   // It's hard to test InitGoogleTest() directly, as it has many
    991   // global side effects.  The following line serves as a sanity test
    992   // for it.
    993   testing::InitGoogleTest(&argc, argv);
    994   if (argc >= 2 &&
    995       String(argv[1]) == "--gtest_internal_skip_environment_and_ad_hoc_tests")
    996     GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = true;
    997 
    998 #if GTEST_HAS_DEATH_TEST
    999   if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
   1000     // Skip the usual output capturing if we're running as the child
   1001     // process of an threadsafe-style death test.
   1002 # if GTEST_OS_WINDOWS
   1003     posix::FReopen("nul:", "w", stdout);
   1004 # else
   1005     posix::FReopen("/dev/null", "w", stdout);
   1006 # endif  // GTEST_OS_WINDOWS
   1007     return RUN_ALL_TESTS();
   1008   }
   1009 #endif  // GTEST_HAS_DEATH_TEST
   1010 
   1011   if (GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests))
   1012     return RUN_ALL_TESTS();
   1013 
   1014   // Registers two global test environments.
   1015   // The golden file verifies that they are set up in the order they
   1016   // are registered, and torn down in the reverse order.
   1017   testing::AddGlobalTestEnvironment(new FooEnvironment);
   1018   testing::AddGlobalTestEnvironment(new BarEnvironment);
   1019 
   1020   return RunAllTests();
   1021 }
   1022