gtest-death-test_test.cc 44 KB

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