Path: blob/master/dep/googletest/include/gtest/internal/gtest-death-test-internal.h
4808 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 internal utilities needed for implementing32// death tests. They are subject to change without notice.3334// IWYU pragma: private, include "gtest/gtest.h"35// IWYU pragma: friend gtest/.*36// IWYU pragma: friend gmock/.*3738#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_39#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_4041#include <stdio.h>4243#include <memory>44#include <string>4546#include "gtest/gtest-matchers.h"47#include "gtest/internal/gtest-internal.h"48#include "gtest/internal/gtest-port.h"4950GTEST_DECLARE_string_(internal_run_death_test);5152namespace testing {53namespace internal {5455// Name of the flag (needed for parsing Google Test flag).56const char kInternalRunDeathTestFlag[] = "internal_run_death_test";5758// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads59// and interpreted as a regex (rather than an Eq matcher) for legacy60// compatibility.61inline Matcher<const ::std::string&> MakeDeathTestMatcher(62::testing::internal::RE regex) {63return ContainsRegex(regex.pattern());64}65inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {66return ContainsRegex(regex);67}68inline Matcher<const ::std::string&> MakeDeathTestMatcher(69const ::std::string& regex) {70return ContainsRegex(regex);71}7273// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's74// used directly.75inline Matcher<const ::std::string&> MakeDeathTestMatcher(76Matcher<const ::std::string&> matcher) {77return matcher;78}7980#ifdef GTEST_HAS_DEATH_TEST8182GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \83/* class A needs to have dll-interface to be used by clients of class B */)8485// DeathTest is a class that hides much of the complexity of the86// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method87// returns a concrete class that depends on the prevailing death test88// style, as defined by the --gtest_death_test_style and/or89// --gtest_internal_run_death_test flags.9091// In describing the results of death tests, these terms are used with92// the corresponding definitions:93//94// exit status: The integer exit information in the format specified95// by wait(2)96// exit code: The integer code passed to exit(3), _Exit(2), or97// returned from main()98class GTEST_API_ DeathTest {99public:100// Create returns false if there was an error determining the101// appropriate action to take for the current death test; for example,102// if the gtest_death_test_style flag is set to an invalid value.103// The LastMessage method will return a more detailed message in that104// case. Otherwise, the DeathTest pointer pointed to by the "test"105// argument is set. If the death test should be skipped, the pointer106// is set to NULL; otherwise, it is set to the address of a new concrete107// DeathTest object that controls the execution of the current test.108static bool Create(const char* statement, Matcher<const std::string&> matcher,109const char* file, int line, DeathTest** test);110DeathTest();111virtual ~DeathTest() = default;112113// A helper class that aborts a death test when it's deleted.114class ReturnSentinel {115public:116explicit ReturnSentinel(DeathTest* test) : test_(test) {}117~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }118119private:120DeathTest* const test_;121ReturnSentinel(const ReturnSentinel&) = delete;122ReturnSentinel& operator=(const ReturnSentinel&) = delete;123};124125// An enumeration of possible roles that may be taken when a death126// test is encountered. EXECUTE means that the death test logic should127// be executed immediately. OVERSEE means that the program should prepare128// the appropriate environment for a child process to execute the death129// test, then wait for it to complete.130enum TestRole { OVERSEE_TEST, EXECUTE_TEST };131132// An enumeration of the three reasons that a test might be aborted.133enum AbortReason {134TEST_ENCOUNTERED_RETURN_STATEMENT,135TEST_THREW_EXCEPTION,136TEST_DID_NOT_DIE137};138139// Assumes one of the above roles.140virtual TestRole AssumeRole() = 0;141142// Waits for the death test to finish and returns its status.143virtual int Wait() = 0;144145// Returns true if the death test passed; that is, the test process146// exited during the test, its exit status matches a user-supplied147// predicate, and its stderr output matches a user-supplied regular148// expression.149// The user-supplied predicate may be a macro expression rather150// than a function pointer or functor, or else Wait and Passed could151// be combined.152virtual bool Passed(bool exit_status_ok) = 0;153154// Signals that the death test did not die as expected.155virtual void Abort(AbortReason reason) = 0;156157// Returns a human-readable outcome message regarding the outcome of158// the last death test.159static const char* LastMessage();160161static void set_last_death_test_message(const std::string& message);162163private:164// A string containing a description of the outcome of the last death test.165static std::string last_death_test_message_;166167DeathTest(const DeathTest&) = delete;168DeathTest& operator=(const DeathTest&) = delete;169};170171GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251172173// Factory interface for death tests. May be mocked out for testing.174class DeathTestFactory {175public:176virtual ~DeathTestFactory() = default;177virtual bool Create(const char* statement,178Matcher<const std::string&> matcher, const char* file,179int line, DeathTest** test) = 0;180};181182// A concrete DeathTestFactory implementation for normal use.183class DefaultDeathTestFactory : public DeathTestFactory {184public:185bool Create(const char* statement, Matcher<const std::string&> matcher,186const char* file, int line, DeathTest** test) override;187};188189// Returns true if exit_status describes a process that was terminated190// by a signal, or exited normally with a nonzero exit code.191GTEST_API_ bool ExitedUnsuccessfully(int exit_status);192193// Traps C++ exceptions escaping statement and reports them as test194// failures. Note that trapping SEH exceptions is not implemented here.195#if GTEST_HAS_EXCEPTIONS196#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \197try { \198GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \199} catch (const ::std::exception& gtest_exception) { \200fprintf( \201stderr, \202"\n%s: Caught std::exception-derived exception escaping the " \203"death test statement. Exception message: %s\n", \204::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \205gtest_exception.what()); \206fflush(stderr); \207death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \208} catch (...) { \209death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \210}211212#else213#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \214GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)215216#endif217218// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,219// ASSERT_EXIT*, and EXPECT_EXIT*.220#define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \221GTEST_AMBIGUOUS_ELSE_BLOCKER_ \222if (::testing::internal::AlwaysTrue()) { \223::testing::internal::DeathTest* gtest_dt; \224if (!::testing::internal::DeathTest::Create( \225#statement, \226::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \227__FILE__, __LINE__, >est_dt)) { \228goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \229} \230if (gtest_dt != nullptr) { \231std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \232switch (gtest_dt->AssumeRole()) { \233case ::testing::internal::DeathTest::OVERSEE_TEST: \234if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \235goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \236} \237break; \238case ::testing::internal::DeathTest::EXECUTE_TEST: { \239const ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \240gtest_dt); \241GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \242gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \243break; \244} \245} \246} \247} else \248GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \249: fail(::testing::internal::DeathTest::LastMessage())250// The symbol "fail" here expands to something into which a message251// can be streamed.252253// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in254// NDEBUG mode. In this case we need the statements to be executed and the macro255// must accept a streamed message even though the message is never printed.256// The regex object is not evaluated, but it is used to prevent "unused"257// warnings and to avoid an expression that doesn't compile in debug mode.258#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \259GTEST_AMBIGUOUS_ELSE_BLOCKER_ \260if (::testing::internal::AlwaysTrue()) { \261GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \262} else if (!::testing::internal::AlwaysTrue()) { \263::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \264} else \265::testing::Message()266267// A class representing the parsed contents of the268// --gtest_internal_run_death_test flag, as it existed when269// RUN_ALL_TESTS was called.270class InternalRunDeathTestFlag {271public:272InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,273int a_write_fd)274: file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {}275276~InternalRunDeathTestFlag() {277if (write_fd_ >= 0) posix::Close(write_fd_);278}279280const std::string& file() const { return file_; }281int line() const { return line_; }282int index() const { return index_; }283int write_fd() const { return write_fd_; }284285private:286std::string file_;287int line_;288int index_;289int write_fd_;290291InternalRunDeathTestFlag(const InternalRunDeathTestFlag&) = delete;292InternalRunDeathTestFlag& operator=(const InternalRunDeathTestFlag&) = delete;293};294295// Returns a newly created InternalRunDeathTestFlag object with fields296// initialized from the GTEST_FLAG(internal_run_death_test) flag if297// the flag is specified; otherwise returns NULL.298InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();299300#endif // GTEST_HAS_DEATH_TEST301302} // namespace internal303} // namespace testing304305#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_306307308