Home | History | Annotate | Download | only in internal
      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 (at) google.com (Zhanyong Wan), eefacm (at) 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 
     42 namespace testing {
     43 namespace internal {
     44 
     45 GTEST_DECLARE_string_(internal_run_death_test);
     46 
     47 // Names of the flags (needed for parsing Google Test flags).
     48 const char kDeathTestStyleFlag[] = "death_test_style";
     49 const char kDeathTestUseFork[] = "death_test_use_fork";
     50 const 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()
     67 class GTEST_API_ 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.
    134 class 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.
    142 class 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.
    150 GTEST_API_ bool 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.
    190 class InternalRunDeathTestFlag {
    191  public:
    192   InternalRunDeathTestFlag(const String& a_file,
    193                            int a_line,
    194                            int an_index,
    195                            int a_write_fd)
    196       : file_(a_file), line_(a_line), index_(an_index),
    197         write_fd_(a_write_fd) {}
    198 
    199   ~InternalRunDeathTestFlag() {
    200     if (write_fd_ >= 0)
    201       posix::Close(write_fd_);
    202   }
    203 
    204   String file() const { return file_; }
    205   int line() const { return line_; }
    206   int index() const { return index_; }
    207   int write_fd() const { return write_fd_; }
    208 
    209  private:
    210   String file_;
    211   int line_;
    212   int index_;
    213   int write_fd_;
    214 
    215   GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
    216 };
    217 
    218 // Returns a newly created InternalRunDeathTestFlag object with fields
    219 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
    220 // the flag is specified; otherwise returns NULL.
    221 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
    222 
    223 #else  // GTEST_HAS_DEATH_TEST
    224 
    225 // This macro is used for implementing macros such as
    226 // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
    227 // death tests are not supported. Those macros must compile on such systems
    228 // iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
    229 // systems that support death tests. This allows one to write such a macro
    230 // on a system that does not support death tests and be sure that it will
    231 // compile on a death-test supporting system.
    232 //
    233 // Parameters:
    234 //   statement -  A statement that a macro such as EXPECT_DEATH would test
    235 //                for program termination. This macro has to make sure this
    236 //                statement is compiled but not executed, to ensure that
    237 //                EXPECT_DEATH_IF_SUPPORTED compiles with a certain
    238 //                parameter iff EXPECT_DEATH compiles with it.
    239 //   regex     -  A regex that a macro such as EXPECT_DEATH would use to test
    240 //                the output of statement.  This parameter has to be
    241 //                compiled but not evaluated by this macro, to ensure that
    242 //                this macro only accepts expressions that a macro such as
    243 //                EXPECT_DEATH would accept.
    244 //   terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
    245 //                and a return statement for ASSERT_DEATH_IF_SUPPORTED.
    246 //                This ensures that ASSERT_DEATH_IF_SUPPORTED will not
    247 //                compile inside functions where ASSERT_DEATH doesn't
    248 //                compile.
    249 //
    250 //  The branch that has an always false condition is used to ensure that
    251 //  statement and regex are compiled (and thus syntactically correct) but
    252 //  never executed. The unreachable code macro protects the terminator
    253 //  statement from generating an 'unreachable code' warning in case
    254 //  statement unconditionally returns or throws. The Message constructor at
    255 //  the end allows the syntax of streaming additional messages into the
    256 //  macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
    257 #define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
    258     GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
    259     if (::testing::internal::AlwaysTrue()) { \
    260       GTEST_LOG_(WARNING) \
    261           << "Death tests are not supported on this platform.\n" \
    262           << "Statement '" #statement "' cannot be verified."; \
    263     } else if (::testing::internal::AlwaysFalse()) { \
    264       ::testing::internal::RE::PartialMatch(".*", (regex)); \
    265       GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
    266       terminator; \
    267     } else \
    268       ::testing::Message()
    269 
    270 #endif  // GTEST_HAS_DEATH_TEST
    271 
    272 }  // namespace internal
    273 }  // namespace testing
    274 
    275 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
    276