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