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 // Author: wan (at) google.com (Zhanyong Wan)
     31 //
     32 // Tests for death tests.
     33 
     34 #include <gtest/gtest-death-test.h>
     35 #include <gtest/gtest.h>
     36 #include <gtest/internal/gtest-filepath.h>
     37 
     38 using testing::internal::AlwaysFalse;
     39 using testing::internal::AlwaysTrue;
     40 
     41 #if GTEST_HAS_DEATH_TEST
     42 
     43 #if GTEST_OS_WINDOWS
     44 #include <direct.h>          // For chdir().
     45 #else
     46 #include <unistd.h>
     47 #include <sys/wait.h>        // For waitpid.
     48 #include <limits>            // For std::numeric_limits.
     49 #endif  // GTEST_OS_WINDOWS
     50 
     51 #include <limits.h>
     52 #include <signal.h>
     53 #include <stdio.h>
     54 
     55 #include <gtest/gtest-spi.h>
     56 
     57 // Indicates that this translation unit is part of Google Test's
     58 // implementation.  It must come before gtest-internal-inl.h is
     59 // included, or there will be a compiler error.  This trick is to
     60 // prevent a user from accidentally including gtest-internal-inl.h in
     61 // his code.
     62 #define GTEST_IMPLEMENTATION_ 1
     63 #include "src/gtest-internal-inl.h"
     64 #undef GTEST_IMPLEMENTATION_
     65 
     66 namespace posix = ::testing::internal::posix;
     67 
     68 using testing::Message;
     69 using testing::internal::DeathTest;
     70 using testing::internal::DeathTestFactory;
     71 using testing::internal::FilePath;
     72 using testing::internal::GetLastErrnoDescription;
     73 using testing::internal::GetUnitTestImpl;
     74 using testing::internal::ParseNaturalNumber;
     75 using testing::internal::String;
     76 
     77 namespace testing {
     78 namespace internal {
     79 
     80 // A helper class whose objects replace the death test factory for a
     81 // single UnitTest object during their lifetimes.
     82 class ReplaceDeathTestFactory {
     83  public:
     84   explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
     85       : unit_test_impl_(GetUnitTestImpl()) {
     86     old_factory_ = unit_test_impl_->death_test_factory_.release();
     87     unit_test_impl_->death_test_factory_.reset(new_factory);
     88   }
     89 
     90   ~ReplaceDeathTestFactory() {
     91     unit_test_impl_->death_test_factory_.release();
     92     unit_test_impl_->death_test_factory_.reset(old_factory_);
     93   }
     94  private:
     95   // Prevents copying ReplaceDeathTestFactory objects.
     96   ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
     97   void operator=(const ReplaceDeathTestFactory&);
     98 
     99   UnitTestImpl* unit_test_impl_;
    100   DeathTestFactory* old_factory_;
    101 };
    102 
    103 }  // namespace internal
    104 }  // namespace testing
    105 
    106 void DieInside(const char* function) {
    107   fprintf(stderr, "death inside %s().", function);
    108   fflush(stderr);
    109   // We call _exit() instead of exit(), as the former is a direct
    110   // system call and thus safer in the presence of threads.  exit()
    111   // will invoke user-defined exit-hooks, which may do dangerous
    112   // things that conflict with death tests.
    113   //
    114   // Some compilers can recognize that _exit() never returns and issue the
    115   // 'unreachable code' warning for code following this function, unless
    116   // fooled by a fake condition.
    117   if (AlwaysTrue())
    118     _exit(1);
    119 }
    120 
    121 // Tests that death tests work.
    122 
    123 class TestForDeathTest : public testing::Test {
    124  protected:
    125   TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
    126 
    127   virtual ~TestForDeathTest() {
    128     posix::ChDir(original_dir_.c_str());
    129   }
    130 
    131   // A static member function that's expected to die.
    132   static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
    133 
    134   // A method of the test fixture that may die.
    135   void MemberFunction() {
    136     if (should_die_)
    137       DieInside("MemberFunction");
    138   }
    139 
    140   // True iff MemberFunction() should die.
    141   bool should_die_;
    142   const FilePath original_dir_;
    143 };
    144 
    145 // A class with a member function that may die.
    146 class MayDie {
    147  public:
    148   explicit MayDie(bool should_die) : should_die_(should_die) {}
    149 
    150   // A member function that may die.
    151   void MemberFunction() const {
    152     if (should_die_)
    153       DieInside("MayDie::MemberFunction");
    154   }
    155 
    156  private:
    157   // True iff MemberFunction() should die.
    158   bool should_die_;
    159 };
    160 
    161 // A global function that's expected to die.
    162 void GlobalFunction() { DieInside("GlobalFunction"); }
    163 
    164 // A non-void function that's expected to die.
    165 int NonVoidFunction() {
    166   DieInside("NonVoidFunction");
    167   return 1;
    168 }
    169 
    170 // A unary function that may die.
    171 void DieIf(bool should_die) {
    172   if (should_die)
    173     DieInside("DieIf");
    174 }
    175 
    176 // A binary function that may die.
    177 bool DieIfLessThan(int x, int y) {
    178   if (x < y) {
    179     DieInside("DieIfLessThan");
    180   }
    181   return true;
    182 }
    183 
    184 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
    185 void DeathTestSubroutine() {
    186   EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
    187   ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
    188 }
    189 
    190 // Death in dbg, not opt.
    191 int DieInDebugElse12(int* sideeffect) {
    192   if (sideeffect) *sideeffect = 12;
    193 #ifndef NDEBUG
    194   DieInside("DieInDebugElse12");
    195 #endif  // NDEBUG
    196   return 12;
    197 }
    198 
    199 #if GTEST_OS_WINDOWS
    200 
    201 // Tests the ExitedWithCode predicate.
    202 TEST(ExitStatusPredicateTest, ExitedWithCode) {
    203   // On Windows, the process's exit code is the same as its exit status,
    204   // so the predicate just compares the its input with its parameter.
    205   EXPECT_TRUE(testing::ExitedWithCode(0)(0));
    206   EXPECT_TRUE(testing::ExitedWithCode(1)(1));
    207   EXPECT_TRUE(testing::ExitedWithCode(42)(42));
    208   EXPECT_FALSE(testing::ExitedWithCode(0)(1));
    209   EXPECT_FALSE(testing::ExitedWithCode(1)(0));
    210 }
    211 
    212 #else
    213 
    214 // Returns the exit status of a process that calls _exit(2) with a
    215 // given exit code.  This is a helper function for the
    216 // ExitStatusPredicateTest test suite.
    217 static int NormalExitStatus(int exit_code) {
    218   pid_t child_pid = fork();
    219   if (child_pid == 0) {
    220     _exit(exit_code);
    221   }
    222   int status;
    223   waitpid(child_pid, &status, 0);
    224   return status;
    225 }
    226 
    227 // Returns the exit status of a process that raises a given signal.
    228 // If the signal does not cause the process to die, then it returns
    229 // instead the exit status of a process that exits normally with exit
    230 // code 1.  This is a helper function for the ExitStatusPredicateTest
    231 // test suite.
    232 static int KilledExitStatus(int signum) {
    233   pid_t child_pid = fork();
    234   if (child_pid == 0) {
    235     raise(signum);
    236     _exit(1);
    237   }
    238   int status;
    239   waitpid(child_pid, &status, 0);
    240   return status;
    241 }
    242 
    243 // Tests the ExitedWithCode predicate.
    244 TEST(ExitStatusPredicateTest, ExitedWithCode) {
    245   const int status0  = NormalExitStatus(0);
    246   const int status1  = NormalExitStatus(1);
    247   const int status42 = NormalExitStatus(42);
    248   const testing::ExitedWithCode pred0(0);
    249   const testing::ExitedWithCode pred1(1);
    250   const testing::ExitedWithCode pred42(42);
    251   EXPECT_PRED1(pred0,  status0);
    252   EXPECT_PRED1(pred1,  status1);
    253   EXPECT_PRED1(pred42, status42);
    254   EXPECT_FALSE(pred0(status1));
    255   EXPECT_FALSE(pred42(status0));
    256   EXPECT_FALSE(pred1(status42));
    257 }
    258 
    259 // Tests the KilledBySignal predicate.
    260 TEST(ExitStatusPredicateTest, KilledBySignal) {
    261   const int status_segv = KilledExitStatus(SIGSEGV);
    262   const int status_kill = KilledExitStatus(SIGKILL);
    263   const testing::KilledBySignal pred_segv(SIGSEGV);
    264   const testing::KilledBySignal pred_kill(SIGKILL);
    265   EXPECT_PRED1(pred_segv, status_segv);
    266   EXPECT_PRED1(pred_kill, status_kill);
    267   EXPECT_FALSE(pred_segv(status_kill));
    268   EXPECT_FALSE(pred_kill(status_segv));
    269 }
    270 
    271 #endif  // GTEST_OS_WINDOWS
    272 
    273 // Tests that the death test macros expand to code which may or may not
    274 // be followed by operator<<, and that in either case the complete text
    275 // comprises only a single C++ statement.
    276 TEST_F(TestForDeathTest, SingleStatement) {
    277   if (AlwaysFalse())
    278     // This would fail if executed; this is a compilation test only
    279     ASSERT_DEATH(return, "");
    280 
    281   if (AlwaysTrue())
    282     EXPECT_DEATH(_exit(1), "");
    283   else
    284     // This empty "else" branch is meant to ensure that EXPECT_DEATH
    285     // doesn't expand into an "if" statement without an "else"
    286     ;
    287 
    288   if (AlwaysFalse())
    289     ASSERT_DEATH(return, "") << "did not die";
    290 
    291   if (AlwaysFalse())
    292     ;
    293   else
    294     EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
    295 }
    296 
    297 void DieWithEmbeddedNul() {
    298   fprintf(stderr, "Hello%cmy null world.\n", '\0');
    299   fflush(stderr);
    300   _exit(1);
    301 }
    302 
    303 #if GTEST_USES_PCRE
    304 // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
    305 // message has a NUL character in it.
    306 TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
    307   // TODO(wan (at) google.com): <regex.h> doesn't support matching strings
    308   // with embedded NUL characters - find a way to workaround it.
    309   EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
    310   ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
    311 }
    312 #endif  // GTEST_USES_PCRE
    313 
    314 // Tests that death test macros expand to code which interacts well with switch
    315 // statements.
    316 TEST_F(TestForDeathTest, SwitchStatement) {
    317 // Microsoft compiler usually complains about switch statements without
    318 // case labels. We suppress that warning for this test.
    319 #ifdef _MSC_VER
    320 #pragma warning(push)
    321 #pragma warning(disable: 4065)
    322 #endif  // _MSC_VER
    323 
    324   switch (0)
    325     default:
    326       ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
    327 
    328   switch (0)
    329     case 0:
    330       EXPECT_DEATH(_exit(1), "") << "exit in switch case";
    331 
    332 #ifdef _MSC_VER
    333 #pragma warning(pop)
    334 #endif  // _MSC_VER
    335 }
    336 
    337 // Tests that a static member function can be used in a "fast" style
    338 // death test.
    339 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
    340   testing::GTEST_FLAG(death_test_style) = "fast";
    341   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
    342 }
    343 
    344 // Tests that a method of the test fixture can be used in a "fast"
    345 // style death test.
    346 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
    347   testing::GTEST_FLAG(death_test_style) = "fast";
    348   should_die_ = true;
    349   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
    350 }
    351 
    352 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
    353 
    354 // Tests that death tests work even if the current directory has been
    355 // changed.
    356 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
    357   testing::GTEST_FLAG(death_test_style) = "fast";
    358 
    359   ChangeToRootDir();
    360   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
    361 
    362   ChangeToRootDir();
    363   ASSERT_DEATH(_exit(1), "");
    364 }
    365 
    366 // Repeats a representative sample of death tests in the "threadsafe" style:
    367 
    368 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
    369   testing::GTEST_FLAG(death_test_style) = "threadsafe";
    370   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
    371 }
    372 
    373 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
    374   testing::GTEST_FLAG(death_test_style) = "threadsafe";
    375   should_die_ = true;
    376   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
    377 }
    378 
    379 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
    380   testing::GTEST_FLAG(death_test_style) = "threadsafe";
    381 
    382   for (int i = 0; i < 3; ++i)
    383     EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
    384 }
    385 
    386 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
    387   testing::GTEST_FLAG(death_test_style) = "threadsafe";
    388 
    389   ChangeToRootDir();
    390   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
    391 
    392   ChangeToRootDir();
    393   ASSERT_DEATH(_exit(1), "");
    394 }
    395 
    396 TEST_F(TestForDeathTest, MixedStyles) {
    397   testing::GTEST_FLAG(death_test_style) = "threadsafe";
    398   EXPECT_DEATH(_exit(1), "");
    399   testing::GTEST_FLAG(death_test_style) = "fast";
    400   EXPECT_DEATH(_exit(1), "");
    401 }
    402 
    403 namespace {
    404 
    405 bool pthread_flag;
    406 
    407 void SetPthreadFlag() {
    408   pthread_flag = true;
    409 }
    410 
    411 }  // namespace
    412 
    413 #if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
    414 
    415 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
    416   if (!testing::GTEST_FLAG(death_test_use_fork)) {
    417     testing::GTEST_FLAG(death_test_style) = "threadsafe";
    418     pthread_flag = false;
    419     ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
    420     ASSERT_DEATH(_exit(1), "");
    421     ASSERT_FALSE(pthread_flag);
    422   }
    423 }
    424 
    425 #endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
    426 
    427 // Tests that a method of another class can be used in a death test.
    428 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
    429   const MayDie x(true);
    430   ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
    431 }
    432 
    433 // Tests that a global function can be used in a death test.
    434 TEST_F(TestForDeathTest, GlobalFunction) {
    435   EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
    436 }
    437 
    438 // Tests that any value convertible to an RE works as a second
    439 // argument to EXPECT_DEATH.
    440 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
    441   static const char regex_c_str[] = "GlobalFunction";
    442   EXPECT_DEATH(GlobalFunction(), regex_c_str);
    443 
    444   const testing::internal::RE regex(regex_c_str);
    445   EXPECT_DEATH(GlobalFunction(), regex);
    446 
    447 #if GTEST_HAS_GLOBAL_STRING
    448   const string regex_str(regex_c_str);
    449   EXPECT_DEATH(GlobalFunction(), regex_str);
    450 #endif  // GTEST_HAS_GLOBAL_STRING
    451 
    452   const ::std::string regex_std_str(regex_c_str);
    453   EXPECT_DEATH(GlobalFunction(), regex_std_str);
    454 }
    455 
    456 // Tests that a non-void function can be used in a death test.
    457 TEST_F(TestForDeathTest, NonVoidFunction) {
    458   ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
    459 }
    460 
    461 // Tests that functions that take parameter(s) can be used in a death test.
    462 TEST_F(TestForDeathTest, FunctionWithParameter) {
    463   EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
    464   EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
    465 }
    466 
    467 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
    468 TEST_F(TestForDeathTest, OutsideFixture) {
    469   DeathTestSubroutine();
    470 }
    471 
    472 // Tests that death tests can be done inside a loop.
    473 TEST_F(TestForDeathTest, InsideLoop) {
    474   for (int i = 0; i < 5; i++) {
    475     EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
    476   }
    477 }
    478 
    479 // Tests that a compound statement can be used in a death test.
    480 TEST_F(TestForDeathTest, CompoundStatement) {
    481   EXPECT_DEATH({  // NOLINT
    482     const int x = 2;
    483     const int y = x + 1;
    484     DieIfLessThan(x, y);
    485   },
    486   "DieIfLessThan");
    487 }
    488 
    489 // Tests that code that doesn't die causes a death test to fail.
    490 TEST_F(TestForDeathTest, DoesNotDie) {
    491   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
    492                           "failed to die");
    493 }
    494 
    495 // Tests that a death test fails when the error message isn't expected.
    496 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
    497   EXPECT_NONFATAL_FAILURE({  // NOLINT
    498     EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
    499   }, "died but not with expected error");
    500 }
    501 
    502 // On exit, *aborted will be true iff the EXPECT_DEATH() statement
    503 // aborted the function.
    504 void ExpectDeathTestHelper(bool* aborted) {
    505   *aborted = true;
    506   EXPECT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
    507   *aborted = false;
    508 }
    509 
    510 // Tests that EXPECT_DEATH doesn't abort the test on failure.
    511 TEST_F(TestForDeathTest, EXPECT_DEATH) {
    512   bool aborted = true;
    513   EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
    514                           "failed to die");
    515   EXPECT_FALSE(aborted);
    516 }
    517 
    518 // Tests that ASSERT_DEATH does abort the test on failure.
    519 TEST_F(TestForDeathTest, ASSERT_DEATH) {
    520   static bool aborted;
    521   EXPECT_FATAL_FAILURE({  // NOLINT
    522     aborted = true;
    523     ASSERT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
    524     aborted = false;
    525   }, "failed to die");
    526   EXPECT_TRUE(aborted);
    527 }
    528 
    529 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
    530 TEST_F(TestForDeathTest, SingleEvaluation) {
    531   int x = 3;
    532   EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
    533 
    534   const char* regex = "DieIf";
    535   const char* regex_save = regex;
    536   EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
    537   EXPECT_EQ(regex_save + 1, regex);
    538 }
    539 
    540 // Tests that run-away death tests are reported as failures.
    541 TEST_F(TestForDeathTest, Runaway) {
    542   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
    543                           "failed to die.");
    544 
    545   EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
    546                        "illegal return in test statement.");
    547 }
    548 
    549 
    550 // Tests that EXPECT_DEBUG_DEATH works as expected,
    551 // that is, in debug mode, it:
    552 // 1. Asserts on death.
    553 // 2. Has no side effect.
    554 //
    555 // And in opt mode, it:
    556 // 1.  Has side effects but does not assert.
    557 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
    558   int sideeffect = 0;
    559 
    560   EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect),
    561                      "death.*DieInDebugElse12");
    562 
    563 #ifdef NDEBUG
    564   // Checks that the assignment occurs in opt mode (sideeffect).
    565   EXPECT_EQ(12, sideeffect);
    566 #else
    567   // Checks that the assignment does not occur in dbg mode (no sideeffect).
    568   EXPECT_EQ(0, sideeffect);
    569 #endif
    570 }
    571 
    572 // Tests that ASSERT_DEBUG_DEATH works as expected
    573 // In debug mode:
    574 // 1. Asserts on debug death.
    575 // 2. Has no side effect.
    576 //
    577 // In opt mode:
    578 // 1. Has side effects and returns the expected value (12).
    579 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
    580   int sideeffect = 0;
    581 
    582   ASSERT_DEBUG_DEATH({  // NOLINT
    583     // Tests that the return value is 12 in opt mode.
    584     EXPECT_EQ(12, DieInDebugElse12(&sideeffect));
    585     // Tests that the side effect occurred in opt mode.
    586     EXPECT_EQ(12, sideeffect);
    587   }, "death.*DieInDebugElse12");
    588 
    589 #ifdef NDEBUG
    590   // Checks that the assignment occurs in opt mode (sideeffect).
    591   EXPECT_EQ(12, sideeffect);
    592 #else
    593   // Checks that the assignment does not occur in dbg mode (no sideeffect).
    594   EXPECT_EQ(0, sideeffect);
    595 #endif
    596 }
    597 
    598 #ifndef NDEBUG
    599 
    600 void ExpectDebugDeathHelper(bool* aborted) {
    601   *aborted = true;
    602   EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
    603   *aborted = false;
    604 }
    605 
    606 #if GTEST_OS_WINDOWS
    607 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
    608   printf("This test should be considered failing if it shows "
    609          "any pop-up dialogs.\n");
    610   fflush(stdout);
    611 
    612   EXPECT_DEATH({
    613     testing::GTEST_FLAG(catch_exceptions) = false;
    614     abort();
    615   }, "");
    616 }
    617 
    618 TEST(PopUpDeathTest, DoesNotShowPopUpOnThrow) {
    619   printf("This test should be considered failing if it shows "
    620          "any pop-up dialogs.\n");
    621   fflush(stdout);
    622 
    623   EXPECT_DEATH({
    624     testing::GTEST_FLAG(catch_exceptions) = false;
    625     throw 1;
    626   }, "");
    627 }
    628 #endif  // GTEST_OS_WINDOWS
    629 
    630 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
    631 // the function.
    632 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
    633   bool aborted = true;
    634   EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
    635   EXPECT_FALSE(aborted);
    636 }
    637 
    638 void AssertDebugDeathHelper(bool* aborted) {
    639   *aborted = true;
    640   ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
    641   *aborted = false;
    642 }
    643 
    644 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
    645 // failure.
    646 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
    647   static bool aborted;
    648   aborted = false;
    649   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
    650   EXPECT_TRUE(aborted);
    651 }
    652 
    653 #endif  // _NDEBUG
    654 
    655 // Tests the *_EXIT family of macros, using a variety of predicates.
    656 static void TestExitMacros() {
    657   EXPECT_EXIT(_exit(1),  testing::ExitedWithCode(1),  "");
    658   ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
    659 
    660 #if GTEST_OS_WINDOWS
    661   // Of all signals effects on the process exit code, only those of SIGABRT
    662   // are documented on Windows.
    663   // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
    664   EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "");
    665 #else
    666   EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
    667   ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
    668 
    669   EXPECT_FATAL_FAILURE({  // NOLINT
    670     ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
    671         << "This failure is expected, too.";
    672   }, "This failure is expected, too.");
    673 #endif  // GTEST_OS_WINDOWS
    674 
    675   EXPECT_NONFATAL_FAILURE({  // NOLINT
    676     EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
    677         << "This failure is expected.";
    678   }, "This failure is expected.");
    679 }
    680 
    681 TEST_F(TestForDeathTest, ExitMacros) {
    682   TestExitMacros();
    683 }
    684 
    685 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
    686   testing::GTEST_FLAG(death_test_use_fork) = true;
    687   TestExitMacros();
    688 }
    689 
    690 TEST_F(TestForDeathTest, InvalidStyle) {
    691   testing::GTEST_FLAG(death_test_style) = "rococo";
    692   EXPECT_NONFATAL_FAILURE({  // NOLINT
    693     EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
    694   }, "This failure is expected.");
    695 }
    696 
    697 // A DeathTestFactory that returns MockDeathTests.
    698 class MockDeathTestFactory : public DeathTestFactory {
    699  public:
    700   MockDeathTestFactory();
    701   virtual bool Create(const char* statement,
    702                       const ::testing::internal::RE* regex,
    703                       const char* file, int line, DeathTest** test);
    704 
    705   // Sets the parameters for subsequent calls to Create.
    706   void SetParameters(bool create, DeathTest::TestRole role,
    707                      int status, bool passed);
    708 
    709   // Accessors.
    710   int AssumeRoleCalls() const { return assume_role_calls_; }
    711   int WaitCalls() const { return wait_calls_; }
    712   int PassedCalls() const { return passed_args_.size(); }
    713   bool PassedArgument(int n) const { return passed_args_[n]; }
    714   int AbortCalls() const { return abort_args_.size(); }
    715   DeathTest::AbortReason AbortArgument(int n) const {
    716     return abort_args_[n];
    717   }
    718   bool TestDeleted() const { return test_deleted_; }
    719 
    720  private:
    721   friend class MockDeathTest;
    722   // If true, Create will return a MockDeathTest; otherwise it returns
    723   // NULL.
    724   bool create_;
    725   // The value a MockDeathTest will return from its AssumeRole method.
    726   DeathTest::TestRole role_;
    727   // The value a MockDeathTest will return from its Wait method.
    728   int status_;
    729   // The value a MockDeathTest will return from its Passed method.
    730   bool passed_;
    731 
    732   // Number of times AssumeRole was called.
    733   int assume_role_calls_;
    734   // Number of times Wait was called.
    735   int wait_calls_;
    736   // The arguments to the calls to Passed since the last call to
    737   // SetParameters.
    738   std::vector<bool> passed_args_;
    739   // The arguments to the calls to Abort since the last call to
    740   // SetParameters.
    741   std::vector<DeathTest::AbortReason> abort_args_;
    742   // True if the last MockDeathTest returned by Create has been
    743   // deleted.
    744   bool test_deleted_;
    745 };
    746 
    747 
    748 // A DeathTest implementation useful in testing.  It returns values set
    749 // at its creation from its various inherited DeathTest methods, and
    750 // reports calls to those methods to its parent MockDeathTestFactory
    751 // object.
    752 class MockDeathTest : public DeathTest {
    753  public:
    754   MockDeathTest(MockDeathTestFactory *parent,
    755                 TestRole role, int status, bool passed) :
    756       parent_(parent), role_(role), status_(status), passed_(passed) {
    757   }
    758   virtual ~MockDeathTest() {
    759     parent_->test_deleted_ = true;
    760   }
    761   virtual TestRole AssumeRole() {
    762     ++parent_->assume_role_calls_;
    763     return role_;
    764   }
    765   virtual int Wait() {
    766     ++parent_->wait_calls_;
    767     return status_;
    768   }
    769   virtual bool Passed(bool exit_status_ok) {
    770     parent_->passed_args_.push_back(exit_status_ok);
    771     return passed_;
    772   }
    773   virtual void Abort(AbortReason reason) {
    774     parent_->abort_args_.push_back(reason);
    775   }
    776  private:
    777   MockDeathTestFactory* const parent_;
    778   const TestRole role_;
    779   const int status_;
    780   const bool passed_;
    781 };
    782 
    783 
    784 // MockDeathTestFactory constructor.
    785 MockDeathTestFactory::MockDeathTestFactory()
    786     : create_(true),
    787       role_(DeathTest::OVERSEE_TEST),
    788       status_(0),
    789       passed_(true),
    790       assume_role_calls_(0),
    791       wait_calls_(0),
    792       passed_args_(),
    793       abort_args_() {
    794 }
    795 
    796 
    797 // Sets the parameters for subsequent calls to Create.
    798 void MockDeathTestFactory::SetParameters(bool create,
    799                                          DeathTest::TestRole role,
    800                                          int status, bool passed) {
    801   create_ = create;
    802   role_ = role;
    803   status_ = status;
    804   passed_ = passed;
    805 
    806   assume_role_calls_ = 0;
    807   wait_calls_ = 0;
    808   passed_args_.clear();
    809   abort_args_.clear();
    810 }
    811 
    812 
    813 // Sets test to NULL (if create_ is false) or to the address of a new
    814 // MockDeathTest object with parameters taken from the last call
    815 // to SetParameters (if create_ is true).  Always returns true.
    816 bool MockDeathTestFactory::Create(const char* /*statement*/,
    817                                   const ::testing::internal::RE* /*regex*/,
    818                                   const char* /*file*/,
    819                                   int /*line*/,
    820                                   DeathTest** test) {
    821   test_deleted_ = false;
    822   if (create_) {
    823     *test = new MockDeathTest(this, role_, status_, passed_);
    824   } else {
    825     *test = NULL;
    826   }
    827   return true;
    828 }
    829 
    830 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
    831 // It installs a MockDeathTestFactory that is used for the duration
    832 // of the test case.
    833 class MacroLogicDeathTest : public testing::Test {
    834  protected:
    835   static testing::internal::ReplaceDeathTestFactory* replacer_;
    836   static MockDeathTestFactory* factory_;
    837 
    838   static void SetUpTestCase() {
    839     factory_ = new MockDeathTestFactory;
    840     replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
    841   }
    842 
    843   static void TearDownTestCase() {
    844     delete replacer_;
    845     replacer_ = NULL;
    846     delete factory_;
    847     factory_ = NULL;
    848   }
    849 
    850   // Runs a death test that breaks the rules by returning.  Such a death
    851   // test cannot be run directly from a test routine that uses a
    852   // MockDeathTest, or the remainder of the routine will not be executed.
    853   static void RunReturningDeathTest(bool* flag) {
    854     ASSERT_DEATH({  // NOLINT
    855       *flag = true;
    856       return;
    857     }, "");
    858   }
    859 };
    860 
    861 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
    862     = NULL;
    863 MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
    864 
    865 
    866 // Test that nothing happens when the factory doesn't return a DeathTest:
    867 TEST_F(MacroLogicDeathTest, NothingHappens) {
    868   bool flag = false;
    869   factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
    870   EXPECT_DEATH(flag = true, "");
    871   EXPECT_FALSE(flag);
    872   EXPECT_EQ(0, factory_->AssumeRoleCalls());
    873   EXPECT_EQ(0, factory_->WaitCalls());
    874   EXPECT_EQ(0, factory_->PassedCalls());
    875   EXPECT_EQ(0, factory_->AbortCalls());
    876   EXPECT_FALSE(factory_->TestDeleted());
    877 }
    878 
    879 // Test that the parent process doesn't run the death test code,
    880 // and that the Passed method returns false when the (simulated)
    881 // child process exits with status 0:
    882 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
    883   bool flag = false;
    884   factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
    885   EXPECT_DEATH(flag = true, "");
    886   EXPECT_FALSE(flag);
    887   EXPECT_EQ(1, factory_->AssumeRoleCalls());
    888   EXPECT_EQ(1, factory_->WaitCalls());
    889   ASSERT_EQ(1, factory_->PassedCalls());
    890   EXPECT_FALSE(factory_->PassedArgument(0));
    891   EXPECT_EQ(0, factory_->AbortCalls());
    892   EXPECT_TRUE(factory_->TestDeleted());
    893 }
    894 
    895 // Tests that the Passed method was given the argument "true" when
    896 // the (simulated) child process exits with status 1:
    897 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
    898   bool flag = false;
    899   factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
    900   EXPECT_DEATH(flag = true, "");
    901   EXPECT_FALSE(flag);
    902   EXPECT_EQ(1, factory_->AssumeRoleCalls());
    903   EXPECT_EQ(1, factory_->WaitCalls());
    904   ASSERT_EQ(1, factory_->PassedCalls());
    905   EXPECT_TRUE(factory_->PassedArgument(0));
    906   EXPECT_EQ(0, factory_->AbortCalls());
    907   EXPECT_TRUE(factory_->TestDeleted());
    908 }
    909 
    910 // Tests that the (simulated) child process executes the death test
    911 // code, and is aborted with the correct AbortReason if it
    912 // executes a return statement.
    913 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
    914   bool flag = false;
    915   factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
    916   RunReturningDeathTest(&flag);
    917   EXPECT_TRUE(flag);
    918   EXPECT_EQ(1, factory_->AssumeRoleCalls());
    919   EXPECT_EQ(0, factory_->WaitCalls());
    920   EXPECT_EQ(0, factory_->PassedCalls());
    921   EXPECT_EQ(1, factory_->AbortCalls());
    922   EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
    923             factory_->AbortArgument(0));
    924   EXPECT_TRUE(factory_->TestDeleted());
    925 }
    926 
    927 // Tests that the (simulated) child process is aborted with the
    928 // correct AbortReason if it does not die.
    929 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
    930   bool flag = false;
    931   factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
    932   EXPECT_DEATH(flag = true, "");
    933   EXPECT_TRUE(flag);
    934   EXPECT_EQ(1, factory_->AssumeRoleCalls());
    935   EXPECT_EQ(0, factory_->WaitCalls());
    936   EXPECT_EQ(0, factory_->PassedCalls());
    937   // This time there are two calls to Abort: one since the test didn't
    938   // die, and another from the ReturnSentinel when it's destroyed.  The
    939   // sentinel normally isn't destroyed if a test doesn't die, since
    940   // _exit(2) is called in that case by ForkingDeathTest, but not by
    941   // our MockDeathTest.
    942   ASSERT_EQ(2, factory_->AbortCalls());
    943   EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
    944             factory_->AbortArgument(0));
    945   EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
    946             factory_->AbortArgument(1));
    947   EXPECT_TRUE(factory_->TestDeleted());
    948 }
    949 
    950 // Tests that a successful death test does not register a successful
    951 // test part.
    952 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
    953   EXPECT_DEATH(_exit(1), "");
    954   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
    955 }
    956 
    957 TEST(StreamingAssertionsDeathTest, DeathTest) {
    958   EXPECT_DEATH(_exit(1), "") << "unexpected failure";
    959   ASSERT_DEATH(_exit(1), "") << "unexpected failure";
    960   EXPECT_NONFATAL_FAILURE({  // NOLINT
    961     EXPECT_DEATH(_exit(0), "") << "expected failure";
    962   }, "expected failure");
    963   EXPECT_FATAL_FAILURE({  // NOLINT
    964     ASSERT_DEATH(_exit(0), "") << "expected failure";
    965   }, "expected failure");
    966 }
    967 
    968 // Tests that GetLastErrnoDescription returns an empty string when the
    969 // last error is 0 and non-empty string when it is non-zero.
    970 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
    971   errno = ENOENT;
    972   EXPECT_STRNE("", GetLastErrnoDescription().c_str());
    973   errno = 0;
    974   EXPECT_STREQ("", GetLastErrnoDescription().c_str());
    975 }
    976 
    977 #if GTEST_OS_WINDOWS
    978 TEST(AutoHandleTest, AutoHandleWorks) {
    979   HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
    980   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
    981 
    982   // Tests that the AutoHandle is correctly initialized with a handle.
    983   testing::internal::AutoHandle auto_handle(handle);
    984   EXPECT_EQ(handle, auto_handle.Get());
    985 
    986   // Tests that Reset assigns INVALID_HANDLE_VALUE.
    987   // Note that this cannot verify whether the original handle is closed.
    988   auto_handle.Reset();
    989   EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
    990 
    991   // Tests that Reset assigns the new handle.
    992   // Note that this cannot verify whether the original handle is closed.
    993   handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
    994   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
    995   auto_handle.Reset(handle);
    996   EXPECT_EQ(handle, auto_handle.Get());
    997 
    998   // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
    999   testing::internal::AutoHandle auto_handle2;
   1000   EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
   1001 }
   1002 #endif  // GTEST_OS_WINDOWS
   1003 
   1004 #if GTEST_OS_WINDOWS
   1005 typedef unsigned __int64 BiggestParsable;
   1006 typedef signed __int64 BiggestSignedParsable;
   1007 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
   1008 const BiggestParsable kBiggestSignedParsableMax = LLONG_MAX;
   1009 #else
   1010 typedef unsigned long long BiggestParsable;
   1011 typedef signed long long BiggestSignedParsable;
   1012 const BiggestParsable kBiggestParsableMax =
   1013     ::std::numeric_limits<BiggestParsable>::max();
   1014 const BiggestSignedParsable kBiggestSignedParsableMax =
   1015     ::std::numeric_limits<BiggestSignedParsable>::max();
   1016 #endif  // GTEST_OS_WINDOWS
   1017 
   1018 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
   1019   BiggestParsable result = 0;
   1020 
   1021   // Rejects non-numbers.
   1022   EXPECT_FALSE(ParseNaturalNumber(String("non-number string"), &result));
   1023 
   1024   // Rejects numbers with whitespace prefix.
   1025   EXPECT_FALSE(ParseNaturalNumber(String(" 123"), &result));
   1026 
   1027   // Rejects negative numbers.
   1028   EXPECT_FALSE(ParseNaturalNumber(String("-123"), &result));
   1029 
   1030   // Rejects numbers starting with a plus sign.
   1031   EXPECT_FALSE(ParseNaturalNumber(String("+123"), &result));
   1032   errno = 0;
   1033 }
   1034 
   1035 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
   1036   BiggestParsable result = 0;
   1037 
   1038   EXPECT_FALSE(ParseNaturalNumber(String("99999999999999999999999"), &result));
   1039 
   1040   signed char char_result = 0;
   1041   EXPECT_FALSE(ParseNaturalNumber(String("200"), &char_result));
   1042   errno = 0;
   1043 }
   1044 
   1045 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
   1046   BiggestParsable result = 0;
   1047 
   1048   result = 0;
   1049   ASSERT_TRUE(ParseNaturalNumber(String("123"), &result));
   1050   EXPECT_EQ(123U, result);
   1051 
   1052   // Check 0 as an edge case.
   1053   result = 1;
   1054   ASSERT_TRUE(ParseNaturalNumber(String("0"), &result));
   1055   EXPECT_EQ(0U, result);
   1056 
   1057   result = 1;
   1058   ASSERT_TRUE(ParseNaturalNumber(String("00000"), &result));
   1059   EXPECT_EQ(0U, result);
   1060 }
   1061 
   1062 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
   1063   Message msg;
   1064   msg << kBiggestParsableMax;
   1065 
   1066   BiggestParsable result = 0;
   1067   EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
   1068   EXPECT_EQ(kBiggestParsableMax, result);
   1069 
   1070   Message msg2;
   1071   msg2 << kBiggestSignedParsableMax;
   1072 
   1073   BiggestSignedParsable signed_result = 0;
   1074   EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
   1075   EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
   1076 
   1077   Message msg3;
   1078   msg3 << INT_MAX;
   1079 
   1080   int int_result = 0;
   1081   EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
   1082   EXPECT_EQ(INT_MAX, int_result);
   1083 
   1084   Message msg4;
   1085   msg4 << UINT_MAX;
   1086 
   1087   unsigned int uint_result = 0;
   1088   EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
   1089   EXPECT_EQ(UINT_MAX, uint_result);
   1090 }
   1091 
   1092 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
   1093   short short_result = 0;
   1094   ASSERT_TRUE(ParseNaturalNumber(String("123"), &short_result));
   1095   EXPECT_EQ(123, short_result);
   1096 
   1097   signed char char_result = 0;
   1098   ASSERT_TRUE(ParseNaturalNumber(String("123"), &char_result));
   1099   EXPECT_EQ(123, char_result);
   1100 }
   1101 
   1102 #if GTEST_OS_WINDOWS
   1103 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
   1104   // TODO(vladl (at) google.com): Remove this test after this condition is verified
   1105   // in a static assertion in gtest-death-test.cc in the function
   1106   // GetStatusFileDescriptor.
   1107   ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
   1108 }
   1109 #endif  // GTEST_OS_WINDOWS
   1110 
   1111 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
   1112 // failures when death tests are available on the system.
   1113 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
   1114   EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
   1115                             "death inside CondDeathTestExpectMacro");
   1116   ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
   1117                             "death inside CondDeathTestAssertMacro");
   1118 
   1119   // Empty statement will not crash, which must trigger a failure.
   1120   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
   1121   EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
   1122 }
   1123 
   1124 #else
   1125 
   1126 using testing::internal::CaptureStderr;
   1127 using testing::internal::GetCapturedStderr;
   1128 using testing::internal::String;
   1129 
   1130 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
   1131 // defined but do not trigger failures when death tests are not available on
   1132 // the system.
   1133 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
   1134   // Empty statement will not crash, but that should not trigger a failure
   1135   // when death tests are not supported.
   1136   CaptureStderr();
   1137   EXPECT_DEATH_IF_SUPPORTED(;, "");
   1138   String output = GetCapturedStderr();
   1139   ASSERT_TRUE(NULL != strstr(output.c_str(),
   1140                              "Death tests are not supported on this platform"));
   1141   ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
   1142 
   1143   // The streamed message should not be printed as there is no test failure.
   1144   CaptureStderr();
   1145   EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
   1146   output = GetCapturedStderr();
   1147   ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
   1148 
   1149   CaptureStderr();
   1150   ASSERT_DEATH_IF_SUPPORTED(;, "");  // NOLINT
   1151   output = GetCapturedStderr();
   1152   ASSERT_TRUE(NULL != strstr(output.c_str(),
   1153                              "Death tests are not supported on this platform"));
   1154   ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
   1155 
   1156   CaptureStderr();
   1157   ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message";  // NOLINT
   1158   output = GetCapturedStderr();
   1159   ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
   1160 }
   1161 
   1162 void FuncWithAssert(int* n) {
   1163   ASSERT_DEATH_IF_SUPPORTED(return;, "");
   1164   (*n)++;
   1165 }
   1166 
   1167 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
   1168 // function (as ASSERT_DEATH does) if death tests are not supported.
   1169 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
   1170   int n = 0;
   1171   FuncWithAssert(&n);
   1172   EXPECT_EQ(1, n);
   1173 }
   1174 #endif  // GTEST_HAS_DEATH_TEST
   1175 
   1176 // Tests that the death test macros expand to code which may or may not
   1177 // be followed by operator<<, and that in either case the complete text
   1178 // comprises only a single C++ statement.
   1179 //
   1180 // The syntax should work whether death tests are available or not.
   1181 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
   1182   if (AlwaysFalse())
   1183     // This would fail if executed; this is a compilation test only
   1184     ASSERT_DEATH_IF_SUPPORTED(return, "");
   1185 
   1186   if (AlwaysTrue())
   1187     EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
   1188   else
   1189     // This empty "else" branch is meant to ensure that EXPECT_DEATH
   1190     // doesn't expand into an "if" statement without an "else"
   1191     ;  // NOLINT
   1192 
   1193   if (AlwaysFalse())
   1194     ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
   1195 
   1196   if (AlwaysFalse())
   1197     ;  // NOLINT
   1198   else
   1199     EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
   1200 }
   1201 
   1202 // Tests that conditional death test macros expand to code which interacts
   1203 // well with switch statements.
   1204 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
   1205 // Microsoft compiler usually complains about switch statements without
   1206 // case labels. We suppress that warning for this test.
   1207 #ifdef _MSC_VER
   1208 #pragma warning(push)
   1209 #pragma warning(disable: 4065)
   1210 #endif  // _MSC_VER
   1211 
   1212   switch (0)
   1213     default:
   1214       ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
   1215           << "exit in default switch handler";
   1216 
   1217   switch (0)
   1218     case 0:
   1219       EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
   1220 
   1221 #ifdef _MSC_VER
   1222 #pragma warning(pop)
   1223 #endif  // _MSC_VER
   1224 }
   1225 
   1226 // Tests that a test case whose name ends with "DeathTest" works fine
   1227 // on Windows.
   1228 TEST(NotADeathTest, Test) {
   1229   SUCCEED();
   1230 }
   1231