1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // Tests for death tests.
33 #include "gtest/gtest-death-test.h"
34 #include "gtest/gtest.h"
35 #include "gtest/internal/gtest-filepath.h"
37 using testing::internal::AlwaysFalse;
38 using testing::internal::AlwaysTrue;
40 #ifdef GTEST_HAS_DEATH_TEST
42 #ifdef GTEST_OS_WINDOWS
43 #include <direct.h> // For chdir().
44 #include <fcntl.h> // For O_BINARY
47 #include <sys/wait.h> // For waitpid.
49 #endif // GTEST_OS_WINDOWS
60 #endif // GTEST_OS_LINUX
62 #include "gtest/gtest-spi.h"
63 #include "src/gtest-internal-inl.h"
65 namespace posix = ::testing::internal::posix;
67 using testing::ContainsRegex;
68 using testing::Matcher;
69 using testing::Message;
70 using testing::internal::DeathTest;
71 using testing::internal::DeathTestFactory;
72 using testing::internal::FilePath;
73 using testing::internal::GetLastErrnoDescription;
74 using testing::internal::GetUnitTestImpl;
75 using testing::internal::InDeathTestChild;
76 using testing::internal::ParseNaturalNumber;
81 // A helper class whose objects replace the death test factory for a
82 // single UnitTest object during their lifetimes.
83 class ReplaceDeathTestFactory {
85 explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
86 : unit_test_impl_(GetUnitTestImpl()) {
87 old_factory_ = unit_test_impl_->death_test_factory_.release();
88 unit_test_impl_->death_test_factory_.reset(new_factory);
91 ~ReplaceDeathTestFactory() {
92 unit_test_impl_->death_test_factory_.release();
93 unit_test_impl_->death_test_factory_.reset(old_factory_);
97 // Prevents copying ReplaceDeathTestFactory objects.
98 ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
99 void operator=(const ReplaceDeathTestFactory&);
101 UnitTestImpl* unit_test_impl_;
102 DeathTestFactory* old_factory_;
105 } // namespace internal
106 } // namespace testing
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.
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.
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()) _exit(1);
125 void DieInside(const ::std::string& function) {
126 DieWithMessage("death inside " + function + "().");
129 // Tests that death tests work.
131 class TestForDeathTest : public testing::Test {
133 TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
135 ~TestForDeathTest() override { posix::ChDir(original_dir_.c_str()); }
137 // A static member function that's expected to die.
138 static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
140 // A method of the test fixture that may die.
141 void MemberFunction() {
142 if (should_die_) DieInside("MemberFunction");
145 // True if and only if MemberFunction() should die.
147 const FilePath original_dir_;
150 // A class with a member function that may die.
153 explicit MayDie(bool should_die) : should_die_(should_die) {}
155 // A member function that may die.
156 void MemberFunction() const {
157 if (should_die_) DieInside("MayDie::MemberFunction");
161 // True if and only if MemberFunction() should die.
165 // A global function that's expected to die.
166 void GlobalFunction() { DieInside("GlobalFunction"); }
168 // A non-void function that's expected to die.
169 int NonVoidFunction() {
170 DieInside("NonVoidFunction");
174 // A unary function that may die.
175 void DieIf(bool should_die) {
176 if (should_die) DieInside("DieIf");
179 // A binary function that may die.
180 bool DieIfLessThan(int x, int y) {
182 DieInside("DieIfLessThan");
187 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
188 void DeathTestSubroutine() {
189 EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
190 ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
193 // Death in dbg, not opt.
194 int DieInDebugElse12(int* sideeffect) {
195 if (sideeffect) *sideeffect = 12;
199 DieInside("DieInDebugElse12");
206 #ifdef GTEST_OS_WINDOWS
208 // Death in dbg due to Windows CRT assertion failure, not opt.
209 int DieInCRTDebugElse12(int* sideeffect) {
210 if (sideeffect) *sideeffect = 12;
212 // Create an invalid fd by closing a valid one
214 EXPECT_EQ(_pipe(fdpipe, 256, O_BINARY), 0);
215 EXPECT_EQ(_close(fdpipe[0]), 0);
216 EXPECT_EQ(_close(fdpipe[1]), 0);
218 // _dup() should crash in debug mode
219 EXPECT_EQ(_dup(fdpipe[0]), -1);
224 #endif // GTEST_OS_WINDOWS
226 #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA)
228 // Tests the ExitedWithCode predicate.
229 TEST(ExitStatusPredicateTest, ExitedWithCode) {
230 // On Windows, the process's exit code is the same as its exit status,
231 // so the predicate just compares the its input with its parameter.
232 EXPECT_TRUE(testing::ExitedWithCode(0)(0));
233 EXPECT_TRUE(testing::ExitedWithCode(1)(1));
234 EXPECT_TRUE(testing::ExitedWithCode(42)(42));
235 EXPECT_FALSE(testing::ExitedWithCode(0)(1));
236 EXPECT_FALSE(testing::ExitedWithCode(1)(0));
241 // Returns the exit status of a process that calls _exit(2) with a
242 // given exit code. This is a helper function for the
243 // ExitStatusPredicateTest test suite.
244 static int NormalExitStatus(int exit_code) {
245 pid_t child_pid = fork();
246 if (child_pid == 0) {
250 waitpid(child_pid, &status, 0);
254 // Returns the exit status of a process that raises a given signal.
255 // If the signal does not cause the process to die, then it returns
256 // instead the exit status of a process that exits normally with exit
257 // code 1. This is a helper function for the ExitStatusPredicateTest
259 static int KilledExitStatus(int signum) {
260 pid_t child_pid = fork();
261 if (child_pid == 0) {
266 waitpid(child_pid, &status, 0);
270 // Tests the ExitedWithCode predicate.
271 TEST(ExitStatusPredicateTest, ExitedWithCode) {
272 const int status0 = NormalExitStatus(0);
273 const int status1 = NormalExitStatus(1);
274 const int status42 = NormalExitStatus(42);
275 const testing::ExitedWithCode pred0(0);
276 const testing::ExitedWithCode pred1(1);
277 const testing::ExitedWithCode pred42(42);
278 EXPECT_PRED1(pred0, status0);
279 EXPECT_PRED1(pred1, status1);
280 EXPECT_PRED1(pred42, status42);
281 EXPECT_FALSE(pred0(status1));
282 EXPECT_FALSE(pred42(status0));
283 EXPECT_FALSE(pred1(status42));
286 // Tests the KilledBySignal predicate.
287 TEST(ExitStatusPredicateTest, KilledBySignal) {
288 const int status_segv = KilledExitStatus(SIGSEGV);
289 const int status_kill = KilledExitStatus(SIGKILL);
290 const testing::KilledBySignal pred_segv(SIGSEGV);
291 const testing::KilledBySignal pred_kill(SIGKILL);
292 EXPECT_PRED1(pred_segv, status_segv);
293 EXPECT_PRED1(pred_kill, status_kill);
294 EXPECT_FALSE(pred_segv(status_kill));
295 EXPECT_FALSE(pred_kill(status_segv));
298 #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
300 // The following code intentionally tests a suboptimal syntax.
302 #pragma GCC diagnostic push
303 #pragma GCC diagnostic ignored "-Wdangling-else"
304 #pragma GCC diagnostic ignored "-Wempty-body"
305 #pragma GCC diagnostic ignored "-Wpragmas"
307 // Tests that the death test macros expand to code which may or may not
308 // be followed by operator<<, and that in either case the complete text
309 // comprises only a single C++ statement.
310 TEST_F(TestForDeathTest, SingleStatement) {
312 // This would fail if executed; this is a compilation test only
313 ASSERT_DEATH(return, "");
316 EXPECT_DEATH(_exit(1), "");
318 // This empty "else" branch is meant to ensure that EXPECT_DEATH
319 // doesn't expand into an "if" statement without an "else"
322 if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die";
327 EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
330 #pragma GCC diagnostic pop
333 // Tests that death test macros expand to code which interacts well with switch
335 TEST_F(TestForDeathTest, SwitchStatement) {
336 // Microsoft compiler usually complains about switch statements without
337 // case labels. We suppress that warning for this test.
338 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
342 ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
346 EXPECT_DEATH(_exit(1), "") << "exit in switch case";
348 GTEST_DISABLE_MSC_WARNINGS_POP_()
351 // Tests that a static member function can be used in a "fast" style
353 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
354 GTEST_FLAG_SET(death_test_style, "fast");
355 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
358 // Tests that a method of the test fixture can be used in a "fast"
360 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
361 GTEST_FLAG_SET(death_test_style, "fast");
363 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
366 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
368 // Tests that death tests work even if the current directory has been
370 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
371 GTEST_FLAG_SET(death_test_style, "fast");
374 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
377 ASSERT_DEATH(_exit(1), "");
380 #ifdef GTEST_OS_LINUX
381 void SigprofAction(int, siginfo_t*, void*) { /* no op */
384 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
385 void SetSigprofActionAndTimer() {
386 struct sigaction signal_action;
387 memset(&signal_action, 0, sizeof(signal_action));
388 sigemptyset(&signal_action.sa_mask);
389 signal_action.sa_sigaction = SigprofAction;
390 signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
391 ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr));
392 // timer comes second, to avoid SIGPROF premature delivery, as suggested at
393 // https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
394 struct itimerval timer;
395 timer.it_interval.tv_sec = 0;
396 timer.it_interval.tv_usec = 1;
397 timer.it_value = timer.it_interval;
398 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
401 // Disables ITIMER_PROF timer and ignores SIGPROF signal.
402 void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
403 struct itimerval timer;
404 timer.it_interval.tv_sec = 0;
405 timer.it_interval.tv_usec = 0;
406 timer.it_value = timer.it_interval;
407 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
408 struct sigaction signal_action;
409 memset(&signal_action, 0, sizeof(signal_action));
410 sigemptyset(&signal_action.sa_mask);
411 signal_action.sa_handler = SIG_IGN;
412 ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
415 // Tests that death tests work when SIGPROF handler and timer are set.
416 TEST_F(TestForDeathTest, FastSigprofActionSet) {
417 GTEST_FLAG_SET(death_test_style, "fast");
418 SetSigprofActionAndTimer();
419 EXPECT_DEATH(_exit(1), "");
420 struct sigaction old_signal_action;
421 DisableSigprofActionAndTimer(&old_signal_action);
422 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
425 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
426 GTEST_FLAG_SET(death_test_style, "threadsafe");
427 SetSigprofActionAndTimer();
428 EXPECT_DEATH(_exit(1), "");
429 struct sigaction old_signal_action;
430 DisableSigprofActionAndTimer(&old_signal_action);
431 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
433 #endif // GTEST_OS_LINUX
435 // Repeats a representative sample of death tests in the "threadsafe" style:
437 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
438 GTEST_FLAG_SET(death_test_style, "threadsafe");
439 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
442 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
443 GTEST_FLAG_SET(death_test_style, "threadsafe");
445 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
448 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
449 GTEST_FLAG_SET(death_test_style, "threadsafe");
451 for (int i = 0; i < 3; ++i)
452 EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
455 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
456 GTEST_FLAG_SET(death_test_style, "threadsafe");
459 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
462 ASSERT_DEATH(_exit(1), "");
465 TEST_F(TestForDeathTest, MixedStyles) {
466 GTEST_FLAG_SET(death_test_style, "threadsafe");
467 EXPECT_DEATH(_exit(1), "");
468 GTEST_FLAG_SET(death_test_style, "fast");
469 EXPECT_DEATH(_exit(1), "");
472 #if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
476 void SetPthreadFlag() { pthread_flag = true; }
478 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
479 if (!GTEST_FLAG_GET(death_test_use_fork)) {
480 GTEST_FLAG_SET(death_test_style, "threadsafe");
481 pthread_flag = false;
482 ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr));
483 ASSERT_DEATH(_exit(1), "");
484 ASSERT_FALSE(pthread_flag);
488 #endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
490 // Tests that a method of another class can be used in a death test.
491 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
492 const MayDie x(true);
493 ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
496 // Tests that a global function can be used in a death test.
497 TEST_F(TestForDeathTest, GlobalFunction) {
498 EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
501 // Tests that any value convertible to an RE works as a second
502 // argument to EXPECT_DEATH.
503 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
504 static const char regex_c_str[] = "GlobalFunction";
505 EXPECT_DEATH(GlobalFunction(), regex_c_str);
507 const testing::internal::RE regex(regex_c_str);
508 EXPECT_DEATH(GlobalFunction(), regex);
510 const ::std::string regex_std_str(regex_c_str);
511 EXPECT_DEATH(GlobalFunction(), regex_std_str);
513 // This one is tricky; a temporary pointer into another temporary. Reference
514 // lifetime extension of the pointer is not sufficient.
515 EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
518 // Tests that a non-void function can be used in a death test.
519 TEST_F(TestForDeathTest, NonVoidFunction) {
520 ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
523 // Tests that functions that take parameter(s) can be used in a death test.
524 TEST_F(TestForDeathTest, FunctionWithParameter) {
525 EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
526 EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
529 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
530 TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); }
532 // Tests that death tests can be done inside a loop.
533 TEST_F(TestForDeathTest, InsideLoop) {
534 for (int i = 0; i < 5; i++) {
535 EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
539 // Tests that a compound statement can be used in a death test.
540 TEST_F(TestForDeathTest, CompoundStatement) {
550 // Tests that code that doesn't die causes a death test to fail.
551 TEST_F(TestForDeathTest, DoesNotDie) {
552 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die");
555 // Tests that a death test fails when the error message isn't expected.
556 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
557 EXPECT_NONFATAL_FAILURE(
559 EXPECT_DEATH(DieIf(true), "DieIfLessThan")
560 << "End of death test message.";
562 "died but not with expected error");
565 // On exit, *aborted will be true if and only if the EXPECT_DEATH()
566 // statement aborted the function.
567 void ExpectDeathTestHelper(bool* aborted) {
569 EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
573 // Tests that EXPECT_DEATH doesn't abort the test on failure.
574 TEST_F(TestForDeathTest, EXPECT_DEATH) {
576 EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die");
577 EXPECT_FALSE(aborted);
580 // Tests that ASSERT_DEATH does abort the test on failure.
581 TEST_F(TestForDeathTest, ASSERT_DEATH) {
583 EXPECT_FATAL_FAILURE(
586 ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
590 EXPECT_TRUE(aborted);
593 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
594 TEST_F(TestForDeathTest, SingleEvaluation) {
596 EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
598 const char* regex = "DieIf";
599 const char* regex_save = regex;
600 EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
601 EXPECT_EQ(regex_save + 1, regex);
604 // Tests that run-away death tests are reported as failures.
605 TEST_F(TestForDeathTest, RunawayIsFailure) {
606 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
610 // Tests that death tests report executing 'return' in the statement as
612 TEST_F(TestForDeathTest, ReturnIsFailure) {
613 EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
614 "illegal return in test statement.");
617 // Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
618 // message to it, and in debug mode it:
619 // 1. Asserts on death.
620 // 2. Has no side effect.
622 // And in opt mode, it:
623 // 1. Has side effects but does not assert.
624 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
627 // Put the regex in a local variable to make sure we don't get an "unused"
628 // warning in opt mode.
629 const char* regex = "death.*DieInDebugElse12";
631 EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)
632 << "Must accept a streamed message";
636 // Checks that the assignment occurs in opt mode (sideeffect).
637 EXPECT_EQ(12, sideeffect);
641 // Checks that the assignment does not occur in dbg mode (no sideeffect).
642 EXPECT_EQ(0, sideeffect);
647 #ifdef GTEST_OS_WINDOWS
649 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode
650 // In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable
651 // the dumping of assertions to stderr. Tests that EXPECT_DEATH works as
652 // expected when in CRT debug mode (compiled with /MTd or /MDd, which defines
653 // _DEBUG) the Windows CRT crashes the process with an assertion failure.
654 // 1. Asserts on death.
655 // 2. Has no side effect (doesn't pop up a window or wait for user input).
657 TEST_F(TestForDeathTest, CRTDebugDeath) {
658 EXPECT_DEATH(DieInCRTDebugElse12(nullptr), "dup.* : Assertion failed")
659 << "Must accept a streamed message";
663 #endif // GTEST_OS_WINDOWS
665 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
666 // message to it, and in debug mode it:
667 // 1. Asserts on death.
668 // 2. Has no side effect.
670 // And in opt mode, it:
671 // 1. Has side effects but does not assert.
672 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
675 ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
676 << "Must accept a streamed message";
680 // Checks that the assignment occurs in opt mode (sideeffect).
681 EXPECT_EQ(12, sideeffect);
685 // Checks that the assignment does not occur in dbg mode (no sideeffect).
686 EXPECT_EQ(0, sideeffect);
693 void ExpectDebugDeathHelper(bool* aborted) {
695 EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
699 #ifdef GTEST_OS_WINDOWS
700 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
702 "This test should be considered failing if it shows "
703 "any pop-up dialogs.\n");
708 GTEST_FLAG_SET(catch_exceptions, false);
713 #endif // GTEST_OS_WINDOWS
715 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
717 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
719 EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
720 EXPECT_FALSE(aborted);
723 void AssertDebugDeathHelper(bool* aborted) {
725 GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH";
726 ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "")
727 << "This is expected to fail.";
728 GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH";
732 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
734 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
737 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
738 EXPECT_TRUE(aborted);
741 TEST_F(TestForDeathTest, AssertDebugDeathAborts2) {
744 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
745 EXPECT_TRUE(aborted);
748 TEST_F(TestForDeathTest, AssertDebugDeathAborts3) {
751 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
752 EXPECT_TRUE(aborted);
755 TEST_F(TestForDeathTest, AssertDebugDeathAborts4) {
758 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
759 EXPECT_TRUE(aborted);
762 TEST_F(TestForDeathTest, AssertDebugDeathAborts5) {
765 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
766 EXPECT_TRUE(aborted);
769 TEST_F(TestForDeathTest, AssertDebugDeathAborts6) {
772 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
773 EXPECT_TRUE(aborted);
776 TEST_F(TestForDeathTest, AssertDebugDeathAborts7) {
779 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
780 EXPECT_TRUE(aborted);
783 TEST_F(TestForDeathTest, AssertDebugDeathAborts8) {
786 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
787 EXPECT_TRUE(aborted);
790 TEST_F(TestForDeathTest, AssertDebugDeathAborts9) {
793 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
794 EXPECT_TRUE(aborted);
797 TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
800 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
801 EXPECT_TRUE(aborted);
806 // Tests the *_EXIT family of macros, using a variety of predicates.
807 static void TestExitMacros() {
808 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
809 ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
811 #ifdef GTEST_OS_WINDOWS
813 // Of all signals effects on the process exit code, only those of SIGABRT
814 // are documented on Windows.
815 // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
816 EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
818 #elif !defined(GTEST_OS_FUCHSIA)
820 // Fuchsia has no unix signals.
821 EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
822 ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
824 EXPECT_FATAL_FAILURE(
826 ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
827 << "This failure is expected, too.";
829 "This failure is expected, too.");
831 #endif // GTEST_OS_WINDOWS
833 EXPECT_NONFATAL_FAILURE(
835 EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
836 << "This failure is expected.";
838 "This failure is expected.");
841 TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); }
843 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
844 GTEST_FLAG_SET(death_test_use_fork, true);
848 TEST_F(TestForDeathTest, InvalidStyle) {
849 GTEST_FLAG_SET(death_test_style, "rococo");
850 EXPECT_NONFATAL_FAILURE(
852 EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
854 "This failure is expected.");
857 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
858 GTEST_FLAG_SET(death_test_style, "fast");
859 EXPECT_NONFATAL_FAILURE(
860 EXPECT_DEATH(DieWithMessage("death\n"), "expected message"),
862 "[ DEATH ] death\n");
865 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
866 GTEST_FLAG_SET(death_test_style, "fast");
867 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(
869 fprintf(stderr, "returning\n");
874 " Result: illegal return in test statement.\n"
876 "[ DEATH ] returning\n");
879 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
880 GTEST_FLAG_SET(death_test_style, "fast");
881 EXPECT_NONFATAL_FAILURE(
882 EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
883 testing::ExitedWithCode(3), "expected message"),
884 " Result: died but not with expected exit code:\n"
885 " Exited with exit status 1\n"
887 "[ DEATH ] exiting with rc 1\n");
890 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
891 GTEST_FLAG_SET(death_test_style, "fast");
892 EXPECT_NONFATAL_FAILURE(
893 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
894 "line 1\nxyz\nline 3\n"),
898 "[ DEATH ] line 3\n");
901 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
902 GTEST_FLAG_SET(death_test_style, "fast");
903 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
904 "line 1\nline 2\nline 3\n");
907 // A DeathTestFactory that returns MockDeathTests.
908 class MockDeathTestFactory : public DeathTestFactory {
910 MockDeathTestFactory();
911 bool Create(const char* statement,
912 testing::Matcher<const std::string&> matcher, const char* file,
913 int line, DeathTest** test) override;
915 // Sets the parameters for subsequent calls to Create.
916 void SetParameters(bool create, DeathTest::TestRole role, int status,
920 int AssumeRoleCalls() const { return assume_role_calls_; }
921 int WaitCalls() const { return wait_calls_; }
922 size_t PassedCalls() const { return passed_args_.size(); }
923 bool PassedArgument(int n) const {
924 return passed_args_[static_cast<size_t>(n)];
926 size_t AbortCalls() const { return abort_args_.size(); }
927 DeathTest::AbortReason AbortArgument(int n) const {
928 return abort_args_[static_cast<size_t>(n)];
930 bool TestDeleted() const { return test_deleted_; }
933 friend class MockDeathTest;
934 // If true, Create will return a MockDeathTest; otherwise it returns
937 // The value a MockDeathTest will return from its AssumeRole method.
938 DeathTest::TestRole role_;
939 // The value a MockDeathTest will return from its Wait method.
941 // The value a MockDeathTest will return from its Passed method.
944 // Number of times AssumeRole was called.
945 int assume_role_calls_;
946 // Number of times Wait was called.
948 // The arguments to the calls to Passed since the last call to
950 std::vector<bool> passed_args_;
951 // The arguments to the calls to Abort since the last call to
953 std::vector<DeathTest::AbortReason> abort_args_;
954 // True if the last MockDeathTest returned by Create has been
959 // A DeathTest implementation useful in testing. It returns values set
960 // at its creation from its various inherited DeathTest methods, and
961 // reports calls to those methods to its parent MockDeathTestFactory
963 class MockDeathTest : public DeathTest {
965 MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status,
967 : parent_(parent), role_(role), status_(status), passed_(passed) {}
968 ~MockDeathTest() override { parent_->test_deleted_ = true; }
969 TestRole AssumeRole() override {
970 ++parent_->assume_role_calls_;
973 int Wait() override {
974 ++parent_->wait_calls_;
977 bool Passed(bool exit_status_ok) override {
978 parent_->passed_args_.push_back(exit_status_ok);
981 void Abort(AbortReason reason) override {
982 parent_->abort_args_.push_back(reason);
986 MockDeathTestFactory* const parent_;
987 const TestRole role_;
992 // MockDeathTestFactory constructor.
993 MockDeathTestFactory::MockDeathTestFactory()
995 role_(DeathTest::OVERSEE_TEST),
998 assume_role_calls_(0),
1003 // Sets the parameters for subsequent calls to Create.
1004 void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role,
1005 int status, bool passed) {
1011 assume_role_calls_ = 0;
1013 passed_args_.clear();
1014 abort_args_.clear();
1017 // Sets test to NULL (if create_ is false) or to the address of a new
1018 // MockDeathTest object with parameters taken from the last call
1019 // to SetParameters (if create_ is true). Always returns true.
1020 bool MockDeathTestFactory::Create(
1021 const char* /*statement*/, testing::Matcher<const std::string&> /*matcher*/,
1022 const char* /*file*/, int /*line*/, DeathTest** test) {
1023 test_deleted_ = false;
1025 *test = new MockDeathTest(this, role_, status_, passed_);
1032 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
1033 // It installs a MockDeathTestFactory that is used for the duration
1034 // of the test case.
1035 class MacroLogicDeathTest : public testing::Test {
1037 static testing::internal::ReplaceDeathTestFactory* replacer_;
1038 static MockDeathTestFactory* factory_;
1040 static void SetUpTestSuite() {
1041 factory_ = new MockDeathTestFactory;
1042 replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
1045 static void TearDownTestSuite() {
1047 replacer_ = nullptr;
1052 // Runs a death test that breaks the rules by returning. Such a death
1053 // test cannot be run directly from a test routine that uses a
1054 // MockDeathTest, or the remainder of the routine will not be executed.
1055 static void RunReturningDeathTest(bool* flag) {
1065 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ =
1067 MockDeathTestFactory* MacroLogicDeathTest::factory_ = nullptr;
1069 // Test that nothing happens when the factory doesn't return a DeathTest:
1070 TEST_F(MacroLogicDeathTest, NothingHappens) {
1072 factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
1073 EXPECT_DEATH(flag = true, "");
1075 EXPECT_EQ(0, factory_->AssumeRoleCalls());
1076 EXPECT_EQ(0, factory_->WaitCalls());
1077 EXPECT_EQ(0U, factory_->PassedCalls());
1078 EXPECT_EQ(0U, factory_->AbortCalls());
1079 EXPECT_FALSE(factory_->TestDeleted());
1082 // Test that the parent process doesn't run the death test code,
1083 // and that the Passed method returns false when the (simulated)
1084 // child process exits with status 0:
1085 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
1087 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
1088 EXPECT_DEATH(flag = true, "");
1090 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1091 EXPECT_EQ(1, factory_->WaitCalls());
1092 ASSERT_EQ(1U, factory_->PassedCalls());
1093 EXPECT_FALSE(factory_->PassedArgument(0));
1094 EXPECT_EQ(0U, factory_->AbortCalls());
1095 EXPECT_TRUE(factory_->TestDeleted());
1098 // Tests that the Passed method was given the argument "true" when
1099 // the (simulated) child process exits with status 1:
1100 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
1102 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
1103 EXPECT_DEATH(flag = true, "");
1105 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1106 EXPECT_EQ(1, factory_->WaitCalls());
1107 ASSERT_EQ(1U, factory_->PassedCalls());
1108 EXPECT_TRUE(factory_->PassedArgument(0));
1109 EXPECT_EQ(0U, factory_->AbortCalls());
1110 EXPECT_TRUE(factory_->TestDeleted());
1113 // Tests that the (simulated) child process executes the death test
1114 // code, and is aborted with the correct AbortReason if it
1115 // executes a return statement.
1116 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
1118 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1119 RunReturningDeathTest(&flag);
1121 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1122 EXPECT_EQ(0, factory_->WaitCalls());
1123 EXPECT_EQ(0U, factory_->PassedCalls());
1124 EXPECT_EQ(1U, factory_->AbortCalls());
1125 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1126 factory_->AbortArgument(0));
1127 EXPECT_TRUE(factory_->TestDeleted());
1130 // Tests that the (simulated) child process is aborted with the
1131 // correct AbortReason if it does not die.
1132 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
1134 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1135 EXPECT_DEATH(flag = true, "");
1137 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1138 EXPECT_EQ(0, factory_->WaitCalls());
1139 EXPECT_EQ(0U, factory_->PassedCalls());
1140 // This time there are two calls to Abort: one since the test didn't
1141 // die, and another from the ReturnSentinel when it's destroyed. The
1142 // sentinel normally isn't destroyed if a test doesn't die, since
1143 // _exit(2) is called in that case by ForkingDeathTest, but not by
1144 // our MockDeathTest.
1145 ASSERT_EQ(2U, factory_->AbortCalls());
1146 EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0));
1147 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1148 factory_->AbortArgument(1));
1149 EXPECT_TRUE(factory_->TestDeleted());
1152 // Tests that a successful death test does not register a successful
1154 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1155 EXPECT_DEATH(_exit(1), "");
1156 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
1159 TEST(StreamingAssertionsDeathTest, DeathTest) {
1160 EXPECT_DEATH(_exit(1), "") << "unexpected failure";
1161 ASSERT_DEATH(_exit(1), "") << "unexpected failure";
1162 EXPECT_NONFATAL_FAILURE(
1164 EXPECT_DEATH(_exit(0), "") << "expected failure";
1166 "expected failure");
1167 EXPECT_FATAL_FAILURE(
1169 ASSERT_DEATH(_exit(0), "") << "expected failure";
1171 "expected failure");
1174 // Tests that GetLastErrnoDescription returns an empty string when the
1175 // last error is 0 and non-empty string when it is non-zero.
1176 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
1178 EXPECT_STRNE("", GetLastErrnoDescription().c_str());
1180 EXPECT_STREQ("", GetLastErrnoDescription().c_str());
1183 #ifdef GTEST_OS_WINDOWS
1184 TEST(AutoHandleTest, AutoHandleWorks) {
1185 HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1186 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1188 // Tests that the AutoHandle is correctly initialized with a handle.
1189 testing::internal::AutoHandle auto_handle(handle);
1190 EXPECT_EQ(handle, auto_handle.Get());
1192 // Tests that Reset assigns INVALID_HANDLE_VALUE.
1193 // Note that this cannot verify whether the original handle is closed.
1194 auto_handle.Reset();
1195 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
1197 // Tests that Reset assigns the new handle.
1198 // Note that this cannot verify whether the original handle is closed.
1199 handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1200 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1201 auto_handle.Reset(handle);
1202 EXPECT_EQ(handle, auto_handle.Get());
1204 // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
1205 testing::internal::AutoHandle auto_handle2;
1206 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
1208 #endif // GTEST_OS_WINDOWS
1210 #ifdef GTEST_OS_WINDOWS
1211 typedef unsigned __int64 BiggestParsable;
1212 typedef signed __int64 BiggestSignedParsable;
1214 typedef unsigned long long BiggestParsable;
1215 typedef signed long long BiggestSignedParsable;
1216 #endif // GTEST_OS_WINDOWS
1218 // We cannot use std::numeric_limits<T>::max() as it clashes with the
1219 // max() macro defined by <windows.h>.
1220 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1221 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
1223 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
1224 BiggestParsable result = 0;
1226 // Rejects non-numbers.
1227 EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
1229 // Rejects numbers with whitespace prefix.
1230 EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
1232 // Rejects negative numbers.
1233 EXPECT_FALSE(ParseNaturalNumber("-123", &result));
1235 // Rejects numbers starting with a plus sign.
1236 EXPECT_FALSE(ParseNaturalNumber("+123", &result));
1240 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
1241 BiggestParsable result = 0;
1243 EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
1245 signed char char_result = 0;
1246 EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
1250 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
1251 BiggestParsable result = 0;
1254 ASSERT_TRUE(ParseNaturalNumber("123", &result));
1255 EXPECT_EQ(123U, result);
1257 // Check 0 as an edge case.
1259 ASSERT_TRUE(ParseNaturalNumber("0", &result));
1260 EXPECT_EQ(0U, result);
1263 ASSERT_TRUE(ParseNaturalNumber("00000", &result));
1264 EXPECT_EQ(0U, result);
1267 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
1269 msg << kBiggestParsableMax;
1271 BiggestParsable result = 0;
1272 EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
1273 EXPECT_EQ(kBiggestParsableMax, result);
1276 msg2 << kBiggestSignedParsableMax;
1278 BiggestSignedParsable signed_result = 0;
1279 EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
1280 EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
1286 EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
1287 EXPECT_EQ(INT_MAX, int_result);
1292 unsigned int uint_result = 0;
1293 EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
1294 EXPECT_EQ(UINT_MAX, uint_result);
1297 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
1298 short short_result = 0;
1299 ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
1300 EXPECT_EQ(123, short_result);
1302 signed char char_result = 0;
1303 ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
1304 EXPECT_EQ(123, char_result);
1307 #ifdef GTEST_OS_WINDOWS
1308 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
1309 ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
1311 #endif // GTEST_OS_WINDOWS
1313 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
1314 // failures when death tests are available on the system.
1315 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
1316 EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
1317 "death inside CondDeathTestExpectMacro");
1318 ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
1319 "death inside CondDeathTestAssertMacro");
1321 // Empty statement will not crash, which must trigger a failure.
1322 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
1323 EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
1326 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
1327 GTEST_FLAG_SET(death_test_style, "fast");
1328 EXPECT_FALSE(InDeathTestChild());
1331 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1338 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
1339 GTEST_FLAG_SET(death_test_style, "threadsafe");
1340 EXPECT_FALSE(InDeathTestChild());
1343 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1350 void DieWithMessage(const char* message) {
1351 fputs(message, stderr);
1352 fflush(stderr); // Make sure the text is printed before the process exits.
1356 TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {
1357 // googletest tests this, of course; here we ensure that including googlemock
1358 // has not broken it.
1359 #ifdef GTEST_USES_POSIX_RE
1360 EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
1362 EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I di?e");
1366 TEST(MatcherDeathTest, MonomorphicMatcherMatches) {
1367 EXPECT_DEATH(DieWithMessage("Behind O, I am slain!"),
1368 Matcher<const std::string&>(ContainsRegex("I am slain")));
1371 TEST(MatcherDeathTest, MonomorphicMatcherDoesNotMatch) {
1372 EXPECT_NONFATAL_FAILURE(
1374 DieWithMessage("Behind O, I am slain!"),
1375 Matcher<const std::string&>(ContainsRegex("Ow, I am slain"))),
1376 "Expected: contains regular expression \"Ow, I am slain\"");
1379 TEST(MatcherDeathTest, PolymorphicMatcherMatches) {
1380 EXPECT_DEATH(DieWithMessage("The rest is silence."),
1381 ContainsRegex("rest is silence"));
1384 TEST(MatcherDeathTest, PolymorphicMatcherDoesNotMatch) {
1385 EXPECT_NONFATAL_FAILURE(
1386 EXPECT_DEATH(DieWithMessage("The rest is silence."),
1387 ContainsRegex("rest is science")),
1388 "Expected: contains regular expression \"rest is science\"");
1393 #else // !GTEST_HAS_DEATH_TEST follows
1397 using testing::internal::CaptureStderr;
1398 using testing::internal::GetCapturedStderr;
1400 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
1401 // defined but do not trigger failures when death tests are not available on
1403 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
1404 // Empty statement will not crash, but that should not trigger a failure
1405 // when death tests are not supported.
1407 EXPECT_DEATH_IF_SUPPORTED(;, "");
1408 std::string output = GetCapturedStderr();
1409 ASSERT_TRUE(NULL != strstr(output.c_str(),
1410 "Death tests are not supported on this platform"));
1411 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1413 // The streamed message should not be printed as there is no test failure.
1415 EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
1416 output = GetCapturedStderr();
1417 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1420 ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
1421 output = GetCapturedStderr();
1422 ASSERT_TRUE(NULL != strstr(output.c_str(),
1423 "Death tests are not supported on this platform"));
1424 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1427 ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
1428 output = GetCapturedStderr();
1429 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1432 void FuncWithAssert(int* n) {
1433 ASSERT_DEATH_IF_SUPPORTED(return;, "");
1437 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
1438 // function (as ASSERT_DEATH does) if death tests are not supported.
1439 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
1447 #endif // !GTEST_HAS_DEATH_TEST
1451 // The following code intentionally tests a suboptimal syntax.
1453 #pragma GCC diagnostic push
1454 #pragma GCC diagnostic ignored "-Wdangling-else"
1455 #pragma GCC diagnostic ignored "-Wempty-body"
1456 #pragma GCC diagnostic ignored "-Wpragmas"
1458 // Tests that the death test macros expand to code which may or may not
1459 // be followed by operator<<, and that in either case the complete text
1460 // comprises only a single C++ statement.
1462 // The syntax should work whether death tests are available or not.
1463 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
1465 // This would fail if executed; this is a compilation test only
1466 ASSERT_DEATH_IF_SUPPORTED(return, "");
1469 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
1471 // This empty "else" branch is meant to ensure that EXPECT_DEATH
1472 // doesn't expand into an "if" statement without an "else"
1475 if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
1480 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
1483 #pragma GCC diagnostic pop
1486 // Tests that conditional death test macros expand to code which interacts
1487 // well with switch statements.
1488 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
1489 // Microsoft compiler usually complains about switch statements without
1490 // case labels. We suppress that warning for this test.
1491 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
1495 ASSERT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in default switch handler";
1499 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
1501 GTEST_DISABLE_MSC_WARNINGS_POP_()
1504 // Tests that a test case whose name ends with "DeathTest" works fine
1506 TEST(NotADeathTest, Test) { SUCCEED(); }