googletest-death-test-test.cc 44 KB

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