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 # ifdef _MSC_VER
00332 #  pragma warning(push)
00333 #  pragma warning(disable: 4065)
00334 # endif  // _MSC_VER
00335 
00336   switch (0)
00337     default:
00338       ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
00339 
00340   switch (0)
00341     case 0:
00342       EXPECT_DEATH(_exit(1), "") << "exit in switch case";
00343 
00344 # ifdef _MSC_VER
00345 #  pragma warning(pop)
00346 # endif  // _MSC_VER
00347 }
00348 
00349 // Tests that a static member function can be used in a "fast" style
00350 // death test.
00351 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
00352   testing::GTEST_FLAG(death_test_style) = "fast";
00353   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
00354 }
00355 
00356 // Tests that a method of the test fixture can be used in a "fast"
00357 // style death test.
00358 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
00359   testing::GTEST_FLAG(death_test_style) = "fast";
00360   should_die_ = true;
00361   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
00362 }
00363 
00364 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
00365 
00366 // Tests that death tests work even if the current directory has been
00367 // changed.
00368 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
00369   testing::GTEST_FLAG(death_test_style) = "fast";
00370 
00371   ChangeToRootDir();
00372   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
00373 
00374   ChangeToRootDir();
00375   ASSERT_DEATH(_exit(1), "");
00376 }
00377 
00378 # if GTEST_OS_LINUX
00379 void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
00380 
00381 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
00382 void SetSigprofActionAndTimer() {
00383   struct itimerval timer;
00384   timer.it_interval.tv_sec = 0;
00385   timer.it_interval.tv_usec = 1;
00386   timer.it_value = timer.it_interval;
00387   ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
00388   struct sigaction signal_action;
00389   memset(&signal_action, 0, sizeof(signal_action));
00390   sigemptyset(&signal_action.sa_mask);
00391   signal_action.sa_sigaction = SigprofAction;
00392   signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
00393   ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL));
00394 }
00395 
00396 // Disables ITIMER_PROF timer and ignores SIGPROF signal.
00397 void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
00398   struct itimerval timer;
00399   timer.it_interval.tv_sec = 0;
00400   timer.it_interval.tv_usec = 0;
00401   timer.it_value = timer.it_interval;
00402   ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
00403   struct sigaction signal_action;
00404   memset(&signal_action, 0, sizeof(signal_action));
00405   sigemptyset(&signal_action.sa_mask);
00406   signal_action.sa_handler = SIG_IGN;
00407   ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
00408 }
00409 
00410 // Tests that death tests work when SIGPROF handler and timer are set.
00411 TEST_F(TestForDeathTest, FastSigprofActionSet) {
00412   testing::GTEST_FLAG(death_test_style) = "fast";
00413   SetSigprofActionAndTimer();
00414   EXPECT_DEATH(_exit(1), "");
00415   struct sigaction old_signal_action;
00416   DisableSigprofActionAndTimer(&old_signal_action);
00417   EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
00418 }
00419 
00420 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
00421   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00422   SetSigprofActionAndTimer();
00423   EXPECT_DEATH(_exit(1), "");
00424   struct sigaction old_signal_action;
00425   DisableSigprofActionAndTimer(&old_signal_action);
00426   EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
00427 }
00428 # endif  // GTEST_OS_LINUX
00429 
00430 // Repeats a representative sample of death tests in the "threadsafe" style:
00431 
00432 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
00433   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00434   ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
00435 }
00436 
00437 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
00438   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00439   should_die_ = true;
00440   EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
00441 }
00442 
00443 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
00444   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00445 
00446   for (int i = 0; i < 3; ++i)
00447     EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
00448 }
00449 
00450 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
00451   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00452 
00453   ChangeToRootDir();
00454   EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
00455 
00456   ChangeToRootDir();
00457   ASSERT_DEATH(_exit(1), "");
00458 }
00459 
00460 TEST_F(TestForDeathTest, MixedStyles) {
00461   testing::GTEST_FLAG(death_test_style) = "threadsafe";
00462   EXPECT_DEATH(_exit(1), "");
00463   testing::GTEST_FLAG(death_test_style) = "fast";
00464   EXPECT_DEATH(_exit(1), "");
00465 }
00466 
00467 # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
00468 
00469 namespace {
00470 
00471 bool pthread_flag;
00472 
00473 void SetPthreadFlag() {
00474   pthread_flag = true;
00475 }
00476 
00477 }  // namespace
00478 
00479 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
00480   if (!testing::GTEST_FLAG(death_test_use_fork)) {
00481     testing::GTEST_FLAG(death_test_style) = "threadsafe";
00482     pthread_flag = false;
00483     ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
00484     ASSERT_DEATH(_exit(1), "");
00485     ASSERT_FALSE(pthread_flag);
00486   }
00487 }
00488 
00489 # endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
00490 
00491 // Tests that a method of another class can be used in a death test.
00492 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
00493   const MayDie x(true);
00494   ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
00495 }
00496 
00497 // Tests that a global function can be used in a death test.
00498 TEST_F(TestForDeathTest, GlobalFunction) {
00499   EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
00500 }
00501 
00502 // Tests that any value convertible to an RE works as a second
00503 // argument to EXPECT_DEATH.
00504 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
00505   static const char regex_c_str[] = "GlobalFunction";
00506   EXPECT_DEATH(GlobalFunction(), regex_c_str);
00507 
00508   const testing::internal::RE regex(regex_c_str);
00509   EXPECT_DEATH(GlobalFunction(), regex);
00510 
00511 # if GTEST_HAS_GLOBAL_STRING
00512 
00513   const string regex_str(regex_c_str);
00514   EXPECT_DEATH(GlobalFunction(), regex_str);
00515 
00516 # endif  // GTEST_HAS_GLOBAL_STRING
00517 
00518   const ::std::string regex_std_str(regex_c_str);
00519   EXPECT_DEATH(GlobalFunction(), regex_std_str);
00520 }
00521 
00522 // Tests that a non-void function can be used in a death test.
00523 TEST_F(TestForDeathTest, NonVoidFunction) {
00524   ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
00525 }
00526 
00527 // Tests that functions that take parameter(s) can be used in a death test.
00528 TEST_F(TestForDeathTest, FunctionWithParameter) {
00529   EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
00530   EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
00531 }
00532 
00533 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
00534 TEST_F(TestForDeathTest, OutsideFixture) {
00535   DeathTestSubroutine();
00536 }
00537 
00538 // Tests that death tests can be done inside a loop.
00539 TEST_F(TestForDeathTest, InsideLoop) {
00540   for (int i = 0; i < 5; i++) {
00541     EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
00542   }
00543 }
00544 
00545 // Tests that a compound statement can be used in a death test.
00546 TEST_F(TestForDeathTest, CompoundStatement) {
00547   EXPECT_DEATH({  // NOLINT
00548     const int x = 2;
00549     const int y = x + 1;
00550     DieIfLessThan(x, y);
00551   },
00552   "DieIfLessThan");
00553 }
00554 
00555 // Tests that code that doesn't die causes a death test to fail.
00556 TEST_F(TestForDeathTest, DoesNotDie) {
00557   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
00558                           "failed to die");
00559 }
00560 
00561 // Tests that a death test fails when the error message isn't expected.
00562 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
00563   EXPECT_NONFATAL_FAILURE({  // NOLINT
00564     EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
00565   }, "died but not with expected error");
00566 }
00567 
00568 // On exit, *aborted will be true iff the EXPECT_DEATH() statement
00569 // aborted the function.
00570 void ExpectDeathTestHelper(bool* aborted) {
00571   *aborted = true;
00572   EXPECT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
00573   *aborted = false;
00574 }
00575 
00576 // Tests that EXPECT_DEATH doesn't abort the test on failure.
00577 TEST_F(TestForDeathTest, EXPECT_DEATH) {
00578   bool aborted = true;
00579   EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
00580                           "failed to die");
00581   EXPECT_FALSE(aborted);
00582 }
00583 
00584 // Tests that ASSERT_DEATH does abort the test on failure.
00585 TEST_F(TestForDeathTest, ASSERT_DEATH) {
00586   static bool aborted;
00587   EXPECT_FATAL_FAILURE({  // NOLINT
00588     aborted = true;
00589     ASSERT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
00590     aborted = false;
00591   }, "failed to die");
00592   EXPECT_TRUE(aborted);
00593 }
00594 
00595 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
00596 TEST_F(TestForDeathTest, SingleEvaluation) {
00597   int x = 3;
00598   EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
00599 
00600   const char* regex = "DieIf";
00601   const char* regex_save = regex;
00602   EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
00603   EXPECT_EQ(regex_save + 1, regex);
00604 }
00605 
00606 // Tests that run-away death tests are reported as failures.
00607 TEST_F(TestForDeathTest, RunawayIsFailure) {
00608   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
00609                           "failed to die.");
00610 }
00611 
00612 // Tests that death tests report executing 'return' in the statement as
00613 // failure.
00614 TEST_F(TestForDeathTest, ReturnIsFailure) {
00615   EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
00616                        "illegal return in test statement.");
00617 }
00618 
00619 // Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
00620 // message to it, and in debug mode it:
00621 // 1. Asserts on death.
00622 // 2. Has no side effect.
00623 //
00624 // And in opt mode, it:
00625 // 1.  Has side effects but does not assert.
00626 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
00627   int sideeffect = 0;
00628 
00629   EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
00630       << "Must accept a streamed message";
00631 
00632 # ifdef NDEBUG
00633 
00634   // Checks that the assignment occurs in opt mode (sideeffect).
00635   EXPECT_EQ(12, sideeffect);
00636 
00637 # else
00638 
00639   // Checks that the assignment does not occur in dbg mode (no sideeffect).
00640   EXPECT_EQ(0, sideeffect);
00641 
00642 # endif
00643 }
00644 
00645 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
00646 // message to it, and in debug mode it:
00647 // 1. Asserts on death.
00648 // 2. Has no side effect.
00649 //
00650 // And in opt mode, it:
00651 // 1.  Has side effects but does not assert.
00652 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
00653   int sideeffect = 0;
00654 
00655   ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
00656       << "Must accept a streamed message";
00657 
00658 # ifdef NDEBUG
00659 
00660   // Checks that the assignment occurs in opt mode (sideeffect).
00661   EXPECT_EQ(12, sideeffect);
00662 
00663 # else
00664 
00665   // Checks that the assignment does not occur in dbg mode (no sideeffect).
00666   EXPECT_EQ(0, sideeffect);
00667 
00668 # endif
00669 }
00670 
00671 # ifndef NDEBUG
00672 
00673 void ExpectDebugDeathHelper(bool* aborted) {
00674   *aborted = true;
00675   EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
00676   *aborted = false;
00677 }
00678 
00679 #  if GTEST_OS_WINDOWS
00680 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
00681   printf("This test should be considered failing if it shows "
00682          "any pop-up dialogs.\n");
00683   fflush(stdout);
00684 
00685   EXPECT_DEATH({
00686     testing::GTEST_FLAG(catch_exceptions) = false;
00687     abort();
00688   }, "");
00689 }
00690 #  endif  // GTEST_OS_WINDOWS
00691 
00692 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
00693 // the function.
00694 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
00695   bool aborted = true;
00696   EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
00697   EXPECT_FALSE(aborted);
00698 }
00699 
00700 void AssertDebugDeathHelper(bool* aborted) {
00701   *aborted = true;
00702   ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
00703   *aborted = false;
00704 }
00705 
00706 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
00707 // failure.
00708 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
00709   static bool aborted;
00710   aborted = false;
00711   EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
00712   EXPECT_TRUE(aborted);
00713 }
00714 
00715 # endif  // _NDEBUG
00716 
00717 // Tests the *_EXIT family of macros, using a variety of predicates.
00718 static void TestExitMacros() {
00719   EXPECT_EXIT(_exit(1),  testing::ExitedWithCode(1),  "");
00720   ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
00721 
00722 # if GTEST_OS_WINDOWS
00723 
00724   // Of all signals effects on the process exit code, only those of SIGABRT
00725   // are documented on Windows.
00726   // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
00727   EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
00728 
00729 # else
00730 
00731   EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
00732   ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
00733 
00734   EXPECT_FATAL_FAILURE({  // NOLINT
00735     ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
00736       << "This failure is expected, too.";
00737   }, "This failure is expected, too.");
00738 
00739 # endif  // GTEST_OS_WINDOWS
00740 
00741   EXPECT_NONFATAL_FAILURE({  // NOLINT
00742     EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
00743       << "This failure is expected.";
00744   }, "This failure is expected.");
00745 }
00746 
00747 TEST_F(TestForDeathTest, ExitMacros) {
00748   TestExitMacros();
00749 }
00750 
00751 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
00752   testing::GTEST_FLAG(death_test_use_fork) = true;
00753   TestExitMacros();
00754 }
00755 
00756 TEST_F(TestForDeathTest, InvalidStyle) {
00757   testing::GTEST_FLAG(death_test_style) = "rococo";
00758   EXPECT_NONFATAL_FAILURE({  // NOLINT
00759     EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
00760   }, "This failure is expected.");
00761 }
00762 
00763 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
00764   testing::GTEST_FLAG(death_test_style) = "fast";
00765   EXPECT_NONFATAL_FAILURE(
00766       EXPECT_DEATH(DieWithMessage("death\n"),
00767                    "expected message"),
00768       "Actual msg:\n"
00769       "[  DEATH   ] death\n");
00770 }
00771 
00772 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
00773   testing::GTEST_FLAG(death_test_style) = "fast";
00774   EXPECT_NONFATAL_FAILURE(
00775       EXPECT_DEATH({
00776           fprintf(stderr, "returning\n");
00777           fflush(stderr);
00778           return;
00779         }, ""),
00780       "    Result: illegal return in test statement.\n"
00781       " Error msg:\n"
00782       "[  DEATH   ] returning\n");
00783 }
00784 
00785 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
00786   testing::GTEST_FLAG(death_test_style) = "fast";
00787   EXPECT_NONFATAL_FAILURE(
00788       EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
00789                   testing::ExitedWithCode(3),
00790                   "expected message"),
00791       "    Result: died but not with expected exit code:\n"
00792       "            Exited with exit status 1\n"
00793       "Actual msg:\n"
00794       "[  DEATH   ] exiting with rc 1\n");
00795 }
00796 
00797 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
00798   testing::GTEST_FLAG(death_test_style) = "fast";
00799   EXPECT_NONFATAL_FAILURE(
00800       EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
00801                    "line 1\nxyz\nline 3\n"),
00802       "Actual msg:\n"
00803       "[  DEATH   ] line 1\n"
00804       "[  DEATH   ] line 2\n"
00805       "[  DEATH   ] line 3\n");
00806 }
00807 
00808 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
00809   testing::GTEST_FLAG(death_test_style) = "fast";
00810   EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
00811                "line 1\nline 2\nline 3\n");
00812 }
00813 
00814 // A DeathTestFactory that returns MockDeathTests.
00815 class MockDeathTestFactory : public DeathTestFactory {
00816  public:
00817   MockDeathTestFactory();
00818   virtual bool Create(const char* statement,
00819                       const ::testing::internal::RE* regex,
00820                       const char* file, int line, DeathTest** test);
00821 
00822   // Sets the parameters for subsequent calls to Create.
00823   void SetParameters(bool create, DeathTest::TestRole role,
00824                      int status, bool passed);
00825 
00826   // Accessors.
00827   int AssumeRoleCalls() const { return assume_role_calls_; }
00828   int WaitCalls() const { return wait_calls_; }
00829   int PassedCalls() const { return passed_args_.size(); }
00830   bool PassedArgument(int n) const { return passed_args_[n]; }
00831   int AbortCalls() const { return abort_args_.size(); }
00832   DeathTest::AbortReason AbortArgument(int n) const {
00833     return abort_args_[n];
00834   }
00835   bool TestDeleted() const { return test_deleted_; }
00836 
00837  private:
00838   friend class MockDeathTest;
00839   // If true, Create will return a MockDeathTest; otherwise it returns
00840   // NULL.
00841   bool create_;
00842   // The value a MockDeathTest will return from its AssumeRole method.
00843   DeathTest::TestRole role_;
00844   // The value a MockDeathTest will return from its Wait method.
00845   int status_;
00846   // The value a MockDeathTest will return from its Passed method.
00847   bool passed_;
00848 
00849   // Number of times AssumeRole was called.
00850   int assume_role_calls_;
00851   // Number of times Wait was called.
00852   int wait_calls_;
00853   // The arguments to the calls to Passed since the last call to
00854   // SetParameters.
00855   std::vector<bool> passed_args_;
00856   // The arguments to the calls to Abort since the last call to
00857   // SetParameters.
00858   std::vector<DeathTest::AbortReason> abort_args_;
00859   // True if the last MockDeathTest returned by Create has been
00860   // deleted.
00861   bool test_deleted_;
00862 };
00863 
00864 
00865 // A DeathTest implementation useful in testing.  It returns values set
00866 // at its creation from its various inherited DeathTest methods, and
00867 // reports calls to those methods to its parent MockDeathTestFactory
00868 // object.
00869 class MockDeathTest : public DeathTest {
00870  public:
00871   MockDeathTest(MockDeathTestFactory *parent,
00872                 TestRole role, int status, bool passed) :
00873       parent_(parent), role_(role), status_(status), passed_(passed) {
00874   }
00875   virtual ~MockDeathTest() {
00876     parent_->test_deleted_ = true;
00877   }
00878   virtual TestRole AssumeRole() {
00879     ++parent_->assume_role_calls_;
00880     return role_;
00881   }
00882   virtual int Wait() {
00883     ++parent_->wait_calls_;
00884     return status_;
00885   }
00886   virtual bool Passed(bool exit_status_ok) {
00887     parent_->passed_args_.push_back(exit_status_ok);
00888     return passed_;
00889   }
00890   virtual void Abort(AbortReason reason) {
00891     parent_->abort_args_.push_back(reason);
00892   }
00893 
00894  private:
00895   MockDeathTestFactory* const parent_;
00896   const TestRole role_;
00897   const int status_;
00898   const bool passed_;
00899 };
00900 
00901 
00902 // MockDeathTestFactory constructor.
00903 MockDeathTestFactory::MockDeathTestFactory()
00904     : create_(true),
00905       role_(DeathTest::OVERSEE_TEST),
00906       status_(0),
00907       passed_(true),
00908       assume_role_calls_(0),
00909       wait_calls_(0),
00910       passed_args_(),
00911       abort_args_() {
00912 }
00913 
00914 
00915 // Sets the parameters for subsequent calls to Create.
00916 void MockDeathTestFactory::SetParameters(bool create,
00917                                          DeathTest::TestRole role,
00918                                          int status, bool passed) {
00919   create_ = create;
00920   role_ = role;
00921   status_ = status;
00922   passed_ = passed;
00923 
00924   assume_role_calls_ = 0;
00925   wait_calls_ = 0;
00926   passed_args_.clear();
00927   abort_args_.clear();
00928 }
00929 
00930 
00931 // Sets test to NULL (if create_ is false) or to the address of a new
00932 // MockDeathTest object with parameters taken from the last call
00933 // to SetParameters (if create_ is true).  Always returns true.
00934 bool MockDeathTestFactory::Create(const char* /*statement*/,
00935                                   const ::testing::internal::RE* /*regex*/,
00936                                   const char* /*file*/,
00937                                   int /*line*/,
00938                                   DeathTest** test) {
00939   test_deleted_ = false;
00940   if (create_) {
00941     *test = new MockDeathTest(this, role_, status_, passed_);
00942   } else {
00943     *test = NULL;
00944   }
00945   return true;
00946 }
00947 
00948 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
00949 // It installs a MockDeathTestFactory that is used for the duration
00950 // of the test case.
00951 class MacroLogicDeathTest : public testing::Test {
00952  protected:
00953   static testing::internal::ReplaceDeathTestFactory* replacer_;
00954   static MockDeathTestFactory* factory_;
00955 
00956   static void SetUpTestCase() {
00957     factory_ = new MockDeathTestFactory;
00958     replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
00959   }
00960 
00961   static void TearDownTestCase() {
00962     delete replacer_;
00963     replacer_ = NULL;
00964     delete factory_;
00965     factory_ = NULL;
00966   }
00967 
00968   // Runs a death test that breaks the rules by returning.  Such a death
00969   // test cannot be run directly from a test routine that uses a
00970   // MockDeathTest, or the remainder of the routine will not be executed.
00971   static void RunReturningDeathTest(bool* flag) {
00972     ASSERT_DEATH({  // NOLINT
00973       *flag = true;
00974       return;
00975     }, "");
00976   }
00977 };
00978 
00979 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
00980     = NULL;
00981 MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
00982 
00983 
00984 // Test that nothing happens when the factory doesn't return a DeathTest:
00985 TEST_F(MacroLogicDeathTest, NothingHappens) {
00986   bool flag = false;
00987   factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
00988   EXPECT_DEATH(flag = true, "");
00989   EXPECT_FALSE(flag);
00990   EXPECT_EQ(0, factory_->AssumeRoleCalls());
00991   EXPECT_EQ(0, factory_->WaitCalls());
00992   EXPECT_EQ(0, factory_->PassedCalls());
00993   EXPECT_EQ(0, factory_->AbortCalls());
00994   EXPECT_FALSE(factory_->TestDeleted());
00995 }
00996 
00997 // Test that the parent process doesn't run the death test code,
00998 // and that the Passed method returns false when the (simulated)
00999 // child process exits with status 0:
01000 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
01001   bool flag = false;
01002   factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
01003   EXPECT_DEATH(flag = true, "");
01004   EXPECT_FALSE(flag);
01005   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01006   EXPECT_EQ(1, factory_->WaitCalls());
01007   ASSERT_EQ(1, factory_->PassedCalls());
01008   EXPECT_FALSE(factory_->PassedArgument(0));
01009   EXPECT_EQ(0, factory_->AbortCalls());
01010   EXPECT_TRUE(factory_->TestDeleted());
01011 }
01012 
01013 // Tests that the Passed method was given the argument "true" when
01014 // the (simulated) child process exits with status 1:
01015 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
01016   bool flag = false;
01017   factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
01018   EXPECT_DEATH(flag = true, "");
01019   EXPECT_FALSE(flag);
01020   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01021   EXPECT_EQ(1, factory_->WaitCalls());
01022   ASSERT_EQ(1, factory_->PassedCalls());
01023   EXPECT_TRUE(factory_->PassedArgument(0));
01024   EXPECT_EQ(0, factory_->AbortCalls());
01025   EXPECT_TRUE(factory_->TestDeleted());
01026 }
01027 
01028 // Tests that the (simulated) child process executes the death test
01029 // code, and is aborted with the correct AbortReason if it
01030 // executes a return statement.
01031 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
01032   bool flag = false;
01033   factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
01034   RunReturningDeathTest(&flag);
01035   EXPECT_TRUE(flag);
01036   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01037   EXPECT_EQ(0, factory_->WaitCalls());
01038   EXPECT_EQ(0, factory_->PassedCalls());
01039   EXPECT_EQ(1, factory_->AbortCalls());
01040   EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
01041             factory_->AbortArgument(0));
01042   EXPECT_TRUE(factory_->TestDeleted());
01043 }
01044 
01045 // Tests that the (simulated) child process is aborted with the
01046 // correct AbortReason if it does not die.
01047 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
01048   bool flag = false;
01049   factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
01050   EXPECT_DEATH(flag = true, "");
01051   EXPECT_TRUE(flag);
01052   EXPECT_EQ(1, factory_->AssumeRoleCalls());
01053   EXPECT_EQ(0, factory_->WaitCalls());
01054   EXPECT_EQ(0, factory_->PassedCalls());
01055   // This time there are two calls to Abort: one since the test didn't
01056   // die, and another from the ReturnSentinel when it's destroyed.  The
01057   // sentinel normally isn't destroyed if a test doesn't die, since
01058   // _exit(2) is called in that case by ForkingDeathTest, but not by
01059   // our MockDeathTest.
01060   ASSERT_EQ(2, factory_->AbortCalls());
01061   EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
01062             factory_->AbortArgument(0));
01063   EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
01064             factory_->AbortArgument(1));
01065   EXPECT_TRUE(factory_->TestDeleted());
01066 }
01067 
01068 // Tests that a successful death test does not register a successful
01069 // test part.
01070 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
01071   EXPECT_DEATH(_exit(1), "");
01072   EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
01073 }
01074 
01075 TEST(StreamingAssertionsDeathTest, DeathTest) {
01076   EXPECT_DEATH(_exit(1), "") << "unexpected failure";
01077   ASSERT_DEATH(_exit(1), "") << "unexpected failure";
01078   EXPECT_NONFATAL_FAILURE({  // NOLINT
01079     EXPECT_DEATH(_exit(0), "") << "expected failure";
01080   }, "expected failure");
01081   EXPECT_FATAL_FAILURE({  // NOLINT
01082     ASSERT_DEATH(_exit(0), "") << "expected failure";
01083   }, "expected failure");
01084 }
01085 
01086 // Tests that GetLastErrnoDescription returns an empty string when the
01087 // last error is 0 and non-empty string when it is non-zero.
01088 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
01089   errno = ENOENT;
01090   EXPECT_STRNE("", GetLastErrnoDescription().c_str());
01091   errno = 0;
01092   EXPECT_STREQ("", GetLastErrnoDescription().c_str());
01093 }
01094 
01095 # if GTEST_OS_WINDOWS
01096 TEST(AutoHandleTest, AutoHandleWorks) {
01097   HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
01098   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
01099 
01100   // Tests that the AutoHandle is correctly initialized with a handle.
01101   testing::internal::AutoHandle auto_handle(handle);
01102   EXPECT_EQ(handle, auto_handle.Get());
01103 
01104   // Tests that Reset assigns INVALID_HANDLE_VALUE.
01105   // Note that this cannot verify whether the original handle is closed.
01106   auto_handle.Reset();
01107   EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
01108 
01109   // Tests that Reset assigns the new handle.
01110   // Note that this cannot verify whether the original handle is closed.
01111   handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
01112   ASSERT_NE(INVALID_HANDLE_VALUE, handle);
01113   auto_handle.Reset(handle);
01114   EXPECT_EQ(handle, auto_handle.Get());
01115 
01116   // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
01117   testing::internal::AutoHandle auto_handle2;
01118   EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
01119 }
01120 # endif  // GTEST_OS_WINDOWS
01121 
01122 # if GTEST_OS_WINDOWS
01123 typedef unsigned __int64 BiggestParsable;
01124 typedef signed __int64 BiggestSignedParsable;
01125 # else
01126 typedef unsigned long long BiggestParsable;
01127 typedef signed long long BiggestSignedParsable;
01128 # endif  // GTEST_OS_WINDOWS
01129 
01130 // We cannot use std::numeric_limits<T>::max() as it clashes with the
01131 // max() macro defined by <windows.h>.
01132 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
01133 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
01134 
01135 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
01136   BiggestParsable result = 0;
01137 
01138   // Rejects non-numbers.
01139   EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
01140 
01141   // Rejects numbers with whitespace prefix.
01142   EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
01143 
01144   // Rejects negative numbers.
01145   EXPECT_FALSE(ParseNaturalNumber("-123", &result));
01146 
01147   // Rejects numbers starting with a plus sign.
01148   EXPECT_FALSE(ParseNaturalNumber("+123", &result));
01149   errno = 0;
01150 }
01151 
01152 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
01153   BiggestParsable result = 0;
01154 
01155   EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
01156 
01157   signed char char_result = 0;
01158   EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
01159   errno = 0;
01160 }
01161 
01162 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
01163   BiggestParsable result = 0;
01164 
01165   result = 0;
01166   ASSERT_TRUE(ParseNaturalNumber("123", &result));
01167   EXPECT_EQ(123U, result);
01168 
01169   // Check 0 as an edge case.
01170   result = 1;
01171   ASSERT_TRUE(ParseNaturalNumber("0", &result));
01172   EXPECT_EQ(0U, result);
01173 
01174   result = 1;
01175   ASSERT_TRUE(ParseNaturalNumber("00000", &result));
01176   EXPECT_EQ(0U, result);
01177 }
01178 
01179 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
01180   Message msg;
01181   msg << kBiggestParsableMax;
01182 
01183   BiggestParsable result = 0;
01184   EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
01185   EXPECT_EQ(kBiggestParsableMax, result);
01186 
01187   Message msg2;
01188   msg2 << kBiggestSignedParsableMax;
01189 
01190   BiggestSignedParsable signed_result = 0;
01191   EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
01192   EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
01193 
01194   Message msg3;
01195   msg3 << INT_MAX;
01196 
01197   int int_result = 0;
01198   EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
01199   EXPECT_EQ(INT_MAX, int_result);
01200 
01201   Message msg4;
01202   msg4 << UINT_MAX;
01203 
01204   unsigned int uint_result = 0;
01205   EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
01206   EXPECT_EQ(UINT_MAX, uint_result);
01207 }
01208 
01209 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
01210   short short_result = 0;
01211   ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
01212   EXPECT_EQ(123, short_result);
01213 
01214   signed char char_result = 0;
01215   ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
01216   EXPECT_EQ(123, char_result);
01217 }
01218 
01219 # if GTEST_OS_WINDOWS
01220 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
01221   // TODO(vladl@google.com): Remove this test after this condition is verified
01222   // in a static assertion in gtest-death-test.cc in the function
01223   // GetStatusFileDescriptor.
01224   ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
01225 }
01226 # endif  // GTEST_OS_WINDOWS
01227 
01228 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
01229 // failures when death tests are available on the system.
01230 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
01231   EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
01232                             "death inside CondDeathTestExpectMacro");
01233   ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
01234                             "death inside CondDeathTestAssertMacro");
01235 
01236   // Empty statement will not crash, which must trigger a failure.
01237   EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
01238   EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
01239 }
01240 
01241 #else
01242 
01243 using testing::internal::CaptureStderr;
01244 using testing::internal::GetCapturedStderr;
01245 
01246 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
01247 // defined but do not trigger failures when death tests are not available on
01248 // the system.
01249 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
01250   // Empty statement will not crash, but that should not trigger a failure
01251   // when death tests are not supported.
01252   CaptureStderr();
01253   EXPECT_DEATH_IF_SUPPORTED(;, "");
01254   std::string output = GetCapturedStderr();
01255   ASSERT_TRUE(NULL != strstr(output.c_str(),
01256                              "Death tests are not supported on this platform"));
01257   ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
01258 
01259   // The streamed message should not be printed as there is no test failure.
01260   CaptureStderr();
01261   EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
01262   output = GetCapturedStderr();
01263   ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
01264 
01265   CaptureStderr();
01266   ASSERT_DEATH_IF_SUPPORTED(;, "");  // NOLINT
01267   output = GetCapturedStderr();
01268   ASSERT_TRUE(NULL != strstr(output.c_str(),
01269                              "Death tests are not supported on this platform"));
01270   ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
01271 
01272   CaptureStderr();
01273   ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message";  // NOLINT
01274   output = GetCapturedStderr();
01275   ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
01276 }
01277 
01278 void FuncWithAssert(int* n) {
01279   ASSERT_DEATH_IF_SUPPORTED(return;, "");
01280   (*n)++;
01281 }
01282 
01283 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
01284 // function (as ASSERT_DEATH does) if death tests are not supported.
01285 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
01286   int n = 0;
01287   FuncWithAssert(&n);
01288   EXPECT_EQ(1, n);
01289 }
01290 
01291 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
01292   testing::GTEST_FLAG(death_test_style) = "fast";
01293   EXPECT_FALSE(InDeathTestChild());
01294   EXPECT_DEATH({
01295     fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
01296     fflush(stderr);
01297     _exit(1);
01298   }, "Inside");
01299 }
01300 
01301 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
01302   testing::GTEST_FLAG(death_test_style) = "threadsafe";
01303   EXPECT_FALSE(InDeathTestChild());
01304   EXPECT_DEATH({
01305     fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
01306     fflush(stderr);
01307     _exit(1);
01308   }, "Inside");
01309 }
01310 
01311 #endif  // GTEST_HAS_DEATH_TEST
01312 
01313 // Tests that the death test macros expand to code which may or may not
01314 // be followed by operator<<, and that in either case the complete text
01315 // comprises only a single C++ statement.
01316 //
01317 // The syntax should work whether death tests are available or not.
01318 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
01319   if (AlwaysFalse())
01320     // This would fail if executed; this is a compilation test only
01321     ASSERT_DEATH_IF_SUPPORTED(return, "");
01322 
01323   if (AlwaysTrue())
01324     EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
01325   else
01326     // This empty "else" branch is meant to ensure that EXPECT_DEATH
01327     // doesn't expand into an "if" statement without an "else"
01328     ;  // NOLINT
01329 
01330   if (AlwaysFalse())
01331     ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
01332 
01333   if (AlwaysFalse())
01334     ;  // NOLINT
01335   else
01336     EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
01337 }
01338 
01339 // Tests that conditional death test macros expand to code which interacts
01340 // well with switch statements.
01341 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
01342 // Microsoft compiler usually complains about switch statements without
01343 // case labels. We suppress that warning for this test.
01344 #ifdef _MSC_VER
01345 # pragma warning(push)
01346 # pragma warning(disable: 4065)
01347 #endif  // _MSC_VER
01348 
01349   switch (0)
01350     default:
01351       ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
01352           << "exit in default switch handler";
01353 
01354   switch (0)
01355     case 0:
01356       EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
01357 
01358 #ifdef _MSC_VER
01359 # pragma warning(pop)
01360 #endif  // _MSC_VER
01361 }
01362 
01363 // Tests that a test case whose name ends with "DeathTest" works fine
01364 // on Windows.
01365 TEST(NotADeathTest, Test) {
01366   SUCCEED();
01367 }


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:44