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