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 if 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 if 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 if 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 if 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// Turns const U&, U&, const U, and U all into U.
873#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
874 typename std::remove_const<GTEST_REMOVE_REFERENCE_(T)>::type
875
876// IsAProtocolMessage<T>::value is a compile-time bool constant that's
877// true if T is type proto2::Message or a subclass of it.
878template <typename T>
879struct IsAProtocolMessage
880 : public bool_constant<
881 std::is_convertible<const T*, const ::proto2::Message*>::value> {
882};
883
884// When the compiler sees expression IsContainerTest<C>(0), if C is an
885// STL-style container class, the first overload of IsContainerTest
886// will be viable (since both C::iterator* and C::const_iterator* are
887// valid types and NULL can be implicitly converted to them). It will
888// be picked over the second overload as 'int' is a perfect match for
889// the type of argument 0. If C::iterator or C::const_iterator is not
890// a valid type, the first overload is not viable, and the second
891// overload will be picked. Therefore, we can determine whether C is
892// a container class by checking the type of IsContainerTest<C>(0).
893// The value of the expression is insignificant.
894//
895// In C++11 mode we check the existence of a const_iterator and that an
896// iterator is properly implemented for the container.
897//
898// For pre-C++11 that we look for both C::iterator and C::const_iterator.
899// The reason is that C++ injects the name of a class as a member of the
900// class itself (e.g. you can refer to class iterator as either
901// 'iterator' or 'iterator::iterator'). If we look for C::iterator
902// only, for example, we would mistakenly think that a class named
903// iterator is an STL container.
904//
905// Also note that the simpler approach of overloading
906// IsContainerTest(typename C::const_iterator*) and
907// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
908typedef int IsContainer;
909template <class C,
910 class Iterator = decltype(::std::declval<const C&>().begin()),
911 class = decltype(::std::declval<const C&>().end()),
912 class = decltype(++::std::declval<Iterator&>()),
913 class = decltype(*::std::declval<Iterator>()),
914 class = typename C::const_iterator>
915IsContainer IsContainerTest(int /* dummy */) {
916 return 0;
917}
918
919typedef char IsNotContainer;
920template <class C>
921IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
922
923// Trait to detect whether a type T is a hash table.
924// The heuristic used is that the type contains an inner type `hasher` and does
925// not contain an inner type `reverse_iterator`.
926// If the container is iterable in reverse, then order might actually matter.
927template <typename T>
928struct IsHashTable {
929 private:
930 template <typename U>
931 static char test(typename U::hasher*, typename U::reverse_iterator*);
932 template <typename U>
933 static int test(typename U::hasher*, ...);
934 template <typename U>
935 static char test(...);
936
937 public:
938 static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);
939};
940
941template <typename T>
942const bool IsHashTable<T>::value;
943
944template <typename C,
945 bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>
946struct IsRecursiveContainerImpl;
947
948template <typename C>
949struct IsRecursiveContainerImpl<C, false> : public false_type {};
950
951// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to
952// obey the same inconsistencies as the IsContainerTest, namely check if
953// something is a container is relying on only const_iterator in C++11 and
954// is relying on both const_iterator and iterator otherwise
955template <typename C>
956struct IsRecursiveContainerImpl<C, true> {
957 using value_type = decltype(*std::declval<typename C::const_iterator>());
958 using type =
959 std::is_same<typename std::remove_const<
960 typename std::remove_reference<value_type>::type>::type,
961 C>;
962};
963
964// IsRecursiveContainer<Type> is a unary compile-time predicate that
965// evaluates whether C is a recursive container type. A recursive container
966// type is a container type whose value_type is equal to the container type
967// itself. An example for a recursive container type is
968// boost::filesystem::path, whose iterator has a value_type that is equal to
969// boost::filesystem::path.
970template <typename C>
971struct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};
972
973// EnableIf<condition>::type is void when 'Cond' is true, and
974// undefined when 'Cond' is false. To use SFINAE to make a function
975// overload only apply when a particular expression is true, add
976// "typename EnableIf<expression>::type* = 0" as the last parameter.
977template<bool> struct EnableIf;
978template<> struct EnableIf<true> { typedef void type; }; // NOLINT
979
980// Utilities for native arrays.
981
982// ArrayEq() compares two k-dimensional native arrays using the
983// elements' operator==, where k can be any integer >= 0. When k is
984// 0, ArrayEq() degenerates into comparing a single pair of values.
985
986template <typename T, typename U>
987bool ArrayEq(const T* lhs, size_t size, const U* rhs);
988
989// This generic version is used when k is 0.
990template <typename T, typename U>
991inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
992
993// This overload is used when k >= 1.
994template <typename T, typename U, size_t N>
995inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
996 return internal::ArrayEq(lhs, N, rhs);
997}
998
999// This helper reduces code bloat. If we instead put its logic inside
1000// the previous ArrayEq() function, arrays with different sizes would
1001// lead to different copies of the template code.
1002template <typename T, typename U>
1003bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
1004 for (size_t i = 0; i != size; i++) {
1005 if (!internal::ArrayEq(lhs[i], rhs[i]))
1006 return false;
1007 }
1008 return true;
1009}
1010
1011// Finds the first element in the iterator range [begin, end) that
1012// equals elem. Element may be a native array type itself.
1013template <typename Iter, typename Element>
1014Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
1015 for (Iter it = begin; it != end; ++it) {
1016 if (internal::ArrayEq(*it, elem))
1017 return it;
1018 }
1019 return end;
1020}
1021
1022// CopyArray() copies a k-dimensional native array using the elements'
1023// operator=, where k can be any integer >= 0. When k is 0,
1024// CopyArray() degenerates into copying a single value.
1025
1026template <typename T, typename U>
1027void CopyArray(const T* from, size_t size, U* to);
1028
1029// This generic version is used when k is 0.
1030template <typename T, typename U>
1031inline void CopyArray(const T& from, U* to) { *to = from; }
1032
1033// This overload is used when k >= 1.
1034template <typename T, typename U, size_t N>
1035inline void CopyArray(const T(&from)[N], U(*to)[N]) {
1036 internal::CopyArray(from, N, *to);
1037}
1038
1039// This helper reduces code bloat. If we instead put its logic inside
1040// the previous CopyArray() function, arrays with different sizes
1041// would lead to different copies of the template code.
1042template <typename T, typename U>
1043void CopyArray(const T* from, size_t size, U* to) {
1044 for (size_t i = 0; i != size; i++) {
1045 internal::CopyArray(from[i], to + i);
1046 }
1047}
1048
1049// The relation between an NativeArray object (see below) and the
1050// native array it represents.
1051// We use 2 different structs to allow non-copyable types to be used, as long
1052// as RelationToSourceReference() is passed.
1053struct RelationToSourceReference {};
1054struct RelationToSourceCopy {};
1055
1056// Adapts a native array to a read-only STL-style container. Instead
1057// of the complete STL container concept, this adaptor only implements
1058// members useful for Google Mock's container matchers. New members
1059// should be added as needed. To simplify the implementation, we only
1060// support Element being a raw type (i.e. having no top-level const or
1061// reference modifier). It's the client's responsibility to satisfy
1062// this requirement. Element can be an array type itself (hence
1063// multi-dimensional arrays are supported).
1064template <typename Element>
1065class NativeArray {
1066 public:
1067 // STL-style container typedefs.
1068 typedef Element value_type;
1069 typedef Element* iterator;
1070 typedef const Element* const_iterator;
1071
1072 // Constructs from a native array. References the source.
1073 NativeArray(const Element* array, size_t count, RelationToSourceReference) {
1074 InitRef(array, count);
1075 }
1076
1077 // Constructs from a native array. Copies the source.
1078 NativeArray(const Element* array, size_t count, RelationToSourceCopy) {
1079 InitCopy(array, count);
1080 }
1081
1082 // Copy constructor.
1083 NativeArray(const NativeArray& rhs) {
1084 (this->*rhs.clone_)(rhs.array_, rhs.size_);
1085 }
1086
1087 ~NativeArray() {
1088 if (clone_ != &NativeArray::InitRef)
1089 delete[] array_;
1090 }
1091
1092 // STL-style container methods.
1093 size_t size() const { return size_; }
1094 const_iterator begin() const { return array_; }
1095 const_iterator end() const { return array_ + size_; }
1096 bool operator==(const NativeArray& rhs) const {
1097 return size() == rhs.size() &&
1098 ArrayEq(begin(), size(), rhs.begin());
1099 }
1100
1101 private:
1102 enum {
1103 kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper<
1104 Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value
1105 };
1106
1107 // Initializes this object with a copy of the input.
1108 void InitCopy(const Element* array, size_t a_size) {
1109 Element* const copy = new Element[a_size];
1110 CopyArray(array, a_size, copy);
1111 array_ = copy;
1112 size_ = a_size;
1113 clone_ = &NativeArray::InitCopy;
1114 }
1115
1116 // Initializes this object with a reference of the input.
1117 void InitRef(const Element* array, size_t a_size) {
1118 array_ = array;
1119 size_ = a_size;
1120 clone_ = &NativeArray::InitRef;
1121 }
1122
1123 const Element* array_;
1124 size_t size_;
1125 void (NativeArray::*clone_)(const Element*, size_t);
1126
1127 GTEST_DISALLOW_ASSIGN_(NativeArray);
1128};
1129
1130// Backport of std::index_sequence.
1131template <size_t... Is>
1132struct IndexSequence {
1133 using type = IndexSequence;
1134};
1135
1136// Double the IndexSequence, and one if plus_one is true.
1137template <bool plus_one, typename T, size_t sizeofT>
1138struct DoubleSequence;
1139template <size_t... I, size_t sizeofT>
1140struct DoubleSequence<true, IndexSequence<I...>, sizeofT> {
1141 using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;
1142};
1143template <size_t... I, size_t sizeofT>
1144struct DoubleSequence<false, IndexSequence<I...>, sizeofT> {
1145 using type = IndexSequence<I..., (sizeofT + I)...>;
1146};
1147
1148// Backport of std::make_index_sequence.
1149// It uses O(ln(N)) instantiation depth.
1150template <size_t N>
1151struct MakeIndexSequence
1152 : DoubleSequence<N % 2 == 1, typename MakeIndexSequence<N / 2>::type,
1153 N / 2>::type {};
1154
1155template <>
1156struct MakeIndexSequence<0> : IndexSequence<> {};
1157
1158// FIXME: This implementation of ElemFromList is O(1) in instantiation depth,
1159// but it is O(N^2) in total instantiations. Not sure if this is the best
1160// tradeoff, as it will make it somewhat slow to compile.
1161template <typename T, size_t, size_t>
1162struct ElemFromListImpl {};
1163
1164template <typename T, size_t I>
1165struct ElemFromListImpl<T, I, I> {
1166 using type = T;
1167};
1168
1169// Get the Nth element from T...
1170// It uses O(1) instantiation depth.
1171template <size_t N, typename I, typename... T>
1172struct ElemFromList;
1173
1174template <size_t N, size_t... I, typename... T>
1175struct ElemFromList<N, IndexSequence<I...>, T...>
1176 : ElemFromListImpl<T, N, I>... {};
1177
1178template <typename... T>
1179class FlatTuple;
1180
1181template <typename Derived, size_t I>
1182struct FlatTupleElemBase;
1183
1184template <typename... T, size_t I>
1185struct FlatTupleElemBase<FlatTuple<T...>, I> {
1186 using value_type =
1187 typename ElemFromList<I, typename MakeIndexSequence<sizeof...(T)>::type,
1188 T...>::type;
1189 FlatTupleElemBase() = default;
1190 explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {}
1191 value_type value;
1192};
1193
1194template <typename Derived, typename Idx>
1195struct FlatTupleBase;
1196
1197template <size_t... Idx, typename... T>
1198struct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>
1199 : FlatTupleElemBase<FlatTuple<T...>, Idx>... {
1200 using Indices = IndexSequence<Idx...>;
1201 FlatTupleBase() = default;
1202 explicit FlatTupleBase(T... t)
1203 : FlatTupleElemBase<FlatTuple<T...>, Idx>(std::move(t))... {}
1204};
1205
1206// Analog to std::tuple but with different tradeoffs.
1207// This class minimizes the template instantiation depth, thus allowing more
1208// elements that std::tuple would. std::tuple has been seen to require an
1209// instantiation depth of more than 10x the number of elements in some
1210// implementations.
1211// FlatTuple and ElemFromList are not recursive and have a fixed depth
1212// regardless of T...
1213// MakeIndexSequence, on the other hand, it is recursive but with an
1214// instantiation depth of O(ln(N)).
1215template <typename... T>
1216class FlatTuple
1217 : private FlatTupleBase<FlatTuple<T...>,
1218 typename MakeIndexSequence<sizeof...(T)>::type> {
1219 using Indices = typename FlatTuple::FlatTupleBase::Indices;
1220
1221 public:
1222 FlatTuple() = default;
1223 explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {}
1224
1225 template <size_t I>
1226 const typename ElemFromList<I, Indices, T...>::type& Get() const {
1227 return static_cast<const FlatTupleElemBase<FlatTuple, I>*>(this)->value;
1228 }
1229
1230 template <size_t I>
1231 typename ElemFromList<I, Indices, T...>::type& Get() {
1232 return static_cast<FlatTupleElemBase<FlatTuple, I>*>(this)->value;
1233 }
1234};
1235
1236// Utility functions to be called with static_assert to induce deprecation
1237// warnings.
1238GTEST_INTERNAL_DEPRECATED(
1239 "INSTANTIATE_TEST_CASE_P is deprecated, please use "
1240 "INSTANTIATE_TEST_SUITE_P")
1241constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }
1242
1243GTEST_INTERNAL_DEPRECATED(
1244 "TYPED_TEST_CASE_P is deprecated, please use "
1245 "TYPED_TEST_SUITE_P")
1246constexpr bool TypedTestCase_P_IsDeprecated() { return true; }
1247
1248GTEST_INTERNAL_DEPRECATED(
1249 "TYPED_TEST_CASE is deprecated, please use "
1250 "TYPED_TEST_SUITE")
1251constexpr bool TypedTestCaseIsDeprecated() { return true; }
1252
1253GTEST_INTERNAL_DEPRECATED(
1254 "REGISTER_TYPED_TEST_CASE_P is deprecated, please use "
1255 "REGISTER_TYPED_TEST_SUITE_P")
1256constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }
1257
1258GTEST_INTERNAL_DEPRECATED(
1259 "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use "
1260 "INSTANTIATE_TYPED_TEST_SUITE_P")
1261constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }
1262
1263} // namespace internal
1264} // namespace testing
1265
1266#define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1267 ::testing::internal::AssertHelper(result_type, file, line, message) \
1268 = ::testing::Message()
1269
1270#define GTEST_MESSAGE_(message, result_type) \
1271 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1272
1273#define GTEST_FATAL_FAILURE_(message) \
1274 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1275
1276#define GTEST_NONFATAL_FAILURE_(message) \
1277 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1278
1279#define GTEST_SUCCESS_(message) \
1280 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1281
1282#define GTEST_SKIP_(message) \
1283 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)
1284
1285// Suppress MSVC warning 4072 (unreachable code) for the code following
1286// statement if it returns or throws (or doesn't return or throw in some
1287// situations).
1288#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1289 if (::testing::internal::AlwaysTrue()) { statement; }
1290
1291#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1292 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1293 if (::testing::internal::ConstCharPtr gtest_msg = "") { \
1294 bool gtest_caught_expected = false; \
1295 try { \
1296 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1297 } \
1298 catch (expected_exception const&) { \
1299 gtest_caught_expected = true; \
1300 } \
1301 catch (...) { \
1302 gtest_msg.value = \
1303 "Expected: " #statement " throws an exception of type " \
1304 #expected_exception ".\n Actual: it throws a different type."; \
1305 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1306 } \
1307 if (!gtest_caught_expected) { \
1308 gtest_msg.value = \
1309 "Expected: " #statement " throws an exception of type " \
1310 #expected_exception ".\n Actual: it throws nothing."; \
1311 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1312 } \
1313 } else \
1314 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
1315 fail(gtest_msg.value)
1316
1317#define GTEST_TEST_NO_THROW_(statement, fail) \
1318 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1319 if (::testing::internal::AlwaysTrue()) { \
1320 try { \
1321 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1322 } \
1323 catch (...) { \
1324 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1325 } \
1326 } else \
1327 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
1328 fail("Expected: " #statement " doesn't throw an exception.\n" \
1329 " Actual: it throws.")
1330
1331#define GTEST_TEST_ANY_THROW_(statement, fail) \
1332 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1333 if (::testing::internal::AlwaysTrue()) { \
1334 bool gtest_caught_any = false; \
1335 try { \
1336 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1337 } \
1338 catch (...) { \
1339 gtest_caught_any = true; \
1340 } \
1341 if (!gtest_caught_any) { \
1342 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1343 } \
1344 } else \
1345 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1346 fail("Expected: " #statement " throws an exception.\n" \
1347 " Actual: it doesn't.")
1348
1349
1350// Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1351// either a boolean expression or an AssertionResult. text is a textual
1352// represenation of expression as it was passed into the EXPECT_TRUE.
1353#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1354 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1355 if (const ::testing::AssertionResult gtest_ar_ = \
1356 ::testing::AssertionResult(expression)) \
1357 ; \
1358 else \
1359 fail(::testing::internal::GetBoolAssertionFailureMessage(\
1360 gtest_ar_, text, #actual, #expected).c_str())
1361
1362#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1363 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1364 if (::testing::internal::AlwaysTrue()) { \
1365 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1366 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1367 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1368 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1369 } \
1370 } else \
1371 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1372 fail("Expected: " #statement " doesn't generate new fatal " \
1373 "failures in the current thread.\n" \
1374 " Actual: it does.")
1375
1376// Expands to the name of the class that implements the given test.
1377#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1378 test_suite_name##_##test_name##_Test
1379
1380// Helper macro for defining tests.
1381#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \
1382 class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \
1383 : public parent_class { \
1384 public: \
1385 GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \
1386 \
1387 private: \
1388 virtual void TestBody(); \
1389 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
1390 GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \
1391 test_name)); \
1392 }; \
1393 \
1394 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \
1395 test_name)::test_info_ = \
1396 ::testing::internal::MakeAndRegisterTestInfo( \
1397 #test_suite_name, #test_name, nullptr, nullptr, \
1398 ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
1399 ::testing::internal::SuiteApiResolver< \
1400 parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \
1401 ::testing::internal::SuiteApiResolver< \
1402 parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \
1403 new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
1404 test_suite_name, test_name)>); \
1405 void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()
1406
1407#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
1408