gtest-internal.h 52.2 KB
Newer Older
shiqian's avatar
shiqian committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
Gennadiy Civil's avatar
Gennadiy Civil committed
30
// The Google C++ Testing and Mocking Framework (Google Test)
shiqian's avatar
shiqian committed
31
32
33
34
//
// This header file declares functions and macros used internally by
// Google Test.  They are subject to change without notice.

Gennadiy Civil's avatar
Gennadiy Civil committed
35
// GOOGLETEST_CM0001 DO NOT DELETE
Gennadiy Civil's avatar
 
Gennadiy Civil committed
36

shiqian's avatar
shiqian committed
37
38
39
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_

Gennadiy Civil's avatar
Gennadiy Civil committed
40
#include "gtest/internal/gtest-port.h"
shiqian's avatar
shiqian committed
41

zhanyong.wan's avatar
zhanyong.wan committed
42
#if GTEST_OS_LINUX
43
44
45
46
# include <stdlib.h>
# include <sys/types.h>
# include <sys/wait.h>
# include <unistd.h>
shiqian's avatar
shiqian committed
47
48
#endif  // GTEST_OS_LINUX

49
50
51
52
#if GTEST_HAS_EXCEPTIONS
# include <stdexcept>
#endif

53
#include <ctype.h>
54
#include <float.h>
55
56
57
#include <string.h>
#include <iomanip>
#include <limits>
kosak's avatar
kosak committed
58
#include <map>
59
#include <set>
60
61
#include <string>
#include <vector>
shiqian's avatar
shiqian committed
62

Gennadiy Civil's avatar
Gennadiy Civil committed
63
64
65
66
#include "gtest/gtest-message.h"
#include "gtest/internal/gtest-filepath.h"
#include "gtest/internal/gtest-string.h"
#include "gtest/internal/gtest-type-util.h"
shiqian's avatar
shiqian committed
67
68
69
70
71
72
73
74
75

// Due to C++ preprocessor weirdness, we need double indirection to
// concatenate two tokens when one of them is __LINE__.  Writing
//
//   foo ## __LINE__
//
// will result in the token foo__LINE__, instead of foo followed by
// the current line number.  For more details, see
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
shiqian's avatar
shiqian committed
76
77
#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
shiqian's avatar
shiqian committed
78

79
80
81
// Stringifies its argument.
#define GTEST_STRINGIFY_(name) #name

82
83
84
class ProtocolMessage;
namespace proto2 { class Message; }

shiqian's avatar
shiqian committed
85
86
namespace testing {

87
// Forward declarations.
shiqian's avatar
shiqian committed
88

89
class AssertionResult;                 // Result of an assertion.
shiqian's avatar
shiqian committed
90
class Message;                         // Represents a failure message.
91
class Test;                            // Represents a test.
shiqian's avatar
shiqian committed
92
class TestInfo;                        // Information about a test.
93
class TestPartResult;                  // Result of a test part.
shiqian's avatar
shiqian committed
94
95
class UnitTest;                        // A collection of test cases.

96
97
98
template <typename T>
::std::string PrintToString(const T& value);

shiqian's avatar
shiqian committed
99
100
101
102
103
104
namespace internal {

struct TraceInfo;                      // Information about a trace point.
class TestInfoImpl;                    // Opaque implementation of TestInfo
class UnitTestImpl;                    // Opaque implementation of UnitTest

shiqian's avatar
shiqian committed
105
106
// The text used in failure messages to indicate the start of the
// stack trace.
zhanyong.wan's avatar
zhanyong.wan committed
107
GTEST_API_ extern const char kStackTraceMarker[];
shiqian's avatar
shiqian committed
108

shiqian's avatar
shiqian committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Two overloaded helpers for checking at compile time whether an
// expression is a null pointer literal (i.e. NULL or any 0-valued
// compile-time integral constant).  Their return values have
// different sizes, so we can use sizeof() to test which version is
// picked by the compiler.  These helpers have no implementations, as
// we only need their signatures.
//
// Given IsNullLiteralHelper(x), the compiler will pick the first
// version if x can be implicitly converted to Secret*, and pick the
// second version otherwise.  Since Secret is a secret and incomplete
// type, the only expression a user can write that has type Secret* is
// a null pointer literal.  Therefore, we know that x is a null
// pointer literal if and only if the first version is picked by the
// compiler.
char IsNullLiteralHelper(Secret* p);
char (&IsNullLiteralHelper(...))[2];  // NOLINT

// A compile-time bool constant that is true if and only if x is a
// null pointer literal (i.e. NULL or any 0-valued compile-time
// integral constant).
129
130
131
#ifdef GTEST_ELLIPSIS_NEEDS_POD_
// We lose support for NULL detection where the compiler doesn't like
// passing non-POD classes through ellipsis (...).
132
# define GTEST_IS_NULL_LITERAL_(x) false
133
#else
134
# define GTEST_IS_NULL_LITERAL_(x) \
shiqian's avatar
shiqian committed
135
    (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
136
#endif  // GTEST_ELLIPSIS_NEEDS_POD_
shiqian's avatar
shiqian committed
137
138

// Appends the user-supplied message to the Google-Test-generated message.
139
140
GTEST_API_ std::string AppendUserMessage(
    const std::string& gtest_msg, const Message& user_msg);
shiqian's avatar
shiqian committed
141

142
143
#if GTEST_HAS_EXCEPTIONS

misterg's avatar
misterg committed
144
145
146
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
/* an exported class was derived from a class that was not exported */)

147
148
149
150
151
152
153
154
155
156
157
// This exception is thrown by (and only by) a failed Google Test
// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
// are enabled).  We derive it from std::runtime_error, which is for
// errors presumably detectable only at run time.  Since
// std::runtime_error inherits from std::exception, many testing
// frameworks know how to extract and print the message inside it.
class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {
 public:
  explicit GoogleTestFailureException(const TestPartResult& failure);
};

misterg's avatar
misterg committed
158
159
GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4275

160
161
#endif  // GTEST_HAS_EXCEPTIONS

Abseil Team's avatar
Abseil Team committed
162
namespace edit_distance {
163
164
// Returns the optimal edits to go from 'left' to 'right'.
// All edits cost the same, with replace having lower priority than
Abseil Team's avatar
Abseil Team committed
165
166
167
168
// add/remove.
// Simple implementation of the Wagner-Fischer algorithm.
// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
enum EditType { kMatch, kAdd, kRemove, kReplace };
169
GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
Abseil Team's avatar
Abseil Team committed
170
    const std::vector<size_t>& left, const std::vector<size_t>& right);
171
172
173
174
175
176
177
178
179
180
181

// Same as above, but the input is represented as strings.
GTEST_API_ std::vector<EditType> CalculateOptimalEdits(
    const std::vector<std::string>& left,
    const std::vector<std::string>& right);

// Create a diff of the input strings in Unified diff format.
GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,
                                         const std::vector<std::string>& right,
                                         size_t context = 2);

Abseil Team's avatar
Abseil Team committed
182
183
}  // namespace edit_distance

