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
61 #include <type_traits>
64 #include "gtest/gtest-message.h"
65 #include "gtest/internal/gtest-filepath.h"
66 #include "gtest/internal/gtest-string.h"
67 #include "gtest/internal/gtest-type-util.h"
69 // Due to C++ preprocessor weirdness, we need double indirection to
70 // concatenate two tokens when one of them is __LINE__. Writing
74 // will result in the token foo__LINE__, instead of foo followed by
75 // the current line number. For more details, see
76 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
77 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
78 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
80 // Stringifies its argument.
81 #define GTEST_STRINGIFY_(name) #name
83 namespace proto2
{ class Message
; }
87 // Forward declarations.
89 class AssertionResult
; // Result of an assertion.
90 class Message
; // Represents a failure message.
91 class Test
; // Represents a test.
92 class TestInfo
; // Information about a test.
93 class TestPartResult
; // Result of a test part.
94 class UnitTest
; // A collection of test suites.
97 ::std::string
PrintToString(const T
& value
);
101 struct TraceInfo
; // Information about a trace point.
102 class TestInfoImpl
; // Opaque implementation of TestInfo
103 class UnitTestImpl
; // Opaque implementation of UnitTest
105 // The text used in failure messages to indicate the start of the
107 GTEST_API_
extern const char kStackTraceMarker
[];
109 // An IgnoredValue object can be implicitly constructed from ANY value.
113 // This constructor template allows any value to be implicitly
114 // converted to IgnoredValue. The object has no data member and
115 // doesn't try to remember anything about the argument. We
116 // deliberately omit the 'explicit' keyword in order to allow the
117 // conversion to be implicit.
118 // Disable the conversion if T already has a magical conversion operator.
119 // Otherwise we get ambiguity.
120 template <typename T
,
121 typename
std::enable_if
<!std::is_convertible
<T
, Sink
>::value
,
123 IgnoredValue(const T
& /* ignored */) {} // NOLINT(runtime/explicit)
126 // Appends the user-supplied message to the Google-Test-generated message.
127 GTEST_API_
std::string
AppendUserMessage(
128 const std::string
& gtest_msg
, const Message
& user_msg
);
130 #if GTEST_HAS_EXCEPTIONS
132 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \
133 /* an exported class was derived from a class that was not exported */)
135 // This exception is thrown by (and only by) a failed Google Test
136 // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions
137 // are enabled). We derive it from std::runtime_error, which is for
138 // errors presumably detectable only at run time. Since
139 // std::runtime_error inherits from std::exception, many testing
140 // frameworks know how to extract and print the message inside it.
141 class GTEST_API_ GoogleTestFailureException
: public ::std::runtime_error
{
143 explicit GoogleTestFailureException(const TestPartResult
& failure
);
146 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275
148 #endif // GTEST_HAS_EXCEPTIONS
150 namespace edit_distance
{
151 // Returns the optimal edits to go from 'left' to 'right'.
152 // All edits cost the same, with replace having lower priority than
154 // Simple implementation of the Wagner-Fischer algorithm.
155 // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm
156 enum EditType
{ kMatch
, kAdd
, kRemove
, kReplace
};
157 GTEST_API_
std::vector
<EditType
> CalculateOptimalEdits(
158 const std::vector
<size_t>& left
, const std::vector
<size_t>& right
);
160 // Same as above, but the input is represented as strings.
161 GTEST_API_
std::vector
<EditType
> CalculateOptimalEdits(
162 const std::vector
<std::string
>& left
,
163 const std::vector
<std::string
>& right
);
165 // Create a diff of the input strings in Unified diff format.
166 GTEST_API_
std::string
CreateUnifiedDiff(const std::vector
<std::string
>& left
,
167 const std::vector
<std::string
>& right
,
170 } // namespace edit_distance
172 // Calculate the diff between 'left' and 'right' and return it in unified diff
174 // If not null, stores in 'total_line_count' the total number of lines found
176 GTEST_API_
std::string
DiffStrings(const std::string
& left
,
177 const std::string
& right
,
178 size_t* total_line_count
);
180 // Constructs and returns the message for an equality assertion
181 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
183 // The first four parameters are the expressions used in the assertion
184 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
185 // where foo is 5 and bar is 6, we have:
187 // expected_expression: "foo"
188 // actual_expression: "bar"
189 // expected_value: "5"
192 // The ignoring_case parameter is true if the assertion is a
193 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
194 // be inserted into the message.
195 GTEST_API_ AssertionResult
EqFailure(const char* expected_expression
,
196 const char* actual_expression
,
197 const std::string
& expected_value
,
198 const std::string
& actual_value
,
201 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
202 GTEST_API_
std::string
GetBoolAssertionFailureMessage(
203 const AssertionResult
& assertion_result
,
204 const char* expression_text
,
205 const char* actual_predicate_value
,
206 const char* expected_predicate_value
);
208 // This template class represents an IEEE floating-point number
209 // (either single-precision or double-precision, depending on the
210 // template parameters).
212 // The purpose of this class is to do more sophisticated number
213 // comparison. (Due to round-off error, etc, it's very unlikely that
214 // two floating-points will be equal exactly. Hence a naive
215 // comparison by the == operation often doesn't work.)
217 // Format of IEEE floating-point:
219 // The most-significant bit being the leftmost, an IEEE
220 // floating-point looks like
222 // sign_bit exponent_bits fraction_bits
224 // Here, sign_bit is a single bit that designates the sign of the
227 // For float, there are 8 exponent bits and 23 fraction bits.
229 // For double, there are 11 exponent bits and 52 fraction bits.
231 // More details can be found at
232 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
234 // Template parameter:
236 // RawType: the raw floating-point type (either float or double)
237 template <typename RawType
>
238 class FloatingPoint
{
240 // Defines the unsigned integer type that has the same size as the
241 // floating point number.
242 typedef typename TypeWithSize
<sizeof(RawType
)>::UInt Bits
;
246 // # of bits in a number.
247 static const size_t kBitCount
= 8*sizeof(RawType
);
249 // # of fraction bits in a number.
250 static const size_t kFractionBitCount
=
251 std::numeric_limits
<RawType
>::digits
- 1;
253 // # of exponent bits in a number.
254 static const size_t kExponentBitCount
= kBitCount
- 1 - kFractionBitCount
;
256 // The mask for the sign bit.
257 static const Bits kSignBitMask
= static_cast<Bits
>(1) << (kBitCount
- 1);
259 // The mask for the fraction bits.
260 static const Bits kFractionBitMask
=
261 ~static_cast<Bits
>(0) >> (kExponentBitCount
+ 1);
263 // The mask for the exponent bits.
264 static const Bits kExponentBitMask
= ~(kSignBitMask
| kFractionBitMask
);
266 // How many ULP's (Units in the Last Place) we want to tolerate when
267 // comparing two numbers. The larger the value, the more error we
268 // allow. A 0 value means that two numbers must be exactly the same
269 // to be considered equal.
271 // The maximum error of a single floating-point operation is 0.5
272 // units in the last place. On Intel CPU's, all floating-point
273 // calculations are done with 80-bit precision, while double has 64
274 // bits. Therefore, 4 should be enough for ordinary use.
276 // See the following article for more details on ULP:
277 // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
278 static const size_t kMaxUlps
= 4;
280 // Constructs a FloatingPoint from a raw floating-point number.
282 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
283 // around may change its bits, although the new value is guaranteed
284 // to be also a NAN. Therefore, don't expect this constructor to
285 // preserve the bits in x when x is a NAN.
286 explicit FloatingPoint(const RawType
& x
) { u_
.value_
= x
; }
290 // Reinterprets a bit pattern as a floating-point number.
292 // This function is needed to test the AlmostEquals() method.
293 static RawType
ReinterpretBits(const Bits bits
) {
299 // Returns the floating-point number that represent positive infinity.
300 static RawType
Infinity() {
301 return ReinterpretBits(kExponentBitMask
);
304 // Returns the maximum representable finite floating-point number.
305 static RawType
Max();
307 // Non-static methods
309 // Returns the bits that represents this number.
310 const Bits
&bits() const { return u_
.bits_
; }
312 // Returns the exponent bits of this number.
313 Bits
exponent_bits() const { return kExponentBitMask
& u_
.bits_
; }
315 // Returns the fraction bits of this number.
316 Bits
fraction_bits() const { return kFractionBitMask
& u_
.bits_
; }
318 // Returns the sign bit of this number.
319 Bits
sign_bit() const { return kSignBitMask
& u_
.bits_
; }
321 // Returns true if this is NAN (not a number).
322 bool is_nan() const {
323 // It's a NAN if the exponent bits are all ones and the fraction
324 // bits are not entirely zeros.
325 return (exponent_bits() == kExponentBitMask
) && (fraction_bits() != 0);
328 // Returns true if this number is at most kMaxUlps ULP's away from
329 // rhs. In particular, this function:
331 // - returns false if either number is (or both are) NAN.
332 // - treats really large numbers as almost equal to infinity.
333 // - thinks +0.0 and -0.0 are 0 DLP's apart.
334 bool AlmostEquals(const FloatingPoint
& rhs
) const {
335 // The IEEE standard says that any comparison operation involving
336 // a NAN must return false.
337 if (is_nan() || rhs
.is_nan()) return false;
339 return DistanceBetweenSignAndMagnitudeNumbers(u_
.bits_
, rhs
.u_
.bits_
)
344 // The data type used to store the actual floating-point number.
345 union FloatingPointUnion
{
346 RawType value_
; // The raw floating-point number.
347 Bits bits_
; // The bits that represent the number.
350 // Converts an integer from the sign-and-magnitude representation to
351 // the biased representation. More precisely, let N be 2 to the
352 // power of (kBitCount - 1), an integer x is represented by the
353 // unsigned number x + N.
357 // -N + 1 (the most negative number representable using
358 // sign-and-magnitude) is represented by 1;
359 // 0 is represented by N; and
360 // N - 1 (the biggest number representable using
361 // sign-and-magnitude) is represented by 2N - 1.
363 // Read http://en.wikipedia.org/wiki/Signed_number_representations
364 // for more details on signed number representations.
365 static Bits
SignAndMagnitudeToBiased(const Bits
&sam
) {
366 if (kSignBitMask
& sam
) {
367 // sam represents a negative number.
370 // sam represents a positive number.
371 return kSignBitMask
| sam
;
375 // Given two numbers in the sign-and-magnitude representation,
376 // returns the distance between them as an unsigned number.
377 static Bits
DistanceBetweenSignAndMagnitudeNumbers(const Bits
&sam1
,
379 const Bits biased1
= SignAndMagnitudeToBiased(sam1
);
380 const Bits biased2
= SignAndMagnitudeToBiased(sam2
);
381 return (biased1
>= biased2
) ? (biased1
- biased2
) : (biased2
- biased1
);
384 FloatingPointUnion u_
;
387 // We cannot use std::numeric_limits<T>::max() as it clashes with the max()
388 // macro defined by <windows.h>.
390 inline float FloatingPoint
<float>::Max() { return FLT_MAX
; }
392 inline double FloatingPoint
<double>::Max() { return DBL_MAX
; }
394 // Typedefs the instances of the FloatingPoint template class that we
396 typedef FloatingPoint
<float> Float
;
397 typedef FloatingPoint
<double> Double
;
399 // In order to catch the mistake of putting tests that use different
400 // test fixture classes in the same test suite, we need to assign
401 // unique IDs to fixture classes and compare them. The TypeId type is
402 // used to hold such IDs. The user should treat TypeId as an opaque
403 // type: the only operation allowed on TypeId values is to compare
404 // them for equality using the == operator.
405 typedef const void* TypeId
;
407 template <typename T
>
410 // dummy_ must not have a const type. Otherwise an overly eager
411 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
412 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
416 template <typename T
>
417 bool TypeIdHelper
<T
>::dummy_
= false;
419 // GetTypeId<T>() returns the ID of type T. Different values will be
420 // returned for different types. Calling the function twice with the
421 // same type argument is guaranteed to return the same ID.
422 template <typename T
>
424 // The compiler is required to allocate a different
425 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
426 // the template. Therefore, the address of dummy_ is guaranteed to
428 return &(TypeIdHelper
<T
>::dummy_
);
431 // Returns the type ID of ::testing::Test. Always call this instead
432 // of GetTypeId< ::testing::Test>() to get the type ID of
433 // ::testing::Test, as the latter may give the wrong result due to a
434 // suspected linker bug when compiling Google Test as a Mac OS X
436 GTEST_API_ TypeId
GetTestTypeId();
438 // Defines the abstract factory interface that creates instances
440 class TestFactoryBase
{
442 virtual ~TestFactoryBase() {}
444 // Creates a test instance to run. The instance is both created and destroyed
445 // within TestInfoImpl::Run()
446 virtual Test
* CreateTest() = 0;
452 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase
);
455 // This class provides implementation of TeastFactoryBase interface.
456 // It is used in TEST and TEST_F macros.
457 template <class TestClass
>
458 class TestFactoryImpl
: public TestFactoryBase
{
460 Test
* CreateTest() override
{ return new TestClass
; }
465 // Predicate-formatters for implementing the HRESULT checking macros
466 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
467 // We pass a long instead of HRESULT to avoid causing an
468 // include dependency for the HRESULT type.
469 GTEST_API_ AssertionResult
IsHRESULTSuccess(const char* expr
,
471 GTEST_API_ AssertionResult
IsHRESULTFailure(const char* expr
,
474 #endif // GTEST_OS_WINDOWS
476 // Types of SetUpTestSuite() and TearDownTestSuite() functions.
477 using SetUpTestSuiteFunc
= void (*)();
478 using TearDownTestSuiteFunc
= void (*)();
480 struct CodeLocation
{
481 CodeLocation(const std::string
& a_file
, int a_line
)
482 : file(a_file
), line(a_line
) {}
488 // Helper to identify which setup function for TestCase / TestSuite to call.
489 // Only one function is allowed, either TestCase or TestSute but not both.
491 // Utility functions to help SuiteApiResolver
492 using SetUpTearDownSuiteFuncType
= void (*)();
494 inline SetUpTearDownSuiteFuncType
GetNotDefaultOrNull(
495 SetUpTearDownSuiteFuncType a
, SetUpTearDownSuiteFuncType def
) {
496 return a
== def
? nullptr : a
;
499 template <typename T
>
500 // Note that SuiteApiResolver inherits from T because
501 // SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way
502 // SuiteApiResolver can access them.
503 struct SuiteApiResolver
: T
{
504 // testing::Test is only forward declared at this point. So we make it a
505 // dependend class for the compiler to be OK with it.
507 typename
std::conditional
<sizeof(T
) != 0, ::testing::Test
, void>::type
;
509 static SetUpTearDownSuiteFuncType
GetSetUpCaseOrSuite(const char* filename
,
511 SetUpTearDownSuiteFuncType test_case_fp
=
512 GetNotDefaultOrNull(&T::SetUpTestCase
, &Test::SetUpTestCase
);
513 SetUpTearDownSuiteFuncType test_suite_fp
=
514 GetNotDefaultOrNull(&T::SetUpTestSuite
, &Test::SetUpTestSuite
);
516 GTEST_CHECK_(!test_case_fp
|| !test_suite_fp
)
517 << "Test can not provide both SetUpTestSuite and SetUpTestCase, please "
518 "make sure there is only one present at "
519 << filename
<< ":" << line_num
;
521 return test_case_fp
!= nullptr ? test_case_fp
: test_suite_fp
;
524 static SetUpTearDownSuiteFuncType
GetTearDownCaseOrSuite(const char* filename
,
526 SetUpTearDownSuiteFuncType test_case_fp
=
527 GetNotDefaultOrNull(&T::TearDownTestCase
, &Test::TearDownTestCase
);
528 SetUpTearDownSuiteFuncType test_suite_fp
=
529 GetNotDefaultOrNull(&T::TearDownTestSuite
, &Test::TearDownTestSuite
);
531 GTEST_CHECK_(!test_case_fp
|| !test_suite_fp
)
532 << "Test can not provide both TearDownTestSuite and TearDownTestCase,"
533 " please make sure there is only one present at"
534 << filename
<< ":" << line_num
;
536 return test_case_fp
!= nullptr ? test_case_fp
: test_suite_fp
;
540 // Creates a new TestInfo object and registers it with Google Test;
541 // returns the created object.
545 // test_suite_name: name of the test suite
546 // name: name of the test
547 // type_param the name of the test's type parameter, or NULL if
548 // this is not a typed or a type-parameterized test.
549 // value_param text representation of the test's value parameter,
550 // or NULL if this is not a type-parameterized test.
551 // code_location: code location where the test is defined
552 // fixture_class_id: ID of the test fixture class
553 // set_up_tc: pointer to the function that sets up the test suite
554 // tear_down_tc: pointer to the function that tears down the test suite
555 // factory: pointer to the factory that creates a test object.
556 // The newly created TestInfo instance will assume
557 // ownership of the factory object.
558 GTEST_API_ TestInfo
* MakeAndRegisterTestInfo(
559 const char* test_suite_name
, const char* name
, const char* type_param
,
560 const char* value_param
, CodeLocation code_location
,
561 TypeId fixture_class_id
, SetUpTestSuiteFunc set_up_tc
,
562 TearDownTestSuiteFunc tear_down_tc
, TestFactoryBase
* factory
);
564 // If *pstr starts with the given prefix, modifies *pstr to be right
565 // past the prefix and returns true; otherwise leaves *pstr unchanged
566 // and returns false. None of pstr, *pstr, and prefix can be NULL.
567 GTEST_API_
bool SkipPrefix(const char* prefix
, const char** pstr
);
569 #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
571 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
572 /* class A needs to have dll-interface to be used by clients of class B */)
574 // State of the definition of a type-parameterized test suite.
575 class GTEST_API_ TypedTestSuitePState
{
577 TypedTestSuitePState() : registered_(false) {}
579 // Adds the given test name to defined_test_names_ and return true
580 // if the test suite hasn't been registered; otherwise aborts the
582 bool AddTestName(const char* file
, int line
, const char* case_name
,
583 const char* test_name
) {
586 "%s Test %s must be defined before "
587 "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n",
588 FormatFileLocation(file
, line
).c_str(), test_name
, case_name
);
592 registered_tests_
.insert(
593 ::std::make_pair(test_name
, CodeLocation(file
, line
)));
597 bool TestExists(const std::string
& test_name
) const {
598 return registered_tests_
.count(test_name
) > 0;
601 const CodeLocation
& GetCodeLocation(const std::string
& test_name
) const {
602 RegisteredTestsMap::const_iterator it
= registered_tests_
.find(test_name
);
603 GTEST_CHECK_(it
!= registered_tests_
.end());
607 // Verifies that registered_tests match the test names in
608 // defined_test_names_; returns registered_tests if successful, or
609 // aborts the program otherwise.
610 const char* VerifyRegisteredTestNames(
611 const char* file
, int line
, const char* registered_tests
);
614 typedef ::std::map
<std::string
, CodeLocation
> RegisteredTestsMap
;
617 RegisteredTestsMap registered_tests_
;
620 // Legacy API is deprecated but still available
621 #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
622 using TypedTestCasePState
= TypedTestSuitePState
;
623 #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
625 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
627 // Skips to the first non-space char after the first comma in 'str';
628 // returns NULL if no comma is found in 'str'.
629 inline const char* SkipComma(const char* str
) {
630 const char* comma
= strchr(str
, ',');
631 if (comma
== nullptr) {
634 while (IsSpace(*(++comma
))) {}
638 // Returns the prefix of 'str' before the first comma in it; returns
639 // the entire string if it contains no comma.
640 inline std::string
GetPrefixUntilComma(const char* str
) {
641 const char* comma
= strchr(str
, ',');
642 return comma
== nullptr ? str
: std::string(str
, comma
);
645 // Splits a given string on a given delimiter, populating a given
646 // vector with the fields.
647 void SplitString(const ::std::string
& str
, char delimiter
,
648 ::std::vector
< ::std::string
>* dest
);
650 // The default argument to the template below for the case when the user does
651 // not provide a name generator.
652 struct DefaultNameGenerator
{
653 template <typename T
>
654 static std::string
GetName(int i
) {
655 return StreamableToString(i
);
659 template <typename Provided
= DefaultNameGenerator
>
660 struct NameGeneratorSelector
{
661 typedef Provided type
;
664 template <typename NameGenerator
>
665 void GenerateNamesRecursively(Types0
, std::vector
<std::string
>*, int) {}
667 template <typename NameGenerator
, typename Types
>
668 void GenerateNamesRecursively(Types
, std::vector
<std::string
>* result
, int i
) {
669 result
->push_back(NameGenerator::template GetName
<typename
Types::Head
>(i
));
670 GenerateNamesRecursively
<NameGenerator
>(typename
Types::Tail(), result
,
674 template <typename NameGenerator
, typename Types
>
675 std::vector
<std::string
> GenerateNames() {
676 std::vector
<std::string
> result
;
677 GenerateNamesRecursively
<NameGenerator
>(Types(), &result
, 0);
681 // TypeParameterizedTest<Fixture, TestSel, Types>::Register()
682 // registers a list of type-parameterized tests with Google Test. The
683 // return value is insignificant - we just need to return something
684 // such that we can call this function in a namespace scope.
686 // Implementation note: The GTEST_TEMPLATE_ macro declares a template
687 // template parameter. It's defined in gtest-type-util.h.
688 template <GTEST_TEMPLATE_ Fixture
, class TestSel
, typename Types
>
689 class TypeParameterizedTest
{
691 // 'index' is the index of the test in the type list 'Types'
692 // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,
693 // Types). Valid values for 'index' are [0, N - 1] where N is the
695 static bool Register(const char* prefix
, const CodeLocation
& code_location
,
696 const char* case_name
, const char* test_names
, int index
,
697 const std::vector
<std::string
>& type_names
=
698 GenerateNames
<DefaultNameGenerator
, Types
>()) {
699 typedef typename
Types::Head Type
;
700 typedef Fixture
<Type
> FixtureClass
;
701 typedef typename
GTEST_BIND_(TestSel
, Type
) TestClass
;
703 // First, registers the first type-parameterized test in the type
705 MakeAndRegisterTestInfo(
706 (std::string(prefix
) + (prefix
[0] == '\0' ? "" : "/") + case_name
+
707 "/" + type_names
[static_cast<size_t>(index
)])
709 StripTrailingSpaces(GetPrefixUntilComma(test_names
)).c_str(),
710 GetTypeName
<Type
>().c_str(),
711 nullptr, // No value parameter.
712 code_location
, GetTypeId
<FixtureClass
>(),
713 SuiteApiResolver
<TestClass
>::GetSetUpCaseOrSuite(
714 code_location
.file
.c_str(), code_location
.line
),
715 SuiteApiResolver
<TestClass
>::GetTearDownCaseOrSuite(
716 code_location
.file
.c_str(), code_location
.line
),
717 new TestFactoryImpl
<TestClass
>);
719 // Next, recurses (at compile time) with the tail of the type list.
720 return TypeParameterizedTest
<Fixture
, TestSel
,
721 typename
Types::Tail
>::Register(prefix
,
730 // The base case for the compile time recursion.
731 template <GTEST_TEMPLATE_ Fixture
, class TestSel
>
732 class TypeParameterizedTest
<Fixture
, TestSel
, Types0
> {
734 static bool Register(const char* /*prefix*/, const CodeLocation
&,
735 const char* /*case_name*/, const char* /*test_names*/,
737 const std::vector
<std::string
>& =
738 std::vector
<std::string
>() /*type_names*/) {
743 // TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()
744 // registers *all combinations* of 'Tests' and 'Types' with Google
745 // Test. The return value is insignificant - we just need to return
746 // something such that we can call this function in a namespace scope.
747 template <GTEST_TEMPLATE_ Fixture
, typename Tests
, typename Types
>
748 class TypeParameterizedTestSuite
{
750 static bool Register(const char* prefix
, CodeLocation code_location
,
751 const TypedTestSuitePState
* state
, const char* case_name
,
752 const char* test_names
,
753 const std::vector
<std::string
>& type_names
=
754 GenerateNames
<DefaultNameGenerator
, Types
>()) {
755 std::string test_name
= StripTrailingSpaces(
756 GetPrefixUntilComma(test_names
));
757 if (!state
->TestExists(test_name
)) {
758 fprintf(stderr
, "Failed to get code location for test %s.%s at %s.",
759 case_name
, test_name
.c_str(),
760 FormatFileLocation(code_location
.file
.c_str(),
761 code_location
.line
).c_str());
765 const CodeLocation
& test_location
= state
->GetCodeLocation(test_name
);
767 typedef typename
Tests::Head Head
;
769 // First, register the first test in 'Test' for each type in 'Types'.
770 TypeParameterizedTest
<Fixture
, Head
, Types
>::Register(
771 prefix
, test_location
, case_name
, test_names
, 0, type_names
);
773 // Next, recurses (at compile time) with the tail of the test list.
774 return TypeParameterizedTestSuite
<Fixture
, typename
Tests::Tail
,
775 Types
>::Register(prefix
, code_location
,
777 SkipComma(test_names
),
782 // The base case for the compile time recursion.
783 template <GTEST_TEMPLATE_ Fixture
, typename Types
>
784 class TypeParameterizedTestSuite
<Fixture
, Templates0
, Types
> {
786 static bool Register(const char* /*prefix*/, const CodeLocation
&,
787 const TypedTestSuitePState
* /*state*/,
788 const char* /*case_name*/, const char* /*test_names*/,
789 const std::vector
<std::string
>& =
790 std::vector
<std::string
>() /*type_names*/) {
795 #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
797 // Returns the current OS stack trace as an std::string.
799 // The maximum number of stack frames to be included is specified by
800 // the gtest_stack_trace_depth flag. The skip_count parameter
801 // specifies the number of top frames to be skipped, which doesn't
802 // count against the number of frames to be included.
804 // For example, if Foo() calls Bar(), which in turn calls
805 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
806 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
807 GTEST_API_
std::string
GetCurrentOsStackTraceExceptTop(
808 UnitTest
* unit_test
, int skip_count
);
810 // Helpers for suppressing warnings on unreachable code or constant
813 // Always returns true.
814 GTEST_API_
bool AlwaysTrue();
816 // Always returns false.
817 inline bool AlwaysFalse() { return !AlwaysTrue(); }
819 // Helper for suppressing false warning from Clang on a const char*
820 // variable declared in a conditional expression always being NULL in
822 struct GTEST_API_ ConstCharPtr
{
823 ConstCharPtr(const char* str
) : value(str
) {}
824 operator bool() const { return true; }
828 // A simple Linear Congruential Generator for generating random
829 // numbers with a uniform distribution. Unlike rand() and srand(), it
830 // doesn't use global state (and therefore can't interfere with user
831 // code). Unlike rand_r(), it's portable. An LCG isn't very random,
832 // but it's good enough for our purposes.
833 class GTEST_API_ Random
{
835 static const UInt32 kMaxRange
= 1u << 31;
837 explicit Random(UInt32 seed
) : state_(seed
) {}
839 void Reseed(UInt32 seed
) { state_
= seed
; }
841 // Generates a random number from [0, range). Crashes if 'range' is
842 // 0 or greater than kMaxRange.
843 UInt32
Generate(UInt32 range
);
847 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random
);
850 // Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
851 // compiler error if T1 and T2 are different types.
852 template <typename T1
, typename T2
>
853 struct CompileAssertTypesEqual
;
855 template <typename T
>
856 struct CompileAssertTypesEqual
<T
, T
> {
859 // Removes the reference from a type if it is a reference type,
860 // otherwise leaves it unchanged. This is the same as
861 // tr1::remove_reference, which is not widely available yet.
862 template <typename T
>
863 struct RemoveReference
{ typedef T type
; }; // NOLINT
864 template <typename T
>
865 struct RemoveReference
<T
&> { typedef T type
; }; // NOLINT
867 // A handy wrapper around RemoveReference that works when the argument
868 // T depends on template parameters.
869 #define GTEST_REMOVE_REFERENCE_(T) \
870 typename ::testing::internal::RemoveReference<T>::type
872 // Turns const U&, U&, const U, and U all into U.
873 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
874 typename std::remove_const<GTEST_REMOVE_REFERENCE_(T)>::type
876 // IsAProtocolMessage<T>::value is a compile-time bool constant that's
877 // true if T is type proto2::Message or a subclass of it.
878 template <typename T
>
879 struct IsAProtocolMessage
880 : public bool_constant
<
881 std::is_convertible
<const T
*, const ::proto2::Message
*>::value
> {
884 // When the compiler sees expression IsContainerTest<C>(0), if C is an
885 // STL-style container class, the first overload of IsContainerTest
886 // will be viable (since both C::iterator* and C::const_iterator* are
887 // valid types and NULL can be implicitly converted to them). It will
888 // be picked over the second overload as 'int' is a perfect match for
889 // the type of argument 0. If C::iterator or C::const_iterator is not
890 // a valid type, the first overload is not viable, and the second
891 // overload will be picked. Therefore, we can determine whether C is
892 // a container class by checking the type of IsContainerTest<C>(0).
893 // The value of the expression is insignificant.
895 // In C++11 mode we check the existence of a const_iterator and that an
896 // iterator is properly implemented for the container.
898 // For pre-C++11 that we look for both C::iterator and C::const_iterator.
899 // The reason is that C++ injects the name of a class as a member of the
900 // class itself (e.g. you can refer to class iterator as either
901 // 'iterator' or 'iterator::iterator'). If we look for C::iterator
902 // only, for example, we would mistakenly think that a class named
903 // iterator is an STL container.
905 // Also note that the simpler approach of overloading
906 // IsContainerTest(typename C::const_iterator*) and
907 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
908 typedef int IsContainer
;
910 class Iterator
= decltype(::std::declval
<const C
&>().begin()),
911 class = decltype(::std::declval
<const C
&>().end()),
912 class = decltype(++::std::declval
<Iterator
&>()),
913 class = decltype(*::std::declval
<Iterator
>()),
914 class = typename
C::const_iterator
>
915 IsContainer
IsContainerTest(int /* dummy */) {
919 typedef char IsNotContainer
;
921 IsNotContainer
IsContainerTest(long /* dummy */) { return '\0'; }
923 // Trait to detect whether a type T is a hash table.
924 // The heuristic used is that the type contains an inner type `hasher` and does
925 // not contain an inner type `reverse_iterator`.
926 // If the container is iterable in reverse, then order might actually matter.
927 template <typename T
>
930 template <typename U
>
931 static char test(typename
U::hasher
*, typename
U::reverse_iterator
*);
932 template <typename U
>
933 static int test(typename
U::hasher
*, ...);
934 template <typename U
>
935 static char test(...);
938 static const bool value
= sizeof(test
<T
>(nullptr, nullptr)) == sizeof(int);
941 template <typename T
>
942 const bool IsHashTable
<T
>::value
;
944 template <typename C
,
945 bool = sizeof(IsContainerTest
<C
>(0)) == sizeof(IsContainer
)>
946 struct IsRecursiveContainerImpl
;
948 template <typename C
>
949 struct IsRecursiveContainerImpl
<C
, false> : public std::false_type
{};
951 // Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
952 // obey the same inconsistencies as the IsContainerTest, namely check if
953 // something is a container is relying on only const_iterator in C++11 and
954 // is relying on both const_iterator and iterator otherwise
955 template <typename C
>
956 struct IsRecursiveContainerImpl
<C
, true> {
957 using value_type
= decltype(*std::declval
<typename
C::const_iterator
>());
959 std::is_same
<typename
std::remove_const
<
960 typename
std::remove_reference
<value_type
>::type
>::type
,
964 // IsRecursiveContainer<Type> is a unary compile-time predicate that
965 // evaluates whether C is a recursive container type. A recursive container
966 // type is a container type whose value_type is equal to the container type
967 // itself. An example for a recursive container type is
968 // boost::filesystem::path, whose iterator has a value_type that is equal to
969 // boost::filesystem::path.
970 template <typename C
>
971 struct IsRecursiveContainer
: public IsRecursiveContainerImpl
<C
>::type
{};
973 // Utilities for native arrays.
975 // ArrayEq() compares two k-dimensional native arrays using the
976 // elements' operator==, where k can be any integer >= 0. When k is
977 // 0, ArrayEq() degenerates into comparing a single pair of values.
979 template <typename T
, typename U
>
980 bool ArrayEq(const T
* lhs
, size_t size
, const U
* rhs
);
982 // This generic version is used when k is 0.
983 template <typename T
, typename U
>
984 inline bool ArrayEq(const T
& lhs
, const U
& rhs
) { return lhs
== rhs
; }
986 // This overload is used when k >= 1.
987 template <typename T
, typename U
, size_t N
>
988 inline bool ArrayEq(const T(&lhs
)[N
], const U(&rhs
)[N
]) {
989 return internal::ArrayEq(lhs
, N
, rhs
);
992 // This helper reduces code bloat. If we instead put its logic inside
993 // the previous ArrayEq() function, arrays with different sizes would
994 // lead to different copies of the template code.
995 template <typename T
, typename U
>
996 bool ArrayEq(const T
* lhs
, size_t size
, const U
* rhs
) {
997 for (size_t i
= 0; i
!= size
; i
++) {
998 if (!internal::ArrayEq(lhs
[i
], rhs
[i
]))
1004 // Finds the first element in the iterator range [begin, end) that
1005 // equals elem. Element may be a native array type itself.
1006 template <typename Iter
, typename Element
>
1007 Iter
ArrayAwareFind(Iter begin
, Iter end
, const Element
& elem
) {
1008 for (Iter it
= begin
; it
!= end
; ++it
) {
1009 if (internal::ArrayEq(*it
, elem
))
1015 // CopyArray() copies a k-dimensional native array using the elements'
1016 // operator=, where k can be any integer >= 0. When k is 0,
1017 // CopyArray() degenerates into copying a single value.
1019 template <typename T
, typename U
>
1020 void CopyArray(const T
* from
, size_t size
, U
* to
);
1022 // This generic version is used when k is 0.
1023 template <typename T
, typename U
>
1024 inline void CopyArray(const T
& from
, U
* to
) { *to
= from
; }
1026 // This overload is used when k >= 1.
1027 template <typename T
, typename U
, size_t N
>
1028 inline void CopyArray(const T(&from
)[N
], U(*to
)[N
]) {
1029 internal::CopyArray(from
, N
, *to
);
1032 // This helper reduces code bloat. If we instead put its logic inside
1033 // the previous CopyArray() function, arrays with different sizes
1034 // would lead to different copies of the template code.
1035 template <typename T
, typename U
>
1036 void CopyArray(const T
* from
, size_t size
, U
* to
) {
1037 for (size_t i
= 0; i
!= size
; i
++) {
1038 internal::CopyArray(from
[i
], to
+ i
);
1042 // The relation between an NativeArray object (see below) and the
1043 // native array it represents.
1044 // We use 2 different structs to allow non-copyable types to be used, as long
1045 // as RelationToSourceReference() is passed.
1046 struct RelationToSourceReference
{};
1047 struct RelationToSourceCopy
{};
1049 // Adapts a native array to a read-only STL-style container. Instead
1050 // of the complete STL container concept, this adaptor only implements
1051 // members useful for Google Mock's container matchers. New members
1052 // should be added as needed. To simplify the implementation, we only
1053 // support Element being a raw type (i.e. having no top-level const or
1054 // reference modifier). It's the client's responsibility to satisfy
1055 // this requirement. Element can be an array type itself (hence
1056 // multi-dimensional arrays are supported).
1057 template <typename Element
>
1060 // STL-style container typedefs.
1061 typedef Element value_type
;
1062 typedef Element
* iterator
;
1063 typedef const Element
* const_iterator
;
1065 // Constructs from a native array. References the source.
1066 NativeArray(const Element
* array
, size_t count
, RelationToSourceReference
) {
1067 InitRef(array
, count
);
1070 // Constructs from a native array. Copies the source.
1071 NativeArray(const Element
* array
, size_t count
, RelationToSourceCopy
) {
1072 InitCopy(array
, count
);
1075 // Copy constructor.
1076 NativeArray(const NativeArray
& rhs
) {
1077 (this->*rhs
.clone_
)(rhs
.array_
, rhs
.size_
);
1081 if (clone_
!= &NativeArray::InitRef
)
1085 // STL-style container methods.
1086 size_t size() const { return size_
; }
1087 const_iterator
begin() const { return array_
; }
1088 const_iterator
end() const { return array_
+ size_
; }
1089 bool operator==(const NativeArray
& rhs
) const {
1090 return size() == rhs
.size() &&
1091 ArrayEq(begin(), size(), rhs
.begin());
1096 kCheckTypeIsNotConstOrAReference
= StaticAssertTypeEqHelper
<
1097 Element
, GTEST_REMOVE_REFERENCE_AND_CONST_(Element
)>::value
1100 // Initializes this object with a copy of the input.
1101 void InitCopy(const Element
* array
, size_t a_size
) {
1102 Element
* const copy
= new Element
[a_size
];
1103 CopyArray(array
, a_size
, copy
);
1106 clone_
= &NativeArray::InitCopy
;
1109 // Initializes this object with a reference of the input.
1110 void InitRef(const Element
* array
, size_t a_size
) {
1113 clone_
= &NativeArray::InitRef
;
1116 const Element
* array_
;
1118 void (NativeArray::*clone_
)(const Element
*, size_t);
1120 GTEST_DISALLOW_ASSIGN_(NativeArray
);
1123 // Backport of std::index_sequence.
1124 template <size_t... Is
>
1125 struct IndexSequence
{
1126 using type
= IndexSequence
;
1129 // Double the IndexSequence, and one if plus_one is true.
1130 template <bool plus_one
, typename T
, size_t sizeofT
>
1131 struct DoubleSequence
;
1132 template <size_t... I
, size_t sizeofT
>
1133 struct DoubleSequence
<true, IndexSequence
<I
...>, sizeofT
> {
1134 using type
= IndexSequence
<I
..., (sizeofT
+ I
)..., 2 * sizeofT
>;
1136 template <size_t... I
, size_t sizeofT
>
1137 struct DoubleSequence
<false, IndexSequence
<I
...>, sizeofT
> {
1138 using type
= IndexSequence
<I
..., (sizeofT
+ I
)...>;
1141 // Backport of std::make_index_sequence.
1142 // It uses O(ln(N)) instantiation depth.
1144 struct MakeIndexSequence
1145 : DoubleSequence
<N
% 2 == 1, typename MakeIndexSequence
<N
/ 2>::type
,
1149 struct MakeIndexSequence
<0> : IndexSequence
<> {};
1151 // FIXME: This implementation of ElemFromList is O(1) in instantiation depth,
1152 // but it is O(N^2) in total instantiations. Not sure if this is the best
1153 // tradeoff, as it will make it somewhat slow to compile.
1154 template <typename T
, size_t, size_t>
1155 struct ElemFromListImpl
{};
1157 template <typename T
, size_t I
>
1158 struct ElemFromListImpl
<T
, I
, I
> {
1162 // Get the Nth element from T...
1163 // It uses O(1) instantiation depth.
1164 template <size_t N
, typename I
, typename
... T
>
1165 struct ElemFromList
;
1167 template <size_t N
, size_t... I
, typename
... T
>
1168 struct ElemFromList
<N
, IndexSequence
<I
...>, T
...>
1169 : ElemFromListImpl
<T
, N
, I
>... {};
1171 template <typename
... T
>
1174 template <typename Derived
, size_t I
>
1175 struct FlatTupleElemBase
;
1177 template <typename
... T
, size_t I
>
1178 struct FlatTupleElemBase
<FlatTuple
<T
...>, I
> {
1180 typename ElemFromList
<I
, typename MakeIndexSequence
<sizeof...(T
)>::type
,
1182 FlatTupleElemBase() = default;
1183 explicit FlatTupleElemBase(value_type t
) : value(std::move(t
)) {}
1187 template <typename Derived
, typename Idx
>
1188 struct FlatTupleBase
;
1190 template <size_t... Idx
, typename
... T
>
1191 struct FlatTupleBase
<FlatTuple
<T
...>, IndexSequence
<Idx
...>>
1192 : FlatTupleElemBase
<FlatTuple
<T
...>, Idx
>... {
1193 using Indices
= IndexSequence
<Idx
...>;
1194 FlatTupleBase() = default;
1195 explicit FlatTupleBase(T
... t
)
1196 : FlatTupleElemBase
<FlatTuple
<T
...>, Idx
>(std::move(t
))... {}
1199 // Analog to std::tuple but with different tradeoffs.
1200 // This class minimizes the template instantiation depth, thus allowing more
1201 // elements that std::tuple would. std::tuple has been seen to require an
1202 // instantiation depth of more than 10x the number of elements in some
1204 // FlatTuple and ElemFromList are not recursive and have a fixed depth
1205 // regardless of T...
1206 // MakeIndexSequence, on the other hand, it is recursive but with an
1207 // instantiation depth of O(ln(N)).
1208 template <typename
... T
>
1210 : private FlatTupleBase
<FlatTuple
<T
...>,
1211 typename MakeIndexSequence
<sizeof...(T
)>::type
> {
1212 using Indices
= typename
FlatTuple::FlatTupleBase::Indices
;
1215 FlatTuple() = default;
1216 explicit FlatTuple(T
... t
) : FlatTuple::FlatTupleBase(std::move(t
)...) {}
1219 const typename ElemFromList
<I
, Indices
, T
...>::type
& Get() const {
1220 return static_cast<const FlatTupleElemBase
<FlatTuple
, I
>*>(this)->value
;
1224 typename ElemFromList
<I
, Indices
, T
...>::type
& Get() {
1225 return static_cast<FlatTupleElemBase
<FlatTuple
, I
>*>(this)->value
;
1229 // Utility functions to be called with static_assert to induce deprecation
1231 GTEST_INTERNAL_DEPRECATED(
1232 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
1233 "INSTANTIATE_TEST_SUITE_P")
1234 constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
1236 GTEST_INTERNAL_DEPRECATED(
1237 "TYPED_TEST_CASE_P is deprecated, please use "
1238 "TYPED_TEST_SUITE_P")
1239 constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
1241 GTEST_INTERNAL_DEPRECATED(
1242 "TYPED_TEST_CASE is deprecated, please use "
1244 constexpr bool TypedTestCaseIsDeprecated() { return true; }
1246 GTEST_INTERNAL_DEPRECATED(
1247 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
1248 "REGISTER_TYPED_TEST_SUITE_P")
1249 constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
1251 GTEST_INTERNAL_DEPRECATED(
1252 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
1253 "INSTANTIATE_TYPED_TEST_SUITE_P")
1254 constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
1256 } // namespace internal
1257 } // namespace testing
1259 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1260 ::testing::internal::AssertHelper(result_type, file, line, message) \
1261 = ::testing::Message()
1263 #define GTEST_MESSAGE_(message, result_type) \
1264 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1266 #define GTEST_FATAL_FAILURE_(message) \
1267 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1269 #define GTEST_NONFATAL_FAILURE_(message) \
1270 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1272 #define GTEST_SUCCESS_(message) \
1273 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1275 #define GTEST_SKIP_(message) \
1276 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
1278 // Suppress MSVC warning 4072 (unreachable code) for the code following
1279 // statement if it returns or throws (or doesn't return or throw in some
1281 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1282 if (::testing::internal::AlwaysTrue()) { statement; }
1284 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1285 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1286 if (::testing::internal::ConstCharPtr gtest_msg = "") { \
1287 bool gtest_caught_expected = false; \
1289 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1291 catch (expected_exception const&) { \
1292 gtest_caught_expected = true; \
1296 "Expected: " #statement " throws an exception of type " \
1297 #expected_exception ".\n Actual: it throws a different type."; \
1298 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1300 if (!gtest_caught_expected) { \
1302 "Expected: " #statement " throws an exception of type " \
1303 #expected_exception ".\n Actual: it throws nothing."; \
1304 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1307 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
1308 fail(gtest_msg.value)
1310 #define GTEST_TEST_NO_THROW_(statement, fail) \
1311 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1312 if (::testing::internal::AlwaysTrue()) { \
1314 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1317 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1320 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
1321 fail("Expected: " #statement " doesn't throw an exception.\n" \
1322 " Actual: it throws.")
1324 #define GTEST_TEST_ANY_THROW_(statement, fail) \
1325 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1326 if (::testing::internal::AlwaysTrue()) { \
1327 bool gtest_caught_any = false; \
1329 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1332 gtest_caught_any = true; \
1334 if (!gtest_caught_any) { \
1335 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1338 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1339 fail("Expected: " #statement " throws an exception.\n" \
1340 " Actual: it doesn't.")
1343 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1344 // either a boolean expression or an AssertionResult. text is a textual
1345 // represenation of expression as it was passed into the EXPECT_TRUE.
1346 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1347 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1348 if (const ::testing::AssertionResult gtest_ar_ = \
1349 ::testing::AssertionResult(expression)) \
1352 fail(::testing::internal::GetBoolAssertionFailureMessage(\
1353 gtest_ar_, text, #actual, #expected).c_str())
1355 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1356 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1357 if (::testing::internal::AlwaysTrue()) { \
1358 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1359 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1360 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1361 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1364 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1365 fail("Expected: " #statement " doesn't generate new fatal " \
1366 "failures in the current thread.\n" \
1367 " Actual: it does.")
1369 // Expands to the name of the class that implements the given test.
1370 #define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1371 test_suite_name##_##test_name##_Test
1373 // Helper macro for defining tests.
1374 #define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
1375 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1376 : public parent_class { \
1378 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
1381 virtual void TestBody(); \
1382 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
1383 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
1387 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
1388 test_name)::test_info_ = \
1389 ::testing::internal::MakeAndRegisterTestInfo( \
1390 #test_suite_name, #test_name, nullptr, nullptr, \
1391 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
1392 ::testing::internal::SuiteApiResolver< \
1393 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
1394 ::testing::internal::SuiteApiResolver< \
1395 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
1396 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
1397 test_suite_name, test_name)>); \
1398 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
1400 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_