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 // The Google C++ Testing and Mocking Framework (Google Test)
  31 //
  32 // This header file defines internal utilities needed for implementing
  33 // death tests.  They are subject to change without notice.
  34 // GOOGLETEST_CM0001 DO NOT DELETE
  35 
  36 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  37 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
  38 
  39 #include "gtest/internal/gtest-internal.h"
  40 
  41 #include <stdio.h>
  42 
  43 namespace testing {
  44 namespace internal {
  45 
  46 GTEST_DECLARE_string_(internal_run_death_test);
  47 
  48 // Names of the flags (needed for parsing Google Test flags).
  49 const char kDeathTestStyleFlag[] = "death_test_style";
  50 const char kDeathTestUseFork[] = "death_test_use_fork";
  51 const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
  52 
  53 #if GTEST_HAS_DEATH_TEST
  54 
  55 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  56 /* class A needs to have dll-interface to be used by clients of class B */)
  57 
  58 // DeathTest is a class that hides much of the complexity of the
  59 // GTEST_DEATH_TEST_ macro.  It is abstract; its static Create method
  60 // returns a concrete class that depends on the prevailing death test
  61 // style, as defined by the --gtest_death_test_style and/or
  62 // --gtest_internal_run_death_test flags.
  63 
  64 // In describing the results of death tests, these terms are used with
  65 // the corresponding definitions:
  66 //
  67 // exit status:  The integer exit information in the format specified
  68 //               by wait(2)
  69 // exit code:    The integer code passed to exit(3), _exit(2), or
  70 //               returned from main()
  71 class GTEST_API_ DeathTest {
  72  public:
  73   // Create returns false if there was an error determining the
  74   // appropriate action to take for the current death test; for example,
  75   // if the gtest_death_test_style flag is set to an invalid value.
  76   // The LastMessage method will return a more detailed message in that
  77   // case.  Otherwise, the DeathTest pointer pointed to by the "test"
  78   // argument is set.  If the death test should be skipped, the pointer
  79   // is set to NULL; otherwise, it is set to the address of a new concrete
  80   // DeathTest object that controls the execution of the current test.
  81   static bool Create(const char* statement, const RE* regex,
  82                      const char* file, int line, DeathTest** test);
  83   DeathTest();
  84   virtual ~DeathTest() { }
  85 
  86   // A helper class that aborts a death test when it's deleted.
  87   class ReturnSentinel {
  88    public:
  89     explicit ReturnSentinel(DeathTest* test) : test_(test) { }
  90     ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
  91    private:
  92     DeathTest* const test_;
  93     GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
  94   } GTEST_ATTRIBUTE_UNUSED_;
  95 
  96   // An enumeration of possible roles that may be taken when a death
  97   // test is encountered.  EXECUTE means that the death test logic should
  98   // be executed immediately.  OVERSEE means that the program should prepare
  99   // the appropriate environment for a child process to execute the death
 100   // test, then wait for it to complete.
 101   enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
 102 
 103   // An enumeration of the three reasons that a test might be aborted.
 104   enum AbortReason {
 105     TEST_ENCOUNTERED_RETURN_STATEMENT,
 106     TEST_THREW_EXCEPTION,
 107     TEST_DID_NOT_DIE
 108   };
 109 
 110   // Assumes one of the above roles.
 111   virtual TestRole AssumeRole() = 0;
 112 
 113   // Waits for the death test to finish and returns its status.
 114   virtual int Wait() = 0;
 115 
 116   // Returns true if the death test passed; that is, the test process
 117   // exited during the test, its exit status matches a user-supplied
 118   // predicate, and its stderr output matches a user-supplied regular
 119   // expression.
 120   // The user-supplied predicate may be a macro expression rather
 121   // than a function pointer or functor, or else Wait and Passed could
 122   // be combined.
 123   virtual bool Passed(bool exit_status_ok) = 0;
 124 
 125   // Signals that the death test did not die as expected.
 126   virtual void Abort(AbortReason reason) = 0;
 127 
 128   // Returns a human-readable outcome message regarding the outcome of
 129   // the last death test.
 130   static const char* LastMessage();
 131 
 132   static void set_last_death_test_message(const std::string& message);
 133 
 134  private:
 135   // A string containing a description of the outcome of the last death test.
 136   static std::string last_death_test_message_;
 137 
 138   GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
 139 };
 140 
 141 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
 142 
 143 // Factory interface for death tests.  May be mocked out for testing.
 144 class DeathTestFactory {
 145  public:
 146   virtual ~DeathTestFactory() { }
 147   virtual bool Create(const char* statement, const RE* regex,
 148                       const char* file, int line, DeathTest** test) = 0;
 149 };
 150 
 151 // A concrete DeathTestFactory implementation for normal use.
 152 class DefaultDeathTestFactory : public DeathTestFactory {
 153  public:
 154   virtual bool Create(const char* statement, const RE* regex,
 155                       const char* file, int line, DeathTest** test);
 156 };
 157 
 158 // Returns true if exit_status describes a process that was terminated
 159 // by a signal, or exited normally with a nonzero exit code.
 160 GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
 161 
 162 // Traps C++ exceptions escaping statement and reports them as test
 163 // failures. Note that trapping SEH exceptions is not implemented here.
 164 # if GTEST_HAS_EXCEPTIONS
 165 #  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
 166   try { \
 167     GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
 168   } catch (const ::std::exception& gtest_exception) { \
 169     fprintf(\
 170         stderr, \
 171         "\n%s: Caught std::exception-derived exception escaping the " \
 172         "death test statement. Exception message: %s\n", \
 173         ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
 174         gtest_exception.what()); \
 175     fflush(stderr); \
 176     death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
 177   } catch (...) { \
 178     death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
 179   }
 180 
 181 # else
 182 #  define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
 183   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
 184 
 185 # endif
 186 
 187 // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
 188 // ASSERT_EXIT*, and EXPECT_EXIT*.
 189 # define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \
 190   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
 191   if (::testing::internal::AlwaysTrue()) { \
 192     const ::testing::internal::RE& gtest_regex = (regex); \
 193     ::testing::internal::DeathTest* gtest_dt; \
 194     if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \
 195         __FILE__, __LINE__, &gtest_dt)) { \
 196       goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
 197     } \
 198     if (gtest_dt != NULL) { \
 199       ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
 200           gtest_dt_ptr(gtest_dt); \
 201       switch (gtest_dt->AssumeRole()) { \
 202         case ::testing::internal::DeathTest::OVERSEE_TEST: \
 203           if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
 204             goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
 205           } \
 206           break; \
 207         case ::testing::internal::DeathTest::EXECUTE_TEST: { \
 208           ::testing::internal::DeathTest::ReturnSentinel \
 209               gtest_sentinel(gtest_dt); \
 210           GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
 211           gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
 212           break; \
 213         } \
 214         default: \
 215           break; \
 216       } \
 217     } \
 218   } else \
 219     GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \
 220       fail(::testing::internal::DeathTest::LastMessage())
 221 // The symbol "fail" here expands to something into which a message
 222 // can be streamed.
 223 
 224 // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
 225 // NDEBUG mode. In this case we need the statements to be executed and the macro
 226 // must accept a streamed message even though the message is never printed.
 227 // The regex object is not evaluated, but it is used to prevent "unused"
 228 // warnings and to avoid an expression that doesn't compile in debug mode.
 229 #define GTEST_EXECUTE_STATEMENT_(statement, regex)             \
 230   GTEST_AMBIGUOUS_ELSE_BLOCKER_                                \
 231   if (::testing::internal::AlwaysTrue()) {                     \
 232     GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
 233   } else if (!::testing::internal::AlwaysTrue()) {             \
 234     const ::testing::internal::RE& gtest_regex = (regex);      \
 235     static_cast<void>(gtest_regex);                            \
 236   } else                                                       \
 237     ::testing::Message()
 238 
 239 // A class representing the parsed contents of the
 240 // --gtest_internal_run_death_test flag, as it existed when
 241 // RUN_ALL_TESTS was called.
 242 class InternalRunDeathTestFlag {
 243  public:
 244   InternalRunDeathTestFlag(const std::string& a_file,
 245                            int a_line,
 246                            int an_index,
 247                            int a_write_fd)
 248       : file_(a_file), line_(a_line), index_(an_index),
 249         write_fd_(a_write_fd) {}
 250 
 251   ~InternalRunDeathTestFlag() {
 252     if (write_fd_ >= 0)
 253       posix::Close(write_fd_);
 254   }
 255 
 256   const std::string& file() const { return file_; }
 257   int line() const { return line_; }
 258   int index() const { return index_; }
 259   int write_fd() const { return write_fd_; }
 260 
 261  private:
 262   std::string file_;
 263   int line_;
 264   int index_;
 265   int write_fd_;
 266 
 267   GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
 268 };
 269 
 270 // Returns a newly created InternalRunDeathTestFlag object with fields
 271 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
 272 // the flag is specified; otherwise returns NULL.
 273 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
 274 
 275 #endif  // GTEST_HAS_DEATH_TEST
 276 
 277 }  // namespace internal
 278 }  // namespace testing
 279 
 280 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_