gtest-internal.h (55995B)
1 // Copyright 2005, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 // 30 // The Google C++ Testing and Mocking Framework (Google Test) 31 // 32 // This header file declares functions and macros used internally by 33 // Google Test. They are subject to change without notice. 34 35 // GOOGLETEST_CM0001 DO NOT DELETE 36 37 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ 38 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ 39 40 #include "gtest/internal/gtest-port.h" 41 42 #if GTEST_OS_LINUX 43 # include <stdlib.h> 44 # include <sys/types.h> 45 # include <sys/wait.h> 46 # include <unistd.h> 47 #endif // GTEST_OS_LINUX 48 49 #if GTEST_HAS_EXCEPTIONS 50 # include <stdexcept> 51 #endif 52 53 #include <ctype.h> 54 #include <float.h> 55 #include <string.h> 56 #include <cstdint> 57 #include <iomanip> 58 #include <limits> 59 #include <map> 60 #include <set> 61 #include <string> 62 #include <type_traits> 63 #include <vector> 64 65 #include "gtest/gtest-message.h" 66 #include "gtest/internal/gtest-filepath.h" 67 #include "gtest/internal/gtest-string.h" 68 #include "gtest/internal/gtest-type-util.h" 69 70 // Due to C++ preprocessor weirdness, we need double indirection to 71 // concatenate two tokens when one of them is __LINE__. Writing 72 // 73 // foo ## __LINE__ 74 // 75 // will result in the token foo__LINE__, instead of foo followed by 76 // the current line number. For more details, see 77 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 78 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) 79 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar 80 81 // Stringifies its argument. 82 // Work around a bug in visual studio which doesn't accept code like this: 83 // 84 // #define GTEST_STRINGIFY_(name) #name 85 // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ... 86 // MACRO(, x, y) 87 // 88 // Complaining about the argument to GTEST_STRINGIFY_ being empty. 89 // This is allowed by the spec. 90 #define GTEST_STRINGIFY_HELPER_(name, ...) #name 91 #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, ) 92 93 namespace proto2 { class Message; } 94 95 namespace testing { 96 97 // Forward declarations. 98 99 class AssertionResult; // Result of an assertion. 100 class Message; // Represents a failure message. 101 class Test; // Represents a test. 102 class TestInfo; // Information about a test. 103 class TestPartResult; // Result of a test part. 104 class UnitTest; // A collection of test suites. 105 106 template <typename T> 107 ::std::string PrintToString(const T& value); 108 109 namespace internal { 110 111 struct TraceInfo; // Information about a trace point. 112 class TestInfoImpl; // Opaque implementation of TestInfo 113 class UnitTestImpl; // Opaque implementation of UnitTest 114 115 // The text used in failure messages to indicate the start of the 116 // stack trace. 117 GTEST_API_ extern const char kStackTraceMarker[]; 118 119 // An IgnoredValue object can be implicitly constructed from ANY value. 120 class IgnoredValue { 121 struct Sink {}; 122 public: 123 // This constructor template allows any value to be implicitly 124 // converted to IgnoredValue. The object has no data member and 125 // doesn't try to remember anything about the argument. We 126 // deliberately omit the 'explicit' keyword in order to allow the 127 // conversion to be implicit. 128 // Disable the conversion if T already has a magical conversion operator. 129 // Otherwise we get ambiguity. 130 template <typename T, 131 typename std::enable_if<!std::is_convertible<T, Sink>::value, 132 int>::type = 0> 133 IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) 134 }; 135 136 // Appends the user-supplied message to the Google-Test-generated message. 137 GTEST_API_ std::string AppendUserMessage( 138 const std::string& gtest_msg, const Message& user_msg); 139 140 #if GTEST_HAS_EXCEPTIONS 141 142 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \ 143 /* an exported class was derived from a class that was not exported */) 144 145 // This exception is thrown by (and only by) a failed Google Test 146 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions 147 // are enabled). We derive it from std::runtime_error, which is for 148 // errors presumably detectable only at run time. Since 149 // std::runtime_error inherits from std::exception, many testing 150 // frameworks know how to extract and print the message inside it. 151 class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { 152 public: 153 explicit GoogleTestFailureException(const TestPartResult& failure); 154 }; 155 156 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275 157 158 #endif // GTEST_HAS_EXCEPTIONS 159 160 namespace edit_distance { 161 // Returns the optimal edits to go from 'left' to 'right'. 162 // All edits cost the same, with replace having lower priority than 163 // add/remove. 164 // Simple implementation of the Wagner-Fischer algorithm. 165 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm 166 enum EditType { kMatch, kAdd, kRemove, kReplace }; 167 GTEST_API_ std::vector<EditType> CalculateOptimalEdits( 168 const std::vector<size_t>& left, const std::vector<size_t>& right); 169 170 // Same as above, but the input is represented as strings. 171 GTEST_API_ std::vector<EditType> CalculateOptimalEdits( 172 const std::vector<std::string>& left, 173 const std::vector<std::string>& right); 174 175 // Create a diff of the input strings in Unified diff format. 176 GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left, 177 const std::vector<std::string>& right, 178 size_t context = 2); 179 180 } // namespace edit_distance 181 182 // Calculate the diff between 'left' and 'right' and return it in unified diff 183 // format. 184 // If not null, stores in 'total_line_count' the total number of lines found 185 // in left + right. 186 GTEST_API_ std::string DiffStrings(const std::string& left, 187 const std::string& right, 188 size_t* total_line_count); 189 190 // Constructs and returns the message for an equality assertion 191 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. 192 // 193 // The first four parameters are the expressions used in the assertion 194 // 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 a 203 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will 204 // be inserted into the message. 205 GTEST_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. 212 GTEST_API_ std::string GetBoolAssertionFailureMessage( 213 const AssertionResult& assertion_result, 214 const char* expression_text, 215 const char* actual_predicate_value, 216 const char* expected_predicate_value); 217 218 // This template class represents an IEEE floating-point number 219 // (either single-precision or double-precision, depending on the 220 // template parameters). 221 // 222 // The purpose of this class is to do more sophisticated number 223 // comparison. (Due to round-off error, etc, it's very unlikely that 224 // two floating-points will be equal exactly. Hence a naive 225 // comparison by the == operation often doesn't work.) 226 // 227 // Format of IEEE floating-point: 228 // 229 // The most-significant bit being the leftmost, an IEEE 230 // floating-point looks like 231 // 232 // sign_bit exponent_bits fraction_bits 233 // 234 // Here, sign_bit is a single bit that designates the sign of the 235 // number. 236 // 237 // For float, there are 8 exponent bits and 23 fraction bits. 238 // 239 // For double, there are 11 exponent bits and 52 fraction bits. 240 // 241 // More details can be found at 242 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard. 243 // 244 // Template parameter: 245 // 246 // RawType: the raw floating-point type (either float or double) 247 template <typename RawType> 248 class FloatingPoint { 249 public: 250 // Defines the unsigned integer type that has the same size as the 251 // floating point number. 252 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits; 253 254 // Constants. 255 256 // # of bits in a number. 257 static const size_t kBitCount = 8*sizeof(RawType); 258 259 // # of fraction bits in a number. 260 static const size_t kFractionBitCount = 261 std::numeric_limits<RawType>::digits - 1; 262 263 // # of exponent bits in a number. 264 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; 265 266 // The mask for the sign bit. 267 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1); 268 269 // The mask for the fraction bits. 270 static const Bits kFractionBitMask = 271 ~static_cast<Bits>(0) >> (kExponentBitCount + 1); 272 273 // The mask for the exponent bits. 274 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); 275 276 // How many ULP's (Units in the Last Place) we want to tolerate when 277 // comparing two numbers. The larger the value, the more error we 278 // allow. A 0 value means that two numbers must be exactly the same 279 // to be considered equal. 280 // 281 // The maximum error of a single floating-point operation is 0.5 282 // units in the last place. On Intel CPU's, all floating-point 283 // calculations are done with 80-bit precision, while double has 64 284 // bits. Therefore, 4 should be enough for ordinary use. 285 // 286 // See the following article for more details on ULP: 287 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ 288 static const size_t kMaxUlps = 4; 289 290 // Constructs a FloatingPoint from a raw floating-point number. 291 // 292 // On an Intel CPU, passing a non-normalized NAN (Not a Number) 293 // around may change its bits, although the new value is guaranteed 294 // to be also a NAN. Therefore, don't expect this constructor to 295 // preserve the bits in x when x is a NAN. 296 explicit FloatingPoint(const RawType& x) { u_.value_ = x; } 297 298 // Static methods 299 300 // Reinterprets a bit pattern as a floating-point number. 301 // 302 // This function is needed to test the AlmostEquals() method. 303 static RawType ReinterpretBits(const Bits bits) { 304 FloatingPoint fp(0); 305 fp.u_.bits_ = bits; 306 return fp.u_.value_; 307 } 308 309 // Returns the floating-point number that represent positive infinity. 310 static RawType Infinity() { 311 return ReinterpretBits(kExponentBitMask); 312 } 313 314 // Returns the maximum representable finite floating-point number. 315 static RawType Max(); 316 317 // Non-static methods 318 319 // Returns the bits that represents this number. 320 const Bits &bits() const { return u_.bits_; } 321 322 // Returns the exponent bits of this number. 323 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } 324 325 // Returns the fraction bits of this number. 326 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } 327 328 // Returns the sign bit of this number. 329 Bits sign_bit() const { return kSignBitMask & u_.bits_; } 330 331 // Returns true if and only if this is NAN (not a number). 332 bool is_nan() const { 333 // It's a NAN if the exponent bits are all ones and the fraction 334 // bits are not entirely zeros. 335 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); 336 } 337 338 // Returns true if and only if this number is at most kMaxUlps ULP's away 339 // from rhs. In particular, this function: 340 // 341 // - returns false if either number is (or both are) NAN. 342 // - treats really large numbers as almost equal to infinity. 343 // - thinks +0.0 and -0.0 are 0 DLP's apart. 344 bool AlmostEquals(const FloatingPoint& rhs) const { 345 // The IEEE standard says that any comparison operation involving 346 // a NAN must return false. 347 if (is_nan() || rhs.is_nan()) return false; 348 349 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) 350 <= kMaxUlps; 351 } 352 353 private: 354 // The data type used to store the actual floating-point number. 355 union FloatingPointUnion { 356 RawType value_; // The raw floating-point number. 357 Bits bits_; // The bits that represent the number. 358 }; 359 360 // Converts an integer from the sign-and-magnitude representation to 361 // the biased representation. More precisely, let N be 2 to the 362 // power of (kBitCount - 1), an integer x is represented by the 363 // unsigned number x + N. 364 // 365 // For instance, 366 // 367 // -N + 1 (the most negative number representable using 368 // sign-and-magnitude) is represented by 1; 369 // 0 is represented by N; and 370 // N - 1 (the biggest number representable using 371 // sign-and-magnitude) is represented by 2N - 1. 372 // 373 // Read http://en.wikipedia.org/wiki/Signed_number_representations 374 // for more details on signed number representations. 375 static Bits SignAndMagnitudeToBiased(const Bits &sam) { 376 if (kSignBitMask & sam) { 377 // sam represents a negative number. 378 return ~sam + 1; 379 } else { 380 // sam represents a positive number. 381 return kSignBitMask | sam; 382 } 383 } 384 385 // Given two numbers in the sign-and-magnitude representation, 386 // returns the distance between them as an unsigned number. 387 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, 388 const Bits &sam2) { 389 const Bits biased1 = SignAndMagnitudeToBiased(sam1); 390 const Bits biased2 = SignAndMagnitudeToBiased(sam2); 391 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); 392 } 393 394 FloatingPointUnion u_; 395 }; 396 397 // We cannot use std::numeric_limits<T>::max() as it clashes with the max() 398 // macro defined by <windows.h>. 399 template <> 400 inline float FloatingPoint<float>::Max() { return FLT_MAX; } 401 template <> 402 inline double FloatingPoint<double>::Max() { return DBL_MAX; } 403 404 // Typedefs the instances of the FloatingPoint template class that we 405 // care to use. 406 typedef FloatingPoint<float> Float; 407 typedef FloatingPoint<double> Double; 408 409 // In order to catch the mistake of putting tests that use different 410 // test fixture classes in the same test suite, we need to assign 411 // unique IDs to fixture classes and compare them. The TypeId type is 412 // used to hold such IDs. The user should treat TypeId as an opaque 413 // type: the only operation allowed on TypeId values is to compare 414 // them for equality using the == operator. 415 typedef const void* TypeId; 416 417 template <typename T> 418 class TypeIdHelper { 419 public: 420 // dummy_ must not have a const type. Otherwise an overly eager 421 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge 422 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization". 423 static bool dummy_; 424 }; 425 426 template <typename T> 427 bool TypeIdHelper<T>::dummy_ = false; 428 429 // GetTypeId<T>() returns the ID of type T. Different values will be 430 // returned for different types. Calling the function twice with the 431 // same type argument is guaranteed to return the same ID. 432 template <typename T> 433 TypeId GetTypeId() { 434 // The compiler is required to allocate a different 435 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate 436 // the template. Therefore, the address of dummy_ is guaranteed to 437 // be unique. 438 return &(TypeIdHelper<T>::dummy_); 439 } 440 441 // Returns the type ID of ::testing::Test. Always call this instead 442 // of GetTypeId< ::testing::Test>() to get the type ID of 443 // ::testing::Test, as the latter may give the wrong result due to a 444 // suspected linker bug when compiling Google Test as a Mac OS X 445 // framework. 446 GTEST_API_ TypeId GetTestTypeId(); 447 448 // Defines the abstract factory interface that creates instances 449 // of a Test object. 450 class TestFactoryBase { 451 public: 452 virtual ~TestFactoryBase() {} 453 454 // Creates a test instance to run. The instance is both created and destroyed 455 // within TestInfoImpl::Run() 456 virtual Test* CreateTest() = 0; 457 458 protected: 459 TestFactoryBase() {} 460 461 private: 462 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); 463 }; 464 465 // This class provides implementation of TeastFactoryBase interface. 466 // It is used in TEST and TEST_F macros. 467 template <class TestClass> 468 class TestFactoryImpl : public TestFactoryBase { 469 public: 470 Test* CreateTest() override { return new TestClass; } 471 }; 472 473 #if GTEST_OS_WINDOWS 474 475 // Predicate-formatters for implementing the HRESULT checking macros 476 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} 477 // We pass a long instead of HRESULT to avoid causing an 478 // include dependency for the HRESULT type. 479 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, 480 long hr); // NOLINT 481 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, 482 long hr); // NOLINT 483 484 #endif // GTEST_OS_WINDOWS 485 486 // Types of SetUpTestSuite() and TearDownTestSuite() functions. 487 using SetUpTestSuiteFunc = void (*)(); 488 using TearDownTestSuiteFunc = void (*)(); 489 490 struct CodeLocation { 491 CodeLocation(const std::string& a_file, int a_line) 492 : file(a_file), line(a_line) {} 493 494 std::string file; 495 int line; 496 }; 497 498 // Helper to identify which setup function for TestCase / TestSuite to call. 499 // Only one function is allowed, either TestCase or TestSute but not both. 500 501 // Utility functions to help SuiteApiResolver 502 using SetUpTearDownSuiteFuncType = void (*)(); 503 504 inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull( 505 SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) { 506 return a == def ? nullptr : a; 507 } 508 509 template <typename T> 510 // Note that SuiteApiResolver inherits from T because 511 // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way 512 // SuiteApiResolver can access them. 513 struct SuiteApiResolver : T { 514 // testing::Test is only forward declared at this point. So we make it a 515 // dependend class for the compiler to be OK with it. 516 using Test = 517 typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type; 518 519 static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename, 520 int line_num) { 521 SetUpTearDownSuiteFuncType test_case_fp = 522 GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase); 523 SetUpTearDownSuiteFuncType test_suite_fp = 524 GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite); 525 526 GTEST_CHECK_(!test_case_fp || !test_suite_fp) 527 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please " 528 "make sure there is only one present at " 529 << filename << ":" << line_num; 530 531 return test_case_fp != nullptr ? test_case_fp : test_suite_fp; 532 } 533 534 static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename, 535 int line_num) { 536 SetUpTearDownSuiteFuncType test_case_fp = 537 GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase); 538 SetUpTearDownSuiteFuncType test_suite_fp = 539 GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite); 540 541 GTEST_CHECK_(!test_case_fp || !test_suite_fp) 542 << "Test can not provide both TearDownTestSuite and TearDownTestCase," 543 " please make sure there is only one present at" 544 << filename << ":" << line_num; 545 546 return test_case_fp != nullptr ? test_case_fp : test_suite_fp; 547 } 548 }; 549 550 // Creates a new TestInfo object and registers it with Google Test; 551 // returns the created object. 552 // 553 // Arguments: 554 // 555 // test_suite_name: name of the test suite 556 // name: name of the test 557 // type_param the name of the test's type parameter, or NULL if 558 // this is not a typed or a type-parameterized test. 559 // value_param text representation of the test's value parameter, 560 // or NULL if this is not a type-parameterized test. 561 // code_location: code location where the test is defined 562 // fixture_class_id: ID of the test fixture class 563 // set_up_tc: pointer to the function that sets up the test suite 564 // tear_down_tc: pointer to the function that tears down the test suite 565 // factory: pointer to the factory that creates a test object. 566 // The newly created TestInfo instance will assume 567 // ownership of the factory object. 568 GTEST_API_ TestInfo* MakeAndRegisterTestInfo( 569 const char* test_suite_name, const char* name, const char* type_param, 570 const char* value_param, CodeLocation code_location, 571 TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, 572 TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory); 573 574 // If *pstr starts with the given prefix, modifies *pstr to be right 575 // past the prefix and returns true; otherwise leaves *pstr unchanged 576 // and returns false. None of pstr, *pstr, and prefix can be NULL. 577 GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); 578 579 #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P 580 581 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ 582 /* class A needs to have dll-interface to be used by clients of class B */) 583 584 // State of the definition of a type-parameterized test suite. 585 class GTEST_API_ TypedTestSuitePState { 586 public: 587 TypedTestSuitePState() : registered_(false) {} 588 589 // Adds the given test name to defined_test_names_ and return true 590 // if the test suite hasn't been registered; otherwise aborts the 591 // program. 592 bool AddTestName(const char* file, int line, const char* case_name, 593 const char* test_name) { 594 if (registered_) { 595 fprintf(stderr, 596 "%s Test %s must be defined before " 597 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n", 598 FormatFileLocation(file, line).c_str(), test_name, case_name); 599 fflush(stderr); 600 posix::Abort(); 601 } 602 registered_tests_.insert( 603 ::std::make_pair(test_name, CodeLocation(file, line))); 604 return true; 605 } 606 607 bool TestExists(const std::string& test_name) const { 608 return registered_tests_.count(test_name) > 0; 609 } 610 611 const CodeLocation& GetCodeLocation(const std::string& test_name) const { 612 RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name); 613 GTEST_CHECK_(it != registered_tests_.end()); 614 return it->second; 615 } 616 617 // Verifies that registered_tests match the test names in 618 // defined_test_names_; returns registered_tests if successful, or 619 // aborts the program otherwise. 620 const char* VerifyRegisteredTestNames(const char* test_suite_name, 621 const char* file, int line, 622 const char* registered_tests); 623 624 private: 625 typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap; 626 627 bool registered_; 628 RegisteredTestsMap registered_tests_; 629 }; 630 631 // Legacy API is deprecated but still available 632 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 633 using TypedTestCasePState = TypedTestSuitePState; 634 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ 635 636 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 637 638 // Skips to the first non-space char after the first comma in 'str'; 639 // returns NULL if no comma is found in 'str'. 640 inline const char* SkipComma(const char* str) { 641 const char* comma = strchr(str, ','); 642 if (comma == nullptr) { 643 return nullptr; 644 } 645 while (IsSpace(*(++comma))) {} 646 return comma; 647 } 648 649 // Returns the prefix of 'str' before the first comma in it; returns 650 // the entire string if it contains no comma. 651 inline std::string GetPrefixUntilComma(const char* str) { 652 const char* comma = strchr(str, ','); 653 return comma == nullptr ? str : std::string(str, comma); 654 } 655 656 // Splits a given string on a given delimiter, populating a given 657 // vector with the fields. 658 void SplitString(const ::std::string& str, char delimiter, 659 ::std::vector< ::std::string>* dest); 660 661 // The default argument to the template below for the case when the user does 662 // not provide a name generator. 663 struct DefaultNameGenerator { 664 template <typename T> 665 static std::string GetName(int i) { 666 return StreamableToString(i); 667 } 668 }; 669 670 template <typename Provided = DefaultNameGenerator> 671 struct NameGeneratorSelector { 672 typedef Provided type; 673 }; 674 675 template <typename NameGenerator> 676 void GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {} 677 678 template <typename NameGenerator, typename Types> 679 void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) { 680 result->push_back(NameGenerator::template GetName<typename Types::Head>(i)); 681 GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result, 682 i + 1); 683 } 684 685 template <typename NameGenerator, typename Types> 686 std::vector<std::string> GenerateNames() { 687 std::vector<std::string> result; 688 GenerateNamesRecursively<NameGenerator>(Types(), &result, 0); 689 return result; 690 } 691 692 // TypeParameterizedTest<Fixture, TestSel, Types>::Register() 693 // registers a list of type-parameterized tests with Google Test. The 694 // return value is insignificant - we just need to return something 695 // such that we can call this function in a namespace scope. 696 // 697 // Implementation note: The GTEST_TEMPLATE_ macro declares a template 698 // template parameter. It's defined in gtest-type-util.h. 699 template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types> 700 class TypeParameterizedTest { 701 public: 702 // 'index' is the index of the test in the type list 'Types' 703 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite, 704 // Types). Valid values for 'index' are [0, N - 1] where N is the 705 // length of Types. 706 static bool Register(const char* prefix, const CodeLocation& code_location, 707 const char* case_name, const char* test_names, int index, 708 const std::vector<std::string>& type_names = 709 GenerateNames<DefaultNameGenerator, Types>()) { 710 typedef typename Types::Head Type; 711 typedef Fixture<Type> FixtureClass; 712 typedef typename GTEST_BIND_(TestSel, Type) TestClass; 713 714 // First, registers the first type-parameterized test in the type 715 // list. 716 MakeAndRegisterTestInfo( 717 (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + 718 "/" + type_names[static_cast<size_t>(index)]) 719 .c_str(), 720 StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), 721 GetTypeName<Type>().c_str(), 722 nullptr, // No value parameter. 723 code_location, GetTypeId<FixtureClass>(), 724 SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite( 725 code_location.file.c_str(), code_location.line), 726 SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite( 727 code_location.file.c_str(), code_location.line), 728 new TestFactoryImpl<TestClass>); 729 730 // Next, recurses (at compile time) with the tail of the type list. 731 return TypeParameterizedTest<Fixture, TestSel, 732 typename Types::Tail>::Register(prefix, 733 code_location, 734 case_name, 735 test_names, 736 index + 1, 737 type_names); 738 } 739 }; 740 741 // The base case for the compile time recursion. 742 template <GTEST_TEMPLATE_ Fixture, class TestSel> 743 class TypeParameterizedTest<Fixture, TestSel, internal::None> { 744 public: 745 static bool Register(const char* /*prefix*/, const CodeLocation&, 746 const char* /*case_name*/, const char* /*test_names*/, 747 int /*index*/, 748 const std::vector<std::string>& = 749 std::vector<std::string>() /*type_names*/) { 750 return true; 751 } 752 }; 753 754 GTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name, 755 CodeLocation code_location); 756 GTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation( 757 const char* case_name); 758 759 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register() 760 // registers *all combinations* of 'Tests' and 'Types' with Google 761 // Test. The return value is insignificant - we just need to return 762 // something such that we can call this function in a namespace scope. 763 template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types> 764 class TypeParameterizedTestSuite { 765 public: 766 static bool Register(const char* prefix, CodeLocation code_location, 767 const TypedTestSuitePState* state, const char* case_name, 768 const char* test_names, 769 const std::vector<std::string>& type_names = 770 GenerateNames<DefaultNameGenerator, Types>()) { 771 RegisterTypeParameterizedTestSuiteInstantiation(case_name); 772 std::string test_name = StripTrailingSpaces( 773 GetPrefixUntilComma(test_names)); 774 if (!state->TestExists(test_name)) { 775 fprintf(stderr, "Failed to get code location for test %s.%s at %s.", 776 case_name, test_name.c_str(), 777 FormatFileLocation(code_location.file.c_str(), 778 code_location.line).c_str()); 779 fflush(stderr); 780 posix::Abort(); 781 } 782 const CodeLocation& test_location = state->GetCodeLocation(test_name); 783 784 typedef typename Tests::Head Head; 785 786 // First, register the first test in 'Test' for each type in 'Types'. 787 TypeParameterizedTest<Fixture, Head, Types>::Register( 788 prefix, test_location, case_name, test_names, 0, type_names); 789 790 // Next, recurses (at compile time) with the tail of the test list. 791 return TypeParameterizedTestSuite<Fixture, typename Tests::Tail, 792 Types>::Register(prefix, code_location, 793 state, case_name, 794 SkipComma(test_names), 795 type_names); 796 } 797 }; 798 799 // The base case for the compile time recursion. 800 template <GTEST_TEMPLATE_ Fixture, typename Types> 801 class TypeParameterizedTestSuite<Fixture, internal::None, Types> { 802 public: 803 static bool Register(const char* /*prefix*/, const CodeLocation&, 804 const TypedTestSuitePState* /*state*/, 805 const char* /*case_name*/, const char* /*test_names*/, 806 const std::vector<std::string>& = 807 std::vector<std::string>() /*type_names*/) { 808 return true; 809 } 810 }; 811 812 #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P 813 814 // Returns the current OS stack trace as an std::string. 815 // 816 // The maximum number of stack frames to be included is specified by 817 // the gtest_stack_trace_depth flag. The skip_count parameter 818 // specifies the number of top frames to be skipped, which doesn't 819 // count against the number of frames to be included. 820 // 821 // For example, if Foo() calls Bar(), which in turn calls 822 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in 823 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. 824 GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( 825 UnitTest* unit_test, int skip_count); 826 827 // Helpers for suppressing warnings on unreachable code or constant 828 // condition. 829 830 // Always returns true. 831 GTEST_API_ bool AlwaysTrue(); 832 833 // Always returns false. 834 inline bool AlwaysFalse() { return !AlwaysTrue(); } 835 836 // Helper for suppressing false warning from Clang on a const char* 837 // variable declared in a conditional expression always being NULL in 838 // the else branch. 839 struct GTEST_API_ ConstCharPtr { 840 ConstCharPtr(const char* str) : value(str) {} 841 operator bool() const { return true; } 842 const char* value; 843 }; 844 845 // Helper for declaring std::string within 'if' statement 846 // in pre C++17 build environment. 847 struct TrueWithString { 848 TrueWithString() = default; 849 explicit TrueWithString(const char* str) : value(str) {} 850 explicit TrueWithString(const std::string& str) : value(str) {} 851 explicit operator bool() const { return true; } 852 std::string value; 853 }; 854 855 // A simple Linear Congruential Generator for generating random 856 // numbers with a uniform distribution. Unlike rand() and srand(), it 857 // doesn't use global state (and therefore can't interfere with user 858 // code). Unlike rand_r(), it's portable. An LCG isn't very random, 859 // but it's good enough for our purposes. 860 class GTEST_API_ Random { 861 public: 862 static const uint32_t kMaxRange = 1u << 31; 863 864 explicit Random(uint32_t seed) : state_(seed) {} 865 866 void Reseed(uint32_t seed) { state_ = seed; } 867 868 // Generates a random number from [0, range). Crashes if 'range' is 869 // 0 or greater than kMaxRange. 870 uint32_t Generate(uint32_t range); 871 872 private: 873 uint32_t state_; 874 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); 875 }; 876 877 // Turns const U&, U&, const U, and U all into U. 878 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ 879 typename std::remove_const<typename std::remove_reference<T>::type>::type 880 881 // IsAProtocolMessage<T>::value is a compile-time bool constant that's 882 // true if and only if T is type proto2::Message or a subclass of it. 883 template <typename T> 884 struct IsAProtocolMessage 885 : public std::is_convertible<const T*, const ::proto2::Message*> {}; 886 887 // When the compiler sees expression IsContainerTest<C>(0), if C is an 888 // STL-style container class, the first overload of IsContainerTest 889 // will be viable (since both C::iterator* and C::const_iterator* are 890 // valid types and NULL can be implicitly converted to them). It will 891 // be picked over the second overload as 'int' is a perfect match for 892 // the type of argument 0. If C::iterator or C::const_iterator is not 893 // a valid type, the first overload is not viable, and the second 894 // overload will be picked. Therefore, we can determine whether C is 895 // a container class by checking the type of IsContainerTest<C>(0). 896 // The value of the expression is insignificant. 897 // 898 // In C++11 mode we check the existence of a const_iterator and that an 899 // iterator is properly implemented for the container. 900 // 901 // For pre-C++11 that we look for both C::iterator and C::const_iterator. 902 // The reason is that C++ injects the name of a class as a member of the 903 // class itself (e.g. you can refer to class iterator as either 904 // 'iterator' or 'iterator::iterator'). If we look for C::iterator 905 // only, for example, we would mistakenly think that a class named 906 // iterator is an STL container. 907 // 908 // Also note that the simpler approach of overloading 909 // IsContainerTest(typename C::const_iterator*) and 910 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. 911 typedef int IsContainer; 912 template <class C, 913 class Iterator = decltype(::std::declval<const C&>().begin()), 914 class = decltype(::std::declval<const C&>().end()), 915 class = decltype(++::std::declval<Iterator&>()), 916 class = decltype(*::std::declval<Iterator>()), 917 class = typename C::const_iterator> 918 IsContainer IsContainerTest(int /* dummy */) { 919 return 0; 920 } 921 922 typedef char IsNotContainer; 923 template <class C> 924 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } 925 926 // Trait to detect whether a type T is a hash table. 927 // The heuristic used is that the type contains an inner type `hasher` and does 928 // not contain an inner type `reverse_iterator`. 929 // If the container is iterable in reverse, then order might actually matter. 930 template <typename T> 931 struct IsHashTable { 932 private: 933 template <typename U> 934 static char test(typename U::hasher*, typename U::reverse_iterator*); 935 template <typename U> 936 static int test(typename U::hasher*, ...); 937 template <typename U> 938 static char test(...); 939 940 public: 941 static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int); 942 }; 943 944 template <typename T> 945 const bool IsHashTable<T>::value; 946 947 template <typename C, 948 bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)> 949 struct IsRecursiveContainerImpl; 950 951 template <typename C> 952 struct IsRecursiveContainerImpl<C, false> : public std::false_type {}; 953 954 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to 955 // obey the same inconsistencies as the IsContainerTest, namely check if 956 // something is a container is relying on only const_iterator in C++11 and 957 // is relying on both const_iterator and iterator otherwise 958 template <typename C> 959 struct IsRecursiveContainerImpl<C, true> { 960 using value_type = decltype(*std::declval<typename C::const_iterator>()); 961 using type = 962 std::is_same<typename std::remove_const< 963 typename std::remove_reference<value_type>::type>::type, 964 C>; 965 }; 966 967 // IsRecursiveContainer<Type> is a unary compile-time predicate that 968 // evaluates whether C is a recursive container type. A recursive container 969 // type is a container type whose value_type is equal to the container type 970 // itself. An example for a recursive container type is 971 // boost::filesystem::path, whose iterator has a value_type that is equal to 972 // boost::filesystem::path. 973 template <typename C> 974 struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {}; 975 976 // Utilities for native arrays. 977 978 // ArrayEq() compares two k-dimensional native arrays using the 979 // elements' operator==, where k can be any integer >= 0. When k is 980 // 0, ArrayEq() degenerates into comparing a single pair of values. 981 982 template <typename T, typename U> 983 bool ArrayEq(const T* lhs, size_t size, const U* rhs); 984 985 // This generic version is used when k is 0. 986 template <typename T, typename U> 987 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } 988 989 // This overload is used when k >= 1. 990 template <typename T, typename U, size_t N> 991 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { 992 return internal::ArrayEq(lhs, N, rhs); 993 } 994 995 // This helper reduces code bloat. If we instead put its logic inside 996 // the previous ArrayEq() function, arrays with different sizes would 997 // lead to different copies of the template code. 998 template <typename T, typename U> 999 bool ArrayEq(const T* lhs, size_t size, const U* rhs) { 1000 for (size_t i = 0; i != size; i++) { 1001 if (!internal::ArrayEq(lhs[i], rhs[i])) 1002 return false; 1003 } 1004 return true; 1005 } 1006 1007 // Finds the first element in the iterator range [begin, end) that 1008 // equals elem. Element may be a native array type itself. 1009 template <typename Iter, typename Element> 1010 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { 1011 for (Iter it = begin; it != end; ++it) { 1012 if (internal::ArrayEq(*it, elem)) 1013 return it; 1014 } 1015 return end; 1016 } 1017 1018 // CopyArray() copies a k-dimensional native array using the elements' 1019 // operator=, where k can be any integer >= 0. When k is 0, 1020 // CopyArray() degenerates into copying a single value. 1021 1022 template <typename T, typename U> 1023 void CopyArray(const T* from, size_t size, U* to); 1024 1025 // This generic version is used when k is 0. 1026 template <typename T, typename U> 1027 inline void CopyArray(const T& from, U* to) { *to = from; } 1028 1029 // This overload is used when k >= 1. 1030 template <typename T, typename U, size_t N> 1031 inline void CopyArray(const T(&from)[N], U(*to)[N]) { 1032 internal::CopyArray(from, N, *to); 1033 } 1034 1035 // This helper reduces code bloat. If we instead put its logic inside 1036 // the previous CopyArray() function, arrays with different sizes 1037 // would lead to different copies of the template code. 1038 template <typename T, typename U> 1039 void CopyArray(const T* from, size_t size, U* to) { 1040 for (size_t i = 0; i != size; i++) { 1041 internal::CopyArray(from[i], to + i); 1042 } 1043 } 1044 1045 // The relation between an NativeArray object (see below) and the 1046 // native array it represents. 1047 // We use 2 different structs to allow non-copyable types to be used, as long 1048 // as RelationToSourceReference() is passed. 1049 struct RelationToSourceReference {}; 1050 struct RelationToSourceCopy {}; 1051 1052 // Adapts a native array to a read-only STL-style container. Instead 1053 // of the complete STL container concept, this adaptor only implements 1054 // members useful for Google Mock's container matchers. New members 1055 // should be added as needed. To simplify the implementation, we only 1056 // support Element being a raw type (i.e. having no top-level const or 1057 // reference modifier). It's the client's responsibility to satisfy 1058 // this requirement. Element can be an array type itself (hence 1059 // multi-dimensional arrays are supported). 1060 template <typename Element> 1061 class NativeArray { 1062 public: 1063 // STL-style container typedefs. 1064 typedef Element value_type; 1065 typedef Element* iterator; 1066 typedef const Element* const_iterator; 1067 1068 // Constructs from a native array. References the source. 1069 NativeArray(const Element* array, size_t count, RelationToSourceReference) { 1070 InitRef(array, count); 1071 } 1072 1073 // Constructs from a native array. Copies the source. 1074 NativeArray(const Element* array, size_t count, RelationToSourceCopy) { 1075 InitCopy(array, count); 1076 } 1077 1078 // Copy constructor. 1079 NativeArray(const NativeArray& rhs) { 1080 (this->*rhs.clone_)(rhs.array_, rhs.size_); 1081 } 1082 1083 ~NativeArray() { 1084 if (clone_ != &NativeArray::InitRef) 1085 delete[] array_; 1086 } 1087 1088 // STL-style container methods. 1089 size_t size() const { return size_; } 1090 const_iterator begin() const { return array_; } 1091 const_iterator end() const { return array_ + size_; } 1092 bool operator==(const NativeArray& rhs) const { 1093 return size() == rhs.size() && 1094 ArrayEq(begin(), size(), rhs.begin()); 1095 } 1096 1097 private: 1098 static_assert(!std::is_const<Element>::value, "Type must not be const"); 1099 static_assert(!std::is_reference<Element>::value, 1100 "Type must not be a reference"); 1101 1102 // Initializes this object with a copy of the input. 1103 void InitCopy(const Element* array, size_t a_size) { 1104 Element* const copy = new Element[a_size]; 1105 CopyArray(array, a_size, copy); 1106 array_ = copy; 1107 size_ = a_size; 1108 clone_ = &NativeArray::InitCopy; 1109 } 1110 1111 // Initializes this object with a reference of the input. 1112 void InitRef(const Element* array, size_t a_size) { 1113 array_ = array; 1114 size_ = a_size; 1115 clone_ = &NativeArray::InitRef; 1116 } 1117 1118 const Element* array_; 1119 size_t size_; 1120 void (NativeArray::*clone_)(const Element*, size_t); 1121 1122 GTEST_DISALLOW_ASSIGN_(NativeArray); 1123 }; 1124 1125 // Backport of std::index_sequence. 1126 template <size_t... Is> 1127 struct IndexSequence { 1128 using type = IndexSequence; 1129 }; 1130 1131 // Double the IndexSequence, and one if plus_one is true. 1132 template <bool plus_one, typename T, size_t sizeofT> 1133 struct DoubleSequence; 1134 template <size_t... I, size_t sizeofT> 1135 struct DoubleSequence<true, IndexSequence<I...>, sizeofT> { 1136 using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>; 1137 }; 1138 template <size_t... I, size_t sizeofT> 1139 struct DoubleSequence<false, IndexSequence<I...>, sizeofT> { 1140 using type = IndexSequence<I..., (sizeofT + I)...>; 1141 }; 1142 1143 // Backport of std::make_index_sequence. 1144 // It uses O(ln(N)) instantiation depth. 1145 template <size_t N> 1146 struct MakeIndexSequence 1147 : DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type, 1148 N / 2>::type {}; 1149 1150 template <> 1151 struct MakeIndexSequence<0> : IndexSequence<> {}; 1152 1153 template <size_t> 1154 struct Ignore { 1155 Ignore(...); // NOLINT 1156 }; 1157 1158 template <typename> 1159 struct ElemFromListImpl; 1160 template <size_t... I> 1161 struct ElemFromListImpl<IndexSequence<I...>> { 1162 // We make Ignore a template to solve a problem with MSVC. 1163 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but 1164 // MSVC doesn't understand how to deal with that pack expansion. 1165 // Use `0 * I` to have a single instantiation of Ignore. 1166 template <typename R> 1167 static R Apply(Ignore<0 * I>..., R (*)(), ...); 1168 }; 1169 1170 template <size_t N, typename... T> 1171 struct ElemFromList { 1172 using type = 1173 decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply( 1174 static_cast<T (*)()>(nullptr)...)); 1175 }; 1176 1177 template <typename... T> 1178 class FlatTuple; 1179 1180 template <typename Derived, size_t I> 1181 struct FlatTupleElemBase; 1182 1183 template <typename... T, size_t I> 1184 struct FlatTupleElemBase<FlatTuple<T...>, I> { 1185 using value_type = typename ElemFromList<I, T...>::type; 1186 FlatTupleElemBase() = default; 1187 explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {} 1188 value_type value; 1189 }; 1190 1191 template <typename Derived, typename Idx> 1192 struct FlatTupleBase; 1193 1194 template <size_t... Idx, typename... T> 1195 struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>> 1196 : FlatTupleElemBase<FlatTuple<T...>, Idx>... { 1197 using Indices = IndexSequence<Idx...>; 1198 FlatTupleBase() = default; 1199 explicit FlatTupleBase(T... t) 1200 : FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {} 1201 }; 1202 1203 // Analog to std::tuple but with different tradeoffs. 1204 // This class minimizes the template instantiation depth, thus allowing more 1205 // elements than std::tuple would. std::tuple has been seen to require an 1206 // instantiation depth of more than 10x the number of elements in some 1207 // implementations. 1208 // FlatTuple and ElemFromList are not recursive and have a fixed depth 1209 // regardless of T... 1210 // MakeIndexSequence, on the other hand, it is recursive but with an 1211 // instantiation depth of O(ln(N)). 1212 template <typename... T> 1213 class FlatTuple 1214 : private FlatTupleBase<FlatTuple<T...>, 1215 typename MakeIndexSequence<sizeof...(T)>::type> { 1216 using Indices = typename FlatTupleBase< 1217 FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices; 1218 1219 public: 1220 FlatTuple() = default; 1221 explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {} 1222 1223 template <size_t I> 1224 const typename ElemFromList<I, T...>::type& Get() const { 1225 return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value; 1226 } 1227 1228 template <size_t I> 1229 typename ElemFromList<I, T...>::type& Get() { 1230 return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value; 1231 } 1232 }; 1233 1234 // Utility functions to be called with static_assert to induce deprecation 1235 // warnings. 1236 GTEST_INTERNAL_DEPRECATED( 1237 "INSTANTIATE_TEST_CASE_P is deprecated, please use " 1238 "INSTANTIATE_TEST_SUITE_P") 1239 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; } 1240 1241 GTEST_INTERNAL_DEPRECATED( 1242 "TYPED_TEST_CASE_P is deprecated, please use " 1243 "TYPED_TEST_SUITE_P") 1244 constexpr bool TypedTestCase_P_IsDeprecated() { return true; } 1245 1246 GTEST_INTERNAL_DEPRECATED( 1247 "TYPED_TEST_CASE is deprecated, please use " 1248 "TYPED_TEST_SUITE") 1249 constexpr bool TypedTestCaseIsDeprecated() { return true; } 1250 1251 GTEST_INTERNAL_DEPRECATED( 1252 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use " 1253 "REGISTER_TYPED_TEST_SUITE_P") 1254 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; } 1255 1256 GTEST_INTERNAL_DEPRECATED( 1257 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use " 1258 "INSTANTIATE_TYPED_TEST_SUITE_P") 1259 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } 1260 1261 } // namespace internal 1262 } // namespace testing 1263 1264 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \ 1265 ::testing::internal::AssertHelper(result_type, file, line, message) \ 1266 = ::testing::Message() 1267 1268 #define GTEST_MESSAGE_(message, result_type) \ 1269 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) 1270 1271 #define GTEST_FATAL_FAILURE_(message) \ 1272 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) 1273 1274 #define GTEST_NONFATAL_FAILURE_(message) \ 1275 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) 1276 1277 #define GTEST_SUCCESS_(message) \ 1278 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) 1279 1280 #define GTEST_SKIP_(message) \ 1281 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip) 1282 1283 // Suppress MSVC warning 4072 (unreachable code) for the code following 1284 // statement if it returns or throws (or doesn't return or throw in some 1285 // situations). 1286 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ 1287 if (::testing::internal::AlwaysTrue()) { statement; } 1288 1289 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \ 1290 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1291 if (::testing::internal::ConstCharPtr gtest_msg = "") { \ 1292 bool gtest_caught_expected = false; \ 1293 try { \ 1294 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1295 } \ 1296 catch (expected_exception const&) { \ 1297 gtest_caught_expected = true; \ 1298 } \ 1299 catch (...) { \ 1300 gtest_msg.value = \ 1301 "Expected: " #statement " throws an exception of type " \ 1302 #expected_exception ".\n Actual: it throws a different type."; \ 1303 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ 1304 } \ 1305 if (!gtest_caught_expected) { \ 1306 gtest_msg.value = \ 1307 "Expected: " #statement " throws an exception of type " \ 1308 #expected_exception ".\n Actual: it throws nothing."; \ 1309 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ 1310 } \ 1311 } else \ 1312 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ 1313 fail(gtest_msg.value) 1314 1315 #if GTEST_HAS_EXCEPTIONS 1316 1317 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ 1318 catch (std::exception const& e) { \ 1319 gtest_msg.value = ( \ 1320 "it throws std::exception-derived exception with description: \"" \ 1321 ); \ 1322 gtest_msg.value += e.what(); \ 1323 gtest_msg.value += "\"."; \ 1324 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ 1325 } 1326 1327 #else // GTEST_HAS_EXCEPTIONS 1328 1329 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() 1330 1331 #endif // GTEST_HAS_EXCEPTIONS 1332 1333 #define GTEST_TEST_NO_THROW_(statement, fail) \ 1334 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1335 if (::testing::internal::TrueWithString gtest_msg{}) { \ 1336 try { \ 1337 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1338 } \ 1339 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \ 1340 catch (...) { \ 1341 gtest_msg.value = "it throws."; \ 1342 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ 1343 } \ 1344 } else \ 1345 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ 1346 fail(("Expected: " #statement " doesn't throw an exception.\n" \ 1347 " Actual: " + gtest_msg.value).c_str()) 1348 1349 #define GTEST_TEST_ANY_THROW_(statement, fail) \ 1350 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1351 if (::testing::internal::AlwaysTrue()) { \ 1352 bool gtest_caught_any = false; \ 1353 try { \ 1354 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1355 } \ 1356 catch (...) { \ 1357 gtest_caught_any = true; \ 1358 } \ 1359 if (!gtest_caught_any) { \ 1360 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ 1361 } \ 1362 } else \ 1363 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ 1364 fail("Expected: " #statement " throws an exception.\n" \ 1365 " Actual: it doesn't.") 1366 1367 1368 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be 1369 // either a boolean expression or an AssertionResult. text is a textual 1370 // represenation of expression as it was passed into the EXPECT_TRUE. 1371 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ 1372 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1373 if (const ::testing::AssertionResult gtest_ar_ = \ 1374 ::testing::AssertionResult(expression)) \ 1375 ; \ 1376 else \ 1377 fail(::testing::internal::GetBoolAssertionFailureMessage(\ 1378 gtest_ar_, text, #actual, #expected).c_str()) 1379 1380 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ 1381 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1382 if (::testing::internal::AlwaysTrue()) { \ 1383 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ 1384 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1385 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ 1386 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ 1387 } \ 1388 } else \ 1389 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ 1390 fail("Expected: " #statement " doesn't generate new fatal " \ 1391 "failures in the current thread.\n" \ 1392 " Actual: it does.") 1393 1394 // Expands to the name of the class that implements the given test. 1395 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ 1396 test_suite_name##_##test_name##_Test 1397 1398 // Helper macro for defining tests. 1399 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \ 1400 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ 1401 "test_suite_name must not be empty"); \ 1402 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \ 1403 "test_name must not be empty"); \ 1404 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ 1405 : public parent_class { \ 1406 public: \ 1407 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ 1408 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \ 1409 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ 1410 test_name)); \ 1411 GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ 1412 test_name)); \ 1413 \ 1414 private: \ 1415 void TestBody() override; \ 1416 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ 1417 }; \ 1418 \ 1419 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ 1420 test_name)::test_info_ = \ 1421 ::testing::internal::MakeAndRegisterTestInfo( \ 1422 #test_suite_name, #test_name, nullptr, nullptr, \ 1423 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \ 1424 ::testing::internal::SuiteApiResolver< \ 1425 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \ 1426 ::testing::internal::SuiteApiResolver< \ 1427 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \ 1428 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \ 1429 test_suite_name, test_name)>); \ 1430 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() 1431 1432 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_