gtest-death-test.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 the public API for death tests. It is
  33. // #included by gtest.h so a user doesn't need to include this
  34. // directly.
  35. // GOOGLETEST_CM0001 DO NOT DELETE
  36. #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  37. #define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
  38. #include "gtest/internal/gtest-death-test-internal.h"
  39. namespace testing {
  40. // This flag controls the style of death tests. Valid values are "threadsafe",
  41. // meaning that the death test child process will re-execute the test binary
  42. // from the start, running only a single death test, or "fast",
  43. // meaning that the child process will execute the test logic immediately
  44. // after forking.
  45. GTEST_DECLARE_string_(death_test_style);
  46. #if GTEST_HAS_DEATH_TEST
  47. namespace internal {
  48. // Returns a Boolean value indicating whether the caller is currently
  49. // executing in the context of the death test child process. Tools such as
  50. // Valgrind heap checkers may need this to modify their behavior in death
  51. // tests. IMPORTANT: This is an internal utility. Using it may break the
  52. // implementation of death tests. User code MUST NOT use it.
  53. GTEST_API_ bool InDeathTestChild();
  54. } // namespace internal
  55. // The following macros are useful for writing death tests.
  56. // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is
  57. // executed:
  58. //
  59. // 1. It generates a warning if there is more than one active
  60. // thread. This is because it's safe to fork() or clone() only
  61. // when there is a single thread.
  62. //
  63. // 2. The parent process clone()s a sub-process and runs the death
  64. // test in it; the sub-process exits with code 0 at the end of the
  65. // death test, if it hasn't exited already.
  66. //
  67. // 3. The parent process waits for the sub-process to terminate.
  68. //
  69. // 4. The parent process checks the exit code and error message of
  70. // the sub-process.
  71. //
  72. // Examples:
  73. //
  74. // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");
  75. // for (int i = 0; i < 5; i++) {
  76. // EXPECT_DEATH(server.ProcessRequest(i),
  77. // "Invalid request .* in ProcessRequest()")
  78. // << "Failed to die on request " << i;
  79. // }
  80. //
  81. // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");
  82. //
  83. // bool KilledBySIGHUP(int exit_code) {
  84. // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;
  85. // }
  86. //
  87. // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
  88. //
  89. // The final parameter to each of these macros is a matcher applied to any data
  90. // the sub-process wrote to stderr. For compatibility with existing tests, a
  91. // bare string is interpreted as a regular expression matcher.
  92. //
  93. // On the regular expressions used in death tests:
  94. //
  95. // GOOGLETEST_CM0005 DO NOT DELETE
  96. // On POSIX-compliant systems (*nix), we use the <regex.h> library,
  97. // which uses the POSIX extended regex syntax.
  98. //
  99. // On other platforms (e.g. Windows or Mac), we only support a simple regex
  100. // syntax implemented as part of Google Test. This limited
  101. // implementation should be enough most of the time when writing
  102. // death tests; though it lacks many features you can find in PCRE
  103. // or POSIX extended regex syntax. For example, we don't support
  104. // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and
  105. // repetition count ("x{5,7}"), among others.
  106. //
  107. // Below is the syntax that we do support. We chose it to be a
  108. // subset of both PCRE and POSIX extended regex, so it's easy to
  109. // learn wherever you come from. In the following: 'A' denotes a
  110. // literal character, period (.), or a single \\ escape sequence;
  111. // 'x' and 'y' denote regular expressions; 'm' and 'n' are for
  112. // natural numbers.
  113. //
  114. // c matches any literal character c
  115. // \\d matches any decimal digit
  116. // \\D matches any character that's not a decimal digit
  117. // \\f matches \f
  118. // \\n matches \n
  119. // \\r matches \r
  120. // \\s matches any ASCII whitespace, including \n
  121. // \\S matches any character that's not a whitespace
  122. // \\t matches \t
  123. // \\v matches \v
  124. // \\w matches any letter, _, or decimal digit
  125. // \\W matches any character that \\w doesn't match
  126. // \\c matches any literal character c, which must be a punctuation
  127. // . matches any single character except \n
  128. // A? matches 0 or 1 occurrences of A
  129. // A* matches 0 or many occurrences of A
  130. // A+ matches 1 or many occurrences of A
  131. // ^ matches the beginning of a string (not that of each line)
  132. // $ matches the end of a string (not that of each line)
  133. // xy matches x followed by y
  134. //
  135. // If you accidentally use PCRE or POSIX extended regex features
  136. // not implemented by us, you will get a run-time failure. In that
  137. // case, please try to rewrite your regular expression within the
  138. // above syntax.
  139. //
  140. // This implementation is *not* meant to be as highly tuned or robust
  141. // as a compiled regex library, but should perform well enough for a
  142. // death test, which already incurs significant overhead by launching
  143. // a child process.
  144. //
  145. // Known caveats:
  146. //
  147. // A "threadsafe" style death test obtains the path to the test
  148. // program from argv[0] and re-executes it in the sub-process. For
  149. // simplicity, the current implementation doesn't search the PATH
  150. // when launching the sub-process. This means that the user must
  151. // invoke the test program via a path that contains at least one
  152. // path separator (e.g. path/to/foo_test and
  153. // /absolute/path/to/bar_test are fine, but foo_test is not). This
  154. // is rarely a problem as people usually don't put the test binary
  155. // directory in PATH.
  156. //
  157. // Asserts that a given `statement` causes the program to exit, with an
  158. // integer exit status that satisfies `predicate`, and emitting error output
  159. // that matches `matcher`.
  160. # define ASSERT_EXIT(statement, predicate, matcher) \
  161. GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
  162. // Like `ASSERT_EXIT`, but continues on to successive tests in the
  163. // test suite, if any:
  164. # define EXPECT_EXIT(statement, predicate, matcher) \
  165. GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
  166. // Asserts that a given `statement` causes the program to exit, either by
  167. // explicitly exiting with a nonzero exit code or being killed by a
  168. // signal, and emitting error output that matches `matcher`.
  169. # define ASSERT_DEATH(statement, matcher) \
  170. ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
  171. // Like `ASSERT_DEATH`, but continues on to successive tests in the
  172. // test suite, if any:
  173. # define EXPECT_DEATH(statement, matcher) \
  174. EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
  175. // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
  176. // Tests that an exit code describes a normal exit with a given exit code.
  177. class GTEST_API_ ExitedWithCode {
  178. public:
  179. explicit ExitedWithCode(int exit_code);
  180. ExitedWithCode(const ExitedWithCode&) = default;
  181. void operator=(const ExitedWithCode& other) = delete;
  182. bool operator()(int exit_status) const;
  183. private:
  184. const int exit_code_;
  185. };
  186. # if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
  187. // Tests that an exit code describes an exit due to termination by a
  188. // given signal.
  189. // GOOGLETEST_CM0006 DO NOT DELETE
  190. class GTEST_API_ KilledBySignal {
  191. public:
  192. explicit KilledBySignal(int signum);
  193. bool operator()(int exit_status) const;
  194. private:
  195. const int signum_;
  196. };
  197. # endif // !GTEST_OS_WINDOWS
  198. // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
  199. // The death testing framework causes this to have interesting semantics,
  200. // since the sideeffects of the call are only visible in opt mode, and not
  201. // in debug mode.
  202. //
  203. // In practice, this can be used to test functions that utilize the
  204. // LOG(DFATAL) macro using the following style:
  205. //
  206. // int DieInDebugOr12(int* sideeffect) {
  207. // if (sideeffect) {
  208. // *sideeffect = 12;
  209. // }
  210. // LOG(DFATAL) << "death";
  211. // return 12;
  212. // }
  213. //
  214. // TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
  215. // int sideeffect = 0;
  216. // // Only asserts in dbg.
  217. // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
  218. //
  219. // #ifdef NDEBUG
  220. // // opt-mode has sideeffect visible.
  221. // EXPECT_EQ(12, sideeffect);
  222. // #else
  223. // // dbg-mode no visible sideeffect.
  224. // EXPECT_EQ(0, sideeffect);
  225. // #endif
  226. // }
  227. //
  228. // This will assert that DieInDebugReturn12InOpt() crashes in debug
  229. // mode, usually due to a DCHECK or LOG(DFATAL), but returns the
  230. // appropriate fallback value (12 in this case) in opt mode. If you
  231. // need to test that a function has appropriate side-effects in opt
  232. // mode, include assertions against the side-effects. A general
  233. // pattern for this is:
  234. //
  235. // EXPECT_DEBUG_DEATH({
  236. // // Side-effects here will have an effect after this statement in
  237. // // opt mode, but none in debug mode.
  238. // EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
  239. // }, "death");
  240. //
  241. # ifdef NDEBUG
  242. # define EXPECT_DEBUG_DEATH(statement, regex) \
  243. GTEST_EXECUTE_STATEMENT_(statement, regex)
  244. # define ASSERT_DEBUG_DEATH(statement, regex) \
  245. GTEST_EXECUTE_STATEMENT_(statement, regex)
  246. # else
  247. # define EXPECT_DEBUG_DEATH(statement, regex) \
  248. EXPECT_DEATH(statement, regex)
  249. # define ASSERT_DEBUG_DEATH(statement, regex) \
  250. ASSERT_DEATH(statement, regex)
  251. # endif // NDEBUG for EXPECT_DEBUG_DEATH
  252. #endif // GTEST_HAS_DEATH_TEST
  253. // This macro is used for implementing macros such as
  254. // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
  255. // death tests are not supported. Those macros must compile on such systems
  256. // if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
  257. // on systems that support death tests. This allows one to write such a macro on
  258. // a system that does not support death tests and be sure that it will compile
  259. // on a death-test supporting system. It is exposed publicly so that systems
  260. // that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
  261. // can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
  262. // ASSERT_DEATH_IF_SUPPORTED.
  263. //
  264. // Parameters:
  265. // statement - A statement that a macro such as EXPECT_DEATH would test
  266. // for program termination. This macro has to make sure this
  267. // statement is compiled but not executed, to ensure that
  268. // EXPECT_DEATH_IF_SUPPORTED compiles with a certain
  269. // parameter if and only if EXPECT_DEATH compiles with it.
  270. // regex - A regex that a macro such as EXPECT_DEATH would use to test
  271. // the output of statement. This parameter has to be
  272. // compiled but not evaluated by this macro, to ensure that
  273. // this macro only accepts expressions that a macro such as
  274. // EXPECT_DEATH would accept.
  275. // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
  276. // and a return statement for ASSERT_DEATH_IF_SUPPORTED.
  277. // This ensures that ASSERT_DEATH_IF_SUPPORTED will not
  278. // compile inside functions where ASSERT_DEATH doesn't
  279. // compile.
  280. //
  281. // The branch that has an always false condition is used to ensure that
  282. // statement and regex are compiled (and thus syntactically correct) but
  283. // never executed. The unreachable code macro protects the terminator
  284. // statement from generating an 'unreachable code' warning in case
  285. // statement unconditionally returns or throws. The Message constructor at
  286. // the end allows the syntax of streaming additional messages into the
  287. // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
  288. # define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
  289. GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
  290. if (::testing::internal::AlwaysTrue()) { \
  291. GTEST_LOG_(WARNING) \
  292. << "Death tests are not supported on this platform.\n" \
  293. << "Statement '" #statement "' cannot be verified."; \
  294. } else if (::testing::internal::AlwaysFalse()) { \
  295. ::testing::internal::RE::PartialMatch(".*", (regex)); \
  296. GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
  297. terminator; \
  298. } else \
  299. ::testing::Message()
  300. // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
  301. // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
  302. // death tests are supported; otherwise they just issue a warning. This is
  303. // useful when you are combining death test assertions with normal test
  304. // assertions in one test.
  305. #if GTEST_HAS_DEATH_TEST
  306. # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
  307. EXPECT_DEATH(statement, regex)
  308. # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
  309. ASSERT_DEATH(statement, regex)
  310. #else
  311. # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
  312. GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
  313. # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
  314. GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
  315. #endif
  316. } // namespace testing
  317. #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_