?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download | RSS feed

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