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