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.

319 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 std::string& message);
  113. private:
  114. // A string containing a description of the outcome of the last death test.
  115. static std::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. // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
  193. // NDEBUG mode. In this case we need the statements to be executed, the regex is
  194. // ignored, and the macro must accept a streamed message even though the message
  195. // is never printed.
  196. # define GTEST_EXECUTE_STATEMENT_(statement, regex) \
  197. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  198. if (::testing::internal::AlwaysTrue()) { \
  199. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  200. } else \
  201. ::testing::Message()
  202. // A class representing the parsed contents of the
  203. // --gtest_internal_run_death_test flag, as it existed when
  204. // RUN_ALL_TESTS was called.
  205. class InternalRunDeathTestFlag {
  206. public:
  207. InternalRunDeathTestFlag(const std::string& a_file,
  208. int a_line,
  209. int an_index,
  210. int a_write_fd)
  211. : file_(a_file), line_(a_line), index_(an_index),
  212. write_fd_(a_write_fd) {}
  213. ~InternalRunDeathTestFlag() {
  214. if (write_fd_ >= 0)
  215. posix::Close(write_fd_);
  216. }
  217. const std::string& file() const { return file_; }
  218. int line() const { return line_; }
  219. int index() const { return index_; }
  220. int write_fd() const { return write_fd_; }
  221. private:
  222. std::string file_;
  223. int line_;
  224. int index_;
  225. int write_fd_;
  226. GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
  227. };
  228. // Returns a newly created InternalRunDeathTestFlag object with fields
  229. // initialized from the GTEST_FLAG(internal_run_death_test) flag if
  230. // the flag is specified; otherwise returns NULL.
  231. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
  232. #else // GTEST_HAS_DEATH_TEST
  233. // This macro is used for implementing macros such as
  234. // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
  235. // death tests are not supported. Those macros must compile on such systems
  236. // iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
  237. // systems that support death tests. This allows one to write such a macro
  238. // on a system that does not support death tests and be sure that it will
  239. // compile on a death-test supporting system.
  240. //
  241. // Parameters:
  242. // statement - A statement that a macro such as EXPECT_DEATH would test
  243. // for program termination. This macro has to make sure this
  244. // statement is compiled but not executed, to ensure that
  245. // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
  246. // parameter iff EXPECT_DEATH compiles with it.
  247. // regex - A regex that a macro such as EXPECT_DEATH would use to test
  248. // the output of statement. This parameter has to be
  249. // compiled but not evaluated by this macro, to ensure that
  250. // this macro only accepts expressions that a macro such as
  251. // EXPECT_DEATH would accept.
  252. // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
  253. // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
  254. // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
  255. // compile inside functions where ASSERT_DEATH doesn't
  256. // compile.
  257. //
  258. // The branch that has an always false condition is used to ensure that
  259. // statement and regex are compiled (and thus syntactically correct) but
  260. // never executed. The unreachable code macro protects the terminator
  261. // statement from generating an 'unreachable code' warning in case
  262. // statement unconditionally returns or throws. The Message constructor at
  263. // the end allows the syntax of streaming additional messages into the
  264. // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
  265. # define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
  266. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  267. if (::testing::internal::AlwaysTrue()) { \
  268. GTEST_LOG_(WARNING) \
  269. << "Death tests are not supported on this platform.\n" \
  270. << "Statement '" #statement "' cannot be verified."; \
  271. } else if (::testing::internal::AlwaysFalse()) { \
  272. ::testing::internal::RE::PartialMatch(".*", (regex)); \
  273. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  274. terminator; \
  275. } else \
  276. ::testing::Message()
  277. #endif // GTEST_HAS_DEATH_TEST
  278. } // namespace internal
  279. } // namespace testing
  280. #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_