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"
35 #include "gtest/gtest.h"
36 #include "gtest/internal/gtest-filepath.h"
38 using testing::internal::AlwaysFalse;
39 using testing::internal::AlwaysTrue;
41 #if GTEST_HAS_DEATH_TEST
44 # include <fcntl.h> // For O_BINARY
45 # include <direct.h> // For chdir().
49 # include <sys/wait.h> // For waitpid.
50 # endif // GTEST_OS_WINDOWS
57 # include <sys/time.h>
58 # endif // GTEST_OS_LINUX
60 # include "gtest/gtest-spi.h"
61 # include "src/gtest-internal-inl.h"
63 namespace posix = ::testing::internal::posix;
65 using testing::ContainsRegex;
66 using testing::Matcher;
67 using testing::Message;
68 using testing::internal::DeathTest;
69 using testing::internal::DeathTestFactory;
70 using testing::internal::FilePath;
71 using testing::internal::GetLastErrnoDescription;
72 using testing::internal::GetUnitTestImpl;
73 using testing::internal::InDeathTestChild;
74 using testing::internal::ParseNaturalNumber;
79 // A helper class whose objects replace the death test factory for a
80 // single UnitTest object during their lifetimes.
81 class ReplaceDeathTestFactory {
83 explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
84 : unit_test_impl_(GetUnitTestImpl()) {
85 old_factory_ = unit_test_impl_->death_test_factory_.release();
86 unit_test_impl_->death_test_factory_.reset(new_factory);
89 ~ReplaceDeathTestFactory() {
90 unit_test_impl_->death_test_factory_.release();
91 unit_test_impl_->death_test_factory_.reset(old_factory_);
94 // Prevents copying ReplaceDeathTestFactory objects.
95 ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
96 void operator=(const ReplaceDeathTestFactory&);
98 UnitTestImpl* unit_test_impl_;
99 DeathTestFactory* old_factory_;
102 } // namespace internal
103 } // namespace testing
107 void DieWithMessage(const ::std::string& message) {
108 fprintf(stderr, "%s", message.c_str());
109 fflush(stderr); // Make sure the text is printed before the process exits.
111 // We call _exit() instead of exit(), as the former is a direct
112 // system call and thus safer in the presence of threads. exit()
113 // will invoke user-defined exit-hooks, which may do dangerous
114 // things that conflict with death tests.
116 // Some compilers can recognize that _exit() never returns and issue the
117 // 'unreachable code' warning for code following this function, unless
118 // fooled by a fake condition.
123 void DieInside(const ::std::string& function) {
124 DieWithMessage("death inside " + function + "().");
127 // Tests that death tests work.
129 class TestForDeathTest : public testing::Test {
131 TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
133 ~TestForDeathTest() override { posix::ChDir(original_dir_.c_str()); }
135 // A static member function that's expected to die.
136 static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
138 // A method of the test fixture that may die.
139 void MemberFunction() {
141 DieInside("MemberFunction");
144 // True if and only if MemberFunction() should die.
146 const FilePath original_dir_;
149 // A class with a member function that may die.
152 explicit MayDie(bool should_die) : should_die_(should_die) {}
154 // A member function that may die.
155 void MemberFunction() const {
157 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) {
180 // A binary function that may die.
181 bool DieIfLessThan(int x, int y) {
183 DieInside("DieIfLessThan");
188 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
189 void DeathTestSubroutine() {
190 EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
191 ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
194 // Death in dbg, not opt.
195 int DieInDebugElse12(int* sideeffect) {
196 if (sideeffect) *sideeffect = 12;
200 DieInside("DieInDebugElse12");
207 # if GTEST_OS_WINDOWS
209 // Death in dbg due to Windows CRT assertion failure, not opt.
210 int DieInCRTDebugElse12(int* sideeffect) {
211 if (sideeffect) *sideeffect = 12;
213 // Create an invalid fd by closing a valid one
215 EXPECT_EQ(_pipe(fdpipe, 256, O_BINARY), 0);
216 EXPECT_EQ(_close(fdpipe[0]), 0);
217 EXPECT_EQ(_close(fdpipe[1]), 0);
219 // _dup() should crash in debug mode
220 EXPECT_EQ(_dup(fdpipe[0]), -1);
225 #endif // GTEST_OS_WINDOWS
227 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
229 // Tests the ExitedWithCode predicate.
230 TEST(ExitStatusPredicateTest, ExitedWithCode) {
231 // On Windows, the process's exit code is the same as its exit status,
232 // so the predicate just compares the its input with its parameter.
233 EXPECT_TRUE(testing::ExitedWithCode(0)(0));
234 EXPECT_TRUE(testing::ExitedWithCode(1)(1));
235 EXPECT_TRUE(testing::ExitedWithCode(42)(42));
236 EXPECT_FALSE(testing::ExitedWithCode(0)(1));
237 EXPECT_FALSE(testing::ExitedWithCode(1)(0));
242 // Returns the exit status of a process that calls _exit(2) with a
243 // given exit code. This is a helper function for the
244 // ExitStatusPredicateTest test suite.
245 static int NormalExitStatus(int exit_code) {
246 pid_t child_pid = fork();
247 if (child_pid == 0) {
251 waitpid(child_pid, &status, 0);
255 // Returns the exit status of a process that raises a given signal.
256 // If the signal does not cause the process to die, then it returns
257 // instead the exit status of a process that exits normally with exit
258 // code 1. This is a helper function for the ExitStatusPredicateTest
260 static int KilledExitStatus(int signum) {
261 pid_t child_pid = fork();
262 if (child_pid == 0) {
267 waitpid(child_pid, &status, 0);
271 // Tests the ExitedWithCode predicate.
272 TEST(ExitStatusPredicateTest, ExitedWithCode) {
273 const int status0 = NormalExitStatus(0);
274 const int status1 = NormalExitStatus(1);
275 const int status42 = NormalExitStatus(42);
276 const testing::ExitedWithCode pred0(0);
277 const testing::ExitedWithCode pred1(1);
278 const testing::ExitedWithCode pred42(42);
279 EXPECT_PRED1(pred0, status0);
280 EXPECT_PRED1(pred1, status1);
281 EXPECT_PRED1(pred42, status42);
282 EXPECT_FALSE(pred0(status1));
283 EXPECT_FALSE(pred42(status0));
284 EXPECT_FALSE(pred1(status42));
287 // Tests the KilledBySignal predicate.
288 TEST(ExitStatusPredicateTest, KilledBySignal) {
289 const int status_segv = KilledExitStatus(SIGSEGV);
290 const int status_kill = KilledExitStatus(SIGKILL);
291 const testing::KilledBySignal pred_segv(SIGSEGV);
292 const testing::KilledBySignal pred_kill(SIGKILL);
293 EXPECT_PRED1(pred_segv, status_segv);
294 EXPECT_PRED1(pred_kill, status_kill);
295 EXPECT_FALSE(pred_segv(status_kill));
296 EXPECT_FALSE(pred_kill(status_segv));
299 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
301 // The following code intentionally tests a suboptimal syntax.
303 #pragma GCC diagnostic push
304 #pragma GCC diagnostic ignored "-Wdangling-else"
305 #pragma GCC diagnostic ignored "-Wempty-body"
306 #pragma GCC diagnostic ignored "-Wpragmas"
308 // Tests that the death test macros expand to code which may or may not
309 // be followed by operator<<, and that in either case the complete text
310 // comprises only a single C++ statement.
311 TEST_F(TestForDeathTest, SingleStatement) {
313 // This would fail if executed; this is a compilation test only
314 ASSERT_DEATH(return, "");
317 EXPECT_DEATH(_exit(1), "");
319 // This empty "else" branch is meant to ensure that EXPECT_DEATH
320 // doesn't expand into an "if" statement without an "else"
324 ASSERT_DEATH(return, "") << "did not die";
329 EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
332 #pragma GCC diagnostic pop
337 void DieWithEmbeddedNul() {
338 fprintf(stderr, "Hello%cmy null world.\n", '\0');
343 // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
344 // message has a NUL character in it.
345 TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
346 EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
347 ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
350 # endif // GTEST_USES_PCRE
352 // Tests that death test macros expand to code which interacts well with switch
354 TEST_F(TestForDeathTest, SwitchStatement) {
355 // Microsoft compiler usually complains about switch statements without
356 // case labels. We suppress that warning for this test.
357 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
361 ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
365 EXPECT_DEATH(_exit(1), "") << "exit in switch case";
367 GTEST_DISABLE_MSC_WARNINGS_POP_()
370 // Tests that a static member function can be used in a "fast" style
372 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
373 testing::GTEST_FLAG(death_test_style) = "fast";
374 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
377 // Tests that a method of the test fixture can be used in a "fast"
379 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
380 testing::GTEST_FLAG(death_test_style) = "fast";
382 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
385 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
387 // Tests that death tests work even if the current directory has been
389 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
390 testing::GTEST_FLAG(death_test_style) = "fast";
393 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
396 ASSERT_DEATH(_exit(1), "");
400 void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
402 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
403 void SetSigprofActionAndTimer() {
404 struct sigaction signal_action;
405 memset(&signal_action, 0, sizeof(signal_action));
406 sigemptyset(&signal_action.sa_mask);
407 signal_action.sa_sigaction = SigprofAction;
408 signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
409 ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr));
410 // timer comes second, to avoid SIGPROF premature delivery, as suggested at
411 // https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
412 struct itimerval timer;
413 timer.it_interval.tv_sec = 0;
414 timer.it_interval.tv_usec = 1;
415 timer.it_value = timer.it_interval;
416 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
419 // Disables ITIMER_PROF timer and ignores SIGPROF signal.
420 void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
421 struct itimerval timer;
422 timer.it_interval.tv_sec = 0;
423 timer.it_interval.tv_usec = 0;
424 timer.it_value = timer.it_interval;
425 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
426 struct sigaction signal_action;
427 memset(&signal_action, 0, sizeof(signal_action));
428 sigemptyset(&signal_action.sa_mask);
429 signal_action.sa_handler = SIG_IGN;
430 ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
433 // Tests that death tests work when SIGPROF handler and timer are set.
434 TEST_F(TestForDeathTest, FastSigprofActionSet) {
435 testing::GTEST_FLAG(death_test_style) = "fast";
436 SetSigprofActionAndTimer();
437 EXPECT_DEATH(_exit(1), "");
438 struct sigaction old_signal_action;
439 DisableSigprofActionAndTimer(&old_signal_action);
440 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
443 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
444 testing::GTEST_FLAG(death_test_style) = "threadsafe";
445 SetSigprofActionAndTimer();
446 EXPECT_DEATH(_exit(1), "");
447 struct sigaction old_signal_action;
448 DisableSigprofActionAndTimer(&old_signal_action);
449 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
451 # endif // GTEST_OS_LINUX
453 // Repeats a representative sample of death tests in the "threadsafe" style:
455 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
456 testing::GTEST_FLAG(death_test_style) = "threadsafe";
457 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
460 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
461 testing::GTEST_FLAG(death_test_style) = "threadsafe";
463 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
466 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
467 testing::GTEST_FLAG(death_test_style) = "threadsafe";
469 for (int i = 0; i < 3; ++i)
470 EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
473 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
474 testing::GTEST_FLAG(death_test_style) = "threadsafe";
477 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
480 ASSERT_DEATH(_exit(1), "");
483 TEST_F(TestForDeathTest, MixedStyles) {
484 testing::GTEST_FLAG(death_test_style) = "threadsafe";
485 EXPECT_DEATH(_exit(1), "");
486 testing::GTEST_FLAG(death_test_style) = "fast";
487 EXPECT_DEATH(_exit(1), "");
490 # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
494 void SetPthreadFlag() {
498 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
499 if (!testing::GTEST_FLAG(death_test_use_fork)) {
500 testing::GTEST_FLAG(death_test_style) = "threadsafe";
501 pthread_flag = false;
502 ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr));
503 ASSERT_DEATH(_exit(1), "");
504 ASSERT_FALSE(pthread_flag);
508 # endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
510 // Tests that a method of another class can be used in a death test.
511 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
512 const MayDie x(true);
513 ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
516 // Tests that a global function can be used in a death test.
517 TEST_F(TestForDeathTest, GlobalFunction) {
518 EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
521 // Tests that any value convertible to an RE works as a second
522 // argument to EXPECT_DEATH.
523 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
524 static const char regex_c_str[] = "GlobalFunction";
525 EXPECT_DEATH(GlobalFunction(), regex_c_str);
527 const testing::internal::RE regex(regex_c_str);
528 EXPECT_DEATH(GlobalFunction(), regex);
530 # if !GTEST_USES_PCRE
532 const ::std::string regex_std_str(regex_c_str);
533 EXPECT_DEATH(GlobalFunction(), regex_std_str);
535 // This one is tricky; a temporary pointer into another temporary. Reference
536 // lifetime extension of the pointer is not sufficient.
537 EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
539 # endif // !GTEST_USES_PCRE
542 // Tests that a non-void function can be used in a death test.
543 TEST_F(TestForDeathTest, NonVoidFunction) {
544 ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
547 // Tests that functions that take parameter(s) can be used in a death test.
548 TEST_F(TestForDeathTest, FunctionWithParameter) {
549 EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
550 EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
553 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
554 TEST_F(TestForDeathTest, OutsideFixture) {
555 DeathTestSubroutine();
558 // Tests that death tests can be done inside a loop.
559 TEST_F(TestForDeathTest, InsideLoop) {
560 for (int i = 0; i < 5; i++) {
561 EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
565 // Tests that a compound statement can be used in a death test.
566 TEST_F(TestForDeathTest, CompoundStatement) {
567 EXPECT_DEATH({ // NOLINT
575 // Tests that code that doesn't die causes a death test to fail.
576 TEST_F(TestForDeathTest, DoesNotDie) {
577 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
581 // Tests that a death test fails when the error message isn't expected.
582 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
583 EXPECT_NONFATAL_FAILURE({ // NOLINT
584 EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
585 }, "died but not with expected error");
588 // On exit, *aborted will be true if and only if the EXPECT_DEATH()
589 // statement aborted the function.
590 void ExpectDeathTestHelper(bool* aborted) {
592 EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
596 // Tests that EXPECT_DEATH doesn't abort the test on failure.
597 TEST_F(TestForDeathTest, EXPECT_DEATH) {
599 EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
601 EXPECT_FALSE(aborted);
604 // Tests that ASSERT_DEATH does abort the test on failure.
605 TEST_F(TestForDeathTest, ASSERT_DEATH) {
607 EXPECT_FATAL_FAILURE({ // NOLINT
609 ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
612 EXPECT_TRUE(aborted);
615 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
616 TEST_F(TestForDeathTest, SingleEvaluation) {
618 EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
620 const char* regex = "DieIf";
621 const char* regex_save = regex;
622 EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
623 EXPECT_EQ(regex_save + 1, regex);
626 // Tests that run-away death tests are reported as failures.
627 TEST_F(TestForDeathTest, RunawayIsFailure) {
628 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
632 // Tests that death tests report executing 'return' in the statement as
634 TEST_F(TestForDeathTest, ReturnIsFailure) {
635 EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
636 "illegal return in test statement.");
639 // Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
640 // message to it, and in debug mode it:
641 // 1. Asserts on death.
642 // 2. Has no side effect.
644 // And in opt mode, it:
645 // 1. Has side effects but does not assert.
646 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
649 // Put the regex in a local variable to make sure we don't get an "unused"
650 // warning in opt mode.
651 const char* regex = "death.*DieInDebugElse12";
653 EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)
654 << "Must accept a streamed message";
658 // Checks that the assignment occurs in opt mode (sideeffect).
659 EXPECT_EQ(12, sideeffect);
663 // Checks that the assignment does not occur in dbg mode (no sideeffect).
664 EXPECT_EQ(0, sideeffect);
669 # if GTEST_OS_WINDOWS
671 // Tests that EXPECT_DEBUG_DEATH works as expected when in debug mode
672 // the Windows CRT crashes the process with an assertion failure.
673 // 1. Asserts on death.
674 // 2. Has no side effect (doesn't pop up a window or wait for user input).
676 // And in opt mode, it:
677 // 1. Has side effects but does not assert.
678 TEST_F(TestForDeathTest, CRTDebugDeath) {
681 // Put the regex in a local variable to make sure we don't get an "unused"
682 // warning in opt mode.
683 const char* regex = "dup.* : Assertion failed";
685 EXPECT_DEBUG_DEATH(DieInCRTDebugElse12(&sideeffect), regex)
686 << "Must accept a streamed message";
690 // Checks that the assignment occurs in opt mode (sideeffect).
691 EXPECT_EQ(12, sideeffect);
695 // Checks that the assignment does not occur in dbg mode (no sideeffect).
696 EXPECT_EQ(0, sideeffect);
701 # endif // GTEST_OS_WINDOWS
703 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
704 // message to it, and in debug mode it:
705 // 1. Asserts on death.
706 // 2. Has no side effect.
708 // And in opt mode, it:
709 // 1. Has side effects but does not assert.
710 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
713 ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
714 << "Must accept a streamed message";
718 // Checks that the assignment occurs in opt mode (sideeffect).
719 EXPECT_EQ(12, sideeffect);
723 // Checks that the assignment does not occur in dbg mode (no sideeffect).
724 EXPECT_EQ(0, sideeffect);
731 void ExpectDebugDeathHelper(bool* aborted) {
733 EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
737 # if GTEST_OS_WINDOWS
738 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
739 printf("This test should be considered failing if it shows "
740 "any pop-up dialogs.\n");
744 testing::GTEST_FLAG(catch_exceptions) = false;
748 # endif // GTEST_OS_WINDOWS
750 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
752 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
754 EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
755 EXPECT_FALSE(aborted);
758 void AssertDebugDeathHelper(bool* aborted) {
760 GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH";
761 ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "")
762 << "This is expected to fail.";
763 GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH";
767 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
769 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
772 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
773 EXPECT_TRUE(aborted);
776 TEST_F(TestForDeathTest, AssertDebugDeathAborts2) {
779 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
780 EXPECT_TRUE(aborted);
783 TEST_F(TestForDeathTest, AssertDebugDeathAborts3) {
786 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
787 EXPECT_TRUE(aborted);
790 TEST_F(TestForDeathTest, AssertDebugDeathAborts4) {
793 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
794 EXPECT_TRUE(aborted);
797 TEST_F(TestForDeathTest, AssertDebugDeathAborts5) {
800 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
801 EXPECT_TRUE(aborted);
804 TEST_F(TestForDeathTest, AssertDebugDeathAborts6) {
807 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
808 EXPECT_TRUE(aborted);
811 TEST_F(TestForDeathTest, AssertDebugDeathAborts7) {
814 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
815 EXPECT_TRUE(aborted);
818 TEST_F(TestForDeathTest, AssertDebugDeathAborts8) {
821 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
822 EXPECT_TRUE(aborted);
825 TEST_F(TestForDeathTest, AssertDebugDeathAborts9) {
828 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
829 EXPECT_TRUE(aborted);
832 TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
835 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
836 EXPECT_TRUE(aborted);
841 // Tests the *_EXIT family of macros, using a variety of predicates.
842 static void TestExitMacros() {
843 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
844 ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
846 # if GTEST_OS_WINDOWS
848 // Of all signals effects on the process exit code, only those of SIGABRT
849 // are documented on Windows.
850 // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
851 EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
853 # elif !GTEST_OS_FUCHSIA
855 // Fuchsia has no unix signals.
856 EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
857 ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
859 EXPECT_FATAL_FAILURE({ // NOLINT
860 ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
861 << "This failure is expected, too.";
862 }, "This failure is expected, too.");
864 # endif // GTEST_OS_WINDOWS
866 EXPECT_NONFATAL_FAILURE({ // NOLINT
867 EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
868 << "This failure is expected.";
869 }, "This failure is expected.");
872 TEST_F(TestForDeathTest, ExitMacros) {
876 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
877 testing::GTEST_FLAG(death_test_use_fork) = true;
881 TEST_F(TestForDeathTest, InvalidStyle) {
882 testing::GTEST_FLAG(death_test_style) = "rococo";
883 EXPECT_NONFATAL_FAILURE({ // NOLINT
884 EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
885 }, "This failure is expected.");
888 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
889 testing::GTEST_FLAG(death_test_style) = "fast";
890 EXPECT_NONFATAL_FAILURE(
891 EXPECT_DEATH(DieWithMessage("death\n"),
894 "[ DEATH ] death\n");
897 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
898 testing::GTEST_FLAG(death_test_style) = "fast";
899 EXPECT_NONFATAL_FAILURE(
901 fprintf(stderr, "returning\n");
905 " Result: illegal return in test statement.\n"
907 "[ DEATH ] returning\n");
910 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
911 testing::GTEST_FLAG(death_test_style) = "fast";
912 EXPECT_NONFATAL_FAILURE(
913 EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
914 testing::ExitedWithCode(3),
916 " Result: died but not with expected exit code:\n"
917 " Exited with exit status 1\n"
919 "[ DEATH ] exiting with rc 1\n");
922 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
923 testing::GTEST_FLAG(death_test_style) = "fast";
924 EXPECT_NONFATAL_FAILURE(
925 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
926 "line 1\nxyz\nline 3\n"),
930 "[ DEATH ] line 3\n");
933 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
934 testing::GTEST_FLAG(death_test_style) = "fast";
935 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
936 "line 1\nline 2\nline 3\n");
939 // A DeathTestFactory that returns MockDeathTests.
940 class MockDeathTestFactory : public DeathTestFactory {
942 MockDeathTestFactory();
943 bool Create(const char* statement,
944 testing::Matcher<const std::string&> matcher, const char* file,
945 int line, DeathTest** test) override;
947 // Sets the parameters for subsequent calls to Create.
948 void SetParameters(bool create, DeathTest::TestRole role,
949 int status, bool passed);
952 int AssumeRoleCalls() const { return assume_role_calls_; }
953 int WaitCalls() const { return wait_calls_; }
954 size_t PassedCalls() const { return passed_args_.size(); }
955 bool PassedArgument(int n) const {
956 return passed_args_[static_cast<size_t>(n)];
958 size_t AbortCalls() const { return abort_args_.size(); }
959 DeathTest::AbortReason AbortArgument(int n) const {
960 return abort_args_[static_cast<size_t>(n)];
962 bool TestDeleted() const { return test_deleted_; }
965 friend class MockDeathTest;
966 // If true, Create will return a MockDeathTest; otherwise it returns
969 // The value a MockDeathTest will return from its AssumeRole method.
970 DeathTest::TestRole role_;
971 // The value a MockDeathTest will return from its Wait method.
973 // The value a MockDeathTest will return from its Passed method.
976 // Number of times AssumeRole was called.
977 int assume_role_calls_;
978 // Number of times Wait was called.
980 // The arguments to the calls to Passed since the last call to
982 std::vector<bool> passed_args_;
983 // The arguments to the calls to Abort since the last call to
985 std::vector<DeathTest::AbortReason> abort_args_;
986 // True if the last MockDeathTest returned by Create has been
992 // A DeathTest implementation useful in testing. It returns values set
993 // at its creation from its various inherited DeathTest methods, and
994 // reports calls to those methods to its parent MockDeathTestFactory
996 class MockDeathTest : public DeathTest {
998 MockDeathTest(MockDeathTestFactory *parent,
999 TestRole role, int status, bool passed) :
1000 parent_(parent), role_(role), status_(status), passed_(passed) {
1002 ~MockDeathTest() override { parent_->test_deleted_ = true; }
1003 TestRole AssumeRole() override {
1004 ++parent_->assume_role_calls_;
1007 int Wait() override {
1008 ++parent_->wait_calls_;
1011 bool Passed(bool exit_status_ok) override {
1012 parent_->passed_args_.push_back(exit_status_ok);
1015 void Abort(AbortReason reason) override {
1016 parent_->abort_args_.push_back(reason);
1020 MockDeathTestFactory* const parent_;
1021 const TestRole role_;
1027 // MockDeathTestFactory constructor.
1028 MockDeathTestFactory::MockDeathTestFactory()
1030 role_(DeathTest::OVERSEE_TEST),
1033 assume_role_calls_(0),
1040 // Sets the parameters for subsequent calls to Create.
1041 void MockDeathTestFactory::SetParameters(bool create,
1042 DeathTest::TestRole role,
1043 int status, bool passed) {
1049 assume_role_calls_ = 0;
1051 passed_args_.clear();
1052 abort_args_.clear();
1056 // Sets test to NULL (if create_ is false) or to the address of a new
1057 // MockDeathTest object with parameters taken from the last call
1058 // to SetParameters (if create_ is true). Always returns true.
1059 bool MockDeathTestFactory::Create(
1060 const char* /*statement*/, testing::Matcher<const std::string&> /*matcher*/,
1061 const char* /*file*/, int /*line*/, DeathTest** test) {
1062 test_deleted_ = false;
1064 *test = new MockDeathTest(this, role_, status_, passed_);
1071 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
1072 // It installs a MockDeathTestFactory that is used for the duration
1073 // of the test case.
1074 class MacroLogicDeathTest : public testing::Test {
1076 static testing::internal::ReplaceDeathTestFactory* replacer_;
1077 static MockDeathTestFactory* factory_;
1079 static void SetUpTestSuite() {
1080 factory_ = new MockDeathTestFactory;
1081 replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
1084 static void TearDownTestSuite() {
1086 replacer_ = nullptr;
1091 // Runs a death test that breaks the rules by returning. Such a death
1092 // test cannot be run directly from a test routine that uses a
1093 // MockDeathTest, or the remainder of the routine will not be executed.
1094 static void RunReturningDeathTest(bool* flag) {
1095 ASSERT_DEATH({ // NOLINT
1102 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ =
1104 MockDeathTestFactory* MacroLogicDeathTest::factory_ = nullptr;
1106 // Test that nothing happens when the factory doesn't return a DeathTest:
1107 TEST_F(MacroLogicDeathTest, NothingHappens) {
1109 factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
1110 EXPECT_DEATH(flag = true, "");
1112 EXPECT_EQ(0, factory_->AssumeRoleCalls());
1113 EXPECT_EQ(0, factory_->WaitCalls());
1114 EXPECT_EQ(0U, factory_->PassedCalls());
1115 EXPECT_EQ(0U, factory_->AbortCalls());
1116 EXPECT_FALSE(factory_->TestDeleted());
1119 // Test that the parent process doesn't run the death test code,
1120 // and that the Passed method returns false when the (simulated)
1121 // child process exits with status 0:
1122 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
1124 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
1125 EXPECT_DEATH(flag = true, "");
1127 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1128 EXPECT_EQ(1, factory_->WaitCalls());
1129 ASSERT_EQ(1U, factory_->PassedCalls());
1130 EXPECT_FALSE(factory_->PassedArgument(0));
1131 EXPECT_EQ(0U, factory_->AbortCalls());
1132 EXPECT_TRUE(factory_->TestDeleted());
1135 // Tests that the Passed method was given the argument "true" when
1136 // the (simulated) child process exits with status 1:
1137 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
1139 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
1140 EXPECT_DEATH(flag = true, "");
1142 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1143 EXPECT_EQ(1, factory_->WaitCalls());
1144 ASSERT_EQ(1U, factory_->PassedCalls());
1145 EXPECT_TRUE(factory_->PassedArgument(0));
1146 EXPECT_EQ(0U, factory_->AbortCalls());
1147 EXPECT_TRUE(factory_->TestDeleted());
1150 // Tests that the (simulated) child process executes the death test
1151 // code, and is aborted with the correct AbortReason if it
1152 // executes a return statement.
1153 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
1155 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1156 RunReturningDeathTest(&flag);
1158 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1159 EXPECT_EQ(0, factory_->WaitCalls());
1160 EXPECT_EQ(0U, factory_->PassedCalls());
1161 EXPECT_EQ(1U, factory_->AbortCalls());
1162 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1163 factory_->AbortArgument(0));
1164 EXPECT_TRUE(factory_->TestDeleted());
1167 // Tests that the (simulated) child process is aborted with the
1168 // correct AbortReason if it does not die.
1169 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
1171 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1172 EXPECT_DEATH(flag = true, "");
1174 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1175 EXPECT_EQ(0, factory_->WaitCalls());
1176 EXPECT_EQ(0U, factory_->PassedCalls());
1177 // This time there are two calls to Abort: one since the test didn't
1178 // die, and another from the ReturnSentinel when it's destroyed. The
1179 // sentinel normally isn't destroyed if a test doesn't die, since
1180 // _exit(2) is called in that case by ForkingDeathTest, but not by
1181 // our MockDeathTest.
1182 ASSERT_EQ(2U, factory_->AbortCalls());
1183 EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
1184 factory_->AbortArgument(0));
1185 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1186 factory_->AbortArgument(1));
1187 EXPECT_TRUE(factory_->TestDeleted());
1190 // Tests that a successful death test does not register a successful
1192 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1193 EXPECT_DEATH(_exit(1), "");
1194 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
1197 TEST(StreamingAssertionsDeathTest, DeathTest) {
1198 EXPECT_DEATH(_exit(1), "") << "unexpected failure";
1199 ASSERT_DEATH(_exit(1), "") << "unexpected failure";
1200 EXPECT_NONFATAL_FAILURE({ // NOLINT
1201 EXPECT_DEATH(_exit(0), "") << "expected failure";
1202 }, "expected failure");
1203 EXPECT_FATAL_FAILURE({ // NOLINT
1204 ASSERT_DEATH(_exit(0), "") << "expected failure";
1205 }, "expected failure");
1208 // Tests that GetLastErrnoDescription returns an empty string when the
1209 // last error is 0 and non-empty string when it is non-zero.
1210 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
1212 EXPECT_STRNE("", GetLastErrnoDescription().c_str());
1214 EXPECT_STREQ("", GetLastErrnoDescription().c_str());
1217 # if GTEST_OS_WINDOWS
1218 TEST(AutoHandleTest, AutoHandleWorks) {
1219 HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1220 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1222 // Tests that the AutoHandle is correctly initialized with a handle.
1223 testing::internal::AutoHandle auto_handle(handle);
1224 EXPECT_EQ(handle, auto_handle.Get());
1226 // Tests that Reset assigns INVALID_HANDLE_VALUE.
1227 // Note that this cannot verify whether the original handle is closed.
1228 auto_handle.Reset();
1229 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
1231 // Tests that Reset assigns the new handle.
1232 // Note that this cannot verify whether the original handle is closed.
1233 handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1234 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1235 auto_handle.Reset(handle);
1236 EXPECT_EQ(handle, auto_handle.Get());
1238 // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
1239 testing::internal::AutoHandle auto_handle2;
1240 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
1242 # endif // GTEST_OS_WINDOWS
1244 # if GTEST_OS_WINDOWS
1245 typedef unsigned __int64 BiggestParsable;
1246 typedef signed __int64 BiggestSignedParsable;
1248 typedef unsigned long long BiggestParsable;
1249 typedef signed long long BiggestSignedParsable;
1250 # endif // GTEST_OS_WINDOWS
1252 // We cannot use std::numeric_limits<T>::max() as it clashes with the
1253 // max() macro defined by <windows.h>.
1254 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1255 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
1257 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
1258 BiggestParsable result = 0;
1260 // Rejects non-numbers.
1261 EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
1263 // Rejects numbers with whitespace prefix.
1264 EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
1266 // Rejects negative numbers.
1267 EXPECT_FALSE(ParseNaturalNumber("-123", &result));
1269 // Rejects numbers starting with a plus sign.
1270 EXPECT_FALSE(ParseNaturalNumber("+123", &result));
1274 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
1275 BiggestParsable result = 0;
1277 EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
1279 signed char char_result = 0;
1280 EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
1284 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
1285 BiggestParsable result = 0;
1288 ASSERT_TRUE(ParseNaturalNumber("123", &result));
1289 EXPECT_EQ(123U, result);
1291 // Check 0 as an edge case.
1293 ASSERT_TRUE(ParseNaturalNumber("0", &result));
1294 EXPECT_EQ(0U, result);
1297 ASSERT_TRUE(ParseNaturalNumber("00000", &result));
1298 EXPECT_EQ(0U, result);
1301 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
1303 msg << kBiggestParsableMax;
1305 BiggestParsable result = 0;
1306 EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
1307 EXPECT_EQ(kBiggestParsableMax, result);
1310 msg2 << kBiggestSignedParsableMax;
1312 BiggestSignedParsable signed_result = 0;
1313 EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
1314 EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
1320 EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
1321 EXPECT_EQ(INT_MAX, int_result);
1326 unsigned int uint_result = 0;
1327 EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
1328 EXPECT_EQ(UINT_MAX, uint_result);
1331 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
1332 short short_result = 0;
1333 ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
1334 EXPECT_EQ(123, short_result);
1336 signed char char_result = 0;
1337 ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
1338 EXPECT_EQ(123, char_result);
1341 # if GTEST_OS_WINDOWS
1342 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
1343 ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
1345 # endif // GTEST_OS_WINDOWS
1347 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
1348 // failures when death tests are available on the system.
1349 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
1350 EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
1351 "death inside CondDeathTestExpectMacro");
1352 ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
1353 "death inside CondDeathTestAssertMacro");
1355 // Empty statement will not crash, which must trigger a failure.
1356 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
1357 EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
1360 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
1361 testing::GTEST_FLAG(death_test_style) = "fast";
1362 EXPECT_FALSE(InDeathTestChild());
1364 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1370 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
1371 testing::GTEST_FLAG(death_test_style) = "threadsafe";
1372 EXPECT_FALSE(InDeathTestChild());
1374 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1380 void DieWithMessage(const char* message) {
1381 fputs(message, stderr);
1382 fflush(stderr); // Make sure the text is printed before the process exits.
1386 TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {
1387 // googletest tests this, of course; here we ensure that including googlemock
1388 // has not broken it.
1389 #if GTEST_USES_POSIX_RE
1390 EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
1392 EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I di?e");
1396 TEST(MatcherDeathTest, MonomorphicMatcherMatches) {
1397 EXPECT_DEATH(DieWithMessage("Behind O, I am slain!"),
1398 Matcher<const std::string&>(ContainsRegex("I am slain")));
1401 TEST(MatcherDeathTest, MonomorphicMatcherDoesNotMatch) {
1402 EXPECT_NONFATAL_FAILURE(
1404 DieWithMessage("Behind O, I am slain!"),
1405 Matcher<const std::string&>(ContainsRegex("Ow, I am slain"))),
1406 "Expected: contains regular expression \"Ow, I am slain\"");
1409 TEST(MatcherDeathTest, PolymorphicMatcherMatches) {
1410 EXPECT_DEATH(DieWithMessage("The rest is silence."),
1411 ContainsRegex("rest is silence"));
1414 TEST(MatcherDeathTest, PolymorphicMatcherDoesNotMatch) {
1415 EXPECT_NONFATAL_FAILURE(
1416 EXPECT_DEATH(DieWithMessage("The rest is silence."),
1417 ContainsRegex("rest is science")),
1418 "Expected: contains regular expression \"rest is science\"");
1423 #else // !GTEST_HAS_DEATH_TEST follows
1427 using testing::internal::CaptureStderr;
1428 using testing::internal::GetCapturedStderr;
1430 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
1431 // defined but do not trigger failures when death tests are not available on
1433 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
1434 // Empty statement will not crash, but that should not trigger a failure
1435 // when death tests are not supported.
1437 EXPECT_DEATH_IF_SUPPORTED(;, "");
1438 std::string output = GetCapturedStderr();
1439 ASSERT_TRUE(NULL != strstr(output.c_str(),
1440 "Death tests are not supported on this platform"));
1441 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1443 // The streamed message should not be printed as there is no test failure.
1445 EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
1446 output = GetCapturedStderr();
1447 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1450 ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
1451 output = GetCapturedStderr();
1452 ASSERT_TRUE(NULL != strstr(output.c_str(),
1453 "Death tests are not supported on this platform"));
1454 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1457 ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
1458 output = GetCapturedStderr();
1459 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1462 void FuncWithAssert(int* n) {
1463 ASSERT_DEATH_IF_SUPPORTED(return;, "");
1467 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
1468 // function (as ASSERT_DEATH does) if death tests are not supported.
1469 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
1477 #endif // !GTEST_HAS_DEATH_TEST
1481 // The following code intentionally tests a suboptimal syntax.
1483 #pragma GCC diagnostic push
1484 #pragma GCC diagnostic ignored "-Wdangling-else"
1485 #pragma GCC diagnostic ignored "-Wempty-body"
1486 #pragma GCC diagnostic ignored "-Wpragmas"
1488 // Tests that the death test macros expand to code which may or may not
1489 // be followed by operator<<, and that in either case the complete text
1490 // comprises only a single C++ statement.
1492 // The syntax should work whether death tests are available or not.
1493 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
1495 // This would fail if executed; this is a compilation test only
1496 ASSERT_DEATH_IF_SUPPORTED(return, "");
1499 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
1501 // This empty "else" branch is meant to ensure that EXPECT_DEATH
1502 // doesn't expand into an "if" statement without an "else"
1506 ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
1511 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
1514 #pragma GCC diagnostic pop
1517 // Tests that conditional death test macros expand to code which interacts
1518 // well with switch statements.
1519 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
1520 // Microsoft compiler usually complains about switch statements without
1521 // case labels. We suppress that warning for this test.
1522 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
1526 ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
1527 << "exit in default switch handler";
1531 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
1533 GTEST_DISABLE_MSC_WARNINGS_POP_()
1536 // Tests that a test case whose name ends with "DeathTest" works fine
1538 TEST(NotADeathTest, Test) {