184
185
186
187
188
189
190
191
// Calculate the diff between 'left' and 'right' and return it in unified diff
// format.
// If not null, stores in 'total_line_count' the total number of lines found
// in left + right.
GTEST_API_ std::string DiffStrings(const std::string& left,
                                   const std::string& right,
                                   size_t* total_line_count);

shiqian's avatar
shiqian committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// Constructs and returns the message for an equality assertion
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
//
// The first four parameters are the expressions used in the assertion
// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
// where foo is 5 and bar is 6, we have:
//
//   expected_expression: "foo"
//   actual_expression:   "bar"
//   expected_value:      "5"
//   actual_value:        "6"
//
// The ignoring_case parameter is true iff the assertion is a
// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
// be inserted into the message.
207
208
GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
                                     const char* actual_expression,
209
210
                                     const std::string& expected_value,
                                     const std::string& actual_value,
211
                                     bool ignoring_case);
shiqian's avatar
shiqian committed
212

213
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
214
GTEST_API_ std::string GetBoolAssertionFailureMessage(
215
216
217
218
    const AssertionResult& assertion_result,
    const char* expression_text,
    const char* actual_predicate_value,
    const char* expected_predicate_value);
shiqian's avatar
shiqian committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288

// This template class represents an IEEE floating-point number
// (either single-precision or double-precision, depending on the
// template parameters).
//
// The purpose of this class is to do more sophisticated number
// comparison.  (Due to round-off error, etc, it's very unlikely that
// two floating-points will be equal exactly.  Hence a naive
// comparison by the == operation often doesn't work.)
//
// Format of IEEE floating-point:
//
//   The most-significant bit being the leftmost, an IEEE
//   floating-point looks like
//
//     sign_bit exponent_bits fraction_bits
//
//   Here, sign_bit is a single bit that designates the sign of the
//   number.
//
//   For float, there are 8 exponent bits and 23 fraction bits.
//
//   For double, there are 11 exponent bits and 52 fraction bits.
//
//   More details can be found at
//   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
//
// Template parameter:
//
//   RawType: the raw floating-point type (either float or double)
template <typename RawType>
class FloatingPoint {
 public:
  // Defines the unsigned integer type that has the same size as the
  // floating point number.
  typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;

  // Constants.

  // # of bits in a number.
  static const size_t kBitCount = 8*sizeof(RawType);

  // # of fraction bits in a number.
  static const size_t kFractionBitCount =
    std::numeric_limits<RawType>::digits - 1;

  // # of exponent bits in a number.
  static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;

  // The mask for the sign bit.
  static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);

  // The mask for the fraction bits.
  static const Bits kFractionBitMask =
    ~static_cast<Bits>(0) >> (kExponentBitCount + 1);

  // The mask for the exponent bits.
  static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);

  // How many ULP's (Units in the Last Place) we want to tolerate when
  // comparing two numbers.  The larger the value, the more error we
  // allow.  A 0 value means that two numbers must be exactly the same
  // to be considered equal.
  //
  // The maximum error of a single floating-point operation is 0.5
  // units in the last place.  On Intel CPU's, all floating-point
  // calculations are done with 80-bit precision, while double has 64
  // bits.  Therefore, 4 should be enough for ordinary use.
  //
  // See the following article for more details on ULP:
zhanyong.wan's avatar
zhanyong.wan committed
289
  // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
shiqian's avatar
shiqian committed
290
291
292
293
294
295
296
297
  static const size_t kMaxUlps = 4;

  // Constructs a FloatingPoint from a raw floating-point number.
  //
  // On an Intel CPU, passing a non-normalized NAN (Not a Number)
  // around may change its bits, although the new value is guaranteed
  // to be also a NAN.  Therefore, don't expect this constructor to
  // preserve the bits in x when x is a NAN.
298
  explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
shiqian's avatar
shiqian committed
299
300
301
302
303
304
305
306

  // Static methods

  // Reinterprets a bit pattern as a floating-point number.
  //
  // This function is needed to test the AlmostEquals() method.
  static RawType ReinterpretBits(const Bits bits) {
    FloatingPoint fp(0);
307
308
    fp.u_.bits_ = bits;
    return fp.u_.value_;
shiqian's avatar
shiqian committed
309
310
311
312
313
314
315
  }

  // Returns the floating-point number that represent positive infinity.
  static RawType Infinity() {
    return ReinterpretBits(kExponentBitMask);
  }

316
317
318
  // Returns the maximum representable finite floating-point number.
  static RawType Max();

shiqian's avatar
shiqian committed
319
320
321
  // Non-static methods

  // Returns the bits that represents this number.
322
  const Bits &bits() const { return u_.bits_; }
shiqian's avatar
shiqian committed
323
324

  // Returns the exponent bits of this number.
325
  Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
shiqian's avatar
shiqian committed
326
327

  // Returns the fraction bits of this number.
328
  Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
shiqian's avatar
shiqian committed
329
330

  // Returns the sign bit of this number.
331
  Bits sign_bit() const { return kSignBitMask & u_.bits_; }
shiqian's avatar
shiqian committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

  // Returns true iff this is NAN (not a number).
  bool is_nan() const {
    // It's a NAN if the exponent bits are all ones and the fraction
    // bits are not entirely zeros.
    return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
  }

  // Returns true iff this number is at most kMaxUlps ULP's away from
  // rhs.  In particular, this function:
  //
  //   - returns false if either number is (or both are) NAN.
  //   - treats really large numbers as almost equal to infinity.
  //   - thinks +0.0 and -0.0 are 0 DLP's apart.
  bool AlmostEquals(const FloatingPoint& rhs) const {
    // The IEEE standard says that any comparison operation involving
    // a NAN must return false.
    if (is_nan() || rhs.is_nan()) return false;

351
352
    return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
        <= kMaxUlps;
shiqian's avatar
shiqian committed
353
354
355
  }

 private:
356
357
358
359
360
361
  // The data type used to store the actual floating-point number.
  union FloatingPointUnion {
    RawType value_;  // The raw floating-point number.
    Bits bits_;      // The bits that represent the number.
  };

