1// Copyright 2005, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
31//
32// The Google C++ Testing Framework (Google Test)
33//
34// This header file defines internal utilities needed for implementing
35// death tests.  They are subject to change without notice.
36
37#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
38#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
39
40#include <gtest/internal/gtest-internal.h>
41
42namespace testing {
43namespace internal {
44
45GTEST_DECLARE_string_(internal_run_death_test);
46
47// Names of the flags (needed for parsing Google Test flags).
48const char kDeathTestStyleFlag[] = "death_test_style";
49const char kDeathTestUseFork[] = "death_test_use_fork";
50const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
51
52#if GTEST_HAS_DEATH_TEST
53
54// DeathTest is a class that hides much of the complexity of the
55// GTEST_DEATH_TEST_ macro.  It is abstract; its static Create method
56// returns a concrete class that depends on the prevailing death test
57// style, as defined by the --gtest_death_test_style and/or
58// --gtest_internal_run_death_test flags.
59
60// In describing the results of death tests, these terms are used with
61// the corresponding definitions:
62//
63// exit status:  The integer exit information in the format specified
64//               by wait(2)
65// exit code:    The integer code passed to exit(3), _exit(2), or
66//               returned from main()
67class DeathTest {
68 public:
69  // Create returns false if there was an error determining the
70  // appropriate action to take for the current death test; for example,
71  // if the gtest_death_test_style flag is set to an invalid value.
72  // The LastMessage method will return a more detailed message in that
73  // case.  Otherwise, the DeathTest pointer pointed to by the "test"
74  // argument is set.  If the death test should be skipped, the pointer
75  // is set to NULL; otherwise, it is set to the address of a new concrete
76  // DeathTest object that controls the execution of the current test.
77  static bool Create(const char* statement, const RE* regex,
78                     const char* file, int line, DeathTest** test);
79  DeathTest();
80  virtual ~DeathTest() { }
81
82  // A helper class that aborts a death test when it's deleted.
83  class ReturnSentinel {
84   public:
85    explicit ReturnSentinel(DeathTest* test) : test_(test) { }
86    ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
87   private:
88    DeathTest* const test_;
89    GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
90  } GTEST_ATTRIBUTE_UNUSED_;
91
92  // An enumeration of possible roles that may be taken when a death
93  // test is encountered.  EXECUTE means that the death test logic should
94  // be executed immediately.  OVERSEE means that the program should prepare
95  // the appropriate environment for a child process to execute the death
96  // test, then wait for it to complete.
97  enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
98
99  // An enumeration of the two reasons that a test might be aborted.
100  enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_DID_NOT_DIE };
101
102  // Assumes one of the above roles.
103  virtual TestRole AssumeRole() = 0;
104
105  // Waits for the death test to finish and returns its status.
106  virtual int Wait() = 0;
107
108  // Returns true if the death test passed; that is, the test process
109  // exited during the test, its exit status matches a user-supplied
110  // predicate, and its stderr output matches a user-supplied regular
111  // expression.
112  // The user-supplied predicate may be a macro expression rather
113  // than a function pointer or functor, or else Wait and Passed could
114  // be combined.
115  virtual bool Passed(bool exit_status_ok) = 0;
116
117  // Signals that the death test did not die as expected.
118  virtual void Abort(AbortReason reason) = 0;
119
120  // Returns a human-readable outcome message regarding the outcome of
121  // the last death test.
122  static const char* LastMessage();
123
124  static void set_last_death_test_message(const String& message);
125
126 private:
127  // A string containing a description of the outcome of the last death test.
128  static String last_death_test_message_;
129
130  GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
131};
132
133// Factory interface for death tests.  May be mocked out for testing.
134class DeathTestFactory {
135 public:
136  virtual ~DeathTestFactory() { }
137  virtual bool Create(const char* statement, const RE* regex,
138                      const char* file, int line, DeathTest** test) = 0;
139};
140
141// A concrete DeathTestFactory implementation for normal use.
142class DefaultDeathTestFactory : public DeathTestFactory {
143 public:
144  virtual bool Create(const char* statement, const RE* regex,
145                      const char* file, int line, DeathTest** test);
146};
147
148// Returns true if exit_status describes a process that was terminated
149// by a signal, or exited normally with a nonzero exit code.
150bool ExitedUnsuccessfully(int exit_status);
151
152// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
153// ASSERT_EXIT*, and EXPECT_EXIT*.
154#define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \
155  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
156  if (::testing::internal::AlwaysTrue()) { \
157    const ::testing::internal::RE& gtest_regex = (regex); \
158    ::testing::internal::DeathTest* gtest_dt; \
159    if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \
160        __FILE__, __LINE__, &gtest_dt)) { \
161      goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
162    } \
163    if (gtest_dt != NULL) { \
164      ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
165          gtest_dt_ptr(gtest_dt); \
166      switch (gtest_dt->AssumeRole()) { \
167        case ::testing::internal::DeathTest::OVERSEE_TEST: \
168          if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
169            goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
170          } \
171          break; \
172        case ::testing::internal::DeathTest::EXECUTE_TEST: { \
173          ::testing::internal::DeathTest::ReturnSentinel \
174              gtest_sentinel(gtest_dt); \
175          GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
176          gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
177          break; \
178        } \
179      } \
180    } \
181  } else \
182    GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \
183      fail(::testing::internal::DeathTest::LastMessage())
184// The symbol "fail" here expands to something into which a message
185// can be streamed.
186
187// A class representing the parsed contents of the
188// --gtest_internal_run_death_test flag, as it existed when
189// RUN_ALL_TESTS was called.
190class InternalRunDeathTestFlag {
191 public:
192  InternalRunDeathTestFlag(const String& file,
193                           int line,
194                           int index,
195                           int write_fd)
196      : file_(file), line_(line), index_(index), write_fd_(write_fd) {}
197
198  ~InternalRunDeathTestFlag() {
199    if (write_fd_ >= 0)
200      posix::Close(write_fd_);
201  }
202
203  String file() const { return file_; }
204  int line() const { return line_; }
205  int index() const { return index_; }
206  int write_fd() const { return write_fd_; }
207
208 private:
209  String file_;
210  int line_;
211  int index_;
212  int write_fd_;
213
214  GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
215};
216
217// Returns a newly created InternalRunDeathTestFlag object with fields
218// initialized from the GTEST_FLAG(internal_run_death_test) flag if
219// the flag is specified; otherwise returns NULL.
220InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
221
222#else  // GTEST_HAS_DEATH_TEST
223
224// This macro is used for implementing macros such as
225// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
226// death tests are not supported. Those macros must compile on such systems
227// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
228// systems that support death tests. This allows one to write such a macro
229// on a system that does not support death tests and be sure that it will
230// compile on a death-test supporting system.
231//
232// Parameters:
233//   statement -  A statement that a macro such as EXPECT_DEATH would test
234//                for program termination. This macro has to make sure this
235//                statement is compiled but not executed, to ensure that
236//                EXPECT_DEATH_IF_SUPPORTED compiles with a certain
237//                parameter iff EXPECT_DEATH compiles with it.
238//   regex     -  A regex that a macro such as EXPECT_DEATH would use to test
239//                the output of statement.  This parameter has to be
240//                compiled but not evaluated by this macro, to ensure that
241//                this macro only accepts expressions that a macro such as
242//                EXPECT_DEATH would accept.
243//   terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
244//                and a return statement for ASSERT_DEATH_IF_SUPPORTED.
245//                This ensures that ASSERT_DEATH_IF_SUPPORTED will not
246//                compile inside functions where ASSERT_DEATH doesn't
247//                compile.
248//
249//  The branch that has an always false condition is used to ensure that
250//  statement and regex are compiled (and thus syntactically correct) but
251//  never executed. The unreachable code macro protects the terminator
252//  statement from generating an 'unreachable code' warning in case
253//  statement unconditionally returns or throws. The Message constructor at
254//  the end allows the syntax of streaming additional messages into the
255//  macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
256#define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
257    GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
258    if (::testing::internal::AlwaysTrue()) { \
259      GTEST_LOG_(WARNING) \
260          << "Death tests are not supported on this platform.\n" \
261          << "Statement '" #statement "' cannot be verified."; \
262    } else if (::testing::internal::AlwaysFalse()) { \
263      ::testing::internal::RE::PartialMatch(".*", (regex)); \
264      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
265      terminator; \
266    } else \
267      ::testing::Message()
268
269#endif  // GTEST_HAS_DEATH_TEST
270
271}  // namespace internal
272}  // namespace testing
273
274#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
275