gtest-death-test_test.cc 43.9 KB
Newer Older
shiqian's avatar
shiqian committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Tests for death tests.

34
35
36
#include "gtest/gtest-death-test.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-filepath.h"
shiqian's avatar
shiqian committed
37

38
39
40
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;

zhanyong.wan's avatar
zhanyong.wan committed
41
#if GTEST_HAS_DEATH_TEST
shiqian's avatar
shiqian committed
42

43
44
45
46
47
48
# if GTEST_OS_WINDOWS
#  include <direct.h>          // For chdir().
# else
#  include <unistd.h>
#  include <sys/wait.h>        // For waitpid.
# endif  // GTEST_OS_WINDOWS
49

50
51
52
# include <limits.h>
# include <signal.h>
# include <stdio.h>
53

54
55
56
57
# if GTEST_OS_LINUX
#  include <sys/time.h>
# endif  // GTEST_OS_LINUX

58
# include "gtest/gtest-spi.h"
shiqian's avatar
shiqian committed
59
60
61
62
63
64

// Indicates that this translation unit is part of Google Test's
// implementation.  It must come before gtest-internal-inl.h is
// included, or there will be a compiler error.  This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
65
66
67
# define GTEST_IMPLEMENTATION_ 1
# include "src/gtest-internal-inl.h"
# undef GTEST_IMPLEMENTATION_
shiqian's avatar
shiqian committed
68

69
namespace posix = ::testing::internal::posix;
70

71
using testing::Message;
shiqian's avatar
shiqian committed
72
73
using testing::internal::DeathTest;
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;
shiqian's avatar
shiqian committed
79
80
81
82
83
84
85
86

namespace testing {
namespace internal {

// A helper class whose objects replace the death test factory for a
// single UnitTest object during their lifetimes.
class ReplaceDeathTestFactory {
 public:
87
88
89
90
  explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)
      : unit_test_impl_(GetUnitTestImpl()) {
    old_factory_ = unit_test_impl_->death_test_factory_.release();
    unit_test_impl_->death_test_factory_.reset(new_factory);
shiqian's avatar
shiqian committed
91
92
93
  }

  ~ReplaceDeathTestFactory() {
94
95
    unit_test_impl_->death_test_factory_.release();
    unit_test_impl_->death_test_factory_.reset(old_factory_);
shiqian's avatar
shiqian committed
96
97
98
99
100
101
  }
 private:
  // Prevents copying ReplaceDeathTestFactory objects.
  ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);
  void operator=(const ReplaceDeathTestFactory&);

102
  UnitTestImpl* unit_test_impl_;
shiqian's avatar
shiqian committed
103
104
105
106
107
108
  DeathTestFactory* old_factory_;
};

}  // namespace internal
}  // namespace testing

109
110
111
112
void DieWithMessage(const ::std::string& message) {
  fprintf(stderr, "%s", message.c_str());
  fflush(stderr);  // Make sure the text is printed before the process exits.

113
114
115
116
  // We call _exit() instead of exit(), as the former is a direct
  // system call and thus safer in the presence of threads.  exit()
  // will invoke user-defined exit-hooks, which may do dangerous
  // things that conflict with death tests.
117
118
119
120
121
122
  //
  // Some compilers can recognize that _exit() never returns and issue the
  // 'unreachable code' warning for code following this function, unless
  // fooled by a fake condition.
  if (AlwaysTrue())
    _exit(1);
123
124
}

125
126
127
128
void DieInside(const ::std::string& function) {
  DieWithMessage("death inside " + function + "().");
}

shiqian's avatar
shiqian committed
129
130
131
132
// Tests that death tests work.

class TestForDeathTest : public testing::Test {
 protected:
133
134
135
  TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}

  virtual ~TestForDeathTest() {
136
    posix::ChDir(original_dir_.c_str());
137
138
  }

shiqian's avatar
shiqian committed
139
  // A static member function that's expected to die.
140
  static void StaticMemberFunction() { DieInside("StaticMemberFunction"); }
shiqian's avatar
shiqian committed
141
142
143

  // A method of the test fixture that may die.
  void MemberFunction() {
144
145
    if (should_die_)
      DieInside("MemberFunction");
shiqian's avatar
shiqian committed
146
147
148
149
  }

  // True iff MemberFunction() should die.
  bool should_die_;
150
  const FilePath original_dir_;
shiqian's avatar
shiqian committed
151
152
153
154
155
156
157
158
159
};

// A class with a member function that may die.
class MayDie {
 public:
  explicit MayDie(bool should_die) : should_die_(should_die) {}

  // A member function that may die.
  void MemberFunction() const {
160
161
    if (should_die_)
      DieInside("MayDie::MemberFunction");
shiqian's avatar
shiqian committed
162
163
164
165
166
167
168
169
  }

 private:
  // True iff MemberFunction() should die.
  bool should_die_;
};

// A global function that's expected to die.
170
void GlobalFunction() { DieInside("GlobalFunction"); }
shiqian's avatar
shiqian committed
171
172
173

// A non-void function that's expected to die.
int NonVoidFunction() {
174
  DieInside("NonVoidFunction");
shiqian's avatar
shiqian committed
175
176
177
178
179
  return 1;
}

// A unary function that may die.
void DieIf(bool should_die) {
180
181
  if (should_die)
    DieInside("DieIf");
shiqian's avatar
shiqian committed
182
183
184
185
186
}

// A binary function that may die.
bool DieIfLessThan(int x, int y) {
  if (x < y) {
187
    DieInside("DieIfLessThan");
shiqian's avatar
shiqian committed
188
189
190
191
192
193
194
195
196
197
198
199
200
  }
  return true;
}

// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
void DeathTestSubroutine() {
  EXPECT_DEATH(GlobalFunction(), "death.*GlobalFunction");
  ASSERT_DEATH(GlobalFunction(), "death.*GlobalFunction");
}

// Death in dbg, not opt.
int DieInDebugElse12(int* sideeffect) {
  if (sideeffect) *sideeffect = 12;
201
202
203

# ifndef NDEBUG

204
  DieInside("DieInDebugElse12");
205
206
207

# endif  // NDEBUG

shiqian's avatar
shiqian committed
208
209
210
  return 12;
}

