Debian Codegraph @

llvm-project/third-party/unittest/googletest/include/gtest/gtest-death-test.h

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