• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <type_traits>
62 #include <vector>
63 
64 #include "gtest/gtest-message.h"
65 #include "gtest/internal/gtest-filepath.h"
66 #include "gtest/internal/gtest-string.h"
67 #include "gtest/internal/gtest-type-util.h"
68 
69 // Due to C++ preprocessor weirdness, we need double indirection to
70 // concatenate two tokens when one of them is __LINE__.  Writing
71 //
72 //   foo ## __LINE__
73 //
74 // will result in the token foo__LINE__, instead of foo followed by
75 // the current line number.  For more details, see
76 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
77 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
78 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
79 
80 // Stringifies its argument.
81 #define GTEST_STRINGIFY_(name) #name
82 
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 suites.
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 // An IgnoredValue object can be implicitly constructed from ANY value.
110 class IgnoredValue {
111   struct Sink {};
112  public:
113   // This constructor template allows any value to be implicitly
114   // converted to IgnoredValue.  The object has no data member and
115   // doesn't try to remember anything about the argument.  We
116   // deliberately omit the 'explicit' keyword in order to allow the
117   // conversion to be implicit.
118   // Disable the conversion if T already has a magical conversion operator.
119   // Otherwise we get ambiguity.
120   template <typename T,
121             typename std::enable_if<!std::is_convertible<T, Sink>::value,
122                                     int>::type = 0>
IgnoredValue(const T &)123   IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)
124 };
125 
126 // Appends the user-supplied message to the Google-Test-generated message.
127 GTEST_API_ std::string AppendUserMessage(
128     const std::string& gtest_msg, const Message& user_msg);
129 
130 #if GTEST_HAS_EXCEPTIONS
131 
132 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
133 /* an exported class was derived from a class that was not exported */)
134 
135 // This exception is thrown by (and only by) a failed Google Test
136 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
137 // are enabled).  We derive it from std::runtime_error, which is for
138 // errors presumably detectable only at run time.  Since
139 // std::runtime_error inherits from std::exception, many testing
140 // frameworks know how to extract and print the message inside it.
141 class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
142  public:
143   explicit GoogleTestFailureException(const TestPartResult& failure);
144 };
145 
GTEST_DISABLE_MSC_WARNINGS_POP_()146 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4275
147 
148 #endif  // GTEST_HAS_EXCEPTIONS
149 
150 namespace edit_distance {
151 // Returns the optimal edits to go from 'left' to 'right'.
152 // All edits cost the same, with replace having lower priority than
153 // add/remove.
154 // Simple implementation of the Wagner-Fischer algorithm.
155 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
156 enum EditType { kMatch, kAdd, kRemove, kReplace };
157 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
158     const std::vector<size_t>& left, const std::vector<size_t>& right);
159 
160 // Same as above, but the input is represented as strings.
161 GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
162     const std::vector<std::string>& left,
163     const std::vector<std::string>& right);
164 
165 // Create a diff of the input strings in Unified diff format.
166 GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
167                                          const std::vector<std::string>& right,
168                                          size_t context = 2);
169 
170 }  // namespace edit_distance
171 
172 // Calculate the diff between 'left' and 'right' and return it in unified diff
173 // format.
174 // If not null, stores in 'total_line_count' the total number of lines found
175 // in left + right.
176 GTEST_API_ std::string DiffStrings(const std::string& left,
177                                    const std::string& right,
178                                    size_t* total_line_count);
179 
180 // Constructs and returns the message for an equality assertion
181 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
182 //
183 // The first four parameters are the expressions used in the assertion
184 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
185 // where foo is 5 and bar is 6, we have:
186 //
187 //   expected_expression: "foo"
188 //   actual_expression:   "bar"
189 //   expected_value:      "5"
190 //   actual_value:        "6"
191 //
192 // The ignoring_case parameter is true iff the assertion is a
193 // *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
194 // be inserted into the message.
195 GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
196                                      const char* actual_expression,
197                                      const std::string& expected_value,
198                                      const std::string& actual_value,
199                                      bool ignoring_case);
200 
201 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
202 GTEST_API_ std::string GetBoolAssertionFailureMessage(
203     const AssertionResult& assertion_result,
204     const char* expression_text,
205     const char* actual_predicate_value,
206     const char* expected_predicate_value);
207 
208 // This template class represents an IEEE floating-point number
209 // (either single-precision or double-precision, depending on the
210 // template parameters).
211 //
212 // The purpose of this class is to do more sophisticated number
213 // comparison.  (Due to round-off error, etc, it's very unlikely that
214 // two floating-points will be equal exactly.  Hence a naive
215 // comparison by the == operation often doesn't work.)
216 //
217 // Format of IEEE floating-point:
218 //
219 //   The most-significant bit being the leftmost, an IEEE
220 //   floating-point looks like
221 //
222 //     sign_bit exponent_bits fraction_bits
223 //
224 //   Here, sign_bit is a single bit that designates the sign of the
225 //   number.
226 //
227 //   For float, there are 8 exponent bits and 23 fraction bits.
228 //
229 //   For double, there are 11 exponent bits and 52 fraction bits.
230 //
231 //   More details can be found at
232 //   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
233 //
234 // Template parameter:
235 //
236 //   RawType: the raw floating-point type (either float or double)
237 template <typename RawType>
238 class FloatingPoint {
239  public:
240   // Defines the unsigned integer type that has the same size as the
241   // floating point number.
242   typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
243 
244   // Constants.
245 
246   // # of bits in a number.
247   static const size_t kBitCount = 8*sizeof(RawType);
248 
249   // # of fraction bits in a number.
250   static const size_t kFractionBitCount =
251     std::numeric_limits<RawType>::digits - 1;
252 
253   // # of exponent bits in a number.
254   static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
255 
256   // The mask for the sign bit.
257   static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
258 
259   // The mask for the fraction bits.
260   static const Bits kFractionBitMask =
261     ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
262 
263   // The mask for the exponent bits.
264   static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
265 
266   // How many ULP's (Units in the Last Place) we want to tolerate when
267   // comparing two numbers.  The larger the value, the more error we
268   // allow.  A 0 value means that two numbers must be exactly the same
269   // to be considered equal.
270   //
271   // The maximum error of a single floating-point operation is 0.5
272   // units in the last place.  On Intel CPU's, all floating-point
273   // calculations are done with 80-bit precision, while double has 64
274   // bits.  Therefore, 4 should be enough for ordinary use.
275   //
276   // See the following article for more details on ULP:
277   // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
278   static const size_t kMaxUlps = 4;
279 
280   // Constructs a FloatingPoint from a raw floating-point number.
281   //
282   // On an Intel CPU, passing a non-normalized NAN (Not a Number)
283   // around may change its bits, although the new value is guaranteed
284   // to be also a NAN.  Therefore, don't expect this constructor to
285   // preserve the bits in x when x is a NAN.
FloatingPoint(const RawType & x)286   explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
287 
288   // Static methods
289 
290   // Reinterprets a bit pattern as a floating-point number.
291   //
292   // This function is needed to test the AlmostEquals() method.
ReinterpretBits(const Bits bits)293   static RawType ReinterpretBits(const Bits bits) {
294     FloatingPoint fp(0);
295     fp.u_.bits_ = bits;
296     return fp.u_.value_;
297   }
298 
299   // Returns the floating-point number that represent positive infinity.
Infinity()300   static RawType Infinity() {
301     return ReinterpretBits(kExponentBitMask);
302   }
303 
304   // Returns the maximum representable finite floating-point number.
305   static RawType Max();
306 
307   // Non-static methods
308 
309   // Returns the bits that represents this number.
bits()310   const Bits &bits() const { return u_.bits_; }
311 
312   // Returns the exponent bits of this number.
exponent_bits()313   Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
314 
315   // Returns the fraction bits of this number.
fraction_bits()316   Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
317 
318   // Returns the sign bit of this number.
sign_bit()319   Bits sign_bit() const { return kSignBitMask & u_.bits_; }
320 
321   // Returns true iff this is NAN (not a number).
is_nan()322   bool is_nan() const {
323     // It's a NAN if the exponent bits are all ones and the fraction
324     // bits are not entirely zeros.
325     return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
326   }
327 
328   // Returns true iff this number is at most kMaxUlps ULP's away from
329   // rhs.  In particular, this function:
330   //
331   //   - returns false if either number is (or both are) NAN.
332   //   - treats really large numbers as almost equal to infinity.
333   //   - thinks +0.0 and -0.0 are 0 DLP's apart.
AlmostEquals(const FloatingPoint & rhs)334   bool AlmostEquals(const FloatingPoint& rhs) const {
335     // The IEEE standard says that any comparison operation involving
336     // a NAN must return false.
337     if (is_nan() || rhs.is_nan()) return false;
338 
339     return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
340         <= kMaxUlps;
341   }
342 
343  private:
344   // The data type used to store the actual floating-point number.
345   union FloatingPointUnion {
346     RawType value_;  // The raw floating-point number.
347     Bits bits_;      // The bits that represent the number.
348   };
349 
350   // Converts an integer from the sign-and-magnitude representation to
351   // the biased representation.  More precisely, let N be 2 to the
352   // power of (kBitCount - 1), an integer x is represented by the
353   // unsigned number x + N.
354   //
355   // For instance,
356   //
357   //   -N + 1 (the most negative number representable using
358   //          sign-and-magnitude) is represented by 1;
359   //   0      is represented by N; and
360   //   N - 1  (the biggest number representable using
361   //          sign-and-magnitude) is represented by 2N - 1.
362   //
363   // Read http://en.wikipedia.org/wiki/Signed_number_representations
364   // for more details on signed number representations.
SignAndMagnitudeToBiased(const Bits & sam)365   static Bits SignAndMagnitudeToBiased(const Bits &sam) {
366     if (kSignBitMask & sam) {
367       // sam represents a negative number.
368       return ~sam + 1;
369     } else {
370       // sam represents a positive number.
371       return kSignBitMask | sam;
372     }
373   }
374 
375   // Given two numbers in the sign-and-magnitude representation,
376   // returns the distance between them as an unsigned number.
DistanceBetweenSignAndMagnitudeNumbers(const Bits & sam1,const Bits & sam2)377   static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
378                                                      const Bits &sam2) {
379     const Bits biased1 = SignAndMagnitudeToBiased(sam1);
380     const Bits biased2 = SignAndMagnitudeToBiased(sam2);
381     return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
382   }
383 
384   FloatingPointUnion u_;
385 };
386 
387 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
388 // macro defined by <windows.h>.
389 template <>
Max()390 inline float FloatingPoint<float>::Max() { return FLT_MAX; }
391 template <>
Max()392 inline double FloatingPoint<double>::Max() { return DBL_MAX; }
393 
394 // Typedefs the instances of the FloatingPoint template class that we
395 // care to use.
396 typedef FloatingPoint<float> Float;
397 typedef FloatingPoint<double> Double;
398 
399 // In order to catch the mistake of putting tests that use different
400 // test fixture classes in the same test suite, we need to assign
401 // unique IDs to fixture classes and compare them.  The TypeId type is
402 // used to hold such IDs.  The user should treat TypeId as an opaque
403 // type: the only operation allowed on TypeId values is to compare
404 // them for equality using the == operator.
405 typedef const void* TypeId;
406 
407 template <typename T>
408 class TypeIdHelper {
409  public:
410   // dummy_ must not have a const type.  Otherwise an overly eager
411   // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
412   // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
413   static bool dummy_;
414 };
415 
416 template <typename T>
417 bool TypeIdHelper<T>::dummy_ = false;
418 
419 // GetTypeId<T>() returns the ID of type T.  Different values will be
420 // returned for different types.  Calling the function twice with the
421 // same type argument is guaranteed to return the same ID.
422 template <typename T>
GetTypeId()423 TypeId GetTypeId() {
424   // The compiler is required to allocate a different
425   // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
426   // the template.  Therefore, the address of dummy_ is guaranteed to
427   // be unique.
428   return &(TypeIdHelper<T>::dummy_);
429 }
430 
431 // Returns the type ID of ::testing::Test.  Always call this instead
432 // of GetTypeId< ::testing::Test>() to get the type ID of
433 // ::testing::Test, as the latter may give the wrong result due to a
434 // suspected linker bug when compiling Google Test as a Mac OS X
435 // framework.
436 GTEST_API_ TypeId GetTestTypeId();
437 
438 // Defines the abstract factory interface that creates instances
439 // of a Test object.
440 class TestFactoryBase {
441  public:
~TestFactoryBase()442   virtual ~TestFactoryBase() {}
443 
444   // Creates a test instance to run. The instance is both created and destroyed
445   // within TestInfoImpl::Run()
446   virtual Test* CreateTest() = 0;
447 
448  protected:
TestFactoryBase()449   TestFactoryBase() {}
450 
451  private:
452   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
453 };
454 
455 // This class provides implementation of TeastFactoryBase interface.
456 // It is used in TEST and TEST_F macros.
457 template <class TestClass>
458 class TestFactoryImpl : public TestFactoryBase {
459  public:
CreateTest()460   Test* CreateTest() override { return new TestClass; }
461 };
462 
463 #if GTEST_OS_WINDOWS
464 
465 // Predicate-formatters for implementing the HRESULT checking macros
466 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
467 // We pass a long instead of HRESULT to avoid causing an
468 // include dependency for the HRESULT type.
469 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
470                                             long hr);  // NOLINT
471 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
472                                             long hr);  // NOLINT
473 
474 #endif  // GTEST_OS_WINDOWS
475 
476 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
477 using SetUpTestSuiteFunc = void (*)();
478 using TearDownTestSuiteFunc = void (*)();
479 
480 struct CodeLocation {
CodeLocationCodeLocation481   CodeLocation(const std::string& a_file, int a_line)
482       : file(a_file), line(a_line) {}
483 
484   std::string file;
485   int line;
486 };
487 
488 //  Helper to identify which setup function for TestCase / TestSuite to call.
489 //  Only one function is allowed, either TestCase or TestSute but not both.
490 
491 // Utility functions to help SuiteApiResolver
492 using SetUpTearDownSuiteFuncType = void (*)();
493 
GetNotDefaultOrNull(SetUpTearDownSuiteFuncType a,SetUpTearDownSuiteFuncType def)494 inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(
495     SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {
496   return a == def ? nullptr : a;
497 }
498 
499 template <typename T>
500 //  Note that SuiteApiResolver inherits from T because
501 //  SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
502 //  SuiteApiResolver can access them.
503 struct SuiteApiResolver : T {
504   // testing::Test is only forward declared at this point. So we make it a
505   // dependend class for the compiler to be OK with it.
506   using Test =
507       typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;
508 
GetSetUpCaseOrSuiteSuiteApiResolver509   static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite() {
510     SetUpTearDownSuiteFuncType test_case_fp =
511         GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);
512     SetUpTearDownSuiteFuncType test_suite_fp =
513         GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);
514 
515     GTEST_CHECK_(!test_case_fp || !test_suite_fp)
516         << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
517            "make sure there is only one present ";
518 
519     return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
520   }
521 
GetTearDownCaseOrSuiteSuiteApiResolver522   static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite() {
523     SetUpTearDownSuiteFuncType test_case_fp =
524         GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);
525     SetUpTearDownSuiteFuncType test_suite_fp =
526         GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);
527 
528     GTEST_CHECK_(!test_case_fp || !test_suite_fp)
529         << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
530            " please make sure there is only one present ";
531 
532     return test_case_fp != nullptr ? test_case_fp : test_suite_fp;
533   }
534 };
535 
536 // Creates a new TestInfo object and registers it with Google Test;
537 // returns the created object.
538 //
539 // Arguments:
540 //
541 //   test_suite_name:   name of the test suite
542 //   name:             name of the test
543 //   type_param        the name of the test's type parameter, or NULL if
544 //                     this is not a typed or a type-parameterized test.
545 //   value_param       text representation of the test's value parameter,
546 //                     or NULL if this is not a type-parameterized test.
547 //   code_location:    code location where the test is defined
548 //   fixture_class_id: ID of the test fixture class
549 //   set_up_tc:        pointer to the function that sets up the test suite
550 //   tear_down_tc:     pointer to the function that tears down the test suite
551 //   factory:          pointer to the factory that creates a test object.
552 //                     The newly created TestInfo instance will assume
553 //                     ownership of the factory object.
554 GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
555     const char* test_suite_name, const char* name, const char* type_param,
556     const char* value_param, CodeLocation code_location,
557     TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,
558     TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);
559 
560 // If *pstr starts with the given prefix, modifies *pstr to be right
561 // past the prefix and returns true; otherwise leaves *pstr unchanged
562 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
563 GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
564 
565 #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
566 
567 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
568 /* class A needs to have dll-interface to be used by clients of class B */)
569 
570 // State of the definition of a type-parameterized test suite.
571 class GTEST_API_ TypedTestSuitePState {
572  public:
TypedTestSuitePState()573   TypedTestSuitePState() : registered_(false) {}
574 
575   // Adds the given test name to defined_test_names_ and return true
576   // if the test suite hasn't been registered; otherwise aborts the
577   // program.
AddTestName(const char * file,int line,const char * case_name,const char * test_name)578   bool AddTestName(const char* file, int line, const char* case_name,
579                    const char* test_name) {
580     if (registered_) {
581       fprintf(stderr,
582               "%s Test %s must be defined before "
583               "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
584               FormatFileLocation(file, line).c_str(), test_name, case_name);
585       fflush(stderr);
586       posix::Abort();
587     }
588     registered_tests_.insert(
589         ::std::make_pair(test_name, CodeLocation(file, line)));
590     return true;
591   }
592 
TestExists(const std::string & test_name)593   bool TestExists(const std::string& test_name) const {
594     return registered_tests_.count(test_name) > 0;
595   }
596 
GetCodeLocation(const std::string & test_name)597   const CodeLocation& GetCodeLocation(const std::string& test_name) const {
598     RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
599     GTEST_CHECK_(it != registered_tests_.end());
600     return it->second;
601   }
602 
603   // Verifies that registered_tests match the test names in
604   // defined_test_names_; returns registered_tests if successful, or
605   // aborts the program otherwise.
606   const char* VerifyRegisteredTestNames(
607       const char* file, int line, const char* registered_tests);
608 
609  private:
610   typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;
611 
612   bool registered_;
613   RegisteredTestsMap registered_tests_;
614 };
615 
616 //  Legacy API is deprecated but still available
617 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
618 using TypedTestCasePState = TypedTestSuitePState;
619 #endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_
620 
GTEST_DISABLE_MSC_WARNINGS_POP_()621 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
622 
623 // Skips to the first non-space char after the first comma in 'str';
624 // returns NULL if no comma is found in 'str'.
625 inline const char* SkipComma(const char* str) {
626   const char* comma = strchr(str, ',');
627   if (comma == nullptr) {
628     return nullptr;
629   }
630   while (IsSpace(*(++comma))) {}
631   return comma;
632 }
633 
634 // Returns the prefix of 'str' before the first comma in it; returns
635 // the entire string if it contains no comma.
GetPrefixUntilComma(const char * str)636 inline std::string GetPrefixUntilComma(const char* str) {
637   const char* comma = strchr(str, ',');
638   return comma == nullptr ? str : std::string(str, comma);
639 }
640 
641 // Splits a given string on a given delimiter, populating a given
642 // vector with the fields.
643 void SplitString(const ::std::string& str, char delimiter,
644                  ::std::vector< ::std::string>* dest);
645 
646 // The default argument to the template below for the case when the user does
647 // not provide a name generator.
648 struct DefaultNameGenerator {
649   template <typename T>
GetNameDefaultNameGenerator650   static std::string GetName(int i) {
651     return StreamableToString(i);
652   }
653 };
654 
655 template <typename Provided = DefaultNameGenerator>
656 struct NameGeneratorSelector {
657   typedef Provided type;
658 };
659 
660 template <typename NameGenerator>
GenerateNamesRecursively(Types0,std::vector<std::string> *,int)661 void GenerateNamesRecursively(Types0, std::vector<std::string>*, int) {}
662 
663 template <typename NameGenerator, typename Types>
GenerateNamesRecursively(Types,std::vector<std::string> * result,int i)664 void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
665   result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
666   GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
667                                           i + 1);
668 }
669 
670 template <typename NameGenerator, typename Types>
GenerateNames()671 std::vector<std::string> GenerateNames() {
672   std::vector<std::string> result;
673   GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
674   return result;
675 }
676 
677 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
678 // registers a list of type-parameterized tests with Google Test.  The
679 // return value is insignificant - we just need to return something
680 // such that we can call this function in a namespace scope.
681 //
682 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
683 // template parameter.  It's defined in gtest-type-util.h.
684 template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
685 class TypeParameterizedTest {
686  public:
687   // 'index' is the index of the test in the type list 'Types'
688   // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
689   // Types).  Valid values for 'index' are [0, N - 1] where N is the
690   // length of Types.
691   static bool Register(const char* prefix, const CodeLocation& code_location,
692                        const char* case_name, const char* test_names, int index,
693                        const std::vector<std::string>& type_names =
694                            GenerateNames<DefaultNameGenerator, Types>()) {
695     typedef typename Types::Head Type;
696     typedef Fixture<Type> FixtureClass;
697     typedef typename GTEST_BIND_(TestSel, Type) TestClass;
698 
699     // First, registers the first type-parameterized test in the type
700     // list.
701     MakeAndRegisterTestInfo(
702         (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
703          "/" + type_names[index])
704             .c_str(),
705         StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
706         GetTypeName<Type>().c_str(),
707         nullptr,  // No value parameter.
708         code_location, GetTypeId<FixtureClass>(),
709         SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(),
710         SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(),
711         new TestFactoryImpl<TestClass>);
712 
713     // Next, recurses (at compile time) with the tail of the type list.
714     return TypeParameterizedTest<Fixture, TestSel,
715                                  typename Types::Tail>::Register(prefix,
716                                                                  code_location,
717                                                                  case_name,
718                                                                  test_names,
719                                                                  index + 1,
720                                                                  type_names);
721   }
722 };
723 
724 // The base case for the compile time recursion.
725 template <GTEST_TEMPLATE_ Fixture, class TestSel>
726 class TypeParameterizedTest<Fixture, TestSel, Types0> {
727  public:
728   static bool Register(const char* /*prefix*/, const CodeLocation&,
729                        const char* /*case_name*/, const char* /*test_names*/,
730                        int /*index*/,
731                        const std::vector<std::string>& =
732                            std::vector<std::string>() /*type_names*/) {
733     return true;
734   }
735 };
736 
737 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
738 // registers *all combinations* of 'Tests' and 'Types' with Google
739 // Test.  The return value is insignificant - we just need to return
740 // something such that we can call this function in a namespace scope.
741 template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
742 class TypeParameterizedTestSuite {
743  public:
744   static bool Register(const char* prefix, CodeLocation code_location,
745                        const TypedTestSuitePState* state, const char* case_name,
746                        const char* test_names,
747                        const std::vector<std::string>& type_names =
748                            GenerateNames<DefaultNameGenerator, Types>()) {
749     std::string test_name = StripTrailingSpaces(
750         GetPrefixUntilComma(test_names));
751     if (!state->TestExists(test_name)) {
752       fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
753               case_name, test_name.c_str(),
754               FormatFileLocation(code_location.file.c_str(),
755                                  code_location.line).c_str());
756       fflush(stderr);
757       posix::Abort();
758     }
759     const CodeLocation& test_location = state->GetCodeLocation(test_name);
760 
761     typedef typename Tests::Head Head;
762 
763     // First, register the first test in 'Test' for each type in 'Types'.
764     TypeParameterizedTest<Fixture, Head, Types>::Register(
765         prefix, test_location, case_name, test_names, 0, type_names);
766 
767     // Next, recurses (at compile time) with the tail of the test list.
768     return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,
769                                       Types>::Register(prefix, code_location,
770                                                        state, case_name,
771                                                        SkipComma(test_names),
772                                                        type_names);
773   }
774 };
775 
776 // The base case for the compile time recursion.
777 template <GTEST_TEMPLATE_ Fixture, typename Types>
778 class TypeParameterizedTestSuite<Fixture, Templates0, Types> {
779  public:
780   static bool Register(const char* /*prefix*/, const CodeLocation&,
781                        const TypedTestSuitePState* /*state*/,
782                        const char* /*case_name*/, const char* /*test_names*/,
783                        const std::vector<std::string>& =
784                            std::vector<std::string>() /*type_names*/) {
785     return true;
786   }
787 };
788 
789 #endif  // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
790 
791 // Returns the current OS stack trace as an std::string.
792 //
793 // The maximum number of stack frames to be included is specified by
794 // the gtest_stack_trace_depth flag.  The skip_count parameter
795 // specifies the number of top frames to be skipped, which doesn't
796 // count against the number of frames to be included.
797 //
798 // For example, if Foo() calls Bar(), which in turn calls
799 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
800 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
801 GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
802     UnitTest* unit_test, int skip_count);
803 
804 // Helpers for suppressing warnings on unreachable code or constant
805 // condition.
806 
807 // Always returns true.
808 GTEST_API_ bool AlwaysTrue();
809 
810 // Always returns false.
AlwaysFalse()811 inline bool AlwaysFalse() { return !AlwaysTrue(); }
812 
813 // Helper for suppressing false warning from Clang on a const char*
814 // variable declared in a conditional expression always being NULL in
815 // the else branch.
816 struct GTEST_API_ ConstCharPtr {
ConstCharPtrConstCharPtr817   ConstCharPtr(const char* str) : value(str) {}
818   operator bool() const { return true; }
819   const char* value;
820 };
821 
822 // A simple Linear Congruential Generator for generating random
823 // numbers with a uniform distribution.  Unlike rand() and srand(), it
824 // doesn't use global state (and therefore can't interfere with user
825 // code).  Unlike rand_r(), it's portable.  An LCG isn't very random,
826 // but it's good enough for our purposes.
827 class GTEST_API_ Random {
828  public:
829   static const UInt32 kMaxRange = 1u << 31;
830 
Random(UInt32 seed)831   explicit Random(UInt32 seed) : state_(seed) {}
832 
Reseed(UInt32 seed)833   void Reseed(UInt32 seed) { state_ = seed; }
834 
835   // Generates a random number from [0, range).  Crashes if 'range' is
836   // 0 or greater than kMaxRange.
837   UInt32 Generate(UInt32 range);
838 
839  private:
840   UInt32 state_;
841   GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
842 };
843 
844 // Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
845 // compiler error iff T1 and T2 are different types.
846 template <typename T1, typename T2>
847 struct CompileAssertTypesEqual;
848 
849 template <typename T>
850 struct CompileAssertTypesEqual<T, T> {
851 };
852 
853 // Removes the reference from a type if it is a reference type,
854 // otherwise leaves it unchanged.  This is the same as
855 // tr1::remove_reference, which is not widely available yet.
856 template <typename T>
857 struct RemoveReference { typedef T type; };  // NOLINT
858 template <typename T>
859 struct RemoveReference<T&> { typedef T type; };  // NOLINT
860 
861 // A handy wrapper around RemoveReference that works when the argument
862 // T depends on template parameters.
863 #define GTEST_REMOVE_REFERENCE_(T) \
864     typename ::testing::internal::RemoveReference<T>::type
865 
866 // Removes const from a type if it is a const type, otherwise leaves
867 // it unchanged.  This is the same as tr1::remove_const, which is not
868 // widely available yet.
869 template <typename T>
870 struct RemoveConst { typedef T type; };  // NOLINT
871 template <typename T>
872 struct RemoveConst<const T> { typedef T type; };  // NOLINT
873 
874 // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above
875 // definition to fail to remove the const in 'const int[3]' and 'const
876 // char[3][4]'.  The following specialization works around the bug.
877 template <typename T, size_t N>
878 struct RemoveConst<const T[N]> {
879   typedef typename RemoveConst<T>::type type[N];
880 };
881 
882 // A handy wrapper around RemoveConst that works when the argument
883 // T depends on template parameters.
884 #define GTEST_REMOVE_CONST_(T) \
885     typename ::testing::internal::RemoveConst<T>::type
886 
887 // Turns const U&, U&, const U, and U all into U.
888 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
889     GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T))
890 
891 // IsAProtocolMessage<T>::value is a compile-time bool constant that's
892 // true iff T is type proto2::Message or a subclass of it.
893 template <typename T>
894 struct IsAProtocolMessage
895     : public bool_constant<
896   std::is_convertible<const T*, const ::proto2::Message*>::value> {
897 };
898 
899 // When the compiler sees expression IsContainerTest<C>(0), if C is an
900 // STL-style container class, the first overload of IsContainerTest
901 // will be viable (since both C::iterator* and C::const_iterator* are
902 // valid types and NULL can be implicitly converted to them).  It will
903 // be picked over the second overload as 'int' is a perfect match for
904 // the type of argument 0.  If C::iterator or C::const_iterator is not
905 // a valid type, the first overload is not viable, and the second
906 // overload will be picked.  Therefore, we can determine whether C is
907 // a container class by checking the type of IsContainerTest<C>(0).
908 // The value of the expression is insignificant.
909 //
910 // In C++11 mode we check the existence of a const_iterator and that an
911 // iterator is properly implemented for the container.
912 //
913 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
914 // The reason is that C++ injects the name of a class as a member of the
915 // class itself (e.g. you can refer to class iterator as either
916 // 'iterator' or 'iterator::iterator').  If we look for C::iterator
917 // only, for example, we would mistakenly think that a class named
918 // iterator is an STL container.
919 //
920 // Also note that the simpler approach of overloading
921 // IsContainerTest(typename C::const_iterator*) and
922 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
923 typedef int IsContainer;
924 template <class C,
925           class Iterator = decltype(::std::declval<const C&>().begin()),
926           class = decltype(::std::declval<const C&>().end()),
927           class = decltype(++::std::declval<Iterator&>()),
928           class = decltype(*::std::declval<Iterator>()),
929           class = typename C::const_iterator>
930 IsContainer IsContainerTest(int /* dummy */) {
931   return 0;
932 }
933 
934 typedef char IsNotContainer;
935 template <class C>
936 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
937 
938 // Trait to detect whether a type T is a hash table.
939 // The heuristic used is that the type contains an inner type `hasher` and does
940 // not contain an inner type `reverse_iterator`.
941 // If the container is iterable in reverse, then order might actually matter.
942 template <typename T>
943 struct IsHashTable {
944  private:
945   template <typename U>
946   static char test(typename U::hasher*, typename U::reverse_iterator*);
947   template <typename U>
948   static int test(typename U::hasher*, ...);
949   template <typename U>
950   static char test(...);
951 
952  public:
953   static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
954 };
955 
956 template <typename T>
957 const bool IsHashTable<T>::value;
958 
959 template <typename C,
960           bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
961 struct IsRecursiveContainerImpl;
962 
963 template <typename C>
964 struct IsRecursiveContainerImpl<C, false> : 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> {
972   using value_type = decltype(*std::declval<typename C::const_iterator>());
973   using type =
974       is_same<typename std::remove_const<
975                   typename std::remove_reference<value_type>::type>::type,
976               C>;
977 };
978 
979 // IsRecursiveContainer<Type> is a unary compile-time predicate that
980 // evaluates whether C is a recursive container type. A recursive container
981 // type is a container type whose value_type is equal to the container type
982 // itself. An example for a recursive container type is
983 // boost::filesystem::path, whose iterator has a value_type that is equal to
984 // boost::filesystem::path.
985 template <typename C>
986 struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
987 
988 // EnableIf<condition>::type is void when 'Cond' is true, and
989 // undefined when 'Cond' is false.  To use SFINAE to make a function
990 // overload only apply when a particular expression is true, add
991 // "typename EnableIf<expression>::type* = 0" as the last parameter.
992 template<bool> struct EnableIf;
993 template<> struct EnableIf<true> { typedef void type; };  // NOLINT
994 
995 // Utilities for native arrays.
996 
997 // ArrayEq() compares two k-dimensional native arrays using the
998 // elements' operator==, where k can be any integer >= 0.  When k is
999 // 0, ArrayEq() degenerates into comparing a single pair of values.
1000 
1001 template <typename T, typename U>
1002 bool ArrayEq(const T* lhs, size_t size, const U* rhs);
1003 
1004 // This generic version is used when k is 0.
1005 template <typename T, typename U>
1006 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
1007 
1008 // This overload is used when k >= 1.
1009 template <typename T, typename U, size_t N>
1010 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
1011   return internal::ArrayEq(lhs, N, rhs);
1012 }
1013 
1014 // This helper reduces code bloat.  If we instead put its logic inside
1015 // the previous ArrayEq() function, arrays with different sizes would
1016 // lead to different copies of the template code.
1017 template <typename T, typename U>
1018 bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
1019   for (size_t i = 0; i != size; i++) {
1020     if (!internal::ArrayEq(lhs[i], rhs[i]))
1021       return false;
1022   }
1023   return true;
1024 }
1025 
1026 // Finds the first element in the iterator range [begin, end) that
1027 // equals elem.  Element may be a native array type itself.
1028 template <typename Iter, typename Element>
1029 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
1030   for (Iter it = begin; it != end; ++it) {
1031     if (internal::ArrayEq(*it, elem))
1032       return it;
1033   }
1034   return end;
1035 }
1036 
1037 // CopyArray() copies a k-dimensional native array using the elements'
1038 // operator=, where k can be any integer >= 0.  When k is 0,
1039 // CopyArray() degenerates into copying a single value.
1040 
1041 template <typename T, typename U>
1042 void CopyArray(const T* from, size_t size, U* to);
1043 
1044 // This generic version is used when k is 0.
1045 template <typename T, typename U>
1046 inline void CopyArray(const T& from, U* to) { *to = from; }
1047 
1048 // This overload is used when k >= 1.
1049 template <typename T, typename U, size_t N>
1050 inline void CopyArray(const T(&from)[N], U(*to)[N]) {
1051   internal::CopyArray(from, N, *to);
1052 }
1053 
1054 // This helper reduces code bloat.  If we instead put its logic inside
1055 // the previous CopyArray() function, arrays with different sizes
1056 // would lead to different copies of the template code.
1057 template <typename T, typename U>
1058 void CopyArray(const T* from, size_t size, U* to) {
1059   for (size_t i = 0; i != size; i++) {
1060     internal::CopyArray(from[i], to + i);
1061   }
1062 }
1063 
1064 // The relation between an NativeArray object (see below) and the
1065 // native array it represents.
1066 // We use 2 different structs to allow non-copyable types to be used, as long
1067 // as RelationToSourceReference() is passed.
1068 struct RelationToSourceReference {};
1069 struct RelationToSourceCopy {};
1070 
1071 // Adapts a native array to a read-only STL-style container.  Instead
1072 // of the complete STL container concept, this adaptor only implements
1073 // members useful for Google Mock's container matchers.  New members
1074 // should be added as needed.  To simplify the implementation, we only
1075 // support Element being a raw type (i.e. having no top-level const or
1076 // reference modifier).  It's the client's responsibility to satisfy
1077 // this requirement.  Element can be an array type itself (hence
1078 // multi-dimensional arrays are supported).
1079 template <typename Element>
1080 class NativeArray {
1081  public:
1082   // STL-style container typedefs.
1083   typedef Element value_type;
1084   typedef Element* iterator;
1085   typedef const Element* const_iterator;
1086 
1087   // Constructs from a native array. References the source.
1088   NativeArray(const Element* array, size_t count, RelationToSourceReference) {
1089     InitRef(array, count);
1090   }
1091 
1092   // Constructs from a native array. Copies the source.
1093   NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
1094     InitCopy(array, count);
1095   }
1096 
1097   // Copy constructor.
1098   NativeArray(const NativeArray& rhs) {
1099     (this->*rhs.clone_)(rhs.array_, rhs.size_);
1100   }
1101 
1102   ~NativeArray() {
1103     if (clone_ != &NativeArray::InitRef)
1104       delete[] array_;
1105   }
1106 
1107   // STL-style container methods.
1108   size_t size() const { return size_; }
1109   const_iterator begin() const { return array_; }
1110   const_iterator end() const { return array_ + size_; }
1111   bool operator==(const NativeArray& rhs) const {
1112     return size() == rhs.size() &&
1113         ArrayEq(begin(), size(), rhs.begin());
1114   }
1115 
1116  private:
1117   enum {
1118     kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper<
1119         Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value
1120   };
1121 
1122   // Initializes this object with a copy of the input.
1123   void InitCopy(const Element* array, size_t a_size) {
1124     Element* const copy = new Element[a_size];
1125     CopyArray(array, a_size, copy);
1126     array_ = copy;
1127     size_ = a_size;
1128     clone_ = &NativeArray::InitCopy;
1129   }
1130 
1131   // Initializes this object with a reference of the input.
1132   void InitRef(const Element* array, size_t a_size) {
1133     array_ = array;
1134     size_ = a_size;
1135     clone_ = &NativeArray::InitRef;
1136   }
1137 
1138   const Element* array_;
1139   size_t size_;
1140   void (NativeArray::*clone_)(const Element*, size_t);
1141 
1142   GTEST_DISALLOW_ASSIGN_(NativeArray);
1143 };
1144 
1145 // Backport of std::index_sequence.
1146 template <size_t... Is>
1147 struct IndexSequence {
1148   using type = IndexSequence;
1149 };
1150 
1151 // Double the IndexSequence, and one if plus_one is true.
1152 template <bool plus_one, typename T, size_t sizeofT>
1153 struct DoubleSequence;
1154 template <size_t... I, size_t sizeofT>
1155 struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
1156   using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
1157 };
1158 template <size_t... I, size_t sizeofT>
1159 struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
1160   using type = IndexSequence<I..., (sizeofT + I)...>;
1161 };
1162 
1163 // Backport of std::make_index_sequence.
1164 // It uses O(ln(N)) instantiation depth.
1165 template <size_t N>
1166 struct MakeIndexSequence
1167     : DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type,
1168                      N / 2>::type {};
1169 
1170 template <>
1171 struct MakeIndexSequence<0> : IndexSequence<> {};
1172 
1173 // FIXME: This implementation of ElemFromList is O(1) in instantiation depth,
1174 // but it is O(N^2) in total instantiations. Not sure if this is the best
1175 // tradeoff, as it will make it somewhat slow to compile.
1176 template <typename T, size_t, size_t>
1177 struct ElemFromListImpl {};
1178 
1179 template <typename T, size_t I>
1180 struct ElemFromListImpl<T, I, I> {
1181   using type = T;
1182 };
1183 
1184 // Get the Nth element from T...
1185 // It uses O(1) instantiation depth.
1186 template <size_t N, typename I, typename... T>
1187 struct ElemFromList;
1188 
1189 template <size_t N, size_t... I, typename... T>
1190 struct ElemFromList<N, IndexSequence<I...>, T...>
1191     : ElemFromListImpl<T, N, I>... {};
1192 
1193 template <typename... T>
1194 class FlatTuple;
1195 
1196 template <typename Derived, size_t I>
1197 struct FlatTupleElemBase;
1198 
1199 template <typename... T, size_t I>
1200 struct FlatTupleElemBase<FlatTuple<T...>, I> {
1201   using value_type =
1202       typename ElemFromList<I, typename MakeIndexSequence<sizeof...(T)>::type,
1203                             T...>::type;
1204   FlatTupleElemBase() = default;
1205   explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {}
1206   value_type value;
1207 };
1208 
1209 template <typename Derived, typename Idx>
1210 struct FlatTupleBase;
1211 
1212 template <size_t... Idx, typename... T>
1213 struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
1214     : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
1215   using Indices = IndexSequence<Idx...>;
1216   FlatTupleBase() = default;
1217   explicit FlatTupleBase(T... t)
1218       : FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {}
1219 };
1220 
1221 // Analog to std::tuple but with different tradeoffs.
1222 // This class minimizes the template instantiation depth, thus allowing more
1223 // elements that std::tuple would. std::tuple has been seen to require an
1224 // instantiation depth of more than 10x the number of elements in some
1225 // implementations.
1226 // FlatTuple and ElemFromList are not recursive and have a fixed depth
1227 // regardless of T...
1228 // MakeIndexSequence, on the other hand, it is recursive but with an
1229 // instantiation depth of O(ln(N)).
1230 template <typename... T>
1231 class FlatTuple
1232     : private FlatTupleBase<FlatTuple<T...>,
1233                             typename MakeIndexSequence<sizeof...(T)>::type> {
1234   using Indices = typename FlatTuple::FlatTupleBase::Indices;
1235 
1236  public:
1237   FlatTuple() = default;
1238   explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {}
1239 
1240   template <size_t I>
1241   const typename ElemFromList<I, Indices, T...>::type& Get() const {
1242     return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value;
1243   }
1244 
1245   template <size_t I>
1246   typename ElemFromList<I, Indices, T...>::type& Get() {
1247     return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value;
1248   }
1249 };
1250 
1251 // Utility functions to be called with static_assert to induce deprecation
1252 // warnings.
1253 GTEST_INTERNAL_DEPRECATED(
1254     "INSTANTIATE_TEST_CASE_P is deprecated, please use "
1255     "INSTANTIATE_TEST_SUITE_P")
1256 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
1257 
1258 GTEST_INTERNAL_DEPRECATED(
1259     "TYPED_TEST_CASE_P is deprecated, please use "
1260     "TYPED_TEST_SUITE_P")
1261 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
1262 
1263 GTEST_INTERNAL_DEPRECATED(
1264     "TYPED_TEST_CASE is deprecated, please use "
1265     "TYPED_TEST_SUITE")
1266 constexpr bool TypedTestCaseIsDeprecated() { return true; }
1267 
1268 GTEST_INTERNAL_DEPRECATED(
1269     "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
1270     "REGISTER_TYPED_TEST_SUITE_P")
1271 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
1272 
1273 GTEST_INTERNAL_DEPRECATED(
1274     "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
1275     "INSTANTIATE_TYPED_TEST_SUITE_P")
1276 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
1277 
1278 }  // namespace internal
1279 }  // namespace testing
1280 
1281 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1282   ::testing::internal::AssertHelper(result_type, file, line, message) \
1283     = ::testing::Message()
1284 
1285 #define GTEST_MESSAGE_(message, result_type) \
1286   GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1287 
1288 #define GTEST_FATAL_FAILURE_(message) \
1289   return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1290 
1291 #define GTEST_NONFATAL_FAILURE_(message) \
1292   GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1293 
1294 #define GTEST_SUCCESS_(message) \
1295   GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1296 
1297 #define GTEST_SKIP_(message) \
1298   return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
1299 
1300 // Suppress MSVC warning 4072 (unreachable code) for the code following
1301 // statement if it returns or throws (or doesn't return or throw in some
1302 // situations).
1303 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1304   if (::testing::internal::AlwaysTrue()) { statement; }
1305 
1306 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1307   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1308   if (::testing::internal::ConstCharPtr gtest_msg = "") { \
1309     bool gtest_caught_expected = false; \
1310     try { \
1311       GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1312     } \
1313     catch (expected_exception const&) { \
1314       gtest_caught_expected = true; \
1315     } \
1316     catch (...) { \
1317       gtest_msg.value = \
1318           "Expected: " #statement " throws an exception of type " \
1319           #expected_exception ".\n  Actual: it throws a different type."; \
1320       goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1321     } \
1322     if (!gtest_caught_expected) { \
1323       gtest_msg.value = \
1324           "Expected: " #statement " throws an exception of type " \
1325           #expected_exception ".\n  Actual: it throws nothing."; \
1326       goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1327     } \
1328   } else \
1329     GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
1330       fail(gtest_msg.value)
1331 
1332 #define GTEST_TEST_NO_THROW_(statement, fail) \
1333   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1334   if (::testing::internal::AlwaysTrue()) { \
1335     try { \
1336       GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1337     } \
1338     catch (...) { \
1339       goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1340     } \
1341   } else \
1342     GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
1343       fail("Expected: " #statement " doesn't throw an exception.\n" \
1344            "  Actual: it throws.")
1345 
1346 #define GTEST_TEST_ANY_THROW_(statement, fail) \
1347   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1348   if (::testing::internal::AlwaysTrue()) { \
1349     bool gtest_caught_any = false; \
1350     try { \
1351       GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1352     } \
1353     catch (...) { \
1354       gtest_caught_any = true; \
1355     } \
1356     if (!gtest_caught_any) { \
1357       goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1358     } \
1359   } else \
1360     GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1361       fail("Expected: " #statement " throws an exception.\n" \
1362            "  Actual: it doesn't.")
1363 
1364 
1365 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1366 // either a boolean expression or an AssertionResult. text is a textual
1367 // represenation of expression as it was passed into the EXPECT_TRUE.
1368 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1369   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1370   if (const ::testing::AssertionResult gtest_ar_ = \
1371       ::testing::AssertionResult(expression)) \
1372     ; \
1373   else \
1374     fail(::testing::internal::GetBoolAssertionFailureMessage(\
1375         gtest_ar_, text, #actual, #expected).c_str())
1376 
1377 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1378   GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1379   if (::testing::internal::AlwaysTrue()) { \
1380     ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1381     GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1382     if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1383       goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1384     } \
1385   } else \
1386     GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1387       fail("Expected: " #statement " doesn't generate new fatal " \
1388            "failures in the current thread.\n" \
1389            "  Actual: it does.")
1390 
1391 // Expands to the name of the class that implements the given test.
1392 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1393   test_suite_name##_##test_name##_Test
1394 
1395 // Helper macro for defining tests.
1396 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id)      \
1397   class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                    \
1398       : public parent_class {                                                 \
1399    public:                                                                    \
1400     GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {}                   \
1401                                                                               \
1402    private:                                                                   \
1403     virtual void TestBody();                                                  \
1404     static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;     \
1405     GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name,   \
1406                                                            test_name));       \
1407   };                                                                          \
1408                                                                               \
1409   ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name,          \
1410                                                     test_name)::test_info_ =  \
1411       ::testing::internal::MakeAndRegisterTestInfo(                           \
1412           #test_suite_name, #test_name, nullptr, nullptr,                     \
1413           ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
1414           ::testing::internal::SuiteApiResolver<                              \
1415               parent_class>::GetSetUpCaseOrSuite(),                           \
1416           ::testing::internal::SuiteApiResolver<                              \
1417               parent_class>::GetTearDownCaseOrSuite(),                        \
1418           new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_(    \
1419               test_suite_name, test_name)>);                                  \
1420   void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
1421 
1422 #endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
1423