1561 lines · c
1// Copyright 2005, Google Inc.2// All rights reserved.3//4// Redistribution and use in source and binary forms, with or without5// modification, are permitted provided that the following conditions are6// met:7//8// * Redistributions of source code must retain the above copyright9// notice, this list of conditions and the following disclaimer.10// * Redistributions in binary form must reproduce the above11// copyright notice, this list of conditions and the following disclaimer12// in the documentation and/or other materials provided with the13// distribution.14// * Neither the name of Google Inc. nor the names of its15// contributors may be used to endorse or promote products derived from16// this software without specific prior written permission.17//18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29 30// The Google C++ Testing and Mocking Framework (Google Test)31//32// This header file declares functions and macros used internally by33// Google Test. They are subject to change without notice.34 35// IWYU pragma: private, include "gtest/gtest.h"36// IWYU pragma: friend gtest/.*37// IWYU pragma: friend gmock/.*38 39#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_40#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_41 42#include "gtest/internal/gtest-port.h"43 44#ifdef GTEST_OS_LINUX45#include <stdlib.h>46#include <sys/types.h>47#include <sys/wait.h>48#include <unistd.h>49#endif // GTEST_OS_LINUX50 51#if GTEST_HAS_EXCEPTIONS52#include <stdexcept>53#endif54 55#include <ctype.h>56#include <float.h>57#include <string.h>58 59#include <cstdint>60#include <functional>61#include <iomanip>62#include <limits>63#include <map>64#include <set>65#include <string>66#include <type_traits>67#include <utility>68#include <vector>69 70#include "gtest/gtest-message.h"71#include "gtest/internal/gtest-filepath.h"72#include "gtest/internal/gtest-string.h"73#include "gtest/internal/gtest-type-util.h"74 75// Due to C++ preprocessor weirdness, we need double indirection to76// concatenate two tokens when one of them is __LINE__. Writing77//78// foo ## __LINE__79//80// will result in the token foo__LINE__, instead of foo followed by81// the current line number. For more details, see82// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.683#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)84#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar85 86// Stringifies its argument.87// Work around a bug in visual studio which doesn't accept code like this:88//89// #define GTEST_STRINGIFY_(name) #name90// #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...91// MACRO(, x, y)92//93// Complaining about the argument to GTEST_STRINGIFY_ being empty.94// This is allowed by the spec.95#define GTEST_STRINGIFY_HELPER_(name, ...) #name96#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )97 98namespace proto2 {99class MessageLite;100}101 102namespace testing {103 104// Forward declarations.105 106class AssertionResult; // Result of an assertion.107class Message; // Represents a failure message.108class Test; // Represents a test.109class TestInfo; // Information about a test.110class TestPartResult; // Result of a test part.111class UnitTest; // A collection of test suites.112 113template <typename T>114::std::string PrintToString(const T& value);115 116namespace internal {117 118struct TraceInfo; // Information about a trace point.119class TestInfoImpl; // Opaque implementation of TestInfo120class UnitTestImpl; // Opaque implementation of UnitTest121 122// The text used in failure messages to indicate the start of the123// stack trace.124GTEST_API_ extern const char kStackTraceMarker[];125 126// An IgnoredValue object can be implicitly constructed from ANY value.127class IgnoredValue {128 struct Sink {};129 130 public:131 // This constructor template allows any value to be implicitly132 // converted to IgnoredValue. The object has no data member and133 // doesn't try to remember anything about the argument. We134 // deliberately omit the 'explicit' keyword in order to allow the135 // conversion to be implicit.136 // Disable the conversion if T already has a magical conversion operator.137 // Otherwise we get ambiguity.138 template <typename T,139 typename std::enable_if<!std::is_convertible<T, Sink>::value,140 int>::type = 0>141 IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)142};143 144// Appends the user-supplied message to the Google-Test-generated message.145GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg,146 const Message& user_msg);147 148#if GTEST_HAS_EXCEPTIONS149 150GTEST_DISABLE_MSC_WARNINGS_PUSH_(151 4275 /* an exported class was derived from a class that was not exported */)152 153// This exception is thrown by (and only by) a failed Google Test154// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions155// are enabled). We derive it from std::runtime_error, which is for156// errors presumably detectable only at run time. Since157// std::runtime_error inherits from std::exception, many testing158// frameworks know how to extract and print the message inside it.159class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {160 public:161 explicit GoogleTestFailureException(const TestPartResult& failure);162};163 164GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275165 166#endif // GTEST_HAS_EXCEPTIONS167 168namespace edit_distance {169// Returns the optimal edits to go from 'left' to 'right'.170// All edits cost the same, with replace having lower priority than171// add/remove.172// Simple implementation of the Wagner-Fischer algorithm.173// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm174enum EditType { kMatch, kAdd, kRemove, kReplace };175GTEST_API_ std::vector<EditType> CalculateOptimalEdits(176 const std::vector<size_t>& left, const std::vector<size_t>& right);177 178// Same as above, but the input is represented as strings.179GTEST_API_ std::vector<EditType> CalculateOptimalEdits(180 const std::vector<std::string>& left,181 const std::vector<std::string>& right);182 183// Create a diff of the input strings in Unified diff format.184GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,185 const std::vector<std::string>& right,186 size_t context = 2);187 188} // namespace edit_distance189 190// Constructs and returns the message for an equality assertion191// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.192//193// The first four parameters are the expressions used in the assertion194// and their values, as strings. For example, for ASSERT_EQ(foo, bar)195// where foo is 5 and bar is 6, we have:196//197// expected_expression: "foo"198// actual_expression: "bar"199// expected_value: "5"200// actual_value: "6"201//202// The ignoring_case parameter is true if and only if the assertion is a203// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will204// be inserted into the message.205GTEST_API_ AssertionResult EqFailure(const char* expected_expression,206 const char* actual_expression,207 const std::string& expected_value,208 const std::string& actual_value,209 bool ignoring_case);210 211// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.212GTEST_API_ std::string GetBoolAssertionFailureMessage(213 const AssertionResult& assertion_result, const char* expression_text,214 const char* actual_predicate_value, const char* expected_predicate_value);215 216// This template class represents an IEEE floating-point number217// (either single-precision or double-precision, depending on the218// template parameters).219//220// The purpose of this class is to do more sophisticated number221// comparison. (Due to round-off error, etc, it's very unlikely that222// two floating-points will be equal exactly. Hence a naive223// comparison by the == operation often doesn't work.)224//225// Format of IEEE floating-point:226//227// The most-significant bit being the leftmost, an IEEE228// floating-point looks like229//230// sign_bit exponent_bits fraction_bits231//232// Here, sign_bit is a single bit that designates the sign of the233// number.234//235// For float, there are 8 exponent bits and 23 fraction bits.236//237// For double, there are 11 exponent bits and 52 fraction bits.238//239// More details can be found at240// http://en.wikipedia.org/wiki/IEEE_floating-point_standard.241//242// Template parameter:243//244// RawType: the raw floating-point type (either float or double)245template <typename RawType>246class FloatingPoint {247 public:248 // Defines the unsigned integer type that has the same size as the249 // floating point number.250 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;251 252 // Constants.253 254 // # of bits in a number.255 static const size_t kBitCount = 8 * sizeof(RawType);256 257 // # of fraction bits in a number.258 static const size_t kFractionBitCount =259 std::numeric_limits<RawType>::digits - 1;260 261 // # of exponent bits in a number.262 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;263 264 // The mask for the sign bit.265 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);266 267 // The mask for the fraction bits.268 static const Bits kFractionBitMask = ~static_cast<Bits>(0) >>269 (kExponentBitCount + 1);270 271 // The mask for the exponent bits.272 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);273 274 // How many ULP's (Units in the Last Place) we want to tolerate when275 // comparing two numbers. The larger the value, the more error we276 // allow. A 0 value means that two numbers must be exactly the same277 // to be considered equal.278 //279 // The maximum error of a single floating-point operation is 0.5280 // units in the last place. On Intel CPU's, all floating-point281 // calculations are done with 80-bit precision, while double has 64282 // bits. Therefore, 4 should be enough for ordinary use.283 //284 // See the following article for more details on ULP:285 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/286 static const uint32_t kMaxUlps = 4;287 288 // Constructs a FloatingPoint from a raw floating-point number.289 //290 // On an Intel CPU, passing a non-normalized NAN (Not a Number)291 // around may change its bits, although the new value is guaranteed292 // to be also a NAN. Therefore, don't expect this constructor to293 // preserve the bits in x when x is a NAN.294 explicit FloatingPoint(const RawType& x) { u_.value_ = x; }295 296 // Static methods297 298 // Reinterprets a bit pattern as a floating-point number.299 //300 // This function is needed to test the AlmostEquals() method.301 static RawType ReinterpretBits(const Bits bits) {302 FloatingPoint fp(0);303 fp.u_.bits_ = bits;304 return fp.u_.value_;305 }306 307 // Returns the floating-point number that represent positive infinity.308 static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }309 310 // Non-static methods311 312 // Returns the bits that represents this number.313 const Bits& bits() const { return u_.bits_; }314 315 // Returns the exponent bits of this number.316 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }317 318 // Returns the fraction bits of this number.319 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }320 321 // Returns the sign bit of this number.322 Bits sign_bit() const { return kSignBitMask & u_.bits_; }323 324 // Returns true if and only if this is NAN (not a number).325 bool is_nan() const {326 // It's a NAN if the exponent bits are all ones and the fraction327 // bits are not entirely zeros.328 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);329 }330 331 // Returns true if and only if this number is at most kMaxUlps ULP's away332 // from rhs. In particular, this function:333 //334 // - returns false if either number is (or both are) NAN.335 // - treats really large numbers as almost equal to infinity.336 // - thinks +0.0 and -0.0 are 0 DLP's apart.337 bool AlmostEquals(const FloatingPoint& rhs) const {338 // The IEEE standard says that any comparison operation involving339 // a NAN must return false.340 if (is_nan() || rhs.is_nan()) return false;341 342 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=343 kMaxUlps;344 }345 346 private:347 // The data type used to store the actual floating-point number.348 union FloatingPointUnion {349 RawType value_; // The raw floating-point number.350 Bits bits_; // The bits that represent the number.351 };352 353 // Converts an integer from the sign-and-magnitude representation to354 // the biased representation. More precisely, let N be 2 to the355 // power of (kBitCount - 1), an integer x is represented by the356 // unsigned number x + N.357 //358 // For instance,359 //360 // -N + 1 (the most negative number representable using361 // sign-and-magnitude) is represented by 1;362 // 0 is represented by N; and363 // N - 1 (the biggest number representable using364 // sign-and-magnitude) is represented by 2N - 1.365 //366 // Read http://en.wikipedia.org/wiki/Signed_number_representations367 // for more details on signed number representations.368 static Bits SignAndMagnitudeToBiased(const Bits& sam) {369 if (kSignBitMask & sam) {370 // sam represents a negative number.371 return ~sam + 1;372 } else {373 // sam represents a positive number.374 return kSignBitMask | sam;375 }376 }377 378 // Given two numbers in the sign-and-magnitude representation,379 // returns the distance between them as an unsigned number.380 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1,381 const Bits& sam2) {382 const Bits biased1 = SignAndMagnitudeToBiased(sam1);383 const Bits biased2 = SignAndMagnitudeToBiased(sam2);384 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);385 }386 387 FloatingPointUnion u_;388};389 390// Typedefs the instances of the FloatingPoint template class that we391// care to use.392typedef FloatingPoint<float> Float;393typedef FloatingPoint<double> Double;394 395// In order to catch the mistake of putting tests that use different396// test fixture classes in the same test suite, we need to assign397// unique IDs to fixture classes and compare them. The TypeId type is398// used to hold such IDs. The user should treat TypeId as an opaque399// type: the only operation allowed on TypeId values is to compare400// them for equality using the == operator.401typedef const void* TypeId;402 403template <typename T>404class TypeIdHelper {405 public:406 // dummy_ must not have a const type. Otherwise an overly eager407 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge408 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".409 static bool dummy_;410};411 412template <typename T>413bool TypeIdHelper<T>::dummy_ = false;414 415// GetTypeId<T>() returns the ID of type T. Different values will be416// returned for different types. Calling the function twice with the417// same type argument is guaranteed to return the same ID.418template <typename T>419TypeId GetTypeId() {420 // The compiler is required to allocate a different421 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate422 // the template. Therefore, the address of dummy_ is guaranteed to423 // be unique.424 return &(TypeIdHelper<T>::dummy_);425}426 427// Returns the type ID of ::testing::Test. Always call this instead428// of GetTypeId< ::testing::Test>() to get the type ID of429// ::testing::Test, as the latter may give the wrong result due to a430// suspected linker bug when compiling Google Test as a Mac OS X431// framework.432GTEST_API_ TypeId GetTestTypeId();433 434// Defines the abstract factory interface that creates instances435// of a Test object.436class TestFactoryBase {437 public:438 virtual ~TestFactoryBase() = default;439 440 // Creates a test instance to run. The instance is both created and destroyed441 // within TestInfoImpl::Run()442 virtual Test* CreateTest() = 0;443 444 protected:445 TestFactoryBase() {}446 447 private:448 TestFactoryBase(const TestFactoryBase&) = delete;449 TestFactoryBase& operator=(const TestFactoryBase&) = delete;450};451 452// This class provides implementation of TestFactoryBase interface.453// It is used in TEST and TEST_F macros.454template <class TestClass>455class TestFactoryImpl : public TestFactoryBase {456 public:457 Test* CreateTest() override { return new TestClass; }458};459 460#ifdef GTEST_OS_WINDOWS461 462// Predicate-formatters for implementing the HRESULT checking macros463// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}464// We pass a long instead of HRESULT to avoid causing an465// include dependency for the HRESULT type.466GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,467 long hr); // NOLINT468GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,469 long hr); // NOLINT470 471#endif // GTEST_OS_WINDOWS472 473// Types of SetUpTestSuite() and TearDownTestSuite() functions.474using SetUpTestSuiteFunc = void (*)();475using TearDownTestSuiteFunc = void (*)();476 477struct CodeLocation {478 CodeLocation(const std::string& a_file, int a_line)479 : file(a_file), line(a_line) {}480 481 std::string file;482 int line;483};484 485// Helper to identify which setup function for TestCase / TestSuite to call.486// Only one function is allowed, either TestCase or TestSute but not both.487 488// Utility functions to help SuiteApiResolver489using SetUpTearDownSuiteFuncType = void (*)();490 491inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(492 SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {493 return a == def ? nullptr : a;494}495 496template <typename T>497// Note that SuiteApiResolver inherits from T because498// SetUpTestSuite()/TearDownTestSuite() could be protected. This way499// SuiteApiResolver can access them.500struct SuiteApiResolver : T {501 // testing::Test is only forward declared at this point. So we make it a502 // dependent class for the compiler to be OK with it.503 using Test =504 typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;505 506 static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,507 int line_num) {508#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_509 SetUpTearDownSuiteFuncType test_case_fp =510 GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);511 SetUpTearDownSuiteFuncType test_suite_fp =512 GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);513 514 GTEST_CHECK_(!test_case_fp || !test_suite_fp)515 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "516 "make sure there is only one present at "517 << filename << ":" << line_num;518 519 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;520#else521 (void)(filename);522 (void)(line_num);523 return &T::SetUpTestSuite;524#endif525 }526 527 static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,528 int line_num) {529#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_530 SetUpTearDownSuiteFuncType test_case_fp =531 GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);532 SetUpTearDownSuiteFuncType test_suite_fp =533 GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);534 535 GTEST_CHECK_(!test_case_fp || !test_suite_fp)536 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"537 " please make sure there is only one present at"538 << filename << ":" << line_num;539 540 return test_case_fp != nullptr ? test_case_fp : test_suite_fp;541#else542 (void)(filename);543 (void)(line_num);544 return &T::TearDownTestSuite;545#endif546 }547};548 549// Creates a new TestInfo object and registers it with Google Test;550// returns the created object.551//552// Arguments:553//554// test_suite_name: name of the test suite555// name: name of the test556// type_param: the name of the test's type parameter, or NULL if557// this is not a typed or a type-parameterized test.558// value_param: text representation of the test's value parameter,559// or NULL if this is not a type-parameterized test.560// code_location: code location where the test is defined561// fixture_class_id: ID of the test fixture class562// set_up_tc: pointer to the function that sets up the test suite563// tear_down_tc: pointer to the function that tears down the test suite564// factory: pointer to the factory that creates a test object.565// The newly created TestInfo instance will assume566// ownership of the factory object.567GTEST_API_ TestInfo* MakeAndRegisterTestInfo(568 const char* test_suite_name, const char* name, const char* type_param,569 const char* value_param, CodeLocation code_location,570 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,571 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);572 573// If *pstr starts with the given prefix, modifies *pstr to be right574// past the prefix and returns true; otherwise leaves *pstr unchanged575// and returns false. None of pstr, *pstr, and prefix can be NULL.576GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);577 578GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \579/* class A needs to have dll-interface to be used by clients of class B */)580 581// State of the definition of a type-parameterized test suite.582class GTEST_API_ TypedTestSuitePState {583 public:584 TypedTestSuitePState() : registered_(false) {}585 586 // Adds the given test name to defined_test_names_ and return true587 // if the test suite hasn't been registered; otherwise aborts the588 // program.589 bool AddTestName(const char* file, int line, const char* case_name,590 const char* test_name) {591 if (registered_) {592 fprintf(stderr,593 "%s Test %s must be defined before "594 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",595 FormatFileLocation(file, line).c_str(), test_name, case_name);596 fflush(stderr);597 posix::Abort();598 }599 registered_tests_.insert(600 ::std::make_pair(test_name, CodeLocation(file, line)));601 return true;602 }603 604 bool TestExists(const std::string& test_name) const {605 return registered_tests_.count(test_name) > 0;606 }607 608 const CodeLocation& GetCodeLocation(const std::string& test_name) const {609 RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);610 GTEST_CHECK_(it != registered_tests_.end());611 return it->second;612 }613 614 // Verifies that registered_tests match the test names in615 // defined_test_names_; returns registered_tests if successful, or616 // aborts the program otherwise.617 const char* VerifyRegisteredTestNames(const char* test_suite_name,618 const char* file, int line,619 const char* registered_tests);620 621 private:622 typedef ::std::map<std::string, CodeLocation, std::less<>> RegisteredTestsMap;623 624 bool registered_;625 RegisteredTestsMap registered_tests_;626};627 628// Legacy API is deprecated but still available629#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_630using TypedTestCasePState = TypedTestSuitePState;631#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_632 633GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251634 635// Skips to the first non-space char after the first comma in 'str';636// returns NULL if no comma is found in 'str'.637inline const char* SkipComma(const char* str) {638 const char* comma = strchr(str, ',');639 if (comma == nullptr) {640 return nullptr;641 }642 while (IsSpace(*(++comma))) {643 }644 return comma;645}646 647// Returns the prefix of 'str' before the first comma in it; returns648// the entire string if it contains no comma.649inline std::string GetPrefixUntilComma(const char* str) {650 const char* comma = strchr(str, ',');651 return comma == nullptr ? str : std::string(str, comma);652}653 654// Splits a given string on a given delimiter, populating a given655// vector with the fields.656void SplitString(const ::std::string& str, char delimiter,657 ::std::vector<::std::string>* dest);658 659// The default argument to the template below for the case when the user does660// not provide a name generator.661struct DefaultNameGenerator {662 template <typename T>663 static std::string GetName(int i) {664 return StreamableToString(i);665 }666};667 668template <typename Provided = DefaultNameGenerator>669struct NameGeneratorSelector {670 typedef Provided type;671};672 673template <typename NameGenerator>674void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}675 676template <typename NameGenerator, typename Types>677void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {678 result->push_back(NameGenerator::template GetName<typename Types::Head>(i));679 GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,680 i + 1);681}682 683template <typename NameGenerator, typename Types>684std::vector<std::string> GenerateNames() {685 std::vector<std::string> result;686 GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);687 return result;688}689 690// TypeParameterizedTest<Fixture, TestSel, Types>::Register()691// registers a list of type-parameterized tests with Google Test. The692// return value is insignificant - we just need to return something693// such that we can call this function in a namespace scope.694//695// Implementation note: The GTEST_TEMPLATE_ macro declares a template696// template parameter. It's defined in gtest-type-util.h.697template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>698class TypeParameterizedTest {699 public:700 // 'index' is the index of the test in the type list 'Types'701 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,702 // Types). Valid values for 'index' are [0, N - 1] where N is the703 // length of Types.704 static bool Register(const char* prefix, const CodeLocation& code_location,705 const char* case_name, const char* test_names, int index,706 const std::vector<std::string>& type_names =707 GenerateNames<DefaultNameGenerator, Types>()) {708 typedef typename Types::Head Type;709 typedef Fixture<Type> FixtureClass;710 typedef typename GTEST_BIND_(TestSel, Type) TestClass;711 712 // First, registers the first type-parameterized test in the type713 // list.714 MakeAndRegisterTestInfo(715 (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +716 "/" + type_names[static_cast<size_t>(index)])717 .c_str(),718 StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),719 GetTypeName<Type>().c_str(),720 nullptr, // No value parameter.721 code_location, GetTypeId<FixtureClass>(),722 SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(723 code_location.file.c_str(), code_location.line),724 SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(725 code_location.file.c_str(), code_location.line),726 new TestFactoryImpl<TestClass>);727 728 // Next, recurses (at compile time) with the tail of the type list.729 return TypeParameterizedTest<Fixture, TestSel,730 typename Types::Tail>::Register(prefix,731 code_location,732 case_name,733 test_names,734 index + 1,735 type_names);736 }737};738 739// The base case for the compile time recursion.740template <GTEST_TEMPLATE_ Fixture, class TestSel>741class TypeParameterizedTest<Fixture, TestSel, internal::None> {742 public:743 static bool Register(const char* /*prefix*/, const CodeLocation&,744 const char* /*case_name*/, const char* /*test_names*/,745 int /*index*/,746 const std::vector<std::string>& =747 std::vector<std::string>() /*type_names*/) {748 return true;749 }750};751 752GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,753 CodeLocation code_location);754GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(755 const char* case_name);756 757// TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()758// registers *all combinations* of 'Tests' and 'Types' with Google759// Test. The return value is insignificant - we just need to return760// something such that we can call this function in a namespace scope.761template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>762class TypeParameterizedTestSuite {763 public:764 static bool Register(const char* prefix, CodeLocation code_location,765 const TypedTestSuitePState* state, const char* case_name,766 const char* test_names,767 const std::vector<std::string>& type_names =768 GenerateNames<DefaultNameGenerator, Types>()) {769 RegisterTypeParameterizedTestSuiteInstantiation(case_name);770 std::string test_name =771 StripTrailingSpaces(GetPrefixUntilComma(test_names));772 if (!state->TestExists(test_name)) {773 fprintf(stderr, "Failed to get code location for test %s.%s at %s.",774 case_name, test_name.c_str(),775 FormatFileLocation(code_location.file.c_str(), code_location.line)776 .c_str());777 fflush(stderr);778 posix::Abort();779 }780 const CodeLocation& test_location = state->GetCodeLocation(test_name);781 782 typedef typename Tests::Head Head;783 784 // First, register the first test in 'Test' for each type in 'Types'.785 TypeParameterizedTest<Fixture, Head, Types>::Register(786 prefix, test_location, case_name, test_names, 0, type_names);787 788 // Next, recurses (at compile time) with the tail of the test list.789 return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,790 Types>::Register(prefix, code_location,791 state, case_name,792 SkipComma(test_names),793 type_names);794 }795};796 797// The base case for the compile time recursion.798template <GTEST_TEMPLATE_ Fixture, typename Types>799class TypeParameterizedTestSuite<Fixture, internal::None, Types> {800 public:801 static bool Register(const char* /*prefix*/, const CodeLocation&,802 const TypedTestSuitePState* /*state*/,803 const char* /*case_name*/, const char* /*test_names*/,804 const std::vector<std::string>& =805 std::vector<std::string>() /*type_names*/) {806 return true;807 }808};809 810// Returns the current OS stack trace as an std::string.811//812// The maximum number of stack frames to be included is specified by813// the gtest_stack_trace_depth flag. The skip_count parameter814// specifies the number of top frames to be skipped, which doesn't815// count against the number of frames to be included.816//817// For example, if Foo() calls Bar(), which in turn calls818// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in819// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.820GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(int skip_count);821 822// Helpers for suppressing warnings on unreachable code or constant823// condition.824 825// Always returns true.826GTEST_API_ bool AlwaysTrue();827 828// Always returns false.829inline bool AlwaysFalse() { return !AlwaysTrue(); }830 831// Helper for suppressing false warning from Clang on a const char*832// variable declared in a conditional expression always being NULL in833// the else branch.834struct GTEST_API_ ConstCharPtr {835 ConstCharPtr(const char* str) : value(str) {}836 operator bool() const { return true; }837 const char* value;838};839 840// Helper for declaring std::string within 'if' statement841// in pre C++17 build environment.842struct TrueWithString {843 TrueWithString() = default;844 explicit TrueWithString(const char* str) : value(str) {}845 explicit TrueWithString(const std::string& str) : value(str) {}846 explicit operator bool() const { return true; }847 std::string value;848};849 850// A simple Linear Congruential Generator for generating random851// numbers with a uniform distribution. Unlike rand() and srand(), it852// doesn't use global state (and therefore can't interfere with user853// code). Unlike rand_r(), it's portable. An LCG isn't very random,854// but it's good enough for our purposes.855class GTEST_API_ Random {856 public:857 static const uint32_t kMaxRange = 1u << 31;858 859 explicit Random(uint32_t seed) : state_(seed) {}860 861 void Reseed(uint32_t seed) { state_ = seed; }862 863 // Generates a random number from [0, range). Crashes if 'range' is864 // 0 or greater than kMaxRange.865 uint32_t Generate(uint32_t range);866 867 private:868 uint32_t state_;869 Random(const Random&) = delete;870 Random& operator=(const Random&) = delete;871};872 873// Turns const U&, U&, const U, and U all into U.874#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \875 typename std::remove_const<typename std::remove_reference<T>::type>::type876 877// HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant878// that's true if and only if T has methods DebugString() and ShortDebugString()879// that return std::string.880template <typename T>881class HasDebugStringAndShortDebugString {882 private:883 template <typename C>884 static auto CheckDebugString(C*) -> typename std::is_same<885 std::string, decltype(std::declval<const C>().DebugString())>::type;886 template <typename>887 static std::false_type CheckDebugString(...);888 889 template <typename C>890 static auto CheckShortDebugString(C*) -> typename std::is_same<891 std::string, decltype(std::declval<const C>().ShortDebugString())>::type;892 template <typename>893 static std::false_type CheckShortDebugString(...);894 895 using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));896 using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));897 898 public:899 static constexpr bool value =900 HasDebugStringType::value && HasShortDebugStringType::value;901};902 903#ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL904template <typename T>905constexpr bool HasDebugStringAndShortDebugString<T>::value;906#endif907 908// When the compiler sees expression IsContainerTest<C>(0), if C is an909// STL-style container class, the first overload of IsContainerTest910// will be viable (since both C::iterator* and C::const_iterator* are911// valid types and NULL can be implicitly converted to them). It will912// be picked over the second overload as 'int' is a perfect match for913// the type of argument 0. If C::iterator or C::const_iterator is not914// a valid type, the first overload is not viable, and the second915// overload will be picked. Therefore, we can determine whether C is916// a container class by checking the type of IsContainerTest<C>(0).917// The value of the expression is insignificant.918//919// In C++11 mode we check the existence of a const_iterator and that an920// iterator is properly implemented for the container.921//922// For pre-C++11 that we look for both C::iterator and C::const_iterator.923// The reason is that C++ injects the name of a class as a member of the924// class itself (e.g. you can refer to class iterator as either925// 'iterator' or 'iterator::iterator'). If we look for C::iterator926// only, for example, we would mistakenly think that a class named927// iterator is an STL container.928//929// Also note that the simpler approach of overloading930// IsContainerTest(typename C::const_iterator*) and931// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.932typedef int IsContainer;933template <class C,934 class Iterator = decltype(::std::declval<const C&>().begin()),935 class = decltype(::std::declval<const C&>().end()),936 class = decltype(++::std::declval<Iterator&>()),937 class = decltype(*::std::declval<Iterator>()),938 class = typename C::const_iterator>939IsContainer IsContainerTest(int /* dummy */) {940 return 0;941}942 943typedef char IsNotContainer;944template <class C>945IsNotContainer IsContainerTest(long /* dummy */) {946 return '\0';947}948 949// Trait to detect whether a type T is a hash table.950// The heuristic used is that the type contains an inner type `hasher` and does951// not contain an inner type `reverse_iterator`.952// If the container is iterable in reverse, then order might actually matter.953template <typename T>954struct IsHashTable {955 private:956 template <typename U>957 static char test(typename U::hasher*, typename U::reverse_iterator*);958 template <typename U>959 static int test(typename U::hasher*, ...);960 template <typename U>961 static char test(...);962 963 public:964 static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);965};966 967template <typename T>968const bool IsHashTable<T>::value;969 970template <typename C,971 bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>972struct IsRecursiveContainerImpl;973 974template <typename C>975struct IsRecursiveContainerImpl<C, false> : public std::false_type {};976 977// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to978// obey the same inconsistencies as the IsContainerTest, namely check if979// something is a container is relying on only const_iterator in C++11 and980// is relying on both const_iterator and iterator otherwise981template <typename C>982struct IsRecursiveContainerImpl<C, true> {983 using value_type = decltype(*std::declval<typename C::const_iterator>());984 using type =985 std::is_same<typename std::remove_const<986 typename std::remove_reference<value_type>::type>::type,987 C>;988};989 990// IsRecursiveContainer<Type> is a unary compile-time predicate that991// evaluates whether C is a recursive container type. A recursive container992// type is a container type whose value_type is equal to the container type993// itself. An example for a recursive container type is994// boost::filesystem::path, whose iterator has a value_type that is equal to995// boost::filesystem::path.996template <typename C>997struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};998 999// Utilities for native arrays.1000 1001// ArrayEq() compares two k-dimensional native arrays using the1002// elements' operator==, where k can be any integer >= 0. When k is1003// 0, ArrayEq() degenerates into comparing a single pair of values.1004 1005template <typename T, typename U>1006bool ArrayEq(const T* lhs, size_t size, const U* rhs);1007 1008// This generic version is used when k is 0.1009template <typename T, typename U>1010inline bool ArrayEq(const T& lhs, const U& rhs) {1011 return lhs == rhs;1012}1013 1014// This overload is used when k >= 1.1015template <typename T, typename U, size_t N>1016inline bool ArrayEq(const T (&lhs)[N], const U (&rhs)[N]) {1017 return internal::ArrayEq(lhs, N, rhs);1018}1019 1020// This helper reduces code bloat. If we instead put its logic inside1021// the previous ArrayEq() function, arrays with different sizes would1022// lead to different copies of the template code.1023template <typename T, typename U>1024bool ArrayEq(const T* lhs, size_t size, const U* rhs) {1025 for (size_t i = 0; i != size; i++) {1026 if (!internal::ArrayEq(lhs[i], rhs[i])) return false;1027 }1028 return true;1029}1030 1031// Finds the first element in the iterator range [begin, end) that1032// equals elem. Element may be a native array type itself.1033template <typename Iter, typename Element>1034Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {1035 for (Iter it = begin; it != end; ++it) {1036 if (internal::ArrayEq(*it, elem)) return it;1037 }1038 return end;1039}1040 1041// CopyArray() copies a k-dimensional native array using the elements'1042// operator=, where k can be any integer >= 0. When k is 0,1043// CopyArray() degenerates into copying a single value.1044 1045template <typename T, typename U>1046void CopyArray(const T* from, size_t size, U* to);1047 1048// This generic version is used when k is 0.1049template <typename T, typename U>1050inline void CopyArray(const T& from, U* to) {1051 *to = from;1052}1053 1054// This overload is used when k >= 1.1055template <typename T, typename U, size_t N>1056inline void CopyArray(const T (&from)[N], U (*to)[N]) {1057 internal::CopyArray(from, N, *to);1058}1059 1060// This helper reduces code bloat. If we instead put its logic inside1061// the previous CopyArray() function, arrays with different sizes1062// would lead to different copies of the template code.1063template <typename T, typename U>1064void CopyArray(const T* from, size_t size, U* to) {1065 for (size_t i = 0; i != size; i++) {1066 internal::CopyArray(from[i], to + i);1067 }1068}1069 1070// The relation between an NativeArray object (see below) and the1071// native array it represents.1072// We use 2 different structs to allow non-copyable types to be used, as long1073// as RelationToSourceReference() is passed.1074struct RelationToSourceReference {};1075struct RelationToSourceCopy {};1076 1077// Adapts a native array to a read-only STL-style container. Instead1078// of the complete STL container concept, this adaptor only implements1079// members useful for Google Mock's container matchers. New members1080// should be added as needed. To simplify the implementation, we only1081// support Element being a raw type (i.e. having no top-level const or1082// reference modifier). It's the client's responsibility to satisfy1083// this requirement. Element can be an array type itself (hence1084// multi-dimensional arrays are supported).1085template <typename Element>1086class NativeArray {1087 public:1088 // STL-style container typedefs.1089 typedef Element value_type;1090 typedef Element* iterator;1091 typedef const Element* const_iterator;1092 1093 // Constructs from a native array. References the source.1094 NativeArray(const Element* array, size_t count, RelationToSourceReference) {1095 InitRef(array, count);1096 }1097 1098 // Constructs from a native array. Copies the source.1099 NativeArray(const Element* array, size_t count, RelationToSourceCopy) {1100 InitCopy(array, count);1101 }1102 1103 // Copy constructor.1104 NativeArray(const NativeArray& rhs) {1105 (this->*rhs.clone_)(rhs.array_, rhs.size_);1106 }1107 1108 ~NativeArray() {1109 if (clone_ != &NativeArray::InitRef) delete[] array_;1110 }1111 1112 // STL-style container methods.1113 size_t size() const { return size_; }1114 const_iterator begin() const { return array_; }1115 const_iterator end() const { return array_ + size_; }1116 bool operator==(const NativeArray& rhs) const {1117 return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin());1118 }1119 1120 private:1121 static_assert(!std::is_const<Element>::value, "Type must not be const");1122 static_assert(!std::is_reference<Element>::value,1123 "Type must not be a reference");1124 1125 // Initializes this object with a copy of the input.1126 void InitCopy(const Element* array, size_t a_size) {1127 Element* const copy = new Element[a_size];1128 CopyArray(array, a_size, copy);1129 array_ = copy;1130 size_ = a_size;1131 clone_ = &NativeArray::InitCopy;1132 }1133 1134 // Initializes this object with a reference of the input.1135 void InitRef(const Element* array, size_t a_size) {1136 array_ = array;1137 size_ = a_size;1138 clone_ = &NativeArray::InitRef;1139 }1140 1141 const Element* array_;1142 size_t size_;1143 void (NativeArray::*clone_)(const Element*, size_t);1144};1145 1146// Backport of std::index_sequence.1147template <size_t... Is>1148struct IndexSequence {1149 using type = IndexSequence;1150};1151 1152// Double the IndexSequence, and one if plus_one is true.1153template <bool plus_one, typename T, size_t sizeofT>1154struct DoubleSequence;1155template <size_t... I, size_t sizeofT>1156struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {1157 using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;1158};1159template <size_t... I, size_t sizeofT>1160struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {1161 using type = IndexSequence<I..., (sizeofT + I)...>;1162};1163 1164// Backport of std::make_index_sequence.1165// It uses O(ln(N)) instantiation depth.1166template <size_t N>1167struct MakeIndexSequenceImpl1168 : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,1169 N / 2>::type {};1170 1171template <>1172struct MakeIndexSequenceImpl<0> : IndexSequence<> {};1173 1174template <size_t N>1175using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;1176 1177template <typename... T>1178using IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;1179 1180template <size_t>1181struct Ignore {1182 Ignore(...); // NOLINT1183};1184 1185template <typename>1186struct ElemFromListImpl;1187template <size_t... I>1188struct ElemFromListImpl<IndexSequence<I...>> {1189 // We make Ignore a template to solve a problem with MSVC.1190 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but1191 // MSVC doesn't understand how to deal with that pack expansion.1192 // Use `0 * I` to have a single instantiation of Ignore.1193 template <typename R>1194 static R Apply(Ignore<0 * I>..., R (*)(), ...);1195};1196 1197template <size_t N, typename... T>1198struct ElemFromList {1199 using type =1200 decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(1201 static_cast<T (*)()>(nullptr)...));1202};1203 1204struct FlatTupleConstructTag {};1205 1206template <typename... T>1207class FlatTuple;1208 1209template <typename Derived, size_t I>1210struct FlatTupleElemBase;1211 1212template <typename... T, size_t I>1213struct FlatTupleElemBase<FlatTuple<T...>, I> {1214 using value_type = typename ElemFromList<I, T...>::type;1215 FlatTupleElemBase() = default;1216 template <typename Arg>1217 explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)1218 : value(std::forward<Arg>(t)) {}1219 value_type value;1220};1221 1222template <typename Derived, typename Idx>1223struct FlatTupleBase;1224 1225template <size_t... Idx, typename... T>1226struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>1227 : FlatTupleElemBase<FlatTuple<T...>, Idx>... {1228 using Indices = IndexSequence<Idx...>;1229 FlatTupleBase() = default;1230 template <typename... Args>1231 explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)1232 : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},1233 std::forward<Args>(args))... {}1234 1235 template <size_t I>1236 const typename ElemFromList<I, T...>::type& Get() const {1237 return FlatTupleElemBase<FlatTuple<T...>, I>::value;1238 }1239 1240 template <size_t I>1241 typename ElemFromList<I, T...>::type& Get() {1242 return FlatTupleElemBase<FlatTuple<T...>, I>::value;1243 }1244 1245 template <typename F>1246 auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {1247 return std::forward<F>(f)(Get<Idx>()...);1248 }1249 1250 template <typename F>1251 auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {1252 return std::forward<F>(f)(Get<Idx>()...);1253 }1254};1255 1256// Analog to std::tuple but with different tradeoffs.1257// This class minimizes the template instantiation depth, thus allowing more1258// elements than std::tuple would. std::tuple has been seen to require an1259// instantiation depth of more than 10x the number of elements in some1260// implementations.1261// FlatTuple and ElemFromList are not recursive and have a fixed depth1262// regardless of T...1263// MakeIndexSequence, on the other hand, it is recursive but with an1264// instantiation depth of O(ln(N)).1265template <typename... T>1266class FlatTuple1267 : private FlatTupleBase<FlatTuple<T...>,1268 typename MakeIndexSequence<sizeof...(T)>::type> {1269 using Indices = typename FlatTupleBase<1270 FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;1271 1272 public:1273 FlatTuple() = default;1274 template <typename... Args>1275 explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)1276 : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}1277 1278 using FlatTuple::FlatTupleBase::Apply;1279 using FlatTuple::FlatTupleBase::Get;1280};1281 1282// Utility functions to be called with static_assert to induce deprecation1283// warnings.1284GTEST_INTERNAL_DEPRECATED(1285 "INSTANTIATE_TEST_CASE_P is deprecated, please use "1286 "INSTANTIATE_TEST_SUITE_P")1287constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }1288 1289GTEST_INTERNAL_DEPRECATED(1290 "TYPED_TEST_CASE_P is deprecated, please use "1291 "TYPED_TEST_SUITE_P")1292constexpr bool TypedTestCase_P_IsDeprecated() { return true; }1293 1294GTEST_INTERNAL_DEPRECATED(1295 "TYPED_TEST_CASE is deprecated, please use "1296 "TYPED_TEST_SUITE")1297constexpr bool TypedTestCaseIsDeprecated() { return true; }1298 1299GTEST_INTERNAL_DEPRECATED(1300 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "1301 "REGISTER_TYPED_TEST_SUITE_P")1302constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }1303 1304GTEST_INTERNAL_DEPRECATED(1305 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "1306 "INSTANTIATE_TYPED_TEST_SUITE_P")1307constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }1308 1309} // namespace internal1310} // namespace testing1311 1312namespace std {1313// Some standard library implementations use `struct tuple_size` and some use1314// `class tuple_size`. Clang warns about the mismatch.1315// https://reviews.llvm.org/D554661316#ifdef __clang__1317#pragma clang diagnostic push1318#pragma clang diagnostic ignored "-Wmismatched-tags"1319#endif1320template <typename... Ts>1321struct tuple_size<testing::internal::FlatTuple<Ts...>>1322 : std::integral_constant<size_t, sizeof...(Ts)> {};1323#ifdef __clang__1324#pragma clang diagnostic pop1325#endif1326} // namespace std1327 1328#define GTEST_MESSAGE_AT_(file, line, message, result_type) \1329 ::testing::internal::AssertHelper(result_type, file, line, message) = \1330 ::testing::Message()1331 1332#define GTEST_MESSAGE_(message, result_type) \1333 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)1334 1335#define GTEST_FATAL_FAILURE_(message) \1336 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)1337 1338#define GTEST_NONFATAL_FAILURE_(message) \1339 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)1340 1341#define GTEST_SUCCESS_(message) \1342 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)1343 1344#define GTEST_SKIP_(message) \1345 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)1346 1347// Suppress MSVC warning 4072 (unreachable code) for the code following1348// statement if it returns or throws (or doesn't return or throw in some1349// situations).1350// NOTE: The "else" is important to keep this expansion to prevent a top-level1351// "else" from attaching to our "if".1352#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \1353 if (::testing::internal::AlwaysTrue()) { \1354 statement; \1355 } else /* NOLINT */ \1356 static_assert(true, "") // User must have a semicolon after expansion.1357 1358#if GTEST_HAS_EXCEPTIONS1359 1360namespace testing {1361namespace internal {1362 1363class NeverThrown {1364 public:1365 const char* what() const noexcept {1366 return "this exception should never be thrown";1367 }1368};1369 1370} // namespace internal1371} // namespace testing1372 1373#if GTEST_HAS_RTTI1374 1375#define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))1376 1377#else // GTEST_HAS_RTTI1378 1379#define GTEST_EXCEPTION_TYPE_(e) \1380 std::string { "an std::exception-derived error" }1381 1382#endif // GTEST_HAS_RTTI1383 1384#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \1385 catch (typename std::conditional< \1386 std::is_same<typename std::remove_cv<typename std::remove_reference< \1387 expected_exception>::type>::type, \1388 std::exception>::value, \1389 const ::testing::internal::NeverThrown&, const std::exception&>::type \1390 e) { \1391 gtest_msg.value = "Expected: " #statement \1392 " throws an exception of type " #expected_exception \1393 ".\n Actual: it throws "; \1394 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \1395 gtest_msg.value += " with description \""; \1396 gtest_msg.value += e.what(); \1397 gtest_msg.value += "\"."; \1398 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \1399 }1400 1401#else // GTEST_HAS_EXCEPTIONS1402 1403#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)1404 1405#endif // GTEST_HAS_EXCEPTIONS1406 1407#define GTEST_TEST_THROW_(statement, expected_exception, fail) \1408 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1409 if (::testing::internal::TrueWithString gtest_msg{}) { \1410 bool gtest_caught_expected = false; \1411 try { \1412 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1413 } catch (expected_exception const&) { \1414 gtest_caught_expected = true; \1415 } \1416 GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \1417 catch (...) { \1418 gtest_msg.value = "Expected: " #statement \1419 " throws an exception of type " #expected_exception \1420 ".\n Actual: it throws a different type."; \1421 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \1422 } \1423 if (!gtest_caught_expected) { \1424 gtest_msg.value = "Expected: " #statement \1425 " throws an exception of type " #expected_exception \1426 ".\n Actual: it throws nothing."; \1427 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \1428 } \1429 } else /*NOLINT*/ \1430 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \1431 : fail(gtest_msg.value.c_str())1432 1433#if GTEST_HAS_EXCEPTIONS1434 1435#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \1436 catch (std::exception const& e) { \1437 gtest_msg.value = "it throws "; \1438 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \1439 gtest_msg.value += " with description \""; \1440 gtest_msg.value += e.what(); \1441 gtest_msg.value += "\"."; \1442 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \1443 }1444 1445#else // GTEST_HAS_EXCEPTIONS1446 1447#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()1448 1449#endif // GTEST_HAS_EXCEPTIONS1450 1451#define GTEST_TEST_NO_THROW_(statement, fail) \1452 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1453 if (::testing::internal::TrueWithString gtest_msg{}) { \1454 try { \1455 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1456 } \1457 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \1458 catch (...) { \1459 gtest_msg.value = "it throws."; \1460 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \1461 } \1462 } else \1463 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \1464 : fail(("Expected: " #statement " doesn't throw an exception.\n" \1465 " Actual: " + \1466 gtest_msg.value) \1467 .c_str())1468 1469#define GTEST_TEST_ANY_THROW_(statement, fail) \1470 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1471 if (::testing::internal::AlwaysTrue()) { \1472 bool gtest_caught_any = false; \1473 try { \1474 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1475 } catch (...) { \1476 gtest_caught_any = true; \1477 } \1478 if (!gtest_caught_any) { \1479 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \1480 } \1481 } else \1482 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \1483 : fail("Expected: " #statement \1484 " throws an exception.\n" \1485 " Actual: it doesn't.")1486 1487// Implements Boolean test assertions such as EXPECT_TRUE. expression can be1488// either a boolean expression or an AssertionResult. text is a textual1489// representation of expression as it was passed into the EXPECT_TRUE.1490#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \1491 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1492 if (const ::testing::AssertionResult gtest_ar_ = \1493 ::testing::AssertionResult(expression)) \1494 ; \1495 else \1496 fail(::testing::internal::GetBoolAssertionFailureMessage( \1497 gtest_ar_, text, #actual, #expected) \1498 .c_str())1499 1500#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \1501 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \1502 if (::testing::internal::AlwaysTrue()) { \1503 const ::testing::internal::HasNewFatalFailureHelper \1504 gtest_fatal_failure_checker; \1505 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \1506 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \1507 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \1508 } \1509 } else /* NOLINT */ \1510 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \1511 : fail("Expected: " #statement \1512 " doesn't generate new fatal " \1513 "failures in the current thread.\n" \1514 " Actual: it does.")1515 1516// Expands to the name of the class that implements the given test.1517#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1518 test_suite_name##_##test_name##_Test1519 1520// Helper macro for defining tests.1521#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \1522 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \1523 "test_suite_name must not be empty"); \1524 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \1525 "test_name must not be empty"); \1526 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1527 : public parent_class { \1528 public: \1529 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \1530 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \1531 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1532 (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \1533 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \1534 const GTEST_TEST_CLASS_NAME_(test_suite_name, \1535 test_name) &) = delete; /* NOLINT */ \1536 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \1537 (GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &&) noexcept = delete; \1538 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \1539 GTEST_TEST_CLASS_NAME_(test_suite_name, \1540 test_name) &&) noexcept = delete; /* NOLINT */ \1541 \1542 private: \1543 void TestBody() override; \1544 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \1545 }; \1546 \1547 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \1548 test_name)::test_info_ = \1549 ::testing::internal::MakeAndRegisterTestInfo( \1550 #test_suite_name, #test_name, nullptr, nullptr, \1551 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \1552 ::testing::internal::SuiteApiResolver< \1553 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \1554 ::testing::internal::SuiteApiResolver< \1555 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \1556 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \1557 test_suite_name, test_name)>); \1558 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()1559 1560#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_1561