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