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