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