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