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