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