gtest-death-test_test.cc 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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. # ifdef _MSC_VER
  280. # pragma warning(push)
  281. # pragma warning(disable: 4065)
  282. # endif // _MSC_VER
  283. switch (0)
  284. default:
  285. ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
  286. switch (0)
  287. case 0:
  288. EXPECT_DEATH(_exit(1), "") << "exit in switch case";
  289. # ifdef _MSC_VER
  290. # pragma warning(pop)
  291. # endif // _MSC_VER
  292. }
  293. // Tests that a static member function can be used in a "fast" style
  294. // death test.
  295. TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
  296. testing::GTEST_FLAG(death_test_style) = "fast";
  297. ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
  298. }
  299. // Tests that a method of the test fixture can be used in a "fast"
  300. // style death test.
  301. TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
  302. testing::GTEST_FLAG(death_test_style) = "fast";
  303. should_die_ = true;
  304. EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
  305. }
  306. void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
  307. // Tests that death tests work even if the current directory has been
  308. // changed.
  309. TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
  310. testing::GTEST_FLAG(death_test_style) = "fast";
  311. ChangeToRootDir();
  312. EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
  313. ChangeToRootDir();
  314. ASSERT_DEATH(_exit(1), "");
  315. }
  316. # if GTEST_OS_LINUX
  317. void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
  318. // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
  319. void SetSigprofActionAndTimer() {
  320. struct itimerval timer;
  321. timer.it_interval.tv_sec = 0;
  322. timer.it_interval.tv_usec = 1;
  323. timer.it_value = timer.it_interval;
  324. ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
  325. struct sigaction signal_action;
  326. memset(&signal_action, 0, sizeof(signal_action));
  327. sigemptyset(&signal_action.sa_mask);
  328. signal_action.sa_sigaction = SigprofAction;
  329. signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
  330. ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL));
  331. }
  332. // Disables ITIMER_PROF timer and ignores SIGPROF signal.
  333. void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
  334. struct itimerval timer;
  335. timer.it_interval.tv_sec = 0;
  336. timer.it_interval.tv_usec = 0;
  337. timer.it_value = timer.it_interval;
  338. ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
  339. struct sigaction signal_action;
  340. memset(&signal_action, 0, sizeof(signal_action));
  341. sigemptyset(&signal_action.sa_mask);
  342. signal_action.sa_handler = SIG_IGN;
  343. ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
  344. }
  345. // Tests that death tests work when SIGPROF handler and timer are set.
  346. TEST_F(TestForDeathTest, FastSigprofActionSet) {
  347. testing::GTEST_FLAG(death_test_style) = "fast";
  348. SetSigprofActionAndTimer();
  349. EXPECT_DEATH(_exit(1), "");
  350. struct sigaction old_signal_action;
  351. DisableSigprofActionAndTimer(&old_signal_action);
  352. EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
  353. }
  354. TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
  355. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  356. SetSigprofActionAndTimer();
  357. EXPECT_DEATH(_exit(1), "");
  358. struct sigaction old_signal_action;
  359. DisableSigprofActionAndTimer(&old_signal_action);
  360. EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
  361. }
  362. # endif // GTEST_OS_LINUX
  363. // Repeats a representative sample of death tests in the "threadsafe" style:
  364. TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
  365. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  366. ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
  367. }
  368. TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
  369. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  370. should_die_ = true;
  371. EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
  372. }
  373. TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
  374. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  375. for (int i = 0; i < 3; ++i)
  376. EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
  377. }
  378. TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
  379. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  380. ChangeToRootDir();
  381. EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
  382. ChangeToRootDir();
  383. ASSERT_DEATH(_exit(1), "");
  384. }
  385. TEST_F(TestForDeathTest, MixedStyles) {
  386. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  387. EXPECT_DEATH(_exit(1), "");
  388. testing::GTEST_FLAG(death_test_style) = "fast";
  389. EXPECT_DEATH(_exit(1), "");
  390. }
  391. # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
  392. namespace {
  393. bool pthread_flag;
  394. void SetPthreadFlag() {
  395. pthread_flag = true;
  396. }
  397. } // namespace
  398. TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
  399. if (!testing::GTEST_FLAG(death_test_use_fork)) {
  400. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  401. pthread_flag = false;
  402. ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
  403. ASSERT_DEATH(_exit(1), "");
  404. ASSERT_FALSE(pthread_flag);
  405. }
  406. }
  407. # endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
  408. // Tests that a method of another class can be used in a death test.
  409. TEST_F(TestForDeathTest, MethodOfAnotherClass) {
  410. const MayDie x(true);
  411. ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
  412. }
  413. // Tests that a global function can be used in a death test.
  414. TEST_F(TestForDeathTest, GlobalFunction) {
  415. EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
  416. }
  417. // Tests that any value convertible to an RE works as a second
  418. // argument to EXPECT_DEATH.
  419. TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
  420. static const char regex_c_str[] = "GlobalFunction";
  421. EXPECT_DEATH(GlobalFunction(), regex_c_str);
  422. const testing::internal::RE regex(regex_c_str);
  423. EXPECT_DEATH(GlobalFunction(), regex);
  424. # if GTEST_HAS_GLOBAL_STRING
  425. const string regex_str(regex_c_str);
  426. EXPECT_DEATH(GlobalFunction(), regex_str);
  427. # endif // GTEST_HAS_GLOBAL_STRING
  428. const ::std::string regex_std_str(regex_c_str);
  429. EXPECT_DEATH(GlobalFunction(), regex_std_str);
  430. }
  431. // Tests that a non-void function can be used in a death test.
  432. TEST_F(TestForDeathTest, NonVoidFunction) {
  433. ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
  434. }
  435. // Tests that functions that take parameter(s) can be used in a death test.
  436. TEST_F(TestForDeathTest, FunctionWithParameter) {
  437. EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
  438. EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
  439. }
  440. // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
  441. TEST_F(TestForDeathTest, OutsideFixture) {
  442. DeathTestSubroutine();
  443. }
  444. // Tests that death tests can be done inside a loop.
  445. TEST_F(TestForDeathTest, InsideLoop) {
  446. for (int i = 0; i < 5; i++) {
  447. EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
  448. }
  449. }
  450. // Tests that a compound statement can be used in a death test.
  451. TEST_F(TestForDeathTest, CompoundStatement) {
  452. EXPECT_DEATH({ // NOLINT
  453. const int x = 2;
  454. const int y = x + 1;
  455. DieIfLessThan(x, y);
  456. },
  457. "DieIfLessThan");
  458. }
  459. // Tests that code that doesn't die causes a death test to fail.
  460. TEST_F(TestForDeathTest, DoesNotDie) {
  461. EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
  462. "failed to die");
  463. }
  464. // Tests that a death test fails when the error message isn't expected.
  465. TEST_F(TestForDeathTest, ErrorMessageMismatch) {
  466. EXPECT_NONFATAL_FAILURE({ // NOLINT
  467. EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
  468. }, "died but not with expected error");
  469. }
  470. // On exit, *aborted will be true iff the EXPECT_DEATH() statement
  471. // aborted the function.
  472. void ExpectDeathTestHelper(bool* aborted) {
  473. *aborted = true;
  474. EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
  475. *aborted = false;
  476. }
  477. // Tests that EXPECT_DEATH doesn't abort the test on failure.
  478. TEST_F(TestForDeathTest, EXPECT_DEATH) {
  479. bool aborted = true;
  480. EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
  481. "failed to die");
  482. EXPECT_FALSE(aborted);
  483. }
  484. // Tests that ASSERT_DEATH does abort the test on failure.
  485. TEST_F(TestForDeathTest, ASSERT_DEATH) {
  486. static bool aborted;
  487. EXPECT_FATAL_FAILURE({ // NOLINT
  488. aborted = true;
  489. ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
  490. aborted = false;
  491. }, "failed to die");
  492. EXPECT_TRUE(aborted);
  493. }
  494. // Tests that EXPECT_DEATH evaluates the arguments exactly once.
  495. TEST_F(TestForDeathTest, SingleEvaluation) {
  496. int x = 3;
  497. EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
  498. const char* regex = "DieIf";
  499. const char* regex_save = regex;
  500. EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
  501. EXPECT_EQ(regex_save + 1, regex);
  502. }
  503. // Tests that run-away death tests are reported as failures.
  504. TEST_F(TestForDeathTest, RunawayIsFailure) {
  505. EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
  506. "failed to die.");
  507. }
  508. // Tests that death tests report executing 'return' in the statement as
  509. // failure.
  510. TEST_F(TestForDeathTest, ReturnIsFailure) {
  511. EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
  512. "illegal return in test statement.");
  513. }
  514. // Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
  515. // message to it, and in debug mode it:
  516. // 1. Asserts on death.
  517. // 2. Has no side effect.
  518. //
  519. // And in opt mode, it:
  520. // 1. Has side effects but does not assert.
  521. TEST_F(TestForDeathTest, TestExpectDebugDeath) {
  522. int sideeffect = 0;
  523. EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
  524. << "Must accept a streamed message";
  525. # ifdef NDEBUG
  526. // Checks that the assignment occurs in opt mode (sideeffect).
  527. EXPECT_EQ(12, sideeffect);
  528. # else
  529. // Checks that the assignment does not occur in dbg mode (no sideeffect).
  530. EXPECT_EQ(0, sideeffect);
  531. # endif
  532. }
  533. // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
  534. // message to it, and in debug mode it:
  535. // 1. Asserts on death.
  536. // 2. Has no side effect.
  537. //
  538. // And in opt mode, it:
  539. // 1. Has side effects but does not assert.
  540. TEST_F(TestForDeathTest, TestAssertDebugDeath) {
  541. int sideeffect = 0;
  542. ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
  543. << "Must accept a streamed message";
  544. # ifdef NDEBUG
  545. // Checks that the assignment occurs in opt mode (sideeffect).
  546. EXPECT_EQ(12, sideeffect);
  547. # else
  548. // Checks that the assignment does not occur in dbg mode (no sideeffect).
  549. EXPECT_EQ(0, sideeffect);
  550. # endif
  551. }
  552. # ifndef NDEBUG
  553. void ExpectDebugDeathHelper(bool* aborted) {
  554. *aborted = true;
  555. EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
  556. *aborted = false;
  557. }
  558. # if GTEST_OS_WINDOWS
  559. TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
  560. printf("This test should be considered failing if it shows "
  561. "any pop-up dialogs.\n");
  562. fflush(stdout);
  563. EXPECT_DEATH({
  564. testing::GTEST_FLAG(catch_exceptions) = false;
  565. abort();
  566. }, "");
  567. }
  568. # endif // GTEST_OS_WINDOWS
  569. // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
  570. // the function.
  571. TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
  572. bool aborted = true;
  573. EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
  574. EXPECT_FALSE(aborted);
  575. }
  576. void AssertDebugDeathHelper(bool* aborted) {
  577. *aborted = true;
  578. ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
  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. # endif // _NDEBUG
  590. // Tests the *_EXIT family of macros, using a variety of predicates.
  591. static void TestExitMacros() {
  592. EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
  593. ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
  594. # if GTEST_OS_WINDOWS
  595. // Of all signals effects on the process exit code, only those of SIGABRT
  596. // are documented on Windows.
  597. // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
  598. EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
  599. # else
  600. EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
  601. ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
  602. EXPECT_FATAL_FAILURE({ // NOLINT
  603. ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
  604. << "This failure is expected, too.";
  605. }, "This failure is expected, too.");
  606. # endif // GTEST_OS_WINDOWS
  607. EXPECT_NONFATAL_FAILURE({ // NOLINT
  608. EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
  609. << "This failure is expected.";
  610. }, "This failure is expected.");
  611. }
  612. TEST_F(TestForDeathTest, ExitMacros) {
  613. TestExitMacros();
  614. }
  615. TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
  616. testing::GTEST_FLAG(death_test_use_fork) = true;
  617. TestExitMacros();
  618. }
  619. TEST_F(TestForDeathTest, InvalidStyle) {
  620. testing::GTEST_FLAG(death_test_style) = "rococo";
  621. EXPECT_NONFATAL_FAILURE({ // NOLINT
  622. EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
  623. }, "This failure is expected.");
  624. }
  625. TEST_F(TestForDeathTest, DeathTestFailedOutput) {
  626. testing::GTEST_FLAG(death_test_style) = "fast";
  627. EXPECT_NONFATAL_FAILURE(
  628. EXPECT_DEATH(DieWithMessage("death\n"),
  629. "expected message"),
  630. "Actual msg:\n"
  631. "[ DEATH ] death\n");
  632. }
  633. TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
  634. testing::GTEST_FLAG(death_test_style) = "fast";
  635. EXPECT_NONFATAL_FAILURE(
  636. EXPECT_DEATH({
  637. fprintf(stderr, "returning\n");
  638. fflush(stderr);
  639. return;
  640. }, ""),
  641. " Result: illegal return in test statement.\n"
  642. " Error msg:\n"
  643. "[ DEATH ] returning\n");
  644. }
  645. TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
  646. testing::GTEST_FLAG(death_test_style) = "fast";
  647. EXPECT_NONFATAL_FAILURE(
  648. EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
  649. testing::ExitedWithCode(3),
  650. "expected message"),
  651. " Result: died but not with expected exit code:\n"
  652. " Exited with exit status 1\n"
  653. "Actual msg:\n"
  654. "[ DEATH ] exiting with rc 1\n");
  655. }
  656. TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
  657. testing::GTEST_FLAG(death_test_style) = "fast";
  658. EXPECT_NONFATAL_FAILURE(
  659. EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
  660. "line 1\nxyz\nline 3\n"),
  661. "Actual msg:\n"
  662. "[ DEATH ] line 1\n"
  663. "[ DEATH ] line 2\n"
  664. "[ DEATH ] line 3\n");
  665. }
  666. TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
  667. testing::GTEST_FLAG(death_test_style) = "fast";
  668. EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
  669. "line 1\nline 2\nline 3\n");
  670. }
  671. // A DeathTestFactory that returns MockDeathTests.
  672. class MockDeathTestFactory : public DeathTestFactory {
  673. public:
  674. MockDeathTestFactory();
  675. virtual bool Create(const char* statement,
  676. const ::testing::internal::RE* regex,
  677. const char* file, int line, DeathTest** test);
  678. // Sets the parameters for subsequent calls to Create.
  679. void SetParameters(bool create, DeathTest::TestRole role,
  680. int status, bool passed);
  681. // Accessors.
  682. int AssumeRoleCalls() const { return assume_role_calls_; }
  683. int WaitCalls() const { return wait_calls_; }
  684. int PassedCalls() const { return passed_args_.size(); }
  685. bool PassedArgument(int n) const { return passed_args_[n]; }
  686. int AbortCalls() const { return abort_args_.size(); }
  687. DeathTest::AbortReason AbortArgument(int n) const {
  688. return abort_args_[n];
  689. }
  690. bool TestDeleted() const { return test_deleted_; }
  691. private:
  692. friend class MockDeathTest;
  693. // If true, Create will return a MockDeathTest; otherwise it returns
  694. // NULL.
  695. bool create_;
  696. // The value a MockDeathTest will return from its AssumeRole method.
  697. DeathTest::TestRole role_;
  698. // The value a MockDeathTest will return from its Wait method.
  699. int status_;
  700. // The value a MockDeathTest will return from its Passed method.
  701. bool passed_;
  702. // Number of times AssumeRole was called.
  703. int assume_role_calls_;
  704. // Number of times Wait was called.
  705. int wait_calls_;
  706. // The arguments to the calls to Passed since the last call to
  707. // SetParameters.
  708. std::vector<bool> passed_args_;
  709. // The arguments to the calls to Abort since the last call to
  710. // SetParameters.
  711. std::vector<DeathTest::AbortReason> abort_args_;
  712. // True if the last MockDeathTest returned by Create has been
  713. // deleted.
  714. bool test_deleted_;
  715. };
  716. // A DeathTest implementation useful in testing. It returns values set
  717. // at its creation from its various inherited DeathTest methods, and
  718. // reports calls to those methods to its parent MockDeathTestFactory
  719. // object.
  720. class MockDeathTest : public DeathTest {
  721. public:
  722. MockDeathTest(MockDeathTestFactory *parent,
  723. TestRole role, int status, bool passed) :
  724. parent_(parent), role_(role), status_(status), passed_(passed) {
  725. }
  726. virtual ~MockDeathTest() {
  727. parent_->test_deleted_ = true;
  728. }
  729. virtual TestRole AssumeRole() {
  730. ++parent_->assume_role_calls_;
  731. return role_;
  732. }
  733. virtual int Wait() {
  734. ++parent_->wait_calls_;
  735. return status_;
  736. }
  737. virtual bool Passed(bool exit_status_ok) {
  738. parent_->passed_args_.push_back(exit_status_ok);
  739. return passed_;
  740. }
  741. virtual void Abort(AbortReason reason) {
  742. parent_->abort_args_.push_back(reason);
  743. }
  744. private:
  745. MockDeathTestFactory* const parent_;
  746. const TestRole role_;
  747. const int status_;
  748. const bool passed_;
  749. };
  750. // MockDeathTestFactory constructor.
  751. MockDeathTestFactory::MockDeathTestFactory()
  752. : create_(true),
  753. role_(DeathTest::OVERSEE_TEST),
  754. status_(0),
  755. passed_(true),
  756. assume_role_calls_(0),
  757. wait_calls_(0),
  758. passed_args_(),
  759. abort_args_() {
  760. }
  761. // Sets the parameters for subsequent calls to Create.
  762. void MockDeathTestFactory::SetParameters(bool create,
  763. DeathTest::TestRole role,
  764. int status, bool passed) {
  765. create_ = create;
  766. role_ = role;
  767. status_ = status;
  768. passed_ = passed;
  769. assume_role_calls_ = 0;
  770. wait_calls_ = 0;
  771. passed_args_.clear();
  772. abort_args_.clear();
  773. }
  774. // Sets test to NULL (if create_ is false) or to the address of a new
  775. // MockDeathTest object with parameters taken from the last call
  776. // to SetParameters (if create_ is true). Always returns true.
  777. bool MockDeathTestFactory::Create(const char* /*statement*/,
  778. const ::testing::internal::RE* /*regex*/,
  779. const char* /*file*/,
  780. int /*line*/,
  781. DeathTest** test) {
  782. test_deleted_ = false;
  783. if (create_) {
  784. *test = new MockDeathTest(this, role_, status_, passed_);
  785. } else {
  786. *test = NULL;
  787. }
  788. return true;
  789. }
  790. // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
  791. // It installs a MockDeathTestFactory that is used for the duration
  792. // of the test case.
  793. class MacroLogicDeathTest : public testing::Test {
  794. protected:
  795. static testing::internal::ReplaceDeathTestFactory* replacer_;
  796. static MockDeathTestFactory* factory_;
  797. static void SetUpTestCase() {
  798. factory_ = new MockDeathTestFactory;
  799. replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
  800. }
  801. static void TearDownTestCase() {
  802. delete replacer_;
  803. replacer_ = NULL;
  804. delete factory_;
  805. factory_ = NULL;
  806. }
  807. // Runs a death test that breaks the rules by returning. Such a death
  808. // test cannot be run directly from a test routine that uses a
  809. // MockDeathTest, or the remainder of the routine will not be executed.
  810. static void RunReturningDeathTest(bool* flag) {
  811. ASSERT_DEATH({ // NOLINT
  812. *flag = true;
  813. return;
  814. }, "");
  815. }
  816. };
  817. testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
  818. = NULL;
  819. MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
  820. // Test that nothing happens when the factory doesn't return a DeathTest:
  821. TEST_F(MacroLogicDeathTest, NothingHappens) {
  822. bool flag = false;
  823. factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
  824. EXPECT_DEATH(flag = true, "");
  825. EXPECT_FALSE(flag);
  826. EXPECT_EQ(0, factory_->AssumeRoleCalls());
  827. EXPECT_EQ(0, factory_->WaitCalls());
  828. EXPECT_EQ(0, factory_->PassedCalls());
  829. EXPECT_EQ(0, factory_->AbortCalls());
  830. EXPECT_FALSE(factory_->TestDeleted());
  831. }
  832. // Test that the parent process doesn't run the death test code,
  833. // and that the Passed method returns false when the (simulated)
  834. // child process exits with status 0:
  835. TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
  836. bool flag = false;
  837. factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
  838. EXPECT_DEATH(flag = true, "");
  839. EXPECT_FALSE(flag);
  840. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  841. EXPECT_EQ(1, factory_->WaitCalls());
  842. ASSERT_EQ(1, factory_->PassedCalls());
  843. EXPECT_FALSE(factory_->PassedArgument(0));
  844. EXPECT_EQ(0, factory_->AbortCalls());
  845. EXPECT_TRUE(factory_->TestDeleted());
  846. }
  847. // Tests that the Passed method was given the argument "true" when
  848. // the (simulated) child process exits with status 1:
  849. TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
  850. bool flag = false;
  851. factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
  852. EXPECT_DEATH(flag = true, "");
  853. EXPECT_FALSE(flag);
  854. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  855. EXPECT_EQ(1, factory_->WaitCalls());
  856. ASSERT_EQ(1, factory_->PassedCalls());
  857. EXPECT_TRUE(factory_->PassedArgument(0));
  858. EXPECT_EQ(0, factory_->AbortCalls());
  859. EXPECT_TRUE(factory_->TestDeleted());
  860. }
  861. // Tests that the (simulated) child process executes the death test
  862. // code, and is aborted with the correct AbortReason if it
  863. // executes a return statement.
  864. TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
  865. bool flag = false;
  866. factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
  867. RunReturningDeathTest(&flag);
  868. EXPECT_TRUE(flag);
  869. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  870. EXPECT_EQ(0, factory_->WaitCalls());
  871. EXPECT_EQ(0, factory_->PassedCalls());
  872. EXPECT_EQ(1, factory_->AbortCalls());
  873. EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
  874. factory_->AbortArgument(0));
  875. EXPECT_TRUE(factory_->TestDeleted());
  876. }
  877. // Tests that the (simulated) child process is aborted with the
  878. // correct AbortReason if it does not die.
  879. TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
  880. bool flag = false;
  881. factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
  882. EXPECT_DEATH(flag = true, "");
  883. EXPECT_TRUE(flag);
  884. EXPECT_EQ(1, factory_->AssumeRoleCalls());
  885. EXPECT_EQ(0, factory_->WaitCalls());
  886. EXPECT_EQ(0, factory_->PassedCalls());
  887. // This time there are two calls to Abort: one since the test didn't
  888. // die, and another from the ReturnSentinel when it's destroyed. The
  889. // sentinel normally isn't destroyed if a test doesn't die, since
  890. // _exit(2) is called in that case by ForkingDeathTest, but not by
  891. // our MockDeathTest.
  892. ASSERT_EQ(2, factory_->AbortCalls());
  893. EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
  894. factory_->AbortArgument(0));
  895. EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
  896. factory_->AbortArgument(1));
  897. EXPECT_TRUE(factory_->TestDeleted());
  898. }
  899. // Tests that a successful death test does not register a successful
  900. // test part.
  901. TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
  902. EXPECT_DEATH(_exit(1), "");
  903. EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
  904. }
  905. TEST(StreamingAssertionsDeathTest, DeathTest) {
  906. EXPECT_DEATH(_exit(1), "") << "unexpected failure";
  907. ASSERT_DEATH(_exit(1), "") << "unexpected failure";
  908. EXPECT_NONFATAL_FAILURE({ // NOLINT
  909. EXPECT_DEATH(_exit(0), "") << "expected failure";
  910. }, "expected failure");
  911. EXPECT_FATAL_FAILURE({ // NOLINT
  912. ASSERT_DEATH(_exit(0), "") << "expected failure";
  913. }, "expected failure");
  914. }
  915. // Tests that GetLastErrnoDescription returns an empty string when the
  916. // last error is 0 and non-empty string when it is non-zero.
  917. TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
  918. errno = ENOENT;
  919. EXPECT_STRNE("", GetLastErrnoDescription().c_str());
  920. errno = 0;
  921. EXPECT_STREQ("", GetLastErrnoDescription().c_str());
  922. }
  923. # if GTEST_OS_WINDOWS
  924. TEST(AutoHandleTest, AutoHandleWorks) {
  925. HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  926. ASSERT_NE(INVALID_HANDLE_VALUE, handle);
  927. // Tests that the AutoHandle is correctly initialized with a handle.
  928. testing::internal::AutoHandle auto_handle(handle);
  929. EXPECT_EQ(handle, auto_handle.Get());
  930. // Tests that Reset assigns INVALID_HANDLE_VALUE.
  931. // Note that this cannot verify whether the original handle is closed.
  932. auto_handle.Reset();
  933. EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
  934. // Tests that Reset assigns the new handle.
  935. // Note that this cannot verify whether the original handle is closed.
  936. handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  937. ASSERT_NE(INVALID_HANDLE_VALUE, handle);
  938. auto_handle.Reset(handle);
  939. EXPECT_EQ(handle, auto_handle.Get());
  940. // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
  941. testing::internal::AutoHandle auto_handle2;
  942. EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
  943. }
  944. # endif // GTEST_OS_WINDOWS
  945. # if GTEST_OS_WINDOWS
  946. typedef unsigned __int64 BiggestParsable;
  947. typedef signed __int64 BiggestSignedParsable;
  948. # else
  949. typedef unsigned long long BiggestParsable;
  950. typedef signed long long BiggestSignedParsable;
  951. # endif // GTEST_OS_WINDOWS
  952. // We cannot use std::numeric_limits<T>::max() as it clashes with the
  953. // max() macro defined by <windows.h>.
  954. const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
  955. const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
  956. TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
  957. BiggestParsable result = 0;
  958. // Rejects non-numbers.
  959. EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
  960. // Rejects numbers with whitespace prefix.
  961. EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
  962. // Rejects negative numbers.
  963. EXPECT_FALSE(ParseNaturalNumber("-123", &result));
  964. // Rejects numbers starting with a plus sign.
  965. EXPECT_FALSE(ParseNaturalNumber("+123", &result));
  966. errno = 0;
  967. }
  968. TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
  969. BiggestParsable result = 0;
  970. EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
  971. signed char char_result = 0;
  972. EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
  973. errno = 0;
  974. }
  975. TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
  976. BiggestParsable result = 0;
  977. result = 0;
  978. ASSERT_TRUE(ParseNaturalNumber("123", &result));
  979. EXPECT_EQ(123U, result);
  980. // Check 0 as an edge case.
  981. result = 1;
  982. ASSERT_TRUE(ParseNaturalNumber("0", &result));
  983. EXPECT_EQ(0U, result);
  984. result = 1;
  985. ASSERT_TRUE(ParseNaturalNumber("00000", &result));
  986. EXPECT_EQ(0U, result);
  987. }
  988. TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
  989. Message msg;
  990. msg << kBiggestParsableMax;
  991. BiggestParsable result = 0;
  992. EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
  993. EXPECT_EQ(kBiggestParsableMax, result);
  994. Message msg2;
  995. msg2 << kBiggestSignedParsableMax;
  996. BiggestSignedParsable signed_result = 0;
  997. EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
  998. EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
  999. Message msg3;
  1000. msg3 << INT_MAX;
  1001. int int_result = 0;
  1002. EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
  1003. EXPECT_EQ(INT_MAX, int_result);
  1004. Message msg4;
  1005. msg4 << UINT_MAX;
  1006. unsigned int uint_result = 0;
  1007. EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
  1008. EXPECT_EQ(UINT_MAX, uint_result);
  1009. }
  1010. TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
  1011. short short_result = 0;
  1012. ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
  1013. EXPECT_EQ(123, short_result);
  1014. signed char char_result = 0;
  1015. ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
  1016. EXPECT_EQ(123, char_result);
  1017. }
  1018. # if GTEST_OS_WINDOWS
  1019. TEST(EnvironmentTest, HandleFitsIntoSizeT) {
  1020. // TODO(vladl@google.com): Remove this test after this condition is verified
  1021. // in a static assertion in gtest-death-test.cc in the function
  1022. // GetStatusFileDescriptor.
  1023. ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
  1024. }
  1025. # endif // GTEST_OS_WINDOWS
  1026. // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
  1027. // failures when death tests are available on the system.
  1028. TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
  1029. EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
  1030. "death inside CondDeathTestExpectMacro");
  1031. ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
  1032. "death inside CondDeathTestAssertMacro");
  1033. // Empty statement will not crash, which must trigger a failure.
  1034. EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
  1035. EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
  1036. }
  1037. #else
  1038. using testing::internal::CaptureStderr;
  1039. using testing::internal::GetCapturedStderr;
  1040. // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
  1041. // defined but do not trigger failures when death tests are not available on
  1042. // the system.
  1043. TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
  1044. // Empty statement will not crash, but that should not trigger a failure
  1045. // when death tests are not supported.
  1046. CaptureStderr();
  1047. EXPECT_DEATH_IF_SUPPORTED(;, "");
  1048. std::string output = GetCapturedStderr();
  1049. ASSERT_TRUE(NULL != strstr(output.c_str(),
  1050. "Death tests are not supported on this platform"));
  1051. ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
  1052. // The streamed message should not be printed as there is no test failure.
  1053. CaptureStderr();
  1054. EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
  1055. output = GetCapturedStderr();
  1056. ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
  1057. CaptureStderr();
  1058. ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
  1059. output = GetCapturedStderr();
  1060. ASSERT_TRUE(NULL != strstr(output.c_str(),
  1061. "Death tests are not supported on this platform"));
  1062. ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
  1063. CaptureStderr();
  1064. ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
  1065. output = GetCapturedStderr();
  1066. ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
  1067. }
  1068. void FuncWithAssert(int* n) {
  1069. ASSERT_DEATH_IF_SUPPORTED(return;, "");
  1070. (*n)++;
  1071. }
  1072. // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
  1073. // function (as ASSERT_DEATH does) if death tests are not supported.
  1074. TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
  1075. int n = 0;
  1076. FuncWithAssert(&n);
  1077. EXPECT_EQ(1, n);
  1078. }
  1079. TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
  1080. testing::GTEST_FLAG(death_test_style) = "fast";
  1081. EXPECT_FALSE(InDeathTestChild());
  1082. EXPECT_DEATH({
  1083. fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
  1084. fflush(stderr);
  1085. _exit(1);
  1086. }, "Inside");
  1087. }
  1088. TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
  1089. testing::GTEST_FLAG(death_test_style) = "threadsafe";
  1090. EXPECT_FALSE(InDeathTestChild());
  1091. EXPECT_DEATH({
  1092. fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
  1093. fflush(stderr);
  1094. _exit(1);
  1095. }, "Inside");
  1096. }
  1097. #endif // GTEST_HAS_DEATH_TEST
  1098. // Tests that the death test macros expand to code which may or may not
  1099. // be followed by operator<<, and that in either case the complete text
  1100. // comprises only a single C++ statement.
  1101. //
  1102. // The syntax should work whether death tests are available or not.
  1103. TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
  1104. if (AlwaysFalse())
  1105. // This would fail if executed; this is a compilation test only
  1106. ASSERT_DEATH_IF_SUPPORTED(return, "");
  1107. if (AlwaysTrue())
  1108. EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
  1109. else
  1110. // This empty "else" branch is meant to ensure that EXPECT_DEATH
  1111. // doesn't expand into an "if" statement without an "else"
  1112. ; // NOLINT
  1113. if (AlwaysFalse())
  1114. ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
  1115. if (AlwaysFalse())
  1116. ; // NOLINT
  1117. else
  1118. EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
  1119. }
  1120. // Tests that conditional death test macros expand to code which interacts
  1121. // well with switch statements.
  1122. TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
  1123. // Microsoft compiler usually complains about switch statements without
  1124. // case labels. We suppress that warning for this test.
  1125. #ifdef _MSC_VER
  1126. # pragma warning(push)
  1127. # pragma warning(disable: 4065)
  1128. #endif // _MSC_VER
  1129. switch (0)
  1130. default:
  1131. ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
  1132. << "exit in default switch handler";
  1133. switch (0)
  1134. case 0:
  1135. EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
  1136. #ifdef _MSC_VER
  1137. # pragma warning(pop)
  1138. #endif // _MSC_VER
  1139. }
  1140. // Tests that a test case whose name ends with "DeathTest" works fine
  1141. // on Windows.
  1142. TEST(NotADeathTest, Test) {
  1143. SUCCEED();
  1144. }