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