shiqian's avatar
shiqian committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
  // Converts an integer from the sign-and-magnitude representation to
  // the biased representation.  More precisely, let N be 2 to the
  // power of (kBitCount - 1), an integer x is represented by the
  // unsigned number x + N.
  //
  // For instance,
  //
  //   -N + 1 (the most negative number representable using
  //          sign-and-magnitude) is represented by 1;
  //   0      is represented by N; and
  //   N - 1  (the biggest number representable using
  //          sign-and-magnitude) is represented by 2N - 1.
  //
  // Read http://en.wikipedia.org/wiki/Signed_number_representations
  // for more details on signed number representations.
  static Bits SignAndMagnitudeToBiased(const Bits &sam) {
    if (kSignBitMask & sam) {
      // sam represents a negative number.
      return ~sam + 1;
    } else {
      // sam represents a positive number.
      return kSignBitMask | sam;
    }
  }

  // Given two numbers in the sign-and-magnitude representation,
  // returns the distance between them as an unsigned number.
  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
                                                     const Bits &sam2) {
    const Bits biased1 = SignAndMagnitudeToBiased(sam1);
    const Bits biased2 = SignAndMagnitudeToBiased(sam2);
    return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
  }

396
  FloatingPointUnion u_;
shiqian's avatar
shiqian committed
397
398
};

399
400
401
402
403
404
405
// We cannot use std::numeric_limits<T>::max() as it clashes with the max()
// macro defined by <windows.h>.
template <>
inline float FloatingPoint<float>::Max() { return FLT_MAX; }
template <>
inline double FloatingPoint<double>::Max() { return DBL_MAX; }

shiqian's avatar
shiqian committed
406
407
408
409
410
411
412
413
414
415
416
// Typedefs the instances of the FloatingPoint template class that we
// care to use.
typedef FloatingPoint<float> Float;
typedef FloatingPoint<double> Double;

// In order to catch the mistake of putting tests that use different
// test fixture classes in the same test case, we need to assign
// unique IDs to fixture classes and compare them.  The TypeId type is
// used to hold such IDs.  The user should treat TypeId as an opaque
// type: the only operation allowed on TypeId values is to compare
// them for equality using the == operator.
417
418
419
420
421
422
423
424
425
426
427
428
429
typedef const void* TypeId;

template <typename T>
class TypeIdHelper {
 public:
  // dummy_ must not have a const type.  Otherwise an overly eager
  // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
  // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
  static bool dummy_;
};

template <typename T>
bool TypeIdHelper<T>::dummy_ = false;
shiqian's avatar
shiqian committed
430
431
432
433
434

// GetTypeId<T>() returns the ID of type T.  Different values will be
// returned for different types.  Calling the function twice with the
// same type argument is guaranteed to return the same ID.
template <typename T>
435
436
437
438
439
440
TypeId GetTypeId() {
  // The compiler is required to allocate a different
  // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
  // the template.  Therefore, the address of dummy_ is guaranteed to
  // be unique.
  return &(TypeIdHelper<T>::dummy_);
shiqian's avatar
shiqian committed
441
442
}

443
444
445
446
447
// Returns the type ID of ::testing::Test.  Always call this instead
// of GetTypeId< ::testing::Test>() to get the type ID of
// ::testing::Test, as the latter may give the wrong result due to a
// suspected linker bug when compiling Google Test as a Mac OS X
// framework.
448
GTEST_API_ TypeId GetTestTypeId();
449

450
451
452
453
454
455
456
457
458
459
460
461
462
463
// Defines the abstract factory interface that creates instances
// of a Test object.
class TestFactoryBase {
 public:
  virtual ~TestFactoryBase() {}

  // Creates a test instance to run. The instance is both created and destroyed
  // within TestInfoImpl::Run()
  virtual Test* CreateTest() = 0;

 protected:
  TestFactoryBase() {}

 private:
shiqian's avatar
shiqian committed
464
  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
465
466
467
468
469
470
471
472
473
474
};

// This class provides implementation of TeastFactoryBase interface.
// It is used in TEST and TEST_F macros.
template <class TestClass>
class TestFactoryImpl : public TestFactoryBase {
 public:
  virtual Test* CreateTest() { return new TestClass; }
};

zhanyong.wan's avatar
zhanyong.wan committed
475
#if GTEST_OS_WINDOWS
shiqian's avatar
shiqian committed
476
477
478
479
480

// Predicate-formatters for implementing the HRESULT checking macros
// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
// We pass a long instead of HRESULT to avoid causing an
// include dependency for the HRESULT type.
481
482
483
484
GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
                                            long hr);  // NOLINT
GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
                                            long hr);  // NOLINT
shiqian's avatar
shiqian committed
485
486
487

#endif  // GTEST_OS_WINDOWS

488
489
490
491
// Types of SetUpTestCase() and TearDownTestCase() functions.
typedef void (*SetUpTestCaseFunc)();
typedef void (*TearDownTestCaseFunc)();

kosak's avatar
kosak committed
492
struct CodeLocation {
493
494
  CodeLocation(const std::string& a_file, int a_line)
      : file(a_file), line(a_line) {}
kosak's avatar
kosak committed
495

496
  std::string file;
kosak's avatar
kosak committed
497
498
499
  int line;
};

500
501
502
503
504
505
506
// Creates a new TestInfo object and registers it with Google Test;
// returns the created object.
//
// Arguments:
//
//   test_case_name:   name of the test case
//   name:             name of the test
507
//   type_param        the name of the test's type parameter, or NULL if
508
//                     this is not a typed or a type-parameterized test.
509
510
//   value_param       text representation of the test's value parameter,
//                     or NULL if this is not a type-parameterized test.
kosak's avatar
kosak committed
511
//   code_location:    code location where the test is defined
512
513
514
515
516
517
//   fixture_class_id: ID of the test fixture class
//   set_up_tc:        pointer to the function that sets up the test case
//   tear_down_tc:     pointer to the function that tears down the test case
//   factory:          pointer to the factory that creates a test object.
//                     The newly created TestInfo instance will assume
//                     ownership of the factory object.
518
GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
519
520
    const char* test_case_name,
    const char* name,
521
522
    const char* type_param,
    const char* value_param,
kosak's avatar
kosak committed
523
    CodeLocation code_location,
524
525
526
527
528
    TypeId fixture_class_id,
    SetUpTestCaseFunc set_up_tc,
    TearDownTestCaseFunc tear_down_tc,
    TestFactoryBase* factory);

