gtest-death-test-internal.h 14 KB

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