1
// Copyright 2005, Google Inc.
2
// All rights reserved.
4
// Redistribution and use in source and binary forms, with or without
5
// modification, are permitted provided that the following conditions are
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
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.
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.
30
// Author: wan@google.com (Zhanyong Wan)
32
// Tests for death tests.
34
#include <gtest/gtest-death-test.h>
35
#include <gtest/gtest.h>
36
#include <gtest/internal/gtest-filepath.h>
38
#if GTEST_HAS_DEATH_TEST
41
#include <direct.h> // For chdir().
44
#include <sys/wait.h> // For waitpid.
45
#include <limits> // For std::numeric_limits.
46
#endif // GTEST_OS_WINDOWS
52
#include <gtest/gtest-spi.h>
54
// Indicates that this translation unit is part of Google Test's
55
// implementation. It must come before gtest-internal-inl.h is
56
// included, or there will be a compiler error. This trick is to
57
// prevent a user from accidentally including gtest-internal-inl.h in
59
#define GTEST_IMPLEMENTATION_ 1
60
#include "src/gtest-internal-inl.h"
61
#undef GTEST_IMPLEMENTATION_
63
using testing::Message;
65
using testing::internal::DeathTest;
66
using testing::internal::DeathTestFactory;
67
using testing::internal::FilePath;
68
using testing::internal::GetLastSystemErrorMessage;
69
using testing::internal::ParseNaturalNumber;
70
using testing::internal::String;
75
// A helper class whose objects replace the death test factory for a
76
// single UnitTest object during their lifetimes.
77
class ReplaceDeathTestFactory {
79
ReplaceDeathTestFactory(UnitTest* parent, DeathTestFactory* new_factory)
80
: parent_impl_(parent->impl()) {
81
old_factory_ = parent_impl_->death_test_factory_.release();
82
parent_impl_->death_test_factory_.reset(new_factory);
85
~ReplaceDeathTestFactory() {
86
parent_impl_->death_test_factory_.release();
87
parent_impl_->death_test_factory_.reset(old_factory_);
90
// Prevents copying ReplaceDeathTestFactory objects.
91
ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
92
void operator=(const ReplaceDeathTestFactory&);
94
UnitTestImpl* parent_impl_;
95
DeathTestFactory* old_factory_;
98
} // namespace internal
99
} // namespace testing
101
// Tests that death tests work.
103
class TestForDeathTest : public testing::Test {
105
TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}
107
virtual ~TestForDeathTest() {
109
_chdir(original_dir_.c_str());
111
chdir(original_dir_.c_str());
115
// A static member function that's expected to die.
116
static void StaticMemberFunction() {
117
fprintf(stderr, "%s", "death inside StaticMemberFunction().");
119
// We call _exit() instead of exit(), as the former is a direct
120
// system call and thus safer in the presence of threads. exit()
121
// will invoke user-defined exit-hooks, which may do dangerous
122
// things that conflict with death tests.
126
// A method of the test fixture that may die.
127
void MemberFunction() {
129
fprintf(stderr, "%s", "death inside MemberFunction().");
135
// True iff MemberFunction() should die.
137
const FilePath original_dir_;
140
// A class with a member function that may die.
143
explicit MayDie(bool should_die) : should_die_(should_die) {}
145
// A member function that may die.
146
void MemberFunction() const {
148
GTEST_LOG_(FATAL, "death inside MayDie::MemberFunction().");
153
// True iff MemberFunction() should die.
157
// A global function that's expected to die.
158
void GlobalFunction() {
159
GTEST_LOG_(FATAL, "death inside GlobalFunction().");
162
// A non-void function that's expected to die.
163
int NonVoidFunction() {
164
GTEST_LOG_(FATAL, "death inside NonVoidFunction().");
168
// A unary function that may die.
169
void DieIf(bool should_die) {
171
GTEST_LOG_(FATAL, "death inside DieIf().");
175
// A binary function that may die.
176
bool DieIfLessThan(int x, int y) {
178
GTEST_LOG_(FATAL, "death inside DieIfLessThan().");
183
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
184
void DeathTestSubroutine() {
185
EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
186
ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
189
// Death in dbg, not opt.
190
int DieInDebugElse12(int* sideeffect) {
191
if (sideeffect) *sideeffect = 12;
193
GTEST_LOG_(FATAL, "debug death inside DieInDebugElse12()");
200
// Tests the ExitedWithCode predicate.
201
TEST(ExitStatusPredicateTest, ExitedWithCode) {
202
// On Windows, the process's exit code is the same as its exit status,
203
// so the predicate just compares the its input with its parameter.
204
EXPECT_TRUE(testing::ExitedWithCode(0)(0));
205
EXPECT_TRUE(testing::ExitedWithCode(1)(1));
206
EXPECT_TRUE(testing::ExitedWithCode(42)(42));
207
EXPECT_FALSE(testing::ExitedWithCode(0)(1));
208
EXPECT_FALSE(testing::ExitedWithCode(1)(0));
213
// Returns the exit status of a process that calls _exit(2) with a
214
// given exit code. This is a helper function for the
215
// ExitStatusPredicateTest test suite.
216
static int NormalExitStatus(int exit_code) {
217
pid_t child_pid = fork();
218
if (child_pid == 0) {
222
waitpid(child_pid, &status, 0);
226
// Returns the exit status of a process that raises a given signal.
227
// If the signal does not cause the process to die, then it returns
228
// instead the exit status of a process that exits normally with exit
229
// code 1. This is a helper function for the ExitStatusPredicateTest
231
static int KilledExitStatus(int signum) {
232
pid_t child_pid = fork();
233
if (child_pid == 0) {
238
waitpid(child_pid, &status, 0);
242
// Tests the ExitedWithCode predicate.
243
TEST(ExitStatusPredicateTest, ExitedWithCode) {
244
const int status0 = NormalExitStatus(0);
245
const int status1 = NormalExitStatus(1);
246
const int status42 = NormalExitStatus(42);
247
const testing::ExitedWithCode pred0(0);
248
const testing::ExitedWithCode pred1(1);
249
const testing::ExitedWithCode pred42(42);
250
EXPECT_PRED1(pred0, status0);
251
EXPECT_PRED1(pred1, status1);
252
EXPECT_PRED1(pred42, status42);
253
EXPECT_FALSE(pred0(status1));
254
EXPECT_FALSE(pred42(status0));
255
EXPECT_FALSE(pred1(status42));
258
// Tests the KilledBySignal predicate.
259
TEST(ExitStatusPredicateTest, KilledBySignal) {
260
const int status_segv = KilledExitStatus(SIGSEGV);
261
const int status_kill = KilledExitStatus(SIGKILL);
262
const testing::KilledBySignal pred_segv(SIGSEGV);
263
const testing::KilledBySignal pred_kill(SIGKILL);
264
EXPECT_PRED1(pred_segv, status_segv);
265
EXPECT_PRED1(pred_kill, status_kill);
266
EXPECT_FALSE(pred_segv(status_kill));
267
EXPECT_FALSE(pred_kill(status_segv));
270
#endif // GTEST_OS_WINDOWS
272
// Tests that the death test macros expand to code which may or may not
273
// be followed by operator<<, and that in either case the complete text
274
// comprises only a single C++ statement.
275
TEST_F(TestForDeathTest, SingleStatement) {
277
// This would fail if executed; this is a compilation test only
278
ASSERT_DEATH(return, "");
281
EXPECT_DEATH(_exit(1), "");
283
// This empty "else" branch is meant to ensure that EXPECT_DEATH
284
// doesn't expand into an "if" statement without an "else"
288
ASSERT_DEATH(return, "") << "did not die";
293
EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
296
void DieWithEmbeddedNul() {
297
fprintf(stderr, "Hello%cworld.\n", '\0');
303
// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
304
// message has a NUL character in it.
305
TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
306
// TODO(wan@google.com): <regex.h> doesn't support matching strings
307
// with embedded NUL characters - find a way to workaround it.
308
EXPECT_DEATH(DieWithEmbeddedNul(), "w.*ld");
309
ASSERT_DEATH(DieWithEmbeddedNul(), "w.*ld");
311
#endif // GTEST_USES_PCRE
313
// Tests that death test macros expand to code which interacts well with switch
315
TEST_F(TestForDeathTest, SwitchStatement) {
316
// Microsoft compiler usually complains about switch statements without
317
// case labels. We suppress that warning for this test.
319
#pragma warning(push)
320
#pragma warning(disable: 4065)
325
ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
329
EXPECT_DEATH(_exit(1), "") << "exit in switch case";
336
// Tests that a static member function can be used in a "fast" style
338
TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
339
testing::GTEST_FLAG(death_test_style) = "fast";
340
ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
343
// Tests that a method of the test fixture can be used in a "fast"
345
TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
346
testing::GTEST_FLAG(death_test_style) = "fast";
348
EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
351
void ChangeToRootDir() {
356
#endif // GTEST_OS_WINDOWS
359
// Tests that death tests work even if the current directory has been
361
TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
362
testing::GTEST_FLAG(death_test_style) = "fast";
365
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
368
ASSERT_DEATH(_exit(1), "");
371
// Repeats a representative sample of death tests in the "threadsafe" style:
373
TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
374
testing::GTEST_FLAG(death_test_style) = "threadsafe";
375
ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
378
TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
379
testing::GTEST_FLAG(death_test_style) = "threadsafe";
381
EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
384
TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
385
testing::GTEST_FLAG(death_test_style) = "threadsafe";
387
for (int i = 0; i < 3; ++i)
388
EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
391
TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
392
testing::GTEST_FLAG(death_test_style) = "threadsafe";
395
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
398
ASSERT_DEATH(_exit(1), "");
401
TEST_F(TestForDeathTest, MixedStyles) {
402
testing::GTEST_FLAG(death_test_style) = "threadsafe";
403
EXPECT_DEATH(_exit(1), "");
404
testing::GTEST_FLAG(death_test_style) = "fast";
405
EXPECT_DEATH(_exit(1), "");
412
void SetPthreadFlag() {
420
TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
421
if (!testing::GTEST_FLAG(death_test_use_fork)) {
422
testing::GTEST_FLAG(death_test_style) = "threadsafe";
423
pthread_flag = false;
424
ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
425
ASSERT_DEATH(_exit(1), "");
426
ASSERT_FALSE(pthread_flag);
430
#endif // GTEST_HAS_CLONE
432
// Tests that a method of another class can be used in a death test.
433
TEST_F(TestForDeathTest, MethodOfAnotherClass) {
434
const MayDie x(true);
435
ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
438
// Tests that a global function can be used in a death test.
439
TEST_F(TestForDeathTest, GlobalFunction) {
440
EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
443
// Tests that any value convertible to an RE works as a second
444
// argument to EXPECT_DEATH.
445
TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
446
static const char regex_c_str[] = "GlobalFunction";
447
EXPECT_DEATH(GlobalFunction(), regex_c_str);
449
const testing::internal::RE regex(regex_c_str);
450
EXPECT_DEATH(GlobalFunction(), regex);
452
#if GTEST_HAS_GLOBAL_STRING
453
const string regex_str(regex_c_str);
454
EXPECT_DEATH(GlobalFunction(), regex_str);
455
#endif // GTEST_HAS_GLOBAL_STRING
457
#if GTEST_HAS_STD_STRING
458
const ::std::string regex_std_str(regex_c_str);
459
EXPECT_DEATH(GlobalFunction(), regex_std_str);
460
#endif // GTEST_HAS_STD_STRING
463
// Tests that a non-void function can be used in a death test.
464
TEST_F(TestForDeathTest, NonVoidFunction) {
465
ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
468
// Tests that functions that take parameter(s) can be used in a death test.
469
TEST_F(TestForDeathTest, FunctionWithParameter) {
470
EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
471
EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
474
// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
475
TEST_F(TestForDeathTest, OutsideFixture) {
476
DeathTestSubroutine();
479
// Tests that death tests can be done inside a loop.
480
TEST_F(TestForDeathTest, InsideLoop) {
481
for (int i = 0; i < 5; i++) {
482
EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
486
// Tests that a compound statement can be used in a death test.
487
TEST_F(TestForDeathTest, CompoundStatement) {
488
EXPECT_DEATH({ // NOLINT
496
// Tests that code that doesn't die causes a death test to fail.
497
TEST_F(TestForDeathTest, DoesNotDie) {
498
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
502
// Tests that a death test fails when the error message isn't expected.
503
TEST_F(TestForDeathTest, ErrorMessageMismatch) {
504
EXPECT_NONFATAL_FAILURE({ // NOLINT
505
EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
506
}, "died but not with expected error");
509
// On exit, *aborted will be true iff the EXPECT_DEATH() statement
510
// aborted the function.
511
void ExpectDeathTestHelper(bool* aborted) {
513
EXPECT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
517
// Tests that EXPECT_DEATH doesn't abort the test on failure.
518
TEST_F(TestForDeathTest, EXPECT_DEATH) {
520
EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
522
EXPECT_FALSE(aborted);
525
// Tests that ASSERT_DEATH does abort the test on failure.
526
TEST_F(TestForDeathTest, ASSERT_DEATH) {
528
EXPECT_FATAL_FAILURE({ // NOLINT
530
ASSERT_DEATH(DieIf(false), "DieIf"); // This assertion should fail.
533
EXPECT_TRUE(aborted);
536
// Tests that EXPECT_DEATH evaluates the arguments exactly once.
537
TEST_F(TestForDeathTest, SingleEvaluation) {
539
EXPECT_DEATH(DieIf((++x) == 4), "DieIf");
541
const char* regex = "DieIf";
542
const char* regex_save = regex;
543
EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
544
EXPECT_EQ(regex_save + 1, regex);
547
// Tests that run-away death tests are reported as failures.
548
TEST_F(TestForDeathTest, Runaway) {
549
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
552
EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
553
"illegal return in test statement.");
557
// Tests that EXPECT_DEBUG_DEATH works as expected,
558
// that is, in debug mode, it:
559
// 1. Asserts on death.
560
// 2. Has no side effect.
562
// And in opt mode, it:
563
// 1. Has side effects but does not assert.
564
TEST_F(TestForDeathTest, TestExpectDebugDeath) {
567
EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect),
568
"death.*DieInDebugElse12");
571
// Checks that the assignment occurs in opt mode (sideeffect).
572
EXPECT_EQ(12, sideeffect);
574
// Checks that the assignment does not occur in dbg mode (no sideeffect).
575
EXPECT_EQ(0, sideeffect);
579
// Tests that ASSERT_DEBUG_DEATH works as expected
581
// 1. Asserts on debug death.
582
// 2. Has no side effect.
585
// 1. Has side effects and returns the expected value (12).
586
TEST_F(TestForDeathTest, TestAssertDebugDeath) {
589
ASSERT_DEBUG_DEATH({ // NOLINT
590
// Tests that the return value is 12 in opt mode.
591
EXPECT_EQ(12, DieInDebugElse12(&sideeffect));
592
// Tests that the side effect occurred in opt mode.
593
EXPECT_EQ(12, sideeffect);
594
}, "death.*DieInDebugElse12");
597
// Checks that the assignment occurs in opt mode (sideeffect).
598
EXPECT_EQ(12, sideeffect);
600
// Checks that the assignment does not occur in dbg mode (no sideeffect).
601
EXPECT_EQ(0, sideeffect);
607
void ExpectDebugDeathHelper(bool* aborted) {
609
EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
614
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
615
printf("This test should be considered failing if it shows "
616
"any pop-up dialogs.\n");
620
testing::GTEST_FLAG(catch_exceptions) = false;
625
TEST(PopUpDeathTest, DoesNotShowPopUpOnThrow) {
626
printf("This test should be considered failing if it shows "
627
"any pop-up dialogs.\n");
631
testing::GTEST_FLAG(catch_exceptions) = false;
635
#endif // GTEST_OS_WINDOWS
637
// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
639
TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
641
EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
642
EXPECT_FALSE(aborted);
645
void AssertDebugDeathHelper(bool* aborted) {
647
ASSERT_DEBUG_DEATH(return, "") << "This is expected to fail.";
651
// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
653
TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
656
EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
657
EXPECT_TRUE(aborted);
662
// Tests the *_EXIT family of macros, using a variety of predicates.
663
static void TestExitMacros() {
664
EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");
665
ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
669
testing::GTEST_FLAG(catch_exceptions) = false;
670
*static_cast<int*>(NULL) = 1;
671
}, testing::ExitedWithCode(0xC0000005), "") << "foo";
673
EXPECT_NONFATAL_FAILURE({ // NOLINT
675
testing::GTEST_FLAG(catch_exceptions) = false;
676
*static_cast<int*>(NULL) = 1;
677
}, testing::ExitedWithCode(0), "") << "This failure is expected.";
678
}, "This failure is expected.");
680
// Of all signals effects on the process exit code, only those of SIGABRT
681
// are documented on Windows.
682
// See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
683
EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "");
685
EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
686
ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";
688
EXPECT_FATAL_FAILURE({ // NOLINT
689
ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
690
<< "This failure is expected, too.";
691
}, "This failure is expected, too.");
692
#endif // GTEST_OS_WINDOWS
694
EXPECT_NONFATAL_FAILURE({ // NOLINT
695
EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
696
<< "This failure is expected.";
697
}, "This failure is expected.");
700
TEST_F(TestForDeathTest, ExitMacros) {
704
TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
705
testing::GTEST_FLAG(death_test_use_fork) = true;
709
TEST_F(TestForDeathTest, InvalidStyle) {
710
testing::GTEST_FLAG(death_test_style) = "rococo";
711
EXPECT_NONFATAL_FAILURE({ // NOLINT
712
EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
713
}, "This failure is expected.");
716
// A DeathTestFactory that returns MockDeathTests.
717
class MockDeathTestFactory : public DeathTestFactory {
719
MockDeathTestFactory();
720
virtual bool Create(const char* statement,
721
const ::testing::internal::RE* regex,
722
const char* file, int line, DeathTest** test);
724
// Sets the parameters for subsequent calls to Create.
725
void SetParameters(bool create, DeathTest::TestRole role,
726
int status, bool passed);
729
int AssumeRoleCalls() const { return assume_role_calls_; }
730
int WaitCalls() const { return wait_calls_; }
731
int PassedCalls() const { return passed_args_.size(); }
732
bool PassedArgument(int n) const { return passed_args_[n]; }
733
int AbortCalls() const { return abort_args_.size(); }
734
DeathTest::AbortReason AbortArgument(int n) const {
735
return abort_args_[n];
737
bool TestDeleted() const { return test_deleted_; }
740
friend class MockDeathTest;
741
// If true, Create will return a MockDeathTest; otherwise it returns
744
// The value a MockDeathTest will return from its AssumeRole method.
745
DeathTest::TestRole role_;
746
// The value a MockDeathTest will return from its Wait method.
748
// The value a MockDeathTest will return from its Passed method.
751
// Number of times AssumeRole was called.
752
int assume_role_calls_;
753
// Number of times Wait was called.
755
// The arguments to the calls to Passed since the last call to
757
std::vector<bool> passed_args_;
758
// The arguments to the calls to Abort since the last call to
760
std::vector<DeathTest::AbortReason> abort_args_;
761
// True if the last MockDeathTest returned by Create has been
767
// A DeathTest implementation useful in testing. It returns values set
768
// at its creation from its various inherited DeathTest methods, and
769
// reports calls to those methods to its parent MockDeathTestFactory
771
class MockDeathTest : public DeathTest {
773
MockDeathTest(MockDeathTestFactory *parent,
774
TestRole role, int status, bool passed) :
775
parent_(parent), role_(role), status_(status), passed_(passed) {
777
virtual ~MockDeathTest() {
778
parent_->test_deleted_ = true;
780
virtual TestRole AssumeRole() {
781
++parent_->assume_role_calls_;
785
++parent_->wait_calls_;
788
virtual bool Passed(bool exit_status_ok) {
789
parent_->passed_args_.push_back(exit_status_ok);
792
virtual void Abort(AbortReason reason) {
793
parent_->abort_args_.push_back(reason);
796
MockDeathTestFactory* const parent_;
797
const TestRole role_;
803
// MockDeathTestFactory constructor.
804
MockDeathTestFactory::MockDeathTestFactory()
806
role_(DeathTest::OVERSEE_TEST),
809
assume_role_calls_(0),
816
// Sets the parameters for subsequent calls to Create.
817
void MockDeathTestFactory::SetParameters(bool create,
818
DeathTest::TestRole role,
819
int status, bool passed) {
825
assume_role_calls_ = 0;
827
passed_args_.clear();
832
// Sets test to NULL (if create_ is false) or to the address of a new
833
// MockDeathTest object with parameters taken from the last call
834
// to SetParameters (if create_ is true). Always returns true.
835
bool MockDeathTestFactory::Create(const char* statement,
836
const ::testing::internal::RE* regex,
837
const char* file, int line,
839
test_deleted_ = false;
841
*test = new MockDeathTest(this, role_, status_, passed_);
848
// A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
849
// It installs a MockDeathTestFactory that is used for the duration
851
class MacroLogicDeathTest : public testing::Test {
853
static testing::internal::ReplaceDeathTestFactory* replacer_;
854
static MockDeathTestFactory* factory_;
856
static void SetUpTestCase() {
857
factory_ = new MockDeathTestFactory;
858
replacer_ = new testing::internal::ReplaceDeathTestFactory(
859
testing::UnitTest::GetInstance(), factory_);
862
static void TearDownTestCase() {
869
// Runs a death test that breaks the rules by returning. Such a death
870
// test cannot be run directly from a test routine that uses a
871
// MockDeathTest, or the remainder of the routine will not be executed.
872
static void RunReturningDeathTest(bool* flag) {
873
ASSERT_DEATH({ // NOLINT
880
testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
882
MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;
885
// Test that nothing happens when the factory doesn't return a DeathTest:
886
TEST_F(MacroLogicDeathTest, NothingHappens) {
888
factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
889
EXPECT_DEATH(flag = true, "");
891
EXPECT_EQ(0, factory_->AssumeRoleCalls());
892
EXPECT_EQ(0, factory_->WaitCalls());
893
EXPECT_EQ(0, factory_->PassedCalls());
894
EXPECT_EQ(0, factory_->AbortCalls());
895
EXPECT_FALSE(factory_->TestDeleted());
898
// Test that the parent process doesn't run the death test code,
899
// and that the Passed method returns false when the (simulated)
900
// child process exits with status 0:
901
TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
903
factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
904
EXPECT_DEATH(flag = true, "");
906
EXPECT_EQ(1, factory_->AssumeRoleCalls());
907
EXPECT_EQ(1, factory_->WaitCalls());
908
ASSERT_EQ(1, factory_->PassedCalls());
909
EXPECT_FALSE(factory_->PassedArgument(0));
910
EXPECT_EQ(0, factory_->AbortCalls());
911
EXPECT_TRUE(factory_->TestDeleted());
914
// Tests that the Passed method was given the argument "true" when
915
// the (simulated) child process exits with status 1:
916
TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
918
factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
919
EXPECT_DEATH(flag = true, "");
921
EXPECT_EQ(1, factory_->AssumeRoleCalls());
922
EXPECT_EQ(1, factory_->WaitCalls());
923
ASSERT_EQ(1, factory_->PassedCalls());
924
EXPECT_TRUE(factory_->PassedArgument(0));
925
EXPECT_EQ(0, factory_->AbortCalls());
926
EXPECT_TRUE(factory_->TestDeleted());
929
// Tests that the (simulated) child process executes the death test
930
// code, and is aborted with the correct AbortReason if it
931
// executes a return statement.
932
TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
934
factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
935
RunReturningDeathTest(&flag);
937
EXPECT_EQ(1, factory_->AssumeRoleCalls());
938
EXPECT_EQ(0, factory_->WaitCalls());
939
EXPECT_EQ(0, factory_->PassedCalls());
940
EXPECT_EQ(1, factory_->AbortCalls());
941
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
942
factory_->AbortArgument(0));
943
EXPECT_TRUE(factory_->TestDeleted());
946
// Tests that the (simulated) child process is aborted with the
947
// correct AbortReason if it does not die.
948
TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
950
factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
951
EXPECT_DEATH(flag = true, "");
953
EXPECT_EQ(1, factory_->AssumeRoleCalls());
954
EXPECT_EQ(0, factory_->WaitCalls());
955
EXPECT_EQ(0, factory_->PassedCalls());
956
// This time there are two calls to Abort: one since the test didn't
957
// die, and another from the ReturnSentinel when it's destroyed. The
958
// sentinel normally isn't destroyed if a test doesn't die, since
959
// _exit(2) is called in that case by ForkingDeathTest, but not by
960
// our MockDeathTest.
961
ASSERT_EQ(2, factory_->AbortCalls());
962
EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
963
factory_->AbortArgument(0));
964
EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
965
factory_->AbortArgument(1));
966
EXPECT_TRUE(factory_->TestDeleted());
969
// Returns the number of successful parts in the current test.
970
static size_t GetSuccessfulTestPartCount() {
971
return testing::UnitTest::GetInstance()->impl()->current_test_result()->
972
successful_part_count();
975
// Tests that a successful death test does not register a successful
977
TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
978
EXPECT_DEATH(_exit(1), "");
979
EXPECT_EQ(0u, GetSuccessfulTestPartCount());
982
TEST(StreamingAssertionsDeathTest, DeathTest) {
983
EXPECT_DEATH(_exit(1), "") << "unexpected failure";
984
ASSERT_DEATH(_exit(1), "") << "unexpected failure";
985
EXPECT_NONFATAL_FAILURE({ // NOLINT
986
EXPECT_DEATH(_exit(0), "") << "expected failure";
987
}, "expected failure");
988
EXPECT_FATAL_FAILURE({ // NOLINT
989
ASSERT_DEATH(_exit(0), "") << "expected failure";
990
}, "expected failure");
993
// Tests that GetLastSystemErrorMessage returns an empty string when the
994
// last error is 0 and non-empty string when it is non-zero.
995
TEST(GetLastSystemErrorMessageTest, GetLastSystemErrorMessageWorks) {
997
::SetLastError(ERROR_FILE_NOT_FOUND);
998
EXPECT_STRNE("", GetLastSystemErrorMessage().c_str());
1000
EXPECT_STREQ("", GetLastSystemErrorMessage().c_str());
1003
EXPECT_STRNE("", GetLastSystemErrorMessage().c_str());
1005
EXPECT_STREQ("", GetLastSystemErrorMessage().c_str());
1009
#if GTEST_OS_WINDOWS
1010
TEST(AutoHandleTest, AutoHandleWorks) {
1011
HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1012
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1014
// Tests that the AutoHandle is correctly initialized with a handle.
1015
testing::internal::AutoHandle auto_handle(handle);
1016
EXPECT_EQ(handle, auto_handle.Get());
1018
// Tests that Reset assigns INVALID_HANDLE_VALUE.
1019
// Note that this cannot verify whether the original handle is closed.
1020
auto_handle.Reset();
1021
EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());
1023
// Tests that Reset assigns the new handle.
1024
// Note that this cannot verify whether the original handle is closed.
1025
handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
1026
ASSERT_NE(INVALID_HANDLE_VALUE, handle);
1027
auto_handle.Reset(handle);
1028
EXPECT_EQ(handle, auto_handle.Get());
1030
// Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
1031
testing::internal::AutoHandle auto_handle2;
1032
EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
1034
#endif // GTEST_OS_WINDOWS
1036
#if GTEST_OS_WINDOWS
1037
typedef unsigned __int64 BiggestParsable;
1038
typedef signed __int64 BiggestSignedParsable;
1039
const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
1040
const BiggestParsable kBiggestSignedParsableMax = LLONG_MAX;
1042
typedef unsigned long long BiggestParsable;
1043
typedef signed long long BiggestSignedParsable;
1044
const BiggestParsable kBiggestParsableMax =
1045
::std::numeric_limits<BiggestParsable>::max();
1046
const BiggestSignedParsable kBiggestSignedParsableMax =
1047
::std::numeric_limits<BiggestSignedParsable>::max();
1048
#endif // GTEST_OS_WINDOWS
1050
TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
1051
BiggestParsable result = 0;
1053
// Rejects non-numbers.
1054
EXPECT_FALSE(ParseNaturalNumber(String("non-number string"), &result));
1056
// Rejects numbers with whitespace prefix.
1057
EXPECT_FALSE(ParseNaturalNumber(String(" 123"), &result));
1059
// Rejects negative numbers.
1060
EXPECT_FALSE(ParseNaturalNumber(String("-123"), &result));
1062
// Rejects numbers starting with a plus sign.
1063
EXPECT_FALSE(ParseNaturalNumber(String("+123"), &result));
1067
TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
1068
BiggestParsable result = 0;
1070
EXPECT_FALSE(ParseNaturalNumber(String("99999999999999999999999"), &result));
1072
signed char char_result = 0;
1073
EXPECT_FALSE(ParseNaturalNumber(String("200"), &char_result));
1077
TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
1078
BiggestParsable result = 0;
1081
ASSERT_TRUE(ParseNaturalNumber(String("123"), &result));
1082
EXPECT_EQ(123, result);
1084
// Check 0 as an edge case.
1086
ASSERT_TRUE(ParseNaturalNumber(String("0"), &result));
1087
EXPECT_EQ(0, result);
1090
ASSERT_TRUE(ParseNaturalNumber(String("00000"), &result));
1091
EXPECT_EQ(0, result);
1094
TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
1096
msg << kBiggestParsableMax;
1098
BiggestParsable result = 0;
1099
EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
1100
EXPECT_EQ(kBiggestParsableMax, result);
1103
msg2 << kBiggestSignedParsableMax;
1105
BiggestSignedParsable signed_result = 0;
1106
EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
1107
EXPECT_EQ(kBiggestSignedParsableMax, signed_result);
1113
EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
1114
EXPECT_EQ(INT_MAX, int_result);
1119
unsigned int uint_result = 0;
1120
EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
1121
EXPECT_EQ(UINT_MAX, uint_result);
1124
TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
1125
short short_result = 0;
1126
ASSERT_TRUE(ParseNaturalNumber(String("123"), &short_result));
1127
EXPECT_EQ(123, short_result);
1129
signed char char_result = 0;
1130
ASSERT_TRUE(ParseNaturalNumber(String("123"), &char_result));
1131
EXPECT_EQ(123, char_result);
1134
#if GTEST_OS_WINDOWS
1135
TEST(EnvironmentTest, HandleFitsIntoSizeT) {
1136
// TODO(vladl@google.com): Remove this test after this condition is verified
1137
// in a static assertion in gtest-death-test.cc in the function
1138
// GetStatusFileDescriptor.
1139
ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
1141
#endif // GTEST_OS_WINDOWS
1143
#endif // GTEST_HAS_DEATH_TEST
1145
// Tests that a test case whose name ends with "DeathTest" works fine
1147
TEST(NotADeathTest, Test) {