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