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