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 // 31 // Tests for death tests. 32 33 #include <stdlib.h> 34 35 #include "gtest/gtest-death-test.h" 36 #include "gtest/gtest.h" 37 #include "gtest/internal/gtest-filepath.h" 38 39 using testing::internal::AlwaysFalse; 40 using testing::internal::AlwaysTrue; 41 42 #ifdef GTEST_HAS_DEATH_TEST 43 44 #ifdef GTEST_OS_WINDOWS 45 #include <direct.h> // For chdir(). 46 #include <fcntl.h> // For O_BINARY 47 #include <io.h> 48 #else 49 #include <sys/wait.h> // For waitpid. 50 #include <unistd.h> 51 #endif // GTEST_OS_WINDOWS 52 53 #include <limits.h> 54 #include <signal.h> 55 #include <stdio.h> 56 57 #include <string> 58 #include <vector> 59 60 #ifdef GTEST_OS_LINUX 61 #include <sys/time.h> 62 #endif // GTEST_OS_LINUX 63 64 #include "gtest/gtest-spi.h" 65 #include "src/gtest-internal-inl.h" 66 67 namespace posix = ::testing::internal::posix; 68 69 using testing::ContainsRegex; 70 using testing::Matcher; 71 using testing::Message; 72 using testing::internal::DeathTest; 73 using testing::internal::DeathTestFactory; 74 using testing::internal::FilePath; 75 using testing::internal::GetLastErrnoDescription; 76 using testing::internal::GetUnitTestImpl; 77 using testing::internal::InDeathTestChild; 78 using testing::internal::ParseNaturalNumber; 79 80 namespace testing { 81 namespace internal { 82 83 // A helper class whose objects replace the death test factory for a 84 // single UnitTest object during their lifetimes. 85 class ReplaceDeathTestFactory { 86 public: 87 explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory) 88 : unit_test_impl_(GetUnitTestImpl()) { 89 old_factory_ = unit_test_impl_->death_test_factory_.release(); 90 unit_test_impl_->death_test_factory_.reset(new_factory); 91 } 92 93 ~ReplaceDeathTestFactory() { 94 unit_test_impl_->death_test_factory_.release(); 95 unit_test_impl_->death_test_factory_.reset(old_factory_); 96 } 97 98 private: 99 // Prevents copying ReplaceDeathTestFactory objects. 100 ReplaceDeathTestFactory(const ReplaceDeathTestFactory&); 101 void operator=(const ReplaceDeathTestFactory&); 102 103 UnitTestImpl* unit_test_impl_; 104 DeathTestFactory* old_factory_; 105 }; 106 107 } // namespace internal 108 } // namespace testing 109 110 namespace { 111 112 void DieWithMessage(const ::std::string& message) { 113 fprintf(stderr, "%s", message.c_str()); 114 fflush(stderr); // Make sure the text is printed before the process exits. 115 116 // We call _Exit() instead of exit(), as the former is a direct 117 // system call and thus safer in the presence of threads. exit() 118 // will invoke user-defined exit-hooks, which may do dangerous 119 // things that conflict with death tests. 120 // 121 // Some compilers can recognize that _Exit() never returns and issue the 122 // 'unreachable code' warning for code following this function, unless 123 // fooled by a fake condition. 124 if (AlwaysTrue()) _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 ~TestForDeathTest() override { posix::ChDir(original_dir_.c_str()); } 138 139 // A static member function that's expected to die. 140 static void StaticMemberFunction() { DieInside("StaticMemberFunction"); } 141 142 // A method of the test fixture that may die. 143 void MemberFunction() { 144 if (should_die_) DieInside("MemberFunction"); 145 } 146 147 // True if and only if MemberFunction() should die. 148 bool should_die_; 149 const FilePath original_dir_; 150 }; 151 152 // A class with a member function that may die. 153 class MayDie { 154 public: 155 explicit MayDie(bool should_die) : should_die_(should_die) {} 156 157 // A member function that may die. 158 void MemberFunction() const { 159 if (should_die_) DieInside("MayDie::MemberFunction"); 160 } 161 162 private: 163 // True if and only if MemberFunction() should die. 164 bool should_die_; 165 }; 166 167 // A global function that's expected to die. 168 void GlobalFunction() { DieInside("GlobalFunction"); } 169 170 // A non-void function that's expected to die. 171 int NonVoidFunction() { 172 DieInside("NonVoidFunction"); 173 return 1; 174 } 175 176 // A unary function that may die. 177 void DieIf(bool should_die) { 178 if (should_die) DieInside("DieIf"); 179 } 180 181 // A binary function that may die. 182 bool DieIfLessThan(int x, int y) { 183 if (x < y) { 184 DieInside("DieIfLessThan"); 185 } 186 return true; 187 } 188 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"); 193 } 194 195 // Death in dbg, not opt. 196 int DieInDebugElse12(int* sideeffect) { 197 if (sideeffect) *sideeffect = 12; 198 199 #ifndef NDEBUG 200 201 DieInside("DieInDebugElse12"); 202 203 #endif // NDEBUG 204 205 return 12; 206 } 207 208 #ifdef GTEST_OS_WINDOWS 209 210 // Death in dbg due to Windows CRT assertion failure, not opt. 211 int DieInCRTDebugElse12(int* sideeffect) { 212 if (sideeffect) *sideeffect = 12; 213 214 // Create an invalid fd by closing a valid one 215 int fdpipe[2]; 216 EXPECT_EQ(_pipe(fdpipe, 256, O_BINARY), 0); 217 EXPECT_EQ(_close(fdpipe[0]), 0); 218 EXPECT_EQ(_close(fdpipe[1]), 0); 219 220 // _dup() should crash in debug mode 221 EXPECT_EQ(_dup(fdpipe[0]), -1); 222 223 return 12; 224 } 225 226 #endif // GTEST_OS_WINDOWS 227 228 #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_FUCHSIA) 229 230 // Tests the ExitedWithCode predicate. 231 TEST(ExitStatusPredicateTest, ExitedWithCode) { 232 // On Windows, the process's exit code is the same as its exit status, 233 // so the predicate just compares the its input with its parameter. 234 EXPECT_TRUE(testing::ExitedWithCode(0)(0)); 235 EXPECT_TRUE(testing::ExitedWithCode(1)(1)); 236 EXPECT_TRUE(testing::ExitedWithCode(42)(42)); 237 EXPECT_FALSE(testing::ExitedWithCode(0)(1)); 238 EXPECT_FALSE(testing::ExitedWithCode(1)(0)); 239 } 240 241 #else 242 243 // Returns the exit status of a process that calls _Exit(2) with a 244 // given exit code. This is a helper function for the 245 // ExitStatusPredicateTest test suite. 246 static int NormalExitStatus(int exit_code) { 247 pid_t child_pid = fork(); 248 if (child_pid == 0) { 249 _Exit(exit_code); 250 } 251 int status; 252 waitpid(child_pid, &status, 0); 253 return status; 254 } 255 256 // Returns the exit status of a process that raises a given signal. 257 // If the signal does not cause the process to die, then it returns 258 // instead the exit status of a process that exits normally with exit 259 // code 1. This is a helper function for the ExitStatusPredicateTest 260 // test suite. 261 static int KilledExitStatus(int signum) { 262 pid_t child_pid = fork(); 263 if (child_pid == 0) { 264 raise(signum); 265 _Exit(1); 266 } 267 int status; 268 waitpid(child_pid, &status, 0); 269 return status; 270 } 271 272 // Tests the ExitedWithCode predicate. 273 TEST(ExitStatusPredicateTest, ExitedWithCode) { 274 const int status0 = NormalExitStatus(0); 275 const int status1 = NormalExitStatus(1); 276 const int status42 = NormalExitStatus(42); 277 const testing::ExitedWithCode pred0(0); 278 const testing::ExitedWithCode pred1(1); 279 const testing::ExitedWithCode pred42(42); 280 EXPECT_PRED1(pred0, status0); 281 EXPECT_PRED1(pred1, status1); 282 EXPECT_PRED1(pred42, status42); 283 EXPECT_FALSE(pred0(status1)); 284 EXPECT_FALSE(pred42(status0)); 285 EXPECT_FALSE(pred1(status42)); 286 } 287 288 // Tests the KilledBySignal predicate. 289 TEST(ExitStatusPredicateTest, KilledBySignal) { 290 const int status_segv = KilledExitStatus(SIGSEGV); 291 const int status_kill = KilledExitStatus(SIGKILL); 292 const testing::KilledBySignal pred_segv(SIGSEGV); 293 const testing::KilledBySignal pred_kill(SIGKILL); 294 #if !(defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ <= 21) 295 EXPECT_PRED1(pred_segv, status_segv); 296 #endif 297 EXPECT_PRED1(pred_kill, status_kill); 298 EXPECT_FALSE(pred_segv(status_kill)); 299 EXPECT_FALSE(pred_kill(status_segv)); 300 } 301 302 #endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA 303 304 // The following code intentionally tests a suboptimal syntax. 305 #ifdef __GNUC__ 306 #pragma GCC diagnostic push 307 #pragma GCC diagnostic ignored "-Wdangling-else" 308 #pragma GCC diagnostic ignored "-Wempty-body" 309 #pragma GCC diagnostic ignored "-Wpragmas" 310 #endif 311 // Tests that the death test macros expand to code which may or may not 312 // be followed by operator<<, and that in either case the complete text 313 // comprises only a single C++ statement. 314 TEST_F(TestForDeathTest, SingleStatement) { 315 if (AlwaysFalse()) 316 // This would fail if executed; this is a compilation test only 317 ASSERT_DEATH(return, ""); 318 319 if (AlwaysTrue()) 320 EXPECT_DEATH(_Exit(1), ""); 321 else 322 // This empty "else" branch is meant to ensure that EXPECT_DEATH 323 // doesn't expand into an "if" statement without an "else" 324 ; 325 326 if (AlwaysFalse()) ASSERT_DEATH(return, "") << "did not die"; 327 328 if (AlwaysFalse()) 329 ; 330 else 331 EXPECT_DEATH(_Exit(1), "") << 1 << 2 << 3; 332 } 333 #ifdef __GNUC__ 334 #pragma GCC diagnostic pop 335 #endif 336 337 // Tests that death test macros expand to code which interacts well with switch 338 // statements. 339 TEST_F(TestForDeathTest, SwitchStatement) { 340 // Microsoft compiler usually complains about switch statements without 341 // case labels. We suppress that warning for this test. 342 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) 343 344 switch (0) 345 default: 346 ASSERT_DEATH(_Exit(1), "") << "exit in default switch handler"; 347 348 switch (0) 349 case 0: 350 EXPECT_DEATH(_Exit(1), "") << "exit in switch case"; 351 352 GTEST_DISABLE_MSC_WARNINGS_POP_() 353 } 354 355 // Tests that a static member function can be used in a "fast" style 356 // death test. 357 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) { 358 GTEST_FLAG_SET(death_test_style, "fast"); 359 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); 360 } 361 362 // Tests that a method of the test fixture can be used in a "fast" 363 // style death test. 364 TEST_F(TestForDeathTest, MemberFunctionFastStyle) { 365 GTEST_FLAG_SET(death_test_style, "fast"); 366 should_die_ = true; 367 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); 368 } 369 370 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); } 371 372 // Tests that death tests work even if the current directory has been 373 // changed. 374 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) { 375 GTEST_FLAG_SET(death_test_style, "fast"); 376 377 ChangeToRootDir(); 378 EXPECT_EXIT(_Exit(1), testing::ExitedWithCode(1), ""); 379 380 ChangeToRootDir(); 381 ASSERT_DEATH(_Exit(1), ""); 382 } 383 384 #ifdef GTEST_OS_LINUX 385 void SigprofAction(int, siginfo_t*, void*) { /* no op */ 386 } 387 388 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms). 389 void SetSigprofActionAndTimer() { 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, nullptr)); 396 // timer comes second, to avoid SIGPROF premature delivery, as suggested at 397 // https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html 398 struct itimerval timer; 399 timer.it_interval.tv_sec = 0; 400 timer.it_interval.tv_usec = 1; 401 timer.it_value = timer.it_interval; 402 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr)); 403 } 404 405 // Disables ITIMER_PROF timer and ignores SIGPROF signal. 406 void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) { 407 struct itimerval timer; 408 timer.it_interval.tv_sec = 0; 409 timer.it_interval.tv_usec = 0; 410 timer.it_value = timer.it_interval; 411 ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr)); 412 struct sigaction signal_action; 413 memset(&signal_action, 0, sizeof(signal_action)); 414 sigemptyset(&signal_action.sa_mask); 415 signal_action.sa_handler = SIG_IGN; 416 ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action)); 417 } 418 419 // Tests that death tests work when SIGPROF handler and timer are set. 420 TEST_F(TestForDeathTest, FastSigprofActionSet) { 421 GTEST_FLAG_SET(death_test_style, "fast"); 422 SetSigprofActionAndTimer(); 423 EXPECT_DEATH(_Exit(1), ""); 424 struct sigaction old_signal_action; 425 DisableSigprofActionAndTimer(&old_signal_action); 426 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); 427 } 428 429 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) { 430 GTEST_FLAG_SET(death_test_style, "threadsafe"); 431 SetSigprofActionAndTimer(); 432 EXPECT_DEATH(_Exit(1), ""); 433 struct sigaction old_signal_action; 434 DisableSigprofActionAndTimer(&old_signal_action); 435 EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction); 436 } 437 #endif // GTEST_OS_LINUX 438 439 // Repeats a representative sample of death tests in the "threadsafe" style: 440 441 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) { 442 GTEST_FLAG_SET(death_test_style, "threadsafe"); 443 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember"); 444 } 445 446 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) { 447 GTEST_FLAG_SET(death_test_style, "threadsafe"); 448 should_die_ = true; 449 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction"); 450 } 451 452 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) { 453 GTEST_FLAG_SET(death_test_style, "threadsafe"); 454 455 for (int i = 0; i < 3; ++i) 456 EXPECT_EXIT(_Exit(i), testing::ExitedWithCode(i), "") << ": i = " << i; 457 } 458 459 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) { 460 GTEST_FLAG_SET(death_test_style, "threadsafe"); 461 462 ChangeToRootDir(); 463 EXPECT_EXIT(_Exit(1), testing::ExitedWithCode(1), ""); 464 465 ChangeToRootDir(); 466 ASSERT_DEATH(_Exit(1), ""); 467 } 468 469 TEST_F(TestForDeathTest, MixedStyles) { 470 GTEST_FLAG_SET(death_test_style, "threadsafe"); 471 EXPECT_DEATH(_Exit(1), ""); 472 GTEST_FLAG_SET(death_test_style, "fast"); 473 EXPECT_DEATH(_Exit(1), ""); 474 } 475 476 #if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD 477 478 bool pthread_flag; 479 480 void SetPthreadFlag() { pthread_flag = true; } 481 482 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) { 483 if (!GTEST_FLAG_GET(death_test_use_fork)) { 484 GTEST_FLAG_SET(death_test_style, "threadsafe"); 485 pthread_flag = false; 486 ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr)); 487 ASSERT_DEATH(_Exit(1), ""); 488 ASSERT_FALSE(pthread_flag); 489 } 490 } 491 492 #endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD 493 494 // Tests that a method of another class can be used in a death test. 495 TEST_F(TestForDeathTest, MethodOfAnotherClass) { 496 const MayDie x(true); 497 ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction"); 498 } 499 500 // Tests that a global function can be used in a death test. 501 TEST_F(TestForDeathTest, GlobalFunction) { 502 EXPECT_DEATH(GlobalFunction(), "GlobalFunction"); 503 } 504 505 // Tests that any value convertible to an RE works as a second 506 // argument to EXPECT_DEATH. 507 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) { 508 static const char regex_c_str[] = "GlobalFunction"; 509 EXPECT_DEATH(GlobalFunction(), regex_c_str); 510 511 const testing::internal::RE regex(regex_c_str); 512 EXPECT_DEATH(GlobalFunction(), regex); 513 514 const ::std::string regex_std_str(regex_c_str); 515 EXPECT_DEATH(GlobalFunction(), regex_std_str); 516 517 // This one is tricky; a temporary pointer into another temporary. Reference 518 // lifetime extension of the pointer is not sufficient. 519 EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str()); 520 } 521 522 // Tests that a non-void function can be used in a death test. 523 TEST_F(TestForDeathTest, NonVoidFunction) { 524 ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction"); 525 } 526 527 // Tests that functions that take parameter(s) can be used in a death test. 528 TEST_F(TestForDeathTest, FunctionWithParameter) { 529 EXPECT_DEATH(DieIf(true), "DieIf\\(\\)"); 530 EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan"); 531 } 532 533 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture. 534 TEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); } 535 536 // Tests that death tests can be done inside a loop. 537 TEST_F(TestForDeathTest, InsideLoop) { 538 for (int i = 0; i < 5; i++) { 539 EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i; 540 } 541 } 542 543 // Tests that a compound statement can be used in a death test. 544 TEST_F(TestForDeathTest, CompoundStatement) { 545 EXPECT_DEATH( 546 { // NOLINT 547 const int x = 2; 548 const int y = x + 1; 549 DieIfLessThan(x, y); 550 }, 551 "DieIfLessThan"); 552 } 553 554 // Tests that code that doesn't die causes a death test to fail. 555 TEST_F(TestForDeathTest, DoesNotDie) { 556 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"), "failed to die"); 557 } 558 559 // Tests that a death test fails when the error message isn't expected. 560 TEST_F(TestForDeathTest, ErrorMessageMismatch) { 561 EXPECT_NONFATAL_FAILURE( 562 { // NOLINT 563 EXPECT_DEATH(DieIf(true), "DieIfLessThan") 564 << "End of death test message."; 565 }, 566 "died but not with expected error"); 567 } 568 569 // On exit, *aborted will be true if and only if the EXPECT_DEATH() 570 // statement aborted the function. 571 void ExpectDeathTestHelper(bool* aborted) { 572 *aborted = true; 573 EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. 574 *aborted = false; 575 } 576 577 // Tests that EXPECT_DEATH doesn't abort the test on failure. 578 TEST_F(TestForDeathTest, EXPECT_DEATH) { 579 bool aborted = true; 580 EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), "failed to die"); 581 EXPECT_FALSE(aborted); 582 } 583 584 // Tests that ASSERT_DEATH does abort the test on failure. 585 TEST_F(TestForDeathTest, ASSERT_DEATH) { 586 static bool aborted; 587 EXPECT_FATAL_FAILURE( 588 { // NOLINT 589 aborted = true; 590 ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail. 591 aborted = false; 592 }, 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 // Put the regex in a local variable to make sure we don't get an "unused" 632 // warning in opt mode. 633 const char* regex = "death.*DieInDebugElse12"; 634 635 EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex) 636 << "Must accept a streamed message"; 637 638 #ifdef NDEBUG 639 640 // Checks that the assignment occurs in opt mode (sideeffect). 641 EXPECT_EQ(12, sideeffect); 642 643 #else 644 645 // Checks that the assignment does not occur in dbg mode (no sideeffect). 646 EXPECT_EQ(0, sideeffect); 647 648 #endif 649 } 650 651 #ifdef GTEST_OS_WINDOWS 652 653 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode 654 // In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable 655 // the dumping of assertions to stderr. Tests that EXPECT_DEATH works as 656 // expected when in CRT debug mode (compiled with /MTd or /MDd, which defines 657 // _DEBUG) the Windows CRT crashes the process with an assertion failure. 658 // 1. Asserts on death. 659 // 2. Has no side effect (doesn't pop up a window or wait for user input). 660 #ifdef _DEBUG 661 TEST_F(TestForDeathTest, CRTDebugDeath) { 662 EXPECT_DEATH(DieInCRTDebugElse12(nullptr), "dup.* : Assertion failed") 663 << "Must accept a streamed message"; 664 } 665 #endif // _DEBUG 666 667 #endif // GTEST_OS_WINDOWS 668 669 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a 670 // message to it, and in debug mode it: 671 // 1. Asserts on death. 672 // 2. Has no side effect. 673 // 674 // And in opt mode, it: 675 // 1. Has side effects but does not assert. 676 TEST_F(TestForDeathTest, TestAssertDebugDeath) { 677 int sideeffect = 0; 678 679 ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12") 680 << "Must accept a streamed message"; 681 682 #ifdef NDEBUG 683 684 // Checks that the assignment occurs in opt mode (sideeffect). 685 EXPECT_EQ(12, sideeffect); 686 687 #else 688 689 // Checks that the assignment does not occur in dbg mode (no sideeffect). 690 EXPECT_EQ(0, sideeffect); 691 692 #endif 693 } 694 695 #ifndef NDEBUG 696 697 void ExpectDebugDeathHelper(bool* aborted) { 698 *aborted = true; 699 EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail."; 700 *aborted = false; 701 } 702 703 #ifdef GTEST_OS_WINDOWS 704 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) { 705 printf( 706 "This test should be considered failing if it shows " 707 "any pop-up dialogs.\n"); 708 fflush(stdout); 709 710 EXPECT_DEATH( 711 { 712 GTEST_FLAG_SET(catch_exceptions, false); 713 abort(); 714 }, 715 ""); 716 } 717 #endif // GTEST_OS_WINDOWS 718 719 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort 720 // the function. 721 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) { 722 bool aborted = true; 723 EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), ""); 724 EXPECT_FALSE(aborted); 725 } 726 727 void AssertDebugDeathHelper(bool* aborted) { 728 *aborted = true; 729 GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH"; 730 ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "") 731 << "This is expected to fail."; 732 GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH"; 733 *aborted = false; 734 } 735 736 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on 737 // failure. 738 TEST_F(TestForDeathTest, AssertDebugDeathAborts) { 739 static bool aborted; 740 aborted = false; 741 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 742 EXPECT_TRUE(aborted); 743 } 744 745 TEST_F(TestForDeathTest, AssertDebugDeathAborts2) { 746 static bool aborted; 747 aborted = false; 748 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 749 EXPECT_TRUE(aborted); 750 } 751 752 TEST_F(TestForDeathTest, AssertDebugDeathAborts3) { 753 static bool aborted; 754 aborted = false; 755 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 756 EXPECT_TRUE(aborted); 757 } 758 759 TEST_F(TestForDeathTest, AssertDebugDeathAborts4) { 760 static bool aborted; 761 aborted = false; 762 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 763 EXPECT_TRUE(aborted); 764 } 765 766 TEST_F(TestForDeathTest, AssertDebugDeathAborts5) { 767 static bool aborted; 768 aborted = false; 769 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 770 EXPECT_TRUE(aborted); 771 } 772 773 TEST_F(TestForDeathTest, AssertDebugDeathAborts6) { 774 static bool aborted; 775 aborted = false; 776 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 777 EXPECT_TRUE(aborted); 778 } 779 780 TEST_F(TestForDeathTest, AssertDebugDeathAborts7) { 781 static bool aborted; 782 aborted = false; 783 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 784 EXPECT_TRUE(aborted); 785 } 786 787 TEST_F(TestForDeathTest, AssertDebugDeathAborts8) { 788 static bool aborted; 789 aborted = false; 790 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 791 EXPECT_TRUE(aborted); 792 } 793 794 TEST_F(TestForDeathTest, AssertDebugDeathAborts9) { 795 static bool aborted; 796 aborted = false; 797 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 798 EXPECT_TRUE(aborted); 799 } 800 801 TEST_F(TestForDeathTest, AssertDebugDeathAborts10) { 802 static bool aborted; 803 aborted = false; 804 EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), ""); 805 EXPECT_TRUE(aborted); 806 } 807 808 #endif // _NDEBUG 809 810 // Tests the *_EXIT family of macros, using a variety of predicates. 811 static void TestExitMacros() { 812 EXPECT_EXIT(_Exit(1), testing::ExitedWithCode(1), ""); 813 ASSERT_EXIT(_Exit(42), testing::ExitedWithCode(42), ""); 814 815 #ifdef GTEST_OS_WINDOWS 816 817 // Of all signals effects on the process exit code, only those of SIGABRT 818 // are documented on Windows. 819 // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. 820 EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; 821 822 #elif !defined(GTEST_OS_FUCHSIA) 823 824 // Fuchsia has no unix signals. 825 EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo"; 826 ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar"; 827 828 EXPECT_FATAL_FAILURE( 829 { // NOLINT 830 ASSERT_EXIT(_Exit(0), testing::KilledBySignal(SIGSEGV), "") 831 << "This failure is expected, too."; 832 }, 833 "This failure is expected, too."); 834 835 #endif // GTEST_OS_WINDOWS 836 837 EXPECT_NONFATAL_FAILURE( 838 { // NOLINT 839 EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "") 840 << "This failure is expected."; 841 }, 842 "This failure is expected."); 843 } 844 845 TEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); } 846 847 TEST_F(TestForDeathTest, ExitMacrosUsingFork) { 848 GTEST_FLAG_SET(death_test_use_fork, true); 849 TestExitMacros(); 850 } 851 852 TEST_F(TestForDeathTest, InvalidStyle) { 853 GTEST_FLAG_SET(death_test_style, "rococo"); 854 EXPECT_NONFATAL_FAILURE( 855 { // NOLINT 856 EXPECT_DEATH(_Exit(0), "") << "This failure is expected."; 857 }, 858 "This failure is expected."); 859 } 860 861 TEST_F(TestForDeathTest, DeathTestFailedOutput) { 862 GTEST_FLAG_SET(death_test_style, "fast"); 863 EXPECT_NONFATAL_FAILURE( 864 EXPECT_DEATH(DieWithMessage("death\n"), "expected message"), 865 "Actual msg:\n" 866 "[ DEATH ] death\n"); 867 } 868 869 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) { 870 GTEST_FLAG_SET(death_test_style, "fast"); 871 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH( 872 { 873 fprintf(stderr, "returning\n"); 874 fflush(stderr); 875 return; 876 }, 877 ""), 878 " Result: illegal return in test statement.\n" 879 " Error msg:\n" 880 "[ DEATH ] returning\n"); 881 } 882 883 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) { 884 GTEST_FLAG_SET(death_test_style, "fast"); 885 EXPECT_NONFATAL_FAILURE( 886 EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"), 887 testing::ExitedWithCode(3), "expected message"), 888 " Result: died but not with expected exit code:\n" 889 " Exited with exit status 1\n" 890 "Actual msg:\n" 891 "[ DEATH ] exiting with rc 1\n"); 892 } 893 894 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) { 895 GTEST_FLAG_SET(death_test_style, "fast"); 896 EXPECT_NONFATAL_FAILURE( 897 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), 898 "line 1\nxyz\nline 3\n"), 899 "Actual msg:\n" 900 "[ DEATH ] line 1\n" 901 "[ DEATH ] line 2\n" 902 "[ DEATH ] line 3\n"); 903 } 904 905 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) { 906 GTEST_FLAG_SET(death_test_style, "fast"); 907 EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"), 908 "line 1\nline 2\nline 3\n"); 909 } 910 911 // A DeathTestFactory that returns MockDeathTests. 912 class MockDeathTestFactory : public DeathTestFactory { 913 public: 914 MockDeathTestFactory(); 915 bool Create(const char* statement, 916 testing::Matcher<const std::string&> matcher, const char* file, 917 int line, DeathTest** test) override; 918 919 // Sets the parameters for subsequent calls to Create. 920 void SetParameters(bool create, DeathTest::TestRole role, int status, 921 bool passed); 922 923 // Accessors. 924 int AssumeRoleCalls() const { return assume_role_calls_; } 925 int WaitCalls() const { return wait_calls_; } 926 size_t PassedCalls() const { return passed_args_.size(); } 927 bool PassedArgument(int n) const { 928 return passed_args_[static_cast<size_t>(n)]; 929 } 930 size_t AbortCalls() const { return abort_args_.size(); } 931 DeathTest::AbortReason AbortArgument(int n) const { 932 return abort_args_[static_cast<size_t>(n)]; 933 } 934 bool TestDeleted() const { return test_deleted_; } 935 936 private: 937 friend class MockDeathTest; 938 // If true, Create will return a MockDeathTest; otherwise it returns 939 // NULL. 940 bool create_; 941 // The value a MockDeathTest will return from its AssumeRole method. 942 DeathTest::TestRole role_; 943 // The value a MockDeathTest will return from its Wait method. 944 int status_; 945 // The value a MockDeathTest will return from its Passed method. 946 bool passed_; 947 948 // Number of times AssumeRole was called. 949 int assume_role_calls_; 950 // Number of times Wait was called. 951 int wait_calls_; 952 // The arguments to the calls to Passed since the last call to 953 // SetParameters. 954 std::vector<bool> passed_args_; 955 // The arguments to the calls to Abort since the last call to 956 // SetParameters. 957 std::vector<DeathTest::AbortReason> abort_args_; 958 // True if the last MockDeathTest returned by Create has been 959 // deleted. 960 bool test_deleted_; 961 }; 962 963 // A DeathTest implementation useful in testing. It returns values set 964 // at its creation from its various inherited DeathTest methods, and 965 // reports calls to those methods to its parent MockDeathTestFactory 966 // object. 967 class MockDeathTest : public DeathTest { 968 public: 969 MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status, 970 bool passed) 971 : parent_(parent), role_(role), status_(status), passed_(passed) {} 972 ~MockDeathTest() override { parent_->test_deleted_ = true; } 973 TestRole AssumeRole() override { 974 ++parent_->assume_role_calls_; 975 return role_; 976 } 977 int Wait() override { 978 ++parent_->wait_calls_; 979 return status_; 980 } 981 bool Passed(bool exit_status_ok) override { 982 parent_->passed_args_.push_back(exit_status_ok); 983 return passed_; 984 } 985 void Abort(AbortReason reason) override { 986 parent_->abort_args_.push_back(reason); 987 } 988 989 private: 990 MockDeathTestFactory* const parent_; 991 const TestRole role_; 992 const int status_; 993 const bool passed_; 994 }; 995 996 // MockDeathTestFactory constructor. 997 MockDeathTestFactory::MockDeathTestFactory() 998 : create_(true), 999 role_(DeathTest::OVERSEE_TEST), 1000 status_(0), 1001 passed_(true), 1002 assume_role_calls_(0), 1003 wait_calls_(0), 1004 passed_args_(), 1005 abort_args_() {} 1006 1007 // Sets the parameters for subsequent calls to Create. 1008 void MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role, 1009 int status, bool passed) { 1010 create_ = create; 1011 role_ = role; 1012 status_ = status; 1013 passed_ = passed; 1014 1015 assume_role_calls_ = 0; 1016 wait_calls_ = 0; 1017 passed_args_.clear(); 1018 abort_args_.clear(); 1019 } 1020 1021 // Sets test to NULL (if create_ is false) or to the address of a new 1022 // MockDeathTest object with parameters taken from the last call 1023 // to SetParameters (if create_ is true). Always returns true. 1024 bool MockDeathTestFactory::Create( 1025 const char* /*statement*/, testing::Matcher<const std::string&> /*matcher*/, 1026 const char* /*file*/, int /*line*/, DeathTest** test) { 1027 test_deleted_ = false; 1028 if (create_) { 1029 *test = new MockDeathTest(this, role_, status_, passed_); 1030 } else { 1031 *test = nullptr; 1032 } 1033 return true; 1034 } 1035 1036 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro. 1037 // It installs a MockDeathTestFactory that is used for the duration 1038 // of the test case. 1039 class MacroLogicDeathTest : public testing::Test { 1040 protected: 1041 static testing::internal::ReplaceDeathTestFactory* replacer_; 1042 static MockDeathTestFactory* factory_; 1043 1044 static void SetUpTestSuite() { 1045 factory_ = new MockDeathTestFactory; 1046 replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_); 1047 } 1048 1049 static void TearDownTestSuite() { 1050 delete replacer_; 1051 replacer_ = nullptr; 1052 delete factory_; 1053 factory_ = nullptr; 1054 } 1055 1056 // Runs a death test that breaks the rules by returning. Such a death 1057 // test cannot be run directly from a test routine that uses a 1058 // MockDeathTest, or the remainder of the routine will not be executed. 1059 static void RunReturningDeathTest(bool* flag) { 1060 ASSERT_DEATH( 1061 { // NOLINT 1062 *flag = true; 1063 return; 1064 }, 1065 ""); 1066 } 1067 }; 1068 1069 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ = 1070 nullptr; 1071 MockDeathTestFactory* MacroLogicDeathTest::factory_ = nullptr; 1072 1073 // Test that nothing happens when the factory doesn't return a DeathTest: 1074 TEST_F(MacroLogicDeathTest, NothingHappens) { 1075 bool flag = false; 1076 factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true); 1077 EXPECT_DEATH(flag = true, ""); 1078 EXPECT_FALSE(flag); 1079 EXPECT_EQ(0, factory_->AssumeRoleCalls()); 1080 EXPECT_EQ(0, factory_->WaitCalls()); 1081 EXPECT_EQ(0U, factory_->PassedCalls()); 1082 EXPECT_EQ(0U, factory_->AbortCalls()); 1083 EXPECT_FALSE(factory_->TestDeleted()); 1084 } 1085 1086 // Test that the parent process doesn't run the death test code, 1087 // and that the Passed method returns false when the (simulated) 1088 // child process exits with status 0: 1089 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) { 1090 bool flag = false; 1091 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true); 1092 EXPECT_DEATH(flag = true, ""); 1093 EXPECT_FALSE(flag); 1094 EXPECT_EQ(1, factory_->AssumeRoleCalls()); 1095 EXPECT_EQ(1, factory_->WaitCalls()); 1096 ASSERT_EQ(1U, factory_->PassedCalls()); 1097 EXPECT_FALSE(factory_->PassedArgument(0)); 1098 EXPECT_EQ(0U, factory_->AbortCalls()); 1099 EXPECT_TRUE(factory_->TestDeleted()); 1100 } 1101 1102 // Tests that the Passed method was given the argument "true" when 1103 // the (simulated) child process exits with status 1: 1104 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) { 1105 bool flag = false; 1106 factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true); 1107 EXPECT_DEATH(flag = true, ""); 1108 EXPECT_FALSE(flag); 1109 EXPECT_EQ(1, factory_->AssumeRoleCalls()); 1110 EXPECT_EQ(1, factory_->WaitCalls()); 1111 ASSERT_EQ(1U, factory_->PassedCalls()); 1112 EXPECT_TRUE(factory_->PassedArgument(0)); 1113 EXPECT_EQ(0U, factory_->AbortCalls()); 1114 EXPECT_TRUE(factory_->TestDeleted()); 1115 } 1116 1117 // Tests that the (simulated) child process executes the death test 1118 // code, and is aborted with the correct AbortReason if it 1119 // executes a return statement. 1120 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) { 1121 bool flag = false; 1122 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true); 1123 RunReturningDeathTest(&flag); 1124 EXPECT_TRUE(flag); 1125 EXPECT_EQ(1, factory_->AssumeRoleCalls()); 1126 EXPECT_EQ(0, factory_->WaitCalls()); 1127 EXPECT_EQ(0U, factory_->PassedCalls()); 1128 EXPECT_EQ(1U, factory_->AbortCalls()); 1129 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, 1130 factory_->AbortArgument(0)); 1131 EXPECT_TRUE(factory_->TestDeleted()); 1132 } 1133 1134 // Tests that the (simulated) child process is aborted with the 1135 // correct AbortReason if it does not die. 1136 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) { 1137 bool flag = false; 1138 factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true); 1139 EXPECT_DEATH(flag = true, ""); 1140 EXPECT_TRUE(flag); 1141 EXPECT_EQ(1, factory_->AssumeRoleCalls()); 1142 EXPECT_EQ(0, factory_->WaitCalls()); 1143 EXPECT_EQ(0U, factory_->PassedCalls()); 1144 // This time there are two calls to Abort: one since the test didn't 1145 // die, and another from the ReturnSentinel when it's destroyed. The 1146 // sentinel normally isn't destroyed if a test doesn't die, since 1147 // _Exit(2) is called in that case by ForkingDeathTest, but not by 1148 // our MockDeathTest. 1149 ASSERT_EQ(2U, factory_->AbortCalls()); 1150 EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0)); 1151 EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT, 1152 factory_->AbortArgument(1)); 1153 EXPECT_TRUE(factory_->TestDeleted()); 1154 } 1155 1156 // Tests that a successful death test does not register a successful 1157 // test part. 1158 TEST(SuccessRegistrationDeathTest, NoSuccessPart) { 1159 EXPECT_DEATH(_Exit(1), ""); 1160 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); 1161 } 1162 1163 TEST(StreamingAssertionsDeathTest, DeathTest) { 1164 EXPECT_DEATH(_Exit(1), "") << "unexpected failure"; 1165 ASSERT_DEATH(_Exit(1), "") << "unexpected failure"; 1166 EXPECT_NONFATAL_FAILURE( 1167 { // NOLINT 1168 EXPECT_DEATH(_Exit(0), "") << "expected failure"; 1169 }, 1170 "expected failure"); 1171 EXPECT_FATAL_FAILURE( 1172 { // NOLINT 1173 ASSERT_DEATH(_Exit(0), "") << "expected failure"; 1174 }, 1175 "expected failure"); 1176 } 1177 1178 // Tests that GetLastErrnoDescription returns an empty string when the 1179 // last error is 0 and non-empty string when it is non-zero. 1180 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) { 1181 errno = ENOENT; 1182 EXPECT_STRNE("", GetLastErrnoDescription().c_str()); 1183 errno = 0; 1184 EXPECT_STREQ("", GetLastErrnoDescription().c_str()); 1185 } 1186 1187 #ifdef GTEST_OS_WINDOWS 1188 TEST(AutoHandleTest, AutoHandleWorks) { 1189 HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); 1190 ASSERT_NE(INVALID_HANDLE_VALUE, handle); 1191 1192 // Tests that the AutoHandle is correctly initialized with a handle. 1193 testing::internal::AutoHandle auto_handle(handle); 1194 EXPECT_EQ(handle, auto_handle.Get()); 1195 1196 // Tests that Reset assigns INVALID_HANDLE_VALUE. 1197 // Note that this cannot verify whether the original handle is closed. 1198 auto_handle.Reset(); 1199 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get()); 1200 1201 // Tests that Reset assigns the new handle. 1202 // Note that this cannot verify whether the original handle is closed. 1203 handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); 1204 ASSERT_NE(INVALID_HANDLE_VALUE, handle); 1205 auto_handle.Reset(handle); 1206 EXPECT_EQ(handle, auto_handle.Get()); 1207 1208 // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default. 1209 testing::internal::AutoHandle auto_handle2; 1210 EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get()); 1211 } 1212 #endif // GTEST_OS_WINDOWS 1213 1214 #ifdef GTEST_OS_WINDOWS 1215 typedef unsigned __int64 BiggestParsable; 1216 typedef signed __int64 BiggestSignedParsable; 1217 #else 1218 typedef unsigned long long BiggestParsable; 1219 typedef signed long long BiggestSignedParsable; 1220 #endif // GTEST_OS_WINDOWS 1221 1222 // We cannot use std::numeric_limits<T>::max() as it clashes with the 1223 // max() macro defined by <windows.h>. 1224 const BiggestParsable kBiggestParsableMax = ULLONG_MAX; 1225 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX; 1226 1227 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) { 1228 BiggestParsable result = 0; 1229 1230 // Rejects non-numbers. 1231 EXPECT_FALSE(ParseNaturalNumber("non-number string", &result)); 1232 1233 // Rejects numbers with whitespace prefix. 1234 EXPECT_FALSE(ParseNaturalNumber(" 123", &result)); 1235 1236 // Rejects negative numbers. 1237 EXPECT_FALSE(ParseNaturalNumber("-123", &result)); 1238 1239 // Rejects numbers starting with a plus sign. 1240 EXPECT_FALSE(ParseNaturalNumber("+123", &result)); 1241 errno = 0; 1242 } 1243 1244 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) { 1245 BiggestParsable result = 0; 1246 1247 EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result)); 1248 1249 signed char char_result = 0; 1250 EXPECT_FALSE(ParseNaturalNumber("200", &char_result)); 1251 errno = 0; 1252 } 1253 1254 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) { 1255 BiggestParsable result = 0; 1256 1257 result = 0; 1258 ASSERT_TRUE(ParseNaturalNumber("123", &result)); 1259 EXPECT_EQ(123U, result); 1260 1261 // Check 0 as an edge case. 1262 result = 1; 1263 ASSERT_TRUE(ParseNaturalNumber("0", &result)); 1264 EXPECT_EQ(0U, result); 1265 1266 result = 1; 1267 ASSERT_TRUE(ParseNaturalNumber("00000", &result)); 1268 EXPECT_EQ(0U, result); 1269 } 1270 1271 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) { 1272 Message msg; 1273 msg << kBiggestParsableMax; 1274 1275 BiggestParsable result = 0; 1276 EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result)); 1277 EXPECT_EQ(kBiggestParsableMax, result); 1278 1279 Message msg2; 1280 msg2 << kBiggestSignedParsableMax; 1281 1282 BiggestSignedParsable signed_result = 0; 1283 EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result)); 1284 EXPECT_EQ(kBiggestSignedParsableMax, signed_result); 1285 1286 Message msg3; 1287 msg3 << INT_MAX; 1288 1289 int int_result = 0; 1290 EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result)); 1291 EXPECT_EQ(INT_MAX, int_result); 1292 1293 Message msg4; 1294 msg4 << UINT_MAX; 1295 1296 unsigned int uint_result = 0; 1297 EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result)); 1298 EXPECT_EQ(UINT_MAX, uint_result); 1299 } 1300 1301 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) { 1302 short short_result = 0; 1303 ASSERT_TRUE(ParseNaturalNumber("123", &short_result)); 1304 EXPECT_EQ(123, short_result); 1305 1306 signed char char_result = 0; 1307 ASSERT_TRUE(ParseNaturalNumber("123", &char_result)); 1308 EXPECT_EQ(123, char_result); 1309 } 1310 1311 #ifdef GTEST_OS_WINDOWS 1312 TEST(EnvironmentTest, HandleFitsIntoSizeT) { 1313 ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t)); 1314 } 1315 #endif // GTEST_OS_WINDOWS 1316 1317 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger 1318 // failures when death tests are available on the system. 1319 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) { 1320 EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"), 1321 "death inside CondDeathTestExpectMacro"); 1322 ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"), 1323 "death inside CondDeathTestAssertMacro"); 1324 1325 // Empty statement will not crash, which must trigger a failure. 1326 EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), ""); 1327 EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), ""); 1328 } 1329 1330 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) { 1331 GTEST_FLAG_SET(death_test_style, "fast"); 1332 EXPECT_FALSE(InDeathTestChild()); 1333 EXPECT_DEATH( 1334 { 1335 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); 1336 fflush(stderr); 1337 _Exit(1); 1338 }, 1339 "Inside"); 1340 } 1341 1342 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) { 1343 GTEST_FLAG_SET(death_test_style, "threadsafe"); 1344 EXPECT_FALSE(InDeathTestChild()); 1345 EXPECT_DEATH( 1346 { 1347 fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside"); 1348 fflush(stderr); 1349 _Exit(1); 1350 }, 1351 "Inside"); 1352 } 1353 1354 void DieWithMessage(const char* message) { 1355 fputs(message, stderr); 1356 fflush(stderr); // Make sure the text is printed before the process exits. 1357 _Exit(1); 1358 } 1359 1360 TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) { 1361 // googletest tests this, of course; here we ensure that including googlemock 1362 // has not broken it. 1363 #ifdef GTEST_USES_POSIX_RE 1364 EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e"); 1365 #else 1366 EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I di?e"); 1367 #endif 1368 } 1369 1370 TEST(MatcherDeathTest, MonomorphicMatcherMatches) { 1371 EXPECT_DEATH(DieWithMessage("Behind O, I am slain!"), 1372 Matcher<const std::string&>(ContainsRegex("I am slain"))); 1373 } 1374 1375 TEST(MatcherDeathTest, MonomorphicMatcherDoesNotMatch) { 1376 EXPECT_NONFATAL_FAILURE( 1377 EXPECT_DEATH( 1378 DieWithMessage("Behind O, I am slain!"), 1379 Matcher<const std::string&>(ContainsRegex("Ow, I am slain"))), 1380 "Expected: contains regular expression \"Ow, I am slain\""); 1381 } 1382 1383 TEST(MatcherDeathTest, PolymorphicMatcherMatches) { 1384 EXPECT_DEATH(DieWithMessage("The rest is silence."), 1385 ContainsRegex("rest is silence")); 1386 } 1387 1388 TEST(MatcherDeathTest, PolymorphicMatcherDoesNotMatch) { 1389 EXPECT_NONFATAL_FAILURE( 1390 EXPECT_DEATH(DieWithMessage("The rest is silence."), 1391 ContainsRegex("rest is science")), 1392 "Expected: contains regular expression \"rest is science\""); 1393 } 1394 1395 } // namespace 1396 1397 #else // !GTEST_HAS_DEATH_TEST follows 1398 1399 namespace { 1400 1401 using testing::internal::CaptureStderr; 1402 using testing::internal::GetCapturedStderr; 1403 1404 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still 1405 // defined but do not trigger failures when death tests are not available on 1406 // the system. 1407 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) { 1408 // Empty statement will not crash, but that should not trigger a failure 1409 // when death tests are not supported. 1410 CaptureStderr(); 1411 EXPECT_DEATH_IF_SUPPORTED(;, ""); 1412 std::string output = GetCapturedStderr(); 1413 ASSERT_TRUE(NULL != strstr(output.c_str(), 1414 "Death tests are not supported on this platform")); 1415 ASSERT_TRUE(NULL != strstr(output.c_str(), ";")); 1416 1417 // The streamed message should not be printed as there is no test failure. 1418 CaptureStderr(); 1419 EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; 1420 output = GetCapturedStderr(); 1421 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message")); 1422 1423 CaptureStderr(); 1424 ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT 1425 output = GetCapturedStderr(); 1426 ASSERT_TRUE(NULL != strstr(output.c_str(), 1427 "Death tests are not supported on this platform")); 1428 ASSERT_TRUE(NULL != strstr(output.c_str(), ";")); 1429 1430 CaptureStderr(); 1431 ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT 1432 output = GetCapturedStderr(); 1433 ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message")); 1434 } 1435 1436 void FuncWithAssert(int* n) { 1437 ASSERT_DEATH_IF_SUPPORTED(return;, ""); 1438 (*n)++; 1439 } 1440 1441 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current 1442 // function (as ASSERT_DEATH does) if death tests are not supported. 1443 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) { 1444 int n = 0; 1445 FuncWithAssert(&n); 1446 EXPECT_EQ(1, n); 1447 } 1448 1449 } // namespace 1450 1451 #endif // !GTEST_HAS_DEATH_TEST 1452 1453 namespace { 1454 1455 // The following code intentionally tests a suboptimal syntax. 1456 #ifdef __GNUC__ 1457 #pragma GCC diagnostic push 1458 #pragma GCC diagnostic ignored "-Wdangling-else" 1459 #pragma GCC diagnostic ignored "-Wempty-body" 1460 #pragma GCC diagnostic ignored "-Wpragmas" 1461 #endif 1462 // Tests that the death test macros expand to code which may or may not 1463 // be followed by operator<<, and that in either case the complete text 1464 // comprises only a single C++ statement. 1465 // 1466 // The syntax should work whether death tests are available or not. 1467 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) { 1468 if (AlwaysFalse()) 1469 // This would fail if executed; this is a compilation test only 1470 ASSERT_DEATH_IF_SUPPORTED(return, ""); 1471 1472 if (AlwaysTrue()) 1473 EXPECT_DEATH_IF_SUPPORTED(_Exit(1), ""); 1474 else 1475 // This empty "else" branch is meant to ensure that EXPECT_DEATH 1476 // doesn't expand into an "if" statement without an "else" 1477 ; // NOLINT 1478 1479 if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die"; 1480 1481 if (AlwaysFalse()) 1482 ; // NOLINT 1483 else 1484 EXPECT_DEATH_IF_SUPPORTED(_Exit(1), "") << 1 << 2 << 3; 1485 } 1486 #ifdef __GNUC__ 1487 #pragma GCC diagnostic pop 1488 #endif 1489 1490 // Tests that conditional death test macros expand to code which interacts 1491 // well with switch statements. 1492 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) { 1493 // Microsoft compiler usually complains about switch statements without 1494 // case labels. We suppress that warning for this test. 1495 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065) 1496 1497 switch (0) 1498 default: 1499 ASSERT_DEATH_IF_SUPPORTED(_Exit(1), "") << "exit in default switch handler"; 1500 1501 switch (0) 1502 case 0: 1503 EXPECT_DEATH_IF_SUPPORTED(_Exit(1), "") << "exit in switch case"; 1504 1505 GTEST_DISABLE_MSC_WARNINGS_POP_() 1506 } 1507 1508 // Tests that a test case whose name ends with "DeathTest" works fine 1509 // on Windows. 1510 TEST(NotADeathTest, Test) { SUCCEED(); } 1511 1512 } // namespace 1513