211
# if GTEST_OS_WINDOWS
212
213
214
215
216
217
218
219
220
221
222
223

// Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) {
  // On Windows, the process's exit code is the same as its exit status,
  // so the predicate just compares the its input with its parameter.
  EXPECT_TRUE(testing::ExitedWithCode(0)(0));
  EXPECT_TRUE(testing::ExitedWithCode(1)(1));
  EXPECT_TRUE(testing::ExitedWithCode(42)(42));
  EXPECT_FALSE(testing::ExitedWithCode(0)(1));
  EXPECT_FALSE(testing::ExitedWithCode(1)(0));
}

224
# else
225

226
// Returns the exit status of a process that calls _exit(2) with a
shiqian's avatar
shiqian committed
227
228
229
230
231
// given exit code.  This is a helper function for the
// ExitStatusPredicateTest test suite.
static int NormalExitStatus(int exit_code) {
  pid_t child_pid = fork();
  if (child_pid == 0) {
232
    _exit(exit_code);
shiqian's avatar
shiqian committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
  }
  int status;
  waitpid(child_pid, &status, 0);
  return status;
}

// Returns the exit status of a process that raises a given signal.
// If the signal does not cause the process to die, then it returns
// instead the exit status of a process that exits normally with exit
// code 1.  This is a helper function for the ExitStatusPredicateTest
// test suite.
static int KilledExitStatus(int signum) {
  pid_t child_pid = fork();
  if (child_pid == 0) {
    raise(signum);
248
    _exit(1);
shiqian's avatar
shiqian committed
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
  }
  int status;
  waitpid(child_pid, &status, 0);
  return status;
}

// Tests the ExitedWithCode predicate.
TEST(ExitStatusPredicateTest, ExitedWithCode) {
  const int status0  = NormalExitStatus(0);
  const int status1  = NormalExitStatus(1);
  const int status42 = NormalExitStatus(42);
  const testing::ExitedWithCode pred0(0);
  const testing::ExitedWithCode pred1(1);
  const testing::ExitedWithCode pred42(42);
  EXPECT_PRED1(pred0,  status0);
  EXPECT_PRED1(pred1,  status1);
  EXPECT_PRED1(pred42, status42);
  EXPECT_FALSE(pred0(status1));
  EXPECT_FALSE(pred42(status0));
  EXPECT_FALSE(pred1(status42));
}

// Tests the KilledBySignal predicate.
TEST(ExitStatusPredicateTest, KilledBySignal) {
  const int status_segv = KilledExitStatus(SIGSEGV);
  const int status_kill = KilledExitStatus(SIGKILL);
  const testing::KilledBySignal pred_segv(SIGSEGV);
  const testing::KilledBySignal pred_kill(SIGKILL);
  EXPECT_PRED1(pred_segv, status_segv);
  EXPECT_PRED1(pred_kill, status_kill);
  EXPECT_FALSE(pred_segv(status_kill));
  EXPECT_FALSE(pred_kill(status_segv));
}

283
# endif  // GTEST_OS_WINDOWS
284

shiqian's avatar
shiqian committed
285
286
287
288
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
TEST_F(TestForDeathTest, SingleStatement) {
289
  if (AlwaysFalse())
shiqian's avatar
shiqian committed
290
291
292
    // This would fail if executed; this is a compilation test only
    ASSERT_DEATH(return, "");

293
  if (AlwaysTrue())
294
    EXPECT_DEATH(_exit(1), "");
shiqian's avatar
shiqian committed
295
296
297
298
299
  else
    // This empty "else" branch is meant to ensure that EXPECT_DEATH
    // doesn't expand into an "if" statement without an "else"
    ;

300
  if (AlwaysFalse())
shiqian's avatar
shiqian committed
301
302
    ASSERT_DEATH(return, "") << "did not die";

303
  if (AlwaysFalse())
shiqian's avatar
shiqian committed
304
305
    ;
  else
306
    EXPECT_DEATH(_exit(1), "") << 1 << 2 << 3;
shiqian's avatar
shiqian committed
307
308
309
}

void DieWithEmbeddedNul() {
310
  fprintf(stderr, "Hello%cmy null world.\n", '\0');
311
  fflush(stderr);
312
  _exit(1);
shiqian's avatar
shiqian committed
313
314
}

315
# if GTEST_USES_PCRE
shiqian's avatar
shiqian committed
316
317
// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error
// message has a NUL character in it.
318
TEST_F(TestForDeathTest, EmbeddedNulInMessage) {
shiqian's avatar
shiqian committed
319
320
  // TODO(wan@google.com): <regex.h> doesn't support matching strings
  // with embedded NUL characters - find a way to workaround it.
321
322
  EXPECT_DEATH(DieWithEmbeddedNul(), "my null world");
  ASSERT_DEATH(DieWithEmbeddedNul(), "my null world");
shiqian's avatar
shiqian committed
323
}
324
# endif  // GTEST_USES_PCRE
shiqian's avatar
shiqian committed
325
326
327
328

// Tests that death test macros expand to code which interacts well with switch
// statements.
TEST_F(TestForDeathTest, SwitchStatement) {
billydonahue's avatar
billydonahue committed
329
330
331
  // Microsoft compiler usually complains about switch statements without
  // case labels. We suppress that warning for this test.
  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
332

shiqian's avatar
shiqian committed
333
334
  switch (0)
    default:
335
      ASSERT_DEATH(_exit(1), "") << "exit in default switch handler";
shiqian's avatar
shiqian committed
336
337
338

  switch (0)
    case 0:
339
      EXPECT_DEATH(_exit(1), "") << "exit in switch case";
340

billydonahue's avatar
billydonahue committed
341
  GTEST_DISABLE_MSC_WARNINGS_POP_()
shiqian's avatar
shiqian committed
342
343
}

344
345
346
347
// Tests that a static member function can be used in a "fast" style
// death test.
TEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {
  testing::GTEST_FLAG(death_test_style) = "fast";
shiqian's avatar
shiqian committed
348
349
350
  ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
}

351
352
353
354
// Tests that a method of the test fixture can be used in a "fast"
// style death test.
TEST_F(TestForDeathTest, MemberFunctionFastStyle) {
  testing::GTEST_FLAG(death_test_style) = "fast";
shiqian's avatar
shiqian committed
355
356
357
358
  should_die_ = true;
  EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
}

