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