You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
13 KiB

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