359
void ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }
360

361
362
363
364
365
// Tests that death tests work even if the current directory has been
// changed.
TEST_F(TestForDeathTest, FastDeathTestInChangedDir) {
  testing::GTEST_FLAG(death_test_style) = "fast";

366
  ChangeToRootDir();
367
368
  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");

369
  ChangeToRootDir();
370
371
372
  ASSERT_DEATH(_exit(1), "");
}

373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# if GTEST_OS_LINUX
void SigprofAction(int, siginfo_t*, void*) { /* no op */ }

// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() {
  struct itimerval timer;
  timer.it_interval.tv_sec = 0;
  timer.it_interval.tv_usec = 1;
  timer.it_value = timer.it_interval;
  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
  struct sigaction signal_action;
  memset(&signal_action, 0, sizeof(signal_action));
  sigemptyset(&signal_action.sa_mask);
  signal_action.sa_sigaction = SigprofAction;
  signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, NULL));
}

// Disables ITIMER_PROF timer and ignores SIGPROF signal.
void DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {
  struct itimerval timer;
394
  timer.it_interval.tv_sec = 0;
395
  timer.it_interval.tv_usec = 0;
396
  timer.it_value = timer.it_interval;
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, NULL));
  struct sigaction signal_action;
  memset(&signal_action, 0, sizeof(signal_action));
  sigemptyset(&signal_action.sa_mask);
  signal_action.sa_handler = SIG_IGN;
  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));
}

// Tests that death tests work when SIGPROF handler and timer are set.
TEST_F(TestForDeathTest, FastSigprofActionSet) {
  testing::GTEST_FLAG(death_test_style) = "fast";
  SetSigprofActionAndTimer();
  EXPECT_DEATH(_exit(1), "");
  struct sigaction old_signal_action;
  DisableSigprofActionAndTimer(&old_signal_action);
  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
}

TEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";
  SetSigprofActionAndTimer();
  EXPECT_DEATH(_exit(1), "");
  struct sigaction old_signal_action;
  DisableSigprofActionAndTimer(&old_signal_action);
  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);
}
# endif  // GTEST_OS_LINUX

shiqian's avatar
shiqian committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Repeats a representative sample of death tests in the "threadsafe" style:

TEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";
  ASSERT_DEATH(StaticMemberFunction(), "death.*StaticMember");
}

TEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";
  should_die_ = true;
  EXPECT_DEATH(MemberFunction(), "inside.*MemberFunction");
}

TEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";

  for (int i = 0; i < 3; ++i)
442
443
444
445
446
447
    EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), "") << ": i = " << i;
}

TEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";

448
  ChangeToRootDir();
449
450
  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), "");

451
  ChangeToRootDir();
452
  ASSERT_DEATH(_exit(1), "");
shiqian's avatar
shiqian committed
453
454
455
456
}

TEST_F(TestForDeathTest, MixedStyles) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";
457
  EXPECT_DEATH(_exit(1), "");
shiqian's avatar
shiqian committed
458
  testing::GTEST_FLAG(death_test_style) = "fast";
459
  EXPECT_DEATH(_exit(1), "");
shiqian's avatar
shiqian committed
460
461
}

462
463
# if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD

shiqian's avatar
shiqian committed
464
465
466
467
468
469
470
471
472
473
474
namespace {

bool pthread_flag;

void SetPthreadFlag() {
  pthread_flag = true;
}

}  // namespace

TEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {
475
476
477
478
479
480
481
  if (!testing::GTEST_FLAG(death_test_use_fork)) {
    testing::GTEST_FLAG(death_test_style) = "threadsafe";
    pthread_flag = false;
    ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, NULL, NULL));
    ASSERT_DEATH(_exit(1), "");
    ASSERT_FALSE(pthread_flag);
  }
shiqian's avatar
shiqian committed
482
483
}

484
# endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD
485

shiqian's avatar
shiqian committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// Tests that a method of another class can be used in a death test.
TEST_F(TestForDeathTest, MethodOfAnotherClass) {
  const MayDie x(true);
  ASSERT_DEATH(x.MemberFunction(), "MayDie\\:\\:MemberFunction");
}

// Tests that a global function can be used in a death test.
TEST_F(TestForDeathTest, GlobalFunction) {
  EXPECT_DEATH(GlobalFunction(), "GlobalFunction");
}

// Tests that any value convertible to an RE works as a second
// argument to EXPECT_DEATH.
TEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {
  static const char regex_c_str[] = "GlobalFunction";
  EXPECT_DEATH(GlobalFunction(), regex_c_str);

  const testing::internal::RE regex(regex_c_str);
  EXPECT_DEATH(GlobalFunction(), regex);

506
507
# if GTEST_HAS_GLOBAL_STRING

shiqian's avatar
shiqian committed
508
509
  const string regex_str(regex_c_str);
  EXPECT_DEATH(GlobalFunction(), regex_str);
510
511

# endif  // GTEST_HAS_GLOBAL_STRING
shiqian's avatar
shiqian committed
512

513
514
# if !GTEST_USES_PCRE

shiqian's avatar
shiqian committed
515
516
  const ::std::string regex_std_str(regex_c_str);
  EXPECT_DEATH(GlobalFunction(), regex_std_str);
517
518

# endif  // !GTEST_USES_PCRE
shiqian's avatar
shiqian committed
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
}

// Tests that a non-void function can be used in a death test.
TEST_F(TestForDeathTest, NonVoidFunction) {
  ASSERT_DEATH(NonVoidFunction(), "NonVoidFunction");
}

// Tests that functions that take parameter(s) can be used in a death test.
TEST_F(TestForDeathTest, FunctionWithParameter) {
  EXPECT_DEATH(DieIf(true), "DieIf\\(\\)");
  EXPECT_DEATH(DieIfLessThan(2, 3), "DieIfLessThan");
}

// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.
TEST_F(TestForDeathTest, OutsideFixture) {
  DeathTestSubroutine();
}

// Tests that death tests can be done inside a loop.
TEST_F(TestForDeathTest, InsideLoop) {
  for (int i = 0; i < 5; i++) {
    EXPECT_DEATH(DieIfLessThan(-1, i), "DieIfLessThan") << "where i == " << i;
  }
}

