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