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