// Tests that a compound statement can be used in a death test.
TEST_F(TestForDeathTest, CompoundStatement) {
  EXPECT_DEATH({  // NOLINT
    const int x = 2;
    const int y = x + 1;
    DieIfLessThan(x, y);
  },
  "DieIfLessThan");
}

// Tests that code that doesn't die causes a death test to fail.
TEST_F(TestForDeathTest, DoesNotDie) {
  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), "DieIf"),
                          "failed to die");
}

// Tests that a death test fails when the error message isn't expected.
TEST_F(TestForDeathTest, ErrorMessageMismatch) {
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_DEATH(DieIf(true), "DieIfLessThan") << "End of death test message.";
  }, "died but not with expected error");
}

// On exit, *aborted will be true iff the EXPECT_DEATH() statement
// aborted the function.
void ExpectDeathTestHelper(bool* aborted) {
  *aborted = true;
  EXPECT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
  *aborted = false;
}

// Tests that EXPECT_DEATH doesn't abort the test on failure.
TEST_F(TestForDeathTest, EXPECT_DEATH) {
  bool aborted = true;
  EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted),
                          "failed to die");
  EXPECT_FALSE(aborted);
}

// Tests that ASSERT_DEATH does abort the test on failure.
TEST_F(TestForDeathTest, ASSERT_DEATH) {
  static bool aborted;
  EXPECT_FATAL_FAILURE({  // NOLINT
    aborted = true;
    ASSERT_DEATH(DieIf(false), "DieIf");  // This assertion should fail.
    aborted = false;
  }, "failed to die");
  EXPECT_TRUE(aborted);
}

// Tests that EXPECT_DEATH evaluates the arguments exactly once.
TEST_F(TestForDeathTest, SingleEvaluation) {
  int x = 3;
  EXPECT_DEATH(DieIf((++x) == 4), "DieIf");

  const char* regex = "DieIf";
  const char* regex_save = regex;
  EXPECT_DEATH(DieIfLessThan(3, 4), regex++);
  EXPECT_EQ(regex_save + 1, regex);
}

// Tests that run-away death tests are reported as failures.
606
TEST_F(TestForDeathTest, RunawayIsFailure) {
shiqian's avatar
shiqian committed
607
608
  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), "Foo"),
                          "failed to die.");
609
}
shiqian's avatar
shiqian committed
610

611
612
613
// Tests that death tests report executing 'return' in the statement as
// failure.
TEST_F(TestForDeathTest, ReturnIsFailure) {
shiqian's avatar
shiqian committed
614
615
616
617
  EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, "Bar"),
                       "illegal return in test statement.");
}

618
619
// Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a
// message to it, and in debug mode it:
shiqian's avatar
shiqian committed
620
621
622
623
624
625
626
627
// 1. Asserts on death.
// 2. Has no side effect.
//
// And in opt mode, it:
// 1.  Has side effects but does not assert.
TEST_F(TestForDeathTest, TestExpectDebugDeath) {
  int sideeffect = 0;

628
629
  EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
      << "Must accept a streamed message";
shiqian's avatar
shiqian committed
630

631
632
# ifdef NDEBUG

shiqian's avatar
shiqian committed
633
634
  // Checks that the assignment occurs in opt mode (sideeffect).
  EXPECT_EQ(12, sideeffect);
635
636
637

# else

shiqian's avatar
shiqian committed
638
639
  // Checks that the assignment does not occur in dbg mode (no sideeffect).
  EXPECT_EQ(0, sideeffect);
640
641

# endif
shiqian's avatar
shiqian committed
642
643
}

644
645
646
// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a
// message to it, and in debug mode it:
// 1. Asserts on death.
shiqian's avatar
shiqian committed
647
648
// 2. Has no side effect.
//
649
650
// And in opt mode, it:
// 1.  Has side effects but does not assert.
651
TEST_F(TestForDeathTest, TestAssertDebugDeath) {
shiqian's avatar
shiqian committed
652
653
  int sideeffect = 0;

654
655
  ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), "death.*DieInDebugElse12")
      << "Must accept a streamed message";
shiqian's avatar
shiqian committed
656

657
658
# ifdef NDEBUG

shiqian's avatar
shiqian committed
659
660
  // Checks that the assignment occurs in opt mode (sideeffect).
  EXPECT_EQ(12, sideeffect);
661
662
663

# else

shiqian's avatar
shiqian committed
664
665
  // Checks that the assignment does not occur in dbg mode (no sideeffect).
  EXPECT_EQ(0, sideeffect);
666
667

# endif
shiqian's avatar
shiqian committed
668
669
}

670
# ifndef NDEBUG
shiqian's avatar
shiqian committed
671
672
673
674
675
676
677

void ExpectDebugDeathHelper(bool* aborted) {
  *aborted = true;
  EXPECT_DEBUG_DEATH(return, "") << "This is expected to fail.";
  *aborted = false;
}

678
#  if GTEST_OS_WINDOWS
679
TEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {
680
681
682
683
684
685
686
687
688
  printf("This test should be considered failing if it shows "
         "any pop-up dialogs.\n");
  fflush(stdout);

  EXPECT_DEATH({
    testing::GTEST_FLAG(catch_exceptions) = false;
    abort();
  }, "");
}
689
#  endif  // GTEST_OS_WINDOWS
690

shiqian's avatar
shiqian committed
691
692
693
694
695
696
697
698
699
700
// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort
// the function.
TEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {
  bool aborted = true;
  EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), "");
  EXPECT_FALSE(aborted);
}

void AssertDebugDeathHelper(bool* aborted) {
  *aborted = true;
701
702
703
704
  GTEST_LOG_(INFO) << "Before ASSERT_DEBUG_DEATH";
  ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << "In ASSERT_DEBUG_DEATH"; return, "")
      << "This is expected to fail.";
  GTEST_LOG_(INFO) << "After ASSERT_DEBUG_DEATH";
shiqian's avatar
shiqian committed
705
706
707
708
709
710
711
712
713
714
715
716
  *aborted = false;
}

// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on
// failure.
TEST_F(TestForDeathTest, AssertDebugDeathAborts) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
TEST_F(TestForDeathTest, AssertDebugDeathAborts2) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts3) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts4) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts5) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts6) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts7) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts8) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts9) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

