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