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