529
530
531
// If *pstr starts with the given prefix, modifies *pstr to be right
// past the prefix and returns true; otherwise leaves *pstr unchanged
// and returns false.  None of pstr, *pstr, and prefix can be NULL.
zhanyong.wan's avatar
zhanyong.wan committed
532
GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);
533

zhanyong.wan's avatar
zhanyong.wan committed
534
#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
535

misterg's avatar
misterg committed
536
537
538
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)

539
// State of the definition of a type-parameterized test case.
540
class GTEST_API_ TypedTestCasePState {
541
542
543
544
545
546
547
548
549
550
551
552
 public:
  TypedTestCasePState() : registered_(false) {}

  // Adds the given test name to defined_test_names_ and return true
  // if the test case hasn't been registered; otherwise aborts the
  // program.
  bool AddTestName(const char* file, int line, const char* case_name,
                   const char* test_name) {
    if (registered_) {
      fprintf(stderr, "%s Test %s must be defined before "
              "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n",
              FormatFileLocation(file, line).c_str(), test_name, case_name);
553
      fflush(stderr);
554
      posix::Abort();
555
    }
kosak's avatar
kosak committed
556
557
    registered_tests_.insert(
        ::std::make_pair(test_name, CodeLocation(file, line)));
558
559
560
    return true;
  }

kosak's avatar
kosak committed
561
562
563
564
565
566
567
568
569
570
  bool TestExists(const std::string& test_name) const {
    return registered_tests_.count(test_name) > 0;
  }

  const CodeLocation& GetCodeLocation(const std::string& test_name) const {
    RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);
    GTEST_CHECK_(it != registered_tests_.end());
    return it->second;
  }

571
572
573
574
575
576
577
  // Verifies that registered_tests match the test names in
  // defined_test_names_; returns registered_tests if successful, or
  // aborts the program otherwise.
  const char* VerifyRegisteredTestNames(
      const char* file, int line, const char* registered_tests);

 private:
kosak's avatar
kosak committed
578
579
  typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;

580
  bool registered_;
kosak's avatar
kosak committed
581
  RegisteredTestsMap registered_tests_;
582
583
};

misterg's avatar
misterg committed
584
585
GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251

586
587
588
589
590
591
592
// Skips to the first non-space char after the first comma in 'str';
// returns NULL if no comma is found in 'str'.
inline const char* SkipComma(const char* str) {
  const char* comma = strchr(str, ',');
  if (comma == NULL) {
    return NULL;
  }
593
  while (IsSpace(*(++comma))) {}
594
595
596
597
598
  return comma;
}

// Returns the prefix of 'str' before the first comma in it; returns
// the entire string if it contains no comma.
599
inline std::string GetPrefixUntilComma(const char* str) {
600
  const char* comma = strchr(str, ',');
601
  return comma == NULL ? str : std::string(str, comma);
602
603
}

kosak's avatar
kosak committed
604
605
606
607
608
// Splits a given string on a given delimiter, populating a given
// vector with the fields.
void SplitString(const ::std::string& str, char delimiter,
                 ::std::vector< ::std::string>* dest);

Abseil Team's avatar
Abseil Team committed
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// The default argument to the template below for the case when the user does
// not provide a name generator.
struct DefaultNameGenerator {
  template <typename T>
  static std::string GetName(int i) {
    return StreamableToString(i);
  }
};

template <typename Provided = DefaultNameGenerator>
struct NameGeneratorSelector {
  typedef Provided type;
};

template <typename NameGenerator>
void GenerateNamesRecursively(Types0, std::vector<std::string>*, int) {}

template <typename NameGenerator, typename Types>
void GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {
  result->push_back(NameGenerator::template GetName<typename Types::Head>(i));
  GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,
                                          i + 1);
}

template <typename NameGenerator, typename Types>
std::vector<std::string> GenerateNames() {
  std::vector<std::string> result;
  GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);
  return result;
}

640
641
642
643
644
645
646
647
648
649
650
651
652
653
// TypeParameterizedTest<Fixture, TestSel, Types>::Register()
// registers a list of type-parameterized tests with Google Test.  The
// return value is insignificant - we just need to return something
// such that we can call this function in a namespace scope.
//
// Implementation note: The GTEST_TEMPLATE_ macro declares a template
// template parameter.  It's defined in gtest-type-util.h.
template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
class TypeParameterizedTest {
 public:
  // 'index' is the index of the test in the type list 'Types'
  // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase,
  // Types).  Valid values for 'index' are [0, N - 1] where N is the
  // length of Types.
Abseil Team's avatar
Abseil Team committed
654
655
656
657
  static bool Register(const char* prefix, const CodeLocation& code_location,
                       const char* case_name, const char* test_names, int index,
                       const std::vector<std::string>& type_names =
                           GenerateNames<DefaultNameGenerator, Types>()) {
658
659
660
661
662
663
664
    typedef typename Types::Head Type;
    typedef Fixture<Type> FixtureClass;
    typedef typename GTEST_BIND_(TestSel, Type) TestClass;

    // First, registers the first type-parameterized test in the type
    // list.
    MakeAndRegisterTestInfo(
Abseil Team's avatar
Abseil Team committed
665
666
667
        (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name +
         "/" + type_names[index])
            .c_str(),
668
        StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),
669
670
        GetTypeName<Type>().c_str(),
        NULL,  // No value parameter.
Abseil Team's avatar
Abseil Team committed
671
672
        code_location, GetTypeId<FixtureClass>(), TestClass::SetUpTestCase,
        TestClass::TearDownTestCase, new TestFactoryImpl<TestClass>);
673
674

    // Next, recurses (at compile time) with the tail of the type list.
Abseil Team's avatar
Abseil Team committed
675
676
677
678
679
680
681
    return TypeParameterizedTest<Fixture, TestSel,
                                 typename Types::Tail>::Register(prefix,
                                                                 code_location,
                                                                 case_name,
                                                                 test_names,
                                                                 index + 1,
                                                                 type_names);
682
683
684
685
686
687
688
  }
};

// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, class TestSel>
class TypeParameterizedTest<Fixture, TestSel, Types0> {
 public:
Gennadiy Civil's avatar
Gennadiy Civil committed
689
  static bool Register(const char* /*prefix*/, const CodeLocation&,
kosak's avatar
kosak committed
690
                       const char* /*case_name*/, const char* /*test_names*/,
Abseil Team's avatar
Abseil Team committed
691
692
693
                       int /*index*/,
                       const std::vector<std::string>& =
                           std::vector<std::string>() /*type_names*/) {
694
695
696
697
698
699
700
701
702
703
704
    return true;
  }
};