TEST_F(TestForDeathTest, AssertDebugDeathAborts10) {
  static bool aborted;
  aborted = false;
  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), "");
  EXPECT_TRUE(aborted);
}

780
# endif  // _NDEBUG
shiqian's avatar
shiqian committed
781
782

// Tests the *_EXIT family of macros, using a variety of predicates.
783
static void TestExitMacros() {
784
785
  EXPECT_EXIT(_exit(1),  testing::ExitedWithCode(1),  "");
  ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), "");
786

787
788
# if GTEST_OS_WINDOWS

789
790
791
  // Of all signals effects on the process exit code, only those of SIGABRT
  // are documented on Windows.
  // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx.
792
  EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar";
793
794
795

# else

796
797
798
  EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), "") << "foo";
  ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), "") << "bar";

shiqian's avatar
shiqian committed
799
  EXPECT_FATAL_FAILURE({  // NOLINT
800
    ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), "")
801
      << "This failure is expected, too.";
shiqian's avatar
shiqian committed
802
  }, "This failure is expected, too.");
803
804

# endif  // GTEST_OS_WINDOWS
805
806
807

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), "")
808
      << "This failure is expected.";
809
  }, "This failure is expected.");
shiqian's avatar
shiqian committed
810
811
}

812
813
814
815
816
817
818
819
820
TEST_F(TestForDeathTest, ExitMacros) {
  TestExitMacros();
}

TEST_F(TestForDeathTest, ExitMacrosUsingFork) {
  testing::GTEST_FLAG(death_test_use_fork) = true;
  TestExitMacros();
}

shiqian's avatar
shiqian committed
821
822
823
TEST_F(TestForDeathTest, InvalidStyle) {
  testing::GTEST_FLAG(death_test_style) = "rococo";
  EXPECT_NONFATAL_FAILURE({  // NOLINT
824
    EXPECT_DEATH(_exit(0), "") << "This failure is expected.";
shiqian's avatar
shiqian committed
825
826
827
  }, "This failure is expected.");
}

828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
TEST_F(TestForDeathTest, DeathTestFailedOutput) {
  testing::GTEST_FLAG(death_test_style) = "fast";
  EXPECT_NONFATAL_FAILURE(
      EXPECT_DEATH(DieWithMessage("death\n"),
                   "expected message"),
      "Actual msg:\n"
      "[  DEATH   ] death\n");
}

TEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {
  testing::GTEST_FLAG(death_test_style) = "fast";
  EXPECT_NONFATAL_FAILURE(
      EXPECT_DEATH({
          fprintf(stderr, "returning\n");
          fflush(stderr);
          return;
        }, ""),
      "    Result: illegal return in test statement.\n"
      " Error msg:\n"
      "[  DEATH   ] returning\n");
}

TEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {
  testing::GTEST_FLAG(death_test_style) = "fast";
  EXPECT_NONFATAL_FAILURE(
      EXPECT_EXIT(DieWithMessage("exiting with rc 1\n"),
                  testing::ExitedWithCode(3),
                  "expected message"),
      "    Result: died but not with expected exit code:\n"
      "            Exited with exit status 1\n"
      "Actual msg:\n"
      "[  DEATH   ] exiting with rc 1\n");
}

TEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {
  testing::GTEST_FLAG(death_test_style) = "fast";
  EXPECT_NONFATAL_FAILURE(
      EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
                   "line 1\nxyz\nline 3\n"),
      "Actual msg:\n"
      "[  DEATH   ] line 1\n"
      "[  DEATH   ] line 2\n"
      "[  DEATH   ] line 3\n");
}

TEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {
  testing::GTEST_FLAG(death_test_style) = "fast";
  EXPECT_DEATH(DieWithMessage("line 1\nline 2\nline 3\n"),
               "line 1\nline 2\nline 3\n");
}

shiqian's avatar
shiqian committed
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
// A DeathTestFactory that returns MockDeathTests.
class MockDeathTestFactory : public DeathTestFactory {
 public:
  MockDeathTestFactory();
  virtual bool Create(const char* statement,
                      const ::testing::internal::RE* regex,
                      const char* file, int line, DeathTest** test);

  // Sets the parameters for subsequent calls to Create.
  void SetParameters(bool create, DeathTest::TestRole role,
                     int status, bool passed);

  // Accessors.
  int AssumeRoleCalls() const { return assume_role_calls_; }
  int WaitCalls() const { return wait_calls_; }
894
  size_t PassedCalls() const { return passed_args_.size(); }
shiqian's avatar
shiqian committed
895
  bool PassedArgument(int n) const { return passed_args_[n]; }
896
  size_t AbortCalls() const { return abort_args_.size(); }
shiqian's avatar
shiqian committed
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
  DeathTest::AbortReason AbortArgument(int n) const {
    return abort_args_[n];
  }
  bool TestDeleted() const { return test_deleted_; }

 private:
  friend class MockDeathTest;
  // If true, Create will return a MockDeathTest; otherwise it returns
  // NULL.
  bool create_;
  // The value a MockDeathTest will return from its AssumeRole method.
  DeathTest::TestRole role_;
  // The value a MockDeathTest will return from its Wait method.
  int status_;
  // The value a MockDeathTest will return from its Passed method.
  bool passed_;

  // Number of times AssumeRole was called.
  int assume_role_calls_;
  // Number of times Wait was called.
  int wait_calls_;
  // The arguments to the calls to Passed since the last call to
  // SetParameters.
  std::vector<bool> passed_args_;
  // The arguments to the calls to Abort since the last call to
  // SetParameters.
  std::vector<DeathTest::AbortReason> abort_args_;
  // True if the last MockDeathTest returned by Create has been
  // deleted.
  bool test_deleted_;
};


