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@google.com (Zhanyong Wan), eefacm@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#ifdef 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 <iomanip> // NOLINT 50#include <limits> // NOLINT 51 52#include <gtest/internal/gtest-string.h> 53#include <gtest/internal/gtest-filepath.h> 54 55// Due to C++ preprocessor weirdness, we need double indirection to 56// concatenate two tokens when one of them is __LINE__. Writing 57// 58// foo ## __LINE__ 59// 60// will result in the token foo__LINE__, instead of foo followed by 61// the current line number. For more details, see 62// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 63#define GTEST_CONCAT_TOKEN(foo, bar) GTEST_CONCAT_TOKEN_IMPL(foo, bar) 64#define GTEST_CONCAT_TOKEN_IMPL(foo, bar) foo ## bar 65 66// Google Test defines the testing::Message class to allow construction of 67// test messages via the << operator. The idea is that anything 68// streamable to std::ostream can be streamed to a testing::Message. 69// This allows a user to use his own types in Google Test assertions by 70// overloading the << operator. 71// 72// util/gtl/stl_logging-inl.h overloads << for STL containers. These 73// overloads cannot be defined in the std namespace, as that will be 74// undefined behavior. Therefore, they are defined in the global 75// namespace instead. 76// 77// C++'s symbol lookup rule (i.e. Koenig lookup) says that these 78// overloads are visible in either the std namespace or the global 79// namespace, but not other namespaces, including the testing 80// namespace which Google Test's Message class is in. 81// 82// To allow STL containers (and other types that has a << operator 83// defined in the global namespace) to be used in Google Test assertions, 84// testing::Message must access the custom << operator from the global 85// namespace. Hence this helper function. 86// 87// Note: Jeffrey Yasskin suggested an alternative fix by "using 88// ::operator<<;" in the definition of Message's operator<<. That fix 89// doesn't require a helper function, but unfortunately doesn't 90// compile with MSVC. 91template <typename T> 92inline void GTestStreamToHelper(std::ostream* os, const T& val) { 93 *os << val; 94} 95 96namespace testing { 97 98// Forward declaration of classes. 99 100class Message; // Represents a failure message. 101class TestCase; // A collection of related tests. 102class TestPartResult; // Result of a test part. 103class TestInfo; // Information about a test. 104class UnitTest; // A collection of test cases. 105class UnitTestEventListenerInterface; // Listens to Google Test events. 106class AssertionResult; // Result of an assertion. 107 108namespace internal { 109 110struct TraceInfo; // Information about a trace point. 111class ScopedTrace; // Implements scoped trace. 112class TestInfoImpl; // Opaque implementation of TestInfo 113class TestResult; // Result of a single Test. 114class UnitTestImpl; // Opaque implementation of UnitTest 115 116template <typename E> class List; // A generic list. 117template <typename E> class ListNode; // A node in a generic list. 118 119// A secret type that Google Test users don't know about. It has no 120// definition on purpose. Therefore it's impossible to create a 121// Secret object, which is what we want. 122class Secret; 123 124// Two overloaded helpers for checking at compile time whether an 125// expression is a null pointer literal (i.e. NULL or any 0-valued 126// compile-time integral constant). Their return values have 127// different sizes, so we can use sizeof() to test which version is 128// picked by the compiler. These helpers have no implementations, as 129// we only need their signatures. 130// 131// Given IsNullLiteralHelper(x), the compiler will pick the first 132// version if x can be implicitly converted to Secret*, and pick the 133// second version otherwise. Since Secret is a secret and incomplete 134// type, the only expression a user can write that has type Secret* is 135// a null pointer literal. Therefore, we know that x is a null 136// pointer literal if and only if the first version is picked by the 137// compiler. 138char IsNullLiteralHelper(Secret* p); 139char (&IsNullLiteralHelper(...))[2]; // NOLINT 140 141// A compile-time bool constant that is true if and only if x is a 142// null pointer literal (i.e. NULL or any 0-valued compile-time 143// integral constant). 144#ifdef __SYMBIAN32__ // Symbian 145// Passing non-POD classes through ellipsis (...) crashes the ARM compiler. 146// The Nokia Symbian compiler tries to instantiate a copy constructor for 147// objects passed through ellipsis (...), failing for uncopyable objects. 148// Hence we define this to false (and lose support for NULL detection). 149#define GTEST_IS_NULL_LITERAL(x) false 150#else // ! __SYMBIAN32__ 151#define GTEST_IS_NULL_LITERAL(x) \ 152 (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) 153#endif // __SYMBIAN32__ 154 155// Appends the user-supplied message to the Google-Test-generated message. 156String AppendUserMessage(const String& gtest_msg, 157 const Message& user_msg); 158 159// A helper class for creating scoped traces in user programs. 160class ScopedTrace { 161 public: 162 // The c'tor pushes the given source file location and message onto 163 // a trace stack maintained by Google Test. 164 ScopedTrace(const char* file, int line, const Message& message); 165 166 // The d'tor pops the info pushed by the c'tor. 167 // 168 // Note that the d'tor is not virtual in order to be efficient. 169 // Don't inherit from ScopedTrace! 170 ~ScopedTrace(); 171 172 private: 173 GTEST_DISALLOW_COPY_AND_ASSIGN(ScopedTrace); 174} GTEST_ATTRIBUTE_UNUSED; // A ScopedTrace object does its job in its 175 // c'tor and d'tor. Therefore it doesn't 176 // need to be used otherwise. 177 178// Converts a streamable value to a String. A NULL pointer is 179// converted to "(null)". When the input value is a ::string, 180// ::std::string, ::wstring, or ::std::wstring object, each NUL 181// character in it is replaced with "\\0". 182// Declared here but defined in gtest.h, so that it has access 183// to the definition of the Message class, required by the ARM 184// compiler. 185template <typename T> 186String StreamableToString(const T& streamable); 187 188// Formats a value to be used in a failure message. 189 190#ifdef __SYMBIAN32__ 191 192// These are needed as the Nokia Symbian Compiler cannot decide between 193// const T& and const T* in a function template. The Nokia compiler _can_ 194// decide between class template specializations for T and T*, so a 195// tr1::type_traits-like is_pointer works, and we can overload on that. 196 197// This overload makes sure that all pointers (including 198// those to char or wchar_t) are printed as raw pointers. 199template <typename T> 200inline String FormatValueForFailureMessage(internal::true_type dummy, 201 T* pointer) { 202 return StreamableToString(static_cast<const void*>(pointer)); 203} 204 205template <typename T> 206inline String FormatValueForFailureMessage(internal::false_type dummy, 207 const T& value) { 208 return StreamableToString(value); 209} 210 211template <typename T> 212inline String FormatForFailureMessage(const T& value) { 213 return FormatValueForFailureMessage( 214 typename internal::is_pointer<T>::type(), value); 215} 216 217#else 218 219template <typename T> 220inline String FormatForFailureMessage(const T& value) { 221 return StreamableToString(value); 222} 223 224// This overload makes sure that all pointers (including 225// those to char or wchar_t) are printed as raw pointers. 226template <typename T> 227inline String FormatForFailureMessage(T* pointer) { 228 return StreamableToString(static_cast<const void*>(pointer)); 229} 230 231#endif // __SYMBIAN32__ 232 233// These overloaded versions handle narrow and wide characters. 234String FormatForFailureMessage(char ch); 235String FormatForFailureMessage(wchar_t wchar); 236 237// When this operand is a const char* or char*, and 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. 240 241// This internal macro is used to avoid duplicated code. 242#define GTEST_FORMAT_IMPL(operand2_type, operand1_printer)\ 243inline String FormatForComparisonFailureMessage(\ 244 operand2_type::value_type* str, const operand2_type& /*operand2*/) {\ 245 return operand1_printer(str);\ 246}\ 247inline String FormatForComparisonFailureMessage(\ 248 const operand2_type::value_type* str, const operand2_type& /*operand2*/) {\ 249 return operand1_printer(str);\ 250} 251 252#if GTEST_HAS_STD_STRING 253GTEST_FORMAT_IMPL(::std::string, String::ShowCStringQuoted) 254#endif // GTEST_HAS_STD_STRING 255#if GTEST_HAS_STD_WSTRING 256GTEST_FORMAT_IMPL(::std::wstring, String::ShowWideCStringQuoted) 257#endif // GTEST_HAS_STD_WSTRING 258 259#if GTEST_HAS_GLOBAL_STRING 260GTEST_FORMAT_IMPL(::string, String::ShowCStringQuoted) 261#endif // GTEST_HAS_GLOBAL_STRING 262#if GTEST_HAS_GLOBAL_WSTRING 263GTEST_FORMAT_IMPL(::wstring, String::ShowWideCStringQuoted) 264#endif // GTEST_HAS_GLOBAL_WSTRING 265 266#undef GTEST_FORMAT_IMPL 267 268// Constructs and returns the message for an equality assertion 269// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. 270// 271// The first four parameters are the expressions used in the assertion 272// and their values, as strings. For example, for ASSERT_EQ(foo, bar) 273// where foo is 5 and bar is 6, we have: 274// 275// expected_expression: "foo" 276// actual_expression: "bar" 277// expected_value: "5" 278// actual_value: "6" 279// 280// The ignoring_case parameter is true iff the assertion is a 281// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will 282// be inserted into the message. 283AssertionResult EqFailure(const char* expected_expression, 284 const char* actual_expression, 285 const String& expected_value, 286 const String& actual_value, 287 bool ignoring_case); 288 289 290// This template class represents an IEEE floating-point number 291// (either single-precision or double-precision, depending on the 292// template parameters). 293// 294// The purpose of this class is to do more sophisticated number 295// comparison. (Due to round-off error, etc, it's very unlikely that 296// two floating-points will be equal exactly. Hence a naive 297// comparison by the == operation often doesn't work.) 298// 299// Format of IEEE floating-point: 300// 301// The most-significant bit being the leftmost, an IEEE 302// floating-point looks like 303// 304// sign_bit exponent_bits fraction_bits 305// 306// Here, sign_bit is a single bit that designates the sign of the 307// number. 308// 309// For float, there are 8 exponent bits and 23 fraction bits. 310// 311// For double, there are 11 exponent bits and 52 fraction bits. 312// 313// More details can be found at 314// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. 315// 316// Template parameter: 317// 318// RawType: the raw floating-point type (either float or double) 319template <typename RawType> 320class FloatingPoint { 321 public: 322 // Defines the unsigned integer type that has the same size as the 323 // floating point number. 324 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits; 325 326 // Constants. 327 328 // # of bits in a number. 329 static const size_t kBitCount = 8*sizeof(RawType); 330 331 // # of fraction bits in a number. 332 static const size_t kFractionBitCount = 333 std::numeric_limits<RawType>::digits - 1; 334 335 // # of exponent bits in a number. 336 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; 337 338 // The mask for the sign bit. 339 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1); 340 341 // The mask for the fraction bits. 342 static const Bits kFractionBitMask = 343 ~static_cast<Bits>(0) >> (kExponentBitCount + 1); 344 345 // The mask for the exponent bits. 346 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); 347 348 // How many ULP's (Units in the Last Place) we want to tolerate when 349 // comparing two numbers. The larger the value, the more error we 350 // allow. A 0 value means that two numbers must be exactly the same 351 // to be considered equal. 352 // 353 // The maximum error of a single floating-point operation is 0.5 354 // units in the last place. On Intel CPU's, all floating-point 355 // calculations are done with 80-bit precision, while double has 64 356 // bits. Therefore, 4 should be enough for ordinary use. 357 // 358 // See the following article for more details on ULP: 359 // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm. 360 static const size_t kMaxUlps = 4; 361 362 // Constructs a FloatingPoint from a raw floating-point number. 363 // 364 // On an Intel CPU, passing a non-normalized NAN (Not a Number) 365 // around may change its bits, although the new value is guaranteed 366 // to be also a NAN. Therefore, don't expect this constructor to 367 // preserve the bits in x when x is a NAN. 368 explicit FloatingPoint(const RawType& x) : value_(x) {} 369 370 // Static methods 371 372 // Reinterprets a bit pattern as a floating-point number. 373 // 374 // This function is needed to test the AlmostEquals() method. 375 static RawType ReinterpretBits(const Bits bits) { 376 FloatingPoint fp(0); 377 fp.bits_ = bits; 378 return fp.value_; 379 } 380 381 // Returns the floating-point number that represent positive infinity. 382 static RawType Infinity() { 383 return ReinterpretBits(kExponentBitMask); 384 } 385 386 // Non-static methods 387 388 // Returns the bits that represents this number. 389 const Bits &bits() const { return bits_; } 390 391 // Returns the exponent bits of this number. 392 Bits exponent_bits() const { return kExponentBitMask & bits_; } 393 394 // Returns the fraction bits of this number. 395 Bits fraction_bits() const { return kFractionBitMask & bits_; } 396 397 // Returns the sign bit of this number. 398 Bits sign_bit() const { return kSignBitMask & bits_; } 399 400 // Returns true iff this is NAN (not a number). 401 bool is_nan() const { 402 // It's a NAN if the exponent bits are all ones and the fraction 403 // bits are not entirely zeros. 404 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); 405 } 406 407 // Returns true iff this number is at most kMaxUlps ULP's away from 408 // rhs. In particular, this function: 409 // 410 // - returns false if either number is (or both are) NAN. 411 // - treats really large numbers as almost equal to infinity. 412 // - thinks +0.0 and -0.0 are 0 DLP's apart. 413 bool AlmostEquals(const FloatingPoint& rhs) const { 414 // The IEEE standard says that any comparison operation involving 415 // a NAN must return false. 416 if (is_nan() || rhs.is_nan()) return false; 417 418 return DistanceBetweenSignAndMagnitudeNumbers(bits_, rhs.bits_) <= kMaxUlps; 419 } 420 421 private: 422 // Converts an integer from the sign-and-magnitude representation to 423 // the biased representation. More precisely, let N be 2 to the 424 // power of (kBitCount - 1), an integer x is represented by the 425 // unsigned number x + N. 426 // 427 // For instance, 428 // 429 // -N + 1 (the most negative number representable using 430 // sign-and-magnitude) is represented by 1; 431 // 0 is represented by N; and 432 // N - 1 (the biggest number representable using 433 // sign-and-magnitude) is represented by 2N - 1. 434 // 435 // Read http://en.wikipedia.org/wiki/Signed_number_representations 436 // for more details on signed number representations. 437 static Bits SignAndMagnitudeToBiased(const Bits &sam) { 438 if (kSignBitMask & sam) { 439 // sam represents a negative number. 440 return ~sam + 1; 441 } else { 442 // sam represents a positive number. 443 return kSignBitMask | sam; 444 } 445 } 446 447 // Given two numbers in the sign-and-magnitude representation, 448 // returns the distance between them as an unsigned number. 449 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, 450 const Bits &sam2) { 451 const Bits biased1 = SignAndMagnitudeToBiased(sam1); 452 const Bits biased2 = SignAndMagnitudeToBiased(sam2); 453 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); 454 } 455 456 union { 457 RawType value_; // The raw floating-point number. 458 Bits bits_; // The bits that represent the number. 459 }; 460}; 461 462// Typedefs the instances of the FloatingPoint template class that we 463// care to use. 464typedef FloatingPoint<float> Float; 465typedef FloatingPoint<double> Double; 466 467// In order to catch the mistake of putting tests that use different 468// test fixture classes in the same test case, we need to assign 469// unique IDs to fixture classes and compare them. The TypeId type is 470// used to hold such IDs. The user should treat TypeId as an opaque 471// type: the only operation allowed on TypeId values is to compare 472// them for equality using the == operator. 473typedef void* TypeId; 474 475// GetTypeId<T>() returns the ID of type T. Different values will be 476// returned for different types. Calling the function twice with the 477// same type argument is guaranteed to return the same ID. 478template <typename T> 479inline TypeId GetTypeId() { 480 static bool dummy = false; 481 // The compiler is required to create an instance of the static 482 // variable dummy for each T used to instantiate the template. 483 // Therefore, the address of dummy is guaranteed to be unique. 484 return &dummy; 485} 486 487#ifdef GTEST_OS_WINDOWS 488 489// Predicate-formatters for implementing the HRESULT checking macros 490// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} 491// We pass a long instead of HRESULT to avoid causing an 492// include dependency for the HRESULT type. 493AssertionResult IsHRESULTSuccess(const char* expr, long hr); // NOLINT 494AssertionResult IsHRESULTFailure(const char* expr, long hr); // NOLINT 495 496#endif // GTEST_OS_WINDOWS 497 498} // namespace internal 499} // namespace testing 500 501#define GTEST_MESSAGE(message, result_type) \ 502 ::testing::internal::AssertHelper(result_type, __FILE__, __LINE__, message) \ 503 = ::testing::Message() 504 505#define GTEST_FATAL_FAILURE(message) \ 506 return GTEST_MESSAGE(message, ::testing::TPRT_FATAL_FAILURE) 507 508#define GTEST_NONFATAL_FAILURE(message) \ 509 GTEST_MESSAGE(message, ::testing::TPRT_NONFATAL_FAILURE) 510 511#define GTEST_SUCCESS(message) \ 512 GTEST_MESSAGE(message, ::testing::TPRT_SUCCESS) 513 514#define GTEST_TEST_BOOLEAN(boolexpr, booltext, actual, expected, fail) \ 515 GTEST_AMBIGUOUS_ELSE_BLOCKER \ 516 if (boolexpr) \ 517 ; \ 518 else \ 519 fail("Value of: " booltext "\n Actual: " #actual "\nExpected: " #expected) 520 521// Helper macro for defining tests. 522#define GTEST_TEST(test_case_name, test_name, parent_class)\ 523class test_case_name##_##test_name##_Test : public parent_class {\ 524 public:\ 525 test_case_name##_##test_name##_Test() {}\ 526 static ::testing::Test* NewTest() {\ 527 return new test_case_name##_##test_name##_Test;\ 528 }\ 529 private:\ 530 virtual void TestBody();\ 531 static ::testing::TestInfo* const test_info_;\ 532 GTEST_DISALLOW_COPY_AND_ASSIGN(test_case_name##_##test_name##_Test);\ 533};\ 534\ 535::testing::TestInfo* const test_case_name##_##test_name##_Test::test_info_ =\ 536 ::testing::TestInfo::MakeAndRegisterInstance(\ 537 #test_case_name, \ 538 #test_name, \ 539 ::testing::internal::GetTypeId< parent_class >(), \ 540 parent_class::SetUpTestCase, \ 541 parent_class::TearDownTestCase, \ 542 test_case_name##_##test_name##_Test::NewTest);\ 543void test_case_name##_##test_name##_Test::TestBody() 544 545 546#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ 547