// TypeParameterizedTestCase<Fixture, Tests, Types>::Register()
// registers *all combinations* of 'Tests' and 'Types' with Google
// Test.  The return value is insignificant - we just need to return
// something such that we can call this function in a namespace scope.
template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
class TypeParameterizedTestCase {
 public:
kosak's avatar
kosak committed
705
  static bool Register(const char* prefix, CodeLocation code_location,
Abseil Team's avatar
Abseil Team committed
706
707
708
709
                       const TypedTestCasePState* state, const char* case_name,
                       const char* test_names,
                       const std::vector<std::string>& type_names =
                           GenerateNames<DefaultNameGenerator, Types>()) {
kosak's avatar
kosak committed
710
711
712
713
714
715
716
717
718
719
720
721
    std::string test_name = StripTrailingSpaces(
        GetPrefixUntilComma(test_names));
    if (!state->TestExists(test_name)) {
      fprintf(stderr, "Failed to get code location for test %s.%s at %s.",
              case_name, test_name.c_str(),
              FormatFileLocation(code_location.file.c_str(),
                                 code_location.line).c_str());
      fflush(stderr);
      posix::Abort();
    }
    const CodeLocation& test_location = state->GetCodeLocation(test_name);

722
723
724
725
    typedef typename Tests::Head Head;

    // First, register the first test in 'Test' for each type in 'Types'.
    TypeParameterizedTest<Fixture, Head, Types>::Register(
Abseil Team's avatar
Abseil Team committed
726
        prefix, test_location, case_name, test_names, 0, type_names);
727
728

    // Next, recurses (at compile time) with the tail of the test list.
Abseil Team's avatar
Abseil Team committed
729
730
731
732
733
    return TypeParameterizedTestCase<Fixture, typename Tests::Tail,
                                     Types>::Register(prefix, code_location,
                                                      state, case_name,
                                                      SkipComma(test_names),
                                                      type_names);
734
735
736
737
738
739
740
  }
};

// The base case for the compile time recursion.
template <GTEST_TEMPLATE_ Fixture, typename Types>
class TypeParameterizedTestCase<Fixture, Templates0, Types> {
 public:
Gennadiy Civil's avatar
Gennadiy Civil committed
741
  static bool Register(const char* /*prefix*/, const CodeLocation&,
kosak's avatar
kosak committed
742
                       const TypedTestCasePState* /*state*/,
Abseil Team's avatar
Abseil Team committed
743
744
745
                       const char* /*case_name*/, const char* /*test_names*/,
                       const std::vector<std::string>& =
                           std::vector<std::string>() /*type_names*/) {
746
747
748
749
750
751
    return true;
  }
};

#endif  // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P

752
// Returns the current OS stack trace as an std::string.
753
754
//
// The maximum number of stack frames to be included is specified by
Gennadiy Civil's avatar
Gennadiy Civil committed
755
// the gtest_stack_trace_depth flag.  The skip_count parameter
756
757
758
759
760
761
// specifies the number of top frames to be skipped, which doesn't
// count against the number of frames to be included.
//
// For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
762
763
GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(
    UnitTest* unit_test, int skip_count);
764

765
766
767
768
// Helpers for suppressing warnings on unreachable code or constant
// condition.

// Always returns true.
769
GTEST_API_ bool AlwaysTrue();
770

771
772
773
// Always returns false.
inline bool AlwaysFalse() { return !AlwaysTrue(); }

774
775
776
777
778
779
780
781
782
// Helper for suppressing false warning from Clang on a const char*
// variable declared in a conditional expression always being NULL in
// the else branch.
struct GTEST_API_ ConstCharPtr {
  ConstCharPtr(const char* str) : value(str) {}
  operator bool() const { return true; }
  const char* value;
};

783
784
785
786
787
// A simple Linear Congruential Generator for generating random
// numbers with a uniform distribution.  Unlike rand() and srand(), it
// doesn't use global state (and therefore can't interfere with user
// code).  Unlike rand_r(), it's portable.  An LCG isn't very random,
// but it's good enough for our purposes.
zhanyong.wan's avatar
zhanyong.wan committed
788
class GTEST_API_ Random {
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
 public:
  static const UInt32 kMaxRange = 1u << 31;

  explicit Random(UInt32 seed) : state_(seed) {}

  void Reseed(UInt32 seed) { state_ = seed; }

  // Generates a random number from [0, range).  Crashes if 'range' is
  // 0 or greater than kMaxRange.
  UInt32 Generate(UInt32 range);

 private:
  UInt32 state_;
  GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
};

805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
// compiler error iff T1 and T2 are different types.
template <typename T1, typename T2>
struct CompileAssertTypesEqual;

template <typename T>
struct CompileAssertTypesEqual<T, T> {
};

// Removes the reference from a type if it is a reference type,
// otherwise leaves it unchanged.  This is the same as
// tr1::remove_reference, which is not widely available yet.
template <typename T>
struct RemoveReference { typedef T type; };  // NOLINT
template <typename T>
struct RemoveReference<T&> { typedef T type; };  // NOLINT

// A handy wrapper around RemoveReference that works when the argument
// T depends on template parameters.
#define GTEST_REMOVE_REFERENCE_(T) \
    typename ::testing::internal::RemoveReference<T>::type

// Removes const from a type if it is a const type, otherwise leaves
// it unchanged.  This is the same as tr1::remove_const, which is not
// widely available yet.
template <typename T>
struct RemoveConst { typedef T type; };  // NOLINT
template <typename T>
struct RemoveConst<const T> { typedef T type; };  // NOLINT

835
836
837
// MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above
// definition to fail to remove the const in 'const int[3]' and 'const
// char[3][4]'.  The following specialization works around the bug.
838
template <typename T, size_t N>
839
struct RemoveConst<const T[N]> {
840
841
842
  typedef typename RemoveConst<T>::type type[N];
};

vladlosev's avatar
vladlosev committed
843
844
845
846
847
848
849
850
851
852
#if defined(_MSC_VER) && _MSC_VER < 1400
// This is the only specialization that allows VC++ 7.1 to remove const in
// 'const int[3] and 'const int[3][4]'.  However, it causes trouble with GCC
// and thus needs to be conditionally compiled.
template <typename T, size_t N>
struct RemoveConst<T[N]> {
  typedef typename RemoveConst<T>::type type[N];
};
#endif

853
854
855
856
857
// A handy wrapper around RemoveConst that works when the argument
// T depends on template parameters.
#define GTEST_REMOVE_CONST_(T) \
    typename ::testing::internal::RemoveConst<T>::type

