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