Counter Strike : Global Offensive Source Code
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.

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