858
859
860
861
// Turns const U&, U&, const U, and U all into U.
#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
    GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T))

862
863
864
865
866
867
868
869
870
871
872
873
// ImplicitlyConvertible<From, To>::value is a compile-time bool
// constant that's true iff type From can be implicitly converted to
// type To.
template <typename From, typename To>
class ImplicitlyConvertible {
 private:
  // We need the following helper functions only for their types.
  // They have no implementations.

  // MakeFrom() is an expression whose type is From.  We cannot simply
  // use From(), as the type From may not have a public default
  // constructor.
874
  static typename AddReference<From>::type MakeFrom();
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891

  // These two functions are overloaded.  Given an expression
  // Helper(x), the compiler will pick the first version if x can be
  // implicitly converted to type To; otherwise it will pick the
  // second version.
  //
  // The first version returns a value of size 1, and the second
  // version returns a value of size 2.  Therefore, by checking the
  // size of Helper(x), which can be done at compile time, we can tell
  // which version of Helper() is used, and hence whether x can be
  // implicitly converted to type To.
  static char Helper(To);
  static char (&Helper(...))[2];  // NOLINT

  // We have to put the 'public' section after the 'private' section,
  // or MSVC refuses to compile the code.
 public:
billydonahue's avatar
billydonahue committed
892
#if defined(__BORLANDC__)
893
894
895
896
  // C++Builder cannot use member overload resolution during template
  // instantiation.  The simplest workaround is to use its C++0x type traits
  // functions (C++Builder 2009 and above only).
  static const bool value = __is_convertible(From, To);
897
#else
billydonahue's avatar
billydonahue committed
898
899
900
901
  // MSVC warns about implicitly converting from double to int for
  // possible loss of data, so we need to temporarily disable the
  // warning.
  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244)
902
903
  static const bool value =
      sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
billydonahue's avatar
billydonahue committed
904
905
  GTEST_DISABLE_MSC_WARNINGS_POP_()
#endif  // __BORLANDC__
906
907
908
909
910
911
912
913
914
915
916
917
918
919
};
template <typename From, typename To>
const bool ImplicitlyConvertible<From, To>::value;

// IsAProtocolMessage<T>::value is a compile-time bool constant that's
// true iff T is type ProtocolMessage, proto2::Message, or a subclass
// of those.
template <typename T>
struct IsAProtocolMessage
    : public bool_constant<
  ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value ||
  ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> {
};

920
921
922
923
924
925
926
927
928
929
930
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
// will be viable (since both C::iterator* and C::const_iterator* are
// valid types and NULL can be implicitly converted to them).  It will
// be picked over the second overload as 'int' is a perfect match for
// the type of argument 0.  If C::iterator or C::const_iterator is not
// a valid type, the first overload is not viable, and the second
// overload will be picked.  Therefore, we can determine whether C is
// a container class by checking the type of IsContainerTest<C>(0).
// The value of the expression is insignificant.
//
931
932
933
934
935
// In C++11 mode we check the existence of a const_iterator and that an
// iterator is properly implemented for the container.
//
// For pre-C++11 that we look for both C::iterator and C::const_iterator.
// The reason is that C++ injects the name of a class as a member of the
936
937
938
939
940
941
942
943
// class itself (e.g. you can refer to class iterator as either
// 'iterator' or 'iterator::iterator').  If we look for C::iterator
// only, for example, we would mistakenly think that a class named
// iterator is an STL container.
//
// Also note that the simpler approach of overloading
// IsContainerTest(typename C::const_iterator*) and
// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
944
typedef int IsContainer;
945
946
947
948
949
950
951
952
953
954
955
#if GTEST_LANG_CXX11
template <class C,
          class Iterator = decltype(::std::declval<const C&>().begin()),
          class = decltype(::std::declval<const C&>().end()),
          class = decltype(++::std::declval<Iterator&>()),
          class = decltype(*::std::declval<Iterator>()),
          class = typename C::const_iterator>
IsContainer IsContainerTest(int /* dummy */) {
  return 0;
}
#else
956
template <class C>
957
958
959
960
961
IsContainer IsContainerTest(int /* dummy */,
                            typename C::iterator* /* it */ = NULL,
                            typename C::const_iterator* /* const_it */ = NULL) {
  return 0;
}
962
#endif  // GTEST_LANG_CXX11
963
964
965

typedef char IsNotContainer;
template <class C>
966
IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
967

968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
// Trait to detect whether a type T is a hash table.
// The heuristic used is that the type contains an inner type `hasher` and does
// not contain an inner type `reverse_iterator`.
// If the container is iterable in reverse, then order might actually matter.
template <typename T>
struct IsHashTable {
 private:
  template <typename U>
  static char test(typename U::hasher*, typename U::reverse_iterator*);
  template <typename U>
  static int test(typename U::hasher*, ...);
  template <typename U>
  static char test(...);

 public:
  static const bool value = sizeof(test<T>(0, 0)) == sizeof(int);
};

template <typename T>
const bool IsHashTable<T>::value;

Gennadiy Civil's avatar
Gennadiy Civil committed
989
990
991
992
993
994
995
996
997
998
999
template<typename T>
struct VoidT {
    typedef void value_type;
};

template <typename T, typename = void>
struct HasValueType : false_type {};
template <typename T>
struct HasValueType<T, VoidT<typename T::value_type> > : true_type {
};

1000
template <typename C,
Gennadiy Civil's avatar
Gennadiy Civil committed
1001
1002
          bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer),
          bool = HasValueType<C>::value>
1003
1004
struct IsRecursiveContainerImpl;

Gennadiy Civil's avatar
Gennadiy Civil committed
1005
1006
template <typename C, bool HV>
struct IsRecursiveContainerImpl<C, false, HV> : public false_type {};
1007

Gennadiy Civil's avatar
Gennadiy Civil committed
1008
1009
1010
1011
// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
// obey the same inconsistencies as the IsContainerTest, namely check if
// something is a container is relying on only const_iterator in C++11 and
// is relying on both const_iterator and iterator otherwise
1012
template <typename C>
Gennadiy Civil's avatar
Gennadiy Civil committed
1013
1014
1015
1016
struct IsRecursiveContainerImpl<C, true, false> : public false_type {};

template <typename C>
struct IsRecursiveContainerImpl<C, true, true> {
Gennadiy Civil's avatar
Gennadiy Civil committed
1017
1018
1019
  #if GTEST_LANG_CXX11
  typedef typename IteratorTraits<typename C::const_iterator>::value_type
      value_type;
1020
#else
Gennadiy Civil's avatar
Gennadiy Civil committed
1021
  typedef typename IteratorTraits<typename C::iterator>::value_type value_type;
1022
#endif
Gennadiy Civil's avatar
Gennadiy Civil committed
1023
  typedef is_same<value_type, C> type;
1024
1025
1026
};

