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