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