source: gtest-1.7.0/test/gtest-death-test_test.cc@ 12775

Last change on this file since 12775 was 12746, checked in by hock@…, 10 years ago

integrated the Google Testing Framework (gtest)

and wrote an Hello World test, to ensure the framework is working..

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