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
55 # include "gtest/gtest-spi.h"
57 // Indicates that this translation unit is part of Google Test's
58 // implementation. It must come before gtest-internal-inl.h is
59 // included, or there will be a compiler error. This trick is to
60 // prevent a user from accidentally including gtest-internal-inl.h in
62 # define GTEST_IMPLEMENTATION_ 1
63 # include "src/gtest-internal-inl.h"
64 # undef GTEST_IMPLEMENTATION_
66 namespace posix = ::testing::internal::posix;
68 using testing::Message;
69 using testing::internal::DeathTest;
70 using testing::internal::DeathTestFactory;
71 using testing::internal::FilePath;
72 using testing::internal::GetLastErrnoDescription;
73 using testing::internal::GetUnitTestImpl;
74 using testing::internal::ParseNaturalNumber;
75 using testing::internal::String;
80 // A helper class whose objects replace the death test factory for a
81 // single UnitTest object during their lifetimes.
82 class ReplaceDeathTestFactory {
84 explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
85 : unit_test_impl_(GetUnitTestImpl()) {
86 old_factory_ = unit_test_impl_->death_test_factory_.release();
87 unit_test_impl_->death_test_factory_.reset(new_factory);
90 ~ReplaceDeathTestFactory() {
91 unit_test_impl_->death_test_factory_.release();
92 unit_test_impl_->death_test_factory_.reset(old_factory_);
95 // Prevents copying ReplaceDeathTestFactory objects.
96 ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
97 void operator=(const ReplaceDeathTestFactory&);
99 UnitTestImpl* unit_test_impl_;
100 DeathTestFactory* old_factory_;
103 } // namespace internal
104 } // namespace testing
106 void DieWithMessage(const ::std::string& message) {
107 fprintf(stderr, "%s", message.c_str());
108 fflush(stderr); // Make sure the text is printed before the process exits.
110 // We call _exit() instead of exit(), as the former is a direct
111 // system call and thus safer in the presence of threads. exit()
112 // will invoke user-defined exit-hooks, which may do dangerous
113 // things that conflict with death tests.
115 // Some compilers can recognize that _exit() never returns and issue the
116 // 'unreachable code' warning for code following this function, unless
117 // fooled by a fake condition.
122 void DieInside(const ::std::string& function) {
123 DieWithMessage("death inside " + function + "().");
126 // Tests that death tests work.
128 class TestForDeathTest : public testing::Test {
130 TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
132 virtual ~TestForDeathTest() {
133 posix::ChDir(original_dir_.c_str());
136 // A static member function that's expected to die.
137 static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
139 // A method of the test fixture that may die.
140 void MemberFunction() {
142 DieInside("MemberFunction");
145 // True iff 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 {
158 DieInside("MayDie::MemberFunction");
162 // True iff MemberFunction() should die.
166 // A global function that's expected to die.
167 void GlobalFunction() { DieInside("GlobalFunction"); }
169 // A non-void function that's expected to die.
170 int NonVoidFunction() {
171 DieInside("NonVoidFunction");
175 // A unary function that may die.
176 void DieIf(bool should_die) {
181 // A binary function that may die.
182 bool DieIfLessThan(int x, int y) {
184 DieInside("DieIfLessThan");
189 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
190 void DeathTestSubroutine() {
191 EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
192 ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
195 // Death in dbg, not opt.
196 int DieInDebugElse12(int* sideeffect) {
197 if (sideeffect) *sideeffect = 12;
201 DieInside("DieInDebugElse12");
208 # if GTEST_OS_WINDOWS
210 // Tests the ExitedWithCode predicate.
211 TEST(ExitStatusPredicateTest, ExitedWithCode) {
212 // On Windows, the process's exit code is the same as its exit status,
213 // so the predicate just compares the its input with its parameter.
214 EXPECT_TRUE(testing::ExitedWithCode(0)(0));
215 EXPECT_TRUE(testing::ExitedWithCode(1)(1));
216 EXPECT_TRUE(testing::ExitedWithCode(42)(42));
217 EXPECT_FALSE(testing::ExitedWithCode(0)(1));
218 EXPECT_FALSE(testing::ExitedWithCode(1)(0));
223 // Returns the exit status of a process that calls _exit(2) with a
224 // given exit code. This is a helper function for the
225 // ExitStatusPredicateTest test suite.
226 static int NormalExitStatus(int exit_code) {
227 pid_t child_pid = fork();
228 if (child_pid == 0) {
232 waitpid(child_pid, &status, 0);
236 // Returns the exit status of a process that raises a given signal.
237 // If the signal does not cause the process to die, then it returns
238 // instead the exit status of a process that exits normally with exit
239 // code 1. This is a helper function for the ExitStatusPredicateTest
241 static int KilledExitStatus(int signum) {
242 pid_t child_pid = fork();
243 if (child_pid == 0) {
248 waitpid(child_pid, &status, 0);
252 // Tests the ExitedWithCode predicate.
253 TEST(ExitStatusPredicateTest, ExitedWithCode) {
254 const int status0 = NormalExitStatus(0);
255 const int status1 = NormalExitStatus(1);
256 const int status42 = NormalExitStatus(42);
257 const testing::ExitedWithCode pred0(0);
258 const testing::ExitedWithCode pred1(1);
259 const testing::ExitedWithCode pred42(42);
260 EXPECT_PRED1(pred0, status0);
261 EXPECT_PRED1(pred1, status1);
262 EXPECT_PRED1(pred42, status42);
263 EXPECT_FALSE(pred0(status1));
264 EXPECT_FALSE(pred42(status0));
265 EXPECT_FALSE(pred1(status42));
268 // Tests the KilledBySignal predicate.
269 TEST(ExitStatusPredicateTest, KilledBySignal) {
270 const int status_segv = KilledExitStatus(SIGSEGV);
271 const int status_kill = KilledExitStatus(SIGKILL);
272 const testing::KilledBySignal pred_segv(SIGSEGV);
273 const testing::KilledBySignal pred_kill(SIGKILL);
274 EXPECT_PRED1(pred_segv, status_segv);
275 EXPECT_PRED1(pred_kill, status_kill);
276 EXPECT_FALSE(pred_segv(status_kill));
277 EXPECT_FALSE(pred_kill(status_segv));
280 # endif // GTEST_OS_WINDOWS
282 // Tests that the death test macros expand to code which may or may not
283 // be followed by operator<<, and that in either case the complete text
284 // comprises only a single C++ statement.
285 TEST_F(TestForDeathTest, SingleStatement) {
287 // This would fail if executed; this is a compilation test only
288 ASSERT_DEATH(return, "");
291 EXPECT_DEATH(_exit(1), "");
293 // This empty "else" branch is meant to ensure that EXPECT_DEATH
294 // doesn't expand into an "if" statement without an "else"
298 ASSERT_DEATH(return, "") << "did not die";
303 EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
306 void DieWithEmbeddedNul() {
307 fprintf(stderr, "Hello%cmy null world.\n", '\0');
313 // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
314 // message has a NUL character in it.
315 TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
316 // TODO(wan@google.com): <regex.h> doesn't support matching strings
317 // with embedded NUL characters - find a way to workaround it.
318 EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
319 ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
321 # endif // GTEST_USES_PCRE
323 // Tests that death test macros expand to code which interacts well with switch
325 TEST_F(TestForDeathTest, SwitchStatement) {
326 // Microsoft compiler usually complains about switch statements without
327 // case labels. We suppress that warning for this test.
329 # pragma warning(push)
330 # pragma warning(disable: 4065)
335 ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
339 EXPECT_DEATH(_exit(1), "") << "exit in switch case";
342 # pragma warning(pop)
346 // Tests that a static member function can be used in a "fast" style
348 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
349 testing::GTEST_FLAG(death_test_style) = "fast";
350 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
353 // Tests that a method of the test fixture can be used in a "fast"
355 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
356 testing::GTEST_FLAG(death_test_style) = "fast";
358 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
361 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
363 // Tests that death tests work even if the current directory has been
365 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
366 testing::GTEST_FLAG(death_test_style) = "fast";
369 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
372 ASSERT_DEATH(_exit(1), "");
375 // Repeats a representative sample of death tests in the "threadsafe" style:
377 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
378 testing::GTEST_FLAG(death_test_style) = "threadsafe";
379 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
382 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
383 testing::GTEST_FLAG(death_test_style) = "threadsafe";
385 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
388 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
389 testing::GTEST_FLAG(death_test_style) = "threadsafe";
391 for (int i = 0; i < 3; ++i)
392 EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
395 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
396 testing::GTEST_FLAG(death_test_style) = "threadsafe";
399 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
402 ASSERT_DEATH(_exit(1), "");
405 TEST_F(TestForDeathTest, MixedStyles) {
406 testing::GTEST_FLAG(death_test_style) = "threadsafe";
407 EXPECT_DEATH(_exit(1), "");
408 testing::GTEST_FLAG(death_test_style) = "fast";
409 EXPECT_DEATH(_exit(1), "");
416 void SetPthreadFlag() {
422 # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
424 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
425 if (!testing::GTEST_FLAG(death_test_use_fork)) {
426 testing::GTEST_FLAG(death_test_style) = "threadsafe";
427 pthread_flag = false;
428 ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
429 ASSERT_DEATH(_exit(1), "");
430 ASSERT_FALSE(pthread_flag);
434 # endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
436 // Tests that a method of another class can be used in a death test.
437 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
438 const MayDie x(true);
439 ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
442 // Tests that a global function can be used in a death test.
443 TEST_F(TestForDeathTest, GlobalFunction) {
444 EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
447 // Tests that any value convertible to an RE works as a second
448 // argument to EXPECT_DEATH.
449 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
450 static const char regex_c_str[] = "GlobalFunction";
451 EXPECT_DEATH(GlobalFunction(), regex_c_str);
453 const testing::internal::RE regex(regex_c_str);
454 EXPECT_DEATH(GlobalFunction(), regex);
456 # if GTEST_HAS_GLOBAL_STRING
458 const string regex_str(regex_c_str);
459 EXPECT_DEATH(GlobalFunction(), regex_str);
461 # endif // GTEST_HAS_GLOBAL_STRING
463 const ::std::string regex_std_str(regex_c_str);
464 EXPECT_DEATH(GlobalFunction(), regex_std_str);
467 // Tests that a non-void function can be used in a death test.
468 TEST_F(TestForDeathTest, NonVoidFunction) {
469 ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
472 // Tests that functions that take parameter(s) can be used in a death test.
473 TEST_F(TestForDeathTest, FunctionWithParameter) {
474 EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
475 EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
478 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
479 TEST_F(TestForDeathTest, OutsideFixture) {
480 DeathTestSubroutine();
483 // Tests that death tests can be done inside a loop.
484 TEST_F(TestForDeathTest, InsideLoop) {
485 for (int i = 0; i < 5; i++) {
486 EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
490 // Tests that a compound statement can be used in a death test.
491 TEST_F(TestForDeathTest, CompoundStatement) {
492 EXPECT_DEATH({ // NOLINT
500 // Tests that code that doesn't die causes a death test to fail.
501 TEST_F(TestForDeathTest, DoesNotDie) {
502 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
506 // Tests that a death test fails when the error message isn't expected.
507 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
508 EXPECT_NONFATAL_FAILURE({ // NOLINT
509 EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
510 }, "died but not with expected error");
513 // On exit, *aborted will be true iff the EXPECT_DEATH() statement
514 // aborted the function.
515 void ExpectDeathTestHelper(bool* aborted) {
517 EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
521 // Tests that EXPECT_DEATH doesn't abort the test on failure.
522 TEST_F(TestForDeathTest, EXPECT_DEATH) {
524 EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
526 EXPECT_FALSE(aborted);
529 // Tests that ASSERT_DEATH does abort the test on failure.
530 TEST_F(TestForDeathTest, ASSERT_DEATH) {
532 EXPECT_FATAL_FAILURE({ // NOLINT
534 ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
537 EXPECT_TRUE(aborted);
540 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
541 TEST_F(TestForDeathTest, SingleEvaluation) {
543 EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
545 const char* regex = "DieIf";
546 const char* regex_save = regex;
547 EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
548 EXPECT_EQ(regex_save + 1, regex);
551 // Tests that run-away death tests are reported as failures.
552 TEST_F(TestForDeathTest, RunawayIsFailure) {
553 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
557 // Tests that death tests report executing 'return' in the statement as
559 TEST_F(TestForDeathTest, ReturnIsFailure) {
560 EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
561 "illegal return in test statement.");
564 // Tests that EXPECT_DEBUG_DEATH works as expected,
565 // that is, in debug mode, it:
566 // 1. Asserts on death.
567 // 2. Has no side effect.
569 // And in opt mode, it:
570 // 1. Has side effects but does not assert.
571 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
574 EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect),
575 "death.*DieInDebugElse12");
579 // Checks that the assignment occurs in opt mode (sideeffect).
580 EXPECT_EQ(12, sideeffect);
584 // Checks that the assignment does not occur in dbg mode (no sideeffect).
585 EXPECT_EQ(0, sideeffect);
590 // Tests that ASSERT_DEBUG_DEATH works as expected
592 // 1. Asserts on debug death.
593 // 2. Has no side effect.
596 // 1. Has side effects and returns the expected value (12).
597 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
600 ASSERT_DEBUG_DEATH({ // NOLINT
601 // Tests that the return value is 12 in opt mode.
602 EXPECT_EQ(12, DieInDebugElse12(&sideeffect));
603 // Tests that the side effect occurred in opt mode.
604 EXPECT_EQ(12, sideeffect);
605 }, "death.*DieInDebugElse12");
609 // Checks that the assignment occurs in opt mode (sideeffect).
610 EXPECT_EQ(12, sideeffect);
614 // Checks that the assignment does not occur in dbg mode (no sideeffect).
615 EXPECT_EQ(0, sideeffect);
622 void ExpectDebugDeathHelper(bool* aborted) {
624 EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
628 # if GTEST_OS_WINDOWS
629 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
630 printf("This test should be considered failing if it shows "
631 "any pop-up dialogs.\n");
635 testing::GTEST_FLAG(catch_exceptions) = false;
639 # endif // GTEST_OS_WINDOWS
641 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
643 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
645 EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
646 EXPECT_FALSE(aborted);
649 void AssertDebugDeathHelper(bool* aborted) {
651 ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
655 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
657 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
660 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
661 EXPECT_TRUE(aborted);
666 // Tests the *_EXIT family of macros, using a variety of predicates.
667 static void TestExitMacros() {
668 EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
669 ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
671 # if GTEST_OS_WINDOWS
673 // Of all signals effects on the process exit code, only those of SIGABRT
674 // are documented on Windows.
675 // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
676 EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "");
680 EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
681 ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
683 EXPECT_FATAL_FAILURE({ // NOLINT
684 ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
685 << "This failure is expected, too.";
686 }, "This failure is expected, too.");
688 # endif // GTEST_OS_WINDOWS
690 EXPECT_NONFATAL_FAILURE({ // NOLINT
691 EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
692 << "This failure is expected.";
693 }, "This failure is expected.");
696 TEST_F(TestForDeathTest, ExitMacros) {
700 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
701 testing::GTEST_FLAG(death_test_use_fork) = true;
705 TEST_F(TestForDeathTest, InvalidStyle) {
706 testing::GTEST_FLAG(death_test_style) = "rococo";
707 EXPECT_NONFATAL_FAILURE({ // NOLINT
708 EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
709 }, "This failure is expected.");
712 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
713 testing::GTEST_FLAG(death_test_style) = "fast";
714 EXPECT_NONFATAL_FAILURE(
715 EXPECT_DEATH(DieWithMessage("death\n"),
718 "[ DEATH ] death\n");
721 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
722 testing::GTEST_FLAG(death_test_style) = "fast";
723 EXPECT_NONFATAL_FAILURE(
725 fprintf(stderr, "returning\n");
729 " Result: illegal return in test statement.\n"
731 "[ DEATH ] returning\n");
734 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
735 testing::GTEST_FLAG(death_test_style) = "fast";
736 EXPECT_NONFATAL_FAILURE(
737 EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
738 testing::ExitedWithCode(3),
740 " Result: died but not with expected exit code:\n"
741 " Exited with exit status 1\n"
743 "[ DEATH ] exiting with rc 1\n");
746 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
747 testing::GTEST_FLAG(death_test_style) = "fast";
748 EXPECT_NONFATAL_FAILURE(
749 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
750 "line 1\nxyz\nline 3\n"),
754 "[ DEATH ] line 3\n");
757 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
758 testing::GTEST_FLAG(death_test_style) = "fast";
759 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
760 "line 1\nline 2\nline 3\n");
763 // A DeathTestFactory that returns MockDeathTests.
764 class MockDeathTestFactory : public DeathTestFactory {
766 MockDeathTestFactory();
767 virtual bool Create(const char* statement,
768 const ::testing::internal::RE* regex,
769 const char* file, int line, DeathTest** test);
771 // Sets the parameters for subsequent calls to Create.
772 void SetParameters(bool create, DeathTest::TestRole role,
773 int status, bool passed);
776 int AssumeRoleCalls() const { return assume_role_calls_; }
777 int WaitCalls() const { return wait_calls_; }
778 int PassedCalls() const { return passed_args_.size(); }
779 bool PassedArgument(int n) const { return passed_args_[n]; }
780 int AbortCalls() const { return abort_args_.size(); }
781 DeathTest::AbortReason AbortArgument(int n) const {
782 return abort_args_[n];
784 bool TestDeleted() const { return test_deleted_; }
787 friend class MockDeathTest;
788 // If true, Create will return a MockDeathTest; otherwise it returns
791 // The value a MockDeathTest will return from its AssumeRole method.
792 DeathTest::TestRole role_;
793 // The value a MockDeathTest will return from its Wait method.
795 // The value a MockDeathTest will return from its Passed method.
798 // Number of times AssumeRole was called.
799 int assume_role_calls_;
800 // Number of times Wait was called.
802 // The arguments to the calls to Passed since the last call to
804 std::vector<bool> passed_args_;
805 // The arguments to the calls to Abort since the last call to
807 std::vector<DeathTest::AbortReason> abort_args_;
808 // True if the last MockDeathTest returned by Create has been
814 // A DeathTest implementation useful in testing. It returns values set
815 // at its creation from its various inherited DeathTest methods, and
816 // reports calls to those methods to its parent MockDeathTestFactory
818 class MockDeathTest : public DeathTest {
820 MockDeathTest(MockDeathTestFactory *parent,
821 TestRole role, int status, bool passed) :
822 parent_(parent), role_(role), status_(status), passed_(passed) {
824 virtual ~MockDeathTest() {
825 parent_->test_deleted_ = true;
827 virtual TestRole AssumeRole() {
828 ++parent_->assume_role_calls_;
832 ++parent_->wait_calls_;
835 virtual bool Passed(bool exit_status_ok) {
836 parent_->passed_args_.push_back(exit_status_ok);
839 virtual void Abort(AbortReason reason) {
840 parent_->abort_args_.push_back(reason);
843 MockDeathTestFactory* const parent_;
844 const TestRole role_;
850 // MockDeathTestFactory constructor.
851 MockDeathTestFactory::MockDeathTestFactory()
853 role_(DeathTest::OVERSEE_TEST),
856 assume_role_calls_(0),
863 // Sets the parameters for subsequent calls to Create.
864 void MockDeathTestFactory::SetParameters(bool create,
865 DeathTest::TestRole role,
866 int status, bool passed) {
872 assume_role_calls_ = 0;
874 passed_args_.clear();
879 // Sets test to NULL (if create_ is false) or to the address of a new
880 // MockDeathTest object with parameters taken from the last call
881 // to SetParameters (if create_ is true). Always returns true.
882 bool MockDeathTestFactory::Create(const char* /*statement*/,
883 const ::testing::internal::RE* /*regex*/,
884 const char* /*file*/,
887 test_deleted_ = false;
889 *test = new MockDeathTest(this, role_, status_, passed_);
896 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
897 // It installs a MockDeathTestFactory that is used for the duration
899 class MacroLogicDeathTest : public testing::Test {
901 static testing::internal::ReplaceDeathTestFactory* replacer_;
902 static MockDeathTestFactory* factory_;
904 static void SetUpTestCase() {
905 factory_ = new MockDeathTestFactory;
906 replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
909 static void TearDownTestCase() {
916 // Runs a death test that breaks the rules by returning. Such a death
917 // test cannot be run directly from a test routine that uses a
918 // MockDeathTest, or the remainder of the routine will not be executed.
919 static void RunReturningDeathTest(bool* flag) {
920 ASSERT_DEATH({ // NOLINT
927 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
929 MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
932 // Test that nothing happens when the factory doesn't return a DeathTest:
933 TEST_F(MacroLogicDeathTest, NothingHappens) {
935 factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
936 EXPECT_DEATH(flag = true, "");
938 EXPECT_EQ(0, factory_->AssumeRoleCalls());
939 EXPECT_EQ(0, factory_->WaitCalls());
940 EXPECT_EQ(0, factory_->PassedCalls());
941 EXPECT_EQ(0, factory_->AbortCalls());
942 EXPECT_FALSE(factory_->TestDeleted());
945 // Test that the parent process doesn't run the death test code,
946 // and that the Passed method returns false when the (simulated)
947 // child process exits with status 0:
948 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
950 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
951 EXPECT_DEATH(flag = true, "");
953 EXPECT_EQ(1, factory_->AssumeRoleCalls());
954 EXPECT_EQ(1, factory_->WaitCalls());
955 ASSERT_EQ(1, factory_->PassedCalls());
956 EXPECT_FALSE(factory_->PassedArgument(0));
957 EXPECT_EQ(0, factory_->AbortCalls());
958 EXPECT_TRUE(factory_->TestDeleted());
961 // Tests that the Passed method was given the argument "true" when
962 // the (simulated) child process exits with status 1:
963 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
965 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
966 EXPECT_DEATH(flag = true, "");
968 EXPECT_EQ(1, factory_->AssumeRoleCalls());
969 EXPECT_EQ(1, factory_->WaitCalls());
970 ASSERT_EQ(1, factory_->PassedCalls());
971 EXPECT_TRUE(factory_->PassedArgument(0));
972 EXPECT_EQ(0, factory_->AbortCalls());
973 EXPECT_TRUE(factory_->TestDeleted());
976 // Tests that the (simulated) child process executes the death test
977 // code, and is aborted with the correct AbortReason if it
978 // executes a return statement.
979 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
981 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
982 RunReturningDeathTest(&flag);
984 EXPECT_EQ(1, factory_->AssumeRoleCalls());
985 EXPECT_EQ(0, factory_->WaitCalls());
986 EXPECT_EQ(0, factory_->PassedCalls());
987 EXPECT_EQ(1, factory_->AbortCalls());
988 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
989 factory_->AbortArgument(0));
990 EXPECT_TRUE(factory_->TestDeleted());
993 // Tests that the (simulated) child process is aborted with the
994 // correct AbortReason if it does not die.
995 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
997 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
998 EXPECT_DEATH(flag = true, "");
1000 EXPECT_EQ(1, factory_->AssumeRoleCalls());
1001 EXPECT_EQ(0, factory_->WaitCalls());
1002 EXPECT_EQ(0, factory_->PassedCalls());
1003 // This time there are two calls to Abort: one since the test didn't
1004 // die, and another from the ReturnSentinel when it's destroyed. The
1005 // sentinel normally isn't destroyed if a test doesn't die, since
1006 // _exit(2) is called in that case by ForkingDeathTest, but not by
1007 // our MockDeathTest.
1008 ASSERT_EQ(2, factory_->AbortCalls());
1009 EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
1010 factory_->AbortArgument(0));
1011 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1012 factory_->AbortArgument(1));
1013 EXPECT_TRUE(factory_->TestDeleted());
1016 // Tests that a successful death test does not register a successful
1018 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1019 EXPECT_DEATH(_exit(1), "");
1020 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
1023 TEST(StreamingAssertionsDeathTest, DeathTest) {
1024 EXPECT_DEATH(_exit(1), "") << "unexpected failure";
1025 ASSERT_DEATH(_exit(1), "") << "unexpected failure";
1026 EXPECT_NONFATAL_FAILURE({ // NOLINT
1027 EXPECT_DEATH(_exit(0), "") << "expected failure";
1028 }, "expected failure");
1029 EXPECT_FATAL_FAILURE({ // NOLINT
1030 ASSERT_DEATH(_exit(0), "") << "expected failure";
1031 }, "expected failure");
1034 // Tests that GetLastErrnoDescription returns an empty string when the
1035 // last error is 0 and non-empty string when it is non-zero.
1036 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
1038 EXPECT_STRNE("", GetLastErrnoDescription().c_str());
1040 EXPECT_STREQ("", GetLastErrnoDescription().c_str());
1043 # if GTEST_OS_WINDOWS
1044 TEST(AutoHandleTest, AutoHandleWorks) {
1045 HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1046 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1048 // Tests that the AutoHandle is correctly initialized with a handle.
1049 testing::internal::AutoHandle auto_handle(handle);
1050 EXPECT_EQ(handle, auto_handle.Get());
1052 // Tests that Reset assigns INVALID_HANDLE_VALUE.
1053 // Note that this cannot verify whether the original handle is closed.
1054 auto_handle.Reset();
1055 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
1057 // Tests that Reset assigns the new handle.
1058 // Note that this cannot verify whether the original handle is closed.
1059 handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1060 ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1061 auto_handle.Reset(handle);
1062 EXPECT_EQ(handle, auto_handle.Get());
1064 // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
1065 testing::internal::AutoHandle auto_handle2;
1066 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
1068 # endif // GTEST_OS_WINDOWS
1070 # if GTEST_OS_WINDOWS
1071 typedef unsigned __int64 BiggestParsable;
1072 typedef signed __int64 BiggestSignedParsable;
1073 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1074 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
1076 typedef unsigned long long BiggestParsable;
1077 typedef signed long long BiggestSignedParsable;
1078 const BiggestParsable kBiggestParsableMax =
1079 ::std::numeric_limits<BiggestParsable>::max();
1080 const BiggestSignedParsable kBiggestSignedParsableMax =
1081 ::std::numeric_limits<BiggestSignedParsable>::max();
1082 # endif // GTEST_OS_WINDOWS
1084 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
1085 BiggestParsable result = 0;
1087 // Rejects non-numbers.
1088 EXPECT_FALSE(ParseNaturalNumber(String("non-number string"), &result));
1090 // Rejects numbers with whitespace prefix.
1091 EXPECT_FALSE(ParseNaturalNumber(String(" 123"), &result));
1093 // Rejects negative numbers.
1094 EXPECT_FALSE(ParseNaturalNumber(String("-123"), &result));
1096 // Rejects numbers starting with a plus sign.
1097 EXPECT_FALSE(ParseNaturalNumber(String("+123"), &result));
1101 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
1102 BiggestParsable result = 0;
1104 EXPECT_FALSE(ParseNaturalNumber(String("99999999999999999999999"), &result));
1106 signed char char_result = 0;
1107 EXPECT_FALSE(ParseNaturalNumber(String("200"), &char_result));
1111 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
1112 BiggestParsable result = 0;
1115 ASSERT_TRUE(ParseNaturalNumber(String("123"), &result));
1116 EXPECT_EQ(123U, result);
1118 // Check 0 as an edge case.
1120 ASSERT_TRUE(ParseNaturalNumber(String("0"), &result));
1121 EXPECT_EQ(0U, result);
1124 ASSERT_TRUE(ParseNaturalNumber(String("00000"), &result));
1125 EXPECT_EQ(0U, result);
1128 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
1130 msg << kBiggestParsableMax;
1132 BiggestParsable result = 0;
1133 EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
1134 EXPECT_EQ(kBiggestParsableMax, result);
1137 msg2 << kBiggestSignedParsableMax;
1139 BiggestSignedParsable signed_result = 0;
1140 EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
1141 EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
1147 EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
1148 EXPECT_EQ(INT_MAX, int_result);
1153 unsigned int uint_result = 0;
1154 EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
1155 EXPECT_EQ(UINT_MAX, uint_result);
1158 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
1159 short short_result = 0;
1160 ASSERT_TRUE(ParseNaturalNumber(String("123"), &short_result));
1161 EXPECT_EQ(123, short_result);
1163 signed char char_result = 0;
1164 ASSERT_TRUE(ParseNaturalNumber(String("123"), &char_result));
1165 EXPECT_EQ(123, char_result);
1168 # if GTEST_OS_WINDOWS
1169 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
1170 // TODO(vladl@google.com): Remove this test after this condition is verified
1171 // in a static assertion in gtest-death-test.cc in the function
1172 // GetStatusFileDescriptor.
1173 ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
1175 # endif // GTEST_OS_WINDOWS
1177 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
1178 // failures when death tests are available on the system.
1179 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
1180 EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
1181 "death inside CondDeathTestExpectMacro");
1182 ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
1183 "death inside CondDeathTestAssertMacro");
1185 // Empty statement will not crash, which must trigger a failure.
1186 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
1187 EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
1192 using testing::internal::CaptureStderr;
1193 using testing::internal::GetCapturedStderr;
1194 using testing::internal::String;
1196 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
1197 // defined but do not trigger failures when death tests are not available on
1199 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
1200 // Empty statement will not crash, but that should not trigger a failure
1201 // when death tests are not supported.
1203 EXPECT_DEATH_IF_SUPPORTED(;, "");
1204 String output = GetCapturedStderr();
1205 ASSERT_TRUE(NULL != strstr(output.c_str(),
1206 "Death tests are not supported on this platform"));
1207 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1209 // The streamed message should not be printed as there is no test failure.
1211 EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
1212 output = GetCapturedStderr();
1213 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1216 ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
1217 output = GetCapturedStderr();
1218 ASSERT_TRUE(NULL != strstr(output.c_str(),
1219 "Death tests are not supported on this platform"));
1220 ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1223 ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
1224 output = GetCapturedStderr();
1225 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1228 void FuncWithAssert(int* n) {
1229 ASSERT_DEATH_IF_SUPPORTED(return;, "");
1233 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
1234 // function (as ASSERT_DEATH does) if death tests are not supported.
1235 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
1240 #endif // GTEST_HAS_DEATH_TEST
1242 // Tests that the death test macros expand to code which may or may not
1243 // be followed by operator<<, and that in either case the complete text
1244 // comprises only a single C++ statement.
1246 // The syntax should work whether death tests are available or not.
1247 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
1249 // This would fail if executed; this is a compilation test only
1250 ASSERT_DEATH_IF_SUPPORTED(return, "");
1253 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
1255 // This empty "else" branch is meant to ensure that EXPECT_DEATH
1256 // doesn't expand into an "if" statement without an "else"
1260 ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
1265 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
1268 // Tests that conditional death test macros expand to code which interacts
1269 // well with switch statements.
1270 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
1271 // Microsoft compiler usually complains about switch statements without
1272 // case labels. We suppress that warning for this test.
1274 # pragma warning(push)
1275 # pragma warning(disable: 4065)
1280 ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
1281 << "exit in default switch handler";
1285 EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
1288 # pragma warning(pop)
1292 // Tests that a test case whose name ends with "DeathTest" works fine
1294 TEST(NotADeathTest, Test) {