You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1296 lines
40 KiB

  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. void DieWithMessage(const ::std::string& message) {
  92. fprintf(stderr, "%s", message.c_str());
  93. fflush(stderr); // Make sure the text is printed before the process exits.
  94. // We call _exit() instead of exit(), as the former is a direct
  95. // system call and thus safer in the presence of threads. exit()
  96. // will invoke user-defined exit-hooks, which may do dangerous
  97. // things that conflict with death tests.
  98. //
  99. // Some compilers can recognize that _exit() never returns and issue the
  100. // 'unreachable code' warning for code following this function, unless
  101. // fooled by a fake condition.
  102. if (AlwaysTrue())
  103. _exit(1);
  104. }
  105. void DieInside(const ::std::string& function) {
  106. DieWithMessage("death inside " + function + "().");
  107. }
  108. // Tests that death tests work.
  109. class TestForDeathTest : public testing::Test {
  110. protected:
  111. TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
  112. virtual ~TestForDeathTest() {
  113. posix::ChDir(original_dir_.c_str());
  114. }
  115. // A static member function that's expected to die.
  116. static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
  117. // A method of the test fixture that may die.
  118. void MemberFunction() {
  119. if (should_die_)
  120. DieInside("MemberFunction");
  121. }
  122. // True iff MemberFunction() should die.
  123. bool should_die_;
  124. const FilePath original_dir_;
  125. };
  126. // A class with a member function that may die.
  127. class MayDie {
  128. public:
  129. explicit MayDie(bool should_die) : should_die_(should_die) {}
  130. // A member function that may die.
  131. void MemberFunction() const {
  132. if (should_die_)
  133. DieInside("MayDie::MemberFunction");
  134. }
  135. private:
  136. // True iff MemberFunction() should die.
  137. bool should_die_;
  138. };
  139. // A global function that's expected to die.
  140. void GlobalFunction() { DieInside("GlobalFunction"); }
  141. // A non-void function that's expected to die.
  142. int NonVoidFunction() {
  143. DieInside("NonVoidFunction");
  144. return 1;
  145. }
  146. // A unary function that may die.
  147. void DieIf(bool should_die) {
  148. if (should_die)
  149. DieInside("DieIf");
  150. }
  151. // A binary function that may die.
  152. bool DieIfLessThan(int x, int y) {
  153. if (x < y) {
  154. DieInside("DieIfLessThan");
  155. }
  156. return true;
  157. }
  158. // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
  159. void DeathTestSubroutine() {
  160. EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
  161. ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
  162. }
  163. // Death in dbg, not opt.
  164. int DieInDebugElse12(int* sideeffect) {
  165. if (sideeffect) *sideeffect = 12;
  166. # ifndef NDEBUG
  167. DieInside("DieInDebugElse12");
  168. # endif // NDEBUG
  169. return 12;
  170. }
  171. # if GTEST_OS_WINDOWS
  172. // Tests the ExitedWithCode predicate.
  173. TEST(ExitStatusPredicateTest, ExitedWithCode) {
  174. // On Windows, the process's exit code is the same as its exit status,
  175. // so the predicate just compares the its input with its parameter.
  176. EXPECT_TRUE(testing::ExitedWithCode(0)(0));
  177. EXPECT_TRUE(testing::ExitedWithCode(1)(1));
  178. EXPECT_TRUE(testing::ExitedWithCode(42)(42));
  179. EXPECT_FALSE(testing::ExitedWithCode(0)(1));
  180. EXPECT_FALSE(testing::ExitedWithCode(1)(0));
  181. }
  182. # else
  183. // Returns the exit status of a process that calls _exit(2) with a
  184. // given exit code. This is a helper function for the
  185. // ExitStatusPredicateTest test suite.
  186. static int NormalExitStatus(int exit_code) {
  187. pid_t child_pid = fork();
  188. if (child_pid == 0) {
  189. _exit(exit_code);
  190. }
  191. int status;
  192. waitpid(child_pid, &status, 0);
  193. return status;
  194. }
  195. // Returns the exit status of a process that raises a given signal.
  196. // If the signal does not cause the process to die, then it returns
  197. // instead the exit status of a process that exits normally with exit
  198. // code 1. This is a helper function for the ExitStatusPredicateTest
  199. // test suite.
  200. static int KilledExitStatus(int signum) {
  201. pid_t child_pid = fork();
  202. if (child_pid == 0) {
  203. raise(signum);
  204. _exit(1);
  205. }
  206. int status;
  207. waitpid(child_pid, &status, 0);
  208. return status;
  209. }
  210. // Tests the ExitedWithCode predicate.
  211. TEST(ExitStatusPredicateTest, ExitedWithCode) {
  212. const int status0 = NormalExitStatus(0);
  213. const int status1 = NormalExitStatus(1);
  214. const int status42 = NormalExitStatus(42);
  215. const testing::ExitedWithCode pred0(0);
  216. const testing::ExitedWithCode pred1(1);
  217. const testing::ExitedWithCode pred42(42);
  218. EXPECT_PRED1(pred0, status0);
  219. EXPECT_PRED1(pred1, status1);
  220. EXPECT_PRED1(pred42, status42);
  221. EXPECT_FALSE(pred0(status1));
  222. EXPECT_FALSE(pred42(status0));
  223. EXPECT_FALSE(pred1(status42));
  224. }
  225. // Tests the KilledBySignal predicate.
  226. TEST(ExitStatusPredicateTest, KilledBySignal) {
  227. const int status_segv = KilledExitStatus(SIGSEGV);
  228. const int status_kill = KilledExitStatus(SIGKILL);
  229. const testing::KilledBySignal pred_segv(SIGSEGV);
  230. const testing::KilledBySignal pred_kill(SIGKILL);
  231. EXPECT_PRED1(pred_segv, status_segv);
  232. EXPECT_PRED1(pred_kill, status_kill);
  233. EXPECT_FALSE(pred_segv(status_kill));
  234. EXPECT_FALSE(pred_kill(status_segv));
  235. }
  236. # endif // GTEST_OS_WINDOWS
  237. // Tests that the death test macros expand to code which may or may not
  238. // be followed by operator<<, and that in either case the complete text
  239. // comprises only a single C++ statement.
  240. TEST_F(TestForDeathTest, SingleStatement) {
  241. if (AlwaysFalse())
  242. // This would fail if executed; this is a compilation test only
  243. ASSERT_DEATH(return, "");
  244. if (AlwaysTrue())
  245. EXPECT_DEATH(_exit(1), "");
  246. else
  247. // This empty "else" branch is meant to ensure that EXPECT_DEATH
  248. // doesn't expand into an "if" statement without an "else"
  249. ;
  250. if (AlwaysFalse())
  251. ASSERT_DEATH(return, "") << "did not die";
  252. if (AlwaysFalse())
  253. ;
  254. else
  255. EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
  256. }
  257. void DieWithEmbeddedNul() {
  258. fprintf(stderr, "Hello%cmy null world.\n", '\0');
  259. fflush(stderr);
  260. _exit(1);
  261. }
  262. # if GTEST_USES_PCRE
  263. // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
  264. // message has a NUL character in it.
  265. TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
  266. // TODO(wan@google.com): <regex.h> doesn't support matching strings
  267. // with embedded NUL characters - find a way to workaround it.
  268. EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
  269. ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
  270. }
  271. # endif // GTEST_USES_PCRE
  272. // Tests that death test macros expand to code which interacts well with switch
  273. // statements.
  274. TEST_F(TestForDeathTest, SwitchStatement) {
  275. // Microsoft compiler usually complains about switch statements without
  276. // case labels. We suppress that warning for this test.
  277. # ifdef _MSC_VER
  278. # pragma warning(push)
  279. # pragma warning(disable: 4065)
  280. # endif // _MSC_VER
  281. switch (0)
  282. default:
  283. ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
  284. switch (0)
  285. case 0:
  286. EXPECT_DEATH(_exit(1), "") << "exit in switch case";
  287. # ifdef _MSC_VER
  288. # pragma warning(pop)
  289. # endif // _MSC_VER
  290. }
  291. // Tests that a static member function can be used in a "fast" style
  292. // death test.
  293. TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
  294. testing::GTEST_FLAG(death_test_style) = "fast";
  295. ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
  296. }
  297. // Tests that a method of the test fixture can be used in a "fast"
  298. // style death test.
  299. TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
  300. testing::GTEST_FLAG(death_test_style) = "fast";
  301. should_die_ = true;
  302. EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
  303. }
  304. void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
  305. // Tests that death tests work even if the current directory has been
  306. // changed.
  307. TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
  308. testing::GTEST_FLAG(death_test_style) = "fast";
  309. ChangeToRootDir();
  310. EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
  311. ChangeToRootDir();
  312. ASSERT_DEATH(_exit(1), "");
  313. }
  314. // Repeats a representative sample of death tests in the "threadsafe" style:
  315. TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
  316. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  317. ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
  318. }
  319. TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
  320. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  321. should_die_ = true;
  322. EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
  323. }
  324. TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
  325. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  326. for (int i = 0; i < 3; ++i)
  327. EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
  328. }
  329. TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
  330. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  331. ChangeToRootDir();
  332. EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
  333. ChangeToRootDir();
  334. ASSERT_DEATH(_exit(1), "");
  335. }
  336. TEST_F(TestForDeathTest, MixedStyles) {
  337. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  338. EXPECT_DEATH(_exit(1), "");
  339. testing::GTEST_FLAG(death_test_style) = "fast";
  340. EXPECT_DEATH(_exit(1), "");
  341. }
  342. namespace {
  343. bool pthread_flag;
  344. void SetPthreadFlag() {
  345. pthread_flag = true;
  346. }
  347. } // namespace
  348. # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
  349. TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
  350. if (!testing::GTEST_FLAG(death_test_use_fork)) {
  351. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  352. pthread_flag = false;
  353. ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
  354. ASSERT_DEATH(_exit(1), "");
  355. ASSERT_FALSE(pthread_flag);
  356. }
  357. }
  358. # endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
  359. // Tests that a method of another class can be used in a death test.
  360. TEST_F(TestForDeathTest, MethodOfAnotherClass) {
  361. const MayDie x(true);
  362. ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
  363. }
  364. // Tests that a global function can be used in a death test.
  365. TEST_F(TestForDeathTest, GlobalFunction) {
  366. EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
  367. }
  368. // Tests that any value convertible to an RE works as a second
  369. // argument to EXPECT_DEATH.
  370. TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
  371. static const char regex_c_str[] = "GlobalFunction";
  372. EXPECT_DEATH(GlobalFunction(), regex_c_str);
  373. const testing::internal::RE regex(regex_c_str);
  374. EXPECT_DEATH(GlobalFunction(), regex);
  375. # if GTEST_HAS_GLOBAL_STRING
  376. const string regex_str(regex_c_str);
  377. EXPECT_DEATH(GlobalFunction(), regex_str);
  378. # endif // GTEST_HAS_GLOBAL_STRING
  379. const ::std::string regex_std_str(regex_c_str);
  380. EXPECT_DEATH(GlobalFunction(), regex_std_str);
  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, RunawayIsFailure) {
  456. EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
  457. "failed to die.");
  458. }
  459. // Tests that death tests report executing 'return' in the statement as
  460. // failure.
  461. TEST_F(TestForDeathTest, ReturnIsFailure) {
  462. EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
  463. "illegal return in test statement.");
  464. }
  465. // Tests that EXPECT_DEBUG_DEATH works as expected,
  466. // that is, in debug mode, it:
  467. // 1. Asserts on death.
  468. // 2. Has no side effect.
  469. //
  470. // And in opt mode, it:
  471. // 1. Has side effects but does not assert.
  472. TEST_F(TestForDeathTest, TestExpectDebugDeath) {
  473. int sideeffect = 0;
  474. EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect),
  475. "death.*DieInDebugElse12");
  476. # ifdef NDEBUG
  477. // Checks that the assignment occurs in opt mode (sideeffect).
  478. EXPECT_EQ(12, sideeffect);
  479. # else
  480. // Checks that the assignment does not occur in dbg mode (no sideeffect).
  481. EXPECT_EQ(0, sideeffect);
  482. # endif
  483. }
  484. // Tests that ASSERT_DEBUG_DEATH works as expected
  485. // In debug mode:
  486. // 1. Asserts on debug death.
  487. // 2. Has no side effect.
  488. //
  489. // In opt mode:
  490. // 1. Has side effects and returns the expected value (12).
  491. TEST_F(TestForDeathTest, TestAssertDebugDeath) {
  492. int sideeffect = 0;
  493. ASSERT_DEBUG_DEATH({ // NOLINT
  494. // Tests that the return value is 12 in opt mode.
  495. EXPECT_EQ(12, DieInDebugElse12(&sideeffect));
  496. // Tests that the side effect occurred in opt mode.
  497. EXPECT_EQ(12, sideeffect);
  498. }, "death.*DieInDebugElse12");
  499. # ifdef NDEBUG
  500. // Checks that the assignment occurs in opt mode (sideeffect).
  501. EXPECT_EQ(12, sideeffect);
  502. # else
  503. // Checks that the assignment does not occur in dbg mode (no sideeffect).
  504. EXPECT_EQ(0, sideeffect);
  505. # endif
  506. }
  507. # ifndef NDEBUG
  508. void ExpectDebugDeathHelper(bool* aborted) {
  509. *aborted = true;
  510. EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
  511. *aborted = false;
  512. }
  513. # if GTEST_OS_WINDOWS
  514. TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
  515. printf("This test should be considered failing if it shows "
  516. "any pop-up dialogs.\n");
  517. fflush(stdout);
  518. EXPECT_DEATH({
  519. testing::GTEST_FLAG(catch_exceptions) = false;
  520. abort();
  521. }, "");
  522. }
  523. # endif // GTEST_OS_WINDOWS
  524. // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
  525. // the function.
  526. TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
  527. bool aborted = true;
  528. EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
  529. EXPECT_FALSE(aborted);
  530. }
  531. void AssertDebugDeathHelper(bool* aborted) {
  532. *aborted = true;
  533. ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
  534. *aborted = false;
  535. }
  536. // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
  537. // failure.
  538. TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
  539. static bool aborted;
  540. aborted = false;
  541. EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  542. EXPECT_TRUE(aborted);
  543. }
  544. # endif // _NDEBUG
  545. // Tests the *_EXIT family of macros, using a variety of predicates.
  546. static void TestExitMacros() {
  547. EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
  548. ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
  549. # if GTEST_OS_WINDOWS
  550. // Of all signals effects on the process exit code, only those of SIGABRT
  551. // are documented on Windows.
  552. // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
  553. EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "");
  554. # else
  555. EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
  556. ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
  557. EXPECT_FATAL_FAILURE({ // NOLINT
  558. ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
  559. << "This failure is expected, too.";
  560. }, "This failure is expected, too.");
  561. # endif // GTEST_OS_WINDOWS
  562. EXPECT_NONFATAL_FAILURE({ // NOLINT
  563. EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
  564. << "This failure is expected.";
  565. }, "This failure is expected.");
  566. }
  567. TEST_F(TestForDeathTest, ExitMacros) {
  568. TestExitMacros();
  569. }
  570. TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
  571. testing::GTEST_FLAG(death_test_use_fork) = true;
  572. TestExitMacros();
  573. }
  574. TEST_F(TestForDeathTest, InvalidStyle) {
  575. testing::GTEST_FLAG(death_test_style) = "rococo";
  576. EXPECT_NONFATAL_FAILURE({ // NOLINT
  577. EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
  578. }, "This failure is expected.");
  579. }
  580. TEST_F(TestForDeathTest, DeathTestFailedOutput) {
  581. testing::GTEST_FLAG(death_test_style) = "fast";
  582. EXPECT_NONFATAL_FAILURE(
  583. EXPECT_DEATH(DieWithMessage("death\n"),
  584. "expected message"),
  585. "Actual msg:\n"
  586. "[ DEATH ] death\n");
  587. }
  588. TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
  589. testing::GTEST_FLAG(death_test_style) = "fast";
  590. EXPECT_NONFATAL_FAILURE(
  591. EXPECT_DEATH({
  592. fprintf(stderr, "returning\n");
  593. fflush(stderr);
  594. return;
  595. }, ""),
  596. " Result: illegal return in test statement.\n"
  597. " Error msg:\n"
  598. "[ DEATH ] returning\n");
  599. }
  600. TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
  601. testing::GTEST_FLAG(death_test_style) = "fast";
  602. EXPECT_NONFATAL_FAILURE(
  603. EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
  604. testing::ExitedWithCode(3),
  605. "expected message"),
  606. " Result: died but not with expected exit code:\n"
  607. " Exited with exit status 1\n"
  608. "Actual msg:\n"
  609. "[ DEATH ] exiting with rc 1\n");
  610. }
  611. TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
  612. testing::GTEST_FLAG(death_test_style) = "fast";
  613. EXPECT_NONFATAL_FAILURE(
  614. EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
  615. "line 1\nxyz\nline 3\n"),
  616. "Actual msg:\n"
  617. "[ DEATH ] line 1\n"
  618. "[ DEATH ] line 2\n"
  619. "[ DEATH ] line 3\n");
  620. }
  621. TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
  622. testing::GTEST_FLAG(death_test_style) = "fast";
  623. EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
  624. "line 1\nline 2\nline 3\n");
  625. }
  626. // A DeathTestFactory that returns MockDeathTests.
  627. class MockDeathTestFactory : public DeathTestFactory {
  628. public:
  629. MockDeathTestFactory();
  630. virtual bool Create(const char* statement,
  631. const ::testing::internal::RE* regex,
  632. const char* file, int line, DeathTest** test);
  633. // Sets the parameters for subsequent calls to Create.
  634. void SetParameters(bool create, DeathTest::TestRole role,
  635. int status, bool passed);
  636. // Accessors.
  637. int AssumeRoleCalls() const { return assume_role_calls_; }
  638. int WaitCalls() const { return wait_calls_; }
  639. int PassedCalls() const { return passed_args_.size(); }
  640. bool PassedArgument(int n) const { return passed_args_[n]; }
  641. int AbortCalls() const { return abort_args_.size(); }
  642. DeathTest::AbortReason AbortArgument(int n) const {
  643. return abort_args_[n];
  644. }
  645. bool TestDeleted() const { return test_deleted_; }
  646. private:
  647. friend class MockDeathTest;
  648. // If true, Create will return a MockDeathTest; otherwise it returns
  649. // NULL.
  650. bool create_;
  651. // The value a MockDeathTest will return from its AssumeRole method.
  652. DeathTest::TestRole role_;
  653. // The value a MockDeathTest will return from its Wait method.
  654. int status_;
  655. // The value a MockDeathTest will return from its Passed method.
  656. bool passed_;
  657. // Number of times AssumeRole was called.
  658. int assume_role_calls_;
  659. // Number of times Wait was called.
  660. int wait_calls_;
  661. // The arguments to the calls to Passed since the last call to
  662. // SetParameters.
  663. std::vector<bool> passed_args_;
  664. // The arguments to the calls to Abort since the last call to
  665. // SetParameters.
  666. std::vector<DeathTest::AbortReason> abort_args_;
  667. // True if the last MockDeathTest returned by Create has been
  668. // deleted.
  669. bool test_deleted_;
  670. };
  671. // A DeathTest implementation useful in testing. It returns values set
  672. // at its creation from its various inherited DeathTest methods, and
  673. // reports calls to those methods to its parent MockDeathTestFactory
  674. // object.
  675. class MockDeathTest : public DeathTest {
  676. public:
  677. MockDeathTest(MockDeathTestFactory *parent,
  678. TestRole role, int status, bool passed) :
  679. parent_(parent), role_(role), status_(status), passed_(passed) {
  680. }
  681. virtual ~MockDeathTest() {
  682. parent_->test_deleted_ = true;
  683. }
  684. virtual TestRole AssumeRole() {
  685. ++parent_->assume_role_calls_;
  686. return role_;
  687. }
  688. virtual int Wait() {
  689. ++parent_->wait_calls_;
  690. return status_;
  691. }
  692. virtual bool Passed(bool exit_status_ok) {
  693. parent_->passed_args_.push_back(exit_status_ok);
  694. return passed_;
  695. }
  696. virtual void Abort(AbortReason reason) {
  697. parent_->abort_args_.push_back(reason);
  698. }
  699. private:
  700. MockDeathTestFactory* const parent_;
  701. const TestRole role_;
  702. const int status_;
  703. const bool passed_;
  704. };
  705. // MockDeathTestFactory constructor.
  706. MockDeathTestFactory::MockDeathTestFactory()
  707. : create_(true),
  708. role_(DeathTest::OVERSEE_TEST),
  709. status_(0),
  710. passed_(true),
  711. assume_role_calls_(0),
  712. wait_calls_(0),
  713. passed_args_(),
  714. abort_args_() {
  715. }
  716. // Sets the parameters for subsequent calls to Create.
  717. void MockDeathTestFactory::SetParameters(bool create,
  718. DeathTest::TestRole role,
  719. int status, bool passed) {
  720. create_ = create;
  721. role_ = role;
  722. status_ = status;
  723. passed_ = passed;
  724. assume_role_calls_ = 0;
  725. wait_calls_ = 0;
  726. passed_args_.clear();
  727. abort_args_.clear();
  728. }
  729. // Sets test to NULL (if create_ is false) or to the address of a new
  730. // MockDeathTest object with parameters taken from the last call
  731. // to SetParameters (if create_ is true). Always returns true.
  732. bool MockDeathTestFactory::Create(const char* /*statement*/,
  733. const ::testing::internal::RE* /*regex*/,
  734. const char* /*file*/,
  735. int /*line*/,
  736. DeathTest** test) {
  737. test_deleted_ = false;
  738. if (create_) {
  739. *test = new MockDeathTest(this, role_, status_, passed_);
  740. } else {
  741. *test = NULL;
  742. }
  743. return true;
  744. }
  745. // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
  746. // It installs a MockDeathTestFactory that is used for the duration
  747. // of the test case.
  748. class MacroLogicDeathTest : public testing::Test {
  749. protected:
  750. static testing::internal::ReplaceDeathTestFactory* replacer_;
  751. static MockDeathTestFactory* factory_;
  752. static void SetUpTestCase() {
  753. factory_ = new MockDeathTestFactory;
  754. replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
  755. }
  756. static void TearDownTestCase() {
  757. delete replacer_;
  758. replacer_ = NULL;
  759. delete factory_;
  760. factory_ = NULL;
  761. }
  762. // Runs a death test that breaks the rules by returning. Such a death
  763. // test cannot be run directly from a test routine that uses a
  764. // MockDeathTest, or the remainder of the routine will not be executed.
  765. static void RunReturningDeathTest(bool* flag) {
  766. ASSERT_DEATH({ // NOLINT
  767. *flag = true;
  768. return;
  769. }, "");
  770. }
  771. };
  772. testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
  773. = NULL;
  774. MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
  775. // Test that nothing happens when the factory doesn't return a DeathTest:
  776. TEST_F(MacroLogicDeathTest, NothingHappens) {
  777. bool flag = false;
  778. factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
  779. EXPECT_DEATH(flag = true, "");
  780. EXPECT_FALSE(flag);
  781. EXPECT_EQ(0, factory_->AssumeRoleCalls());
  782. EXPECT_EQ(0, factory_->WaitCalls());
  783. EXPECT_EQ(0, factory_->PassedCalls());
  784. EXPECT_EQ(0, factory_->AbortCalls());
  785. EXPECT_FALSE(factory_->TestDeleted());
  786. }
  787. // Test that the parent process doesn't run the death test code,
  788. // and that the Passed method returns false when the (simulated)
  789. // child process exits with status 0:
  790. TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
  791. bool flag = false;
  792. factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
  793. EXPECT_DEATH(flag = true, "");
  794. EXPECT_FALSE(flag);
  795. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  796. EXPECT_EQ(1, factory_->WaitCalls());
  797. ASSERT_EQ(1, factory_->PassedCalls());
  798. EXPECT_FALSE(factory_->PassedArgument(0));
  799. EXPECT_EQ(0, factory_->AbortCalls());
  800. EXPECT_TRUE(factory_->TestDeleted());
  801. }
  802. // Tests that the Passed method was given the argument "true" when
  803. // the (simulated) child process exits with status 1:
  804. TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
  805. bool flag = false;
  806. factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
  807. EXPECT_DEATH(flag = true, "");
  808. EXPECT_FALSE(flag);
  809. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  810. EXPECT_EQ(1, factory_->WaitCalls());
  811. ASSERT_EQ(1, factory_->PassedCalls());
  812. EXPECT_TRUE(factory_->PassedArgument(0));
  813. EXPECT_EQ(0, factory_->AbortCalls());
  814. EXPECT_TRUE(factory_->TestDeleted());
  815. }
  816. // Tests that the (simulated) child process executes the death test
  817. // code, and is aborted with the correct AbortReason if it
  818. // executes a return statement.
  819. TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
  820. bool flag = false;
  821. factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
  822. RunReturningDeathTest(&flag);
  823. EXPECT_TRUE(flag);
  824. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  825. EXPECT_EQ(0, factory_->WaitCalls());
  826. EXPECT_EQ(0, factory_->PassedCalls());
  827. EXPECT_EQ(1, factory_->AbortCalls());
  828. EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
  829. factory_->AbortArgument(0));
  830. EXPECT_TRUE(factory_->TestDeleted());
  831. }
  832. // Tests that the (simulated) child process is aborted with the
  833. // correct AbortReason if it does not die.
  834. TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
  835. bool flag = false;
  836. factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
  837. EXPECT_DEATH(flag = true, "");
  838. EXPECT_TRUE(flag);
  839. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  840. EXPECT_EQ(0, factory_->WaitCalls());
  841. EXPECT_EQ(0, factory_->PassedCalls());
  842. // This time there are two calls to Abort: one since the test didn't
  843. // die, and another from the ReturnSentinel when it's destroyed. The
  844. // sentinel normally isn't destroyed if a test doesn't die, since
  845. // _exit(2) is called in that case by ForkingDeathTest, but not by
  846. // our MockDeathTest.
  847. ASSERT_EQ(2, factory_->AbortCalls());
  848. EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
  849. factory_->AbortArgument(0));
  850. EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
  851. factory_->AbortArgument(1));
  852. EXPECT_TRUE(factory_->TestDeleted());
  853. }
  854. // Tests that a successful death test does not register a successful
  855. // test part.
  856. TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
  857. EXPECT_DEATH(_exit(1), "");
  858. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  859. }
  860. TEST(StreamingAssertionsDeathTest, DeathTest) {
  861. EXPECT_DEATH(_exit(1), "") << "unexpected failure";
  862. ASSERT_DEATH(_exit(1), "") << "unexpected failure";
  863. EXPECT_NONFATAL_FAILURE({ // NOLINT
  864. EXPECT_DEATH(_exit(0), "") << "expected failure";
  865. }, "expected failure");
  866. EXPECT_FATAL_FAILURE({ // NOLINT
  867. ASSERT_DEATH(_exit(0), "") << "expected failure";
  868. }, "expected failure");
  869. }
  870. // Tests that GetLastErrnoDescription returns an empty string when the
  871. // last error is 0 and non-empty string when it is non-zero.
  872. TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
  873. errno = ENOENT;
  874. EXPECT_STRNE("", GetLastErrnoDescription().c_str());
  875. errno = 0;
  876. EXPECT_STREQ("", GetLastErrnoDescription().c_str());
  877. }
  878. # if GTEST_OS_WINDOWS
  879. TEST(AutoHandleTest, AutoHandleWorks) {
  880. HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  881. ASSERT_NE(INVALID_HANDLE_VALUE, handle);
  882. // Tests that the AutoHandle is correctly initialized with a handle.
  883. testing::internal::AutoHandle auto_handle(handle);
  884. EXPECT_EQ(handle, auto_handle.Get());
  885. // Tests that Reset assigns INVALID_HANDLE_VALUE.
  886. // Note that this cannot verify whether the original handle is closed.
  887. auto_handle.Reset();
  888. EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
  889. // Tests that Reset assigns the new handle.
  890. // Note that this cannot verify whether the original handle is closed.
  891. handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  892. ASSERT_NE(INVALID_HANDLE_VALUE, handle);
  893. auto_handle.Reset(handle);
  894. EXPECT_EQ(handle, auto_handle.Get());
  895. // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
  896. testing::internal::AutoHandle auto_handle2;
  897. EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
  898. }
  899. # endif // GTEST_OS_WINDOWS
  900. # if GTEST_OS_WINDOWS
  901. typedef unsigned __int64 BiggestParsable;
  902. typedef signed __int64 BiggestSignedParsable;
  903. const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
  904. const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
  905. # else
  906. typedef unsigned long long BiggestParsable;
  907. typedef signed long long BiggestSignedParsable;
  908. const BiggestParsable kBiggestParsableMax =
  909. ::std::numeric_limits<BiggestParsable>::max();
  910. const BiggestSignedParsable kBiggestSignedParsableMax =
  911. ::std::numeric_limits<BiggestSignedParsable>::max();
  912. # endif // GTEST_OS_WINDOWS
  913. TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
  914. BiggestParsable result = 0;
  915. // Rejects non-numbers.
  916. EXPECT_FALSE(ParseNaturalNumber(String("non-number string"), &result));
  917. // Rejects numbers with whitespace prefix.
  918. EXPECT_FALSE(ParseNaturalNumber(String(" 123"), &result));
  919. // Rejects negative numbers.
  920. EXPECT_FALSE(ParseNaturalNumber(String("-123"), &result));
  921. // Rejects numbers starting with a plus sign.
  922. EXPECT_FALSE(ParseNaturalNumber(String("+123"), &result));
  923. errno = 0;
  924. }
  925. TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
  926. BiggestParsable result = 0;
  927. EXPECT_FALSE(ParseNaturalNumber(String("99999999999999999999999"), &result));
  928. signed char char_result = 0;
  929. EXPECT_FALSE(ParseNaturalNumber(String("200"), &char_result));
  930. errno = 0;
  931. }
  932. TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
  933. BiggestParsable result = 0;
  934. result = 0;
  935. ASSERT_TRUE(ParseNaturalNumber(String("123"), &result));
  936. EXPECT_EQ(123U, result);
  937. // Check 0 as an edge case.
  938. result = 1;
  939. ASSERT_TRUE(ParseNaturalNumber(String("0"), &result));
  940. EXPECT_EQ(0U, result);
  941. result = 1;
  942. ASSERT_TRUE(ParseNaturalNumber(String("00000"), &result));
  943. EXPECT_EQ(0U, result);
  944. }
  945. TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
  946. Message msg;
  947. msg << kBiggestParsableMax;
  948. BiggestParsable result = 0;
  949. EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
  950. EXPECT_EQ(kBiggestParsableMax, result);
  951. Message msg2;
  952. msg2 << kBiggestSignedParsableMax;
  953. BiggestSignedParsable signed_result = 0;
  954. EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
  955. EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
  956. Message msg3;
  957. msg3 << INT_MAX;
  958. int int_result = 0;
  959. EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
  960. EXPECT_EQ(INT_MAX, int_result);
  961. Message msg4;
  962. msg4 << UINT_MAX;
  963. unsigned int uint_result = 0;
  964. EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
  965. EXPECT_EQ(UINT_MAX, uint_result);
  966. }
  967. TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
  968. short short_result = 0;
  969. ASSERT_TRUE(ParseNaturalNumber(String("123"), &short_result));
  970. EXPECT_EQ(123, short_result);
  971. signed char char_result = 0;
  972. ASSERT_TRUE(ParseNaturalNumber(String("123"), &char_result));
  973. EXPECT_EQ(123, char_result);
  974. }
  975. # if GTEST_OS_WINDOWS
  976. TEST(EnvironmentTest, HandleFitsIntoSizeT) {
  977. // TODO(vladl@google.com): Remove this test after this condition is verified
  978. // in a static assertion in gtest-death-test.cc in the function
  979. // GetStatusFileDescriptor.
  980. ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
  981. }
  982. # endif // GTEST_OS_WINDOWS
  983. // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
  984. // failures when death tests are available on the system.
  985. TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
  986. EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
  987. "death inside CondDeathTestExpectMacro");
  988. ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
  989. "death inside CondDeathTestAssertMacro");
  990. // Empty statement will not crash, which must trigger a failure.
  991. EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
  992. EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
  993. }
  994. #else
  995. using testing::internal::CaptureStderr;
  996. using testing::internal::GetCapturedStderr;
  997. using testing::internal::String;
  998. // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
  999. // defined but do not trigger failures when death tests are not available on
  1000. // the system.
  1001. TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
  1002. // Empty statement will not crash, but that should not trigger a failure
  1003. // when death tests are not supported.
  1004. CaptureStderr();
  1005. EXPECT_DEATH_IF_SUPPORTED(;, "");
  1006. String output = GetCapturedStderr();
  1007. ASSERT_TRUE(NULL != strstr(output.c_str(),
  1008. "Death tests are not supported on this platform"));
  1009. ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
  1010. // The streamed message should not be printed as there is no test failure.
  1011. CaptureStderr();
  1012. EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
  1013. output = GetCapturedStderr();
  1014. ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
  1015. CaptureStderr();
  1016. ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
  1017. output = GetCapturedStderr();
  1018. ASSERT_TRUE(NULL != strstr(output.c_str(),
  1019. "Death tests are not supported on this platform"));
  1020. ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
  1021. CaptureStderr();
  1022. ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
  1023. output = GetCapturedStderr();
  1024. ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
  1025. }
  1026. void FuncWithAssert(int* n) {
  1027. ASSERT_DEATH_IF_SUPPORTED(return;, "");
  1028. (*n)++;
  1029. }
  1030. // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
  1031. // function (as ASSERT_DEATH does) if death tests are not supported.
  1032. TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
  1033. int n = 0;
  1034. FuncWithAssert(&n);
  1035. EXPECT_EQ(1, n);
  1036. }
  1037. #endif // GTEST_HAS_DEATH_TEST
  1038. // Tests that the death test macros expand to code which may or may not
  1039. // be followed by operator<<, and that in either case the complete text
  1040. // comprises only a single C++ statement.
  1041. //
  1042. // The syntax should work whether death tests are available or not.
  1043. TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
  1044. if (AlwaysFalse())
  1045. // This would fail if executed; this is a compilation test only
  1046. ASSERT_DEATH_IF_SUPPORTED(return, "");
  1047. if (AlwaysTrue())
  1048. EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
  1049. else
  1050. // This empty "else" branch is meant to ensure that EXPECT_DEATH
  1051. // doesn't expand into an "if" statement without an "else"
  1052. ; // NOLINT
  1053. if (AlwaysFalse())
  1054. ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
  1055. if (AlwaysFalse())
  1056. ; // NOLINT
  1057. else
  1058. EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
  1059. }
  1060. // Tests that conditional death test macros expand to code which interacts
  1061. // well with switch statements.
  1062. TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
  1063. // Microsoft compiler usually complains about switch statements without
  1064. // case labels. We suppress that warning for this test.
  1065. #ifdef _MSC_VER
  1066. # pragma warning(push)
  1067. # pragma warning(disable: 4065)
  1068. #endif // _MSC_VER
  1069. switch (0)
  1070. default:
  1071. ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
  1072. << "exit in default switch handler";
  1073. switch (0)
  1074. case 0:
  1075. EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
  1076. #ifdef _MSC_VER
  1077. # pragma warning(pop)
  1078. #endif // _MSC_VER
  1079. }
  1080. // Tests that a test case whose name ends with "DeathTest" works fine
  1081. // on Windows.
  1082. TEST(NotADeathTest, Test) {
  1083. SUCCEED();
  1084. }