protobuf/third_party/googletest/googletest/test/googletest-death-test-test.cc
Go to the documentation of this file.
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 //
31 // Tests for death tests.
32 
33 #include "gtest/gtest-death-test.h"
34 
35 #include "gtest/gtest.h"
36 #include "gtest/internal/gtest-filepath.h"
37 
40 
41 #if GTEST_HAS_DEATH_TEST
42 
43 # if GTEST_OS_WINDOWS
44 # include <direct.h> // For chdir().
45 # else
46 # include <unistd.h>
47 # include <sys/wait.h> // For waitpid.
48 # endif // GTEST_OS_WINDOWS
49 
50 # include <limits.h>
51 # include <signal.h>
52 # include <stdio.h>
53 
54 # if GTEST_OS_LINUX
55 # include <sys/time.h>
56 # endif // GTEST_OS_LINUX
57 
58 # include "gtest/gtest-spi.h"
59 # include "src/gtest-internal-inl.h"
60 
61 namespace posix = ::testing::internal::posix;
62 
64 using testing::Matcher;
65 using testing::Message;
66 using testing::internal::DeathTest;
67 using testing::internal::DeathTestFactory;
69 using testing::internal::GetLastErrnoDescription;
71 using testing::internal::InDeathTestChild;
72 using testing::internal::ParseNaturalNumber;
73 
74 namespace testing {
75 namespace internal {
76 
77 // A helper class whose objects replace the death test factory for a
78 // single UnitTest object during their lifetimes.
79 class ReplaceDeathTestFactory {
80  public:
81  explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
82  : unit_test_impl_(GetUnitTestImpl()) {
83  old_factory_ = unit_test_impl_->death_test_factory_.release();
84  unit_test_impl_->death_test_factory_.reset(new_factory);
85  }
86 
87  ~ReplaceDeathTestFactory() {
88  unit_test_impl_->death_test_factory_.release();
89  unit_test_impl_->death_test_factory_.reset(old_factory_);
90  }
91  private:
92  // Prevents copying ReplaceDeathTestFactory objects.
93  ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
94  void operator=(const ReplaceDeathTestFactory&);
95 
96  UnitTestImpl* unit_test_impl_;
97  DeathTestFactory* old_factory_;
98 };
99 
100 } // namespace internal
101 } // namespace testing
102 
103 namespace {
104 
105 void DieWithMessage(const ::std::string& message) {
106  fprintf(stderr, "%s", message.c_str());
107  fflush(stderr); // Make sure the text is printed before the process exits.
108 
109  // We call _exit() instead of exit(), as the former is a direct
110  // system call and thus safer in the presence of threads. exit()
111  // will invoke user-defined exit-hooks, which may do dangerous
112  // things that conflict with death tests.
113  //
114  // Some compilers can recognize that _exit() never returns and issue the
115  // 'unreachable code' warning for code following this function, unless
116  // fooled by a fake condition.
117  if (AlwaysTrue())
118  _exit(1);
119 }
120 
121 void DieInside(const ::std::string& function) {
122  DieWithMessage("death inside " + function + "().");
123 }
124 
125 // Tests that death tests work.
126 
127 class TestForDeathTest : public testing::Test {
128  protected:
129  TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
130 
131  ~TestForDeathTest() override { posix::ChDir(original_dir_.c_str()); }
132 
133  // A static member function that's expected to die.
134  static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
135 
136  // A method of the test fixture that may die.
137  void MemberFunction() {
138  if (should_die_)
139  DieInside("MemberFunction");
140  }
141 
142  // True iff MemberFunction() should die.
143  bool should_die_;
144  const FilePath original_dir_;
145 };
146 
147 // A class with a member function that may die.
148 class MayDie {
149  public:
150  explicit MayDie(bool should_die) : should_die_(should_die) {}
151 
152  // A member function that may die.
153  void MemberFunction() const {
154  if (should_die_)
155  DieInside("MayDie::MemberFunction");
156  }
157 
158  private:
159  // True iff MemberFunction() should die.
160  bool should_die_;
161 };
162 
163 // A global function that's expected to die.
164 void GlobalFunction() { DieInside("GlobalFunction"); }
165 
166 // A non-void function that's expected to die.
167 int NonVoidFunction() {
168  DieInside("NonVoidFunction");
169  return 1;
170 }
171 
172 // A unary function that may die.
173 void DieIf(bool should_die) {
174  if (should_die)
175  DieInside("DieIf");
176 }
177 
178 // A binary function that may die.
179 bool DieIfLessThan(int x, int y) {
180  if (x < y) {
181  DieInside("DieIfLessThan");
182  }
183  return true;
184 }
185 
186 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
187 void DeathTestSubroutine() {
188  EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
189  ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
190 }
191 
192 // Death in dbg, not opt.
193 int DieInDebugElse12(int* sideeffect) {
194  if (sideeffect) *sideeffect = 12;
195 
196 # ifndef NDEBUG
197 
198  DieInside("DieInDebugElse12");
199 
200 # endif // NDEBUG
201 
202  return 12;
203 }
204 
205 # if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
206 
207 // Tests the ExitedWithCode predicate.
208 TEST(ExitStatusPredicateTest, ExitedWithCode) {
209  // On Windows, the process's exit code is the same as its exit status,
210  // so the predicate just compares the its input with its parameter.
211  EXPECT_TRUE(testing::ExitedWithCode(0)(0));
212  EXPECT_TRUE(testing::ExitedWithCode(1)(1));
213  EXPECT_TRUE(testing::ExitedWithCode(42)(42));
214  EXPECT_FALSE(testing::ExitedWithCode(0)(1));
215  EXPECT_FALSE(testing::ExitedWithCode(1)(0));
216 }
217 
218 # else
219 
220 // Returns the exit status of a process that calls _exit(2) with a
221 // given exit code. This is a helper function for the
222 // ExitStatusPredicateTest test suite.
223 static int NormalExitStatus(int exit_code) {
224  pid_t child_pid = fork();
225  if (child_pid == 0) {
226  _exit(exit_code);
227  }
228  int status;
229  waitpid(child_pid, &status, 0);
230  return status;
231 }
232 
233 // Returns the exit status of a process that raises a given signal.
234 // If the signal does not cause the process to die, then it returns
235 // instead the exit status of a process that exits normally with exit
236 // code 1. This is a helper function for the ExitStatusPredicateTest
237 // test suite.
238 static int KilledExitStatus(int signum) {
239  pid_t child_pid = fork();
240  if (child_pid == 0) {
241  raise(signum);
242  _exit(1);
243  }
244  int status;
245  waitpid(child_pid, &status, 0);
246  return status;
247 }
248 
249 // Tests the ExitedWithCode predicate.
250 TEST(ExitStatusPredicateTest, ExitedWithCode) {
251  const int status0 = NormalExitStatus(0);
252  const int status1 = NormalExitStatus(1);
253  const int status42 = NormalExitStatus(42);
254  const testing::ExitedWithCode pred0(0);
255  const testing::ExitedWithCode pred1(1);
256  const testing::ExitedWithCode pred42(42);
257  EXPECT_PRED1(pred0, status0);
258  EXPECT_PRED1(pred1, status1);
259  EXPECT_PRED1(pred42, status42);
260  EXPECT_FALSE(pred0(status1));
261  EXPECT_FALSE(pred42(status0));
262  EXPECT_FALSE(pred1(status42));
263 }
264 
265 // Tests the KilledBySignal predicate.
266 TEST(ExitStatusPredicateTest, KilledBySignal) {
267  const int status_segv = KilledExitStatus(SIGSEGV);
268  const int status_kill = KilledExitStatus(SIGKILL);
269  const testing::KilledBySignal pred_segv(SIGSEGV);
270  const testing::KilledBySignal pred_kill(SIGKILL);
271  EXPECT_PRED1(pred_segv, status_segv);
272  EXPECT_PRED1(pred_kill, status_kill);
273  EXPECT_FALSE(pred_segv(status_kill));
274  EXPECT_FALSE(pred_kill(status_segv));
275 }
276 
277 # endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA
278 
279 // Tests that the death test macros expand to code which may or may not
280 // be followed by operator<<, and that in either case the complete text
281 // comprises only a single C++ statement.
282 TEST_F(TestForDeathTest, SingleStatement) {
283  if (AlwaysFalse())
284  // This would fail if executed; this is a compilation test only
285  ASSERT_DEATH(return, "");
286 
287  if (AlwaysTrue())
288  EXPECT_DEATH(_exit(1), "");
289  else
290  // This empty "else" branch is meant to ensure that EXPECT_DEATH
291  // doesn't expand into an "if" statement without an "else"
292  ;
293 
294  if (AlwaysFalse())
295  ASSERT_DEATH(return, "") << "did not die";
296 
297  if (AlwaysFalse())
298  ;
299  else
300  EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
301 }
302 
303 # if GTEST_USES_PCRE
304 
305 void DieWithEmbeddedNul() {
306  fprintf(stderr, "Hello%cmy null world.\n", '\0');
307  fflush(stderr);
308  _exit(1);
309 }
310 
311 // Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
312 // message has a NUL character in it.
313 TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
314  EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
315  ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
316 }
317 
318 # endif // GTEST_USES_PCRE
319 
320 // Tests that death test macros expand to code which interacts well with switch
321 // statements.
322 TEST_F(TestForDeathTest, SwitchStatement) {
323  // Microsoft compiler usually complains about switch statements without
324  // case labels. We suppress that warning for this test.
326 
327  switch (0)
328  default:
329  ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
330 
331  switch (0)
332  case 0:
333  EXPECT_DEATH(_exit(1), "") << "exit in switch case";
334 
336 }
337 
338 // Tests that a static member function can be used in a "fast" style
339 // death test.
340 TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
341  testing::GTEST_FLAG(death_test_style) = "fast";
342  ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
343 }
344 
345 // Tests that a method of the test fixture can be used in a "fast"
346 // style death test.
347 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
348  testing::GTEST_FLAG(death_test_style) = "fast";
349  should_die_ = true;
350  EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
351 }
352 
353 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
354 
355 // Tests that death tests work even if the current directory has been
356 // changed.
357 TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
358  testing::GTEST_FLAG(death_test_style) = "fast";
359 
360  ChangeToRootDir();
361  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
362 
363  ChangeToRootDir();
364  ASSERT_DEATH(_exit(1), "");
365 }
366 
367 # if GTEST_OS_LINUX
368 void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
369 
370 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
371 void SetSigprofActionAndTimer() {
372  struct itimerval timer;
373  timer.it_interval.tv_sec = 0;
374  timer.it_interval.tv_usec = 1;
375  timer.it_value = timer.it_interval;
376  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
377  struct sigaction signal_action;
378  memset(&signal_action, 0, sizeof(signal_action));
379  sigemptyset(&signal_action.sa_mask);
380  signal_action.sa_sigaction = SigprofAction;
381  signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
382  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr));
383 }
384 
385 // Disables ITIMER_PROF timer and ignores SIGPROF signal.
386 void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
387  struct itimerval timer;
388  timer.it_interval.tv_sec = 0;
389  timer.it_interval.tv_usec = 0;
390  timer.it_value = timer.it_interval;
391  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
392  struct sigaction signal_action;
393  memset(&signal_action, 0, sizeof(signal_action));
394  sigemptyset(&signal_action.sa_mask);
395  signal_action.sa_handler = SIG_IGN;
396  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
397 }
398 
399 // Tests that death tests work when SIGPROF handler and timer are set.
400 TEST_F(TestForDeathTest, FastSigprofActionSet) {
401  testing::GTEST_FLAG(death_test_style) = "fast";
402  SetSigprofActionAndTimer();
403  EXPECT_DEATH(_exit(1), "");
404  struct sigaction old_signal_action;
405  DisableSigprofActionAndTimer(&old_signal_action);
406  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
407 }
408 
409 TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
410  testing::GTEST_FLAG(death_test_style) = "threadsafe";
411  SetSigprofActionAndTimer();
412  EXPECT_DEATH(_exit(1), "");
413  struct sigaction old_signal_action;
414  DisableSigprofActionAndTimer(&old_signal_action);
415  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
416 }
417 # endif // GTEST_OS_LINUX
418 
419 // Repeats a representative sample of death tests in the "threadsafe" style:
420 
421 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
422  testing::GTEST_FLAG(death_test_style) = "threadsafe";
423  ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
424 }
425 
426 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
427  testing::GTEST_FLAG(death_test_style) = "threadsafe";
428  should_die_ = true;
429  EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
430 }
431 
432 TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
433  testing::GTEST_FLAG(death_test_style) = "threadsafe";
434 
435  for (int i = 0; i < 3; ++i)
436  EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
437 }
438 
439 TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
440  testing::GTEST_FLAG(death_test_style) = "threadsafe";
441 
442  ChangeToRootDir();
443  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
444 
445  ChangeToRootDir();
446  ASSERT_DEATH(_exit(1), "");
447 }
448 
449 TEST_F(TestForDeathTest, MixedStyles) {
450  testing::GTEST_FLAG(death_test_style) = "threadsafe";
451  EXPECT_DEATH(_exit(1), "");
452  testing::GTEST_FLAG(death_test_style) = "fast";
453  EXPECT_DEATH(_exit(1), "");
454 }
455 
456 # if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
457 
458 bool pthread_flag;
459 
460 void SetPthreadFlag() {
461  pthread_flag = true;
462 }
463 
464 TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
465  if (!testing::GTEST_FLAG(death_test_use_fork)) {
466  testing::GTEST_FLAG(death_test_style) = "threadsafe";
467  pthread_flag = false;
468  ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr));
469  ASSERT_DEATH(_exit(1), "");
470  ASSERT_FALSE(pthread_flag);
471  }
472 }
473 
474 # endif // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
475 
476 // Tests that a method of another class can be used in a death test.
477 TEST_F(TestForDeathTest, MethodOfAnotherClass) {
478  const MayDie x(true);
479  ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
480 }
481 
482 // Tests that a global function can be used in a death test.
483 TEST_F(TestForDeathTest, GlobalFunction) {
484  EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
485 }
486 
487 // Tests that any value convertible to an RE works as a second
488 // argument to EXPECT_DEATH.
489 TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
490  static const char regex_c_str[] = "GlobalFunction";
491  EXPECT_DEATH(GlobalFunction(), regex_c_str);
492 
493  const testing::internal::RE regex(regex_c_str);
494  EXPECT_DEATH(GlobalFunction(), regex);
495 
496 # if GTEST_HAS_GLOBAL_STRING
497 
498  const ::string regex_str(regex_c_str);
499  EXPECT_DEATH(GlobalFunction(), regex_str);
500 
501  // This one is tricky; a temporary pointer into another temporary. Reference
502  // lifetime extension of the pointer is not sufficient.
503  EXPECT_DEATH(GlobalFunction(), ::string(regex_c_str).c_str());
504 
505 # endif // GTEST_HAS_GLOBAL_STRING
506 
507 # if !GTEST_USES_PCRE
508 
509  const ::std::string regex_std_str(regex_c_str);
510  EXPECT_DEATH(GlobalFunction(), regex_std_str);
511 
512  // This one is tricky; a temporary pointer into another temporary. Reference
513  // lifetime extension of the pointer is not sufficient.
514  EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());
515 
516 # endif // !GTEST_USES_PCRE
517 }
518 
519 // Tests that a non-void function can be used in a death test.
520 TEST_F(TestForDeathTest, NonVoidFunction) {
521  ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
522 }
523 
524 // Tests that functions that take parameter(s) can be used in a death test.
525 TEST_F(TestForDeathTest, FunctionWithParameter) {
526  EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
527  EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
528 }
529 
530 // Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
531 TEST_F(TestForDeathTest, OutsideFixture) {
532  DeathTestSubroutine();
533 }
534 
535 // Tests that death tests can be done inside a loop.
536 TEST_F(TestForDeathTest, InsideLoop) {
537  for (int i = 0; i < 5; i++) {
538  EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
539  }
540 }
541 
542 // Tests that a compound statement can be used in a death test.
543 TEST_F(TestForDeathTest, CompoundStatement) {
544  EXPECT_DEATH({ // NOLINT
545  const int x = 2;
546  const int y = x + 1;
547  DieIfLessThan(x, y);
548  },
549  "DieIfLessThan");
550 }
551 
552 // Tests that code that doesn't die causes a death test to fail.
553 TEST_F(TestForDeathTest, DoesNotDie) {
554  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
555  "failed to die");
556 }
557 
558 // Tests that a death test fails when the error message isn't expected.
559 TEST_F(TestForDeathTest, ErrorMessageMismatch) {
560  EXPECT_NONFATAL_FAILURE({ // NOLINT
561  EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
562  }, "died but not with expected error");
563 }
564 
565 // On exit, *aborted will be true iff the EXPECT_DEATH() statement
566 // aborted the function.
567 void ExpectDeathTestHelper(bool* aborted) {
568  *aborted = true;
569  EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
570  *aborted = false;
571 }
572 
573 // Tests that EXPECT_DEATH doesn't abort the test on failure.
574 TEST_F(TestForDeathTest, EXPECT_DEATH) {
575  bool aborted = true;
576  EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
577  "failed to die");
578  EXPECT_FALSE(aborted);
579 }
580 
581 // Tests that ASSERT_DEATH does abort the test on failure.
582 TEST_F(TestForDeathTest, ASSERT_DEATH) {
583  static bool aborted;
584  EXPECT_FATAL_FAILURE({ // NOLINT
585  aborted = true;
586  ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
587  aborted = false;
588  }, "failed to die");
589  EXPECT_TRUE(aborted);
590 }
591 
592 // Tests that EXPECT_DEATH evaluates the arguments exactly once.
593 TEST_F(TestForDeathTest, SingleEvaluation) {
594  int x = 3;
595  EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
596 
597  const char* regex = "DieIf";
598  const char* regex_save = regex;
599  EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
600  EXPECT_EQ(regex_save + 1, regex);
601 }
602 
603 // Tests that run-away death tests are reported as failures.
604 TEST_F(TestForDeathTest, RunawayIsFailure) {
605  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
606  "failed to die.");
607 }
608 
609 // Tests that death tests report executing 'return' in the statement as
610 // failure.
611 TEST_F(TestForDeathTest, ReturnIsFailure) {
612  EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
613  "illegal return in test statement.");
614 }
615 
616 // Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
617 // message to it, and in debug mode it:
618 // 1. Asserts on death.
619 // 2. Has no side effect.
620 //
621 // And in opt mode, it:
622 // 1. Has side effects but does not assert.
623 TEST_F(TestForDeathTest, TestExpectDebugDeath) {
624  int sideeffect = 0;
625 
626  // Put the regex in a local variable to make sure we don't get an "unused"
627  // warning in opt mode.
628  const char* regex = "death.*DieInDebugElse12";
629 
630  EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)
631  << "Must accept a streamed message";
632 
633 # ifdef NDEBUG
634 
635  // Checks that the assignment occurs in opt mode (sideeffect).
636  EXPECT_EQ(12, sideeffect);
637 
638 # else
639 
640  // Checks that the assignment does not occur in dbg mode (no sideeffect).
641  EXPECT_EQ(0, sideeffect);
642 
643 # endif
644 }
645 
646 // Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
647 // message to it, and in debug mode it:
648 // 1. Asserts on death.
649 // 2. Has no side effect.
650 //
651 // And in opt mode, it:
652 // 1. Has side effects but does not assert.
653 TEST_F(TestForDeathTest, TestAssertDebugDeath) {
654  int sideeffect = 0;
655 
656  ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
657  << "Must accept a streamed message";
658 
659 # ifdef NDEBUG
660 
661  // Checks that the assignment occurs in opt mode (sideeffect).
662  EXPECT_EQ(12, sideeffect);
663 
664 # else
665 
666  // Checks that the assignment does not occur in dbg mode (no sideeffect).
667  EXPECT_EQ(0, sideeffect);
668 
669 # endif
670 }
671 
672 # ifndef NDEBUG
673 
674 void ExpectDebugDeathHelper(bool* aborted) {
675  *aborted = true;
676  EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
677  *aborted = false;
678 }
679 
680 # if GTEST_OS_WINDOWS
681 TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
682  printf("This test should be considered failing if it shows "
683  "any pop-up dialogs.\n");
684  fflush(stdout);
685 
686  EXPECT_DEATH({
687  testing::GTEST_FLAG(catch_exceptions) = false;
688  abort();
689  }, "");
690 }
691 # endif // GTEST_OS_WINDOWS
692 
693 // Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
694 // the function.
695 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
696  bool aborted = true;
697  EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
698  EXPECT_FALSE(aborted);
699 }
700 
701 void AssertDebugDeathHelper(bool* aborted) {
702  *aborted = true;
703  GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH";
704  ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "")
705  << "This is expected to fail.";
706  GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH";
707  *aborted = false;
708 }
709 
710 // Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
711 // failure.
712 TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
713  static bool aborted;
714  aborted = false;
715  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
716  EXPECT_TRUE(aborted);
717 }
718 
719 TEST_F(TestForDeathTest, AssertDebugDeathAborts2) {
720  static bool aborted;
721  aborted = false;
722  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
723  EXPECT_TRUE(aborted);
724 }
725 
726 TEST_F(TestForDeathTest, AssertDebugDeathAborts3) {
727  static bool aborted;
728  aborted = false;
729  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
730  EXPECT_TRUE(aborted);
731 }
732 
733 TEST_F(TestForDeathTest, AssertDebugDeathAborts4) {
734  static bool aborted;
735  aborted = false;
736  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
737  EXPECT_TRUE(aborted);
738 }
739 
740 TEST_F(TestForDeathTest, AssertDebugDeathAborts5) {
741  static bool aborted;
742  aborted = false;
743  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
744  EXPECT_TRUE(aborted);
745 }
746 
747 TEST_F(TestForDeathTest, AssertDebugDeathAborts6) {
748  static bool aborted;
749  aborted = false;
750  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
751  EXPECT_TRUE(aborted);
752 }
753 
754 TEST_F(TestForDeathTest, AssertDebugDeathAborts7) {
755  static bool aborted;
756  aborted = false;
757  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
758  EXPECT_TRUE(aborted);
759 }
760 
761 TEST_F(TestForDeathTest, AssertDebugDeathAborts8) {
762  static bool aborted;
763  aborted = false;
764  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
765  EXPECT_TRUE(aborted);
766 }
767 
768 TEST_F(TestForDeathTest, AssertDebugDeathAborts9) {
769  static bool aborted;
770  aborted = false;
771  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
772  EXPECT_TRUE(aborted);
773 }
774 
775 TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
776  static bool aborted;
777  aborted = false;
778  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
779  EXPECT_TRUE(aborted);
780 }
781 
782 # endif // _NDEBUG
783 
784 // Tests the *_EXIT family of macros, using a variety of predicates.
785 static void TestExitMacros() {
786  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
787  ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
788 
789 # if GTEST_OS_WINDOWS
790 
791  // Of all signals effects on the process exit code, only those of SIGABRT
792  // are documented on Windows.
793  // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.
794  EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
795 
796 # elif !GTEST_OS_FUCHSIA
797 
798  // Fuchsia has no unix signals.
799  EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
800  ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
801 
802  EXPECT_FATAL_FAILURE({ // NOLINT
803  ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
804  << "This failure is expected, too.";
805  }, "This failure is expected, too.");
806 
807 # endif // GTEST_OS_WINDOWS
808 
809  EXPECT_NONFATAL_FAILURE({ // NOLINT
810  EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
811  << "This failure is expected.";
812  }, "This failure is expected.");
813 }
814 
815 TEST_F(TestForDeathTest, ExitMacros) {
816  TestExitMacros();
817 }
818 
819 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
820  testing::GTEST_FLAG(death_test_use_fork) = true;
821  TestExitMacros();
822 }
823 
824 TEST_F(TestForDeathTest, InvalidStyle) {
825  testing::GTEST_FLAG(death_test_style) = "rococo";
826  EXPECT_NONFATAL_FAILURE({ // NOLINT
827  EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
828  }, "This failure is expected.");
829 }
830 
831 TEST_F(TestForDeathTest, DeathTestFailedOutput) {
832  testing::GTEST_FLAG(death_test_style) = "fast";
834  EXPECT_DEATH(DieWithMessage("death\n"),
835  "expected message"),
836  "Actual msg:\n"
837  "[ DEATH ] death\n");
838 }
839 
840 TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
841  testing::GTEST_FLAG(death_test_style) = "fast";
843  EXPECT_DEATH({
844  fprintf(stderr, "returning\n");
845  fflush(stderr);
846  return;
847  }, ""),
848  " Result: illegal return in test statement.\n"
849  " Error msg:\n"
850  "[ DEATH ] returning\n");
851 }
852 
853 TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
854  testing::GTEST_FLAG(death_test_style) = "fast";
856  EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
857  testing::ExitedWithCode(3),
858  "expected message"),
859  " Result: died but not with expected exit code:\n"
860  " Exited with exit status 1\n"
861  "Actual msg:\n"
862  "[ DEATH ] exiting with rc 1\n");
863 }
864 
865 TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
866  testing::GTEST_FLAG(death_test_style) = "fast";
868  EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
869  "line 1\nxyz\nline 3\n"),
870  "Actual msg:\n"
871  "[ DEATH ] line 1\n"
872  "[ DEATH ] line 2\n"
873  "[ DEATH ] line 3\n");
874 }
875 
876 TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
877  testing::GTEST_FLAG(death_test_style) = "fast";
878  EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
879  "line 1\nline 2\nline 3\n");
880 }
881 
882 // A DeathTestFactory that returns MockDeathTests.
883 class MockDeathTestFactory : public DeathTestFactory {
884  public:
885  MockDeathTestFactory();
886  bool Create(const char* statement,
887  testing::Matcher<const std::string&> matcher, const char* file,
888  int line, DeathTest** test) override;
889 
890  // Sets the parameters for subsequent calls to Create.
891  void SetParameters(bool create, DeathTest::TestRole role,
892  int status, bool passed);
893 
894  // Accessors.
895  int AssumeRoleCalls() const { return assume_role_calls_; }
896  int WaitCalls() const { return wait_calls_; }
897  size_t PassedCalls() const { return passed_args_.size(); }
898  bool PassedArgument(int n) const { return passed_args_[n]; }
899  size_t AbortCalls() const { return abort_args_.size(); }
900  DeathTest::AbortReason AbortArgument(int n) const {
901  return abort_args_[n];
902  }
903  bool TestDeleted() const { return test_deleted_; }
904 
905  private:
906  friend class MockDeathTest;
907  // If true, Create will return a MockDeathTest; otherwise it returns
908  // NULL.
909  bool create_;
910  // The value a MockDeathTest will return from its AssumeRole method.
911  DeathTest::TestRole role_;
912  // The value a MockDeathTest will return from its Wait method.
913  int status_;
914  // The value a MockDeathTest will return from its Passed method.
915  bool passed_;
916 
917  // Number of times AssumeRole was called.
918  int assume_role_calls_;
919  // Number of times Wait was called.
920  int wait_calls_;
921  // The arguments to the calls to Passed since the last call to
922  // SetParameters.
923  std::vector<bool> passed_args_;
924  // The arguments to the calls to Abort since the last call to
925  // SetParameters.
926  std::vector<DeathTest::AbortReason> abort_args_;
927  // True if the last MockDeathTest returned by Create has been
928  // deleted.
929  bool test_deleted_;
930 };
931 
932 
933 // A DeathTest implementation useful in testing. It returns values set
934 // at its creation from its various inherited DeathTest methods, and
935 // reports calls to those methods to its parent MockDeathTestFactory
936 // object.
937 class MockDeathTest : public DeathTest {
938  public:
939  MockDeathTest(MockDeathTestFactory *parent,
940  TestRole role, int status, bool passed) :
941  parent_(parent), role_(role), status_(status), passed_(passed) {
942  }
943  ~MockDeathTest() override { parent_->test_deleted_ = true; }
944  TestRole AssumeRole() override {
945  ++parent_->assume_role_calls_;
946  return role_;
947  }
948  int Wait() override {
949  ++parent_->wait_calls_;
950  return status_;
951  }
952  bool Passed(bool exit_status_ok) override {
953  parent_->passed_args_.push_back(exit_status_ok);
954  return passed_;
955  }
956  void Abort(AbortReason reason) override {
957  parent_->abort_args_.push_back(reason);
958  }
959 
960  private:
961  MockDeathTestFactory* const parent_;
962  const TestRole role_;
963  const int status_;
964  const bool passed_;
965 };
966 
967 
968 // MockDeathTestFactory constructor.
969 MockDeathTestFactory::MockDeathTestFactory()
970  : create_(true),
971  role_(DeathTest::OVERSEE_TEST),
972  status_(0),
973  passed_(true),
974  assume_role_calls_(0),
975  wait_calls_(0),
976  passed_args_(),
977  abort_args_() {
978 }
979 
980 
981 // Sets the parameters for subsequent calls to Create.
982 void MockDeathTestFactory::SetParameters(bool create,
983  DeathTest::TestRole role,
984  int status, bool passed) {
985  create_ = create;
986  role_ = role;
987  status_ = status;
988  passed_ = passed;
989 
990  assume_role_calls_ = 0;
991  wait_calls_ = 0;
992  passed_args_.clear();
993  abort_args_.clear();
994 }
995 
996 
997 // Sets test to NULL (if create_ is false) or to the address of a new
998 // MockDeathTest object with parameters taken from the last call
999 // to SetParameters (if create_ is true). Always returns true.
1000 bool MockDeathTestFactory::Create(
1001  const char* /*statement*/, testing::Matcher<const std::string&> /*matcher*/,
1002  const char* /*file*/, int /*line*/, DeathTest** test) {
1003  test_deleted_ = false;
1004  if (create_) {
1005  *test = new MockDeathTest(this, role_, status_, passed_);
1006  } else {
1007  *test = nullptr;
1008  }
1009  return true;
1010 }
1011 
1012 // A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
1013 // It installs a MockDeathTestFactory that is used for the duration
1014 // of the test case.
1015 class MacroLogicDeathTest : public testing::Test {
1016  protected:
1017  static testing::internal::ReplaceDeathTestFactory* replacer_;
1018  static MockDeathTestFactory* factory_;
1019 
1020  static void SetUpTestSuite() {
1021  factory_ = new MockDeathTestFactory;
1022  replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
1023  }
1024 
1025  static void TearDownTestSuite() {
1026  delete replacer_;
1027  replacer_ = nullptr;
1028  delete factory_;
1029  factory_ = nullptr;
1030  }
1031 
1032  // Runs a death test that breaks the rules by returning. Such a death
1033  // test cannot be run directly from a test routine that uses a
1034  // MockDeathTest, or the remainder of the routine will not be executed.
1035  static void RunReturningDeathTest(bool* flag) {
1036  ASSERT_DEATH({ // NOLINT
1037  *flag = true;
1038  return;
1039  }, "");
1040  }
1041 };
1042 
1043 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ =
1044  nullptr;
1045 MockDeathTestFactory* MacroLogicDeathTest::factory_ = nullptr;
1046 
1047 // Test that nothing happens when the factory doesn't return a DeathTest:
1048 TEST_F(MacroLogicDeathTest, NothingHappens) {
1049  bool flag = false;
1050  factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
1051  EXPECT_DEATH(flag = true, "");
1052  EXPECT_FALSE(flag);
1053  EXPECT_EQ(0, factory_->AssumeRoleCalls());
1054  EXPECT_EQ(0, factory_->WaitCalls());
1055  EXPECT_EQ(0U, factory_->PassedCalls());
1056  EXPECT_EQ(0U, factory_->AbortCalls());
1057  EXPECT_FALSE(factory_->TestDeleted());
1058 }
1059 
1060 // Test that the parent process doesn't run the death test code,
1061 // and that the Passed method returns false when the (simulated)
1062 // child process exits with status 0:
1063 TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
1064  bool flag = false;
1065  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
1066  EXPECT_DEATH(flag = true, "");
1067  EXPECT_FALSE(flag);
1068  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1069  EXPECT_EQ(1, factory_->WaitCalls());
1070  ASSERT_EQ(1U, factory_->PassedCalls());
1071  EXPECT_FALSE(factory_->PassedArgument(0));
1072  EXPECT_EQ(0U, factory_->AbortCalls());
1073  EXPECT_TRUE(factory_->TestDeleted());
1074 }
1075 
1076 // Tests that the Passed method was given the argument "true" when
1077 // the (simulated) child process exits with status 1:
1078 TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
1079  bool flag = false;
1080  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
1081  EXPECT_DEATH(flag = true, "");
1082  EXPECT_FALSE(flag);
1083  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1084  EXPECT_EQ(1, factory_->WaitCalls());
1085  ASSERT_EQ(1U, factory_->PassedCalls());
1086  EXPECT_TRUE(factory_->PassedArgument(0));
1087  EXPECT_EQ(0U, factory_->AbortCalls());
1088  EXPECT_TRUE(factory_->TestDeleted());
1089 }
1090 
1091 // Tests that the (simulated) child process executes the death test
1092 // code, and is aborted with the correct AbortReason if it
1093 // executes a return statement.
1094 TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
1095  bool flag = false;
1096  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1097  RunReturningDeathTest(&flag);
1098  EXPECT_TRUE(flag);
1099  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1100  EXPECT_EQ(0, factory_->WaitCalls());
1101  EXPECT_EQ(0U, factory_->PassedCalls());
1102  EXPECT_EQ(1U, factory_->AbortCalls());
1103  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1104  factory_->AbortArgument(0));
1105  EXPECT_TRUE(factory_->TestDeleted());
1106 }
1107 
1108 // Tests that the (simulated) child process is aborted with the
1109 // correct AbortReason if it does not die.
1110 TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
1111  bool flag = false;
1112  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
1113  EXPECT_DEATH(flag = true, "");
1114  EXPECT_TRUE(flag);
1115  EXPECT_EQ(1, factory_->AssumeRoleCalls());
1116  EXPECT_EQ(0, factory_->WaitCalls());
1117  EXPECT_EQ(0U, factory_->PassedCalls());
1118  // This time there are two calls to Abort: one since the test didn't
1119  // die, and another from the ReturnSentinel when it's destroyed. The
1120  // sentinel normally isn't destroyed if a test doesn't die, since
1121  // _exit(2) is called in that case by ForkingDeathTest, but not by
1122  // our MockDeathTest.
1123  ASSERT_EQ(2U, factory_->AbortCalls());
1124  EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
1125  factory_->AbortArgument(0));
1126  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
1127  factory_->AbortArgument(1));
1128  EXPECT_TRUE(factory_->TestDeleted());
1129 }
1130 
1131 // Tests that a successful death test does not register a successful
1132 // test part.
1133 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1134  EXPECT_DEATH(_exit(1), "");
1135  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
1136 }
1137 
1138 TEST(StreamingAssertionsDeathTest, DeathTest) {
1139  EXPECT_DEATH(_exit(1), "") << "unexpected failure";
1140  ASSERT_DEATH(_exit(1), "") << "unexpected failure";
1141  EXPECT_NONFATAL_FAILURE({ // NOLINT
1142  EXPECT_DEATH(_exit(0), "") << "expected failure";
1143  }, "expected failure");
1144  EXPECT_FATAL_FAILURE({ // NOLINT
1145  ASSERT_DEATH(_exit(0), "") << "expected failure";
1146  }, "expected failure");
1147 }
1148 
1149 // Tests that GetLastErrnoDescription returns an empty string when the
1150 // last error is 0 and non-empty string when it is non-zero.
1151 TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
1152  errno = ENOENT;
1153  EXPECT_STRNE("", GetLastErrnoDescription().c_str());
1154  errno = 0;
1155  EXPECT_STREQ("", GetLastErrnoDescription().c_str());
1156 }
1157 
1158 # if GTEST_OS_WINDOWS
1159 TEST(AutoHandleTest, AutoHandleWorks) {
1160  HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1162 
1163  // Tests that the AutoHandle is correctly initialized with a handle.
1164  testing::internal::AutoHandle auto_handle(handle);
1165  EXPECT_EQ(handle, auto_handle.Get());
1166 
1167  // Tests that Reset assigns INVALID_HANDLE_VALUE.
1168  // Note that this cannot verify whether the original handle is closed.
1169  auto_handle.Reset();
1170  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
1171 
1172  // Tests that Reset assigns the new handle.
1173  // Note that this cannot verify whether the original handle is closed.
1174  handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1176  auto_handle.Reset(handle);
1177  EXPECT_EQ(handle, auto_handle.Get());
1178 
1179  // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
1180  testing::internal::AutoHandle auto_handle2;
1181  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
1182 }
1183 # endif // GTEST_OS_WINDOWS
1184 
1185 # if GTEST_OS_WINDOWS
1186 typedef unsigned __int64 BiggestParsable;
1187 typedef signed __int64 BiggestSignedParsable;
1188 # else
1189 typedef unsigned long long BiggestParsable;
1190 typedef signed long long BiggestSignedParsable;
1191 # endif // GTEST_OS_WINDOWS
1192 
1193 // We cannot use std::numeric_limits<T>::max() as it clashes with the
1194 // max() macro defined by <windows.h>.
1195 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1196 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
1197 
1198 TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
1199  BiggestParsable result = 0;
1200 
1201  // Rejects non-numbers.
1202  EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
1203 
1204  // Rejects numbers with whitespace prefix.
1205  EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
1206 
1207  // Rejects negative numbers.
1208  EXPECT_FALSE(ParseNaturalNumber("-123", &result));
1209 
1210  // Rejects numbers starting with a plus sign.
1211  EXPECT_FALSE(ParseNaturalNumber("+123", &result));
1212  errno = 0;
1213 }
1214 
1215 TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
1216  BiggestParsable result = 0;
1217 
1218  EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
1219 
1220  signed char char_result = 0;
1221  EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
1222  errno = 0;
1223 }
1224 
1225 TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
1226  BiggestParsable result = 0;
1227 
1228  result = 0;
1229  ASSERT_TRUE(ParseNaturalNumber("123", &result));
1230  EXPECT_EQ(123U, result);
1231 
1232  // Check 0 as an edge case.
1233  result = 1;
1234  ASSERT_TRUE(ParseNaturalNumber("0", &result));
1235  EXPECT_EQ(0U, result);
1236 
1237  result = 1;
1238  ASSERT_TRUE(ParseNaturalNumber("00000", &result));
1239  EXPECT_EQ(0U, result);
1240 }
1241 
1242 TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
1243  Message msg;
1244  msg << kBiggestParsableMax;
1245 
1246  BiggestParsable result = 0;
1247  EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
1248  EXPECT_EQ(kBiggestParsableMax, result);
1249 
1250  Message msg2;
1251  msg2 << kBiggestSignedParsableMax;
1252 
1253  BiggestSignedParsable signed_result = 0;
1254  EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
1255  EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
1256 
1257  Message msg3;
1258  msg3 << INT_MAX;
1259 
1260  int int_result = 0;
1261  EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
1262  EXPECT_EQ(INT_MAX, int_result);
1263 
1264  Message msg4;
1265  msg4 << UINT_MAX;
1266 
1267  unsigned int uint_result = 0;
1268  EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
1269  EXPECT_EQ(UINT_MAX, uint_result);
1270 }
1271 
1272 TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
1273  short short_result = 0;
1274  ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
1275  EXPECT_EQ(123, short_result);
1276 
1277  signed char char_result = 0;
1278  ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
1279  EXPECT_EQ(123, char_result);
1280 }
1281 
1282 # if GTEST_OS_WINDOWS
1283 TEST(EnvironmentTest, HandleFitsIntoSizeT) {
1284  ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
1285 }
1286 # endif // GTEST_OS_WINDOWS
1287 
1288 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
1289 // failures when death tests are available on the system.
1290 TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
1291  EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
1292  "death inside CondDeathTestExpectMacro");
1293  ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
1294  "death inside CondDeathTestAssertMacro");
1295 
1296  // Empty statement will not crash, which must trigger a failure.
1299 }
1300 
1301 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
1302  testing::GTEST_FLAG(death_test_style) = "fast";
1303  EXPECT_FALSE(InDeathTestChild());
1304  EXPECT_DEATH({
1305  fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1306  fflush(stderr);
1307  _exit(1);
1308  }, "Inside");
1309 }
1310 
1311 TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
1312  testing::GTEST_FLAG(death_test_style) = "threadsafe";
1313  EXPECT_FALSE(InDeathTestChild());
1314  EXPECT_DEATH({
1315  fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
1316  fflush(stderr);
1317  _exit(1);
1318  }, "Inside");
1319 }
1320 
1321 void DieWithMessage(const char* message) {
1322  fputs(message, stderr);
1323  fflush(stderr); // Make sure the text is printed before the process exits.
1324  _exit(1);
1325 }
1326 
1327 TEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {
1328  // googletest tests this, of course; here we ensure that including googlemock
1329  // has not broken it.
1330  EXPECT_DEATH(DieWithMessage("O, I die, Horatio."), "I d[aeiou]e");
1331 }
1332 
1333 TEST(MatcherDeathTest, MonomorphicMatcherMatches) {
1334  EXPECT_DEATH(DieWithMessage("Behind O, I am slain!"),
1335  Matcher<const std::string&>(ContainsRegex("I am slain")));
1336 }
1337 
1338 TEST(MatcherDeathTest, MonomorphicMatcherDoesNotMatch) {
1340  EXPECT_DEATH(
1341  DieWithMessage("Behind O, I am slain!"),
1342  Matcher<const std::string&>(ContainsRegex("Ow, I am slain"))),
1343  "Expected: contains regular expression \"Ow, I am slain\"");
1344 }
1345 
1346 TEST(MatcherDeathTest, PolymorphicMatcherMatches) {
1347  EXPECT_DEATH(DieWithMessage("The rest is silence."),
1348  ContainsRegex("rest is silence"));
1349 }
1350 
1351 TEST(MatcherDeathTest, PolymorphicMatcherDoesNotMatch) {
1353  EXPECT_DEATH(DieWithMessage("The rest is silence."),
1354  ContainsRegex("rest is science")),
1355  "Expected: contains regular expression \"rest is science\"");
1356 }
1357 
1358 } // namespace
1359 
1360 #else // !GTEST_HAS_DEATH_TEST follows
1361 
1362 namespace {
1363 
1366 
1367 // Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
1368 // defined but do not trigger failures when death tests are not available on
1369 // the system.
1370 TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
1371  // Empty statement will not crash, but that should not trigger a failure
1372  // when death tests are not supported.
1373  CaptureStderr();
1376  ASSERT_TRUE(NULL != strstr(output.c_str(),
1377  "Death tests are not supported on this platform"));
1378  ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1379 
1380  // The streamed message should not be printed as there is no test failure.
1381  CaptureStderr();
1382  EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
1384  ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1385 
1386  CaptureStderr();
1387  ASSERT_DEATH_IF_SUPPORTED(;, ""); // NOLINT
1389  ASSERT_TRUE(NULL != strstr(output.c_str(),
1390  "Death tests are not supported on this platform"));
1391  ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1392 
1393  CaptureStderr();
1394  ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message"; // NOLINT
1396  ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1397 }
1398 
1399 void FuncWithAssert(int* n) {
1400  ASSERT_DEATH_IF_SUPPORTED(return;, "");
1401  (*n)++;
1402 }
1403 
1404 // Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
1405 // function (as ASSERT_DEATH does) if death tests are not supported.
1406 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
1407  int n = 0;
1408  FuncWithAssert(&n);
1409  EXPECT_EQ(1, n);
1410 }
1411 
1412 } // namespace
1413 
1414 #endif // !GTEST_HAS_DEATH_TEST
1415 
1416 namespace {
1417 
1418 // Tests that the death test macros expand to code which may or may not
1419 // be followed by operator<<, and that in either case the complete text
1420 // comprises only a single C++ statement.
1421 //
1422 // The syntax should work whether death tests are available or not.
1423 TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
1424  if (AlwaysFalse())
1425  // This would fail if executed; this is a compilation test only
1426  ASSERT_DEATH_IF_SUPPORTED(return, "");
1427 
1428  if (AlwaysTrue())
1429  EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
1430  else
1431  // This empty "else" branch is meant to ensure that EXPECT_DEATH
1432  // doesn't expand into an "if" statement without an "else"
1433  ; // NOLINT
1434 
1435  if (AlwaysFalse())
1436  ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";
1437 
1438  if (AlwaysFalse())
1439  ; // NOLINT
1440  else
1441  EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
1442 }
1443 
1444 // Tests that conditional death test macros expand to code which interacts
1445 // well with switch statements.
1446 TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
1447  // Microsoft compiler usually complains about switch statements without
1448  // case labels. We suppress that warning for this test.
1450 
1451  switch (0)
1452  default:
1453  ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
1454  << "exit in default switch handler";
1455 
1456  switch (0)
1457  case 0:
1458  EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";
1459 
1461 }
1462 
1463 // Tests that a test case whose name ends with "DeathTest" works fine
1464 // on Windows.
1465 TEST(NotADeathTest, Test) {
1466  SUCCEED();
1467 }
1468 
1469 } // namespace
EXPECT_FALSE
#define EXPECT_FALSE(condition)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1970
_gevent_test_main.result
result
Definition: _gevent_test_main.py:96
flag
uint32_t flag
Definition: ssl_versions.cc:162
testing
Definition: aws_request_signer_test.cc:25
ASSERT_NE
#define ASSERT_NE(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2060
testing::ContainsRegex
PolymorphicMatcher< internal::MatchesRegexMatcher > ContainsRegex(const internal::RE *regex)
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:8835
GTEST_DISABLE_MSC_WARNINGS_PUSH_
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:308
memset
return memset(p, 0, total)
demumble_test.stdout
stdout
Definition: demumble_test.py:38
asyncio_get_stats.default
default
Definition: asyncio_get_stats.py:38
test
Definition: spinlock_test.cc:36
y
const double y
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3611
EXPECT_FATAL_FAILURE
#define EXPECT_FATAL_FAILURE(statement, substr)
testing::internal::GetUnitTestImpl
UnitTestImpl * GetUnitTestImpl()
Definition: gmock-gtest-all.cc:1334
testing::Test::SetUpTestSuite
static void SetUpTestSuite()
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:417
printf
_Use_decl_annotations_ int __cdecl printf(const char *_Format,...)
Definition: cs_driver.c:91
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
grpc::protobuf::Message
GRPC_CUSTOM_MESSAGE Message
Definition: include/grpcpp/impl/codegen/config_protobuf.h:78
file
Definition: bloaty/third_party/zlib/examples/gzappend.c:170
status
absl::Status status
Definition: rls.cc:251
testing::internal::posix::ChDir
int ChDir(const char *dir)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:2031
Abort
static void Abort(const char *fmt,...)
Definition: acountry.c:94
message
char * message
Definition: libuv/docs/code/tty-gravity/main.c:12
true
#define true
Definition: setup_once.h:324
testing::Test
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:402
python_utils.port_server.stderr
stderr
Definition: port_server.py:51
EXPECT_EQ
#define EXPECT_EQ(a, b)
Definition: iomgr/time_averaged_stats_test.cc:27
GTEST_LOG_
#define GTEST_LOG_(severity)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:975
in
const char * in
Definition: third_party/abseil-cpp/absl/strings/internal/str_format/parser_test.cc:391
generic_client_interceptor.create
def create(intercept_call)
Definition: generic_client_interceptor.py:55
GTEST_PATH_SEP_
#define GTEST_PATH_SEP_
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:1905
gen_stats_data.c_str
def c_str(s, encoding='ascii')
Definition: gen_stats_data.py:38
SIGKILL
#define SIGKILL
Definition: win.h:87
TEST
#define TEST(name, init_size,...)
Definition: arena_test.cc:75
gmock_output_test.output
output
Definition: bloaty/third_party/googletest/googlemock/test/gmock_output_test.py:175
ASSERT_DEATH_IF_SUPPORTED
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest-death-test.h:337
python_utils.jobset.INFO
INFO
Definition: jobset.py:111
testing::internal::AlwaysTrue
GTEST_API_ bool AlwaysTrue()
Definition: bloaty/third_party/googletest/googletest/src/gtest.cc:5712
testing::internal::AlwaysFalse
bool AlwaysFalse()
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-internal.h:817
EXPECT_STRNE
#define EXPECT_STRNE(s1, s2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2097
status_
absl::Status status_
Definition: outlier_detection.cc:404
x
int x
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3610
testing::Matcher
Definition: bloaty/third_party/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h:52
n
int n
Definition: abseil-cpp/absl/container/btree_test.cc:1080
EXPECT_DEATH_IF_SUPPORTED
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest-death-test.h:335
msg
std::string msg
Definition: client_interceptors_end2end_test.cc:372
testing::internal::CaptureStderr
GTEST_API_ void CaptureStderr()
Definition: gmock-gtest-all.cc:9591
EXPECT_STREQ
#define EXPECT_STREQ(s1, s2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2095
GTEST_FLAG
#define GTEST_FLAG(name)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:2169
EXPECT_PRED1
#define EXPECT_PRED1(pred, v1)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest_pred_impl.h:116
FALSE
const BOOL FALSE
Definition: undname.c:47
testing::Test::TearDownTestSuite
static void TearDownTestSuite()
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:427
testing::internal::posix
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:1963
SUCCEED
#define SUCCEED()
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1939
client.handler
handler
Definition: examples/python/multiprocessing/client.py:87
SA_RESTART
#define SA_RESTART
Definition: unix/signal.c:32
regen-readme.line
line
Definition: regen-readme.py:30
INVALID_HANDLE_VALUE
#define INVALID_HANDLE_VALUE
Definition: bloaty/third_party/zlib/contrib/minizip/iowin32.c:21
ASSERT_TRUE
#define ASSERT_TRUE(condition)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1973
ASSERT_FALSE
#define ASSERT_FALSE(condition)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1976
signal_action
signal_action
Definition: test-signal-multiple-loops.c:46
GTEST_DISABLE_MSC_WARNINGS_POP_
#define GTEST_DISABLE_MSC_WARNINGS_POP_()
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:309
EXPECT_TRUE
#define EXPECT_TRUE(condition)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1967
handle
static csh handle
Definition: test_arm_regression.c:16
internal
Definition: benchmark/test/output_test_helper.cc:20
EXPECT_NONFATAL_FAILURE
#define EXPECT_NONFATAL_FAILURE(statement, substr)
parent_
RefCountedPtr< GrpcLb > parent_
Definition: grpclb.cc:438
google::protobuf::compiler::objectivec::FilePath
string FilePath(const FileDescriptor *file)
Definition: bloaty/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc:404
run_tests.exit_code
int exit_code
Definition: run_tests.py:1701
testing::internal::RE
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:882
Test
Definition: hpack_parser_test.cc:43
Message
Definition: protobuf/php/ext/google/protobuf/message.c:53
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
ASSERT_EQ
#define ASSERT_EQ(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2056
testing::internal::GetCapturedStderr
GTEST_API_ std::string GetCapturedStderr()
Definition: gmock-gtest-all.cc:9601
TEST_F
#define TEST_F(test_fixture, test_name)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2367
absl::types_internal::AlwaysFalse
std::false_type AlwaysFalse
Definition: abseil-cpp/absl/types/internal/conformance_profile.h:367
timer
static uv_timer_t timer
Definition: test-callback-stack.c:34


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:40