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 // GOOGLETEST_CM0001 DO NOT DELETE
37 #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
38 #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
40 #include "gtest/internal/gtest-port.h"
44 # include <sys/types.h>
45 # include <sys/wait.h>
47 #endif // GTEST_OS_LINUX
49 #if GTEST_HAS_EXCEPTIONS
62 #include <type_traits>
65 #include "gtest/gtest-message.h"
66 #include "gtest/internal/gtest-filepath.h"
67 #include "gtest/internal/gtest-string.h"
68 #include "gtest/internal/gtest-type-util.h"
70 // Due to C++ preprocessor weirdness, we need double indirection to
71 // concatenate two tokens when one of them is __LINE__. Writing
75 // will result in the token foo__LINE__, instead of foo followed by
76 // the current line number. For more details, see
77 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
78 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
79 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
81 // Stringifies its argument.
82 // Work around a bug in visual studio which doesn't accept code like this:
84 // #define GTEST_STRINGIFY_(name) #name
85 // #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...
88 // Complaining about the argument to GTEST_STRINGIFY_ being empty.
89 // This is allowed by the spec.
90 #define GTEST_STRINGIFY_HELPER_(name, ...) #name
91 #define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
99 // Forward declarations.
101 class AssertionResult
; // Result of an assertion.
102 class Message
; // Represents a failure message.
103 class Test
; // Represents a test.
104 class TestInfo
; // Information about a test.
105 class TestPartResult
; // Result of a test part.
106 class UnitTest
; // A collection of test suites.
108 template <typename T
>
109 ::std::string
PrintToString(const T
& value
);
113 struct TraceInfo
; // Information about a trace point.
114 class TestInfoImpl
; // Opaque implementation of TestInfo
115 class UnitTestImpl
; // Opaque implementation of UnitTest
117 // The text used in failure messages to indicate the start of the
119 GTEST_API_
extern const char kStackTraceMarker
[];
121 // An IgnoredValue object can be implicitly constructed from ANY value.
125 // This constructor template allows any value to be implicitly
126 // converted to IgnoredValue. The object has no data member and
127 // doesn't try to remember anything about the argument. We
128 // deliberately omit the 'explicit' keyword in order to allow the
129 // conversion to be implicit.
130 // Disable the conversion if T already has a magical conversion operator.
131 // Otherwise we get ambiguity.
132 template <typename T
,
133 typename
std::enable_if
<!std::is_convertible
<T
, Sink
>::value
,
135 IgnoredValue(const T
& /* ignored */) {} // NOLINT(runtime/explicit)
138 // Appends the user-supplied message to the Google-Test-generated message.
139 GTEST_API_
std::string
AppendUserMessage(
140 const std::string
& gtest_msg
, const Message
& user_msg
);
142 #if GTEST_HAS_EXCEPTIONS
144 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
145 /* an exported class was derived from a class that was not exported */)
147 // This exception is thrown by (and only by) a failed Google Test
148 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
149 // are enabled). We derive it from std::runtime_error, which is for
150 // errors presumably detectable only at run time. Since
151 // std::runtime_error inherits from std::exception, many testing
152 // frameworks know how to extract and print the message inside it.
153 class GTEST_API_ GoogleTestFailureException
: public ::std::runtime_error
{
155 explicit GoogleTestFailureException(const TestPartResult
& failure
);
158 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
160 #endif // GTEST_HAS_EXCEPTIONS
162 namespace edit_distance
{
163 // Returns the optimal edits to go from 'left' to 'right'.
164 // All edits cost the same, with replace having lower priority than
166 // Simple implementation of the Wagner-Fischer algorithm.
167 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
168 enum EditType
{ kMatch
, kAdd
, kRemove
, kReplace
};
169 GTEST_API_
std::vector
<EditType
> CalculateOptimalEdits(
170 const std::vector
<size_t>& left
, const std::vector
<size_t>& right
);
172 // Same as above, but the input is represented as strings.
173 GTEST_API_
std::vector
<EditType
> CalculateOptimalEdits(
174 const std::vector
<std::string
>& left
,
175 const std::vector
<std::string
>& right
);
177 // Create a diff of the input strings in Unified diff format.
178 GTEST_API_
std::string
CreateUnifiedDiff(const std::vector
<std::string
>& left
,
179 const std::vector
<std::string
>& right
,
182 } // namespace edit_distance
184 // Calculate the diff between 'left' and 'right' and return it in unified diff
186 // If not null, stores in 'total_line_count' the total number of lines found
188 GTEST_API_
std::string
DiffStrings(const std::string
& left
,
189 const std::string
& right
,
190 size_t* total_line_count
);
192 // Constructs and returns the message for an equality assertion
193 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
195 // The first four parameters are the expressions used in the assertion
196 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
197 // where foo is 5 and bar is 6, we have:
199 // expected_expression: "foo"
200 // actual_expression: "bar"
201 // expected_value: "5"
204 // The ignoring_case parameter is true if and only if the assertion is a
205 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
206 // be inserted into the message.
207 GTEST_API_ AssertionResult
EqFailure(const char* expected_expression
,
208 const char* actual_expression
,
209 const std::string
& expected_value
,
210 const std::string
& actual_value
,
213 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
214 GTEST_API_
std::string
GetBoolAssertionFailureMessage(
215 const AssertionResult
& assertion_result
,
216 const char* expression_text
,
217 const char* actual_predicate_value
,
218 const char* expected_predicate_value
);
220 // This template class represents an IEEE floating-point number
221 // (either single-precision or double-precision, depending on the
222 // template parameters).
224 // The purpose of this class is to do more sophisticated number
225 // comparison. (Due to round-off error, etc, it's very unlikely that
226 // two floating-points will be equal exactly. Hence a naive
227 // comparison by the == operation often doesn't work.)
229 // Format of IEEE floating-point:
231 // The most-significant bit being the leftmost, an IEEE
232 // floating-point looks like
234 // sign_bit exponent_bits fraction_bits
236 // Here, sign_bit is a single bit that designates the sign of the
239 // For float, there are 8 exponent bits and 23 fraction bits.
241 // For double, there are 11 exponent bits and 52 fraction bits.
243 // More details can be found at
244 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
246 // Template parameter:
248 // RawType: the raw floating-point type (either float or double)
249 template <typename RawType
>
250 class FloatingPoint
{
252 // Defines the unsigned integer type that has the same size as the
253 // floating point number.
254 typedef typename TypeWithSize
<sizeof(RawType
)>::UInt Bits
;
258 // # of bits in a number.
259 static const size_t kBitCount
= 8*sizeof(RawType
);
261 // # of fraction bits in a number.
262 static const size_t kFractionBitCount
=
263 std::numeric_limits
<RawType
>::digits
- 1;
265 // # of exponent bits in a number.
266 static const size_t kExponentBitCount
= kBitCount
- 1 - kFractionBitCount
;
268 // The mask for the sign bit.
269 static const Bits kSignBitMask
= static_cast<Bits
>(1) << (kBitCount
- 1);
271 // The mask for the fraction bits.
272 static const Bits kFractionBitMask
=
273 ~static_cast<Bits
>(0) >> (kExponentBitCount
+ 1);
275 // The mask for the exponent bits.
276 static const Bits kExponentBitMask
= ~(kSignBitMask
| kFractionBitMask
);
278 // How many ULP's (Units in the Last Place) we want to tolerate when
279 // comparing two numbers. The larger the value, the more error we
280 // allow. A 0 value means that two numbers must be exactly the same
281 // to be considered equal.
283 // The maximum error of a single floating-point operation is 0.5
284 // units in the last place. On Intel CPU's, all floating-point
285 // calculations are done with 80-bit precision, while double has 64
286 // bits. Therefore, 4 should be enough for ordinary use.
288 // See the following article for more details on ULP:
289 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
290 static const uint32_t kMaxUlps
= 4;
292 // Constructs a FloatingPoint from a raw floating-point number.
294 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
295 // around may change its bits, although the new value is guaranteed
296 // to be also a NAN. Therefore, don't expect this constructor to
297 // preserve the bits in x when x is a NAN.
298 explicit FloatingPoint(const RawType
& x
) { u_
.value_
= x
; }
302 // Reinterprets a bit pattern as a floating-point number.
304 // This function is needed to test the AlmostEquals() method.
305 static RawType
ReinterpretBits(const Bits bits
) {
311 // Returns the floating-point number that represent positive infinity.
312 static RawType
Infinity() {
313 return ReinterpretBits(kExponentBitMask
);
316 // Returns the maximum representable finite floating-point number.
317 static RawType
Max();
319 // Non-static methods
321 // Returns the bits that represents this number.
322 const Bits
&bits() const { return u_
.bits_
; }
324 // Returns the exponent bits of this number.
325 Bits
exponent_bits() const { return kExponentBitMask
& u_
.bits_
; }
327 // Returns the fraction bits of this number.
328 Bits
fraction_bits() const { return kFractionBitMask
& u_
.bits_
; }
330 // Returns the sign bit of this number.
331 Bits
sign_bit() const { return kSignBitMask
& u_
.bits_
; }
333 // Returns true if and only if this is NAN (not a number).
334 bool is_nan() const {
335 // It's a NAN if the exponent bits are all ones and the fraction
336 // bits are not entirely zeros.
337 return (exponent_bits() == kExponentBitMask
) && (fraction_bits() != 0);
340 // Returns true if and only if this number is at most kMaxUlps ULP's away
341 // from rhs. In particular, this function:
343 // - returns false if either number is (or both are) NAN.
344 // - treats really large numbers as almost equal to infinity.
345 // - thinks +0.0 and -0.0 are 0 DLP's apart.
346 bool AlmostEquals(const FloatingPoint
& rhs
) const {
347 // The IEEE standard says that any comparison operation involving
348 // a NAN must return false.
349 if (is_nan() || rhs
.is_nan()) return false;
351 return DistanceBetweenSignAndMagnitudeNumbers(u_
.bits_
, rhs
.u_
.bits_
)
356 // The data type used to store the actual floating-point number.
357 union FloatingPointUnion
{
358 RawType value_
; // The raw floating-point number.
359 Bits bits_
; // The bits that represent the number.
362 // Converts an integer from the sign-and-magnitude representation to
363 // the biased representation. More precisely, let N be 2 to the
364 // power of (kBitCount - 1), an integer x is represented by the
365 // unsigned number x + N.
369 // -N + 1 (the most negative number representable using
370 // sign-and-magnitude) is represented by 1;
371 // 0 is represented by N; and
372 // N - 1 (the biggest number representable using
373 // sign-and-magnitude) is represented by 2N - 1.
375 // Read http://en.wikipedia.org/wiki/Signed_number_representations
376 // for more details on signed number representations.
377 static Bits
SignAndMagnitudeToBiased(const Bits
&sam
) {
378 if (kSignBitMask
& sam
) {
379 // sam represents a negative number.
382 // sam represents a positive number.
383 return kSignBitMask
| sam
;
387 // Given two numbers in the sign-and-magnitude representation,
388 // returns the distance between them as an unsigned number.
389 static Bits
DistanceBetweenSignAndMagnitudeNumbers(const Bits
&sam1
,
391 const Bits biased1
= SignAndMagnitudeToBiased(sam1
);
392 const Bits biased2
= SignAndMagnitudeToBiased(sam2
);
393 return (biased1
>= biased2
) ? (biased1
- biased2
) : (biased2
- biased1
);
396 FloatingPointUnion u_
;
399 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
400 // macro defined by <windows.h>.
402 inline float FloatingPoint
<float>::Max() { return FLT_MAX
; }
404 inline double FloatingPoint
<double>::Max() { return DBL_MAX
; }
406 // Typedefs the instances of the FloatingPoint template class that we
408 typedef FloatingPoint
<float> Float
;
409 typedef FloatingPoint
<double> Double
;
411 // In order to catch the mistake of putting tests that use different
412 // test fixture classes in the same test suite, we need to assign
413 // unique IDs to fixture classes and compare them. The TypeId type is
414 // used to hold such IDs. The user should treat TypeId as an opaque
415 // type: the only operation allowed on TypeId values is to compare
416 // them for equality using the == operator.
417 typedef const void* TypeId
;
419 template <typename T
>
422 // dummy_ must not have a const type. Otherwise an overly eager
423 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
424 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
428 template <typename T
>
429 bool TypeIdHelper
<T
>::dummy_
= false;
431 // GetTypeId<T>() returns the ID of type T. Different values will be
432 // returned for different types. Calling the function twice with the
433 // same type argument is guaranteed to return the same ID.
434 template <typename T
>
436 // The compiler is required to allocate a different
437 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
438 // the template. Therefore, the address of dummy_ is guaranteed to
440 return &(TypeIdHelper
<T
>::dummy_
);
443 // Returns the type ID of ::testing::Test. Always call this instead
444 // of GetTypeId< ::testing::Test>() to get the type ID of
445 // ::testing::Test, as the latter may give the wrong result due to a
446 // suspected linker bug when compiling Google Test as a Mac OS X
448 GTEST_API_ TypeId
GetTestTypeId();
450 // Defines the abstract factory interface that creates instances
452 class TestFactoryBase
{
454 virtual ~TestFactoryBase() {}
456 // Creates a test instance to run. The instance is both created and destroyed
457 // within TestInfoImpl::Run()
458 virtual Test
* CreateTest() = 0;
464 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase
);
467 // This class provides implementation of TeastFactoryBase interface.
468 // It is used in TEST and TEST_F macros.
469 template <class TestClass
>
470 class TestFactoryImpl
: public TestFactoryBase
{
472 Test
* CreateTest() override
{ return new TestClass
; }
477 // Predicate-formatters for implementing the HRESULT checking macros
478 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
479 // We pass a long instead of HRESULT to avoid causing an
480 // include dependency for the HRESULT type.
481 GTEST_API_ AssertionResult
IsHRESULTSuccess(const char* expr
,
483 GTEST_API_ AssertionResult
IsHRESULTFailure(const char* expr
,
486 #endif // GTEST_OS_WINDOWS
488 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
489 using SetUpTestSuiteFunc
= void (*)();
490 using TearDownTestSuiteFunc
= void (*)();
492 struct CodeLocation
{
493 CodeLocation(const std::string
& a_file
, int a_line
)
494 : file(a_file
), line(a_line
) {}
500 // Helper to identify which setup function for TestCase / TestSuite to call.
501 // Only one function is allowed, either TestCase or TestSute but not both.
503 // Utility functions to help SuiteApiResolver
504 using SetUpTearDownSuiteFuncType
= void (*)();
506 inline SetUpTearDownSuiteFuncType
GetNotDefaultOrNull(
507 SetUpTearDownSuiteFuncType a
, SetUpTearDownSuiteFuncType def
) {
508 return a
== def
? nullptr : a
;
511 template <typename T
>
512 // Note that SuiteApiResolver inherits from T because
513 // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
514 // SuiteApiResolver can access them.
515 struct SuiteApiResolver
: T
{
516 // testing::Test is only forward declared at this point. So we make it a
517 // dependend class for the compiler to be OK with it.
519 typename
std::conditional
<sizeof(T
) != 0, ::testing::Test
, void>::type
;
521 static SetUpTearDownSuiteFuncType
GetSetUpCaseOrSuite(const char* filename
,
523 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
524 SetUpTearDownSuiteFuncType test_case_fp
=
525 GetNotDefaultOrNull(&T::SetUpTestCase
, &Test::SetUpTestCase
);
526 SetUpTearDownSuiteFuncType test_suite_fp
=
527 GetNotDefaultOrNull(&T::SetUpTestSuite
, &Test::SetUpTestSuite
);
529 GTEST_CHECK_(!test_case_fp
|| !test_suite_fp
)
530 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
531 "make sure there is only one present at "
532 << filename
<< ":" << line_num
;
534 return test_case_fp
!= nullptr ? test_case_fp
: test_suite_fp
;
538 return &T::SetUpTestSuite
;
542 static SetUpTearDownSuiteFuncType
GetTearDownCaseOrSuite(const char* filename
,
544 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
545 SetUpTearDownSuiteFuncType test_case_fp
=
546 GetNotDefaultOrNull(&T::TearDownTestCase
, &Test::TearDownTestCase
);
547 SetUpTearDownSuiteFuncType test_suite_fp
=
548 GetNotDefaultOrNull(&T::TearDownTestSuite
, &Test::TearDownTestSuite
);
550 GTEST_CHECK_(!test_case_fp
|| !test_suite_fp
)
551 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
552 " please make sure there is only one present at"
553 << filename
<< ":" << line_num
;
555 return test_case_fp
!= nullptr ? test_case_fp
: test_suite_fp
;
559 return &T::TearDownTestSuite
;
564 // Creates a new TestInfo object and registers it with Google Test;
565 // returns the created object.
569 // test_suite_name: name of the test suite
570 // name: name of the test
571 // type_param: the name of the test's type parameter, or NULL if
572 // this is not a typed or a type-parameterized test.
573 // value_param: text representation of the test's value parameter,
574 // or NULL if this is not a type-parameterized test.
575 // code_location: code location where the test is defined
576 // fixture_class_id: ID of the test fixture class
577 // set_up_tc: pointer to the function that sets up the test suite
578 // tear_down_tc: pointer to the function that tears down the test suite
579 // factory: pointer to the factory that creates a test object.
580 // The newly created TestInfo instance will assume
581 // ownership of the factory object.
582 GTEST_API_ TestInfo
* MakeAndRegisterTestInfo(
583 const char* test_suite_name
, const char* name
, const char* type_param
,
584 const char* value_param
, CodeLocation code_location
,
585 TypeId fixture_class_id
, SetUpTestSuiteFunc set_up_tc
,
586 TearDownTestSuiteFunc tear_down_tc
, TestFactoryBase
* factory
);
588 // If *pstr starts with the given prefix, modifies *pstr to be right
589 // past the prefix and returns true; otherwise leaves *pstr unchanged
590 // and returns false. None of pstr, *pstr, and prefix can be NULL.
591 GTEST_API_
bool SkipPrefix(const char* prefix
, const char** pstr
);
593 #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
595 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
596 /* class A needs to have dll-interface to be used by clients of class B */)
598 // State of the definition of a type-parameterized test suite.
599 class GTEST_API_ TypedTestSuitePState
{
601 TypedTestSuitePState() : registered_(false) {}
603 // Adds the given test name to defined_test_names_ and return true
604 // if the test suite hasn't been registered; otherwise aborts the
606 bool AddTestName(const char* file
, int line
, const char* case_name
,
607 const char* test_name
) {
610 "%s Test %s must be defined before "
611 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
612 FormatFileLocation(file
, line
).c_str(), test_name
, case_name
);
616 registered_tests_
.insert(
617 ::std::make_pair(test_name
, CodeLocation(file
, line
)));
621 bool TestExists(const std::string
& test_name
) const {
622 return registered_tests_
.count(test_name
) > 0;
625 const CodeLocation
& GetCodeLocation(const std::string
& test_name
) const {
626 RegisteredTestsMap::const_iterator it
= registered_tests_
.find(test_name
);
627 GTEST_CHECK_(it
!= registered_tests_
.end());
631 // Verifies that registered_tests match the test names in
632 // defined_test_names_; returns registered_tests if successful, or
633 // aborts the program otherwise.
634 const char* VerifyRegisteredTestNames(const char* test_suite_name
,
635 const char* file
, int line
,
636 const char* registered_tests
);
639 typedef ::std::map
<std::string
, CodeLocation
> RegisteredTestsMap
;
642 RegisteredTestsMap registered_tests_
;
645 // Legacy API is deprecated but still available
646 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
647 using TypedTestCasePState
= TypedTestSuitePState
;
648 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
650 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
652 // Skips to the first non-space char after the first comma in 'str';
653 // returns NULL if no comma is found in 'str'.
654 inline const char* SkipComma(const char* str
) {
655 const char* comma
= strchr(str
, ',');
656 if (comma
== nullptr) {
659 while (IsSpace(*(++comma
))) {}
663 // Returns the prefix of 'str' before the first comma in it; returns
664 // the entire string if it contains no comma.
665 inline std::string
GetPrefixUntilComma(const char* str
) {
666 const char* comma
= strchr(str
, ',');
667 return comma
== nullptr ? str
: std::string(str
, comma
);
670 // Splits a given string on a given delimiter, populating a given
671 // vector with the fields.
672 void SplitString(const ::std::string
& str
, char delimiter
,
673 ::std::vector
< ::std::string
>* dest
);
675 // The default argument to the template below for the case when the user does
676 // not provide a name generator.
677 struct DefaultNameGenerator
{
678 template <typename T
>
679 static std::string
GetName(int i
) {
680 return StreamableToString(i
);
684 template <typename Provided
= DefaultNameGenerator
>
685 struct NameGeneratorSelector
{
686 typedef Provided type
;
689 template <typename NameGenerator
>
690 void GenerateNamesRecursively(internal::None
, std::vector
<std::string
>*, int) {}
692 template <typename NameGenerator
, typename Types
>
693 void GenerateNamesRecursively(Types
, std::vector
<std::string
>* result
, int i
) {
694 result
->push_back(NameGenerator::template GetName
<typename
Types::Head
>(i
));
695 GenerateNamesRecursively
<NameGenerator
>(typename
Types::Tail(), result
,
699 template <typename NameGenerator
, typename Types
>
700 std::vector
<std::string
> GenerateNames() {
701 std::vector
<std::string
> result
;
702 GenerateNamesRecursively
<NameGenerator
>(Types(), &result
, 0);
706 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
707 // registers a list of type-parameterized tests with Google Test. The
708 // return value is insignificant - we just need to return something
709 // such that we can call this function in a namespace scope.
711 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
712 // template parameter. It's defined in gtest-type-util.h.
713 template <GTEST_TEMPLATE_ Fixture
, class TestSel
, typename Types
>
714 class TypeParameterizedTest
{
716 // 'index' is the index of the test in the type list 'Types'
717 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
718 // Types). Valid values for 'index' are [0, N - 1] where N is the
720 static bool Register(const char* prefix
, const CodeLocation
& code_location
,
721 const char* case_name
, const char* test_names
, int index
,
722 const std::vector
<std::string
>& type_names
=
723 GenerateNames
<DefaultNameGenerator
, Types
>()) {
724 typedef typename
Types::Head Type
;
725 typedef Fixture
<Type
> FixtureClass
;
726 typedef typename
GTEST_BIND_(TestSel
, Type
) TestClass
;
728 // First, registers the first type-parameterized test in the type
730 MakeAndRegisterTestInfo(
731 (std::string(prefix
) + (prefix
[0] == '\0' ? "" : "/") + case_name
+
732 "/" + type_names
[static_cast<size_t>(index
)])
734 StripTrailingSpaces(GetPrefixUntilComma(test_names
)).c_str(),
735 GetTypeName
<Type
>().c_str(),
736 nullptr, // No value parameter.
737 code_location
, GetTypeId
<FixtureClass
>(),
738 SuiteApiResolver
<TestClass
>::GetSetUpCaseOrSuite(
739 code_location
.file
.c_str(), code_location
.line
),
740 SuiteApiResolver
<TestClass
>::GetTearDownCaseOrSuite(
741 code_location
.file
.c_str(), code_location
.line
),
742 new TestFactoryImpl
<TestClass
>);
744 // Next, recurses (at compile time) with the tail of the type list.
745 return TypeParameterizedTest
<Fixture
, TestSel
,
746 typename
Types::Tail
>::Register(prefix
,
755 // The base case for the compile time recursion.
756 template <GTEST_TEMPLATE_ Fixture
, class TestSel
>
757 class TypeParameterizedTest
<Fixture
, TestSel
, internal::None
> {
759 static bool Register(const char* /*prefix*/, const CodeLocation
&,
760 const char* /*case_name*/, const char* /*test_names*/,
762 const std::vector
<std::string
>& =
763 std::vector
<std::string
>() /*type_names*/) {
768 GTEST_API_
void RegisterTypeParameterizedTestSuite(const char* test_suite_name
,
769 CodeLocation code_location
);
770 GTEST_API_
void RegisterTypeParameterizedTestSuiteInstantiation(
771 const char* case_name
);
773 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
774 // registers *all combinations* of 'Tests' and 'Types' with Google
775 // Test. The return value is insignificant - we just need to return
776 // something such that we can call this function in a namespace scope.
777 template <GTEST_TEMPLATE_ Fixture
, typename Tests
, typename Types
>
778 class TypeParameterizedTestSuite
{
780 static bool Register(const char* prefix
, CodeLocation code_location
,
781 const TypedTestSuitePState
* state
, const char* case_name
,
782 const char* test_names
,
783 const std::vector
<std::string
>& type_names
=
784 GenerateNames
<DefaultNameGenerator
, Types
>()) {
785 RegisterTypeParameterizedTestSuiteInstantiation(case_name
);
786 std::string test_name
= StripTrailingSpaces(
787 GetPrefixUntilComma(test_names
));
788 if (!state
->TestExists(test_name
)) {
789 fprintf(stderr
, "Failed to get code location for test %s.%s at %s.",
790 case_name
, test_name
.c_str(),
791 FormatFileLocation(code_location
.file
.c_str(),
792 code_location
.line
).c_str());
796 const CodeLocation
& test_location
= state
->GetCodeLocation(test_name
);
798 typedef typename
Tests::Head Head
;
800 // First, register the first test in 'Test' for each type in 'Types'.
801 TypeParameterizedTest
<Fixture
, Head
, Types
>::Register(
802 prefix
, test_location
, case_name
, test_names
, 0, type_names
);
804 // Next, recurses (at compile time) with the tail of the test list.
805 return TypeParameterizedTestSuite
<Fixture
, typename
Tests::Tail
,
806 Types
>::Register(prefix
, code_location
,
808 SkipComma(test_names
),
813 // The base case for the compile time recursion.
814 template <GTEST_TEMPLATE_ Fixture
, typename Types
>
815 class TypeParameterizedTestSuite
<Fixture
, internal::None
, Types
> {
817 static bool Register(const char* /*prefix*/, const CodeLocation
&,
818 const TypedTestSuitePState
* /*state*/,
819 const char* /*case_name*/, const char* /*test_names*/,
820 const std::vector
<std::string
>& =
821 std::vector
<std::string
>() /*type_names*/) {
826 #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
828 // Returns the current OS stack trace as an std::string.
830 // The maximum number of stack frames to be included is specified by
831 // the gtest_stack_trace_depth flag. The skip_count parameter
832 // specifies the number of top frames to be skipped, which doesn't
833 // count against the number of frames to be included.
835 // For example, if Foo() calls Bar(), which in turn calls
836 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
837 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
838 GTEST_API_
std::string
GetCurrentOsStackTraceExceptTop(
839 UnitTest
* unit_test
, int skip_count
);
841 // Helpers for suppressing warnings on unreachable code or constant
844 // Always returns true.
845 GTEST_API_
bool AlwaysTrue();
847 // Always returns false.
848 inline bool AlwaysFalse() { return !AlwaysTrue(); }
850 // Helper for suppressing false warning from Clang on a const char*
851 // variable declared in a conditional expression always being NULL in
853 struct GTEST_API_ ConstCharPtr
{
854 ConstCharPtr(const char* str
) : value(str
) {}
855 operator bool() const { return true; }
859 // Helper for declaring std::string within 'if' statement
860 // in pre C++17 build environment.
861 struct TrueWithString
{
862 TrueWithString() = default;
863 explicit TrueWithString(const char* str
) : value(str
) {}
864 explicit TrueWithString(const std::string
& str
) : value(str
) {}
865 explicit operator bool() const { return true; }
869 // A simple Linear Congruential Generator for generating random
870 // numbers with a uniform distribution. Unlike rand() and srand(), it
871 // doesn't use global state (and therefore can't interfere with user
872 // code). Unlike rand_r(), it's portable. An LCG isn't very random,
873 // but it's good enough for our purposes.
874 class GTEST_API_ Random
{
876 static const uint32_t kMaxRange
= 1u << 31;
878 explicit Random(uint32_t seed
) : state_(seed
) {}
880 void Reseed(uint32_t seed
) { state_
= seed
; }
882 // Generates a random number from [0, range). Crashes if 'range' is
883 // 0 or greater than kMaxRange.
884 uint32_t Generate(uint32_t range
);
888 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random
);
891 // Turns const U&, U&, const U, and U all into U.
892 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
893 typename std::remove_const<typename std::remove_reference<T>::type>::type
895 // HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant
896 // that's true if and only if T has methods DebugString() and ShortDebugString()
897 // that return std::string.
898 template <typename T
>
899 class HasDebugStringAndShortDebugString
{
901 template <typename C
>
902 static constexpr auto CheckDebugString(C
*) -> typename
std::is_same
<
903 std::string
, decltype(std::declval
<const C
>().DebugString())>::type
;
905 static constexpr std::false_type
CheckDebugString(...);
907 template <typename C
>
908 static constexpr auto CheckShortDebugString(C
*) -> typename
std::is_same
<
909 std::string
, decltype(std::declval
<const C
>().ShortDebugString())>::type
;
911 static constexpr std::false_type
CheckShortDebugString(...);
913 using HasDebugStringType
= decltype(CheckDebugString
<T
>(nullptr));
914 using HasShortDebugStringType
= decltype(CheckShortDebugString
<T
>(nullptr));
917 static constexpr bool value
=
918 HasDebugStringType::value
&& HasShortDebugStringType::value
;
921 template <typename T
>
922 constexpr bool HasDebugStringAndShortDebugString
<T
>::value
;
924 // When the compiler sees expression IsContainerTest<C>(0), if C is an
925 // STL-style container class, the first overload of IsContainerTest
926 // will be viable (since both C::iterator* and C::const_iterator* are
927 // valid types and NULL can be implicitly converted to them). It will
928 // be picked over the second overload as 'int' is a perfect match for
929 // the type of argument 0. If C::iterator or C::const_iterator is not
930 // a valid type, the first overload is not viable, and the second
931 // overload will be picked. Therefore, we can determine whether C is
932 // a container class by checking the type of IsContainerTest<C>(0).
933 // The value of the expression is insignificant.
935 // In C++11 mode we check the existence of a const_iterator and that an
936 // iterator is properly implemented for the container.
938 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
939 // The reason is that C++ injects the name of a class as a member of the
940 // class itself (e.g. you can refer to class iterator as either
941 // 'iterator' or 'iterator::iterator'). If we look for C::iterator
942 // only, for example, we would mistakenly think that a class named
943 // iterator is an STL container.
945 // Also note that the simpler approach of overloading
946 // IsContainerTest(typename C::const_iterator*) and
947 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
948 typedef int IsContainer
;
950 class Iterator
= decltype(::std::declval
<const C
&>().begin()),
951 class = decltype(::std::declval
<const C
&>().end()),
952 class = decltype(++::std::declval
<Iterator
&>()),
953 class = decltype(*::std::declval
<Iterator
>()),
954 class = typename
C::const_iterator
>
955 IsContainer
IsContainerTest(int /* dummy */) {
959 typedef char IsNotContainer
;
961 IsNotContainer
IsContainerTest(long /* dummy */) { return '\0'; }
963 // Trait to detect whether a type T is a hash table.
964 // The heuristic used is that the type contains an inner type `hasher` and does
965 // not contain an inner type `reverse_iterator`.
966 // If the container is iterable in reverse, then order might actually matter.
967 template <typename T
>
970 template <typename U
>
971 static char test(typename
U::hasher
*, typename
U::reverse_iterator
*);
972 template <typename U
>
973 static int test(typename
U::hasher
*, ...);
974 template <typename U
>
975 static char test(...);
978 static const bool value
= sizeof(test
<T
>(nullptr, nullptr)) == sizeof(int);
981 template <typename T
>
982 const bool IsHashTable
<T
>::value
;
984 template <typename C
,
985 bool = sizeof(IsContainerTest
<C
>(0)) == sizeof(IsContainer
)>
986 struct IsRecursiveContainerImpl
;
988 template <typename C
>
989 struct IsRecursiveContainerImpl
<C
, false> : public std::false_type
{};
991 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
992 // obey the same inconsistencies as the IsContainerTest, namely check if
993 // something is a container is relying on only const_iterator in C++11 and
994 // is relying on both const_iterator and iterator otherwise
995 template <typename C
>
996 struct IsRecursiveContainerImpl
<C
, true> {
997 using value_type
= decltype(*std::declval
<typename
C::const_iterator
>());
999 std::is_same
<typename
std::remove_const
<
1000 typename
std::remove_reference
<value_type
>::type
>::type
,
1004 // IsRecursiveContainer<Type> is a unary compile-time predicate that
1005 // evaluates whether C is a recursive container type. A recursive container
1006 // type is a container type whose value_type is equal to the container type
1007 // itself. An example for a recursive container type is
1008 // boost::filesystem::path, whose iterator has a value_type that is equal to
1009 // boost::filesystem::path.
1010 template <typename C
>
1011 struct IsRecursiveContainer
: public IsRecursiveContainerImpl
<C
>::type
{};
1013 // Utilities for native arrays.
1015 // ArrayEq() compares two k-dimensional native arrays using the
1016 // elements' operator==, where k can be any integer >= 0. When k is
1017 // 0, ArrayEq() degenerates into comparing a single pair of values.
1019 template <typename T
, typename U
>
1020 bool ArrayEq(const T
* lhs
, size_t size
, const U
* rhs
);
1022 // This generic version is used when k is 0.
1023 template <typename T
, typename U
>
1024 inline bool ArrayEq(const T
& lhs
, const U
& rhs
) { return lhs
== rhs
; }
1026 // This overload is used when k >= 1.
1027 template <typename T
, typename U
, size_t N
>
1028 inline bool ArrayEq(const T(&lhs
)[N
], const U(&rhs
)[N
]) {
1029 return internal::ArrayEq(lhs
, N
, rhs
);
1032 // This helper reduces code bloat. If we instead put its logic inside
1033 // the previous ArrayEq() function, arrays with different sizes would
1034 // lead to different copies of the template code.
1035 template <typename T
, typename U
>
1036 bool ArrayEq(const T
* lhs
, size_t size
, const U
* rhs
) {
1037 for (size_t i
= 0; i
!= size
; i
++) {
1038 if (!internal::ArrayEq(lhs
[i
], rhs
[i
]))
1044 // Finds the first element in the iterator range [begin, end) that
1045 // equals elem. Element may be a native array type itself.
1046 template <typename Iter
, typename Element
>
1047 Iter
ArrayAwareFind(Iter begin
, Iter end
, const Element
& elem
) {
1048 for (Iter it
= begin
; it
!= end
; ++it
) {
1049 if (internal::ArrayEq(*it
, elem
))
1055 // CopyArray() copies a k-dimensional native array using the elements'
1056 // operator=, where k can be any integer >= 0. When k is 0,
1057 // CopyArray() degenerates into copying a single value.
1059 template <typename T
, typename U
>
1060 void CopyArray(const T
* from
, size_t size
, U
* to
);
1062 // This generic version is used when k is 0.
1063 template <typename T
, typename U
>
1064 inline void CopyArray(const T
& from
, U
* to
) { *to
= from
; }
1066 // This overload is used when k >= 1.
1067 template <typename T
, typename U
, size_t N
>
1068 inline void CopyArray(const T(&from
)[N
], U(*to
)[N
]) {
1069 internal::CopyArray(from
, N
, *to
);
1072 // This helper reduces code bloat. If we instead put its logic inside
1073 // the previous CopyArray() function, arrays with different sizes
1074 // would lead to different copies of the template code.
1075 template <typename T
, typename U
>
1076 void CopyArray(const T
* from
, size_t size
, U
* to
) {
1077 for (size_t i
= 0; i
!= size
; i
++) {
1078 internal::CopyArray(from
[i
], to
+ i
);
1082 // The relation between an NativeArray object (see below) and the
1083 // native array it represents.
1084 // We use 2 different structs to allow non-copyable types to be used, as long
1085 // as RelationToSourceReference() is passed.
1086 struct RelationToSourceReference
{};
1087 struct RelationToSourceCopy
{};
1089 // Adapts a native array to a read-only STL-style container. Instead
1090 // of the complete STL container concept, this adaptor only implements
1091 // members useful for Google Mock's container matchers. New members
1092 // should be added as needed. To simplify the implementation, we only
1093 // support Element being a raw type (i.e. having no top-level const or
1094 // reference modifier). It's the client's responsibility to satisfy
1095 // this requirement. Element can be an array type itself (hence
1096 // multi-dimensional arrays are supported).
1097 template <typename Element
>
1100 // STL-style container typedefs.
1101 typedef Element value_type
;
1102 typedef Element
* iterator
;
1103 typedef const Element
* const_iterator
;
1105 // Constructs from a native array. References the source.
1106 NativeArray(const Element
* array
, size_t count
, RelationToSourceReference
) {
1107 InitRef(array
, count
);
1110 // Constructs from a native array. Copies the source.
1111 NativeArray(const Element
* array
, size_t count
, RelationToSourceCopy
) {
1112 InitCopy(array
, count
);
1115 // Copy constructor.
1116 NativeArray(const NativeArray
& rhs
) {
1117 (this->*rhs
.clone_
)(rhs
.array_
, rhs
.size_
);
1121 if (clone_
!= &NativeArray::InitRef
)
1125 // STL-style container methods.
1126 size_t size() const { return size_
; }
1127 const_iterator
begin() const { return array_
; }
1128 const_iterator
end() const { return array_
+ size_
; }
1129 bool operator==(const NativeArray
& rhs
) const {
1130 return size() == rhs
.size() &&
1131 ArrayEq(begin(), size(), rhs
.begin());
1135 static_assert(!std::is_const
<Element
>::value
, "Type must not be const");
1136 static_assert(!std::is_reference
<Element
>::value
,
1137 "Type must not be a reference");
1139 // Initializes this object with a copy of the input.
1140 void InitCopy(const Element
* array
, size_t a_size
) {
1141 Element
* const copy
= new Element
[a_size
];
1142 CopyArray(array
, a_size
, copy
);
1145 clone_
= &NativeArray::InitCopy
;
1148 // Initializes this object with a reference of the input.
1149 void InitRef(const Element
* array
, size_t a_size
) {
1152 clone_
= &NativeArray::InitRef
;
1155 const Element
* array_
;
1157 void (NativeArray::*clone_
)(const Element
*, size_t);
1160 // Backport of std::index_sequence.
1161 template <size_t... Is
>
1162 struct IndexSequence
{
1163 using type
= IndexSequence
;
1166 // Double the IndexSequence, and one if plus_one is true.
1167 template <bool plus_one
, typename T
, size_t sizeofT
>
1168 struct DoubleSequence
;
1169 template <size_t... I
, size_t sizeofT
>
1170 struct DoubleSequence
<true, IndexSequence
<I
...>, sizeofT
> {
1171 using type
= IndexSequence
<I
..., (sizeofT
+ I
)..., 2 * sizeofT
>;
1173 template <size_t... I
, size_t sizeofT
>
1174 struct DoubleSequence
<false, IndexSequence
<I
...>, sizeofT
> {
1175 using type
= IndexSequence
<I
..., (sizeofT
+ I
)...>;
1178 // Backport of std::make_index_sequence.
1179 // It uses O(ln(N)) instantiation depth.
1181 struct MakeIndexSequenceImpl
1182 : DoubleSequence
<N
% 2 == 1, typename MakeIndexSequenceImpl
<N
/ 2>::type
,
1186 struct MakeIndexSequenceImpl
<0> : IndexSequence
<> {};
1189 using MakeIndexSequence
= typename MakeIndexSequenceImpl
<N
>::type
;
1191 template <typename
... T
>
1192 using IndexSequenceFor
= typename MakeIndexSequence
<sizeof...(T
)>::type
;
1196 Ignore(...); // NOLINT
1200 struct ElemFromListImpl
;
1201 template <size_t... I
>
1202 struct ElemFromListImpl
<IndexSequence
<I
...>> {
1203 // We make Ignore a template to solve a problem with MSVC.
1204 // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but
1205 // MSVC doesn't understand how to deal with that pack expansion.
1206 // Use `0 * I` to have a single instantiation of Ignore.
1207 template <typename R
>
1208 static R
Apply(Ignore
<0 * I
>..., R (*)(), ...);
1211 template <size_t N
, typename
... T
>
1212 struct ElemFromList
{
1214 decltype(ElemFromListImpl
<typename MakeIndexSequence
<N
>::type
>::Apply(
1215 static_cast<T (*)()>(nullptr)...));
1218 struct FlatTupleConstructTag
{};
1220 template <typename
... T
>
1223 template <typename Derived
, size_t I
>
1224 struct FlatTupleElemBase
;
1226 template <typename
... T
, size_t I
>
1227 struct FlatTupleElemBase
<FlatTuple
<T
...>, I
> {
1228 using value_type
= typename ElemFromList
<I
, T
...>::type
;
1229 FlatTupleElemBase() = default;
1230 template <typename Arg
>
1231 explicit FlatTupleElemBase(FlatTupleConstructTag
, Arg
&& t
)
1232 : value(std::forward
<Arg
>(t
)) {}
1236 template <typename Derived
, typename Idx
>
1237 struct FlatTupleBase
;
1239 template <size_t... Idx
, typename
... T
>
1240 struct FlatTupleBase
<FlatTuple
<T
...>, IndexSequence
<Idx
...>>
1241 : FlatTupleElemBase
<FlatTuple
<T
...>, Idx
>... {
1242 using Indices
= IndexSequence
<Idx
...>;
1243 FlatTupleBase() = default;
1244 template <typename
... Args
>
1245 explicit FlatTupleBase(FlatTupleConstructTag
, Args
&&... args
)
1246 : FlatTupleElemBase
<FlatTuple
<T
...>, Idx
>(FlatTupleConstructTag
{},
1247 std::forward
<Args
>(args
))... {}
1250 const typename ElemFromList
<I
, T
...>::type
& Get() const {
1251 return FlatTupleElemBase
<FlatTuple
<T
...>, I
>::value
;
1255 typename ElemFromList
<I
, T
...>::type
& Get() {
1256 return FlatTupleElemBase
<FlatTuple
<T
...>, I
>::value
;
1259 template <typename F
>
1260 auto Apply(F
&& f
) -> decltype(std::forward
<F
>(f
)(this->Get
<Idx
>()...)) {
1261 return std::forward
<F
>(f
)(Get
<Idx
>()...);
1264 template <typename F
>
1265 auto Apply(F
&& f
) const -> decltype(std::forward
<F
>(f
)(this->Get
<Idx
>()...)) {
1266 return std::forward
<F
>(f
)(Get
<Idx
>()...);
1270 // Analog to std::tuple but with different tradeoffs.
1271 // This class minimizes the template instantiation depth, thus allowing more
1272 // elements than std::tuple would. std::tuple has been seen to require an
1273 // instantiation depth of more than 10x the number of elements in some
1275 // FlatTuple and ElemFromList are not recursive and have a fixed depth
1276 // regardless of T...
1277 // MakeIndexSequence, on the other hand, it is recursive but with an
1278 // instantiation depth of O(ln(N)).
1279 template <typename
... T
>
1281 : private FlatTupleBase
<FlatTuple
<T
...>,
1282 typename MakeIndexSequence
<sizeof...(T
)>::type
> {
1283 using Indices
= typename FlatTupleBase
<
1284 FlatTuple
<T
...>, typename MakeIndexSequence
<sizeof...(T
)>::type
>::Indices
;
1287 FlatTuple() = default;
1288 template <typename
... Args
>
1289 explicit FlatTuple(FlatTupleConstructTag tag
, Args
&&... args
)
1290 : FlatTuple::FlatTupleBase(tag
, std::forward
<Args
>(args
)...) {}
1292 using FlatTuple::FlatTupleBase::Apply
;
1293 using FlatTuple::FlatTupleBase::Get
;
1296 // Utility functions to be called with static_assert to induce deprecation
1298 GTEST_INTERNAL_DEPRECATED(
1299 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
1300 "INSTANTIATE_TEST_SUITE_P")
1301 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
1303 GTEST_INTERNAL_DEPRECATED(
1304 "TYPED_TEST_CASE_P is deprecated, please use "
1305 "TYPED_TEST_SUITE_P")
1306 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
1308 GTEST_INTERNAL_DEPRECATED(
1309 "TYPED_TEST_CASE is deprecated, please use "
1311 constexpr bool TypedTestCaseIsDeprecated() { return true; }
1313 GTEST_INTERNAL_DEPRECATED(
1314 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
1315 "REGISTER_TYPED_TEST_SUITE_P")
1316 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
1318 GTEST_INTERNAL_DEPRECATED(
1319 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
1320 "INSTANTIATE_TYPED_TEST_SUITE_P")
1321 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
1323 } // namespace internal
1324 } // namespace testing
1327 // Some standard library implementations use `struct tuple_size` and some use
1328 // `class tuple_size`. Clang warns about the mismatch.
1329 // https://reviews.llvm.org/D55466
1331 #pragma clang diagnostic push
1332 #pragma clang diagnostic ignored "-Wmismatched-tags"
1334 template <typename
... Ts
>
1335 struct tuple_size
<testing::internal::FlatTuple
<Ts
...>>
1336 : std::integral_constant
<size_t, sizeof...(Ts
)> {};
1338 #pragma clang diagnostic pop
1342 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1343 ::testing::internal::AssertHelper(result_type, file, line, message) \
1344 = ::testing::Message()
1346 #define GTEST_MESSAGE_(message, result_type) \
1347 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1349 #define GTEST_FATAL_FAILURE_(message) \
1350 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1352 #define GTEST_NONFATAL_FAILURE_(message) \
1353 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1355 #define GTEST_SUCCESS_(message) \
1356 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1358 #define GTEST_SKIP_(message) \
1359 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
1361 // Suppress MSVC warning 4072 (unreachable code) for the code following
1362 // statement if it returns or throws (or doesn't return or throw in some
1364 // NOTE: The "else" is important to keep this expansion to prevent a top-level
1365 // "else" from attaching to our "if".
1366 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1367 if (::testing::internal::AlwaysTrue()) { \
1369 } else /* NOLINT */ \
1370 static_assert(true, "") // User must have a semicolon after expansion.
1372 #if GTEST_HAS_EXCEPTIONS
1375 namespace internal
{
1379 const char* what() const noexcept
{
1380 return "this exception should never be thrown";
1384 } // namespace internal
1385 } // namespace testing
1389 #define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))
1391 #else // GTEST_HAS_RTTI
1393 #define GTEST_EXCEPTION_TYPE_(e) \
1394 std::string { "an std::exception-derived error" }
1396 #endif // GTEST_HAS_RTTI
1398 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
1399 catch (typename std::conditional< \
1400 std::is_same<typename std::remove_cv<typename std::remove_reference< \
1401 expected_exception>::type>::type, \
1402 std::exception>::value, \
1403 const ::testing::internal::NeverThrown&, const std::exception&>::type \
1405 gtest_msg.value = "Expected: " #statement \
1406 " throws an exception of type " #expected_exception \
1407 ".\n Actual: it throws "; \
1408 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
1409 gtest_msg.value += " with description \""; \
1410 gtest_msg.value += e.what(); \
1411 gtest_msg.value += "\"."; \
1412 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1415 #else // GTEST_HAS_EXCEPTIONS
1417 #define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)
1419 #endif // GTEST_HAS_EXCEPTIONS
1421 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1422 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1423 if (::testing::internal::TrueWithString gtest_msg{}) { \
1424 bool gtest_caught_expected = false; \
1426 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1427 } catch (expected_exception const&) { \
1428 gtest_caught_expected = true; \
1430 GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception) \
1432 gtest_msg.value = "Expected: " #statement \
1433 " throws an exception of type " #expected_exception \
1434 ".\n Actual: it throws a different type."; \
1435 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1437 if (!gtest_caught_expected) { \
1438 gtest_msg.value = "Expected: " #statement \
1439 " throws an exception of type " #expected_exception \
1440 ".\n Actual: it throws nothing."; \
1441 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1444 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) \
1445 : fail(gtest_msg.value.c_str())
1447 #if GTEST_HAS_EXCEPTIONS
1449 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
1450 catch (std::exception const& e) { \
1451 gtest_msg.value = "it throws "; \
1452 gtest_msg.value += GTEST_EXCEPTION_TYPE_(e); \
1453 gtest_msg.value += " with description \""; \
1454 gtest_msg.value += e.what(); \
1455 gtest_msg.value += "\"."; \
1456 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1459 #else // GTEST_HAS_EXCEPTIONS
1461 #define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()
1463 #endif // GTEST_HAS_EXCEPTIONS
1465 #define GTEST_TEST_NO_THROW_(statement, fail) \
1466 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1467 if (::testing::internal::TrueWithString gtest_msg{}) { \
1469 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1471 GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_() \
1473 gtest_msg.value = "it throws."; \
1474 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1477 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
1478 fail(("Expected: " #statement " doesn't throw an exception.\n" \
1479 " Actual: " + gtest_msg.value).c_str())
1481 #define GTEST_TEST_ANY_THROW_(statement, fail) \
1482 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1483 if (::testing::internal::AlwaysTrue()) { \
1484 bool gtest_caught_any = false; \
1486 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1489 gtest_caught_any = true; \
1491 if (!gtest_caught_any) { \
1492 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1495 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1496 fail("Expected: " #statement " throws an exception.\n" \
1497 " Actual: it doesn't.")
1500 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1501 // either a boolean expression or an AssertionResult. text is a textual
1502 // represenation of expression as it was passed into the EXPECT_TRUE.
1503 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1504 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1505 if (const ::testing::AssertionResult gtest_ar_ = \
1506 ::testing::AssertionResult(expression)) \
1509 fail(::testing::internal::GetBoolAssertionFailureMessage(\
1510 gtest_ar_, text, #actual, #expected).c_str())
1512 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1513 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1514 if (::testing::internal::AlwaysTrue()) { \
1515 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1516 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1517 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1518 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1521 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1522 fail("Expected: " #statement " doesn't generate new fatal " \
1523 "failures in the current thread.\n" \
1524 " Actual: it does.")
1526 // Expands to the name of the class that implements the given test.
1527 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1528 test_suite_name##_##test_name##_Test
1530 // Helper macro for defining tests.
1531 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
1532 static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \
1533 "test_suite_name must not be empty"); \
1534 static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \
1535 "test_name must not be empty"); \
1536 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1537 : public parent_class { \
1539 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default; \
1540 ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default; \
1541 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
1543 GTEST_DISALLOW_MOVE_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
1547 void TestBody() override; \
1548 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
1551 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
1552 test_name)::test_info_ = \
1553 ::testing::internal::MakeAndRegisterTestInfo( \
1554 #test_suite_name, #test_name, nullptr, nullptr, \
1555 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
1556 ::testing::internal::SuiteApiResolver< \
1557 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
1558 ::testing::internal::SuiteApiResolver< \
1559 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
1560 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
1561 test_suite_name, test_name)>); \
1562 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
1564 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_