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 // Authors: wan (at) google.com (Zhanyong Wan), eefacm (at) gmail.com (Sean Mcafee) 31 // 32 // The Google C++ Testing Framework (Google Test) 33 // 34 // This header file declares functions and macros used internally by 35 // Google Test. They are subject to change without notice. 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 #include <ctype.h> 50 #include <string.h> 51 #include <iomanip> 52 #include <limits> 53 #include <set> 54 55 #include "gtest/internal/gtest-string.h" 56 #include "gtest/internal/gtest-filepath.h" 57 #include "gtest/internal/gtest-type-util.h" 58 59 #include "llvm/Support/raw_os_ostream.h" 60 61 // Due to C++ preprocessor weirdness, we need double indirection to 62 // concatenate two tokens when one of them is __LINE__. Writing 63 // 64 // foo ## __LINE__ 65 // 66 // will result in the token foo__LINE__, instead of foo followed by 67 // the current line number. For more details, see 68 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 69 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) 70 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar 71 72 // Google Test defines the testing::Message class to allow construction of 73 // test messages via the << operator. The idea is that anything 74 // streamable to std::ostream can be streamed to a testing::Message. 75 // This allows a user to use his own types in Google Test assertions by 76 // overloading the << operator. 77 // 78 // util/gtl/stl_logging-inl.h overloads << for STL containers. These 79 // overloads cannot be defined in the std namespace, as that will be 80 // undefined behavior. Therefore, they are defined in the global 81 // namespace instead. 82 // 83 // C++'s symbol lookup rule (i.e. Koenig lookup) says that these 84 // overloads are visible in either the std namespace or the global 85 // namespace, but not other namespaces, including the testing 86 // namespace which Google Test's Message class is in. 87 // 88 // To allow STL containers (and other types that has a << operator 89 // defined in the global namespace) to be used in Google Test assertions, 90 // testing::Message must access the custom << operator from the global 91 // namespace. Hence this helper function. 92 // 93 // Note: Jeffrey Yasskin suggested an alternative fix by "using 94 // ::operator<<;" in the definition of Message's operator<<. That fix 95 // doesn't require a helper function, but unfortunately doesn't 96 // compile with MSVC. 97 98 // LLVM INTERNAL CHANGE: To allow operator<< to work with both 99 // std::ostreams and LLVM's raw_ostreams, we define a special 100 // std::ostream with an implicit conversion to raw_ostream& and stream 101 // to that. This causes the compiler to prefer std::ostream overloads 102 // but still find raw_ostream& overloads. 103 namespace llvm { 104 class convertible_fwd_ostream : public std::ostream { 105 std::ostream& os_; 106 raw_os_ostream ros_; 107 108 public: 109 convertible_fwd_ostream(std::ostream& os) 110 : std::ostream(os.rdbuf()), os_(os), ros_(*this) {} 111 operator raw_ostream&() { return ros_; } 112 }; 113 } 114 template <typename T> 115 inline void GTestStreamToHelper(std::ostream* os, const T& val) { 116 llvm::convertible_fwd_ostream cos(*os); 117 cos << val; 118 } 119 120 class ProtocolMessage; 121 namespace proto2 { class Message; } 122 123 namespace testing { 124 125 // Forward declarations. 126 127 class AssertionResult; // Result of an assertion. 128 class Message; // Represents a failure message. 129 class Test; // Represents a test. 130 class TestInfo; // Information about a test. 131 class TestPartResult; // Result of a test part. 132 class UnitTest; // A collection of test cases. 133 134 template <typename T> 135 ::std::string PrintToString(const T& value); 136 137 namespace internal { 138 139 struct TraceInfo; // Information about a trace point. 140 class ScopedTrace; // Implements scoped trace. 141 class TestInfoImpl; // Opaque implementation of TestInfo 142 class UnitTestImpl; // Opaque implementation of UnitTest 143 144 // How many times InitGoogleTest() has been called. 145 extern int g_init_gtest_count; 146 147 // The text used in failure messages to indicate the start of the 148 // stack trace. 149 GTEST_API_ extern const char kStackTraceMarker[]; 150 151 // A secret type that Google Test users don't know about. It has no 152 // definition on purpose. Therefore it's impossible to create a 153 // Secret object, which is what we want. 154 class Secret; 155 156 // Two overloaded helpers for checking at compile time whether an 157 // expression is a null pointer literal (i.e. NULL or any 0-valued 158 // compile-time integral constant). Their return values have 159 // different sizes, so we can use sizeof() to test which version is 160 // picked by the compiler. These helpers have no implementations, as 161 // we only need their signatures. 162 // 163 // Given IsNullLiteralHelper(x), the compiler will pick the first 164 // version if x can be implicitly converted to Secret*, and pick the 165 // second version otherwise. Since Secret is a secret and incomplete 166 // type, the only expression a user can write that has type Secret* is 167 // a null pointer literal. Therefore, we know that x is a null 168 // pointer literal if and only if the first version is picked by the 169 // compiler. 170 char IsNullLiteralHelper(Secret* p); 171 char (&IsNullLiteralHelper(...))[2]; // NOLINT 172 173 // A compile-time bool constant that is true if and only if x is a 174 // null pointer literal (i.e. NULL or any 0-valued compile-time 175 // integral constant). 176 #ifdef GTEST_ELLIPSIS_NEEDS_POD_ 177 // We lose support for NULL detection where the compiler doesn't like 178 // passing non-POD classes through ellipsis (...). 179 # define GTEST_IS_NULL_LITERAL_(x) false 180 #else 181 # define GTEST_IS_NULL_LITERAL_(x) \ 182 (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) 183 #endif // GTEST_ELLIPSIS_NEEDS_POD_ 184 185 // Appends the user-supplied message to the Google-Test-generated message. 186 GTEST_API_ String AppendUserMessage(const String& gtest_msg, 187 const Message& user_msg); 188 189 // A helper class for creating scoped traces in user programs. 190 class GTEST_API_ ScopedTrace { 191 public: 192 // The c'tor pushes the given source file location and message onto 193 // a trace stack maintained by Google Test. 194 ScopedTrace(const char* file, int line, const Message& message); 195 196 // The d'tor pops the info pushed by the c'tor. 197 // 198 // Note that the d'tor is not virtual in order to be efficient. 199 // Don't inherit from ScopedTrace! 200 ~ScopedTrace(); 201 202 private: 203 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); 204 } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its 205 // c'tor and d'tor. Therefore it doesn't 206 // need to be used otherwise. 207 208 // Converts a streamable value to a String. A NULL pointer is 209 // converted to "(null)". When the input value is a ::string, 210 // ::std::string, ::wstring, or ::std::wstring object, each NUL 211 // character in it is replaced with "\\0". 212 // Declared here but defined in gtest.h, so that it has access 213 // to the definition of the Message class, required by the ARM 214 // compiler. 215 template <typename T> 216 String StreamableToString(const T& streamable); 217 218 // The Symbian compiler has a bug that prevents it from selecting the 219 // correct overload of FormatForComparisonFailureMessage (see below) 220 // unless we pass the first argument by reference. If we do that, 221 // however, Visual Age C++ 10.1 generates a compiler error. Therefore 222 // we only apply the work-around for Symbian. 223 #if defined(__SYMBIAN32__) 224 # define GTEST_CREF_WORKAROUND_ const& 225 #else 226 # define GTEST_CREF_WORKAROUND_ 227 #endif 228 229 // When this operand is a const char* or char*, if the other operand 230 // is a ::std::string or ::string, we print this operand as a C string 231 // rather than a pointer (we do the same for wide strings); otherwise 232 // we print it as a pointer to be safe. 233 234 // This internal macro is used to avoid duplicated code. 235 #define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\ 236 inline String FormatForComparisonFailureMessage(\ 237 operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ 238 const operand2_type& /*operand2*/) {\ 239 return operand1_printer(str);\ 240 }\ 241 inline String FormatForComparisonFailureMessage(\ 242 const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \ 243 const operand2_type& /*operand2*/) {\ 244 return operand1_printer(str);\ 245 } 246 247 GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted) 248 #if GTEST_HAS_STD_WSTRING 249 GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted) 250 #endif // GTEST_HAS_STD_WSTRING 251 252 #if GTEST_HAS_GLOBAL_STRING 253 GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted) 254 #endif // GTEST_HAS_GLOBAL_STRING 255 #if GTEST_HAS_GLOBAL_WSTRING 256 GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted) 257 #endif // GTEST_HAS_GLOBAL_WSTRING 258 259 #undef GTEST_FORMAT_IMPL_ 260 261 // The next four overloads handle the case where the operand being 262 // printed is a char/wchar_t pointer and the other operand is not a 263 // string/wstring object. In such cases, we just print the operand as 264 // a pointer to be safe. 265 #define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \ 266 template <typename T> \ 267 String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \ 268 const T&) { \ 269 return PrintToString(static_cast<const void*>(p)); \ 270 } 271 272 GTEST_FORMAT_CHAR_PTR_IMPL_(char) 273 GTEST_FORMAT_CHAR_PTR_IMPL_(const char) 274 GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t) 275 GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t) 276 277 #undef GTEST_FORMAT_CHAR_PTR_IMPL_ 278 279 // Constructs and returns the message for an equality assertion 280 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. 281 // 282 // The first four parameters are the expressions used in the assertion 283 // and their values, as strings. For example, for ASSERT_EQ(foo, bar) 284 // where foo is 5 and bar is 6, we have: 285 // 286 // expected_expression: "foo" 287 // actual_expression: "bar" 288 // expected_value: "5" 289 // actual_value: "6" 290 // 291 // The ignoring_case parameter is true iff the assertion is a 292 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will 293 // be inserted into the message. 294 GTEST_API_ AssertionResult EqFailure(const char* expected_expression, 295 const char* actual_expression, 296 const String& expected_value, 297 const String& actual_value, 298 bool ignoring_case); 299 300 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. 301 GTEST_API_ String GetBoolAssertionFailureMessage( 302 const AssertionResult& assertion_result, 303 const char* expression_text, 304 const char* actual_predicate_value, 305 const char* expected_predicate_value); 306 307 // This template class represents an IEEE floating-point number 308 // (either single-precision or double-precision, depending on the 309 // template parameters). 310 // 311 // The purpose of this class is to do more sophisticated number 312 // comparison. (Due to round-off error, etc, it's very unlikely that 313 // two floating-points will be equal exactly. Hence a naive 314 // comparison by the == operation often doesn't work.) 315 // 316 // Format of IEEE floating-point: 317 // 318 // The most-significant bit being the leftmost, an IEEE 319 // floating-point looks like 320 // 321 // sign_bit exponent_bits fraction_bits 322 // 323 // Here, sign_bit is a single bit that designates the sign of the 324 // number. 325 // 326 // For float, there are 8 exponent bits and 23 fraction bits. 327 // 328 // For double, there are 11 exponent bits and 52 fraction bits. 329 // 330 // More details can be found at 331 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard. 332 // 333 // Template parameter: 334 // 335 // RawType: the raw floating-point type (either float or double) 336 template <typename RawType> 337 class FloatingPoint { 338 public: 339 // Defines the unsigned integer type that has the same size as the 340 // floating point number. 341 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits; 342 343 // Constants. 344 345 // # of bits in a number. 346 static const size_t kBitCount = 8*sizeof(RawType); 347 348 // # of fraction bits in a number. 349 static const size_t kFractionBitCount = 350 std::numeric_limits<RawType>::digits - 1; 351 352 // # of exponent bits in a number. 353 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; 354 355 // The mask for the sign bit. 356 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1); 357 358 // The mask for the fraction bits. 359 static const Bits kFractionBitMask = 360 ~static_cast<Bits>(0) >> (kExponentBitCount + 1); 361 362 // The mask for the exponent bits. 363 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); 364 365 // How many ULP's (Units in the Last Place) we want to tolerate when 366 // comparing two numbers. The larger the value, the more error we 367 // allow. A 0 value means that two numbers must be exactly the same 368 // to be considered equal. 369 // 370 // The maximum error of a single floating-point operation is 0.5 371 // units in the last place. On Intel CPU's, all floating-point 372 // calculations are done with 80-bit precision, while double has 64 373 // bits. Therefore, 4 should be enough for ordinary use. 374 // 375 // See the following article for more details on ULP: 376 // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. 377 static const size_t kMaxUlps = 4; 378 379 // Constructs a FloatingPoint from a raw floating-point number. 380 // 381 // On an Intel CPU, passing a non-normalized NAN (Not a Number) 382 // around may change its bits, although the new value is guaranteed 383 // to be also a NAN. Therefore, don't expect this constructor to 384 // preserve the bits in x when x is a NAN. 385 explicit FloatingPoint(const RawType& x) { u_.value_ = x; } 386 387 // Static methods 388 389 // Reinterprets a bit pattern as a floating-point number. 390 // 391 // This function is needed to test the AlmostEquals() method. 392 static RawType ReinterpretBits(const Bits bits) { 393 FloatingPoint fp(0); 394 fp.u_.bits_ = bits; 395 return fp.u_.value_; 396 } 397 398 // Returns the floating-point number that represent positive infinity. 399 static RawType Infinity() { 400 return ReinterpretBits(kExponentBitMask); 401 } 402 403 // Non-static methods 404 405 // Returns the bits that represents this number. 406 const Bits &bits() const { return u_.bits_; } 407 408 // Returns the exponent bits of this number. 409 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } 410 411 // Returns the fraction bits of this number. 412 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } 413 414 // Returns the sign bit of this number. 415 Bits sign_bit() const { return kSignBitMask & u_.bits_; } 416 417 // Returns true iff this is NAN (not a number). 418 bool is_nan() const { 419 // It's a NAN if the exponent bits are all ones and the fraction 420 // bits are not entirely zeros. 421 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); 422 } 423 424 // Returns true iff this number is at most kMaxUlps ULP's away from 425 // rhs. In particular, this function: 426 // 427 // - returns false if either number is (or both are) NAN. 428 // - treats really large numbers as almost equal to infinity. 429 // - thinks +0.0 and -0.0 are 0 DLP's apart. 430 bool AlmostEquals(const FloatingPoint& rhs) const { 431 // The IEEE standard says that any comparison operation involving 432 // a NAN must return false. 433 if (is_nan() || rhs.is_nan()) return false; 434 435 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) 436 <= kMaxUlps; 437 } 438 439 private: 440 // The data type used to store the actual floating-point number. 441 union FloatingPointUnion { 442 RawType value_; // The raw floating-point number. 443 Bits bits_; // The bits that represent the number. 444 }; 445 446 // Converts an integer from the sign-and-magnitude representation to 447 // the biased representation. More precisely, let N be 2 to the 448 // power of (kBitCount - 1), an integer x is represented by the 449 // unsigned number x + N. 450 // 451 // For instance, 452 // 453 // -N + 1 (the most negative number representable using 454 // sign-and-magnitude) is represented by 1; 455 // 0 is represented by N; and 456 // N - 1 (the biggest number representable using 457 // sign-and-magnitude) is represented by 2N - 1. 458 // 459 // Read http://en.wikipedia.org/wiki/Signed_number_representations 460 // for more details on signed number representations. 461 static Bits SignAndMagnitudeToBiased(const Bits &sam) { 462 if (kSignBitMask & sam) { 463 // sam represents a negative number. 464 return ~sam + 1; 465 } else { 466 // sam represents a positive number. 467 return kSignBitMask | sam; 468 } 469 } 470 471 // Given two numbers in the sign-and-magnitude representation, 472 // returns the distance between them as an unsigned number. 473 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, 474 const Bits &sam2) { 475 const Bits biased1 = SignAndMagnitudeToBiased(sam1); 476 const Bits biased2 = SignAndMagnitudeToBiased(sam2); 477 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); 478 } 479 480 FloatingPointUnion u_; 481 }; 482 483 // Typedefs the instances of the FloatingPoint template class that we 484 // care to use. 485 typedef FloatingPoint<float> Float; 486 typedef FloatingPoint<double> Double; 487 488 // In order to catch the mistake of putting tests that use different 489 // test fixture classes in the same test case, we need to assign 490 // unique IDs to fixture classes and compare them. The TypeId type is 491 // used to hold such IDs. The user should treat TypeId as an opaque 492 // type: the only operation allowed on TypeId values is to compare 493 // them for equality using the == operator. 494 typedef const void* TypeId; 495 496 template <typename T> 497 class TypeIdHelper { 498 public: 499 // dummy_ must not have a const type. Otherwise an overly eager 500 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge 501 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization". 502 static bool dummy_; 503 }; 504 505 template <typename T> 506 bool TypeIdHelper<T>::dummy_ = false; 507 508 // GetTypeId<T>() returns the ID of type T. Different values will be 509 // returned for different types. Calling the function twice with the 510 // same type argument is guaranteed to return the same ID. 511 template <typename T> 512 TypeId GetTypeId() { 513 // The compiler is required to allocate a different 514 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate 515 // the template. Therefore, the address of dummy_ is guaranteed to 516 // be unique. 517 return &(TypeIdHelper<T>::dummy_); 518 } 519 520 // Returns the type ID of ::testing::Test. Always call this instead 521 // of GetTypeId< ::testing::Test>() to get the type ID of 522 // ::testing::Test, as the latter may give the wrong result due to a 523 // suspected linker bug when compiling Google Test as a Mac OS X 524 // framework. 525 GTEST_API_ TypeId GetTestTypeId(); 526 527 // Defines the abstract factory interface that creates instances 528 // of a Test object. 529 class TestFactoryBase { 530 public: 531 virtual ~TestFactoryBase() {} 532 533 // Creates a test instance to run. The instance is both created and destroyed 534 // within TestInfoImpl::Run() 535 virtual Test* CreateTest() = 0; 536 537 protected: 538 TestFactoryBase() {} 539 540 private: 541 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); 542 }; 543 544 // This class provides implementation of TeastFactoryBase interface. 545 // It is used in TEST and TEST_F macros. 546 template <class TestClass> 547 class TestFactoryImpl : public TestFactoryBase { 548 public: 549 virtual Test* CreateTest() { return new TestClass; } 550 }; 551 552 #if GTEST_OS_WINDOWS 553 554 // Predicate-formatters for implementing the HRESULT checking macros 555 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} 556 // We pass a long instead of HRESULT to avoid causing an 557 // include dependency for the HRESULT type. 558 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, 559 long hr); // NOLINT 560 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, 561 long hr); // NOLINT 562 563 #endif // GTEST_OS_WINDOWS 564 565 // Types of SetUpTestCase() and TearDownTestCase() functions. 566 typedef void (*SetUpTestCaseFunc)(); 567 typedef void (*TearDownTestCaseFunc)(); 568 569 // Creates a new TestInfo object and registers it with Google Test; 570 // returns the created object. 571 // 572 // Arguments: 573 // 574 // test_case_name: name of the test case 575 // name: name of the test 576 // type_param the name of the test's type parameter, or NULL if 577 // this is not a typed or a type-parameterized test. 578 // value_param text representation of the test's value parameter, 579 // or NULL if this is not a type-parameterized test. 580 // fixture_class_id: ID of the test fixture class 581 // set_up_tc: pointer to the function that sets up the test case 582 // tear_down_tc: pointer to the function that tears down the test case 583 // factory: pointer to the factory that creates a test object. 584 // The newly created TestInfo instance will assume 585 // ownership of the factory object. 586 GTEST_API_ TestInfo* MakeAndRegisterTestInfo( 587 const char* test_case_name, const char* name, 588 const char* type_param, 589 const char* value_param, 590 TypeId fixture_class_id, 591 SetUpTestCaseFunc set_up_tc, 592 TearDownTestCaseFunc tear_down_tc, 593 TestFactoryBase* factory); 594 595 // If *pstr starts with the given prefix, modifies *pstr to be right 596 // past the prefix and returns true; otherwise leaves *pstr unchanged 597 // and returns false. None of pstr, *pstr, and prefix can be NULL. 598 GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); 599 600 #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P 601 602 // State of the definition of a type-parameterized test case. 603 class GTEST_API_ TypedTestCasePState { 604 public: 605 TypedTestCasePState() : registered_(false) {} 606 607 // Adds the given test name to defined_test_names_ and return true 608 // if the test case hasn't been registered; otherwise aborts the 609 // program. 610 bool AddTestName(const char* file, int line, const char* case_name, 611 const char* test_name) { 612 if (registered_) { 613 fprintf(stderr, "%s Test %s must be defined before " 614 "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", 615 FormatFileLocation(file, line).c_str(), test_name, case_name); 616 fflush(stderr); 617 posix::Abort(); 618 } 619 defined_test_names_.insert(test_name); 620 return true; 621 } 622 623 // Verifies that registered_tests match the test names in 624 // defined_test_names_; returns registered_tests if successful, or 625 // aborts the program otherwise. 626 const char* VerifyRegisteredTestNames( 627 const char* file, int line, const char* registered_tests); 628 629 private: 630 bool registered_; 631 ::std::set<const char*> defined_test_names_; 632 }; 633 634 // Skips to the first non-space char after the first comma in 'str'; 635 // returns NULL if no comma is found in 'str'. 636 inline const char* SkipComma(const char* str) { 637 const char* comma = strchr(str, ','); 638 if (comma == NULL) { 639 return NULL; 640 } 641 while (IsSpace(*(++comma))) {} 642 return comma; 643 } 644 645 // Returns the prefix of 'str' before the first comma in it; returns 646 // the entire string if it contains no comma. 647 inline String GetPrefixUntilComma(const char* str) { 648 const char* comma = strchr(str, ','); 649 return comma == NULL ? String(str) : String(str, comma - str); 650 } 651 652 // TypeParameterizedTest<Fixture, TestSel, Types>::Register() 653 // registers a list of type-parameterized tests with Google Test. The 654 // return value is insignificant - we just need to return something 655 // such that we can call this function in a namespace scope. 656 // 657 // Implementation note: The GTEST_TEMPLATE_ macro declares a template 658 // template parameter. It's defined in gtest-type-util.h. 659 template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types> 660 class TypeParameterizedTest { 661 public: 662 // 'index' is the index of the test in the type list 'Types' 663 // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, 664 // Types). Valid values for 'index' are [0, N - 1] where N is the 665 // length of Types. 666 static bool Register(const char* prefix, const char* case_name, 667 const char* test_names, int index) { 668 typedef typename Types::Head Type; 669 typedef Fixture<Type> FixtureClass; 670 typedef typename GTEST_BIND_(TestSel, Type) TestClass; 671 672 // First, registers the first type-parameterized test in the type 673 // list. 674 MakeAndRegisterTestInfo( 675 String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/", 676 case_name, index).c_str(), 677 GetPrefixUntilComma(test_names).c_str(), 678 GetTypeName<Type>().c_str(), 679 NULL, // No value parameter. 680 GetTypeId<FixtureClass>(), 681 TestClass::SetUpTestCase, 682 TestClass::TearDownTestCase, 683 new TestFactoryImpl<TestClass>); 684 685 // Next, recurses (at compile time) with the tail of the type list. 686 return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail> 687 ::Register(prefix, case_name, test_names, index + 1); 688 } 689 }; 690 691 // The base case for the compile time recursion. 692 template <GTEST_TEMPLATE_ Fixture, class TestSel> 693 class TypeParameterizedTest<Fixture, TestSel, Types0> { 694 public: 695 static bool Register(const char* /*prefix*/, const char* /*case_name*/, 696 const char* /*test_names*/, int /*index*/) { 697 return true; 698 } 699 }; 700 701 // TypeParameterizedTestCase<Fixture, Tests, Types>::Register() 702 // registers *all combinations* of 'Tests' and 'Types' with Google 703 // Test. The return value is insignificant - we just need to return 704 // something such that we can call this function in a namespace scope. 705 template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types> 706 class TypeParameterizedTestCase { 707 public: 708 static bool Register(const char* prefix, const char* case_name, 709 const char* test_names) { 710 typedef typename Tests::Head Head; 711 712 // First, register the first test in 'Test' for each type in 'Types'. 713 TypeParameterizedTest<Fixture, Head, Types>::Register( 714 prefix, case_name, test_names, 0); 715 716 // Next, recurses (at compile time) with the tail of the test list. 717 return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types> 718 ::Register(prefix, case_name, SkipComma(test_names)); 719 } 720 }; 721 722 // The base case for the compile time recursion. 723 template <GTEST_TEMPLATE_ Fixture, typename Types> 724 class TypeParameterizedTestCase<Fixture, Templates0, Types> { 725 public: 726 static bool Register(const char* /*prefix*/, const char* /*case_name*/, 727 const char* /*test_names*/) { 728 return true; 729 } 730 }; 731 732 #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P 733 734 // Returns the current OS stack trace as a String. 735 // 736 // The maximum number of stack frames to be included is specified by 737 // the gtest_stack_trace_depth flag. The skip_count parameter 738 // specifies the number of top frames to be skipped, which doesn't 739 // count against the number of frames to be included. 740 // 741 // For example, if Foo() calls Bar(), which in turn calls 742 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in 743 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. 744 GTEST_API_ String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, 745 int skip_count); 746 747 // Helpers for suppressing warnings on unreachable code or constant 748 // condition. 749 750 // Always returns true. 751 GTEST_API_ bool AlwaysTrue(); 752 753 // Always returns false. 754 inline bool AlwaysFalse() { return !AlwaysTrue(); } 755 756 // Helper for suppressing false warning from Clang on a const char* 757 // variable declared in a conditional expression always being NULL in 758 // the else branch. 759 struct GTEST_API_ ConstCharPtr { 760 ConstCharPtr(const char* str) : value(str) {} 761 operator bool() const { return true; } 762 const char* value; 763 }; 764 765 // A simple Linear Congruential Generator for generating random 766 // numbers with a uniform distribution. Unlike rand() and srand(), it 767 // doesn't use global state (and therefore can't interfere with user 768 // code). Unlike rand_r(), it's portable. An LCG isn't very random, 769 // but it's good enough for our purposes. 770 class GTEST_API_ Random { 771 public: 772 static const UInt32 kMaxRange = 1u << 31; 773 774 explicit Random(UInt32 seed) : state_(seed) {} 775 776 void Reseed(UInt32 seed) { state_ = seed; } 777 778 // Generates a random number from [0, range). Crashes if 'range' is 779 // 0 or greater than kMaxRange. 780 UInt32 Generate(UInt32 range); 781 782 private: 783 UInt32 state_; 784 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); 785 }; 786 787 // Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a 788 // compiler error iff T1 and T2 are different types. 789 template <typename T1, typename T2> 790 struct CompileAssertTypesEqual; 791 792 template <typename T> 793 struct CompileAssertTypesEqual<T, T> { 794 }; 795 796 // Removes the reference from a type if it is a reference type, 797 // otherwise leaves it unchanged. This is the same as 798 // tr1::remove_reference, which is not widely available yet. 799 template <typename T> 800 struct RemoveReference { typedef T type; }; // NOLINT 801 template <typename T> 802 struct RemoveReference<T&> { typedef T type; }; // NOLINT 803 804 // A handy wrapper around RemoveReference that works when the argument 805 // T depends on template parameters. 806 #define GTEST_REMOVE_REFERENCE_(T) \ 807 typename ::testing::internal::RemoveReference<T>::type 808 809 // Removes const from a type if it is a const type, otherwise leaves 810 // it unchanged. This is the same as tr1::remove_const, which is not 811 // widely available yet. 812 template <typename T> 813 struct RemoveConst { typedef T type; }; // NOLINT 814 template <typename T> 815 struct RemoveConst<const T> { typedef T type; }; // NOLINT 816 817 // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above 818 // definition to fail to remove the const in 'const int[3]' and 'const 819 // char[3][4]'. The following specialization works around the bug. 820 // However, it causes trouble with GCC and thus needs to be 821 // conditionally compiled. 822 #if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) 823 template <typename T, size_t N> 824 struct RemoveConst<const T[N]> { 825 typedef typename RemoveConst<T>::type type[N]; 826 }; 827 #endif 828 829 // A handy wrapper around RemoveConst that works when the argument 830 // T depends on template parameters. 831 #define GTEST_REMOVE_CONST_(T) \ 832 typename ::testing::internal::RemoveConst<T>::type 833 834 // Turns const U&, U&, const U, and U all into U. 835 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ 836 GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) 837 838 // Adds reference to a type if it is not a reference type, 839 // otherwise leaves it unchanged. This is the same as 840 // tr1::add_reference, which is not widely available yet. 841 template <typename T> 842 struct AddReference { typedef T& type; }; // NOLINT 843 template <typename T> 844 struct AddReference<T&> { typedef T& type; }; // NOLINT 845 846 // A handy wrapper around AddReference that works when the argument T 847 // depends on template parameters. 848 #define GTEST_ADD_REFERENCE_(T) \ 849 typename ::testing::internal::AddReference<T>::type 850 851 // Adds a reference to const on top of T as necessary. For example, 852 // it transforms 853 // 854 // char ==> const char& 855 // const char ==> const char& 856 // char& ==> const char& 857 // const char& ==> const char& 858 // 859 // The argument T must depend on some template parameters. 860 #define GTEST_REFERENCE_TO_CONST_(T) \ 861 GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) 862 863 // ImplicitlyConvertible<From, To>::value is a compile-time bool 864 // constant that's true iff type From can be implicitly converted to 865 // type To. 866 template <typename From, typename To> 867 class ImplicitlyConvertible { 868 private: 869 // We need the following helper functions only for their types. 870 // They have no implementations. 871 872 // MakeFrom() is an expression whose type is From. We cannot simply 873 // use From(), as the type From may not have a public default 874 // constructor. 875 static From MakeFrom(); 876 877 // These two functions are overloaded. Given an expression 878 // Helper(x), the compiler will pick the first version if x can be 879 // implicitly converted to type To; otherwise it will pick the 880 // second version. 881 // 882 // The first version returns a value of size 1, and the second 883 // version returns a value of size 2. Therefore, by checking the 884 // size of Helper(x), which can be done at compile time, we can tell 885 // which version of Helper() is used, and hence whether x can be 886 // implicitly converted to type To. 887 static char Helper(To); 888 static char (&Helper(...))[2]; // NOLINT 889 890 // We have to put the 'public' section after the 'private' section, 891 // or MSVC refuses to compile the code. 892 public: 893 // MSVC warns about implicitly converting from double to int for 894 // possible loss of data, so we need to temporarily disable the 895 // warning. 896 #ifdef _MSC_VER 897 # pragma warning(push) // Saves the current warning state. 898 # pragma warning(disable:4244) // Temporarily disables warning 4244. 899 900 static const bool value = 901 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; 902 # pragma warning(pop) // Restores the warning state. 903 #elif defined(__BORLANDC__) 904 // C++Builder cannot use member overload resolution during template 905 // instantiation. The simplest workaround is to use its C++0x type traits 906 // functions (C++Builder 2009 and above only). 907 static const bool value = __is_convertible(From, To); 908 #else 909 static const bool value = 910 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; 911 #endif // _MSV_VER 912 }; 913 template <typename From, typename To> 914 const bool ImplicitlyConvertible<From, To>::value; 915 916 // IsAProtocolMessage<T>::value is a compile-time bool constant that's 917 // true iff T is type ProtocolMessage, proto2::Message, or a subclass 918 // of those. 919 template <typename T> 920 struct IsAProtocolMessage 921 : public bool_constant< 922 ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value || 923 ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> { 924 }; 925 926 // When the compiler sees expression IsContainerTest<C>(0), if C is an 927 // STL-style container class, the first overload of IsContainerTest 928 // will be viable (since both C::iterator* and C::const_iterator* are 929 // valid types and NULL can be implicitly converted to them). It will 930 // be picked over the second overload as 'int' is a perfect match for 931 // the type of argument 0. If C::iterator or C::const_iterator is not 932 // a valid type, the first overload is not viable, and the second 933 // overload will be picked. Therefore, we can determine whether C is 934 // a container class by checking the type of IsContainerTest<C>(0). 935 // The value of the expression is insignificant. 936 // 937 // Note that we look for both C::iterator and C::const_iterator. The 938 // reason is that C++ injects the name of a class as a member of the 939 // class itself (e.g. you can refer to class iterator as either 940 // 'iterator' or 'iterator::iterator'). If we look for C::iterator 941 // only, for example, we would mistakenly think that a class named 942 // iterator is an STL container. 943 // 944 // Also note that the simpler approach of overloading 945 // IsContainerTest(typename C::const_iterator*) and 946 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. 947 typedef int IsContainer; 948 template <class C> 949 IsContainer IsContainerTest(int /* dummy */, 950 typename C::iterator* /* it */ = NULL, 951 typename C::const_iterator* /* const_it */ = NULL) { 952 return 0; 953 } 954 955 typedef char IsNotContainer; 956 template <class C> 957 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } 958 959 // EnableIf<condition>::type is void when 'Cond' is true, and 960 // undefined when 'Cond' is false. To use SFINAE to make a function 961 // overload only apply when a particular expression is true, add 962 // "typename EnableIf<expression>::type* = 0" as the last parameter. 963 template<bool> struct EnableIf; 964 template<> struct EnableIf<true> { typedef void type; }; // NOLINT 965 966 // Utilities for native arrays. 967 968 // ArrayEq() compares two k-dimensional native arrays using the 969 // elements' operator==, where k can be any integer >= 0. When k is 970 // 0, ArrayEq() degenerates into comparing a single pair of values. 971 972 template <typename T, typename U> 973 bool ArrayEq(const T* lhs, size_t size, const U* rhs); 974 975 // This generic version is used when k is 0. 976 template <typename T, typename U> 977 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } 978 979 // This overload is used when k >= 1. 980 template <typename T, typename U, size_t N> 981 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { 982 return internal::ArrayEq(lhs, N, rhs); 983 } 984 985 // This helper reduces code bloat. If we instead put its logic inside 986 // the previous ArrayEq() function, arrays with different sizes would 987 // lead to different copies of the template code. 988 template <typename T, typename U> 989 bool ArrayEq(const T* lhs, size_t size, const U* rhs) { 990 for (size_t i = 0; i != size; i++) { 991 if (!internal::ArrayEq(lhs[i], rhs[i])) 992 return false; 993 } 994 return true; 995 } 996 997 // Finds the first element in the iterator range [begin, end) that 998 // equals elem. Element may be a native array type itself. 999 template <typename Iter, typename Element> 1000 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { 1001 for (Iter it = begin; it != end; ++it) { 1002 if (internal::ArrayEq(*it, elem)) 1003 return it; 1004 } 1005 return end; 1006 } 1007 1008 // CopyArray() copies a k-dimensional native array using the elements' 1009 // operator=, where k can be any integer >= 0. When k is 0, 1010 // CopyArray() degenerates into copying a single value. 1011 1012 template <typename T, typename U> 1013 void CopyArray(const T* from, size_t size, U* to); 1014 1015 // This generic version is used when k is 0. 1016 template <typename T, typename U> 1017 inline void CopyArray(const T& from, U* to) { *to = from; } 1018 1019 // This overload is used when k >= 1. 1020 template <typename T, typename U, size_t N> 1021 inline void CopyArray(const T(&from)[N], U(*to)[N]) { 1022 internal::CopyArray(from, N, *to); 1023 } 1024 1025 // This helper reduces code bloat. If we instead put its logic inside 1026 // the previous CopyArray() function, arrays with different sizes 1027 // would lead to different copies of the template code. 1028 template <typename T, typename U> 1029 void CopyArray(const T* from, size_t size, U* to) { 1030 for (size_t i = 0; i != size; i++) { 1031 internal::CopyArray(from[i], to + i); 1032 } 1033 } 1034 1035 // The relation between an NativeArray object (see below) and the 1036 // native array it represents. 1037 enum RelationToSource { 1038 kReference, // The NativeArray references the native array. 1039 kCopy // The NativeArray makes a copy of the native array and 1040 // owns the copy. 1041 }; 1042 1043 // Adapts a native array to a read-only STL-style container. Instead 1044 // of the complete STL container concept, this adaptor only implements 1045 // members useful for Google Mock's container matchers. New members 1046 // should be added as needed. To simplify the implementation, we only 1047 // support Element being a raw type (i.e. having no top-level const or 1048 // reference modifier). It's the client's responsibility to satisfy 1049 // this requirement. Element can be an array type itself (hence 1050 // multi-dimensional arrays are supported). 1051 template <typename Element> 1052 class NativeArray { 1053 public: 1054 // STL-style container typedefs. 1055 typedef Element value_type; 1056 typedef Element* iterator; 1057 typedef const Element* const_iterator; 1058 1059 // Constructs from a native array. 1060 NativeArray(const Element* array, size_t count, RelationToSource relation) { 1061 Init(array, count, relation); 1062 } 1063 1064 // Copy constructor. 1065 NativeArray(const NativeArray& rhs) { 1066 Init(rhs.array_, rhs.size_, rhs.relation_to_source_); 1067 } 1068 1069 ~NativeArray() { 1070 // Ensures that the user doesn't instantiate NativeArray with a 1071 // const or reference type. 1072 static_cast<void>(StaticAssertTypeEqHelper<Element, 1073 GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>()); 1074 if (relation_to_source_ == kCopy) 1075 delete[] array_; 1076 } 1077 1078 // STL-style container methods. 1079 size_t size() const { return size_; } 1080 const_iterator begin() const { return array_; } 1081 const_iterator end() const { return array_ + size_; } 1082 bool operator==(const NativeArray& rhs) const { 1083 return size() == rhs.size() && 1084 ArrayEq(begin(), size(), rhs.begin()); 1085 } 1086 1087 private: 1088 // Initializes this object; makes a copy of the input array if 1089 // 'relation' is kCopy. 1090 void Init(const Element* array, size_t a_size, RelationToSource relation) { 1091 if (relation == kReference) { 1092 array_ = array; 1093 } else { 1094 Element* const copy = new Element[a_size]; 1095 CopyArray(array, a_size, copy); 1096 array_ = copy; 1097 } 1098 size_ = a_size; 1099 relation_to_source_ = relation; 1100 } 1101 1102 const Element* array_; 1103 size_t size_; 1104 RelationToSource relation_to_source_; 1105 1106 GTEST_DISALLOW_ASSIGN_(NativeArray); 1107 }; 1108 1109 } // namespace internal 1110 } // namespace testing 1111 1112 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \ 1113 ::testing::internal::AssertHelper(result_type, file, line, message) \ 1114 = ::testing::Message() 1115 1116 #define GTEST_MESSAGE_(message, result_type) \ 1117 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) 1118 1119 #define GTEST_FATAL_FAILURE_(message) \ 1120 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) 1121 1122 #define GTEST_NONFATAL_FAILURE_(message) \ 1123 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) 1124 1125 #define GTEST_SUCCESS_(message) \ 1126 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) 1127 1128 // Suppresses MSVC warnings 4072 (unreachable code) for the code following 1129 // statement if it returns or throws (or doesn't return or throw in some 1130 // situations). 1131 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ 1132 if (::testing::internal::AlwaysTrue()) { statement; } 1133 1134 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \ 1135 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1136 if (::testing::internal::ConstCharPtr gtest_msg = "") { \ 1137 bool gtest_caught_expected = false; \ 1138 try { \ 1139 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1140 } \ 1141 catch (expected_exception const&) { \ 1142 gtest_caught_expected = true; \ 1143 } \ 1144 catch (...) { \ 1145 gtest_msg.value = \ 1146 "Expected: " #statement " throws an exception of type " \ 1147 #expected_exception ".\n Actual: it throws a different type."; \ 1148 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ 1149 } \ 1150 if (!gtest_caught_expected) { \ 1151 gtest_msg.value = \ 1152 "Expected: " #statement " throws an exception of type " \ 1153 #expected_exception ".\n Actual: it throws nothing."; \ 1154 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ 1155 } \ 1156 } else \ 1157 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ 1158 fail(gtest_msg.value) 1159 1160 #define GTEST_TEST_NO_THROW_(statement, fail) \ 1161 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1162 if (::testing::internal::AlwaysTrue()) { \ 1163 try { \ 1164 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1165 } \ 1166 catch (...) { \ 1167 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ 1168 } \ 1169 } else \ 1170 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ 1171 fail("Expected: " #statement " doesn't throw an exception.\n" \ 1172 " Actual: it throws.") 1173 1174 #define GTEST_TEST_ANY_THROW_(statement, fail) \ 1175 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1176 if (::testing::internal::AlwaysTrue()) { \ 1177 bool gtest_caught_any = false; \ 1178 try { \ 1179 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1180 } \ 1181 catch (...) { \ 1182 gtest_caught_any = true; \ 1183 } \ 1184 if (!gtest_caught_any) { \ 1185 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ 1186 } \ 1187 } else \ 1188 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ 1189 fail("Expected: " #statement " throws an exception.\n" \ 1190 " Actual: it doesn't.") 1191 1192 1193 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be 1194 // either a boolean expression or an AssertionResult. text is a textual 1195 // represenation of expression as it was passed into the EXPECT_TRUE. 1196 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ 1197 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1198 if (const ::testing::AssertionResult gtest_ar_ = \ 1199 ::testing::AssertionResult(expression)) \ 1200 ; \ 1201 else \ 1202 fail(::testing::internal::GetBoolAssertionFailureMessage(\ 1203 gtest_ar_, text, #actual, #expected).c_str()) 1204 1205 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ 1206 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ 1207 if (::testing::internal::AlwaysTrue()) { \ 1208 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ 1209 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ 1210 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ 1211 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ 1212 } \ 1213 } else \ 1214 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ 1215 fail("Expected: " #statement " doesn't generate new fatal " \ 1216 "failures in the current thread.\n" \ 1217 " Actual: it does.") 1218 1219 // Expands to the name of the class that implements the given test. 1220 #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ 1221 test_case_name##_##test_name##_Test 1222 1223 // Helper macro for defining tests. 1224 #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ 1225 class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ 1226 public:\ 1227 GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ 1228 private:\ 1229 virtual void TestBody();\ 1230 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ 1231 GTEST_DISALLOW_COPY_AND_ASSIGN_(\ 1232 GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ 1233 };\ 1234 \ 1235 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ 1236 ::test_info_ =\ 1237 ::testing::internal::MakeAndRegisterTestInfo(\ 1238 #test_case_name, #test_name, NULL, NULL, \ 1239 (parent_id), \ 1240 parent_class::SetUpTestCase, \ 1241 parent_class::TearDownTestCase, \ 1242 new ::testing::internal::TestFactoryImpl<\ 1243 GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ 1244 void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() 1245 1246 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ 1247