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