media/webrtc/trunk/testing/gtest/test/gtest-death-test_test.cc

Wed, 31 Dec 2014 07:53:36 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 07:53:36 +0100
branch
TOR_BUG_3246
changeset 5
4ab42b5ab56c
permissions
-rw-r--r--

Correct small whitespace inconsistency, lost while renaming variables.

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

mercurial