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