gtest-death-test-internal.h 13 KB

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