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