// A DeathTest implementation useful in testing.  It returns values set
// at its creation from its various inherited DeathTest methods, and
// reports calls to those methods to its parent MockDeathTestFactory
// object.
class MockDeathTest : public DeathTest {
 public:
  MockDeathTest(MockDeathTestFactory *parent,
                TestRole role, int status, bool passed) :
      parent_(parent), role_(role), status_(status), passed_(passed) {
  }
  virtual ~MockDeathTest() {
    parent_->test_deleted_ = true;
  }
  virtual TestRole AssumeRole() {
    ++parent_->assume_role_calls_;
    return role_;
  }
  virtual int Wait() {
    ++parent_->wait_calls_;
    return status_;
  }
  virtual bool Passed(bool exit_status_ok) {
    parent_->passed_args_.push_back(exit_status_ok);
    return passed_;
  }
  virtual void Abort(AbortReason reason) {
    parent_->abort_args_.push_back(reason);
  }
958

shiqian's avatar
shiqian committed
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
 private:
  MockDeathTestFactory* const parent_;
  const TestRole role_;
  const int status_;
  const bool passed_;
};


// MockDeathTestFactory constructor.
MockDeathTestFactory::MockDeathTestFactory()
    : create_(true),
      role_(DeathTest::OVERSEE_TEST),
      status_(0),
      passed_(true),
      assume_role_calls_(0),
      wait_calls_(0),
      passed_args_(),
      abort_args_() {
}


// Sets the parameters for subsequent calls to Create.
void MockDeathTestFactory::SetParameters(bool create,
                                         DeathTest::TestRole role,
                                         int status, bool passed) {
  create_ = create;
  role_ = role;
  status_ = status;
  passed_ = passed;

  assume_role_calls_ = 0;
  wait_calls_ = 0;
  passed_args_.clear();
  abort_args_.clear();
}


// Sets test to NULL (if create_ is false) or to the address of a new
// MockDeathTest object with parameters taken from the last call
// to SetParameters (if create_ is true).  Always returns true.
999
1000
1001
1002
bool MockDeathTestFactory::Create(const char* /*statement*/,
                                  const ::testing::internal::RE* /*regex*/,
                                  const char* /*file*/,
                                  int /*line*/,
shiqian's avatar
shiqian committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
                                  DeathTest** test) {
  test_deleted_ = false;
  if (create_) {
    *test = new MockDeathTest(this, role_, status_, passed_);
  } else {
    *test = NULL;
  }
  return true;
}

shiqian's avatar
shiqian committed
1013
// A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.
shiqian's avatar
shiqian committed
1014
1015
1016
1017
1018
1019
1020
1021
1022
// It installs a MockDeathTestFactory that is used for the duration
// of the test case.
class MacroLogicDeathTest : public testing::Test {
 protected:
  static testing::internal::ReplaceDeathTestFactory* replacer_;
  static MockDeathTestFactory* factory_;

  static void SetUpTestCase() {
    factory_ = new MockDeathTestFactory;
1023
    replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);
shiqian's avatar
shiqian committed
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
  }

  static void TearDownTestCase() {
    delete replacer_;
    replacer_ = NULL;
    delete factory_;
    factory_ = NULL;
  }

  // Runs a death test that breaks the rules by returning.  Such a death
  // test cannot be run directly from a test routine that uses a
  // MockDeathTest, or the remainder of the routine will not be executed.
  static void RunReturningDeathTest(bool* flag) {
    ASSERT_DEATH({  // NOLINT
      *flag = true;
      return;
    }, "");
  }
};

testing::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_
    = NULL;
MockDeathTestFactory* MacroLogicDeathTest::factory_ = NULL;


// Test that nothing happens when the factory doesn't return a DeathTest:
TEST_F(MacroLogicDeathTest, NothingHappens) {
  bool flag = false;
  factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);
  EXPECT_DEATH(flag = true, "");
  EXPECT_FALSE(flag);
  EXPECT_EQ(0, factory_->AssumeRoleCalls());
  EXPECT_EQ(0, factory_->WaitCalls());
1057
1058
  EXPECT_EQ(0U, factory_->PassedCalls());
  EXPECT_EQ(0U, factory_->AbortCalls());
shiqian's avatar
shiqian committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
  EXPECT_FALSE(factory_->TestDeleted());
}

// Test that the parent process doesn't run the death test code,
// and that the Passed method returns false when the (simulated)
// child process exits with status 0:
TEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {
  bool flag = false;
  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);
  EXPECT_DEATH(flag = true, "");
  EXPECT_FALSE(flag);
  EXPECT_EQ(1, factory_->AssumeRoleCalls());
  EXPECT_EQ(1, factory_->WaitCalls());
1072
  ASSERT_EQ(1U, factory_->PassedCalls());
shiqian's avatar
shiqian committed
1073
  EXPECT_FALSE(factory_->PassedArgument(0));
1074
  EXPECT_EQ(0U, factory_->AbortCalls());
shiqian's avatar
shiqian committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
  EXPECT_TRUE(factory_->TestDeleted());
}

// Tests that the Passed method was given the argument "true" when
// the (simulated) child process exits with status 1:
TEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {
  bool flag = false;
  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);
  EXPECT_DEATH(flag = true, "");
  EXPECT_FALSE(flag);
  EXPECT_EQ(1, factory_->AssumeRoleCalls());
  EXPECT_EQ(1, factory_->WaitCalls());
1087
  ASSERT_EQ(1U, factory_->PassedCalls());
shiqian's avatar
shiqian committed
1088
  EXPECT_TRUE(factory_->PassedArgument(0));
1089
  EXPECT_EQ(0U, factory_->AbortCalls());
shiqian's avatar
shiqian committed
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
  EXPECT_TRUE(factory_->TestDeleted());
}

// Tests that the (simulated) child process executes the death test
// code, and is aborted with the correct AbortReason if it
// executes a return statement.
TEST_F(MacroLogicDeathTest, ChildPerformsReturn) {
  bool flag = false;
  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
  RunReturningDeathTest(&flag);
  EXPECT_TRUE(flag);
  EXPECT_EQ(1, factory_->AssumeRoleCalls());
  EXPECT_EQ(0, factory_->WaitCalls());
1103
1104
  EXPECT_EQ(0U, factory_->PassedCalls());
  EXPECT_EQ(1U, factory_->AbortCalls());
shiqian's avatar
shiqian committed
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
            factory_->AbortArgument(0));
  EXPECT_TRUE(factory_->TestDeleted());
}

