gtest-death-test-internal.h 10.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
34
35
36
37
38
// 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.
//
//
// The Google C++ Testing Framework (Google Test)
//
// This header file defines internal utilities needed for implementing
// death tests.  They are subject to change without notice.

#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_

39
#include "gtest/internal/gtest-internal.h"
shiqian's avatar
shiqian committed
40

41
42
#include <stdio.h>

shiqian's avatar
shiqian committed
43
44
45
namespace testing {
namespace internal {

shiqian's avatar
shiqian committed
46
GTEST_DECLARE_string_(internal_run_death_test);
shiqian's avatar
shiqian committed
47
48
49

// Names of the flags (needed for parsing Google Test flags).
const char kDeathTestStyleFlag[] = "death_test_style";
50
const char kDeathTestUseFork[] = "death_test_use_fork";
shiqian's avatar
shiqian committed
51
52
const char kInternalRunDeathTestFlag[] = "internal_run_death_test";

zhanyong.wan's avatar
zhanyong.wan committed
53
#if GTEST_HAS_DEATH_TEST
shiqian's avatar
shiqian committed
54
55

// DeathTest is a class that hides much of the complexity of the
shiqian's avatar
shiqian committed
56
// GTEST_DEATH_TEST_ macro.  It is abstract; its static Create method
shiqian's avatar
shiqian committed
57
58
59
60
61
62
63
64
65
66
67
// returns a concrete class that depends on the prevailing death test
// style, as defined by the --gtest_death_test_style and/or
// --gtest_internal_run_death_test flags.

// In describing the results of death tests, these terms are used with
// the corresponding definitions:
//
// exit status:  The integer exit information in the format specified
//               by wait(2)
// exit code:    The integer code passed to exit(3), _exit(2), or
//               returned from main()
68
class GTEST_API_ DeathTest {
shiqian's avatar
shiqian committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
 public:
  // Create returns false if there was an error determining the
  // appropriate action to take for the current death test; for example,
  // if the gtest_death_test_style flag is set to an invalid value.
  // The LastMessage method will return a more detailed message in that
  // case.  Otherwise, the DeathTest pointer pointed to by the "test"
  // argument is set.  If the death test should be skipped, the pointer
  // is set to NULL; otherwise, it is set to the address of a new concrete
  // DeathTest object that controls the execution of the current test.
  static bool Create(const char* statement, const RE* regex,
                     const char* file, int line, DeathTest** test);
  DeathTest();
  virtual ~DeathTest() { }

  // A helper class that aborts a death test when it's deleted.
  class ReturnSentinel {
   public:
    explicit ReturnSentinel(DeathTest* test) : test_(test) { }
    ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
   private:
    DeathTest* const test_;
shiqian's avatar
shiqian committed
90
91
    GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
  } GTEST_ATTRIBUTE_UNUSED_;
shiqian's avatar
shiqian committed
92
93
94
95
96
97
98
99

  // An enumeration of possible roles that may be taken when a death
  // test is encountered.  EXECUTE means that the death test logic should
  // be executed immediately.  OVERSEE means that the program should prepare
  // the appropriate environment for a child process to execute the death
  // test, then wait for it to complete.
  enum TestRole { OVERSEE_TEST, EXECUTE_TEST };

100
101
102
103
104
105
  // An enumeration of the three reasons that a test might be aborted.
  enum AbortReason {
    TEST_ENCOUNTERED_RETURN_STATEMENT,
    TEST_THREW_EXCEPTION,
    TEST_DID_NOT_DIE
  };
shiqian's avatar
shiqian committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

  // Assumes one of the above roles.
  virtual TestRole AssumeRole() = 0;

  // Waits for the death test to finish and returns its status.
  virtual int Wait() = 0;

  // Returns true if the death test passed; that is, the test process
  // exited during the test, its exit status matches a user-supplied
  // predicate, and its stderr output matches a user-supplied regular
  // expression.
  // The user-supplied predicate may be a macro expression rather
  // than a function pointer or functor, or else Wait and Passed could
  // be combined.
  virtual bool Passed(bool exit_status_ok) = 0;

  // Signals that the death test did not die as expected.
  virtual void Abort(AbortReason reason) = 0;

