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.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Tests for death tests.
34 #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 <direct.h> // For chdir().
47 # include <sys/wait.h> // For waitpid.
48 # include <limits> // For std::numeric_limits.
49 # endif // GTEST_OS_WINDOWS
56 # include <sys/time.h>
57 # endif // GTEST_OS_LINUX
59 # include "gtest/gtest-spi.h"
61 // Indicates that this translation unit is part of Google Test's
62 // implementation. It must come before gtest-internal-inl.h is
63 // included, or there will be a compiler error. This trick is to
64 // prevent a user from accidentally including gtest-internal-inl.h in
66 # define GTEST_IMPLEMENTATION_ 1
67 # include "src/gtest-internal-inl.h"
68 # undef GTEST_IMPLEMENTATION_
70 namespace posix = ::testing::internal::posix;
72 using testing::Message;
73 using testing::internal::DeathTest;
74 using testing::internal::DeathTestFactory;
75 using testing::internal::FilePath;
76 using testing::internal::GetLastErrnoDescription;
77 using testing::internal::GetUnitTestImpl;
78 using testing::internal::InDeathTestChild;
79 using testing::internal::ParseNaturalNumber;
84 // A helper class whose objects replace the death test factory for a
85 // single UnitTest object during their lifetimes.
86 class ReplaceDeathTestFactory {
88 explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
89 : unit_test_impl_(GetUnitTestImpl()) {
90 old_factory_ = unit_test_impl_->death_test_factory_.release();
91 unit_test_impl_->death_test_factory_.reset(new_factory);
94 ~ReplaceDeathTestFactory() {
95 unit_test_impl_->death_test_factory_.release();
96 unit_test_impl_->death_test_factory_.reset(old_factory_);
99 // Prevents copying ReplaceDeathTestFactory objects.
100 ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
101 void operator=(const ReplaceDeathTestFactory&);
103 UnitTestImpl* unit_test_impl_;
104 DeathTestFactory* old_factory_;
107 } // namespace internal
108 } // 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.
126 void DieInside(const ::std::string& function) {
127 DieWithMessage("death inside " + function + "().");
130 // Tests that death tests work.
132 class TestForDeathTest : public testing::Test {
134 TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
136 virtual ~TestForDeathTest() {
137 posix::ChDir(original_dir_.c_str());
140 // A static member function that's expected to die.
141 static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
143 // A method of the test fixture that may die.
144 void MemberFunction() {
146 DieInside("MemberFunction");
149 // True iff MemberFunction() should die.
151 const FilePath original_dir_;
154 // A class with a member function that may die.
157 explicit MayDie(bool should_die) : should_die_(should_die) {}
159 // A member function that may die.
160 void MemberFunction() const {
162 DieInside("MayDie::MemberFunction");
166 // True iff MemberFunction() should die.
170 // A global function that's expected to die.
171 void GlobalFunction() { DieInside("GlobalFunction"); }
173 // A non-void function that's expected to die.
174 int NonVoidFunction() {
175 DieInside("NonVoidFunction");
179 // A unary function that may die.
180 void DieIf(bool should_die) {
185 // A binary function that may die.
186 bool DieIfLessThan(int x, int y) {
188 DieInside("DieIfLessThan");
193 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
194 void DeathTestSubroutine() {
195 EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
196 ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
199 // Death in dbg, not opt.
200 int DieInDebugElse12(int* sideeffect) {
201 if (sideeffect) *sideeffect = 12;
205 DieInside("DieInDebugElse12");
212 # if GTEST_OS_WINDOWS
214 // Tests the ExitedWithCode predicate.
215 TEST(ExitStatusPredicateTest, ExitedWithCode) {
216 // On Windows, the process's exit code is the same as its exit status,
217 // so the predicate just compares the its input with its parameter.
218 EXPECT_TRUE(testing::ExitedWithCode(0)(0));
219 EXPECT_TRUE(testing::ExitedWithCode(1)(1));
220 EXPECT_TRUE(testing::ExitedWithCode(42)(42));
221 EXPECT_FALSE(testing::ExitedWithCode(0)(1));
222 EXPECT_FALSE(testing::ExitedWithCode(1)(0));
227 // Returns the exit status of a process that calls _exit(2) with a
228 // given exit code. This is a helper function for the
229 // ExitStatusPredicateTest test suite.
230 static int NormalExitStatus(int exit_code) {
231 pid_t child_pid = fork();
232 if (child_pid == 0) {
236 waitpid(child_pid, &status, 0);
240 // Returns the exit status of a process that raises a given signal.
241 // If the signal does not cause the process to die, then it returns
242 // instead the exit status of a process that exits normally with exit
243 // code 1. This is a helper function for the ExitStatusPredicateTest
245 static int KilledExitStatus(int signum) {
246 pid_t child_pid = fork();
247 if (child_pid == 0) {
252 waitpid(child_pid, &status, 0);
256 // Tests the ExitedWithCode predicate.
257 TEST(ExitStatusPredicateTest, ExitedWithCode) {
258 const int status0 = NormalExitStatus(0);
259 const int status1 = NormalExitStatus(1);
260 const int status42 = NormalExitStatus(42);
261 const testing::ExitedWithCode pred0(0);
262 const testing::ExitedWithCode pred1(1);
263 const testing::ExitedWithCode pred42(42);
264 EXPECT_PRED1(pred0, status0);
265 EXPECT_PRED1(pred1, status1);
266 EXPECT_PRED1(pred42, status42);
267 EXPECT_FALSE(pred0(status1));
268 EXPECT_FALSE(pred42(status0));
269 EXPECT_FALSE(pred1(status42));
272 // Tests the KilledBySignal predicate.
273 TEST(ExitStatusPredicateTest, KilledBySignal) {
274 const int status_segv = KilledExitStatus(SIGSEGV);
275 const int status_kill = KilledExitStatus(SIGKILL);
276 const testing::KilledBySignal pred_segv(SIGSEGV);
277 const testing::KilledBySignal pred_kill(SIGKILL);
278 EXPECT_PRED1(pred_segv, status_segv);
279 EXPECT_PRED1(pred_kill, status_kill);
280 EXPECT_FALSE(pred_segv(status_kill));
281 EXPECT_FALSE(pred_kill(status_segv));
284 # endif // GTEST_OS_WINDOWS
286 // Tests that the death test macros expand to code which may or may not
287 // be followed by operator<<, and that in either case the complete text
288 // comprises only a single C++ statement.
289 TEST_F(TestForDeathTest, SingleStatement) {
291 // This would fail if executed; this is a compilation test only
292 ASSERT_DEATH(return, "");
295 EXPECT_DEATH(_exit(1), "");
297 // This empty "else" branch is meant to ensure that EXPECT_DEATH
298 // doesn't expand into an "if" statement without an "else"
302 ASSERT_DEATH(return, "") << "did not die";
307 EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
310 void DieWithEmbeddedNul() {
311 fprintf(stderr, "Hello%cmy null world.\n", '\0');
317 // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
318 // message has a NUL character in it.
319 TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
320 // TODO(wan@google.com): <regex.h> doesn't support matching strings
321 // with embedded NUL characters - find a way to workaround it.
322 EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
323 ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
325 # endif // GTEST_USES_PCRE
327 // Tests that death test macros expand to code which interacts well with switch
329 TEST_F(TestForDeathTest, SwitchStatement) {
330 // Microsoft compiler usually complains about switch statements without
331 // case labels. We suppress that warning for this test.
333 # pragma warning(push)
334 # pragma warning(disable: 4065)
339 ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
343 EXPECT_DEATH(_exit(1), "") << "exit in switch case";
346 # pragma warning(pop)
350 // Tests that a static member function can be used in a "fast" style
352 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
353 testing::GTEST_FLAG(death_test_style) = "fast";
354 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
357 // Tests that a method of the test fixture can be used in a "fast"
359 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
360 testing::GTEST_FLAG(death_test_style) = "fast";
362 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
365 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
367 // Tests that death tests work even if the current directory has been
369 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
370 testing::GTEST_FLAG(death_test_style) = "fast";
373 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
376 ASSERT_DEATH(_exit(1), "");
380 void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
382 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
383 void SetSigprofActionAndTimer() {
384 struct itimerval timer;
385 timer.it_interval.tv_sec = 0;
386 timer.it_interval.tv_usec = 1;
387 timer.it_value = timer.it_interval;
388 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
389 struct sigaction signal_action;
390 memset(&signal_action, 0, sizeof(signal_action));
391 sigemptyset(&signal_action.sa_mask);
392 signal_action.sa_sigaction = SigprofAction;
393 signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
394 ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL));
397 // Disables ITIMER_PROF timer and ignores SIGPROF signal.
398 void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
399 struct itimerval timer;
400 timer.it_interval.tv_sec = 0;
401 timer.it_interval.tv_usec = 0;
402 timer.it_value = timer.it_interval;
403 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
404 struct sigaction signal_action;
405 memset(&signal_action, 0, sizeof(signal_action));
406 sigemptyset(&signal_action.sa_mask);
407 signal_action.sa_handler = SIG_IGN;
408 ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
411 // Tests that death tests work when SIGPROF handler and timer are set.
412 TEST_F(TestForDeathTest, FastSigprofActionSet) {
413 testing::GTEST_FLAG(death_test_style) = "fast";
414 SetSigprofActionAndTimer();
415 EXPECT_DEATH(_exit(1), "");
416 struct sigaction old_signal_action;
417 DisableSigprofActionAndTimer(&old_signal_action);
418 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
421 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
422 testing::GTEST_FLAG(death_test_style) = "threadsafe";
423 SetSigprofActionAndTimer();
424 EXPECT_DEATH(_exit(1), "");
425 struct sigaction old_signal_action;
426 DisableSigprofActionAndTimer(&old_signal_action);
427 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
429 # endif // GTEST_OS_LINUX
431 // Repeats a representative sample of death tests in the "threadsafe" style:
433 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
434 testing::GTEST_FLAG(death_test_style) = "threadsafe";
435 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
438 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
439 testing::GTEST_FLAG(death_test_style) = "threadsafe";
441 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
444 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
445 testing::GTEST_FLAG(death_test_style) = "threadsafe";
447 for (int i = 0; i < 3; ++i)
448 EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
451 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
452 testing::GTEST_FLAG(death_test_style) = "threadsafe";
455 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
458 ASSERT_DEATH(_exit(1), "");
461 TEST_F(TestForDeathTest, MixedStyles) {
462 testing::GTEST_FLAG(death_test_style) = "threadsafe";
463 EXPECT_DEATH(_exit(1), "");
464 testing::GTEST_FLAG(death_test_style) = "fast";
465 EXPECT_DEATH(_exit(1), "");
472 void SetPthreadFlag() {
478 # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
480 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
481 if (!testing::GTEST_FLAG(death_test_use_fork)) {
482 testing::GTEST_FLAG(death_test_style) = "threadsafe";
483 pthread_flag = false;
484 ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
485 ASSERT_DEATH(_exit(1), "");
486 ASSERT_FALSE(pthread_flag);
490 # endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
492 // Tests that a method of another class can be used in a death test.
493 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
494 const MayDie x(true);
495 ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
498 // Tests that a global function can be used in a death test.
499 TEST_F(TestForDeathTest, GlobalFunction) {
500 EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
503 // Tests that any value convertible to an RE works as a second
504 // argument to EXPECT_DEATH.
505 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
506 static const char regex_c_str[] = "GlobalFunction";
507 EXPECT_DEATH(GlobalFunction(), regex_c_str);
509 const testing::internal::RE regex(regex_c_str);
510 EXPECT_DEATH(GlobalFunction(), regex);
512 # if GTEST_HAS_GLOBAL_STRING
514 const string regex_str(regex_c_str);
515 EXPECT_DEATH(GlobalFunction(), regex_str);
517 # endif // GTEST_HAS_GLOBAL_STRING
519 const ::std::string regex_std_str(regex_c_str);
520 EXPECT_DEATH(GlobalFunction(), regex_std_str);
523 // Tests that a non-void function can be used in a death test.
524 TEST_F(TestForDeathTest, NonVoidFunction) {
525 ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
528 // Tests that functions that take parameter(s) can be used in a death test.
529 TEST_F(TestForDeathTest, FunctionWithParameter) {
530 EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
531 EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
534 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
535 TEST_F(TestForDeathTest, OutsideFixture) {
536 DeathTestSubroutine();
539 // Tests that death tests can be done inside a loop.
540 TEST_F(TestForDeathTest, InsideLoop) {
541 for (int i = 0; i < 5; i++) {
542 EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
546 // Tests that a compound statement can be used in a death test.
547 TEST_F(TestForDeathTest, CompoundStatement) {
548 EXPECT_DEATH({ // NOLINT
556 // Tests that code that doesn't die causes a death test to fail.
557 TEST_F(TestForDeathTest, DoesNotDie) {
558 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
562 // Tests that a death test fails when the error message isn't expected.
563 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
564 EXPECT_NONFATAL_FAILURE({ // NOLINT
565 EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
566 }, "died but not with expected error");
569 // On exit, *aborted will be true iff the EXPECT_DEATH() statement
570 // aborted the function.
571 void ExpectDeathTestHelper(bool* aborted) {
573 EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
577 // Tests that EXPECT_DEATH doesn't abort the test on failure.
578 TEST_F(TestForDeathTest, EXPECT_DEATH) {
580 EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
582 EXPECT_FALSE(aborted);
585 // Tests that ASSERT_DEATH does abort the test on failure.
586 TEST_F(TestForDeathTest, ASSERT_DEATH) {
588 EXPECT_FATAL_FAILURE({ // NOLINT
590 ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
593 EXPECT_TRUE(aborted);
596 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
597 TEST_F(TestForDeathTest, SingleEvaluation) {
599 EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
601 const char* regex = "DieIf";
602 const char* regex_save = regex;
603 EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
604 EXPECT_EQ(regex_save + 1, regex);
607 // Tests that run-away death tests are reported as failures.
608 TEST_F(TestForDeathTest, RunawayIsFailure) {
609 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
613 // Tests that death tests report executing 'return' in the statement as
615 TEST_F(TestForDeathTest, ReturnIsFailure) {
616 EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
617 "illegal return in test statement.");
620 // Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
621 // message to it, and in debug mode it:
622 // 1. Asserts on death.
623 // 2. Has no side effect.
625 // And in opt mode, it:
626 // 1. Has side effects but does not assert.
627 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
630 EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
631 << "Must accept a streamed message";
635 // Checks that the assignment occurs in opt mode (sideeffect).
636 EXPECT_EQ(12, sideeffect);
640 // Checks that the assignment does not occur in dbg mode (no sideeffect).
641 EXPECT_EQ(0, sideeffect);
646 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
647 // message to it, and in debug mode it:
648 // 1. Asserts on death.
649 // 2. Has no side effect.
651 // And in opt mode, it:
652 // 1. Has side effects but does not assert.
653 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
656 ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
657 << "Must accept a streamed message";
661 // Checks that the assignment occurs in opt mode (sideeffect).
662 EXPECT_EQ(12, sideeffect);
666 // Checks that the assignment does not occur in dbg mode (no sideeffect).
667 EXPECT_EQ(0, sideeffect);
674 void ExpectDebugDeathHelper(bool* aborted) {
676 EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
680 # if GTEST_OS_WINDOWS
681 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
682 printf("This test should be considered failing if it shows "
683 "any pop-up dialogs.\n");
687 testing::GTEST_FLAG(catch_exceptions) = false;
691 # endif // GTEST_OS_WINDOWS
693 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
695 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
697 EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
698 EXPECT_FALSE(aborted);
701 void AssertDebugDeathHelper(bool* aborted) {
703 ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
707 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
709 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
712 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
713 EXPECT_TRUE(aborted);
718 // Tests the *_EXIT family of macros, using a variety of predicates.
719 static void TestExitMacros() {
720 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
721 ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
723 # if GTEST_OS_WINDOWS
725 // Of all signals effects on the process exit code, only those of SIGABRT
726 // are documented on Windows.
727 // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
728 EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
732 EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
733 ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
735 EXPECT_FATAL_FAILURE({ // NOLINT
736 ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
737 << "This failure is expected, too.";
738 }, "This failure is expected, too.");
740 # endif // GTEST_OS_WINDOWS
742 EXPECT_NONFATAL_FAILURE({ // NOLINT
743 EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
744 << "This failure is expected.";
745 }, "This failure is expected.");
748 TEST_F(TestForDeathTest, ExitMacros) {
752 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
753 testing::GTEST_FLAG(death_test_use_fork) = true;
757 TEST_F(TestForDeathTest, InvalidStyle) {
758 testing::GTEST_FLAG(death_test_style) = "rococo";
759 EXPECT_NONFATAL_FAILURE({ // NOLINT
760 EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
761 }, "This failure is expected.");
764 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
765 testing::GTEST_FLAG(death_test_style) = "fast";
766 EXPECT_NONFATAL_FAILURE(
767 EXPECT_DEATH(DieWithMessage("death\n"),
770 "[ DEATH ] death\n");
773 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
774 testing::GTEST_FLAG(death_test_style) = "fast";
775 EXPECT_NONFATAL_FAILURE(
777 fprintf(stderr, "returning\n");
781 " Result: illegal return in test statement.\n"
783 "[ DEATH ] returning\n");
786 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
787 testing::GTEST_FLAG(death_test_style) = "fast";
788 EXPECT_NONFATAL_FAILURE(
789 EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
790 testing::ExitedWithCode(3),
792 " Result: died but not with expected exit code:\n"
793 " Exited with exit status 1\n"
795 "[ DEATH ] exiting with rc 1\n");
798 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
799 testing::GTEST_FLAG(death_test_style) = "fast";
800 EXPECT_NONFATAL_FAILURE(
801 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
802 "line 1\nxyz\nline 3\n"),
806 "[ DEATH ] line 3\n");
809 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
810 testing::GTEST_FLAG(death_test_style) = "fast";
811 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
812 "line 1\nline 2\nline 3\n");
815 // A DeathTestFactory that returns MockDeathTests.
816 class MockDeathTestFactory : public DeathTestFactory {
818 MockDeathTestFactory();
819 virtual bool Create(const char* statement,
820 const ::testing::internal::RE* regex,
821 const char* file, int line, DeathTest** test);
823 // Sets the parameters for subsequent calls to Create.
824 void SetParameters(bool create, DeathTest::TestRole role,
825 int status, bool passed);
828 int AssumeRoleCalls() const { return assume_role_calls_; }
829 int WaitCalls() const { return wait_calls_; }
830 int PassedCalls() const { return passed_args_.size(); }
831 bool PassedArgument(int n) const { return passed_args_[n]; }
832 int AbortCalls() const { return abort_args_.size(); }
833 DeathTest::AbortReason AbortArgument(int n) const {
834 return abort_args_[n];
836 bool TestDeleted() const { return test_deleted_; }
839 friend class MockDeathTest;
840 // If true, Create will return a MockDeathTest; otherwise it returns
843 // The value a MockDeathTest will return from its AssumeRole method.
844 DeathTest::TestRole role_;
845 // The value a MockDeathTest will return from its Wait method.
847 // The value a MockDeathTest will return from its Passed method.
850 // Number of times AssumeRole was called.
851 int assume_role_calls_;
852 // Number of times Wait was called.
854 // The arguments to the calls to Passed since the last call to
856 std::vector<bool> passed_args_;
857 // The arguments to the calls to Abort since the last call to
859 std::vector<DeathTest::AbortReason> abort_args_;
860 // True if the last MockDeathTest returned by Create has been
866 // A DeathTest implementation useful in testing. It returns values set
867 // at its creation from its various inherited DeathTest methods, and
868 // reports calls to those methods to its parent MockDeathTestFactory
870 class MockDeathTest : public DeathTest {
872 MockDeathTest(MockDeathTestFactory *parent,
873 TestRole role, int status, bool passed) :
874 parent_(parent), role_(role), status_(status), passed_(passed) {
876 virtual ~MockDeathTest() {
877 parent_->test_deleted_ = true;
879 virtual TestRole AssumeRole() {
880 ++parent_->assume_role_calls_;
884 ++parent_->wait_calls_;
887 virtual bool Passed(bool exit_status_ok) {
888 parent_->passed_args_.push_back(exit_status_ok);
891 virtual void Abort(AbortReason reason) {
892 parent_->abort_args_.push_back(reason);
896 MockDeathTestFactory* const parent_;
897 const TestRole role_;
903 // MockDeathTestFactory constructor.
904 MockDeathTestFactory::MockDeathTestFactory()
906 role_(DeathTest::OVERSEE_TEST),
909 assume_role_calls_(0),
916 // Sets the parameters for subsequent calls to Create.
917 void MockDeathTestFactory::SetParameters(bool create,
918 DeathTest::TestRole role,
919 int status, bool passed) {
925 assume_role_calls_ = 0;
927 passed_args_.clear();
932 // Sets test to NULL (if create_ is false) or to the address of a new
933 // MockDeathTest object with parameters taken from the last call
934 // to SetParameters (if create_ is true). Always returns true.
935 bool MockDeathTestFactory::Create(const char* /*statement*/,
936 const ::testing::internal::RE* /*regex*/,
937 const char* /*file*/,
940 test_deleted_ = false;
942 *test = new MockDeathTest(this, role_, status_, passed_);
949 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
950 // It installs a MockDeathTestFactory that is used for the duration
952 class MacroLogicDeathTest : public testing::Test {
954 static testing::internal::ReplaceDeathTestFactory* replacer_;
955 static MockDeathTestFactory* factory_;
957 static void SetUpTestCase() {
958 factory_ = new MockDeathTestFactory;
959 replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
962 static void TearDownTestCase() {
969 // Runs a death test that breaks the rules by returning. Such a death
970 // test cannot be run directly from a test routine that uses a
971 // MockDeathTest, or the remainder of the routine will not be executed.
972 static void RunReturningDeathTest(bool* flag) {
973 ASSERT_DEATH({ // NOLINT
980 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
982 MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
985 // Test that nothing happens when the factory doesn't return a DeathTest:
986 TEST_F(MacroLogicDeathTest, NothingHappens) {
988 factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
989 EXPECT_DEATH(flag = true, "");
991 EXPECT_EQ(0, factory_->AssumeRoleCalls());
992 EXPECT_EQ(0, factory_->WaitCalls());
993 EXPECT_EQ(0, factory_->PassedCalls());
994 EXPECT_EQ(0, factory_->AbortCalls());
995 EXPECT_FALSE(factory_->TestDeleted());
998 // Test that the parent process doesn't run the death test code,
999 // and that the Passed method returns false when the (simulated)
1000 // child process exits with status 0:
1001 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
1003 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
1004 EXPECT_DEATH(flag = true, "");
1006 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1007 EXPECT_EQ(1, factory_->WaitCalls());
1008 ASSERT_EQ(1, factory_->PassedCalls());
1009 EXPECT_FALSE(factory_->PassedArgument(0));
1010 EXPECT_EQ(0, factory_->AbortCalls());
1011 EXPECT_TRUE(factory_->TestDeleted());
1014 // Tests that the Passed method was given the argument "true" when
1015 // the (simulated) child process exits with status 1:
1016 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
1018 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
1019 EXPECT_DEATH(flag = true, "");
1021 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1022 EXPECT_EQ(1, factory_->WaitCalls());
1023 ASSERT_EQ(1, factory_->PassedCalls());
1024 EXPECT_TRUE(factory_->PassedArgument(0));
1025 EXPECT_EQ(0, factory_->AbortCalls());
1026 EXPECT_TRUE(factory_->TestDeleted());
1029 // Tests that the (simulated) child process executes the death test
1030 // code, and is aborted with the correct AbortReason if it
1031 // executes a return statement.
1032 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
1034 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1035 RunReturningDeathTest(&flag);
1037 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1038 EXPECT_EQ(0, factory_->WaitCalls());
1039 EXPECT_EQ(0, factory_->PassedCalls());
1040 EXPECT_EQ(1, factory_->AbortCalls());
1041 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1042 factory_->AbortArgument(0));
1043 EXPECT_TRUE(factory_->TestDeleted());
1046 // Tests that the (simulated) child process is aborted with the
1047 // correct AbortReason if it does not die.
1048 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
1050 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1051 EXPECT_DEATH(flag = true, "");
1053 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1054 EXPECT_EQ(0, factory_->WaitCalls());
1055 EXPECT_EQ(0, factory_->PassedCalls());
1056 // This time there are two calls to Abort: one since the test didn't
1057 // die, and another from the ReturnSentinel when it's destroyed. The
1058 // sentinel normally isn't destroyed if a test doesn't die, since
1059 // _exit(2) is called in that case by ForkingDeathTest, but not by
1060 // our MockDeathTest.
1061 ASSERT_EQ(2, factory_->AbortCalls());
1062 EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
1063 factory_->AbortArgument(0));
1064 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1065 factory_->AbortArgument(1));
1066 EXPECT_TRUE(factory_->TestDeleted());
1069 // Tests that a successful death test does not register a successful
1071 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1072 EXPECT_DEATH(_exit(1), "");
1073 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
1076 TEST(StreamingAssertionsDeathTest, DeathTest) {
1077 EXPECT_DEATH(_exit(1), "") << "unexpected failure";
1078 ASSERT_DEATH(_exit(1), "") << "unexpected failure";
1079 EXPECT_NONFATAL_FAILURE({ // NOLINT
1080 EXPECT_DEATH(_exit(0), "") << "expected failure";
1081 }, "expected failure");
1082 EXPECT_FATAL_FAILURE({ // NOLINT
1083 ASSERT_DEATH(_exit(0), "") << "expected failure";
1084 }, "expected failure");
1087 // Tests that GetLastErrnoDescription returns an empty string when the
1088 // last error is 0 and non-empty string when it is non-zero.
1089 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
1091 EXPECT_STRNE("", GetLastErrnoDescription().c_str());
1093 EXPECT_STREQ("", GetLastErrnoDescription().c_str());
1096 # if GTEST_OS_WINDOWS
1097 TEST(AutoHandleTest, AutoHandleWorks) {
1098 HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1099 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1101 // Tests that the AutoHandle is correctly initialized with a handle.
1102 testing::internal::AutoHandle auto_handle(handle);
1103 EXPECT_EQ(handle, auto_handle.Get());
1105 // Tests that Reset assigns INVALID_HANDLE_VALUE.
1106 // Note that this cannot verify whether the original handle is closed.
1107 auto_handle.Reset();
1108 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
1110 // Tests that Reset assigns the new handle.
1111 // Note that this cannot verify whether the original handle is closed.
1112 handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1113 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1114 auto_handle.Reset(handle);
1115 EXPECT_EQ(handle, auto_handle.Get());
1117 // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
1118 testing::internal::AutoHandle auto_handle2;
1119 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
1121 # endif // GTEST_OS_WINDOWS
1123 # if GTEST_OS_WINDOWS
1124 typedef unsigned __int64 BiggestParsable;
1125 typedef signed __int64 BiggestSignedParsable;
1126 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1127 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
1129 typedef unsigned long long BiggestParsable;
1130 typedef signed long long BiggestSignedParsable;
1131 const BiggestParsable kBiggestParsableMax =
1132 ::std::numeric_limits<BiggestParsable>::max();
1133 const BiggestSignedParsable kBiggestSignedParsableMax =
1134 ::std::numeric_limits<BiggestSignedParsable>::max();
1135 # endif // GTEST_OS_WINDOWS
1137 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
1138 BiggestParsable result = 0;
1140 // Rejects non-numbers.
1141 EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
1143 // Rejects numbers with whitespace prefix.
1144 EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
1146 // Rejects negative numbers.
1147 EXPECT_FALSE(ParseNaturalNumber("-123", &result));
1149 // Rejects numbers starting with a plus sign.
1150 EXPECT_FALSE(ParseNaturalNumber("+123", &result));
1154 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
1155 BiggestParsable result = 0;
1157 EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
1159 signed char char_result = 0;
1160 EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
1164 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
1165 BiggestParsable result = 0;
1168 ASSERT_TRUE(ParseNaturalNumber("123", &result));
1169 EXPECT_EQ(123U, result);
1171 // Check 0 as an edge case.
1173 ASSERT_TRUE(ParseNaturalNumber("0", &result));
1174 EXPECT_EQ(0U, result);
1177 ASSERT_TRUE(ParseNaturalNumber("00000", &result));
1178 EXPECT_EQ(0U, result);
1181 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
1183 msg << kBiggestParsableMax;
1185 BiggestParsable result = 0;
1186 EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
1187 EXPECT_EQ(kBiggestParsableMax, result);
1190 msg2 << kBiggestSignedParsableMax;
1192 BiggestSignedParsable signed_result = 0;
1193 EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
1194 EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
1200 EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
1201 EXPECT_EQ(INT_MAX, int_result);
1206 unsigned int uint_result = 0;
1207 EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
1208 EXPECT_EQ(UINT_MAX, uint_result);
1211 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
1212 short short_result = 0;
1213 ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
1214 EXPECT_EQ(123, short_result);
1216 signed char char_result = 0;
1217 ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
1218 EXPECT_EQ(123, char_result);
1221 # if GTEST_OS_WINDOWS
1222 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
1223 // TODO(vladl@google.com): Remove this test after this condition is verified
1224 // in a static assertion in gtest-death-test.cc in the function
1225 // GetStatusFileDescriptor.
1226 ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
1228 # endif // GTEST_OS_WINDOWS
1230 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
1231 // failures when death tests are available on the system.
1232 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
1233 EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
1234 "death inside CondDeathTestExpectMacro");
1235 ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
1236 "death inside CondDeathTestAssertMacro");
1238 // Empty statement will not crash, which must trigger a failure.
1239 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
1240 EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
1245 using testing::internal::CaptureStderr;
1246 using testing::internal::GetCapturedStderr;
1248 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
1249 // defined but do not trigger failures when death tests are not available on
1251 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
1252 // Empty statement will not crash, but that should not trigger a failure
1253 // when death tests are not supported.
1255 EXPECT_DEATH_IF_SUPPORTED(;, "");
1256 std::string output = GetCapturedStderr();
1257 ASSERT_TRUE(NULL != strstr(output.c_str(),
1258 "Death tests are not supported on this platform"));
1259 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1261 // The streamed message should not be printed as there is no test failure.
1263 EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
1264 output = GetCapturedStderr();
1265 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1268 ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
1269 output = GetCapturedStderr();
1270 ASSERT_TRUE(NULL != strstr(output.c_str(),
1271 "Death tests are not supported on this platform"));
1272 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1275 ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
1276 output = GetCapturedStderr();
1277 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1280 void FuncWithAssert(int* n) {
1281 ASSERT_DEATH_IF_SUPPORTED(return;, "");
1285 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
1286 // function (as ASSERT_DEATH does) if death tests are not supported.
1287 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
1292 #endif // GTEST_HAS_DEATH_TEST
1294 // Tests that the death test macros expand to code which may or may not
1295 // be followed by operator<<, and that in either case the complete text
1296 // comprises only a single C++ statement.
1298 // The syntax should work whether death tests are available or not.
1299 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
1301 // This would fail if executed; this is a compilation test only
1302 ASSERT_DEATH_IF_SUPPORTED(return, "");
1305 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
1307 // This empty "else" branch is meant to ensure that EXPECT_DEATH
1308 // doesn't expand into an "if" statement without an "else"
1312 ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
1317 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
1320 // Tests that conditional death test macros expand to code which interacts
1321 // well with switch statements.
1322 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
1323 // Microsoft compiler usually complains about switch statements without
1324 // case labels. We suppress that warning for this test.
1326 # pragma warning(push)
1327 # pragma warning(disable: 4065)
1332 ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
1333 << "exit in default switch handler";
1337 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
1340 # pragma warning(pop)
1344 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
1345 testing::GTEST_FLAG(death_test_style) = "fast";
1346 EXPECT_FALSE(InDeathTestChild());
1348 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1354 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
1355 testing::GTEST_FLAG(death_test_style) = "threadsafe";
1356 EXPECT_FALSE(InDeathTestChild());
1358 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1364 // Tests that a test case whose name ends with "DeathTest" works fine
1366 TEST(NotADeathTest, Test) {