gtest-death-test_test.cc
Go to the documentation of this file.
00001 // Copyright 2005, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: wan@google.com (Zhanyong Wan)
00031 //
00032 // Tests for death tests.
00033 
00034 #include "gtest/gtest-death-test.h"
00035 #include "gtest/gtest.h"
00036 #include "gtest/internal/gtest-filepath.h"
00037 
00038 using testing::internal::AlwaysFalse;
00039 using testing::internal::AlwaysTrue;
00040 
00041 #if GTEST_HAS_DEATH_TEST
00042 
00043 # if GTEST_OS_WINDOWS
00044 #  include <direct.h>          // For chdir().
00045 # else
00046 #  include <unistd.h>
00047 #  include <sys/wait.h>        // For waitpid.
00048 # endif  // GTEST_OS_WINDOWS
00049 
00050 # include <limits.h>
00051 # include <signal.h>
00052 # include <stdio.h>
00053 
00054 # if GTEST_OS_LINUX
00055 #  include <sys/time.h>
00056 # endif  // GTEST_OS_LINUX
00057 
00058 # include "gtest/gtest-spi.h"
00059 
00060 // Indicates that this translation unit is part of Google Test's
00061 // implementation.  It must come before gtest-internal-inl.h is
00062 // included, or there will be a compiler error.  This trick is to
00063 // prevent a user from accidentally including gtest-internal-inl.h in
00064 // his code.
00065 # define GTEST_IMPLEMENTATION_ 1
00066 # include "src/gtest-internal-inl.h"
00067 # undef GTEST_IMPLEMENTATION_
00068 
00069 namespace posix = ::testing::internal::posix;
00070 
00071 using testing::Message;
00072 using testing::internal::DeathTest;
00073 using testing::internal::DeathTestFactory;
00074 using testing::internal::FilePath;
00075 using testing::internal::GetLastErrnoDescription;
00076 using testing::internal::GetUnitTestImpl;
00077 using testing::internal::InDeathTestChild;
00078 using testing::internal::ParseNaturalNumber;
00079 
00080 namespace testing {
00081 namespace internal {
00082 
00083 // A helper class whose objects replace the death test factory for a
00084 // single UnitTest object during their lifetimes.
00085 class ReplaceDeathTestFactory {
00086  public:
00087   explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
00088       : unit_test_impl_(GetUnitTestImpl()) {
00089     old_factory_ = unit_test_impl_->death_test_factory_.release();
00090     unit_test_impl_->death_test_factory_.reset(new_factory);
00091   }
00092 
00093   ~ReplaceDeathTestFactory() {
00094     unit_test_impl_->death_test_factory_.release();
00095     unit_test_impl_->death_test_factory_.reset(old_factory_);
00096   }
00097  private:
00098   // Prevents copying ReplaceDeathTestFactory objects.
00099   ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
00100   void operator=(const ReplaceDeathTestFactory&);
00101 
00102   UnitTestImpl* unit_test_impl_;
00103   DeathTestFactory* old_factory_;
00104 };
00105 
00106 }  // namespace internal
00107 }  // namespace testing
00108 
00109 void DieWithMessage(const ::std::string& message) {
00110   fprintf(stderr, "%s", message.c_str());
00111   fflush(stderr);  // Make sure the text is printed before the process exits.
00112 
00113   // We call _exit() instead of exit(), as the former is a direct
00114   // system call and thus safer in the presence of threads.  exit()
00115   // will invoke user-defined exit-hooks, which may do dangerous
00116   // things that conflict with death tests.
00117   //
00118   // Some compilers can recognize that _exit() never returns and issue the
00119   // 'unreachable code' warning for code following this function, unless
00120   // fooled by a fake condition.
00121   if (AlwaysTrue())
00122     _exit(1);
00123 }
00124 
00125 void DieInside(const ::std::string& function) {
00126   DieWithMessage("death inside " + function + "().");
00127 }
00128 
00129 // Tests that death tests work.
00130 
00131 class TestForDeathTest : public testing::Test {
00132  protected:
00133   TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
00134 
00135   virtual ~TestForDeathTest() {
00136     posix::ChDir(original_dir_.c_str());
00137   }
00138 
00139   // A static member function that's expected to die.
00140   static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
00141 
00142   // A method of the test fixture that may die.
00143   void MemberFunction() {
00144     if (should_die_)
00145       DieInside("MemberFunction");
00146   }
00147 
00148   // True iff MemberFunction() should die.
00149   bool should_die_;
00150   const FilePath original_dir_;
00151 };
00152 
00153 // A class with a member function that may die.
00154 class MayDie {
00155  public:
00156   explicit MayDie(bool should_die) : should_die_(should_die) {}
00157 
00158   // A member function that may die.
00159   void MemberFunction() const {
00160     if (should_die_)
00161       DieInside("MayDie::MemberFunction");
00162   }
00163 
00164  private:
00165   // True iff MemberFunction() should die.
00166   bool should_die_;
00167 };
00168 
00169 // A global function that's expected to die.
00170 void GlobalFunction() { DieInside("GlobalFunction"); }
00171 
00172 // A non-void function that's expected to die.
00173 int NonVoidFunction() {
00174   DieInside("NonVoidFunction");
00175   return 1;
00176 }
00177 
00178 // A unary function that may die.
00179 void DieIf(bool should_die) {
00180   if (should_die)
00181     DieInside("DieIf");
00182 }
00183 
00184 // A binary function that may die.
00185 bool DieIfLessThan(int x, int y) {
00186   if (x < y) {
00187     DieInside("DieIfLessThan");
00188   }
00189   return true;
00190 }
00191 
00192 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
00193 void DeathTestSubroutine() {
00194   EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
00195   ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
00196 }
00197 
00198 // Death in dbg, not opt.
00199 int DieInDebugElse12(int* sideeffect) {
00200   if (sideeffect) *sideeffect = 12;
00201 
00202 # ifndef NDEBUG
00203 
00204   DieInside("DieInDebugElse12");
00205 
00206 # endif  // NDEBUG
00207 
00208   return 12;
00209 }
00210 
00211 # if GTEST_OS_WINDOWS
00212 
00213 // Tests the ExitedWithCode predicate.
00214 TEST(ExitStatusPredicateTest, ExitedWithCode) {
00215   // On Windows, the process's exit code is the same as its exit status,
00216   // so the predicate just compares the its input with its parameter.
00217   EXPECT_TRUE(testing::ExitedWithCode(0)(0));
00218   EXPECT_TRUE(testing::ExitedWithCode(1)(1));
00219   EXPECT_TRUE(testing::ExitedWithCode(42)(42));
00220   EXPECT_FALSE(testing::ExitedWithCode(0)(1));
00221   EXPECT_FALSE(testing::ExitedWithCode(1)(0));
00222 }
00223 
00224 # else
00225 
00226 // Returns the exit status of a process that calls _exit(2) with a
00227 // given exit code.  This is a helper function for the
00228 // ExitStatusPredicateTest test suite.
00229 static int NormalExitStatus(int exit_code) {
00230   pid_t child_pid = fork();
00231   if (child_pid == 0) {
00232     _exit(exit_code);
00233   }
00234   int status;
00235   waitpid(child_pid, &status, 0);
00236   return status;
00237 }
00238 
00239 // Returns the exit status of a process that raises a given signal.
00240 // If the signal does not cause the process to die, then it returns
00241 // instead the exit status of a process that exits normally with exit
00242 // code 1.  This is a helper function for the ExitStatusPredicateTest
00243 // test suite.
00244 static int KilledExitStatus(int signum) {
00245   pid_t child_pid = fork();
00246   if (child_pid == 0) {
00247     raise(signum);
00248     _exit(1);
00249   }
00250   int status;
00251   waitpid(child_pid, &status, 0);
00252   return status;
00253 }
00254 
00255 // Tests the ExitedWithCode predicate.
00256 TEST(ExitStatusPredicateTest, ExitedWithCode) {
00257   const int status0  = NormalExitStatus(0);
00258   const int status1  = NormalExitStatus(1);
00259   const int status42 = NormalExitStatus(42);
00260   const testing::ExitedWithCode pred0(0);
00261   const testing::ExitedWithCode pred1(1);
00262   const testing::ExitedWithCode pred42(42);
00263   EXPECT_PRED1(pred0,  status0);
00264   EXPECT_PRED1(pred1,  status1);
00265   EXPECT_PRED1(pred42, status42);
00266   EXPECT_FALSE(pred0(status1));
00267   EXPECT_FALSE(pred42(status0));
00268   EXPECT_FALSE(pred1(status42));
00269 }
00270 
00271 // Tests the KilledBySignal predicate.
00272 TEST(ExitStatusPredicateTest, KilledBySignal) {
00273   const int status_segv = KilledExitStatus(SIGSEGV);
00274   const int status_kill = KilledExitStatus(SIGKILL);
00275   const testing::KilledBySignal pred_segv(SIGSEGV);
00276   const testing::KilledBySignal pred_kill(SIGKILL);
00277   EXPECT_PRED1(pred_segv, status_segv);
00278   EXPECT_PRED1(pred_kill, status_kill);
00279   EXPECT_FALSE(pred_segv(status_kill));
00280   EXPECT_FALSE(pred_kill(status_segv));
00281 }
00282 
00283 # endif  // GTEST_OS_WINDOWS
00284 
00285 // Tests that the death test macros expand to code which may or may not
00286 // be followed by operator<<, and that in either case the complete text
00287 // comprises only a single C++ statement.
00288 TEST_F(TestForDeathTest, SingleStatement) {
00289   if (AlwaysFalse())
00290     // This would fail if executed; this is a compilation test only
00291     ASSERT_DEATH(return, "");
00292 
00293   if (AlwaysTrue())
00294     EXPECT_DEATH(_exit(1), "");
00295   else
00296     // This empty "else" branch is meant to ensure that EXPECT_DEATH
00297     // doesn't expand into an "if" statement without an "else"
00298     ;
00299 
00300   if (AlwaysFalse())
00301     ASSERT_DEATH(return, "") << "did not die";
00302 
00303   if (AlwaysFalse())
00304     ;
00305   else
00306     EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
00307 }
00308 
00309 void DieWithEmbeddedNul() {
00310   fprintf(stderr, "Hello%cmy null world.\n", '\0');
00311   fflush(stderr);
00312   _exit(1);
00313 }
00314 
00315 # if GTEST_USES_PCRE
00316 // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
00317 // message has a NUL character in it.
00318 TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
00319   // TODO(wan@google.com): <regex.h> doesn't support matching strings
00320   // with embedded NUL characters - find a way to workaround it.
00321   EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
00322   ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
00323 }
00324 # endif  // GTEST_USES_PCRE
00325 
00326 // Tests that death test macros expand to code which interacts well with switch
00327 // statements.
00328 TEST_F(TestForDeathTest, SwitchStatement) {
00329   // Microsoft compiler usually complains about switch statements without
00330   // case labels. We suppress that warning for this test.
00331   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
00332 
00333   switch (0)
00334     default:
00335       ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
00336 
00337   switch (0)
00338     case 0:
00339       EXPECT_DEATH(_exit(1), "") << "exit in switch case";
00340 
00341   GTEST_DISABLE_MSC_WARNINGS_POP_()
00342 }
00343 
00344 // Tests that a static member function can be used in a "fast" style
00345 // death test.
00346 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
00347   testing::GTEST_FLAG(death_test_style) = "fast";
00348   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
00349 }
00350 
00351 // Tests that a method of the test fixture can be used in a "fast"
00352 // style death test.
00353 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
00354   testing::GTEST_FLAG(death_test_style) = "fast";
00355   should_die_ = true;
00356   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
00357 }
00358 
00359 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
00360 
00361 // Tests that death tests work even if the current directory has been
00362 // changed.
00363 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
00364   testing::GTEST_FLAG(death_test_style) = "fast";
00365 
00366   ChangeToRootDir();
00367   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
00368 
00369   ChangeToRootDir();
00370   ASSERT_DEATH(_exit(1), "");
00371 }
00372 
00373 # if GTEST_OS_LINUX
00374 void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
00375 
00376 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
00377 void SetSigprofActionAndTimer() {
00378   struct itimerval timer;
00379   timer.it_interval.tv_sec = 0;
00380   timer.it_interval.tv_usec = 1;
00381   timer.it_value = timer.it_interval;
00382   ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
00383   struct sigaction signal_action;
00384   memset(&signal_action, 0, sizeof(signal_action));
00385   sigemptyset(&signal_action.sa_mask);
00386   signal_action.sa_sigaction = SigprofAction;
00387   signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
00388   ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL));
00389 }
00390 
00391 // Disables ITIMER_PROF timer and ignores SIGPROF signal.
00392 void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
00393   struct itimerval timer;
00394   timer.it_interval.tv_sec = 0;
00395   timer.it_interval.tv_usec = 0;
00396   timer.it_value = timer.it_interval;
00397   ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
00398   struct sigaction signal_action;
00399   memset(&signal_action, 0, sizeof(signal_action));
00400   sigemptyset(&signal_action.sa_mask);
00401   signal_action.sa_handler = SIG_IGN;
00402   ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
00403 }
00404 
00405 // Tests that death tests work when SIGPROF handler and timer are set.
00406 TEST_F(TestForDeathTest, FastSigprofActionSet) {
00407   testing::GTEST_FLAG(death_test_style) = "fast";
00408   SetSigprofActionAndTimer();
00409   EXPECT_DEATH(_exit(1), "");
00410   struct sigaction old_signal_action;
00411   DisableSigprofActionAndTimer(&old_signal_action);
00412   EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
00413 }
00414 
00415 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
00416   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00417   SetSigprofActionAndTimer();
00418   EXPECT_DEATH(_exit(1), "");
00419   struct sigaction old_signal_action;
00420   DisableSigprofActionAndTimer(&old_signal_action);
00421   EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
00422 }
00423 # endif  // GTEST_OS_LINUX
00424 
00425 // Repeats a representative sample of death tests in the "threadsafe" style:
00426 
00427 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
00428   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00429   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
00430 }
00431 
00432 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
00433   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00434   should_die_ = true;
00435   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
00436 }
00437 
00438 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
00439   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00440 
00441   for (int i = 0; i < 3; ++i)
00442     EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
00443 }
00444 
00445 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
00446   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00447 
00448   ChangeToRootDir();
00449   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
00450 
00451   ChangeToRootDir();
00452   ASSERT_DEATH(_exit(1), "");
00453 }
00454 
00455 TEST_F(TestForDeathTest, MixedStyles) {
00456   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00457   EXPECT_DEATH(_exit(1), "");
00458   testing::GTEST_FLAG(death_test_style) = "fast";
00459   EXPECT_DEATH(_exit(1), "");
00460 }
00461 
00462 # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
00463 
00464 namespace {
00465 
00466 bool pthread_flag;
00467 
00468 void SetPthreadFlag() {
00469   pthread_flag = true;
00470 }
00471 
00472 }  // namespace
00473 
00474 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
00475   if (!testing::GTEST_FLAG(death_test_use_fork)) {
00476     testing::GTEST_FLAG(death_test_style) = "threadsafe";
00477     pthread_flag = false;
00478     ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
00479     ASSERT_DEATH(_exit(1), "");
00480     ASSERT_FALSE(pthread_flag);
00481   }
00482 }
00483 
00484 # endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
00485 
00486 // Tests that a method of another class can be used in a death test.
00487 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
00488   const MayDie x(true);
00489   ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
00490 }
00491 
00492 // Tests that a global function can be used in a death test.
00493 TEST_F(TestForDeathTest, GlobalFunction) {
00494   EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
00495 }
00496 
00497 // Tests that any value convertible to an RE works as a second
00498 // argument to EXPECT_DEATH.
00499 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
00500   static const char regex_c_str[] = "GlobalFunction";
00501   EXPECT_DEATH(GlobalFunction(), regex_c_str);
00502 
00503   const testing::internal::RE regex(regex_c_str);
00504   EXPECT_DEATH(GlobalFunction(), regex);
00505 
00506 # if GTEST_HAS_GLOBAL_STRING
00507 
00508   const string regex_str(regex_c_str);
00509   EXPECT_DEATH(GlobalFunction(), regex_str);
00510 
00511 # endif  // GTEST_HAS_GLOBAL_STRING
00512 
00513   const ::std::string regex_std_str(regex_c_str);
00514   EXPECT_DEATH(GlobalFunction(), regex_std_str);
00515 }
00516 
00517 // Tests that a non-void function can be used in a death test.
00518 TEST_F(TestForDeathTest, NonVoidFunction) {
00519   ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
00520 }
00521 
00522 // Tests that functions that take parameter(s) can be used in a death test.
00523 TEST_F(TestForDeathTest, FunctionWithParameter) {
00524   EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
00525   EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
00526 }
00527 
00528 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
00529 TEST_F(TestForDeathTest, OutsideFixture) {
00530   DeathTestSubroutine();
00531 }
00532 
00533 // Tests that death tests can be done inside a loop.
00534 TEST_F(TestForDeathTest, InsideLoop) {
00535   for (int i = 0; i < 5; i++) {
00536     EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
00537   }
00538 }
00539 
00540 // Tests that a compound statement can be used in a death test.
00541 TEST_F(TestForDeathTest, CompoundStatement) {
00542   EXPECT_DEATH({  // NOLINT
00543     const int x = 2;
00544     const int y = x + 1;
00545     DieIfLessThan(x, y);
00546   },
00547   "DieIfLessThan");
00548 }
00549 
00550 // Tests that code that doesn't die causes a death test to fail.
00551 TEST_F(TestForDeathTest, DoesNotDie) {
00552   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
00553                           "failed to die");
00554 }
00555 
00556 // Tests that a death test fails when the error message isn't expected.
00557 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
00558   EXPECT_NONFATAL_FAILURE({  // NOLINT
00559     EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
00560   }, "died but not with expected error");
00561 }
00562 
00563 // On exit, *aborted will be true iff the EXPECT_DEATH() statement
00564 // aborted the function.
00565 void ExpectDeathTestHelper(bool* aborted) {
00566   *aborted = true;
00567   EXPECT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
00568   *aborted = false;
00569 }
00570 
00571 // Tests that EXPECT_DEATH doesn't abort the test on failure.
00572 TEST_F(TestForDeathTest, EXPECT_DEATH) {
00573   bool aborted = true;
00574   EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
00575                           "failed to die");
00576   EXPECT_FALSE(aborted);
00577 }
00578 
00579 // Tests that ASSERT_DEATH does abort the test on failure.
00580 TEST_F(TestForDeathTest, ASSERT_DEATH) {
00581   static bool aborted;
00582   EXPECT_FATAL_FAILURE({  // NOLINT
00583     aborted = true;
00584     ASSERT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
00585     aborted = false;
00586   }, "failed to die");
00587   EXPECT_TRUE(aborted);
00588 }
00589 
00590 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
00591 TEST_F(TestForDeathTest, SingleEvaluation) {
00592   int x = 3;
00593   EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
00594 
00595   const char* regex = "DieIf";
00596   const char* regex_save = regex;
00597   EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
00598   EXPECT_EQ(regex_save + 1, regex);
00599 }
00600 
00601 // Tests that run-away death tests are reported as failures.
00602 TEST_F(TestForDeathTest, RunawayIsFailure) {
00603   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
00604                           "failed to die.");
00605 }
00606 
00607 // Tests that death tests report executing 'return' in the statement as
00608 // failure.
00609 TEST_F(TestForDeathTest, ReturnIsFailure) {
00610   EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
00611                        "illegal return in test statement.");
00612 }
00613 
00614 // Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
00615 // message to it, and in debug mode it:
00616 // 1. Asserts on death.
00617 // 2. Has no side effect.
00618 //
00619 // And in opt mode, it:
00620 // 1.  Has side effects but does not assert.
00621 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
00622   int sideeffect = 0;
00623 
00624   EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
00625       << "Must accept a streamed message";
00626 
00627 # ifdef NDEBUG
00628 
00629   // Checks that the assignment occurs in opt mode (sideeffect).
00630   EXPECT_EQ(12, sideeffect);
00631 
00632 # else
00633 
00634   // Checks that the assignment does not occur in dbg mode (no sideeffect).
00635   EXPECT_EQ(0, sideeffect);
00636 
00637 # endif
00638 }
00639 
00640 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
00641 // message to it, and in debug mode it:
00642 // 1. Asserts on death.
00643 // 2. Has no side effect.
00644 //
00645 // And in opt mode, it:
00646 // 1.  Has side effects but does not assert.
00647 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
00648   int sideeffect = 0;
00649 
00650   ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
00651       << "Must accept a streamed message";
00652 
00653 # ifdef NDEBUG
00654 
00655   // Checks that the assignment occurs in opt mode (sideeffect).
00656   EXPECT_EQ(12, sideeffect);
00657 
00658 # else
00659 
00660   // Checks that the assignment does not occur in dbg mode (no sideeffect).
00661   EXPECT_EQ(0, sideeffect);
00662 
00663 # endif
00664 }
00665 
00666 # ifndef NDEBUG
00667 
00668 void ExpectDebugDeathHelper(bool* aborted) {
00669   *aborted = true;
00670   EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
00671   *aborted = false;
00672 }
00673 
00674 #  if GTEST_OS_WINDOWS
00675 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
00676   printf("This test should be considered failing if it shows "
00677          "any pop-up dialogs.\n");
00678   fflush(stdout);
00679 
00680   EXPECT_DEATH({
00681     testing::GTEST_FLAG(catch_exceptions) = false;
00682     abort();
00683   }, "");
00684 }
00685 #  endif  // GTEST_OS_WINDOWS
00686 
00687 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
00688 // the function.
00689 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
00690   bool aborted = true;
00691   EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
00692   EXPECT_FALSE(aborted);
00693 }
00694 
00695 void AssertDebugDeathHelper(bool* aborted) {
00696   *aborted = true;
00697   GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH";
00698   ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "")
00699       << "This is expected to fail.";
00700   GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH";
00701   *aborted = false;
00702 }
00703 
00704 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
00705 // failure.
00706 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
00707   static bool aborted;
00708   aborted = false;
00709   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00710   EXPECT_TRUE(aborted);
00711 }
00712 
00713 TEST_F(TestForDeathTest, AssertDebugDeathAborts2) {
00714   static bool aborted;
00715   aborted = false;
00716   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00717   EXPECT_TRUE(aborted);
00718 }
00719 
00720 TEST_F(TestForDeathTest, AssertDebugDeathAborts3) {
00721   static bool aborted;
00722   aborted = false;
00723   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00724   EXPECT_TRUE(aborted);
00725 }
00726 
00727 TEST_F(TestForDeathTest, AssertDebugDeathAborts4) {
00728   static bool aborted;
00729   aborted = false;
00730   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00731   EXPECT_TRUE(aborted);
00732 }
00733 
00734 TEST_F(TestForDeathTest, AssertDebugDeathAborts5) {
00735   static bool aborted;
00736   aborted = false;
00737   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00738   EXPECT_TRUE(aborted);
00739 }
00740 
00741 TEST_F(TestForDeathTest, AssertDebugDeathAborts6) {
00742   static bool aborted;
00743   aborted = false;
00744   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00745   EXPECT_TRUE(aborted);
00746 }
00747 
00748 TEST_F(TestForDeathTest, AssertDebugDeathAborts7) {
00749   static bool aborted;
00750   aborted = false;
00751   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00752   EXPECT_TRUE(aborted);
00753 }
00754 
00755 TEST_F(TestForDeathTest, AssertDebugDeathAborts8) {
00756   static bool aborted;
00757   aborted = false;
00758   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00759   EXPECT_TRUE(aborted);
00760 }
00761 
00762 TEST_F(TestForDeathTest, AssertDebugDeathAborts9) {
00763   static bool aborted;
00764   aborted = false;
00765   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00766   EXPECT_TRUE(aborted);
00767 }
00768 
00769 TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
00770   static bool aborted;
00771   aborted = false;
00772   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00773   EXPECT_TRUE(aborted);
00774 }
00775 
00776 # endif  // _NDEBUG
00777 
00778 // Tests the *_EXIT family of macros, using a variety of predicates.
00779 static void TestExitMacros() {
00780   EXPECT_EXIT(_exit(1),  testing::ExitedWithCode(1),  "");
00781   ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
00782 
00783 # if GTEST_OS_WINDOWS
00784 
00785   // Of all signals effects on the process exit code, only those of SIGABRT
00786   // are documented on Windows.
00787   // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
00788   EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
00789 
00790 # else
00791 
00792   EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
00793   ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
00794 
00795   EXPECT_FATAL_FAILURE({  // NOLINT
00796     ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
00797       << "This failure is expected, too.";
00798   }, "This failure is expected, too.");
00799 
00800 # endif  // GTEST_OS_WINDOWS
00801 
00802   EXPECT_NONFATAL_FAILURE({  // NOLINT
00803     EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
00804       << "This failure is expected.";
00805   }, "This failure is expected.");
00806 }
00807 
00808 TEST_F(TestForDeathTest, ExitMacros) {
00809   TestExitMacros();
00810 }
00811 
00812 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
00813   testing::GTEST_FLAG(death_test_use_fork) = true;
00814   TestExitMacros();
00815 }
00816 
00817 TEST_F(TestForDeathTest, InvalidStyle) {
00818   testing::GTEST_FLAG(death_test_style) = "rococo";
00819   EXPECT_NONFATAL_FAILURE({  // NOLINT
00820     EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
00821   }, "This failure is expected.");
00822 }
00823 
00824 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
00825   testing::GTEST_FLAG(death_test_style) = "fast";
00826   EXPECT_NONFATAL_FAILURE(
00827       EXPECT_DEATH(DieWithMessage("death\n"),
00828                    "expected message"),
00829       "Actual msg:\n"
00830       "[  DEATH   ] death\n");
00831 }
00832 
00833 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
00834   testing::GTEST_FLAG(death_test_style) = "fast";
00835   EXPECT_NONFATAL_FAILURE(
00836       EXPECT_DEATH({
00837           fprintf(stderr, "returning\n");
00838           fflush(stderr);
00839           return;
00840         }, ""),
00841       "    Result: illegal return in test statement.\n"
00842       " Error msg:\n"
00843       "[  DEATH   ] returning\n");
00844 }
00845 
00846 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
00847   testing::GTEST_FLAG(death_test_style) = "fast";
00848   EXPECT_NONFATAL_FAILURE(
00849       EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
00850                   testing::ExitedWithCode(3),
00851                   "expected message"),
00852       "    Result: died but not with expected exit code:\n"
00853       "            Exited with exit status 1\n"
00854       "Actual msg:\n"
00855       "[  DEATH   ] exiting with rc 1\n");
00856 }
00857 
00858 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
00859   testing::GTEST_FLAG(death_test_style) = "fast";
00860   EXPECT_NONFATAL_FAILURE(
00861       EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
00862                    "line 1\nxyz\nline 3\n"),
00863       "Actual msg:\n"
00864       "[  DEATH   ] line 1\n"
00865       "[  DEATH   ] line 2\n"
00866       "[  DEATH   ] line 3\n");
00867 }
00868 
00869 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
00870   testing::GTEST_FLAG(death_test_style) = "fast";
00871   EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
00872                "line 1\nline 2\nline 3\n");
00873 }
00874 
00875 // A DeathTestFactory that returns MockDeathTests.
00876 class MockDeathTestFactory : public DeathTestFactory {
00877  public:
00878   MockDeathTestFactory();
00879   virtual bool Create(const char* statement,
00880                       const ::testing::internal::RE* regex,
00881                       const char* file, int line, DeathTest** test);
00882 
00883   // Sets the parameters for subsequent calls to Create.
00884   void SetParameters(bool create, DeathTest::TestRole role,
00885                      int status, bool passed);
00886 
00887   // Accessors.
00888   int AssumeRoleCalls() const { return assume_role_calls_; }
00889   int WaitCalls() const { return wait_calls_; }
00890   int PassedCalls() const { return passed_args_.size(); }
00891   bool PassedArgument(int n) const { return passed_args_[n]; }
00892   int AbortCalls() const { return abort_args_.size(); }
00893   DeathTest::AbortReason AbortArgument(int n) const {
00894     return abort_args_[n];
00895   }
00896   bool TestDeleted() const { return test_deleted_; }
00897 
00898  private:
00899   friend class MockDeathTest;
00900   // If true, Create will return a MockDeathTest; otherwise it returns
00901   // NULL.
00902   bool create_;
00903   // The value a MockDeathTest will return from its AssumeRole method.
00904   DeathTest::TestRole role_;
00905   // The value a MockDeathTest will return from its Wait method.
00906   int status_;
00907   // The value a MockDeathTest will return from its Passed method.
00908   bool passed_;
00909 
00910   // Number of times AssumeRole was called.
00911   int assume_role_calls_;
00912   // Number of times Wait was called.
00913   int wait_calls_;
00914   // The arguments to the calls to Passed since the last call to
00915   // SetParameters.
00916   std::vector<bool> passed_args_;
00917   // The arguments to the calls to Abort since the last call to
00918   // SetParameters.
00919   std::vector<DeathTest::AbortReason> abort_args_;
00920   // True if the last MockDeathTest returned by Create has been
00921   // deleted.
00922   bool test_deleted_;
00923 };
00924 
00925 
00926 // A DeathTest implementation useful in testing.  It returns values set
00927 // at its creation from its various inherited DeathTest methods, and
00928 // reports calls to those methods to its parent MockDeathTestFactory
00929 // object.
00930 class MockDeathTest : public DeathTest {
00931  public:
00932   MockDeathTest(MockDeathTestFactory *parent,
00933                 TestRole role, int status, bool passed) :
00934       parent_(parent), role_(role), status_(status), passed_(passed) {
00935   }
00936   virtual ~MockDeathTest() {
00937     parent_->test_deleted_ = true;
00938   }
00939   virtual TestRole AssumeRole() {
00940     ++parent_->assume_role_calls_;
00941     return role_;
00942   }
00943   virtual int Wait() {
00944     ++parent_->wait_calls_;
00945     return status_;
00946   }
00947   virtual bool Passed(bool exit_status_ok) {
00948     parent_->passed_args_.push_back(exit_status_ok);
00949     return passed_;
00950   }
00951   virtual void Abort(AbortReason reason) {
00952     parent_->abort_args_.push_back(reason);
00953   }
00954 
00955  private:
00956   MockDeathTestFactory* const parent_;
00957   const TestRole role_;
00958   const int status_;
00959   const bool passed_;
00960 };
00961 
00962 
00963 // MockDeathTestFactory constructor.
00964 MockDeathTestFactory::MockDeathTestFactory()
00965     : create_(true),
00966       role_(DeathTest::OVERSEE_TEST),
00967       status_(0),
00968       passed_(true),
00969       assume_role_calls_(0),
00970       wait_calls_(0),
00971       passed_args_(),
00972       abort_args_() {
00973 }
00974 
00975 
00976 // Sets the parameters for subsequent calls to Create.
00977 void MockDeathTestFactory::SetParameters(bool create,
00978                                          DeathTest::TestRole role,
00979                                          int status, bool passed) {
00980   create_ = create;
00981   role_ = role;
00982   status_ = status;
00983   passed_ = passed;
00984 
00985   assume_role_calls_ = 0;
00986   wait_calls_ = 0;
00987   passed_args_.clear();
00988   abort_args_.clear();
00989 }
00990 
00991 
00992 // Sets test to NULL (if create_ is false) or to the address of a new
00993 // MockDeathTest object with parameters taken from the last call
00994 // to SetParameters (if create_ is true).  Always returns true.
00995 bool MockDeathTestFactory::Create(const char* /*statement*/,
00996                                   const ::testing::internal::RE* /*regex*/,
00997                                   const char* /*file*/,
00998                                   int /*line*/,
00999                                   DeathTest** test) {
01000   test_deleted_ = false;
01001   if (create_) {
01002     *test = new MockDeathTest(this, role_, status_, passed_);
01003   } else {
01004     *test = NULL;
01005   }
01006   return true;
01007 }
01008 
01009 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
01010 // It installs a MockDeathTestFactory that is used for the duration
01011 // of the test case.
01012 class MacroLogicDeathTest : public testing::Test {
01013  protected:
01014   static testing::internal::ReplaceDeathTestFactory* replacer_;
01015   static MockDeathTestFactory* factory_;
01016 
01017   static void SetUpTestCase() {
01018     factory_ = new MockDeathTestFactory;
01019     replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
01020   }
01021 
01022   static void TearDownTestCase() {
01023     delete replacer_;
01024     replacer_ = NULL;
01025     delete factory_;
01026     factory_ = NULL;
01027   }
01028 
01029   // Runs a death test that breaks the rules by returning.  Such a death
01030   // test cannot be run directly from a test routine that uses a
01031   // MockDeathTest, or the remainder of the routine will not be executed.
01032   static void RunReturningDeathTest(bool* flag) {
01033     ASSERT_DEATH({  // NOLINT
01034       *flag = true;
01035       return;
01036     }, "");
01037   }
01038 };
01039 
01040 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
01041     = NULL;
01042 MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
01043 
01044 
01045 // Test that nothing happens when the factory doesn't return a DeathTest:
01046 TEST_F(MacroLogicDeathTest, NothingHappens) {
01047   bool flag = false;
01048   factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
01049   EXPECT_DEATH(flag = true, "");
01050   EXPECT_FALSE(flag);
01051   EXPECT_EQ(0, factory_->AssumeRoleCalls());
01052   EXPECT_EQ(0, factory_->WaitCalls());
01053   EXPECT_EQ(0, factory_->PassedCalls());
01054   EXPECT_EQ(0, factory_->AbortCalls());
01055   EXPECT_FALSE(factory_->TestDeleted());
01056 }
01057 
01058 // Test that the parent process doesn't run the death test code,
01059 // and that the Passed method returns false when the (simulated)
01060 // child process exits with status 0:
01061 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
01062   bool flag = false;
01063   factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
01064   EXPECT_DEATH(flag = true, "");
01065   EXPECT_FALSE(flag);
01066   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01067   EXPECT_EQ(1, factory_->WaitCalls());
01068   ASSERT_EQ(1, factory_->PassedCalls());
01069   EXPECT_FALSE(factory_->PassedArgument(0));
01070   EXPECT_EQ(0, factory_->AbortCalls());
01071   EXPECT_TRUE(factory_->TestDeleted());
01072 }
01073 
01074 // Tests that the Passed method was given the argument "true" when
01075 // the (simulated) child process exits with status 1:
01076 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
01077   bool flag = false;
01078   factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
01079   EXPECT_DEATH(flag = true, "");
01080   EXPECT_FALSE(flag);
01081   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01082   EXPECT_EQ(1, factory_->WaitCalls());
01083   ASSERT_EQ(1, factory_->PassedCalls());
01084   EXPECT_TRUE(factory_->PassedArgument(0));
01085   EXPECT_EQ(0, factory_->AbortCalls());
01086   EXPECT_TRUE(factory_->TestDeleted());
01087 }
01088 
01089 // Tests that the (simulated) child process executes the death test
01090 // code, and is aborted with the correct AbortReason if it
01091 // executes a return statement.
01092 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
01093   bool flag = false;
01094   factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
01095   RunReturningDeathTest(&flag);
01096   EXPECT_TRUE(flag);
01097   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01098   EXPECT_EQ(0, factory_->WaitCalls());
01099   EXPECT_EQ(0, factory_->PassedCalls());
01100   EXPECT_EQ(1, factory_->AbortCalls());
01101   EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
01102             factory_->AbortArgument(0));
01103   EXPECT_TRUE(factory_->TestDeleted());
01104 }
01105 
01106 // Tests that the (simulated) child process is aborted with the
01107 // correct AbortReason if it does not die.
01108 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
01109   bool flag = false;
01110   factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
01111   EXPECT_DEATH(flag = true, "");
01112   EXPECT_TRUE(flag);
01113   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01114   EXPECT_EQ(0, factory_->WaitCalls());
01115   EXPECT_EQ(0, factory_->PassedCalls());
01116   // This time there are two calls to Abort: one since the test didn't
01117   // die, and another from the ReturnSentinel when it's destroyed.  The
01118   // sentinel normally isn't destroyed if a test doesn't die, since
01119   // _exit(2) is called in that case by ForkingDeathTest, but not by
01120   // our MockDeathTest.
01121   ASSERT_EQ(2, factory_->AbortCalls());
01122   EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
01123             factory_->AbortArgument(0));
01124   EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
01125             factory_->AbortArgument(1));
01126   EXPECT_TRUE(factory_->TestDeleted());
01127 }
01128 
01129 // Tests that a successful death test does not register a successful
01130 // test part.
01131 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
01132   EXPECT_DEATH(_exit(1), "");
01133   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
01134 }
01135 
01136 TEST(StreamingAssertionsDeathTest, DeathTest) {
01137   EXPECT_DEATH(_exit(1), "") << "unexpected failure";
01138   ASSERT_DEATH(_exit(1), "") << "unexpected failure";
01139   EXPECT_NONFATAL_FAILURE({  // NOLINT
01140     EXPECT_DEATH(_exit(0), "") << "expected failure";
01141   }, "expected failure");
01142   EXPECT_FATAL_FAILURE({  // NOLINT
01143     ASSERT_DEATH(_exit(0), "") << "expected failure";
01144   }, "expected failure");
01145 }
01146 
01147 // Tests that GetLastErrnoDescription returns an empty string when the
01148 // last error is 0 and non-empty string when it is non-zero.
01149 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
01150   errno = ENOENT;
01151   EXPECT_STRNE("", GetLastErrnoDescription().c_str());
01152   errno = 0;
01153   EXPECT_STREQ("", GetLastErrnoDescription().c_str());
01154 }
01155 
01156 # if GTEST_OS_WINDOWS
01157 TEST(AutoHandleTest, AutoHandleWorks) {
01158   HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
01159   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
01160 
01161   // Tests that the AutoHandle is correctly initialized with a handle.
01162   testing::internal::AutoHandle auto_handle(handle);
01163   EXPECT_EQ(handle, auto_handle.Get());
01164 
01165   // Tests that Reset assigns INVALID_HANDLE_VALUE.
01166   // Note that this cannot verify whether the original handle is closed.
01167   auto_handle.Reset();
01168   EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
01169 
01170   // Tests that Reset assigns the new handle.
01171   // Note that this cannot verify whether the original handle is closed.
01172   handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
01173   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
01174   auto_handle.Reset(handle);
01175   EXPECT_EQ(handle, auto_handle.Get());
01176 
01177   // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
01178   testing::internal::AutoHandle auto_handle2;
01179   EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
01180 }
01181 # endif  // GTEST_OS_WINDOWS
01182 
01183 # if GTEST_OS_WINDOWS
01184 typedef unsigned __int64 BiggestParsable;
01185 typedef signed __int64 BiggestSignedParsable;
01186 # else
01187 typedef unsigned long long BiggestParsable;
01188 typedef signed long long BiggestSignedParsable;
01189 # endif  // GTEST_OS_WINDOWS
01190 
01191 // We cannot use std::numeric_limits<T>::max() as it clashes with the
01192 // max() macro defined by <windows.h>.
01193 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
01194 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
01195 
01196 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
01197   BiggestParsable result = 0;
01198 
01199   // Rejects non-numbers.
01200   EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
01201 
01202   // Rejects numbers with whitespace prefix.
01203   EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
01204 
01205   // Rejects negative numbers.
01206   EXPECT_FALSE(ParseNaturalNumber("-123", &result));
01207 
01208   // Rejects numbers starting with a plus sign.
01209   EXPECT_FALSE(ParseNaturalNumber("+123", &result));
01210   errno = 0;
01211 }
01212 
01213 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
01214   BiggestParsable result = 0;
01215 
01216   EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
01217 
01218   signed char char_result = 0;
01219   EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
01220   errno = 0;
01221 }
01222 
01223 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
01224   BiggestParsable result = 0;
01225 
01226   result = 0;
01227   ASSERT_TRUE(ParseNaturalNumber("123", &result));
01228   EXPECT_EQ(123U, result);
01229 
01230   // Check 0 as an edge case.
01231   result = 1;
01232   ASSERT_TRUE(ParseNaturalNumber("0", &result));
01233   EXPECT_EQ(0U, result);
01234 
01235   result = 1;
01236   ASSERT_TRUE(ParseNaturalNumber("00000", &result));
01237   EXPECT_EQ(0U, result);
01238 }
01239 
01240 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
01241   Message msg;
01242   msg << kBiggestParsableMax;
01243 
01244   BiggestParsable result = 0;
01245   EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
01246   EXPECT_EQ(kBiggestParsableMax, result);
01247 
01248   Message msg2;
01249   msg2 << kBiggestSignedParsableMax;
01250 
01251   BiggestSignedParsable signed_result = 0;
01252   EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
01253   EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
01254 
01255   Message msg3;
01256   msg3 << INT_MAX;
01257 
01258   int int_result = 0;
01259   EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
01260   EXPECT_EQ(INT_MAX, int_result);
01261 
01262   Message msg4;
01263   msg4 << UINT_MAX;
01264 
01265   unsigned int uint_result = 0;
01266   EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
01267   EXPECT_EQ(UINT_MAX, uint_result);
01268 }
01269 
01270 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
01271   short short_result = 0;
01272   ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
01273   EXPECT_EQ(123, short_result);
01274 
01275   signed char char_result = 0;
01276   ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
01277   EXPECT_EQ(123, char_result);
01278 }
01279 
01280 # if GTEST_OS_WINDOWS
01281 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
01282   // TODO(vladl@google.com): Remove this test after this condition is verified
01283   // in a static assertion in gtest-death-test.cc in the function
01284   // GetStatusFileDescriptor.
01285   ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
01286 }
01287 # endif  // GTEST_OS_WINDOWS
01288 
01289 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
01290 // failures when death tests are available on the system.
01291 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
01292   EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
01293                             "death inside CondDeathTestExpectMacro");
01294   ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
01295                             "death inside CondDeathTestAssertMacro");
01296 
01297   // Empty statement will not crash, which must trigger a failure.
01298   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
01299   EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
01300 }
01301 
01302 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
01303   testing::GTEST_FLAG(death_test_style) = "fast";
01304   EXPECT_FALSE(InDeathTestChild());
01305   EXPECT_DEATH({
01306     fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
01307     fflush(stderr);
01308     _exit(1);
01309   }, "Inside");
01310 }
01311 
01312 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
01313   testing::GTEST_FLAG(death_test_style) = "threadsafe";
01314   EXPECT_FALSE(InDeathTestChild());
01315   EXPECT_DEATH({
01316     fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
01317     fflush(stderr);
01318     _exit(1);
01319   }, "Inside");
01320 }
01321 
01322 #else  // !GTEST_HAS_DEATH_TEST follows
01323 
01324 using testing::internal::CaptureStderr;
01325 using testing::internal::GetCapturedStderr;
01326 
01327 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
01328 // defined but do not trigger failures when death tests are not available on
01329 // the system.
01330 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
01331   // Empty statement will not crash, but that should not trigger a failure
01332   // when death tests are not supported.
01333   CaptureStderr();
01334   EXPECT_DEATH_IF_SUPPORTED(;, "");
01335   std::string output = GetCapturedStderr();
01336   ASSERT_TRUE(NULL != strstr(output.c_str(),
01337                              "Death tests are not supported on this platform"));
01338   ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
01339 
01340   // The streamed message should not be printed as there is no test failure.
01341   CaptureStderr();
01342   EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
01343   output = GetCapturedStderr();
01344   ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
01345 
01346   CaptureStderr();
01347   ASSERT_DEATH_IF_SUPPORTED(;, "");  // NOLINT
01348   output = GetCapturedStderr();
01349   ASSERT_TRUE(NULL != strstr(output.c_str(),
01350                              "Death tests are not supported on this platform"));
01351   ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
01352 
01353   CaptureStderr();
01354   ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message";  // NOLINT
01355   output = GetCapturedStderr();
01356   ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
01357 }
01358 
01359 void FuncWithAssert(int* n) {
01360   ASSERT_DEATH_IF_SUPPORTED(return;, "");
01361   (*n)++;
01362 }
01363 
01364 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
01365 // function (as ASSERT_DEATH does) if death tests are not supported.
01366 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
01367   int n = 0;
01368   FuncWithAssert(&n);
01369   EXPECT_EQ(1, n);
01370 }
01371 
01372 #endif  // !GTEST_HAS_DEATH_TEST
01373 
01374 // Tests that the death test macros expand to code which may or may not
01375 // be followed by operator<<, and that in either case the complete text
01376 // comprises only a single C++ statement.
01377 //
01378 // The syntax should work whether death tests are available or not.
01379 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
01380   if (AlwaysFalse())
01381     // This would fail if executed; this is a compilation test only
01382     ASSERT_DEATH_IF_SUPPORTED(return, "");
01383 
01384   if (AlwaysTrue())
01385     EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
01386   else
01387     // This empty "else" branch is meant to ensure that EXPECT_DEATH
01388     // doesn't expand into an "if" statement without an "else"
01389     ;  // NOLINT
01390 
01391   if (AlwaysFalse())
01392     ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
01393 
01394   if (AlwaysFalse())
01395     ;  // NOLINT
01396   else
01397     EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
01398 }
01399 
01400 // Tests that conditional death test macros expand to code which interacts
01401 // well with switch statements.
01402 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
01403   // Microsoft compiler usually complains about switch statements without
01404   // case labels. We suppress that warning for this test.
01405   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
01406 
01407   switch (0)
01408     default:
01409       ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
01410           << "exit in default switch handler";
01411 
01412   switch (0)
01413     case 0:
01414       EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
01415 
01416   GTEST_DISABLE_MSC_WARNINGS_POP_()
01417 }
01418 
01419 // Tests that a test case whose name ends with "DeathTest" works fine
01420 // on Windows.
01421 TEST(NotADeathTest, Test) {
01422   SUCCEED();
01423 }


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:03