1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // The Google C++ Testing and Mocking Framework (Google Test)
32 // This header file declares functions and macros used internally by
33 // Google Test. They are subject to change without notice.
35 // IWYU pragma: private, include "gtest/gtest.h"
36 // IWYU pragma: friend gtest/.*
37 // IWYU pragma: friend gmock/.*
39 #ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
40 #define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
42 #include "gtest/internal/gtest-port.h"
46 #include <sys/types.h>
49 #endif // GTEST_OS_LINUX
51 #if GTEST_HAS_EXCEPTIONS
66 #include <type_traits>
70 #include "gtest/gtest-message.h"
71 #include "gtest/internal/gtest-filepath.h"
72 #include "gtest/internal/gtest-string.h"
73 #include "gtest/internal/gtest-type-util.h"
75 // Due to C++ preprocessor weirdness, we need double indirection to
76 // concatenate two tokens when one of them is __LINE__. Writing
80 // will result in the token foo__LINE__, instead of foo followed by
81 // the current line number. For more details, see
82 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
83 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
84 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar
86 // Stringifies its argument.
87 // Work around a bug in visual studio which doesn't accept code like this:
89 // #define GTEST_STRINGIFY_(name) #name
90 // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
93 // Complaining about the argument to GTEST_STRINGIFY_ being empty.
94 // This is allowed by the spec.
95 #define GTEST_STRINGIFY_HELPER_(name, ...) #name
96 #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
104 // Forward declarations.
106 class AssertionResult
; // Result of an assertion.
107 class Message
; // Represents a failure message.
108 class Test
; // Represents a test.
109 class TestInfo
; // Information about a test.
110 class TestPartResult
; // Result of a test part.
111 class UnitTest
; // A collection of test suites.
113 template <typename T
>
114 ::std::string
PrintToString(const T
& value
);
118 struct TraceInfo
; // Information about a trace point.
119 class TestInfoImpl
; // Opaque implementation of TestInfo
120 class UnitTestImpl
; // Opaque implementation of UnitTest
122 // The text used in failure messages to indicate the start of the
124 GTEST_API_
extern const char kStackTraceMarker
[];
126 // An IgnoredValue object can be implicitly constructed from ANY value.
131 // This constructor template allows any value to be implicitly
132 // converted to IgnoredValue. The object has no data member and
133 // doesn't try to remember anything about the argument. We
134 // deliberately omit the 'explicit' keyword in order to allow the
135 // conversion to be implicit.
136 // Disable the conversion if T already has a magical conversion operator.
137 // Otherwise we get ambiguity.
138 template <typename T
,
139 typename
std::enable_if
<!std::is_convertible
<T
, Sink
>::value
,
141 IgnoredValue(const T
& /* ignored */) {} // NOLINT(runtime/explicit)
144 // Appends the user-supplied message to the Google-Test-generated message.
145 GTEST_API_
std::string
AppendUserMessage(const std::string
& gtest_msg
,
146 const Message
& user_msg
);
148 #if GTEST_HAS_EXCEPTIONS
150 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
151 4275 /* an exported class was derived from a class that was not exported */)
153 // This exception is thrown by (and only by) a failed Google Test
154 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
155 // are enabled). We derive it from std::runtime_error, which is for
156 // errors presumably detectable only at run time. Since
157 // std::runtime_error inherits from std::exception, many testing
158 // frameworks know how to extract and print the message inside it.
159 class GTEST_API_ GoogleTestFailureException
: public ::std::runtime_error
{
161 explicit GoogleTestFailureException(const TestPartResult
& failure
);
164 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
166 #endif // GTEST_HAS_EXCEPTIONS
168 namespace edit_distance
{
169 // Returns the optimal edits to go from 'left' to 'right'.
170 // All edits cost the same, with replace having lower priority than
172 // Simple implementation of the Wagner-Fischer algorithm.
173 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
174 enum EditType
{ kMatch
, kAdd
, kRemove
, kReplace
};
175 GTEST_API_
std::vector
<EditType
> CalculateOptimalEdits(
176 const std::vector
<size_t>& left
, const std::vector
<size_t>& right
);
178 // Same as above, but the input is represented as strings.
179 GTEST_API_
std::vector
<EditType
> CalculateOptimalEdits(
180 const std::vector
<std::string
>& left
,
181 const std::vector
<std::string
>& right
);
183 // Create a diff of the input strings in Unified diff format.
184 GTEST_API_
std::string
CreateUnifiedDiff(const std::vector
<std::string
>& left
,
185 const std::vector
<std::string
>& right
,
188 } // namespace edit_distance
190 // Constructs and returns the message for an equality assertion
191 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
193 // The first four parameters are the expressions used in the assertion
194 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
195 // where foo is 5 and bar is 6, we have:
197 // expected_expression: "foo"
198 // actual_expression: "bar"
199 // expected_value: "5"
202 // The ignoring_case parameter is true if and only if the assertion is a
203 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
204 // be inserted into the message.
205 GTEST_API_ AssertionResult
EqFailure(const char* expected_expression
,
206 const char* actual_expression
,
207 const std::string
& expected_value
,
208 const std::string
& actual_value
,
211 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
212 GTEST_API_
std::string
GetBoolAssertionFailureMessage(
213 const AssertionResult
& assertion_result
, const char* expression_text
,
214 const char* actual_predicate_value
, const char* expected_predicate_value
);
216 // This template class represents an IEEE floating-point number
217 // (either single-precision or double-precision, depending on the
218 // template parameters).
220 // The purpose of this class is to do more sophisticated number
221 // comparison. (Due to round-off error, etc, it's very unlikely that
222 // two floating-points will be equal exactly. Hence a naive
223 // comparison by the == operation often doesn't work.)
225 // Format of IEEE floating-point:
227 // The most-significant bit being the leftmost, an IEEE
228 // floating-point looks like
230 // sign_bit exponent_bits fraction_bits
232 // Here, sign_bit is a single bit that designates the sign of the
235 // For float, there are 8 exponent bits and 23 fraction bits.
237 // For double, there are 11 exponent bits and 52 fraction bits.
239 // More details can be found at
240 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
242 // Template parameter:
244 // RawType: the raw floating-point type (either float or double)
245 template <typename RawType
>
246 class FloatingPoint
{
248 // Defines the unsigned integer type that has the same size as the
249 // floating point number.
250 typedef typename TypeWithSize
<sizeof(RawType
)>::UInt Bits
;
254 // # of bits in a number.
255 static const size_t kBitCount
= 8 * sizeof(RawType
);
257 // # of fraction bits in a number.
258 static const size_t kFractionBitCount
=
259 std::numeric_limits
<RawType
>::digits
- 1;
261 // # of exponent bits in a number.
262 static const size_t kExponentBitCount
= kBitCount
- 1 - kFractionBitCount
;
264 // The mask for the sign bit.
265 static const Bits kSignBitMask
= static_cast<Bits
>(1) << (kBitCount
- 1);
267 // The mask for the fraction bits.
268 static const Bits kFractionBitMask
= ~static_cast<Bits
>(0) >>
269 (kExponentBitCount
+ 1);
271 // The mask for the exponent bits.
272 static const Bits kExponentBitMask
= ~(kSignBitMask
| kFractionBitMask
);
274 // How many ULP's (Units in the Last Place) we want to tolerate when
275 // comparing two numbers. The larger the value, the more error we
276 // allow. A 0 value means that two numbers must be exactly the same
277 // to be considered equal.
279 // The maximum error of a single floating-point operation is 0.5
280 // units in the last place. On Intel CPU's, all floating-point
281 // calculations are done with 80-bit precision, while double has 64
282 // bits. Therefore, 4 should be enough for ordinary use.
284 // See the following article for more details on ULP:
285 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
286 static const uint32_t kMaxUlps
= 4;
288 // Constructs a FloatingPoint from a raw floating-point number.
290 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
291 // around may change its bits, although the new value is guaranteed
292 // to be also a NAN. Therefore, don't expect this constructor to
293 // preserve the bits in x when x is a NAN.
294 explicit FloatingPoint(const RawType
& x
) { u_
.value_
= x
; }
298 // Reinterprets a bit pattern as a floating-point number.
300 // This function is needed to test the AlmostEquals() method.
301 static RawType
ReinterpretBits(const Bits bits
) {
307 // Returns the floating-point number that represent positive infinity.
308 static RawType
Infinity() { return ReinterpretBits(kExponentBitMask
); }
310 // Non-static methods
312 // Returns the bits that represents this number.
313 const Bits
& bits() const { return u_
.bits_
; }
315 // Returns the exponent bits of this number.
316 Bits
exponent_bits() const { return kExponentBitMask
& u_
.bits_
; }
318 // Returns the fraction bits of this number.
319 Bits
fraction_bits() const { return kFractionBitMask
& u_
.bits_
; }
321 // Returns the sign bit of this number.
322 Bits
sign_bit() const { return kSignBitMask
& u_
.bits_
; }
324 // Returns true if and only if this is NAN (not a number).
325 bool is_nan() const {
326 // It's a NAN if the exponent bits are all ones and the fraction
327 // bits are not entirely zeros.
328 return (exponent_bits() == kExponentBitMask
) && (fraction_bits() != 0);
331 // Returns true if and only if this number is at most kMaxUlps ULP's away
332 // from rhs. In particular, this function:
334 // - returns false if either number is (or both are) NAN.
335 // - treats really large numbers as almost equal to infinity.
336 // - thinks +0.0 and -0.0 are 0 DLP's apart.
337 bool AlmostEquals(const FloatingPoint
& rhs
) const {
338 // The IEEE standard says that any comparison operation involving
339 // a NAN must return false.
340 if (is_nan() || rhs
.is_nan()) return false;
342 return DistanceBetweenSignAndMagnitudeNumbers(u_
.bits_
, rhs
.u_
.bits_
) <=
347 // The data type used to store the actual floating-point number.
348 union FloatingPointUnion
{
349 RawType value_
; // The raw floating-point number.
350 Bits bits_
; // The bits that represent the number.
353 // Converts an integer from the sign-and-magnitude representation to
354 // the biased representation. More precisely, let N be 2 to the
355 // power of (kBitCount - 1), an integer x is represented by the
356 // unsigned number x + N.
360 // -N + 1 (the most negative number representable using
361 // sign-and-magnitude) is represented by 1;
362 // 0 is represented by N; and
363 // N - 1 (the biggest number representable using
364 // sign-and-magnitude) is represented by 2N - 1.
366 // Read http://en.wikipedia.org/wiki/Signed_number_representations
367 // for more details on signed number representations.
368 static Bits
SignAndMagnitudeToBiased(const Bits
& sam
) {
369 if (kSignBitMask
& sam
) {
370 // sam represents a negative number.
373 // sam represents a positive number.
374 return kSignBitMask
| sam
;
378 // Given two numbers in the sign-and-magnitude representation,
379 // returns the distance between them as an unsigned number.
380 static Bits
DistanceBetweenSignAndMagnitudeNumbers(const Bits
& sam1
,
382 const Bits biased1
= SignAndMagnitudeToBiased(sam1
);
383 const Bits biased2
= SignAndMagnitudeToBiased(sam2
);
384 return (biased1
>= biased2
) ? (biased1
- biased2
) : (biased2
- biased1
);
387 FloatingPointUnion u_
;
390 // Typedefs the instances of the FloatingPoint template class that we
392 typedef FloatingPoint
<float> Float
;
393 typedef FloatingPoint
<double> Double
;
395 // In order to catch the mistake of putting tests that use different
396 // test fixture classes in the same test suite, we need to assign
397 // unique IDs to fixture classes and compare them. The TypeId type is
398 // used to hold such IDs. The user should treat TypeId as an opaque
399 // type: the only operation allowed on TypeId values is to compare
400 // them for equality using the == operator.
401 typedef const void* TypeId
;
403 template <typename T
>
406 // dummy_ must not have a const type. Otherwise an overly eager
407 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
408 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
412 template <typename T
>
413 bool TypeIdHelper
<T
>::dummy_
= false;
415 // GetTypeId<T>() returns the ID of type T. Different values will be
416 // returned for different types. Calling the function twice with the
417 // same type argument is guaranteed to return the same ID.
418 template <typename T
>
420 // The compiler is required to allocate a different
421 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
422 // the template. Therefore, the address of dummy_ is guaranteed to
424 return &(TypeIdHelper
<T
>::dummy_
);
427 // Returns the type ID of ::testing::Test. Always call this instead
428 // of GetTypeId< ::testing::Test>() to get the type ID of
429 // ::testing::Test, as the latter may give the wrong result due to a
430 // suspected linker bug when compiling Google Test as a Mac OS X
432 GTEST_API_ TypeId
GetTestTypeId();
434 // Defines the abstract factory interface that creates instances
436 class TestFactoryBase
{
438 virtual ~TestFactoryBase() = default;
440 // Creates a test instance to run. The instance is both created and destroyed
441 // within TestInfoImpl::Run()
442 virtual Test
* CreateTest() = 0;
448 TestFactoryBase(const TestFactoryBase
&) = delete;
449 TestFactoryBase
& operator=(const TestFactoryBase
&) = delete;
452 // This class provides implementation of TestFactoryBase interface.
453 // It is used in TEST and TEST_F macros.
454 template <class TestClass
>
455 class TestFactoryImpl
: public TestFactoryBase
{
457 Test
* CreateTest() override
{ return new TestClass
; }
460 #ifdef GTEST_OS_WINDOWS
462 // Predicate-formatters for implementing the HRESULT checking macros
463 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
464 // We pass a long instead of HRESULT to avoid causing an
465 // include dependency for the HRESULT type.
466 GTEST_API_ AssertionResult
IsHRESULTSuccess(const char* expr
,
468 GTEST_API_ AssertionResult
IsHRESULTFailure(const char* expr
,
471 #endif // GTEST_OS_WINDOWS
473 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
474 using SetUpTestSuiteFunc
= void (*)();
475 using TearDownTestSuiteFunc
= void (*)();
477 struct CodeLocation
{
478 CodeLocation(const std::string
& a_file
, int a_line
)
479 : file(a_file
), line(a_line
) {}
485 // Helper to identify which setup function for TestCase / TestSuite to call.
486 // Only one function is allowed, either TestCase or TestSute but not both.
488 // Utility functions to help SuiteApiResolver
489 using SetUpTearDownSuiteFuncType
= void (*)();
491 inline SetUpTearDownSuiteFuncType
GetNotDefaultOrNull(
492 SetUpTearDownSuiteFuncType a
, SetUpTearDownSuiteFuncType def
) {
493 return a
== def
? nullptr : a
;
496 template <typename T
>
497 // Note that SuiteApiResolver inherits from T because
498 // SetUpTestSuite()/TearDownTestSuite() could be protected. This way
499 // SuiteApiResolver can access them.
500 struct SuiteApiResolver
: T
{
501 // testing::Test is only forward declared at this point. So we make it a
502 // dependent class for the compiler to be OK with it.
504 typename
std::conditional
<sizeof(T
) != 0, ::testing::Test
, void>::type
;
506 static SetUpTearDownSuiteFuncType
GetSetUpCaseOrSuite(const char* filename
,
508 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
509 SetUpTearDownSuiteFuncType test_case_fp
=
510 GetNotDefaultOrNull(&T::SetUpTestCase
, &Test::SetUpTestCase
);
511 SetUpTearDownSuiteFuncType test_suite_fp
=
512 GetNotDefaultOrNull(&T::SetUpTestSuite
, &Test::SetUpTestSuite
);
514 GTEST_CHECK_(!test_case_fp
|| !test_suite_fp
)
515 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
516 "make sure there is only one present at "
517 << filename
<< ":" << line_num
;
519 return test_case_fp
!= nullptr ? test_case_fp
: test_suite_fp
;
523 return &T::SetUpTestSuite
;
527 static SetUpTearDownSuiteFuncType
GetTearDownCaseOrSuite(const char* filename
,
529 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
530 SetUpTearDownSuiteFuncType test_case_fp
=
531 GetNotDefaultOrNull(&T::TearDownTestCase
, &Test::TearDownTestCase
);
532 SetUpTearDownSuiteFuncType test_suite_fp
=
533 GetNotDefaultOrNull(&T::TearDownTestSuite
, &Test::TearDownTestSuite
);
535 GTEST_CHECK_(!test_case_fp
|| !test_suite_fp
)
536 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
537 " please make sure there is only one present at"
538 << filename
<< ":" << line_num
;
540 return test_case_fp
!= nullptr ? test_case_fp
: test_suite_fp
;
544 return &T::TearDownTestSuite
;
549 // Creates a new TestInfo object and registers it with Google Test;
550 // returns the created object.
554 // test_suite_name: name of the test suite
555 // name: name of the test
556 // type_param: the name of the test's type parameter, or NULL if
557 // this is not a typed or a type-parameterized test.
558 // value_param: text representation of the test's value parameter,
559 // or NULL if this is not a type-parameterized test.
560 // code_location: code location where the test is defined
561 // fixture_class_id: ID of the test fixture class
562 // set_up_tc: pointer to the function that sets up the test suite
563 // tear_down_tc: pointer to the function that tears down the test suite
564 // factory: pointer to the factory that creates a test object.
565 // The newly created TestInfo instance will assume
566 // ownership of the factory object.
567 GTEST_API_ TestInfo
* MakeAndRegisterTestInfo(
568 const char* test_suite_name
, const char* name
, const char* type_param
,
569 const char* value_param
, CodeLocation code_location
,
570 TypeId fixture_class_id
, SetUpTestSuiteFunc set_up_tc
,
571 TearDownTestSuiteFunc tear_down_tc
, TestFactoryBase
* factory
);
573 // If *pstr starts with the given prefix, modifies *pstr to be right
574 // past the prefix and returns true; otherwise leaves *pstr unchanged
575 // and returns false. None of pstr, *pstr, and prefix can be NULL.
576 GTEST_API_
bool SkipPrefix(const char* prefix
, const char** pstr
);
578 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
579 /* class A needs to have dll-interface to be used by clients of class B */)
581 // State of the definition of a type-parameterized test suite.
582 class GTEST_API_ TypedTestSuitePState
{
584 TypedTestSuitePState() : registered_(false) {}
586 // Adds the given test name to defined_test_names_ and return true
587 // if the test suite hasn't been registered; otherwise aborts the
589 bool AddTestName(const char* file
, int line
, const char* case_name
,
590 const char* test_name
) {
593 "%s Test %s must be defined before "
594 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
595 FormatFileLocation(file
, line
).c_str(), test_name
, case_name
);
599 registered_tests_
.insert(
600 ::std::make_pair(test_name
, CodeLocation(file
, line
)));
604 bool TestExists(const std::string
& test_name
) const {
605 return registered_tests_
.count(test_name
) > 0;
608 const CodeLocation
& GetCodeLocation(const std::string
& test_name
) const {
609 RegisteredTestsMap::const_iterator it
= registered_tests_
.find(test_name
);
610 GTEST_CHECK_(it
!= registered_tests_
.end());
614 // Verifies that registered_tests match the test names in
615 // defined_test_names_; returns registered_tests if successful, or
616 // aborts the program otherwise.
617 const char* VerifyRegisteredTestNames(const char* test_suite_name
,
618 const char* file
, int line
,
619 const char* registered_tests
);
622 typedef ::std::map
<std::string
, CodeLocation
, std::less
<>> RegisteredTestsMap
;
625 RegisteredTestsMap registered_tests_
;
628 // Legacy API is deprecated but still available
629 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
630 using TypedTestCasePState
= TypedTestSuitePState
;
631 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
633 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
635 // Skips to the first non-space char after the first comma in 'str';
636 // returns NULL if no comma is found in 'str'.
637 inline const char* SkipComma(const char* str
) {
638 const char* comma
= strchr(str
, ',');
639 if (comma
== nullptr) {
642 while (IsSpace(*(++comma
))) {
647 // Returns the prefix of 'str' before the first comma in it; returns
648 // the entire string if it contains no comma.
649 inline std::string
GetPrefixUntilComma(const char* str
) {
650 const char* comma
= strchr(str
, ',');
651 return comma
== nullptr ? str
: std::string(str
, comma
);
654 // Splits a given string on a given delimiter, populating a given
655 // vector with the fields.
656 void SplitString(const ::std::string
& str
, char delimiter
,
657 ::std::vector
<::std::string
>* dest
);
659 // The default argument to the template below for the case when the user does
660 // not provide a name generator.
661 struct DefaultNameGenerator
{
662 template <typename T
>
663 static std::string
GetName(int i
) {
664 return StreamableToString(i
);
668 template <typename Provided
= DefaultNameGenerator
>
669 struct NameGeneratorSelector
{
670 typedef Provided type
;
673 template <typename NameGenerator
>
674 void GenerateNamesRecursively(internal::None
, std::vector
<std::string
>*, int) {}
676 template <typename NameGenerator
, typename Types
>
677 void GenerateNamesRecursively(Types
, std::vector
<std::string
>* result
, int i
) {
678 result
->push_back(NameGenerator::template GetName
<typename
Types::Head
>(i
));
679 GenerateNamesRecursively
<NameGenerator
>(typename
Types::Tail(), result
,
683 template <typename NameGenerator
, typename Types
>
684 std::vector
<std::string
> GenerateNames() {
685 std::vector
<std::string
> result
;
686 GenerateNamesRecursively
<NameGenerator
>(Types(), &result
, 0);
690 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
691 // registers a list of type-parameterized tests with Google Test. The
692 // return value is insignificant - we just need to return something
693 // such that we can call this function in a namespace scope.
695 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
696 // template parameter. It's defined in gtest-type-util.h.
697 template <GTEST_TEMPLATE_ Fixture
, class TestSel
, typename Types
>
698 class TypeParameterizedTest
{
700 // 'index' is the index of the test in the type list 'Types'
701 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
702 // Types). Valid values for 'index' are [0, N - 1] where N is the
704 static bool Register(const char* prefix
, const CodeLocation
& code_location
,
705 const char* case_name
, const char* test_names
, int index
,
706 const std::vector
<std::string
>& type_names
=
707 GenerateNames
<DefaultNameGenerator
, Types
>()) {
708 typedef typename
Types::Head Type
;
709 typedef Fixture
<Type
> FixtureClass
;
710 typedef typename
GTEST_BIND_(TestSel
, Type
) TestClass
;
712 // First, registers the first type-parameterized test in the type
714 MakeAndRegisterTestInfo(
715 (std::string(prefix
) + (prefix
[0] == '\0' ? "" : "/") + case_name
+
716 "/" + type_names
[static_cast<size_t>(index
)])
718 StripTrailingSpaces(GetPrefixUntilComma(test_names
)).c_str(),
719 GetTypeName
<Type
>().c_str(),
720 nullptr, // No value parameter.
721 code_location
, GetTypeId
<FixtureClass
>(),
722 SuiteApiResolver
<TestClass
>::GetSetUpCaseOrSuite(
723 code_location
.file
.c_str(), code_location
.line
),
724 SuiteApiResolver
<TestClass
>::GetTearDownCaseOrSuite(
725 code_location
.file
.c_str(), code_location
.line
),
726 new TestFactoryImpl
<TestClass
>);
728 // Next, recurses (at compile time) with the tail of the type list.
729 return TypeParameterizedTest
<Fixture
, TestSel
,
730 typename
Types::Tail
>::Register(prefix
,
739 // The base case for the compile time recursion.
740 template <GTEST_TEMPLATE_ Fixture
, class TestSel
>
741 class TypeParameterizedTest
<Fixture
, TestSel
, internal::None
> {
743 static bool Register(const char* /*prefix*/, const CodeLocation
&,
744 const char* /*case_name*/, const char* /*test_names*/,
746 const std::vector
<std::string
>& =
747 std::vector
<std::string
>() /*type_names*/) {
752 GTEST_API_
void RegisterTypeParameterizedTestSuite(const char* test_suite_name
,
753 CodeLocation code_location
);
754 GTEST_API_
void RegisterTypeParameterizedTestSuiteInstantiation(
755 const char* case_name
);
757 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
758 // registers *all combinations* of 'Tests' and 'Types' with Google
759 // Test. The return value is insignificant - we just need to return
760 // something such that we can call this function in a namespace scope.
761 template <GTEST_TEMPLATE_ Fixture
, typename Tests
, typename Types
>
762 class TypeParameterizedTestSuite
{
764 static bool Register(const char* prefix
, CodeLocation code_location
,
765 const TypedTestSuitePState
* state
, const char* case_name
,
766 const char* test_names
,
767 const std::vector
<std::string
>& type_names
=
768 GenerateNames
<DefaultNameGenerator
, Types
>()) {
769 RegisterTypeParameterizedTestSuiteInstantiation(case_name
);
770 std::string test_name
=
771 StripTrailingSpaces(GetPrefixUntilComma(test_names
));
772 if (!state
->TestExists(test_name
)) {
773 fprintf(stderr
, "Failed to get code location for test %s.%s at %s.",
774 case_name
, test_name
.c_str(),
775 FormatFileLocation(code_location
.file
.c_str(), code_location
.line
)
780 const CodeLocation
& test_location
= state
->GetCodeLocation(test_name
);
782 typedef typename
Tests::Head Head
;
784 // First, register the first test in 'Test' for each type in 'Types'.
785 TypeParameterizedTest
<Fixture
, Head
, Types
>::Register(
786 prefix
, test_location
, case_name
, test_names
, 0, type_names
);
788 // Next, recurses (at compile time) with the tail of the test list.
789 return TypeParameterizedTestSuite
<Fixture
, typename
Tests::Tail
,
790 Types
>::Register(prefix
, code_location
,
792 SkipComma(test_names
),
797 // The base case for the compile time recursion.
798 template <GTEST_TEMPLATE_ Fixture
, typename Types
>
799 class TypeParameterizedTestSuite
<Fixture
, internal::None
, Types
> {
801 static bool Register(const char* /*prefix*/, const CodeLocation
&,
802 const TypedTestSuitePState
* /*state*/,
803 const char* /*case_name*/, const char* /*test_names*/,
804 const std::vector
<std::string
>& =
805 std::vector
<std::string
>() /*type_names*/) {
810 // Returns the current OS stack trace as an std::string.
812 // The maximum number of stack frames to be included is specified by
813 // the gtest_stack_trace_depth flag. The skip_count parameter
814 // specifies the number of top frames to be skipped, which doesn't
815 // count against the number of frames to be included.
817 // For example, if Foo() calls Bar(), which in turn calls
818 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
819 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
820 GTEST_API_
std::string
GetCurrentOsStackTraceExceptTop(int skip_count
);
822 // Helpers for suppressing warnings on unreachable code or constant
825 // Always returns true.
826 GTEST_API_
bool AlwaysTrue();
828 // Always returns false.
829 inline bool AlwaysFalse() { return !AlwaysTrue(); }
831 // Helper for suppressing false warning from Clang on a const char*
832 // variable declared in a conditional expression always being NULL in
834 struct GTEST_API_ ConstCharPtr
{
835 ConstCharPtr(const char* str
) : value(str
) {}
836 operator bool() const { return true; }
840 // Helper for declaring std::string within 'if' statement
841 // in pre C++17 build environment.
842 struct TrueWithString
{
843 TrueWithString() = default;
844 explicit TrueWithString(const char* str
) : value(str
) {}
845 explicit TrueWithString(const std::string
& str
) : value(str
) {}
846 explicit operator bool() const { return true; }
850 // A simple Linear Congruential Generator for generating random
851 // numbers with a uniform distribution. Unlike rand() and srand(), it
852 // doesn't use global state (and therefore can't interfere with user
853 // code). Unlike rand_r(), it's portable. An LCG isn't very random,
854 // but it's good enough for our purposes.
855 class GTEST_API_ Random
{
857 static const uint32_t kMaxRange
= 1u << 31;
859 explicit Random(uint32_t seed
) : state_(seed
) {}
861 void Reseed(uint32_t seed
) { state_
= seed
; }
863 // Generates a random number from [0, range). Crashes if 'range' is
864 // 0 or greater than kMaxRange.
865 uint32_t Generate(uint32_t range
);
869 Random(const Random
&) = delete;
870 Random
& operator=(const Random
&) = delete;
873 // Turns const U&, U&, const U, and U all into U.
874 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
875 typename std::remove_const<typename std::remove_reference<T>::type>::type
877 // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
878 // that's true if and only if T has methods DebugString() and ShortDebugString()
879 // that return std::string.
880 template <typename T
>
881 class HasDebugStringAndShortDebugString
{
883 template <typename C
>
884 static auto CheckDebugString(C
*) -> typename
std::is_same
<
885 std::string
, decltype(std::declval
<const C
>().DebugString())>::type
;
887 static std::false_type
CheckDebugString(...);
889 template <typename C
>
890 static auto CheckShortDebugString(C
*) -> typename
std::is_same
<
891 std::string
, decltype(std::declval
<const C
>().ShortDebugString())>::type
;
893 static std::false_type
CheckShortDebugString(...);
895 using HasDebugStringType
= decltype(CheckDebugString
<T
>(nullptr));
896 using HasShortDebugStringType
= decltype(CheckShortDebugString
<T
>(nullptr));
899 static constexpr bool value
=
900 HasDebugStringType::value
&& HasShortDebugStringType::value
;
903 #ifdef GTEST_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
904 template <typename T
>
905 constexpr bool HasDebugStringAndShortDebugString
<T
>::value
;
908 // When the compiler sees expression IsContainerTest<C>(0), if C is an
909 // STL-style container class, the first overload of IsContainerTest
910 // will be viable (since both C::iterator* and C::const_iterator* are
911 // valid types and NULL can be implicitly converted to them). It will
912 // be picked over the second overload as 'int' is a perfect match for
913 // the type of argument 0. If C::iterator or C::const_iterator is not
914 // a valid type, the first overload is not viable, and the second
915 // overload will be picked. Therefore, we can determine whether C is
916 // a container class by checking the type of IsContainerTest<C>(0).
917 // The value of the expression is insignificant.
919 // In C++11 mode we check the existence of a const_iterator and that an
920 // iterator is properly implemented for the container.
922 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
923 // The reason is that C++ injects the name of a class as a member of the
924 // class itself (e.g. you can refer to class iterator as either
925 // 'iterator' or 'iterator::iterator'). If we look for C::iterator
926 // only, for example, we would mistakenly think that a class named
927 // iterator is an STL container.
929 // Also note that the simpler approach of overloading
930 // IsContainerTest(typename C::const_iterator*) and
931 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
932 typedef int IsContainer
;
934 class Iterator
= decltype(::std::declval
<const C
&>().begin()),
935 class = decltype(::std::declval
<const C
&>().end()),
936 class = decltype(++::std::declval
<Iterator
&>()),
937 class = decltype(*::std::declval
<Iterator
>()),
938 class = typename
C::const_iterator
>
939 IsContainer
IsContainerTest(int /* dummy */) {
943 typedef char IsNotContainer
;
945 IsNotContainer
IsContainerTest(long /* dummy */) {
949 // Trait to detect whether a type T is a hash table.
950 // The heuristic used is that the type contains an inner type `hasher` and does
951 // not contain an inner type `reverse_iterator`.
952 // If the container is iterable in reverse, then order might actually matter.
953 template <typename T
>
956 template <typename U
>
957 static char test(typename
U::hasher
*, typename
U::reverse_iterator
*);
958 template <typename U
>
959 static int test(typename
U::hasher
*, ...);
960 template <typename U
>
961 static char test(...);
964 static const bool value
= sizeof(test
<T
>(nullptr, nullptr)) == sizeof(int);
967 template <typename T
>
968 const bool IsHashTable
<T
>::value
;
970 template <typename C
,
971 bool = sizeof(IsContainerTest
<C
>(0)) == sizeof(IsContainer
)>
972 struct IsRecursiveContainerImpl
;
974 template <typename C
>
975 struct IsRecursiveContainerImpl
<C
, false> : public std::false_type
{};
977 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
978 // obey the same inconsistencies as the IsContainerTest, namely check if
979 // something is a container is relying on only const_iterator in C++11 and
980 // is relying on both const_iterator and iterator otherwise
981 template <typename C
>
982 struct IsRecursiveContainerImpl
<C
, true> {
983 using value_type
= decltype(*std::declval
<typename
C::const_iterator
>());
985 std::is_same
<typename
std::remove_const
<
986 typename
std::remove_reference
<value_type
>::type
>::type
,
990 // IsRecursiveContainer<Type> is a unary compile-time predicate that
991 // evaluates whether C is a recursive container type. A recursive container
992 // type is a container type whose value_type is equal to the container type
993 // itself. An example for a recursive container type is
994 // boost::filesystem::path, whose iterator has a value_type that is equal to
995 // boost::filesystem::path.
996 template <typename C
>
997 struct IsRecursiveContainer
: public IsRecursiveContainerImpl
<C
>::type
{};
999 // Utilities for native arrays.
1001 // ArrayEq() compares two k-dimensional native arrays using the
1002 // elements' operator==, where k can be any integer >= 0. When k is
1003 // 0, ArrayEq() degenerates into comparing a single pair of values.
1005 template <typename T
, typename U
>
1006 bool ArrayEq(const T
* lhs
, size_t size
, const U
* rhs
);
1008 // This generic version is used when k is 0.
1009 template <typename T
, typename U
>
1010 inline bool ArrayEq(const T
& lhs
, const U
& rhs
) {
1014 // This overload is used when k >= 1.
1015 template <typename T
, typename U
, size_t N
>
1016 inline bool ArrayEq(const T (&lhs
)[N
], const U (&rhs
)[N
]) {
1017 return internal::ArrayEq(lhs
, N
, rhs
);
1020 // This helper reduces code bloat. If we instead put its logic inside
1021 // the previous ArrayEq() function, arrays with different sizes would
1022 // lead to different copies of the template code.
1023 template <typename T
, typename U
>
1024 bool ArrayEq(const T
* lhs
, size_t size
, const U
* rhs
) {
1025 for (size_t i
= 0; i
!= size
; i
++) {
1026 if (!internal::ArrayEq(lhs
[i
], rhs
[i
])) return false;
1031 // Finds the first element in the iterator range [begin, end) that
1032 // equals elem. Element may be a native array type itself.
1033 template <typename Iter
, typename Element
>
1034 Iter
ArrayAwareFind(Iter begin
, Iter end
, const Element
& elem
) {
1035 for (Iter it
= begin
; it
!= end
; ++it
) {
1036 if (internal::ArrayEq(*it
, elem
)) return it
;
1041 // CopyArray() copies a k-dimensional native array using the elements'
1042 // operator=, where k can be any integer >= 0. When k is 0,
1043 // CopyArray() degenerates into copying a single value.
1045 template <typename T
, typename U
>
1046 void CopyArray(const T
* from
, size_t size
, U
* to
);
1048 // This generic version is used when k is 0.
1049 template <typename T
, typename U
>
1050 inline void CopyArray(const T
& from
, U
* to
) {
1054 // This overload is used when k >= 1.
1055 template <typename T
, typename U
, size_t N
>
1056 inline void CopyArray(const T (&from
)[N
], U (*to
)[N
]) {
1057 internal::CopyArray(from
, N
, *to
);
1060 // This helper reduces code bloat. If we instead put its logic inside
1061 // the previous CopyArray() function, arrays with different sizes
1062 // would lead to different copies of the template code.
1063 template <typename T
, typename U
>
1064 void CopyArray(const T
* from
, size_t size
, U
* to
) {
1065 for (size_t i
= 0; i
!= size
; i
++) {
1066 internal::CopyArray(from
[i
], to
+ i
);
1070 // The relation between an NativeArray object (see below) and the
1071 // native array it represents.
1072 // We use 2 different structs to allow non-copyable types to be used, as long
1073 // as RelationToSourceReference() is passed.
1074 struct RelationToSourceReference
{};
1075 struct RelationToSourceCopy
{};
1077 // Adapts a native array to a read-only STL-style container. Instead
1078 // of the complete STL container concept, this adaptor only implements
1079 // members useful for Google Mock's container matchers. New members
1080 // should be added as needed. To simplify the implementation, we only
1081 // support Element being a raw type (i.e. having no top-level const or
1082 // reference modifier). It's the client's responsibility to satisfy
1083 // this requirement. Element can be an array type itself (hence
1084 // multi-dimensional arrays are supported).
1085 template <typename Element
>
1088 // STL-style container typedefs.
1089 typedef Element value_type
;
1090 typedef Element
* iterator
;
1091 typedef const Element
* const_iterator
;
1093 // Constructs from a native array. References the source.
1094 NativeArray(const Element
* array
, size_t count
, RelationToSourceReference
) {
1095 InitRef(array
, count
);
1098 // Constructs from a native array. Copies the source.
1099 NativeArray(const Element
* array
, size_t count
, RelationToSourceCopy
) {
1100 InitCopy(array
, count
);
1103 // Copy constructor.
1104 NativeArray(const NativeArray
& rhs
) {
1105 (this->*rhs
.clone_
)(rhs
.array_
, rhs
.size_
);
1109 if (clone_
!= &NativeArray::InitRef
) delete[] array_
;
1112 // STL-style container methods.
1113 size_t size() const { return size_
; }
1114 const_iterator
begin() const { return array_
; }
1115 const_iterator
end() const { return array_
+ size_
; }
1116 bool operator==(const NativeArray
& rhs
) const {
1117 return size() == rhs
.size() && ArrayEq(begin(), size(), rhs
.begin());
1121 static_assert(!std::is_const
<Element
>::value
, "Type must not be const");
1122 static_assert(!std::is_reference
<Element
>::value
,
1123 "Type must not be a reference");
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
);
1131 clone_
= &NativeArray::InitCopy
;
1134 // Initializes this object with a reference of the input.
1135 void InitRef(const Element
* array
, size_t a_size
) {
1138 clone_
= &NativeArray::InitRef
;
1141 const Element
* array_
;
1143 void (NativeArray::*clone_
)(const Element
*, size_t);
1146 // Backport of std::index_sequence.
1147 template <size_t... Is
>
1148 struct IndexSequence
{
1149 using type
= IndexSequence
;
1152 // Double the IndexSequence, and one if plus_one is true.
1153 template <bool plus_one
, typename T
, size_t sizeofT
>
1154 struct DoubleSequence
;
1155 template <size_t... I
, size_t sizeofT
>
1156 struct DoubleSequence
<true, IndexSequence
<I
...>, sizeofT
> {
1157 using type
= IndexSequence
<I
..., (sizeofT
+ I
)..., 2 * sizeofT
>;
1159 template <size_t... I
, size_t sizeofT
>
1160 struct DoubleSequence
<false, IndexSequence
<I
...>, sizeofT
> {
1161 using type
= IndexSequence
<I
..., (sizeofT
+ I
)...>;
1164 // Backport of std::make_index_sequence.
1165 // It uses O(ln(N)) instantiation depth.
1167 struct MakeIndexSequenceImpl
1168 : DoubleSequence
<N
% 2 == 1, typename MakeIndexSequenceImpl
<N
/ 2>::type
,
1172 struct MakeIndexSequenceImpl
<0> : IndexSequence
<> {};
1175 using MakeIndexSequence
= typename MakeIndexSequenceImpl
<N
>::type
;
1177 template <typename
... T
>
1178 using IndexSequenceFor
= typename MakeIndexSequence
<sizeof...(T
)>::type
;
1182 Ignore(...); // NOLINT
1186 struct ElemFromListImpl
;
1187 template <size_t... I
>
1188 struct ElemFromListImpl
<IndexSequence
<I
...>> {
1189 // We make Ignore a template to solve a problem with MSVC.
1190 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
1191 // MSVC doesn't understand how to deal with that pack expansion.
1192 // Use `0 * I` to have a single instantiation of Ignore.
1193 template <typename R
>
1194 static R
Apply(Ignore
<0 * I
>..., R (*)(), ...);
1197 template <size_t N
, typename
... T
>
1198 struct ElemFromList
{
1200 decltype(ElemFromListImpl
<typename MakeIndexSequence
<N
>::type
>::Apply(
1201 static_cast<T (*)()>(nullptr)...));
1204 struct FlatTupleConstructTag
{};
1206 template <typename
... T
>
1209 template <typename Derived
, size_t I
>
1210 struct FlatTupleElemBase
;
1212 template <typename
... T
, size_t I
>
1213 struct FlatTupleElemBase
<FlatTuple
<T
...>, I
> {
1214 using value_type
= typename ElemFromList
<I
, T
...>::type
;
1215 FlatTupleElemBase() = default;
1216 template <typename Arg
>
1217 explicit FlatTupleElemBase(FlatTupleConstructTag
, Arg
&& t
)
1218 : value(std::forward
<Arg
>(t
)) {}
1222 template <typename Derived
, typename Idx
>
1223 struct FlatTupleBase
;
1225 template <size_t... Idx
, typename
... T
>
1226 struct FlatTupleBase
<FlatTuple
<T
...>, IndexSequence
<Idx
...>>
1227 : FlatTupleElemBase
<FlatTuple
<T
...>, Idx
>... {
1228 using Indices
= IndexSequence
<Idx
...>;
1229 FlatTupleBase() = default;
1230 template <typename
... Args
>
1231 explicit FlatTupleBase(FlatTupleConstructTag
, Args
&&... args
)
1232 : FlatTupleElemBase
<FlatTuple
<T
...>, Idx
>(FlatTupleConstructTag
{},
1233 std::forward
<Args
>(args
))... {}
1236 const typename ElemFromList
<I
, T
...>::type
& Get() const {
1237 return FlatTupleElemBase
<FlatTuple
<T
...>, I
>::value
;
1241 typename ElemFromList
<I
, T
...>::type
& Get() {
1242 return FlatTupleElemBase
<FlatTuple
<T
...>, I
>::value
;
1245 template <typename F
>
1246 auto Apply(F
&& f
) -> decltype(std::forward
<F
>(f
)(this->Get
<Idx
>()...)) {
1247 return std::forward
<F
>(f
)(Get
<Idx
>()...);
1250 template <typename F
>
1251 auto Apply(F
&& f
) const -> decltype(std::forward
<F
>(f
)(this->Get
<Idx
>()...)) {
1252 return std::forward
<F
>(f
)(Get
<Idx
>()...);
1256 // Analog to std::tuple but with different tradeoffs.
1257 // This class minimizes the template instantiation depth, thus allowing more
1258 // elements than std::tuple would. std::tuple has been seen to require an
1259 // instantiation depth of more than 10x the number of elements in some
1261 // FlatTuple and ElemFromList are not recursive and have a fixed depth
1262 // regardless of T...
1263 // MakeIndexSequence, on the other hand, it is recursive but with an
1264 // instantiation depth of O(ln(N)).
1265 template <typename
... T
>
1267 : private FlatTupleBase
<FlatTuple
<T
...>,
1268 typename MakeIndexSequence
<sizeof...(T
)>::type
> {
1269 using Indices
= typename FlatTupleBase
<
1270 FlatTuple
<T
...>, typename MakeIndexSequence
<sizeof...(T
)>::type
>::Indices
;
1273 FlatTuple() = default;
1274 template <typename
... Args
>
1275 explicit FlatTuple(FlatTupleConstructTag tag
, Args
&&... args
)
1276 : FlatTuple::FlatTupleBase(tag
, std::forward
<Args
>(args
)...) {}
1278 using FlatTuple::FlatTupleBase::Apply
;
1279 using FlatTuple::FlatTupleBase::Get
;
1282 // Utility functions to be called with static_assert to induce deprecation
1284 GTEST_INTERNAL_DEPRECATED(
1285 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
1286 "INSTANTIATE_TEST_SUITE_P")
1287 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
1289 GTEST_INTERNAL_DEPRECATED(
1290 "TYPED_TEST_CASE_P is deprecated, please use "
1291 "TYPED_TEST_SUITE_P")
1292 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
1294 GTEST_INTERNAL_DEPRECATED(
1295 "TYPED_TEST_CASE is deprecated, please use "
1297 constexpr bool TypedTestCaseIsDeprecated() { return true; }
1299 GTEST_INTERNAL_DEPRECATED(
1300 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
1301 "REGISTER_TYPED_TEST_SUITE_P")
1302 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
1304 GTEST_INTERNAL_DEPRECATED(
1305 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
1306 "INSTANTIATE_TYPED_TEST_SUITE_P")
1307 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
1309 } // namespace internal
1310 } // namespace testing
1313 // Some standard library implementations use `struct tuple_size` and some use
1314 // `class tuple_size`. Clang warns about the mismatch.
1315 // https://reviews.llvm.org/D55466
1317 #pragma clang diagnostic push
1318 #pragma clang diagnostic ignored "-Wmismatched-tags"
1320 template <typename
... Ts
>
1321 struct tuple_size
<testing::internal::FlatTuple
<Ts
...>>
1322 : std::integral_constant
<size_t, sizeof...(Ts
)> {};
1324 #pragma clang diagnostic pop
1328 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1329 ::testing::internal::AssertHelper(result_type, file, line, message) = \
1330 ::testing::Message()
1332 #define GTEST_MESSAGE_(message, result_type) \
1333 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1335 #define GTEST_FATAL_FAILURE_(message) \
1336 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1338 #define GTEST_NONFATAL_FAILURE_(message) \
1339 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1341 #define GTEST_SUCCESS_(message) \
1342 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1344 #define GTEST_SKIP_(message) \
1345 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
1347 // Suppress MSVC warning 4072 (unreachable code) for the code following
1348 // statement if it returns or throws (or doesn't return or throw in some
1350 // NOTE: The "else" is important to keep this expansion to prevent a top-level
1351 // "else" from attaching to our "if".
1352 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1353 if (::testing::internal::AlwaysTrue()) { \
1355 } else /* NOLINT */ \
1356 static_assert(true, "") // User must have a semicolon after expansion.
1358 #if GTEST_HAS_EXCEPTIONS
1361 namespace internal
{
1365 const char* what() const noexcept
{
1366 return "this exception should never be thrown";
1370 } // namespace internal
1371 } // namespace testing
1375 #define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
1377 #else // GTEST_HAS_RTTI
1379 #define GTEST_EXCEPTION_TYPE_(e) \
1380 std::string { "an std::exception-derived error" }
1382 #endif // GTEST_HAS_RTTI
1384 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
1385 catch (typename std::conditional< \
1386 std::is_same<typename std::remove_cv<typename std::remove_reference< \
1387 expected_exception>::type>::type, \
1388 std::exception>::value, \
1389 const ::testing::internal::NeverThrown&, const std::exception&>::type \
1391 gtest_msg.value = "Expected: " #statement \
1392 " throws an exception of type " #expected_exception \
1393 ".\n Actual: it throws "; \
1394 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
1395 gtest_msg.value += " with description \""; \
1396 gtest_msg.value += e.what(); \
1397 gtest_msg.value += "\"."; \
1398 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1401 #else // GTEST_HAS_EXCEPTIONS
1403 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
1405 #endif // GTEST_HAS_EXCEPTIONS
1407 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1408 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1409 if (::testing::internal::TrueWithString gtest_msg{}) { \
1410 bool gtest_caught_expected = false; \
1412 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1413 } catch (expected_exception const&) { \
1414 gtest_caught_expected = true; \
1416 GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
1418 gtest_msg.value = "Expected: " #statement \
1419 " throws an exception of type " #expected_exception \
1420 ".\n Actual: it throws a different type."; \
1421 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1423 if (!gtest_caught_expected) { \
1424 gtest_msg.value = "Expected: " #statement \
1425 " throws an exception of type " #expected_exception \
1426 ".\n Actual: it throws nothing."; \
1427 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1430 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
1431 : fail(gtest_msg.value.c_str())
1433 #if GTEST_HAS_EXCEPTIONS
1435 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
1436 catch (std::exception const& e) { \
1437 gtest_msg.value = "it throws "; \
1438 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
1439 gtest_msg.value += " with description \""; \
1440 gtest_msg.value += e.what(); \
1441 gtest_msg.value += "\"."; \
1442 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1445 #else // GTEST_HAS_EXCEPTIONS
1447 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
1449 #endif // GTEST_HAS_EXCEPTIONS
1451 #define GTEST_TEST_NO_THROW_(statement, fail) \
1452 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1453 if (::testing::internal::TrueWithString gtest_msg{}) { \
1455 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1457 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
1459 gtest_msg.value = "it throws."; \
1460 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1463 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \
1464 : fail(("Expected: " #statement " doesn't throw an exception.\n" \
1469 #define GTEST_TEST_ANY_THROW_(statement, fail) \
1470 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1471 if (::testing::internal::AlwaysTrue()) { \
1472 bool gtest_caught_any = false; \
1474 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1476 gtest_caught_any = true; \
1478 if (!gtest_caught_any) { \
1479 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1482 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \
1483 : fail("Expected: " #statement \
1484 " throws an exception.\n" \
1485 " Actual: it doesn't.")
1487 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1488 // either a boolean expression or an AssertionResult. text is a textual
1489 // representation of expression as it was passed into the EXPECT_TRUE.
1490 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1491 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1492 if (const ::testing::AssertionResult gtest_ar_ = \
1493 ::testing::AssertionResult(expression)) \
1496 fail(::testing::internal::GetBoolAssertionFailureMessage( \
1497 gtest_ar_, text, #actual, #expected) \
1500 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1501 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1502 if (::testing::internal::AlwaysTrue()) { \
1503 const ::testing::internal::HasNewFatalFailureHelper \
1504 gtest_fatal_failure_checker; \
1505 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1506 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1507 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1509 } else /* NOLINT */ \
1510 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \
1511 : fail("Expected: " #statement \
1512 " doesn't generate new fatal " \
1513 "failures in the current thread.\n" \
1514 " Actual: it does.")
1516 // Expands to the name of the class that implements the given test.
1517 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1518 test_suite_name##_##test_name##_Test
1520 // Helper macro for defining tests.
1521 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
1522 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
1523 "test_suite_name must not be empty"); \
1524 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
1525 "test_name must not be empty"); \
1526 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1527 : public parent_class { \
1529 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
1530 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
1531 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1532 (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete; \
1533 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \
1534 const GTEST_TEST_CLASS_NAME_(test_suite_name, \
1535 test_name) &) = delete; /* NOLINT */ \
1536 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1537 (GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &&) noexcept = delete; \
1538 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=( \
1539 GTEST_TEST_CLASS_NAME_(test_suite_name, \
1540 test_name) &&) noexcept = delete; /* NOLINT */ \
1543 void TestBody() override; \
1544 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
1547 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
1548 test_name)::test_info_ = \
1549 ::testing::internal::MakeAndRegisterTestInfo( \
1550 #test_suite_name, #test_name, nullptr, nullptr, \
1551 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
1552 ::testing::internal::SuiteApiResolver< \
1553 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
1554 ::testing::internal::SuiteApiResolver< \
1555 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
1556 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
1557 test_suite_name, test_name)>); \
1558 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
1560 #endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_