// IsRecursiveContainer<Type> is a unary compile-time predicate that
1027
// evaluates whether C is a recursive container type. A recursive container
1028
// type is a container type whose value_type is equal to the container type
1029
1030
// itself. An example for a recursive container type is
// boost::filesystem::path, whose iterator has a value_type that is equal to
1031
// boost::filesystem::path.
1032
template <typename C>
1033
1034
struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};

1035
1036
1037
1038
1039
1040
1041
// EnableIf<condition>::type is void when 'Cond' is true, and
// undefined when 'Cond' is false.  To use SFINAE to make a function
// overload only apply when a particular expression is true, add
// "typename EnableIf<expression>::type* = 0" as the last parameter.
template<bool> struct EnableIf;
template<> struct EnableIf<true> { typedef void type; };  // NOLINT

1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
// Utilities for native arrays.

// ArrayEq() compares two k-dimensional native arrays using the
// elements' operator==, where k can be any integer >= 0.  When k is
// 0, ArrayEq() degenerates into comparing a single pair of values.

template <typename T, typename U>
bool ArrayEq(const T* lhs, size_t size, const U* rhs);

// This generic version is used when k is 0.
template <typename T, typename U>
inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }

// This overload is used when k >= 1.
template <typename T, typename U, size_t N>
inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
  return internal::ArrayEq(lhs, N, rhs);
}

// This helper reduces code bloat.  If we instead put its logic inside
// the previous ArrayEq() function, arrays with different sizes would
// lead to different copies of the template code.
template <typename T, typename U>
bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
  for (size_t i = 0; i != size; i++) {
    if (!internal::ArrayEq(lhs[i], rhs[i]))
      return false;
  }
  return true;
}

// Finds the first element in the iterator range [begin, end) that
// equals elem.  Element may be a native array type itself.
template <typename Iter, typename Element>
Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
  for (Iter it = begin; it != end; ++it) {
    if (internal::ArrayEq(*it, elem))
      return it;
  }
  return end;
}

// CopyArray() copies a k-dimensional native array using the elements'
// operator=, where k can be any integer >= 0.  When k is 0,
// CopyArray() degenerates into copying a single value.

template <typename T, typename U>
void CopyArray(const T* from, size_t size, U* to);

// This generic version is used when k is 0.
template <typename T, typename U>
inline void CopyArray(const T& from, U* to) { *to = from; }

// This overload is used when k >= 1.
template <typename T, typename U, size_t N>
inline void CopyArray(const T(&from)[N], U(*to)[N]) {
  internal::CopyArray(from, N, *to);
}

// This helper reduces code bloat.  If we instead put its logic inside
// the previous CopyArray() function, arrays with different sizes
// would lead to different copies of the template code.
template <typename T, typename U>
void CopyArray(const T* from, size_t size, U* to) {
  for (size_t i = 0; i != size; i++) {
    internal::CopyArray(from[i], to + i);
  }
}

// The relation between an NativeArray object (see below) and the
// native array it represents.
billydonahue's avatar
billydonahue committed
1113
1114
1115
1116
// We use 2 different structs to allow non-copyable types to be used, as long
// as RelationToSourceReference() is passed.
struct RelationToSourceReference {};
struct RelationToSourceCopy {};
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130

// Adapts a native array to a read-only STL-style container.  Instead
// of the complete STL container concept, this adaptor only implements
// members useful for Google Mock's container matchers.  New members
// should be added as needed.  To simplify the implementation, we only
// support Element being a raw type (i.e. having no top-level const or
// reference modifier).  It's the client's responsibility to satisfy
// this requirement.  Element can be an array type itself (hence
// multi-dimensional arrays are supported).
template <typename Element>
class NativeArray {
 public:
  // STL-style container typedefs.
  typedef Element value_type;
1131
  typedef Element* iterator;
1132
1133
  typedef const Element* const_iterator;

billydonahue's avatar
billydonahue committed
1134
1135
1136
1137
1138
1139
1140
1141
  // Constructs from a native array. References the source.
  NativeArray(const Element* array, size_t count, RelationToSourceReference) {
    InitRef(array, count);
  }

  // Constructs from a native array. Copies the source.
  NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
    InitCopy(array, count);
1142
1143
1144
1145
  }

  // Copy constructor.
  NativeArray(const NativeArray& rhs) {
billydonahue's avatar
billydonahue committed
1146
    (this->*rhs.clone_)(rhs.array_, rhs.size_);
1147
1148
1149
  }

  ~NativeArray() {
billydonahue's avatar
billydonahue committed
1150
    if (clone_ != &NativeArray::InitRef)
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
      delete[] array_;
  }

  // STL-style container methods.
  size_t size() const { return size_; }
  const_iterator begin() const { return array_; }
  const_iterator end() const { return array_ + size_; }
  bool operator==(const NativeArray& rhs) const {
    return size() == rhs.size() &&
        ArrayEq(begin(), size(), rhs.begin());
  }

 private:
billydonahue's avatar
billydonahue committed
1164
1165
  enum {
    kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper<
1166
        Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value
billydonahue's avatar
billydonahue committed
1167
1168
1169
1170
1171
1172
1173
  };

  // Initializes this object with a copy of the input.
  void InitCopy(const Element* array, size_t a_size) {
    Element* const copy = new Element[a_size];
    CopyArray(array, a_size, copy);
    array_ = copy;
1174
    size_ = a_size;
billydonahue's avatar
billydonahue committed
1175
1176
1177
1178
1179
1180
1181
1182
    clone_ = &NativeArray::InitCopy;
  }

  // Initializes this object with a reference of the input.
  void InitRef(const Element* array, size_t a_size) {
    array_ = array;
    size_ = a_size;
    clone_ = &NativeArray::InitRef;
1183
1184
1185
1186
  }

  const Element* array_;
  size_t size_;
billydonahue's avatar
billydonahue committed
1187
  void (NativeArray::*clone_)(const Element*, size_t);
1188
1189
1190
1191

  GTEST_DISALLOW_ASSIGN_(NativeArray);
};

Gennadiy Civil's avatar
Gennadiy Civil committed
1192
1193
class AdditionalMessage {
 public:
1194
1195
  AdditionalMessage(const char* message) : msg(message) {}
  void set(const std::string& message) { msg = message; }
1196
1197
  operator bool() const { return true; }

1198
  const std::string& get() const { return msg; }
1199

Gennadiy Civil's avatar
Gennadiy Civil committed
1200
 private:
1201
  std::string msg;
1202
1203
};