  // Returns a human-readable outcome message regarding the outcome of
  // the last death test.
  static const char* LastMessage();

129
  static void set_last_death_test_message(const std::string& message);
130

shiqian's avatar
shiqian committed
131
 private:
132
  // A string containing a description of the outcome of the last death test.
133
  static std::string last_death_test_message_;
134

shiqian's avatar
shiqian committed
135
  GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
shiqian's avatar
shiqian committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
};

// Factory interface for death tests.  May be mocked out for testing.
class DeathTestFactory {
 public:
  virtual ~DeathTestFactory() { }
  virtual bool Create(const char* statement, const RE* regex,
                      const char* file, int line, DeathTest** test) = 0;
};

// A concrete DeathTestFactory implementation for normal use.
class DefaultDeathTestFactory : public DeathTestFactory {
 public:
  virtual bool Create(const char* statement, const RE* regex,
                      const char* file, int line, DeathTest** test);
};

// Returns true if exit_status describes a process that was terminated
// by a signal, or exited normally with a nonzero exit code.
155
GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
shiqian's avatar
shiqian committed
156

157
158
// Traps C++ exceptions escaping statement and reports them as test
// failures. Note that trapping SEH exceptions is not implemented here.
159
160
# if GTEST_HAS_EXCEPTIONS
#  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
161
162
163
164
165
166
167
168
169
170
171
172
173
174
  try { \
    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  } catch (const ::std::exception& gtest_exception) { \
    fprintf(\
        stderr, \
        "\n%s: Caught std::exception-derived exception escaping the " \
        "death test statement. Exception message: %s\n", \
        ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
        gtest_exception.what()); \
    fflush(stderr); \
    death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
  } catch (...) { \
    death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
  }
175
176
177

# else
#  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
178
  GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
179
180

# endif
181

shiqian's avatar
shiqian committed
182
183
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
// ASSERT_EXIT*, and EXPECT_EXIT*.
184
# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \
shiqian's avatar
shiqian committed
185
  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
186
  if (::testing::internal::AlwaysTrue()) { \
shiqian's avatar
shiqian committed
187
188
189
190
    const ::testing::internal::RE& gtest_regex = (regex); \
    ::testing::internal::DeathTest* gtest_dt; \
    if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \
        __FILE__, __LINE__, &gtest_dt)) { \
shiqian's avatar
shiqian committed
191
      goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
shiqian's avatar
shiqian committed
192
193
194
195
196
197
198
    } \
    if (gtest_dt != NULL) { \
      ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
          gtest_dt_ptr(gtest_dt); \
      switch (gtest_dt->AssumeRole()) { \
        case ::testing::internal::DeathTest::OVERSEE_TEST: \
          if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
shiqian's avatar
shiqian committed
199
            goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
shiqian's avatar
shiqian committed
200
201
202
203
204
          } \
          break; \
        case ::testing::internal::DeathTest::EXECUTE_TEST: { \
          ::testing::internal::DeathTest::ReturnSentinel \
              gtest_sentinel(gtest_dt); \
205
          GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
shiqian's avatar
shiqian committed
206
207
208
          gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
          break; \
        } \
209
210
        default: \
          break; \
shiqian's avatar
shiqian committed
211
212
213
      } \
    } \
  } else \
shiqian's avatar
shiqian committed
214
    GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \
shiqian's avatar
shiqian committed
215
216
217
218
      fail(::testing::internal::DeathTest::LastMessage())
// The symbol "fail" here expands to something into which a message
// can be streamed.

219
// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
Gennadiy Civil's avatar
Gennadiy Civil committed
220
221
222
223
224
225
226
227
228
229
230
231
// NDEBUG mode. In this case we need the statements to be executed and the macro
// must accept a streamed message even though the message is never printed.
// The regex object is not evaluated, but it is used to prevent "unused"
// warnings and to avoid an expression that doesn't compile in debug mode.
#define GTEST_EXECUTE_STATEMENT_(statement, regex)             \
  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                \
  if (::testing::internal::AlwaysTrue()) {                     \
    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  } else if (!::testing::internal::AlwaysTrue()) {             \
    const ::testing::internal::RE& gtest_regex = (regex);      \
    static_cast<void>(gtest_regex);                            \
  } else                                                       \
232
233
    ::testing::Message()

234
// A class representing the parsed contents of the
shiqian's avatar
shiqian committed
235
236
// --gtest_internal_run_death_test flag, as it existed when
// RUN_ALL_TESTS was called.
237
238
class InternalRunDeathTestFlag {
 public:
239
  InternalRunDeathTestFlag(const std::string& a_file,
240
241
242
243
244
                           int a_line,
                           int an_index,
                           int a_write_fd)
      : file_(a_file), line_(a_line), index_(an_index),
        write_fd_(a_write_fd) {}
245
246

  ~InternalRunDeathTestFlag() {
247
    if (write_fd_ >= 0)
248
      posix::Close(write_fd_);
249
250
  }

251
  const std::string& file() const { return file_; }
252
253
  int line() const { return line_; }
  int index() const { return index_; }
254
  int write_fd() const { return write_fd_; }
255
256

 private:
257
  std::string file_;
258
259
  int line_;
  int index_;
260
  int write_fd_;
261
262

  GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
shiqian's avatar
shiqian committed
263
264
265
266
267
268
269
270
271
272
273
274
275
};

// Returns a newly created InternalRunDeathTestFlag object with fields
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
// the flag is specified; otherwise returns NULL.
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();

#endif  // GTEST_HAS_DEATH_TEST

}  // namespace internal
}  // namespace testing

#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_