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