googletest-death-test-test.cc 47 KB

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