?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download

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