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.

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