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
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
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
69 namespace posix = ::testing::internal::posix;
70
71 using testing::Message;
72 using testing::internal::DeathTest;
73 using testing::internal::DeathTestFactory;
74 using testing::internal::FilePath;
75 using testing::internal::GetLastErrnoDescription;
76 using testing::internal::GetUnitTestImpl;
77 using testing::internal::InDeathTestChild;
78 using testing::internal::ParseNaturalNumber;
79
80 namespace testing {
81 namespace internal {
82
83 // A helper class whose objects replace the death test factory for a
84 // single UnitTest object during their lifetimes.
85 class ReplaceDeathTestFactory {
86 public:
ReplaceDeathTestFactory(DeathTestFactory * new_factory)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
~ReplaceDeathTestFactory()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
DieWithMessage(const::std::string & message)109 void 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
DieInside(const::std::string & function)125 void DieInside(const ::std::string& function) {
126 DieWithMessage("death inside " + function + "().");
127 }
128
129 // Tests that death tests work.
130
131 class TestForDeathTest : public testing::Test {
132 protected:
TestForDeathTest()133 TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
134
~TestForDeathTest()135 virtual ~TestForDeathTest() {
136 posix::ChDir(original_dir_.c_str());
137 }
138
139 // A static member function that's expected to die.
StaticMemberFunction()140 static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
141
142 // A method of the test fixture that may die.
MemberFunction()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.
154 class MayDie {
155 public:
MayDie(bool should_die)156 explicit MayDie(bool should_die) : should_die_(should_die) {}
157
158 // A member function that may die.
MemberFunction() const159 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.
GlobalFunction()170 void GlobalFunction() { DieInside("GlobalFunction"); }
171
172 // A non-void function that's expected to die.
NonVoidFunction()173 int NonVoidFunction() {
174 DieInside("NonVoidFunction");
175 return 1;
176 }
177
178 // A unary function that may die.
DieIf(bool should_die)179 void DieIf(bool should_die) {
180 if (should_die)
181 DieInside("DieIf");
182 }
183
184 // A binary function that may die.
DieIfLessThan(int x,int y)185 bool 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.
DeathTestSubroutine()193 void DeathTestSubroutine() {
194 EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
195 ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
196 }
197
198 // Death in dbg, not opt.
DieInDebugElse12(int * sideeffect)199 int 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.
TEST(ExitStatusPredicateTest,ExitedWithCode)214 TEST(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.
NormalExitStatus(int exit_code)229 static 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.
KilledExitStatus(int signum)244 static 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.
TEST(ExitStatusPredicateTest,ExitedWithCode)256 TEST(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.
TEST(ExitStatusPredicateTest,KilledBySignal)272 TEST(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.
TEST_F(TestForDeathTest,SingleStatement)288 TEST_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
DieWithEmbeddedNul()309 void 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.
TEST_F(TestForDeathTest,EmbeddedNulInMessage)318 TEST_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.
TEST_F(TestForDeathTest,SwitchStatement)328 TEST_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.
TEST_F(TestForDeathTest,StaticMemberFunctionFastStyle)351 TEST_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.
TEST_F(TestForDeathTest,MemberFunctionFastStyle)358 TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
359 testing::GTEST_FLAG(death_test_style) = "fast";
360 should_die_ = true;
361 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
362 }
363
ChangeToRootDir()364 void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
365
366 // Tests that death tests work even if the current directory has been
367 // changed.
TEST_F(TestForDeathTest,FastDeathTestInChangedDir)368 TEST_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
SigprofAction(int,siginfo_t *,void *)379 void SigprofAction(int, siginfo_t*, void*) { /* no op */ }
380
381 // Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
SetSigprofActionAndTimer()382 void 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.
DisableSigprofActionAndTimer(struct sigaction * old_signal_action)397 void 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.
TEST_F(TestForDeathTest,FastSigprofActionSet)411 TEST_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
TEST_F(TestForDeathTest,ThreadSafeSigprofActionSet)420 TEST_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
TEST_F(TestForDeathTest,StaticMemberFunctionThreadsafeStyle)432 TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
433 testing::GTEST_FLAG(death_test_style) = "threadsafe";
434 ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
435 }
436
TEST_F(TestForDeathTest,MemberFunctionThreadsafeStyle)437 TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
438 testing::GTEST_FLAG(death_test_style) = "threadsafe";
439 should_die_ = true;
440 EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
441 }
442
TEST_F(TestForDeathTest,ThreadsafeDeathTestInLoop)443 TEST_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
TEST_F(TestForDeathTest,ThreadsafeDeathTestInChangedDir)450 TEST_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
TEST_F(TestForDeathTest,MixedStyles)460 TEST_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
469 namespace {
470
471 bool pthread_flag;
472
SetPthreadFlag()473 void SetPthreadFlag() {
474 pthread_flag = true;
475 }
476
477 } // namespace
478
TEST_F(TestForDeathTest,DoesNotExecuteAtforkHooks)479 TEST_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.
TEST_F(TestForDeathTest,MethodOfAnotherClass)492 TEST_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.
TEST_F(TestForDeathTest,GlobalFunction)498 TEST_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.
TEST_F(TestForDeathTest,AcceptsAnythingConvertibleToRE)504 TEST_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.
TEST_F(TestForDeathTest,NonVoidFunction)523 TEST_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.
TEST_F(TestForDeathTest,FunctionWithParameter)528 TEST_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.
TEST_F(TestForDeathTest,OutsideFixture)534 TEST_F(TestForDeathTest, OutsideFixture) {
535 DeathTestSubroutine();
536 }
537
538 // Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest,InsideLoop)539 TEST_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.
TEST_F(TestForDeathTest,CompoundStatement)546 TEST_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.
TEST_F(TestForDeathTest,DoesNotDie)556 TEST_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.
TEST_F(TestForDeathTest,ErrorMessageMismatch)562 TEST_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.
ExpectDeathTestHelper(bool * aborted)570 void 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.
TEST_F(TestForDeathTest,EXPECT_DEATH)577 TEST_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.
TEST_F(TestForDeathTest,ASSERT_DEATH)585 TEST_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.
TEST_F(TestForDeathTest,SingleEvaluation)596 TEST_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.
TEST_F(TestForDeathTest,RunawayIsFailure)607 TEST_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.
TEST_F(TestForDeathTest,ReturnIsFailure)614 TEST_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.
TEST_F(TestForDeathTest,TestExpectDebugDeath)626 TEST_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.
TEST_F(TestForDeathTest,TestAssertDebugDeath)652 TEST_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
ExpectDebugDeathHelper(bool * aborted)673 void 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
TEST(PopUpDeathTest,DoesNotShowPopUpOnAbort)680 TEST(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.
TEST_F(TestForDeathTest,ExpectDebugDeathDoesNotAbort)694 TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
695 bool aborted = true;
696 EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
697 EXPECT_FALSE(aborted);
698 }
699
AssertDebugDeathHelper(bool * aborted)700 void 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.
TEST_F(TestForDeathTest,AssertDebugDeathAborts)708 TEST_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.
TestExitMacros()718 static 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
TEST_F(TestForDeathTest,ExitMacros)747 TEST_F(TestForDeathTest, ExitMacros) {
748 TestExitMacros();
749 }
750
TEST_F(TestForDeathTest,ExitMacrosUsingFork)751 TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
752 testing::GTEST_FLAG(death_test_use_fork) = true;
753 TestExitMacros();
754 }
755
TEST_F(TestForDeathTest,InvalidStyle)756 TEST_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
TEST_F(TestForDeathTest,DeathTestFailedOutput)763 TEST_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
TEST_F(TestForDeathTest,DeathTestUnexpectedReturnOutput)772 TEST_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
TEST_F(TestForDeathTest,DeathTestBadExitCodeOutput)785 TEST_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
TEST_F(TestForDeathTest,DeathTestMultiLineMatchFail)797 TEST_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
TEST_F(TestForDeathTest,DeathTestMultiLineMatchPass)808 TEST_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.
815 class 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.
AssumeRoleCalls() const827 int AssumeRoleCalls() const { return assume_role_calls_; }
WaitCalls() const828 int WaitCalls() const { return wait_calls_; }
PassedCalls() const829 int PassedCalls() const { return passed_args_.size(); }
PassedArgument(int n) const830 bool PassedArgument(int n) const { return passed_args_[n]; }
AbortCalls() const831 int AbortCalls() const { return abort_args_.size(); }
AbortArgument(int n) const832 DeathTest::AbortReason AbortArgument(int n) const {
833 return abort_args_[n];
834 }
TestDeleted() const835 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.
869 class MockDeathTest : public DeathTest {
870 public:
MockDeathTest(MockDeathTestFactory * parent,TestRole role,int status,bool passed)871 MockDeathTest(MockDeathTestFactory *parent,
872 TestRole role, int status, bool passed) :
873 parent_(parent), role_(role), status_(status), passed_(passed) {
874 }
~MockDeathTest()875 virtual ~MockDeathTest() {
876 parent_->test_deleted_ = true;
877 }
AssumeRole()878 virtual TestRole AssumeRole() {
879 ++parent_->assume_role_calls_;
880 return role_;
881 }
Wait()882 virtual int Wait() {
883 ++parent_->wait_calls_;
884 return status_;
885 }
Passed(bool exit_status_ok)886 virtual bool Passed(bool exit_status_ok) {
887 parent_->passed_args_.push_back(exit_status_ok);
888 return passed_;
889 }
Abort(AbortReason reason)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.
MockDeathTestFactory()903 MockDeathTestFactory::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.
SetParameters(bool create,DeathTest::TestRole role,int status,bool passed)916 void 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.
Create(const char *,const::testing::internal::RE *,const char *,int,DeathTest ** test)934 bool 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.
951 class MacroLogicDeathTest : public testing::Test {
952 protected:
953 static testing::internal::ReplaceDeathTestFactory* replacer_;
954 static MockDeathTestFactory* factory_;
955
SetUpTestCase()956 static void SetUpTestCase() {
957 factory_ = new MockDeathTestFactory;
958 replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
959 }
960
TearDownTestCase()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.
RunReturningDeathTest(bool * flag)971 static void RunReturningDeathTest(bool* flag) {
972 ASSERT_DEATH({ // NOLINT
973 *flag = true;
974 return;
975 }, "");
976 }
977 };
978
979 testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
980 = NULL;
981 MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
982
983
984 // Test that nothing happens when the factory doesn't return a DeathTest:
TEST_F(MacroLogicDeathTest,NothingHappens)985 TEST_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:
TEST_F(MacroLogicDeathTest,ChildExitsSuccessfully)1000 TEST_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:
TEST_F(MacroLogicDeathTest,ChildExitsUnsuccessfully)1015 TEST_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.
TEST_F(MacroLogicDeathTest,ChildPerformsReturn)1031 TEST_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.
TEST_F(MacroLogicDeathTest,ChildDoesNotDie)1047 TEST_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.
TEST(SuccessRegistrationDeathTest,NoSuccessPart)1070 TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1071 EXPECT_DEATH(_exit(1), "");
1072 EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
1073 }
1074
TEST(StreamingAssertionsDeathTest,DeathTest)1075 TEST(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.
TEST(GetLastErrnoDescription,GetLastErrnoDescriptionWorks)1088 TEST(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
TEST(AutoHandleTest,AutoHandleWorks)1096 TEST(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
1123 typedef unsigned __int64 BiggestParsable;
1124 typedef signed __int64 BiggestSignedParsable;
1125 # else
1126 typedef unsigned long long BiggestParsable;
1127 typedef 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>.
1132 const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1133 const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;
1134
TEST(ParseNaturalNumberTest,RejectsInvalidFormat)1135 TEST(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
TEST(ParseNaturalNumberTest,RejectsOverflownNumbers)1152 TEST(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
TEST(ParseNaturalNumberTest,AcceptsValidNumbers)1162 TEST(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
TEST(ParseNaturalNumberTest,AcceptsTypeLimits)1179 TEST(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
TEST(ParseNaturalNumberTest,WorksForShorterIntegers)1209 TEST(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
TEST(EnvironmentTest,HandleFitsIntoSizeT)1220 TEST(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.
TEST(ConditionalDeathMacrosDeathTest,ExpectsDeathWhenDeathTestsAvailable)1230 TEST(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
1243 using testing::internal::CaptureStderr;
1244 using 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.
TEST(ConditionalDeathMacrosTest,WarnsWhenDeathTestsNotAvailable)1249 TEST(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
FuncWithAssert(int * n)1278 void 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.
TEST(ConditionalDeathMacrosTest,AssertDeatDoesNotReturnhIfUnsupported)1285 TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
1286 int n = 0;
1287 FuncWithAssert(&n);
1288 EXPECT_EQ(1, n);
1289 }
1290
TEST(InDeathTestChildDeathTest,ReportsDeathTestCorrectlyInFastStyle)1291 TEST(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
TEST(InDeathTestChildDeathTest,ReportsDeathTestCorrectlyInThreadSafeStyle)1301 TEST(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.
TEST(ConditionalDeathMacrosSyntaxDeathTest,SingleStatement)1318 TEST(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.
TEST(ConditionalDeathMacrosSyntaxDeathTest,SwitchStatement)1341 TEST(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.
TEST(NotADeathTest,Test)1365 TEST(NotADeathTest, Test) {
1366 SUCCEED();
1367 }
1368