// Tests that the (simulated) child process is aborted with the
// correct AbortReason if it does not die.
TEST_F(MacroLogicDeathTest, ChildDoesNotDie) {
  bool flag = false;
  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);
  EXPECT_DEATH(flag = true, "");
  EXPECT_TRUE(flag);
  EXPECT_EQ(1, factory_->AssumeRoleCalls());
  EXPECT_EQ(0, factory_->WaitCalls());
1119
  EXPECT_EQ(0U, factory_->PassedCalls());
shiqian's avatar
shiqian committed
1120
1121
1122
  // This time there are two calls to Abort: one since the test didn't
  // die, and another from the ReturnSentinel when it's destroyed.  The
  // sentinel normally isn't destroyed if a test doesn't die, since
1123
  // _exit(2) is called in that case by ForkingDeathTest, but not by
shiqian's avatar
shiqian committed
1124
  // our MockDeathTest.
1125
  ASSERT_EQ(2U, factory_->AbortCalls());
shiqian's avatar
shiqian committed
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
  EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE,
            factory_->AbortArgument(0));
  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,
            factory_->AbortArgument(1));
  EXPECT_TRUE(factory_->TestDeleted());
}

// Tests that a successful death test does not register a successful
// test part.
TEST(SuccessRegistrationDeathTest, NoSuccessPart) {
1136
  EXPECT_DEATH(_exit(1), "");
1137
  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
shiqian's avatar
shiqian committed
1138
1139
1140
}

TEST(StreamingAssertionsDeathTest, DeathTest) {
1141
1142
  EXPECT_DEATH(_exit(1), "") << "unexpected failure";
  ASSERT_DEATH(_exit(1), "") << "unexpected failure";
shiqian's avatar
shiqian committed
1143
  EXPECT_NONFATAL_FAILURE({  // NOLINT
1144
    EXPECT_DEATH(_exit(0), "") << "expected failure";
shiqian's avatar
shiqian committed
1145
1146
  }, "expected failure");
  EXPECT_FATAL_FAILURE({  // NOLINT
1147
    ASSERT_DEATH(_exit(0), "") << "expected failure";
shiqian's avatar
shiqian committed
1148
1149
1150
  }, "expected failure");
}

1151
// Tests that GetLastErrnoDescription returns an empty string when the
1152
// last error is 0 and non-empty string when it is non-zero.
1153
TEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {
1154
  errno = ENOENT;
1155
  EXPECT_STRNE("", GetLastErrnoDescription().c_str());
1156
  errno = 0;
1157
  EXPECT_STREQ("", GetLastErrnoDescription().c_str());
1158
1159
}

1160
# if GTEST_OS_WINDOWS
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
TEST(AutoHandleTest, AutoHandleWorks) {
  HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  ASSERT_NE(INVALID_HANDLE_VALUE, handle);

  // Tests that the AutoHandle is correctly initialized with a handle.
  testing::internal::AutoHandle auto_handle(handle);
  EXPECT_EQ(handle, auto_handle.Get());

  // Tests that Reset assigns INVALID_HANDLE_VALUE.
  // Note that this cannot verify whether the original handle is closed.
  auto_handle.Reset();
  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());

  // Tests that Reset assigns the new handle.
  // Note that this cannot verify whether the original handle is closed.
  handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);
  ASSERT_NE(INVALID_HANDLE_VALUE, handle);
  auto_handle.Reset(handle);
  EXPECT_EQ(handle, auto_handle.Get());

  // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.
  testing::internal::AutoHandle auto_handle2;
  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());
}
1185
# endif  // GTEST_OS_WINDOWS
1186

1187
# if GTEST_OS_WINDOWS
1188
1189
typedef unsigned __int64 BiggestParsable;
typedef signed __int64 BiggestSignedParsable;
1190
# else
1191
1192
typedef unsigned long long BiggestParsable;
typedef signed long long BiggestSignedParsable;
1193
# endif  // GTEST_OS_WINDOWS
1194

1195
1196
1197
1198
1199
// We cannot use std::numeric_limits<T>::max() as it clashes with the
// max() macro defined by <windows.h>.
const BiggestParsable kBiggestParsableMax = ULLONG_MAX;
const BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;

1200
1201
1202
1203
TEST(ParseNaturalNumberTest, RejectsInvalidFormat) {
  BiggestParsable result = 0;

  // Rejects non-numbers.
1204
  EXPECT_FALSE(ParseNaturalNumber("non-number string", &result));
1205
1206

  // Rejects numbers with whitespace prefix.
1207
  EXPECT_FALSE(ParseNaturalNumber(" 123", &result));
1208
1209

  // Rejects negative numbers.
1210
  EXPECT_FALSE(ParseNaturalNumber("-123", &result));
1211
1212

  // Rejects numbers starting with a plus sign.
1213
  EXPECT_FALSE(ParseNaturalNumber("+123", &result));
1214
1215
1216
1217
1218
1219
  errno = 0;
}

TEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {
  BiggestParsable result = 0;

1220
  EXPECT_FALSE(ParseNaturalNumber("99999999999999999999999", &result));
1221
1222

  signed char char_result = 0;
1223
  EXPECT_FALSE(ParseNaturalNumber("200", &char_result));
1224
1225
1226
1227
1228
1229
1230
  errno = 0;
}

TEST(ParseNaturalNumberTest, AcceptsValidNumbers) {
  BiggestParsable result = 0;

  result = 0;
1231
  ASSERT_TRUE(ParseNaturalNumber("123", &result));
1232
  EXPECT_EQ(123U, result);
1233
1234
1235

  // Check 0 as an edge case.
  result = 1;
1236
  ASSERT_TRUE(ParseNaturalNumber("0", &result));
1237
  EXPECT_EQ(0U, result);
1238
1239

  result = 1;
1240
  ASSERT_TRUE(ParseNaturalNumber("00000", &result));
1241
  EXPECT_EQ(0U, result);
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
}

TEST(ParseNaturalNumberTest, AcceptsTypeLimits) {
  Message msg;
  msg << kBiggestParsableMax;

  BiggestParsable result = 0;
  EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));
  EXPECT_EQ(kBiggestParsableMax, result);

  Message msg2;
  msg2 << kBiggestSignedParsableMax;

  BiggestSignedParsable signed_result = 0;
  EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));
  EXPECT_EQ(kBiggestSignedParsableMax, signed_result);

  Message msg3;
  msg3 << INT_MAX;

  int int_result = 0;
  EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));
  EXPECT_EQ(INT_MAX, int_result);

  Message msg4;
  msg4 << UINT_MAX;

  unsigned int uint_result = 0;
  EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));
  EXPECT_EQ(UINT_MAX, uint_result);
}

