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