/firmware/tests/gtest-1.4.0/test/gtest-death-test_test.cc

http://github.com/makerbot/G3Firmware · C++ · 1248 lines · 827 code · 191 blank · 230 comment · 34 complexity · c748fb168e12273f9bf80ad5a008232f MD5 · raw file

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