gtest-death-test-internal.h 14 KB

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