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