Path: blob/master/dep/googletest/include/gtest/internal/gtest-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 declares functions and macros used internally by32// Google Test. 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_INTERNAL_H_39#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_4041#include "gtest/internal/gtest-port.h"4243#ifdef GTEST_OS_LINUX44#include <stdlib.h>45#include <sys/types.h>46#include <sys/wait.h>47#include <unistd.h>48#endif // GTEST_OS_LINUX4950#if GTEST_HAS_EXCEPTIONS51#include <stdexcept>52#endif5354#include <ctype.h>55#include <float.h>56#include <string.h>5758#include <cstdint>59#include <functional>60#include <limits>61#include <map>62#include <set>63#include <string>64#include <type_traits>65#include <utility>66#include <vector>6768#include "gtest/gtest-message.h"69#include "gtest/internal/gtest-filepath.h"70#include "gtest/internal/gtest-string.h"71#include "gtest/internal/gtest-type-util.h"7273// Due to C++ preprocessor weirdness, we need double indirection to74// concatenate two tokens when one of them is __LINE__. Writing75//76// foo ## __LINE__77//78// will result in the token foo__LINE__, instead of foo followed by79// the current line number. For more details, see80// https://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.681#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)82#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar8384// Stringifies its argument.85// Work around a bug in visual studio which doesn't accept code like this:86//87// #define GTEST_STRINGIFY_(name) #name88// #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...89// MACRO(, x, y)90//91// Complaining about the argument to GTEST_STRINGIFY_ being empty.92// This is allowed by the spec.93#define GTEST_STRINGIFY_HELPER_(name, ...) #name94#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )9596namespace proto2 {97class MessageLite;98}99100namespace testing {101102// Forward declarations.103104class AssertionResult; // Result of an assertion.105class Message; // Represents a failure message.106class Test; // Represents a test.107class TestInfo; // Information about a test.108class TestPartResult; // Result of a test part.109class UnitTest; // A collection of test suites.110111template <typename T>112::std::string PrintToString(const T& value);113114namespace internal {115116struct TraceInfo; // Information about a trace point.117class TestInfoImpl; // Opaque implementation of TestInfo118class UnitTestImpl; // Opaque implementation of UnitTest119120// The text used in failure messages to indicate the start of the121// stack trace.122GTEST_API_ extern const char kStackTraceMarker[];123124// An IgnoredValue object can be implicitly constructed from ANY value.125class IgnoredValue {126struct Sink {};127128public:129// This constructor template allows any value to be implicitly130// converted to IgnoredValue. The object has no data member and131// doesn't try to remember anything about the argument. We132// deliberately omit the 'explicit' keyword in order to allow the133// conversion to be implicit.134// Disable the conversion if T already has a magical conversion operator.135// Otherwise we get ambiguity.136template <typename T,137typename std::enable_if<!std::is_convertible<T, Sink>::value,138int>::type = 0>139IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)140};141142// Appends the user-supplied message to the Google-Test-generated message.143GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg,144const Message& user_msg);145146#if GTEST_HAS_EXCEPTIONS147148GTEST_DISABLE_MSC_WARNINGS_PUSH_(1494275 /* an exported class was derived from a class that was not exported */)150151// This exception is thrown by (and only by) a failed Google Test152// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions153// are enabled). We derive it from std::runtime_error, which is for154// errors presumably detectable only at run time. Since155// std::runtime_error inherits from std::exception, many testing156// frameworks know how to extract and print the message inside it.157class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {158public:159explicit GoogleTestFailureException(const TestPartResult& failure);160};161162GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275163164#endif // GTEST_HAS_EXCEPTIONS165166namespace edit_distance {167// Returns the optimal edits to go from 'left' to 'right'.168// All edits cost the same, with replace having lower priority than169// add/remove.170// Simple implementation of the Wagner-Fischer algorithm.171// See https://en.wikipedia.org/wiki/Wagner-Fischer_algorithm172enum EditType { kMatch, kAdd, kRemove, kReplace };173GTEST_API_ std::vector<EditType> CalculateOptimalEdits(174const std::vector<size_t>& left, const std::vector<size_t>& right);175176// Same as above, but the input is represented as strings.177GTEST_API_ std::vector<EditType> CalculateOptimalEdits(178const std::vector<std::string>& left,179const std::vector<std::string>& right);180181// Create a diff of the input strings in Unified diff format.182GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,183const std::vector<std::string>& right,184size_t context = 2);185186} // namespace edit_distance187188// Constructs and returns the message for an equality assertion189// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.190//191// The first four parameters are the expressions used in the assertion192// and their values, as strings. For example, for ASSERT_EQ(foo, bar)193// where foo is 5 and bar is 6, we have:194//195// expected_expression: "foo"196// actual_expression: "bar"197// expected_value: "5"198// actual_value: "6"199//200// The ignoring_case parameter is true if and only if the assertion is a201// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will202// be inserted into the message.203GTEST_API_ AssertionResult EqFailure(const char* expected_expression,204const char* actual_expression,205const std::string& expected_value,206const std::string& actual_value,207bool ignoring_case);208209// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.210GTEST_API_ std::string GetBoolAssertionFailureMessage(211const AssertionResult& assertion_result, const char* expression_text,212const char* actual_predicate_value, const char* expected_predicate_value);213214// This template class represents an IEEE floating-point number215// (either single-precision or double-precision, depending on the216// template parameters).217//218// The purpose of this class is to do more sophisticated number219// comparison. (Due to round-off error, etc, it's very unlikely that220// two floating-points will be equal exactly. Hence a naive221// comparison by the == operation often doesn't work.)222//223// Format of IEEE floating-point:224//225// The most-significant bit being the leftmost, an IEEE226// floating-point looks like227//228// sign_bit exponent_bits fraction_bits229//230// Here, sign_bit is a single bit that designates the sign of the231// number.232//233// For float, there are 8 exponent bits and 23 fraction bits.234//235// For double, there are 11 exponent bits and 52 fraction bits.236//237// More details can be found at238// https://en.wikipedia.org/wiki/IEEE_floating-point_standard.239//240// Template parameter:241//242// RawType: the raw floating-point type (either float or double)243template <typename RawType>244class FloatingPoint {245public:246// Defines the unsigned integer type that has the same size as the247// floating point number.248typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;249250// Constants.251252// # of bits in a number.253static const size_t kBitCount = 8 * sizeof(RawType);254255// # of fraction bits in a number.256static const size_t kFractionBitCount =257std::numeric_limits<RawType>::digits - 1;258259// # of exponent bits in a number.260static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;261262// The mask for the sign bit.263static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);264265// The mask for the fraction bits.266static const Bits kFractionBitMask = ~static_cast<Bits>(0) >>267(kExponentBitCount + 1);268269// The mask for the exponent bits.270static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);271272// How many ULP's (Units in the Last Place) we want to tolerate when273// comparing two numbers. The larger the value, the more error we274// allow. A 0 value means that two numbers must be exactly the same275// to be considered equal.276//277// The maximum error of a single floating-point operation is 0.5278// units in the last place. On Intel CPU's, all floating-point279// calculations are done with 80-bit precision, while double has 64280// bits. Therefore, 4 should be enough for ordinary use.281//282// See the following article for more details on ULP:283// https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/284static const uint32_t kMaxUlps = 4;285286// Constructs a FloatingPoint from a raw floating-point number.287//288// On an Intel CPU, passing a non-normalized NAN (Not a Number)289// around may change its bits, although the new value is guaranteed290// to be also a NAN. Therefore, don't expect this constructor to291// preserve the bits in x when x is a NAN.292explicit FloatingPoint(RawType x) { memcpy(&bits_, &x, sizeof(x)); }293294// Static methods295296// Reinterprets a bit pattern as a floating-point number.297//298// This function is needed to test the AlmostEquals() method.299static RawType ReinterpretBits(Bits bits) {300RawType fp;301memcpy(&fp, &bits, sizeof(fp));302return fp;303}304305// Returns the floating-point number that represent positive infinity.306static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }307308// Non-static methods309310// Returns the bits that represents this number.311const Bits& bits() const { return bits_; }312313// Returns the exponent bits of this number.314Bits exponent_bits() const { return kExponentBitMask & bits_; }315316// Returns the fraction bits of this number.317Bits fraction_bits() const { return kFractionBitMask & bits_; }318319// Returns the sign bit of this number.320Bits sign_bit() const { return kSignBitMask & bits_; }321322// Returns true if and only if this is NAN (not a number).323bool is_nan() const {324// It's a NAN if the exponent bits are all ones and the fraction325// bits are not entirely zeros.326return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);327}328329// Returns true if and only if this number is at most kMaxUlps ULP's away330// from rhs. In particular, this function:331//332// - returns false if either number is (or both are) NAN.333// - treats really large numbers as almost equal to infinity.334// - thinks +0.0 and -0.0 are 0 ULP's apart.335bool AlmostEquals(const FloatingPoint& rhs) const {336// The IEEE standard says that any comparison operation involving337// a NAN must return false.338if (is_nan() || rhs.is_nan()) return false;339340return DistanceBetweenSignAndMagnitudeNumbers(bits_, rhs.bits_) <= kMaxUlps;341}342343private:344// Converts an integer from the sign-and-magnitude representation to345// the biased representation. More precisely, let N be 2 to the346// power of (kBitCount - 1), an integer x is represented by the347// unsigned number x + N.348//349// For instance,350//351// -N + 1 (the most negative number representable using352// sign-and-magnitude) is represented by 1;353// 0 is represented by N; and354// N - 1 (the biggest number representable using355// sign-and-magnitude) is represented by 2N - 1.356//357// Read https://en.wikipedia.org/wiki/Signed_number_representations358// for more details on signed number representations.359static Bits SignAndMagnitudeToBiased(Bits sam) {360if (kSignBitMask & sam) {361// sam represents a negative number.362return ~sam + 1;363} else {364// sam represents a positive number.365return kSignBitMask | sam;366}367}368369// Given two numbers in the sign-and-magnitude representation,370// returns the distance between them as an unsigned number.371static Bits DistanceBetweenSignAndMagnitudeNumbers(Bits sam1, Bits sam2) {372const Bits biased1 = SignAndMagnitudeToBiased(sam1);373const Bits biased2 = SignAndMagnitudeToBiased(sam2);374return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);375}376377Bits bits_; // The bits that represent the number.378};379380// Typedefs the instances of the FloatingPoint template class that we381// care to use.382typedef FloatingPoint<float> Float;383typedef FloatingPoint<double> Double;384385// In order to catch the mistake of putting tests that use different386// test fixture classes in the same test suite, we need to assign387// unique IDs to fixture classes and compare them. The TypeId type is388// used to hold such IDs. The user should treat TypeId as an opaque389// type: the only operation allowed on TypeId values is to compare390// them for equality using the == operator.391typedef const void* TypeId;392393template <typename T>394class TypeIdHelper {395public:396// dummy_ must not have a const type. Otherwise an overly eager397// compiler (e.g. MSVC 7.1 & 8.0) may try to merge398// TypeIdHelper<T>::dummy_ for different Ts as an "optimization".399static bool dummy_;400};401402template <typename T>403bool TypeIdHelper<T>::dummy_ = false;404405// GetTypeId<T>() returns the ID of type T. Different values will be406// returned for different types. Calling the function twice with the407// same type argument is guaranteed to return the same ID.408template <typename T>409TypeId GetTypeId() {410// The compiler is required to allocate a different411// TypeIdHelper<T>::dummy_ variable for each T used to instantiate412// the template. Therefore, the address of dummy_ is guaranteed to413// be unique.414return &(TypeIdHelper<T>::dummy_);415}416417// Returns the type ID of ::testing::Test. Always call this instead418// of GetTypeId< ::testing::Test>() to get the type ID of419// ::testing::Test, as the latter may give the wrong result due to a420// suspected linker bug when compiling Google Test as a Mac OS X421// framework.422GTEST_API_ TypeId GetTestTypeId();423424// Defines the abstract factory interface that creates instances425// of a Test object.426class TestFactoryBase {427public:428virtual ~TestFactoryBase() = default;429430// Creates a test instance to run. The instance is both created and destroyed431// within TestInfoImpl::Run()432virtual Test* CreateTest() = 0;433434protected:435TestFactoryBase() {}436437private:438TestFactoryBase(const TestFactoryBase&) = delete;439TestFactoryBase& operator=(const TestFactoryBase&) = delete;440};441442// This class provides implementation of TestFactoryBase interface.443// It is used in TEST and TEST_F macros.444template <class TestClass>445class TestFactoryImpl : public TestFactoryBase {446public:447Test* CreateTest() override { return new TestClass; }448};449450#ifdef GTEST_OS_WINDOWS451452// Predicate-formatters for implementing the HRESULT checking macros453// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}454// We pass a long instead of HRESULT to avoid causing an455// include dependency for the HRESULT type.456GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,457long hr); // NOLINT458GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,459long hr); // NOLINT460461#endif // GTEST_OS_WINDOWS462463// Types of SetUpTestSuite() and TearDownTestSuite() functions.464using SetUpTestSuiteFunc = void (*)();465using TearDownTestSuiteFunc = void (*)();466467struct CodeLocation {468CodeLocation(std::string a_file, int a_line)469: file(std::move(a_file)), line(a_line) {}470471std::string file;472int line;473};474475// Helper to identify which setup function for TestCase / TestSuite to call.476// Only one function is allowed, either TestCase or TestSute but not both.477478// Utility functions to help SuiteApiResolver479using SetUpTearDownSuiteFuncType = void (*)();480481inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(482SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {483return a == def ? nullptr : a;484}485486template <typename T>487// Note that SuiteApiResolver inherits from T because488// SetUpTestSuite()/TearDownTestSuite() could be protected. This way489// SuiteApiResolver can access them.490struct SuiteApiResolver : T {491// testing::Test is only forward declared at this point. So we make it a492// dependent class for the compiler to be OK with it.493using Test =494typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;495496static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,497int line_num) {498#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_499SetUpTearDownSuiteFuncType test_case_fp =500GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);501SetUpTearDownSuiteFuncType test_suite_fp =502GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);503504GTEST_CHECK_(!test_case_fp || !test_suite_fp)505<< "Test can not provide both SetUpTestSuite and SetUpTestCase, please "506"make sure there is only one present at "507<< filename << ":" << line_num;508509return test_case_fp != nullptr ? test_case_fp : test_suite_fp;510#else511(void)(filename);512(void)(line_num);513return &T::SetUpTestSuite;514#endif515}516517static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,518int line_num) {519#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_520SetUpTearDownSuiteFuncType test_case_fp =521GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);522SetUpTearDownSuiteFuncType test_suite_fp =523GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);524525GTEST_CHECK_(!test_case_fp || !test_suite_fp)526<< "Test can not provide both TearDownTestSuite and TearDownTestCase,"527" please make sure there is only one present at"528<< filename << ":" << line_num;529530return test_case_fp != nullptr ? test_case_fp : test_suite_fp;531#else532(void)(filename);533(void)(line_num);534return &T::TearDownTestSuite;535#endif536}537};538539// Creates a new TestInfo object and registers it with Google Test;540// returns the created object.541//542// Arguments:543//544// test_suite_name: name of the test suite545// name: name of the test546// type_param: the name of the test's type parameter, or NULL if547// this is not a typed or a type-parameterized test.548// value_param: text representation of the test's value parameter,549// or NULL if this is not a value-parameterized test.550// code_location: code location where the test is defined551// fixture_class_id: ID of the test fixture class552// set_up_tc: pointer to the function that sets up the test suite553// tear_down_tc: pointer to the function that tears down the test suite554// factory: pointer to the factory that creates a test object.555// The newly created TestInfo instance will assume556// ownership of the factory object.557GTEST_API_ TestInfo* MakeAndRegisterTestInfo(558std::string test_suite_name, const char* name, const char* type_param,559const char* value_param, CodeLocation code_location,560TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,561TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);562563// If *pstr starts with the given prefix, modifies *pstr to be right564// past the prefix and returns true; otherwise leaves *pstr unchanged565// and returns false. None of pstr, *pstr, and prefix can be NULL.566GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);567568GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \569/* class A needs to have dll-interface to be used by clients of class B */)570571// State of the definition of a type-parameterized test suite.572class GTEST_API_ TypedTestSuitePState {573public:574TypedTestSuitePState() : registered_(false) {}575576// Adds the given test name to defined_test_names_ and return true577// if the test suite hasn't been registered; otherwise aborts the578// program.579bool AddTestName(const char* file, int line, const char* case_name,580const char* test_name) {581if (registered_) {582fprintf(stderr,583"%s Test %s must be defined before "584"REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",585FormatFileLocation(file, line).c_str(), test_name, case_name);586fflush(stderr);587posix::Abort();588}589registered_tests_.emplace(test_name, CodeLocation(file, line));590return true;591}592593bool TestExists(const std::string& test_name) const {594return registered_tests_.count(test_name) > 0;595}596597const CodeLocation& GetCodeLocation(const std::string& test_name) const {598RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);599GTEST_CHECK_(it != registered_tests_.end());600return it->second;601}602603// Verifies that registered_tests match the test names in604// defined_test_names_; returns registered_tests if successful, or605// aborts the program otherwise.606const char* VerifyRegisteredTestNames(const char* test_suite_name,607const char* file, int line,608const char* registered_tests);609610private:611typedef ::std::map<std::string, CodeLocation, std::less<>> RegisteredTestsMap;612613bool registered_;614RegisteredTestsMap registered_tests_;615};616617// Legacy API is deprecated but still available618#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_619using TypedTestCasePState = TypedTestSuitePState;620#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_621622GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251623624// Skips to the first non-space char after the first comma in 'str';625// returns NULL if no comma is found in 'str'.626inline const char* SkipComma(const char* str) {627const char* comma = strchr(str, ',');628if (comma == nullptr) {629return nullptr;630}631while (IsSpace(*(++comma))) {632}633return comma;634}635636// Returns the prefix of 'str' before the first comma in it; returns637// the entire string if it contains no comma.638inline std::string GetPrefixUntilComma(const char* str) {639const char* comma = strchr(str, ',');640return comma == nullptr ? str : std::string(str, comma);641}642643// Splits a given string on a given delimiter, populating a given644// vector with the fields.645void SplitString(const ::std::string& str, char delimiter,646::std::vector<::std::string>* dest);647648// The default argument to the template below for the case when the user does649// not provide a name generator.650struct DefaultNameGenerator {651template <typename T>652static std::string GetName(int i) {653return StreamableToString(i);654}655};656657template <typename Provided = DefaultNameGenerator>658struct NameGeneratorSelector {659typedef Provided type;660};661662template <typename NameGenerator>663void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}664665template <typename NameGenerator, typename Types>666void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {667result->push_back(NameGenerator::template GetName<typename Types::Head>(i));668GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,669i + 1);670}671672template <typename NameGenerator, typename Types>673std::vector<std::string> GenerateNames() {674std::vector<std::string> result;675GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);676return result;677}678679// TypeParameterizedTest<Fixture, TestSel, Types>::Register()680// registers a list of type-parameterized tests with Google Test. The681// return value is insignificant - we just need to return something682// such that we can call this function in a namespace scope.683//684// Implementation note: The GTEST_TEMPLATE_ macro declares a template685// template parameter. It's defined in gtest-type-util.h.686template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>687class TypeParameterizedTest {688public:689// 'index' is the index of the test in the type list 'Types'690// specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,691// Types). Valid values for 'index' are [0, N - 1] where N is the692// length of Types.693static bool Register(const char* prefix, CodeLocation code_location,694const char* case_name, const char* test_names, int index,695const std::vector<std::string>& type_names =696GenerateNames<DefaultNameGenerator, Types>()) {697typedef typename Types::Head Type;698typedef Fixture<Type> FixtureClass;699typedef typename GTEST_BIND_(TestSel, Type) TestClass;700701// First, registers the first type-parameterized test in the type702// list.703MakeAndRegisterTestInfo(704(std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +705"/" + type_names[static_cast<size_t>(index)]),706StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),707GetTypeName<Type>().c_str(),708nullptr, // No value parameter.709code_location, GetTypeId<FixtureClass>(),710SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(711code_location.file.c_str(), code_location.line),712SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(713code_location.file.c_str(), code_location.line),714new TestFactoryImpl<TestClass>);715716// Next, recurses (at compile time) with the tail of the type list.717return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail>::718Register(prefix, std::move(code_location), case_name, test_names,719index + 1, type_names);720}721};722723// The base case for the compile time recursion.724template <GTEST_TEMPLATE_ Fixture, class TestSel>725class TypeParameterizedTest<Fixture, TestSel, internal::None> {726public:727static bool Register(const char* /*prefix*/, CodeLocation,728const char* /*case_name*/, const char* /*test_names*/,729int /*index*/,730const std::vector<std::string>& =731std::vector<std::string>() /*type_names*/) {732return true;733}734};735736GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,737CodeLocation code_location);738GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(739const char* case_name);740741// TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()742// registers *all combinations* of 'Tests' and 'Types' with Google743// Test. The return value is insignificant - we just need to return744// something such that we can call this function in a namespace scope.745template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>746class TypeParameterizedTestSuite {747public:748static bool Register(const char* prefix, CodeLocation code_location,749const TypedTestSuitePState* state, const char* case_name,750const char* test_names,751const std::vector<std::string>& type_names =752GenerateNames<DefaultNameGenerator, Types>()) {753RegisterTypeParameterizedTestSuiteInstantiation(case_name);754std::string test_name =755StripTrailingSpaces(GetPrefixUntilComma(test_names));756if (!state->TestExists(test_name)) {757fprintf(stderr, "Failed to get code location for test %s.%s at %s.",758case_name, test_name.c_str(),759FormatFileLocation(code_location.file.c_str(), code_location.line)760.c_str());761fflush(stderr);762posix::Abort();763}764const CodeLocation& test_location = state->GetCodeLocation(test_name);765766typedef typename Tests::Head Head;767768// First, register the first test in 'Test' for each type in 'Types'.769TypeParameterizedTest<Fixture, Head, Types>::Register(770prefix, test_location, case_name, test_names, 0, type_names);771772// Next, recurses (at compile time) with the tail of the test list.773return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,774Types>::Register(prefix,775std::move(code_location),776state, case_name,777SkipComma(test_names),778type_names);779}780};781782// The base case for the compile time recursion.783template <GTEST_TEMPLATE_ Fixture, typename Types>784class TypeParameterizedTestSuite<Fixture, internal::None, Types> {785public:786static bool Register(const char* /*prefix*/, const CodeLocation&,787const TypedTestSuitePState* /*state*/,788const char* /*case_name*/, const char* /*test_names*/,789const std::vector<std::string>& =790std::vector<std::string>() /*type_names*/) {791return true;792}793};794795// Returns the current OS stack trace as an std::string.796//797// The maximum number of stack frames to be included is specified by798// the gtest_stack_trace_depth flag. The skip_count parameter799// specifies the number of top frames to be skipped, which doesn't800// count against the number of frames to be included.801//802// For example, if Foo() calls Bar(), which in turn calls803// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in804// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.805GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(int skip_count);806807// Helpers for suppressing warnings on unreachable code or constant808// condition.809810// Always returns true.811GTEST_API_ bool AlwaysTrue();812813// Always returns false.814inline bool AlwaysFalse() { return !AlwaysTrue(); }815816// Helper for suppressing false warning from Clang on a const char*817// variable declared in a conditional expression always being NULL in818// the else branch.819struct GTEST_API_ ConstCharPtr {820ConstCharPtr(const char* str) : value(str) {}821operator bool() const { return true; }822const char* value;823};824825// Helper for declaring std::string within 'if' statement826// in pre C++17 build environment.827struct TrueWithString {828TrueWithString() = default;829explicit TrueWithString(const char* str) : value(str) {}830explicit TrueWithString(const std::string& str) : value(str) {}831explicit operator bool() const { return true; }832std::string value;833};834835// A simple Linear Congruential Generator for generating random836// numbers with a uniform distribution. Unlike rand() and srand(), it837// doesn't use global state (and therefore can't interfere with user838// code). Unlike rand_r(), it's portable. An LCG isn't very random,839// but it's good enough for our purposes.840class GTEST_API_ Random {841public:842static const uint32_t kMaxRange = 1u << 31;843844explicit Random(uint32_t seed) : state_(seed) {}845846void Reseed(uint32_t seed) { state_ = seed; }847848// Generates a random number from [0, range). Crashes if 'range' is849// 0 or greater than kMaxRange.850uint32_t Generate(uint32_t range);851852private:853uint32_t state_;854Random(const Random&) = delete;855Random& operator=(const Random&) = delete;856};857858// Turns const U&, U&, const U, and U all into U.859#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \860typename std::remove_const<typename std::remove_reference<T>::type>::type861862// HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant863// that's true if and only if T has methods DebugString() and ShortDebugString()864// that return std::string.865template <typename T>866class HasDebugStringAndShortDebugString {867private:868template <typename C>869static auto CheckDebugString(C*) -> typename std::is_same<870std::string, decltype(std::declval<const C>().DebugString())>::type;871template <typename>872static std::false_type CheckDebugString(...);873874template <typename C>875static auto CheckShortDebugString(C*) -> typename std::is_same<876std::string, decltype(std::declval<const C>().ShortDebugString())>::type;877template <typename>878static std::false_type CheckShortDebugString(...);879880using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));881using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));882883public:884static constexpr bool value =885HasDebugStringType::value && HasShortDebugStringType::value;886};887888// When the compiler sees expression IsContainerTest<C>(0), if C is an889// STL-style container class, the first overload of IsContainerTest890// will be viable (since both C::iterator* and C::const_iterator* are891// valid types and NULL can be implicitly converted to them). It will892// be picked over the second overload as 'int' is a perfect match for893// the type of argument 0. If C::iterator or C::const_iterator is not894// a valid type, the first overload is not viable, and the second895// overload will be picked. Therefore, we can determine whether C is896// a container class by checking the type of IsContainerTest<C>(0).897// The value of the expression is insignificant.898//899// In C++11 mode we check the existence of a const_iterator and that an900// iterator is properly implemented for the container.901//902// For pre-C++11 that we look for both C::iterator and C::const_iterator.903// The reason is that C++ injects the name of a class as a member of the904// class itself (e.g. you can refer to class iterator as either905// 'iterator' or 'iterator::iterator'). If we look for C::iterator906// only, for example, we would mistakenly think that a class named907// iterator is an STL container.908//909// Also note that the simpler approach of overloading910// IsContainerTest(typename C::const_iterator*) and911// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.912typedef int IsContainer;913template <class C,914class Iterator = decltype(::std::declval<const C&>().begin()),915class = decltype(::std::declval<const C&>().end()),916class = decltype(++::std::declval<Iterator&>()),917class = decltype(*::std::declval<Iterator>()),918class = typename C::const_iterator>919IsContainer IsContainerTest(int /* dummy */) {920return 0;921}922923typedef char IsNotContainer;924template <class C>925IsNotContainer IsContainerTest(long /* dummy */) {926return '\0';927}928929// Trait to detect whether a type T is a hash table.930// The heuristic used is that the type contains an inner type `hasher` and does931// not contain an inner type `reverse_iterator`.932// If the container is iterable in reverse, then order might actually matter.933template <typename T>934struct IsHashTable {935private:936template <typename U>937static char test(typename U::hasher*, typename U::reverse_iterator*);938template <typename U>939static int test(typename U::hasher*, ...);940template <typename U>941static char test(...);942943public:944static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);945};946947template <typename T>948const bool IsHashTable<T>::value;949950template <typename C,951bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>952struct IsRecursiveContainerImpl;953954template <typename C>955struct IsRecursiveContainerImpl<C, false> : public std::false_type {};956957// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to958// obey the same inconsistencies as the IsContainerTest, namely check if959// something is a container is relying on only const_iterator in C++11 and960// is relying on both const_iterator and iterator otherwise961template <typename C>962struct IsRecursiveContainerImpl<C, true> {963using value_type = decltype(*std::declval<typename C::const_iterator>());964using type =965std::is_same<typename std::remove_const<966typename std::remove_reference<value_type>::type>::type,967C>;968};969970// IsRecursiveContainer<Type> is a unary compile-time predicate that971// evaluates whether C is a recursive container type. A recursive container972// type is a container type whose value_type is equal to the container type973// itself. An example for a recursive container type is974// boost::filesystem::path, whose iterator has a value_type that is equal to975// boost::filesystem::path.976template <typename C>977struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};978979// Utilities for native arrays.980981// ArrayEq() compares two k-dimensional native arrays using the982// elements' operator==, where k can be any integer >= 0. When k is983// 0, ArrayEq() degenerates into comparing a single pair of values.984985template <typename T, typename U>986bool ArrayEq(const T* lhs, size_t size, const U* rhs);987988// This generic version is used when k is 0.989template <typename T, typename U>990inline bool ArrayEq(const T& lhs, const U& rhs) {991return lhs == rhs;992}993994// This overload is used when k >= 1.995template <typename T, typename U, size_t N>996inline bool ArrayEq(const T (&lhs)[N], const U (&rhs)[N]) {997return internal::ArrayEq(lhs, N, rhs);998}9991000// This helper reduces code bloat. If we instead put its logic inside1001// the previous ArrayEq() function, arrays with different sizes would1002// lead to different copies of the template code.1003template <typename T, typename U>1004bool ArrayEq(const T* lhs, size_t size, const U* rhs) {1005for (size_t i = 0; i != size; i++) {1006if (!internal::ArrayEq(lhs[i], rhs[i])) return false;1007}1008return true;1009}10101011// Finds the first element in the iterator range [begin, end) that1012// equals elem. Element may be a native array type itself.1013template <typename Iter, typename Element>1014Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {1015for (Iter it = begin; it != end; ++it) {1016if (internal::ArrayEq(*it, elem)) return it;1017}1018return end;1019}10201021// CopyArray() copies a k-dimensional native array using the elements'1022// operator=, where k can be any integer >= 0. When k is 0,1023// CopyArray() degenerates into copying a single value.10241025template <typename T, typename U>1026void CopyArray(const T* from, size_t size, U* to);10271028// This generic version is used when k is 0.1029template <typename T, typename U>1030inline void CopyArray(const T& from, U* to) {1031*to = from;1032}10331034// This overload is used when k >= 1.1035template <typename T, typename U, size_t N>1036inline void CopyArray(const T (&from)[N], U (*to)[N]) {1037internal::CopyArray(from, N, *to);1038}10391040// This helper reduces code bloat. If we instead put its logic inside1041// the previous CopyArray() function, arrays with different sizes1042// would lead to different copies of the template code.1043template <typename T, typename U>1044void CopyArray(const T* from, size_t size, U* to) {1045for (size_t i = 0; i != size; i++) {1046internal::CopyArray(from[i], to + i);1047}1048}10491050// The relation between an NativeArray object (see below) and the1051// native array it represents.1052// We use 2 different structs to allow non-copyable types to be used, as long1053// as RelationToSourceReference() is passed.1054struct RelationToSourceReference {};1055struct RelationToSourceCopy {};10561057// Adapts a native array to a read-only STL-style container. Instead1058// of the complete STL container concept, this adaptor only implements1059// members useful for Google Mock's container matchers. New members1060// should be added as needed. To simplify the implementation, we only1061// support Element being a raw type (i.e. having no top-level const or1062// reference modifier). It's the client's responsibility to satisfy1063// this requirement. Element can be an array type itself (hence1064// multi-dimensional arrays are supported).1065template <typename Element>1066class NativeArray {1067public:1068// STL-style container typedefs.1069typedef Element value_type;1070typedef Element* iterator;1071typedef const Element* const_iterator;10721073// Constructs from a native array. References the source.1074NativeArray(const Element* array, size_t count, RelationToSourceReference) {1075InitRef(array, count);1076}10771078// Constructs from a native array. Copies the source.1079NativeArray(const Element* array, size_t count, RelationToSourceCopy) {1080InitCopy(array, count);1081}10821083// Copy constructor.1084NativeArray(const NativeArray& rhs) {1085(this->*rhs.clone_)(rhs.array_, rhs.size_);1086}10871088~NativeArray() {1089if (clone_ != &NativeArray::InitRef) delete[] array_;1090}10911092// STL-style container methods.1093size_t size() const { return size_; }1094const_iterator begin() const { return array_; }1095const_iterator end() const { return array_ + size_; }1096bool operator==(const NativeArray& rhs) const {1097return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin());1098}10991100private:1101static_assert(!std::is_const<Element>::value, "Type must not be const");1102static_assert(!std::is_reference<Element>::value,1103"Type must not be a reference");11041105// Initializes this object with a copy of the input.1106void InitCopy(const Element* array, size_t a_size) {1107Element* const copy = new Element[a_size];1108CopyArray(array, a_size, copy);1109array_ = copy;1110size_ = a_size;1111clone_ = &NativeArray::InitCopy;1112}11131114// Initializes this object with a reference of the input.1115void InitRef(const Element* array, size_t a_size) {1116array_ = array;1117size_ = a_size;1118clone_ = &NativeArray::InitRef;1119}11201121const Element* array_;1122size_t size_;1123void (NativeArray::*clone_)(const Element*, size_t);1124};11251126template <size_t>1127struct Ignore {1128Ignore(...); // NOLINT1129};11301131template <typename>1132struct ElemFromListImpl;1133template <size_t... I>1134struct ElemFromListImpl<std::index_sequence<I...>> {1135// We make Ignore a template to solve a problem with MSVC.1136// A non-template Ignore would work fine with `decltype(Ignore(I))...`, but1137// MSVC doesn't understand how to deal with that pack expansion.1138// Use `0 * I` to have a single instantiation of Ignore.1139template <typename R>1140static R Apply(Ignore<0 * I>..., R (*)(), ...);1141};11421143template <size_t N, typename... T>1144struct ElemFromList {1145using type = decltype(ElemFromListImpl<std::make_index_sequence<N>>::Apply(1146static_cast<T (*)()>(nullptr)...));1147};11481149struct FlatTupleConstructTag {};11501151template <typename... T>1152class FlatTuple;11531154template <typename Derived, size_t I>1155struct FlatTupleElemBase;11561157template <typename... T, size_t I>1158struct FlatTupleElemBase<FlatTuple<T...>, I> {1159using value_type = typename ElemFromList<I, T...>::type;1160FlatTupleElemBase() = default;1161template <typename Arg>1162explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)1163: value(std::forward<Arg>(t)) {}1164value_type value;1165};11661167template <typename Derived, typename Idx>1168struct FlatTupleBase;11691170template <size_t... Idx, typename... T>1171struct FlatTupleBase<FlatTuple<T...>, std::index_sequence<Idx...>>1172: FlatTupleElemBase<FlatTuple<T...>, Idx>... {1173using Indices = std::index_sequence<Idx...>;1174FlatTupleBase() = default;1175template <typename... Args>1176explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)1177: FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},1178std::forward<Args>(args))... {}11791180template <size_t I>1181const typename ElemFromList<I, T...>::type& Get() const {1182return FlatTupleElemBase<FlatTuple<T...>, I>::value;1183}11841185template <size_t I>1186typename ElemFromList<I, T...>::type& Get() {1187return FlatTupleElemBase<FlatTuple<T...>, I>::value;1188}11891190template <typename F>1191auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {1192return std::forward<F>(f)(Get<Idx>()...);1193}11941195template <typename F>1196auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {1197return std::forward<F>(f)(Get<Idx>()...);1198}1199};12001201// Analog to std::tuple but with different tradeoffs.1202// This class minimizes the template instantiation depth, thus allowing more1203// elements than std::tuple would. std::tuple has been seen to require an1204// instantiation depth of more than 10x the number of elements in some1205// implementations.1206// FlatTuple and ElemFromList are not recursive and have a fixed depth1207// regardless of T...1208// std::make_index_sequence, on the other hand, it is recursive but with an1209// instantiation depth of O(ln(N)).1210template <typename... T>1211class FlatTuple1212: private FlatTupleBase<FlatTuple<T...>,1213std::make_index_sequence<sizeof...(T)>> {1214using Indices =1215typename FlatTupleBase<FlatTuple<T...>,1216std::make_index_sequence<sizeof...(T)>>::Indices;12171218public:1219FlatTuple() = default;1220template <typename... Args>1221explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)1222: FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}12231224using FlatTuple::FlatTupleBase::Apply;1225using FlatTuple::FlatTupleBase::Get;1226};12271228// Utility functions to be called with static_assert to induce deprecation1229// warnings.1230[[deprecated(1231"INSTANTIATE_TEST_CASE_P is deprecated, please use "1232"INSTANTIATE_TEST_SUITE_P")]]1233constexpr bool InstantiateTestCase_P_IsDeprecated() {1234return true;1235}12361237[[deprecated(1238"TYPED_TEST_CASE_P is deprecated, please use "1239"TYPED_TEST_SUITE_P")]]1240constexpr bool TypedTestCase_P_IsDeprecated() {1241return true;1242}12431244[[deprecated(1245"TYPED_TEST_CASE is deprecated, please use "1246"TYPED_TEST_SUITE")]]1247constexpr bool TypedTestCaseIsDeprecated() {1248return true;1249}12501251[[deprecated(1252"REGISTER_TYPED_TEST_CASE_P is deprecated, please use "1253"REGISTER_TYPED_TEST_SUITE_P")]]1254constexpr bool RegisterTypedTestCase_P_IsDeprecated() {1255return true;1256}12571258[[deprecated(1259"INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "1260"INSTANTIATE_TYPED_TEST_SUITE_P")]]1261constexpr bool InstantiateTypedTestCase_P_IsDeprecated() {1262return true;1263}12641265} // namespace internal1266} // namespace testing12671268namespace std {1269// Some standard library implementations use `struct tuple_size` and some use1270// `class tuple_size`. Clang warns about the mismatch.1271// https://reviews.llvm.org/D554661272#ifdef __clang__1273#pragma clang diagnostic push1274#pragma clang diagnostic ignored "-Wmismatched-tags"1275#endif1276template <typename... Ts>1277struct tuple_size<testing::internal::FlatTuple<Ts...>>1278: std::integral_constant<size_t, sizeof...(Ts)> {};1279#ifdef __clang__1280#pragma clang diagnostic pop1281#endif1282} // namespace std12831284#define GTEST_MESSAGE_AT_(file, line, message, result_type) \1285::testing::internal::AssertHelper(result_type, file, line, message) = \1286::testing::Message()12871288#define GTEST_MESSAGE_(message, result_type) \1289GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)12901291#define GTEST_FATAL_FAILURE_(message) \1292return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)12931294#define GTEST_NONFATAL_FAILURE_(message) \1295GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)12961297#define GTEST_SUCCESS_(message) \1298GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)12991300#define GTEST_SKIP_(message) \1301return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)13021303// Suppress MSVC warning 4072 (unreachable code) for the code following1304// statement if it returns or throws (or doesn't return or throw in some1305// situations).1306// NOTE: The "else" is important to keep this expansion to prevent a top-level1307// "else" from attaching to our "if".1308#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \1309if (::testing::internal::AlwaysTrue()) { \1310statement; \1311} else /* NOLINT */ \1312static_assert(true, "") // User must have a semicolon after expansion.13131314#if GTEST_HAS_EXCEPTIONS13151316namespace testing {1317namespace internal {13181319class NeverThrown {1320public:1321const char* what() const noexcept {1322return "this exception should never be thrown";1323}1324};13251326} // namespace internal1327} // namespace testing13281329#if GTEST_HAS_RTTI13301331#define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))13321333#else // GTEST_HAS_RTTI13341335#define GTEST_EXCEPTION_TYPE_(e) \1336std::string { "an std::exception-derived error" }13371338#endif // GTEST_HAS_RTTI13391340#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \1341catch (typename std::conditional< \1342std::is_same<typename std::remove_cv<typename std::remove_reference< \1343expected_exception>::type>::type, \1344std::exception>::value, \1345const ::testing::internal::NeverThrown&, const std::exception&>::type \1346e) { \1347gtest_msg.value = "Expected: " #statement \1348" throws an exception of type " #expected_exception \1349".\n Actual: it throws "; \1350gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \1351gtest_msg.value += " with description \""; \1352gtest_msg.value += e.what(); \1353gtest_msg.value += "\"."; \1354goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \1355}13561357#else // GTEST_HAS_EXCEPTIONS13581359#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)13601361#endif // GTEST_HAS_EXCEPTIONS13621363#define GTEST_TEST_THROW_(statement, expected_exception, fail) \1364GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1365if (::testing::internal::TrueWithString gtest_msg{}) { \1366bool gtest_caught_expected = false; \1367try { \1368GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1369} catch (expected_exception const&) { \1370gtest_caught_expected = true; \1371} \1372GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \1373catch (...) { \1374gtest_msg.value = "Expected: " #statement \1375" throws an exception of type " #expected_exception \1376".\n Actual: it throws a different type."; \1377goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \1378} \1379if (!gtest_caught_expected) { \1380gtest_msg.value = "Expected: " #statement \1381" throws an exception of type " #expected_exception \1382".\n Actual: it throws nothing."; \1383goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \1384} \1385} else /*NOLINT*/ \1386GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \1387: fail(gtest_msg.value.c_str())13881389#if GTEST_HAS_EXCEPTIONS13901391#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \1392catch (std::exception const& e) { \1393gtest_msg.value = "it throws "; \1394gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \1395gtest_msg.value += " with description \""; \1396gtest_msg.value += e.what(); \1397gtest_msg.value += "\"."; \1398goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \1399}14001401#else // GTEST_HAS_EXCEPTIONS14021403#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()14041405#endif // GTEST_HAS_EXCEPTIONS14061407#define GTEST_TEST_NO_THROW_(statement, fail) \1408GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1409if (::testing::internal::TrueWithString gtest_msg{}) { \1410try { \1411GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1412} \1413GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \1414catch (...) { \1415gtest_msg.value = "it throws."; \1416goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \1417} \1418} else \1419GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \1420: fail(("Expected: " #statement " doesn't throw an exception.\n" \1421" Actual: " + \1422gtest_msg.value) \1423.c_str())14241425#define GTEST_TEST_ANY_THROW_(statement, fail) \1426GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1427if (::testing::internal::AlwaysTrue()) { \1428bool gtest_caught_any = false; \1429try { \1430GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1431} catch (...) { \1432gtest_caught_any = true; \1433} \1434if (!gtest_caught_any) { \1435goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \1436} \1437} else \1438GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \1439: fail("Expected: " #statement \1440" throws an exception.\n" \1441" Actual: it doesn't.")14421443// Implements Boolean test assertions such as EXPECT_TRUE. expression can be1444// either a boolean expression or an AssertionResult. text is a textual1445// representation of expression as it was passed into the EXPECT_TRUE.1446#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \1447GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1448if (const ::testing::AssertionResult gtest_ar_ = \1449::testing::AssertionResult(expression)) \1450; \1451else \1452fail(::testing::internal::GetBoolAssertionFailureMessage( \1453gtest_ar_, text, #actual, #expected) \1454.c_str())14551456#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \1457GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1458if (::testing::internal::AlwaysTrue()) { \1459const ::testing::internal::HasNewFatalFailureHelper \1460gtest_fatal_failure_checker; \1461GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1462if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \1463goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \1464} \1465} else /* NOLINT */ \1466GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \1467: fail("Expected: " #statement \1468" doesn't generate new fatal " \1469"failures in the current thread.\n" \1470" Actual: it does.")14711472// Expands to the name of the class that implements the given test.1473#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1474test_suite_name##_##test_name##_Test14751476// Helper macro for defining tests.1477#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \1478static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \1479"test_suite_name must not be empty"); \1480static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \1481"test_name must not be empty"); \1482class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1483: public parent_class { \1484public: \1485GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \1486~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \1487GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1488(const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \1489GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \1490const GTEST_TEST_CLASS_NAME_(test_suite_name, \1491test_name) &) = delete; /* NOLINT */ \1492GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1493(GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &&) noexcept = delete; \1494GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \1495GTEST_TEST_CLASS_NAME_(test_suite_name, \1496test_name) &&) noexcept = delete; /* NOLINT */ \1497\1498private: \1499void TestBody() override; \1500[[maybe_unused]] static ::testing::TestInfo* const test_info_; \1501}; \1502\1503::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \1504test_name)::test_info_ = \1505::testing::internal::MakeAndRegisterTestInfo( \1506#test_suite_name, #test_name, nullptr, nullptr, \1507::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \1508::testing::internal::SuiteApiResolver< \1509parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \1510::testing::internal::SuiteApiResolver< \1511parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \1512new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \1513test_suite_name, test_name)>); \1514void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()15151516#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_151715181519