TEST(ParseNaturalNumberTest, WorksForShorterIntegers) {
  short short_result = 0;
1276
  ASSERT_TRUE(ParseNaturalNumber("123", &short_result));
1277
1278
1279
  EXPECT_EQ(123, short_result);

  signed char char_result = 0;
1280
  ASSERT_TRUE(ParseNaturalNumber("123", &char_result));
1281
1282
1283
  EXPECT_EQ(123, char_result);
}

1284
# if GTEST_OS_WINDOWS
1285
1286
1287
1288
1289
1290
TEST(EnvironmentTest, HandleFitsIntoSizeT) {
  // TODO(vladl@google.com): Remove this test after this condition is verified
  // in a static assertion in gtest-death-test.cc in the function
  // GetStatusFileDescriptor.
  ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));
}
1291
# endif  // GTEST_OS_WINDOWS
1292

1293
1294
1295
// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger
// failures when death tests are available on the system.
TEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {
1296
1297
1298
1299
  EXPECT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestExpectMacro"),
                            "death inside CondDeathTestExpectMacro");
  ASSERT_DEATH_IF_SUPPORTED(DieInside("CondDeathTestAssertMacro"),
                            "death inside CondDeathTestAssertMacro");
1300
1301
1302
1303
1304
1305

  // Empty statement will not crash, which must trigger a failure.
  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, ""), "");
  EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, ""), "");
}

billydonahue's avatar
billydonahue committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {
  testing::GTEST_FLAG(death_test_style) = "fast";
  EXPECT_FALSE(InDeathTestChild());
  EXPECT_DEATH({
    fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
    fflush(stderr);
    _exit(1);
  }, "Inside");
}

TEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";
  EXPECT_FALSE(InDeathTestChild());
  EXPECT_DEATH({
    fprintf(stderr, InDeathTestChild() ? "Inside" : "Outside");
    fflush(stderr);
    _exit(1);
  }, "Inside");
}

#else  // !GTEST_HAS_DEATH_TEST follows
1327
1328
1329
1330
1331

using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;

// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still
1332
// defined but do not trigger failures when death tests are not available on
1333
1334
1335
1336
1337
1338
// the system.
TEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {
  // Empty statement will not crash, but that should not trigger a failure
  // when death tests are not supported.
  CaptureStderr();
  EXPECT_DEATH_IF_SUPPORTED(;, "");
1339
  std::string output = GetCapturedStderr();
1340
1341
1342
1343
  ASSERT_TRUE(NULL != strstr(output.c_str(),
                             "Death tests are not supported on this platform"));
  ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));

1344
  // The streamed message should not be printed as there is no test failure.
1345
  CaptureStderr();
1346
1347
1348
1349
1350
1351
  EXPECT_DEATH_IF_SUPPORTED(;, "") << "streamed message";
  output = GetCapturedStderr();
  ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));

  CaptureStderr();
  ASSERT_DEATH_IF_SUPPORTED(;, "");  // NOLINT
1352
1353
1354
1355
  output = GetCapturedStderr();
  ASSERT_TRUE(NULL != strstr(output.c_str(),
                             "Death tests are not supported on this platform"));
  ASSERT_TRUE(NULL != strstr(output.c_str(), ";"));
1356
1357
1358
1359
1360

  CaptureStderr();
  ASSERT_DEATH_IF_SUPPORTED(;, "") << "streamed message";  // NOLINT
  output = GetCapturedStderr();
  ASSERT_TRUE(NULL == strstr(output.c_str(), "streamed message"));
1361
1362
}

1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
void FuncWithAssert(int* n) {
  ASSERT_DEATH_IF_SUPPORTED(return;, "");
  (*n)++;
}

// Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current
// function (as ASSERT_DEATH does) if death tests are not supported.
TEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {
  int n = 0;
  FuncWithAssert(&n);
  EXPECT_EQ(1, n);
}
1375

billydonahue's avatar
billydonahue committed
1376
#endif  // !GTEST_HAS_DEATH_TEST
shiqian's avatar
shiqian committed
1377

1378
1379
1380
1381
1382
1383
// Tests that the death test macros expand to code which may or may not
// be followed by operator<<, and that in either case the complete text
// comprises only a single C++ statement.
//
// The syntax should work whether death tests are available or not.
TEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {
1384
  if (AlwaysFalse())
1385
1386
1387
    // This would fail if executed; this is a compilation test only
    ASSERT_DEATH_IF_SUPPORTED(return, "");

1388
  if (AlwaysTrue())
1389
1390
1391
1392
1393
1394
    EXPECT_DEATH_IF_SUPPORTED(_exit(1), "");
  else
    // This empty "else" branch is meant to ensure that EXPECT_DEATH
    // doesn't expand into an "if" statement without an "else"
    ;  // NOLINT

1395
  if (AlwaysFalse())
1396
1397
    ASSERT_DEATH_IF_SUPPORTED(return, "") << "did not die";

1398
  if (AlwaysFalse())
1399
1400
1401
1402
1403
1404
1405
1406
    ;  // NOLINT
  else
    EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << 1 << 2 << 3;
}

// Tests that conditional death test macros expand to code which interacts
// well with switch statements.
TEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {
billydonahue's avatar
billydonahue committed
1407
1408
1409
  // Microsoft compiler usually complains about switch statements without
  // case labels. We suppress that warning for this test.
  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419

  switch (0)
    default:
      ASSERT_DEATH_IF_SUPPORTED(_exit(1), "")
          << "exit in default switch handler";

  switch (0)
    case 0:
      EXPECT_DEATH_IF_SUPPORTED(_exit(1), "") << "exit in switch case";

billydonahue's avatar
billydonahue committed
1420
  GTEST_DISABLE_MSC_WARNINGS_POP_()
1421
1422
}

shiqian's avatar
shiqian committed
1423
1424
1425
1426
1427
// Tests that a test case whose name ends with "DeathTest" works fine
// on Windows.
TEST(NotADeathTest, Test) {
  SUCCEED();
}