shiqian's avatar
shiqian committed
1204
1205
1206
}  // namespace internal
}  // namespace testing

1207
1208
#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
  ::testing::internal::AssertHelper(result_type, file, line, message) \
shiqian's avatar
shiqian committed
1209
1210
    = ::testing::Message()

1211
1212
1213
#define GTEST_MESSAGE_(message, result_type) \
  GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)

shiqian's avatar
shiqian committed
1214
#define GTEST_FATAL_FAILURE_(message) \
1215
  return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
shiqian's avatar
shiqian committed
1216

shiqian's avatar
shiqian committed
1217
#define GTEST_NONFATAL_FAILURE_(message) \
1218
  GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
shiqian's avatar
shiqian committed
1219

shiqian's avatar
shiqian committed
1220
#define GTEST_SUCCESS_(message) \
1221
  GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
shiqian's avatar
shiqian committed
1222

Gennadiy Civil's avatar
merging  
Gennadiy Civil committed
1223
// Suppress MSVC warning 4702 (unreachable code) for the code following
1224
1225
// statement if it returns or throws (or doesn't return or throw in some
// situations).
1226
#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1227
1228
  if (::testing::internal::AlwaysTrue()) { statement; }

Gennadiy Civil's avatar
Gennadiy Civil committed
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
#define GTEST_TEST_THROW_(statement, expected_exception, fail)      \
  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                     \
  if (::testing::internal::AdditionalMessage message = "") {        \
    bool gtest_caught_expected = false;                             \
    try {                                                           \
      try {                                                         \
        GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);  \
      } catch (expected_exception const&) {                         \
        gtest_caught_expected = true;                               \
        throw;                                                      \
      }                                                             \
    } catch (const std::exception& e) {                             \
      if (!gtest_caught_expected) {                                 \
        message.set(                                                \
            "it throws a different type "                           \
            "with message: " +                                      \
            std::string(e.what()));                                 \
1246
        goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
Gennadiy Civil's avatar
Gennadiy Civil committed
1247
1248
1249
1250
      }                                                             \
    } catch (...) {                                                 \
      if (!gtest_caught_expected) {                                 \
        message.set("it throws a different type.");                 \
1251
        goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
Gennadiy Civil's avatar
Gennadiy Civil committed
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
      }                                                             \
    }                                                               \
    if (!gtest_caught_expected) {                                   \
      message.set("it throws nothing.");                            \
      goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__);   \
    }                                                               \
  } else                                                            \
    GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__)           \
        : fail(("Expected: " #statement                             \
                " throws an exception of type " #expected_exception \
                ".\n  Actual: " +                                   \
                message.get())                                      \
                   .c_str())

#define GTEST_TEST_NO_THROW_(statement, fail)                            \
  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                          \
  if (::testing::internal::AdditionalMessage message = ".") {            \
    try {                                                                \
      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);         \
    } catch (const std::exception& e) {                                  \
      message.set(std::string(": ") + e.what());                         \
      goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__);      \
    } catch (...) {                                                      \
      goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__);      \
    }                                                                    \
  } else                                                                 \
    GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__)              \
        : fail(("Expected: " #statement " doesn't throw an exception.\n" \
                "  Actual: it throws" +                                  \
                message.get())                                           \
                   .c_str())
1283

shiqian's avatar
shiqian committed
1284
1285
#define GTEST_TEST_ANY_THROW_(statement, fail) \
  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1286
  if (::testing::internal::AlwaysTrue()) { \
1287
1288
    bool gtest_caught_any = false; \
    try { \
1289
      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1290
1291
1292
1293
1294
    } \
    catch (...) { \
      gtest_caught_any = true; \
    } \
    if (!gtest_caught_any) { \
shiqian's avatar
shiqian committed
1295
      goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1296
1297
    } \
  } else \
shiqian's avatar
shiqian committed
1298
    GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1299
1300
      fail("Expected: " #statement " throws an exception.\n" \
           "  Actual: it doesn't.")
1301
1302


1303
1304
1305
1306
// Implements Boolean test assertions such as EXPECT_TRUE. expression can be
// either a boolean expression or an AssertionResult. text is a textual
// represenation of expression as it was passed into the EXPECT_TRUE.
#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
shiqian's avatar
shiqian committed
1307
  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1308
1309
  if (const ::testing::AssertionResult gtest_ar_ = \
      ::testing::AssertionResult(expression)) \
shiqian's avatar
shiqian committed
1310
1311
    ; \
  else \
1312
1313
    fail(::testing::internal::GetBoolAssertionFailureMessage(\
        gtest_ar_, text, #actual, #expected).c_str())
shiqian's avatar
shiqian committed
1314

shiqian's avatar
shiqian committed
1315
1316
#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1317
  if (::testing::internal::AlwaysTrue()) { \
shiqian's avatar
shiqian committed
1318
    ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1319
    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
shiqian's avatar
shiqian committed
1320
1321
1322
1323
1324
    if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
      goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
    } \
  } else \
    GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1325
1326
1327
      fail("Expected: " #statement " doesn't generate new fatal " \
           "failures in the current thread.\n" \
           "  Actual: it does.")
shiqian's avatar
shiqian committed
1328

1329
1330
1331
1332
// Expands to the name of the class that implements the given test.
#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
  test_case_name##_##test_name##_Test

shiqian's avatar
shiqian committed
1333
// Helper macro for defining tests.
1334
#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
1335
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
shiqian's avatar
shiqian committed
1336
 public:\
1337
  GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
shiqian's avatar
shiqian committed
1338
1339
 private:\
  virtual void TestBody();\
1340
  static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
shiqian's avatar
shiqian committed
1341
  GTEST_DISALLOW_COPY_AND_ASSIGN_(\
1342
      GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
shiqian's avatar
shiqian committed
1343
1344
};\
\
1345
1346
1347
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
  ::test_info_ =\
    ::testing::internal::MakeAndRegisterTestInfo(\
1348
        #test_case_name, #test_name, NULL, NULL, \
kosak's avatar
kosak committed
1349
        ::testing::internal::CodeLocation(__FILE__, __LINE__), \
1350
        (parent_id), \
1351
1352
1353
        parent_class::SetUpTestCase, \
        parent_class::TearDownTestCase, \
        new ::testing::internal::TestFactoryImpl<\
1354
1355
            GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
shiqian's avatar
shiqian committed
1356
1357

#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_