Path: blob/master/dep/googletest/include/gtest/gtest-death-test.h
4806 views
// Copyright 2005, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// The Google C++ Testing and Mocking Framework (Google Test)30//31// This header file defines the public API for death tests. It is32// #included by gtest.h so a user doesn't need to include this33// directly.3435// IWYU pragma: private, include "gtest/gtest.h"36// IWYU pragma: friend gtest/.*37// IWYU pragma: friend gmock/.*3839#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_40#define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_4142#include "gtest/internal/gtest-death-test-internal.h"4344// This flag controls the style of death tests. Valid values are "threadsafe",45// meaning that the death test child process will re-execute the test binary46// from the start, running only a single death test, or "fast",47// meaning that the child process will execute the test logic immediately48// after forking.49GTEST_DECLARE_string_(death_test_style);5051namespace testing {5253#ifdef GTEST_HAS_DEATH_TEST5455namespace internal {5657// Returns a Boolean value indicating whether the caller is currently58// executing in the context of the death test child process. Tools such as59// Valgrind heap checkers may need this to modify their behavior in death60// tests. IMPORTANT: This is an internal utility. Using it may break the61// implementation of death tests. User code MUST NOT use it.62GTEST_API_ bool InDeathTestChild();6364} // namespace internal6566// The following macros are useful for writing death tests.6768// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is69// executed:70//71// 1. It generates a warning if there is more than one active72// thread. This is because it's safe to fork() or clone() only73// when there is a single thread.74//75// 2. The parent process clone()s a sub-process and runs the death76// test in it; the sub-process exits with code 0 at the end of the77// death test, if it hasn't exited already.78//79// 3. The parent process waits for the sub-process to terminate.80//81// 4. The parent process checks the exit code and error message of82// the sub-process.83//84// Examples:85//86// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number");87// for (int i = 0; i < 5; i++) {88// EXPECT_DEATH(server.ProcessRequest(i),89// "Invalid request .* in ProcessRequest()")90// << "Failed to die on request " << i;91// }92//93// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting");94//95// bool KilledBySIGHUP(int exit_code) {96// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;97// }98//99// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");100//101// The final parameter to each of these macros is a matcher applied to any data102// the sub-process wrote to stderr. For compatibility with existing tests, a103// bare string is interpreted as a regular expression matcher.104//105// On the regular expressions used in death tests:106//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 regex111// syntax implemented as part of Google Test. This limited112// implementation should be enough most of the time when writing113// death tests; though it lacks many features you can find in PCRE114// or POSIX extended regex syntax. For example, we don't support115// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and116// repetition count ("x{5,7}"), among others.117//118// Below is the syntax that we do support. We chose it to be a119// subset of both PCRE and POSIX extended regex, so it's easy to120// learn wherever you come from. In the following: 'A' denotes a121// literal character, period (.), or a single \\ escape sequence;122// 'x' and 'y' denote regular expressions; 'm' and 'n' are for123// natural numbers.124//125// c matches any literal character c126// \\d matches any decimal digit127// \\D matches any character that's not a decimal digit128// \\f matches \f129// \\n matches \n130// \\r matches \r131// \\s matches any ASCII whitespace, including \n132// \\S matches any character that's not a whitespace133// \\t matches \t134// \\v matches \v135// \\w matches any letter, _, or decimal digit136// \\W matches any character that \\w doesn't match137// \\c matches any literal character c, which must be a punctuation138// . matches any single character except \n139// A? matches 0 or 1 occurrences of A140// A* matches 0 or many occurrences of A141// A+ matches 1 or many occurrences of A142// ^ 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 y145//146// If you accidentally use PCRE or POSIX extended regex features147// not implemented by us, you will get a run-time failure. In that148// case, please try to rewrite your regular expression within the149// above syntax.150//151// This implementation is *not* meant to be as highly tuned or robust152// as a compiled regex library, but should perform well enough for a153// death test, which already incurs significant overhead by launching154// a child process.155//156// Known caveats:157//158// A "threadsafe" style death test obtains the path to the test159// program from argv[0] and re-executes it in the sub-process. For160// simplicity, the current implementation doesn't search the PATH161// when launching the sub-process. This means that the user must162// invoke the test program via a path that contains at least one163// path separator (e.g. path/to/foo_test and164// /absolute/path/to/bar_test are fine, but foo_test is not). This165// is rarely a problem as people usually don't put the test binary166// directory in PATH.167//168169// Asserts that a given `statement` causes the program to exit, with an170// integer exit status that satisfies `predicate`, and emitting error output171// that matches `matcher`.172#define ASSERT_EXIT(statement, predicate, matcher) \173GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)174175// Like `ASSERT_EXIT`, but continues on to successive tests in the176// test suite, if any:177#define EXPECT_EXIT(statement, predicate, matcher) \178GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)179180// Asserts that a given `statement` causes the program to exit, either by181// explicitly exiting with a nonzero exit code or being killed by a182// signal, and emitting error output that matches `matcher`.183#define ASSERT_DEATH(statement, matcher) \184ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)185186// Like `ASSERT_DEATH`, but continues on to successive tests in the187// test suite, if any:188#define EXPECT_DEATH(statement, matcher) \189EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)190191// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:192193// Tests that an exit code describes a normal exit with a given exit code.194class GTEST_API_ ExitedWithCode {195public:196explicit ExitedWithCode(int exit_code);197ExitedWithCode(const ExitedWithCode&) = default;198void operator=(const ExitedWithCode& other) = delete;199bool operator()(int exit_status) const;200201private:202const int exit_code_;203};204205#if !defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_FUCHSIA)206// Tests that an exit code describes an exit due to termination by a207// given signal.208class GTEST_API_ KilledBySignal {209public:210explicit KilledBySignal(int signum);211bool operator()(int exit_status) const;212213private:214const int signum_;215};216#endif // !GTEST_OS_WINDOWS217218// 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 not221// in debug mode.222//223// In practice, this can be used to test functions that utilize the224// 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 NDEBUG240// // opt-mode has sideeffect visible.241// EXPECT_EQ(12, sideeffect);242// #else243// // dbg-mode no visible sideeffect.244// EXPECT_EQ(0, sideeffect);245// #endif246// }247//248// This will assert that DieInDebugReturn12InOpt() crashes in debug249// mode, usually due to a DCHECK or LOG(DFATAL), but returns the250// appropriate fallback value (12 in this case) in opt mode. If you251// need to test that a function has appropriate side-effects in opt252// mode, include assertions against the side-effects. A general253// pattern for this is:254//255// EXPECT_DEBUG_DEATH({256// // Side-effects here will have an effect after this statement in257// // opt mode, but none in debug mode.258// EXPECT_EQ(12, DieInDebugOr12(&sideeffect));259// }, "death");260//261#ifdef NDEBUG262263#define EXPECT_DEBUG_DEATH(statement, regex) \264GTEST_EXECUTE_STATEMENT_(statement, regex)265266#define ASSERT_DEBUG_DEATH(statement, regex) \267GTEST_EXECUTE_STATEMENT_(statement, regex)268269#else270271#define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex)272273#define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex)274275#endif // NDEBUG for EXPECT_DEBUG_DEATH276#endif // GTEST_HAS_DEATH_TEST277278// This macro is used for implementing macros such as279// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where280// death tests are not supported. Those macros must compile on such systems281// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters282// on systems that support death tests. This allows one to write such a macro on283// a system that does not support death tests and be sure that it will compile284// on a death-test supporting system. It is exposed publicly so that systems285// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST286// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and287// ASSERT_DEATH_IF_SUPPORTED.288//289// Parameters:290// statement - A statement that a macro such as EXPECT_DEATH would test291// for program termination. This macro has to make sure this292// statement is compiled but not executed, to ensure that293// EXPECT_DEATH_IF_SUPPORTED compiles with a certain294// parameter if and only if EXPECT_DEATH compiles with it.295// regex_or_matcher - A regex that a macro such as EXPECT_DEATH would use296// to test the output of statement. This parameter has to be297// compiled but not evaluated by this macro, to ensure that298// this macro only accepts expressions that a macro such as299// EXPECT_DEATH would accept.300// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED301// and a return statement for ASSERT_DEATH_IF_SUPPORTED.302// This ensures that ASSERT_DEATH_IF_SUPPORTED will not303// compile inside functions where ASSERT_DEATH doesn't304// compile.305//306// The branch that has an always false condition is used to ensure that307// statement and regex are compiled (and thus syntactically correct) but308// never executed. The unreachable code macro protects the terminator309// statement from generating an 'unreachable code' warning in case310// statement unconditionally returns or throws. The Message constructor at311// the end allows the syntax of streaming additional messages into the312// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.313#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex_or_matcher, terminator) \314GTEST_AMBIGUOUS_ELSE_BLOCKER_ \315if (::testing::internal::AlwaysTrue()) { \316GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \317<< "Statement '" #statement "' cannot be verified."; \318} else if (::testing::internal::AlwaysFalse()) { \319::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \320GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \321terminator; \322} else \323::testing::Message()324325// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and326// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if327// death tests are supported; otherwise they just issue a warning. This is328// useful when you are combining death test assertions with normal test329// assertions in one test.330#ifdef GTEST_HAS_DEATH_TEST331#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \332EXPECT_DEATH(statement, regex)333#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \334ASSERT_DEATH(statement, regex)335#else336#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \337GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )338#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \339GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)340#endif341342} // namespace testing343344#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_345346347