googletest-death-test-test.cc 47 KB

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