googletest-death-test-test.cc 47 KB

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