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