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 <string>
  41. #include "gtest/gtest-matchers.h"
  42. #include "gtest/internal/gtest-internal.h"
  43. #include "gtest/internal/gtest-port.h"
  44. GTEST_DECLARE_string_(internal_run_death_test);
  45. namespace testing {
  46. namespace internal {
  47. // Name of the flag (needed for parsing Google Test flag).
  48. const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
  49. // A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
  50. // and interpreted as a regex (rather than an Eq matcher) for legacy
  51. // compatibility.
  52. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  53. ::testing::internal::RE regex) {
  54. return ContainsRegex(regex.pattern());
  55. }
  56. inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
  57. return ContainsRegex(regex);
  58. }
  59. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  60. const ::std::string& regex) {
  61. return ContainsRegex(regex);
  62. }
  63. // If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
  64. // used directly.
  65. inline Matcher<const ::std::string&> MakeDeathTestMatcher(
  66. Matcher<const ::std::string&> matcher) {
  67. return matcher;
  68. }
  69. #ifdef GTEST_HAS_DEATH_TEST
  70. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  71. /* class A needs to have dll-interface to be used by clients of class B */)
  72. // DeathTest is a class that hides much of the complexity of the
  73. // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
  74. // returns a concrete class that depends on the prevailing death test
  75. // style, as defined by the --gtest_death_test_style and/or
  76. // --gtest_internal_run_death_test flags.
  77. // In describing the results of death tests, these terms are used with
  78. // the corresponding definitions:
  79. //
  80. // exit status: The integer exit information in the format specified
  81. // by wait(2)
  82. // exit code: The integer code passed to exit(3), _Exit(2), or
  83. // returned from main()
  84. class GTEST_API_ DeathTest {
  85. public:
  86. // Create returns false if there was an error determining the
  87. // appropriate action to take for the current death test; for example,
  88. // if the gtest_death_test_style flag is set to an invalid value.
  89. // The LastMessage method will return a more detailed message in that
  90. // case. Otherwise, the DeathTest pointer pointed to by the "test"
  91. // argument is set. If the death test should be skipped, the pointer
  92. // is set to NULL; otherwise, it is set to the address of a new concrete
  93. // DeathTest object that controls the execution of the current test.
  94. static bool Create(const char* statement, Matcher<const std::string&> matcher,
  95. const char* file, int line, DeathTest** test);
  96. DeathTest();
  97. virtual ~DeathTest() = default;
  98. // A helper class that aborts a death test when it's deleted.
  99. class ReturnSentinel {
  100. public:
  101. explicit ReturnSentinel(DeathTest* test) : test_(test) {}
  102. ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
  103. private:
  104. DeathTest* const test_;
  105. ReturnSentinel(const ReturnSentinel&) = delete;
  106. ReturnSentinel& operator=(const ReturnSentinel&) = delete;
  107. };
  108. // An enumeration of possible roles that may be taken when a death
  109. // test is encountered. EXECUTE means that the death test logic should
  110. // be executed immediately. OVERSEE means that the program should prepare
  111. // the appropriate environment for a child process to execute the death
  112. // test, then wait for it to complete.
  113. enum TestRole { OVERSEE_TEST, EXECUTE_TEST };
  114. // An enumeration of the three reasons that a test might be aborted.
  115. enum AbortReason {
  116. TEST_ENCOUNTERED_RETURN_STATEMENT,
  117. TEST_THREW_EXCEPTION,
  118. TEST_DID_NOT_DIE
  119. };
  120. // Assumes one of the above roles.
  121. virtual TestRole AssumeRole() = 0;
  122. // Waits for the death test to finish and returns its status.
  123. virtual int Wait() = 0;
  124. // Returns true if the death test passed; that is, the test process
  125. // exited during the test, its exit status matches a user-supplied
  126. // predicate, and its stderr output matches a user-supplied regular
  127. // expression.
  128. // The user-supplied predicate may be a macro expression rather
  129. // than a function pointer or functor, or else Wait and Passed could
  130. // be combined.
  131. virtual bool Passed(bool exit_status_ok) = 0;
  132. // Signals that the death test did not die as expected.
  133. virtual void Abort(AbortReason reason) = 0;
  134. // Returns a human-readable outcome message regarding the outcome of
  135. // the last death test.
  136. static const char* LastMessage();
  137. static void set_last_death_test_message(const std::string& message);
  138. private:
  139. // A string containing a description of the outcome of the last death test.
  140. static std::string last_death_test_message_;
  141. DeathTest(const DeathTest&) = delete;
  142. DeathTest& operator=(const DeathTest&) = delete;
  143. };
  144. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  145. // Factory interface for death tests. May be mocked out for testing.
  146. class DeathTestFactory {
  147. public:
  148. virtual ~DeathTestFactory() = default;
  149. virtual bool Create(const char* statement,
  150. Matcher<const std::string&> matcher, const char* file,
  151. int line, DeathTest** test) = 0;
  152. };
  153. // A concrete DeathTestFactory implementation for normal use.
  154. class DefaultDeathTestFactory : public DeathTestFactory {
  155. public:
  156. bool Create(const char* statement, Matcher<const std::string&> matcher,
  157. const char* file, int line, DeathTest** test) override;
  158. };
  159. // Returns true if exit_status describes a process that was terminated
  160. // by a signal, or exited normally with a nonzero exit code.
  161. GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
  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. const ::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_