gtest-internal.h revision 96839103cf05c81525e57ef00456e0afac90823f
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#include <ctype.h>
50#include <string.h>
51#include <iomanip>
52#include <limits>
53#include <set>
54
55#include <gtest/internal/gtest-string.h>
56#include <gtest/internal/gtest-filepath.h>
57#include <gtest/internal/gtest-type-util.h>
58
59// Due to C++ preprocessor weirdness, we need double indirection to
60// concatenate two tokens when one of them is __LINE__.  Writing
61//
62//   foo ## __LINE__
63//
64// will result in the token foo__LINE__, instead of foo followed by
65// the current line number.  For more details, see
66// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
67#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
68#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
69
70// Google Test defines the testing::Message class to allow construction of
71// test messages via the << operator.  The idea is that anything
72// streamable to std::ostream can be streamed to a testing::Message.
73// This allows a user to use his own types in Google Test assertions by
74// overloading the << operator.
75//
76// util/gtl/stl_logging-inl.h overloads << for STL containers.  These
77// overloads cannot be defined in the std namespace, as that will be
78// undefined behavior.  Therefore, they are defined in the global
79// namespace instead.
80//
81// C++'s symbol lookup rule (i.e. Koenig lookup) says that these
82// overloads are visible in either the std namespace or the global
83// namespace, but not other namespaces, including the testing
84// namespace which Google Test's Message class is in.
85//
86// To allow STL containers (and other types that has a << operator
87// defined in the global namespace) to be used in Google Test assertions,
88// testing::Message must access the custom << operator from the global
89// namespace.  Hence this helper function.
90//
91// Note: Jeffrey Yasskin suggested an alternative fix by "using
92// ::operator<<;" in the definition of Message's operator<<.  That fix
93// doesn't require a helper function, but unfortunately doesn't
94// compile with MSVC.
95template <typename T>
96inline void GTestStreamToHelper(std::ostream* os, const T& val) {
97  *os << val;
98}
99
100namespace testing {
101
102// Forward declaration of classes.
103
104class Message;                         // Represents a failure message.
105class Test;                            // Represents a test.
106class TestCase;                        // A collection of related tests.
107class TestPartResult;                  // Result of a test part.
108class TestInfo;                        // Information about a test.
109class UnitTest;                        // A collection of test cases.
110class UnitTestEventListenerInterface;  // Listens to Google Test events.
111class AssertionResult;                 // Result of an assertion.
112
113namespace internal {
114
115struct TraceInfo;                      // Information about a trace point.
116class ScopedTrace;                     // Implements scoped trace.
117class TestInfoImpl;                    // Opaque implementation of TestInfo
118class TestResult;                      // Result of a single Test.
119class UnitTestImpl;                    // Opaque implementation of UnitTest
120
121template <typename E> class List;      // A generic list.
122template <typename E> class ListNode;  // A node in a generic list.
123
124// How many times InitGoogleTest() has been called.
125extern int g_init_gtest_count;
126
127// The text used in failure messages to indicate the start of the
128// stack trace.
129extern const char kStackTraceMarker[];
130
131// A secret type that Google Test users don't know about.  It has no
132// definition on purpose.  Therefore it's impossible to create a
133// Secret object, which is what we want.
134class Secret;
135
136// Two overloaded helpers for checking at compile time whether an
137// expression is a null pointer literal (i.e. NULL or any 0-valued
138// compile-time integral constant).  Their return values have
139// different sizes, so we can use sizeof() to test which version is
140// picked by the compiler.  These helpers have no implementations, as
141// we only need their signatures.
142//
143// Given IsNullLiteralHelper(x), the compiler will pick the first
144// version if x can be implicitly converted to Secret*, and pick the
145// second version otherwise.  Since Secret is a secret and incomplete
146// type, the only expression a user can write that has type Secret* is
147// a null pointer literal.  Therefore, we know that x is a null
148// pointer literal if and only if the first version is picked by the
149// compiler.
150char IsNullLiteralHelper(Secret* p);
151char (&IsNullLiteralHelper(...))[2];  // NOLINT
152
153// A compile-time bool constant that is true if and only if x is a
154// null pointer literal (i.e. NULL or any 0-valued compile-time
155// integral constant).
156#ifdef GTEST_ELLIPSIS_NEEDS_COPY_
157// Passing non-POD classes through ellipsis (...) crashes the ARM
158// compiler.  The Nokia Symbian and the IBM XL C/C++ compiler try to
159// instantiate a copy constructor for objects passed through ellipsis
160// (...), failing for uncopyable objects.  Hence we define this to
161// false (and lose support for NULL detection).
162#define GTEST_IS_NULL_LITERAL_(x) false
163#else
164#define GTEST_IS_NULL_LITERAL_(x) \
165    (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
166#endif  // GTEST_ELLIPSIS_NEEDS_COPY_
167
168// Appends the user-supplied message to the Google-Test-generated message.
169String AppendUserMessage(const String& gtest_msg,
170                         const Message& user_msg);
171
172// A helper class for creating scoped traces in user programs.
173class ScopedTrace {
174 public:
175  // The c'tor pushes the given source file location and message onto
176  // a trace stack maintained by Google Test.
177  ScopedTrace(const char* file, int line, const Message& message);
178
179  // The d'tor pops the info pushed by the c'tor.
180  //
181  // Note that the d'tor is not virtual in order to be efficient.
182  // Don't inherit from ScopedTrace!
183  ~ScopedTrace();
184
185 private:
186  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
187} GTEST_ATTRIBUTE_UNUSED_;  // A ScopedTrace object does its job in its
188                            // c'tor and d'tor.  Therefore it doesn't
189                            // need to be used otherwise.
190
191// Converts a streamable value to a String.  A NULL pointer is
192// converted to "(null)".  When the input value is a ::string,
193// ::std::string, ::wstring, or ::std::wstring object, each NUL
194// character in it is replaced with "\\0".
195// Declared here but defined in gtest.h, so that it has access
196// to the definition of the Message class, required by the ARM
197// compiler.
198template <typename T>
199String StreamableToString(const T& streamable);
200
201// Formats a value to be used in a failure message.
202
203#ifdef GTEST_NEEDS_IS_POINTER_
204
205// These are needed as the Nokia Symbian and IBM XL C/C++ compilers
206// cannot decide between const T& and const T* in a function template.
207// These compilers _can_ decide between class template specializations
208// for T and T*, so a tr1::type_traits-like is_pointer works, and we
209// can overload on that.
210
211// This overload makes sure that all pointers (including
212// those to char or wchar_t) are printed as raw pointers.
213template <typename T>
214inline String FormatValueForFailureMessage(internal::true_type dummy,
215                                           T* pointer) {
216  return StreamableToString(static_cast<const void*>(pointer));
217}
218
219template <typename T>
220inline String FormatValueForFailureMessage(internal::false_type dummy,
221                                           const T& value) {
222  return StreamableToString(value);
223}
224
225template <typename T>
226inline String FormatForFailureMessage(const T& value) {
227  return FormatValueForFailureMessage(
228      typename internal::is_pointer<T>::type(), value);
229}
230
231#else
232
233// These are needed as the above solution using is_pointer has the
234// limitation that T cannot be a type without external linkage, when
235// compiled using MSVC.
236
237template <typename T>
238inline String FormatForFailureMessage(const T& value) {
239  return StreamableToString(value);
240}
241
242// This overload makes sure that all pointers (including
243// those to char or wchar_t) are printed as raw pointers.
244template <typename T>
245inline String FormatForFailureMessage(T* pointer) {
246  return StreamableToString(static_cast<const void*>(pointer));
247}
248
249#endif  // GTEST_NEEDS_IS_POINTER_
250
251// These overloaded versions handle narrow and wide characters.
252String FormatForFailureMessage(char ch);
253String FormatForFailureMessage(wchar_t wchar);
254
255// When this operand is a const char* or char*, and the other operand
256// is a ::std::string or ::string, we print this operand as a C string
257// rather than a pointer.  We do the same for wide strings.
258
259// This internal macro is used to avoid duplicated code.
260#define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\
261inline String FormatForComparisonFailureMessage(\
262    operand2_type::value_type* str, const operand2_type& /*operand2*/) {\
263  return operand1_printer(str);\
264}\
265inline String FormatForComparisonFailureMessage(\
266    const operand2_type::value_type* str, const operand2_type& /*operand2*/) {\
267  return operand1_printer(str);\
268}
269
270#if GTEST_HAS_STD_STRING
271GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted)
272#endif  // GTEST_HAS_STD_STRING
273#if GTEST_HAS_STD_WSTRING
274GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted)
275#endif  // GTEST_HAS_STD_WSTRING
276
277#if GTEST_HAS_GLOBAL_STRING
278GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted)
279#endif  // GTEST_HAS_GLOBAL_STRING
280#if GTEST_HAS_GLOBAL_WSTRING
281GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted)
282#endif  // GTEST_HAS_GLOBAL_WSTRING
283
284#undef GTEST_FORMAT_IMPL_
285
286// Constructs and returns the message for an equality assertion
287// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
288//
289// The first four parameters are the expressions used in the assertion
290// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
291// where foo is 5 and bar is 6, we have:
292//
293//   expected_expression: "foo"
294//   actual_expression:   "bar"
295//   expected_value:      "5"
296//   actual_value:        "6"
297//
298// The ignoring_case parameter is true iff the assertion is a
299// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
300// be inserted into the message.
301AssertionResult EqFailure(const char* expected_expression,
302                          const char* actual_expression,
303                          const String& expected_value,
304                          const String& actual_value,
305                          bool ignoring_case);
306
307
308// This template class represents an IEEE floating-point number
309// (either single-precision or double-precision, depending on the
310// template parameters).
311//
312// The purpose of this class is to do more sophisticated number
313// comparison.  (Due to round-off error, etc, it's very unlikely that
314// two floating-points will be equal exactly.  Hence a naive
315// comparison by the == operation often doesn't work.)
316//
317// Format of IEEE floating-point:
318//
319//   The most-significant bit being the leftmost, an IEEE
320//   floating-point looks like
321//
322//     sign_bit exponent_bits fraction_bits
323//
324//   Here, sign_bit is a single bit that designates the sign of the
325//   number.
326//
327//   For float, there are 8 exponent bits and 23 fraction bits.
328//
329//   For double, there are 11 exponent bits and 52 fraction bits.
330//
331//   More details can be found at
332//   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
333//
334// Template parameter:
335//
336//   RawType: the raw floating-point type (either float or double)
337template <typename RawType>
338class FloatingPoint {
339 public:
340  // Defines the unsigned integer type that has the same size as the
341  // floating point number.
342  typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
343
344  // Constants.
345
346  // # of bits in a number.
347  static const size_t kBitCount = 8*sizeof(RawType);
348
349  // # of fraction bits in a number.
350  static const size_t kFractionBitCount =
351    std::numeric_limits<RawType>::digits - 1;
352
353  // # of exponent bits in a number.
354  static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
355
356  // The mask for the sign bit.
357  static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
358
359  // The mask for the fraction bits.
360  static const Bits kFractionBitMask =
361    ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
362
363  // The mask for the exponent bits.
364  static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
365
366  // How many ULP's (Units in the Last Place) we want to tolerate when
367  // comparing two numbers.  The larger the value, the more error we
368  // allow.  A 0 value means that two numbers must be exactly the same
369  // to be considered equal.
370  //
371  // The maximum error of a single floating-point operation is 0.5
372  // units in the last place.  On Intel CPU's, all floating-point
373  // calculations are done with 80-bit precision, while double has 64
374  // bits.  Therefore, 4 should be enough for ordinary use.
375  //
376  // See the following article for more details on ULP:
377  // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.
378  static const size_t kMaxUlps = 4;
379
380  // Constructs a FloatingPoint from a raw floating-point number.
381  //
382  // On an Intel CPU, passing a non-normalized NAN (Not a Number)
383  // around may change its bits, although the new value is guaranteed
384  // to be also a NAN.  Therefore, don't expect this constructor to
385  // preserve the bits in x when x is a NAN.
386  explicit FloatingPoint(const RawType& x) : value_(x) {}
387
388  // Static methods
389
390  // Reinterprets a bit pattern as a floating-point number.
391  //
392  // This function is needed to test the AlmostEquals() method.
393  static RawType ReinterpretBits(const Bits bits) {
394    FloatingPoint fp(0);
395    fp.bits_ = bits;
396    return fp.value_;
397  }
398
399  // Returns the floating-point number that represent positive infinity.
400  static RawType Infinity() {
401    return ReinterpretBits(kExponentBitMask);
402  }
403
404  // Non-static methods
405
406  // Returns the bits that represents this number.
407  const Bits &bits() const { return bits_; }
408
409  // Returns the exponent bits of this number.
410  Bits exponent_bits() const { return kExponentBitMask & bits_; }
411
412  // Returns the fraction bits of this number.
413  Bits fraction_bits() const { return kFractionBitMask & bits_; }
414
415  // Returns the sign bit of this number.
416  Bits sign_bit() const { return kSignBitMask & bits_; }
417
418  // Returns true iff this is NAN (not a number).
419  bool is_nan() const {
420    // It's a NAN if the exponent bits are all ones and the fraction
421    // bits are not entirely zeros.
422    return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
423  }
424
425  // Returns true iff this number is at most kMaxUlps ULP's away from
426  // rhs.  In particular, this function:
427  //
428  //   - returns false if either number is (or both are) NAN.
429  //   - treats really large numbers as almost equal to infinity.
430  //   - thinks +0.0 and -0.0 are 0 DLP's apart.
431  bool AlmostEquals(const FloatingPoint& rhs) const {
432    // The IEEE standard says that any comparison operation involving
433    // a NAN must return false.
434    if (is_nan() || rhs.is_nan()) return false;
435
436    return DistanceBetweenSignAndMagnitudeNumbers(bits_, rhs.bits_) <= kMaxUlps;
437  }
438
439 private:
440  // Converts an integer from the sign-and-magnitude representation to
441  // the biased representation.  More precisely, let N be 2 to the
442  // power of (kBitCount - 1), an integer x is represented by the
443  // unsigned number x + N.
444  //
445  // For instance,
446  //
447  //   -N + 1 (the most negative number representable using
448  //          sign-and-magnitude) is represented by 1;
449  //   0      is represented by N; and
450  //   N - 1  (the biggest number representable using
451  //          sign-and-magnitude) is represented by 2N - 1.
452  //
453  // Read http://en.wikipedia.org/wiki/Signed_number_representations
454  // for more details on signed number representations.
455  static Bits SignAndMagnitudeToBiased(const Bits &sam) {
456    if (kSignBitMask & sam) {
457      // sam represents a negative number.
458      return ~sam + 1;
459    } else {
460      // sam represents a positive number.
461      return kSignBitMask | sam;
462    }
463  }
464
465  // Given two numbers in the sign-and-magnitude representation,
466  // returns the distance between them as an unsigned number.
467  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
468                                                     const Bits &sam2) {
469    const Bits biased1 = SignAndMagnitudeToBiased(sam1);
470    const Bits biased2 = SignAndMagnitudeToBiased(sam2);
471    return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
472  }
473
474  union {
475    RawType value_;  // The raw floating-point number.
476    Bits bits_;      // The bits that represent the number.
477  };
478};
479
480// Typedefs the instances of the FloatingPoint template class that we
481// care to use.
482typedef FloatingPoint<float> Float;
483typedef FloatingPoint<double> Double;
484
485// In order to catch the mistake of putting tests that use different
486// test fixture classes in the same test case, we need to assign
487// unique IDs to fixture classes and compare them.  The TypeId type is
488// used to hold such IDs.  The user should treat TypeId as an opaque
489// type: the only operation allowed on TypeId values is to compare
490// them for equality using the == operator.
491typedef const void* TypeId;
492
493template <typename T>
494class TypeIdHelper {
495 public:
496  // dummy_ must not have a const type.  Otherwise an overly eager
497  // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
498  // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
499  static bool dummy_;
500};
501
502template <typename T>
503bool TypeIdHelper<T>::dummy_ = false;
504
505// GetTypeId<T>() returns the ID of type T.  Different values will be
506// returned for different types.  Calling the function twice with the
507// same type argument is guaranteed to return the same ID.
508template <typename T>
509TypeId GetTypeId() {
510  // The compiler is required to allocate a different
511  // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
512  // the template.  Therefore, the address of dummy_ is guaranteed to
513  // be unique.
514  return &(TypeIdHelper<T>::dummy_);
515}
516
517// Returns the type ID of ::testing::Test.  Always call this instead
518// of GetTypeId< ::testing::Test>() to get the type ID of
519// ::testing::Test, as the latter may give the wrong result due to a
520// suspected linker bug when compiling Google Test as a Mac OS X
521// framework.
522TypeId GetTestTypeId();
523
524// Defines the abstract factory interface that creates instances
525// of a Test object.
526class TestFactoryBase {
527 public:
528  virtual ~TestFactoryBase() {}
529
530  // Creates a test instance to run. The instance is both created and destroyed
531  // within TestInfoImpl::Run()
532  virtual Test* CreateTest() = 0;
533
534 protected:
535  TestFactoryBase() {}
536
537 private:
538  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
539};
540
541// This class provides implementation of TeastFactoryBase interface.
542// It is used in TEST and TEST_F macros.
543template <class TestClass>
544class TestFactoryImpl : public TestFactoryBase {
545 public:
546  virtual Test* CreateTest() { return new TestClass; }
547};
548
549#if GTEST_OS_WINDOWS
550
551// Predicate-formatters for implementing the HRESULT checking macros
552// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
553// We pass a long instead of HRESULT to avoid causing an
554// include dependency for the HRESULT type.
555AssertionResult IsHRESULTSuccess(const char* expr, long hr);  // NOLINT
556AssertionResult IsHRESULTFailure(const char* expr, long hr);  // NOLINT
557
558#endif  // GTEST_OS_WINDOWS
559
560// Formats a source file path and a line number as they would appear
561// in a compiler error message.
562inline String FormatFileLocation(const char* file, int line) {
563  const char* const file_name = file == NULL ? "unknown file" : file;
564  if (line < 0) {
565    return String::Format("%s:", file_name);
566  }
567#ifdef _MSC_VER
568  return String::Format("%s(%d):", file_name, line);
569#else
570  return String::Format("%s:%d:", file_name, line);
571#endif  // _MSC_VER
572}
573
574// Types of SetUpTestCase() and TearDownTestCase() functions.
575typedef void (*SetUpTestCaseFunc)();
576typedef void (*TearDownTestCaseFunc)();
577
578// Creates a new TestInfo object and registers it with Google Test;
579// returns the created object.
580//
581// Arguments:
582//
583//   test_case_name:   name of the test case
584//   name:             name of the test
585//   test_case_comment: a comment on the test case that will be included in
586//                      the test output
587//   comment:          a comment on the test that will be included in the
588//                     test output
589//   fixture_class_id: ID of the test fixture class
590//   set_up_tc:        pointer to the function that sets up the test case
591//   tear_down_tc:     pointer to the function that tears down the test case
592//   factory:          pointer to the factory that creates a test object.
593//                     The newly created TestInfo instance will assume
594//                     ownership of the factory object.
595TestInfo* MakeAndRegisterTestInfo(
596    const char* test_case_name, const char* name,
597    const char* test_case_comment, const char* comment,
598    TypeId fixture_class_id,
599    SetUpTestCaseFunc set_up_tc,
600    TearDownTestCaseFunc tear_down_tc,
601    TestFactoryBase* factory);
602
603#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
604
605// State of the definition of a type-parameterized test case.
606class TypedTestCasePState {
607 public:
608  TypedTestCasePState() : registered_(false) {}
609
610  // Adds the given test name to defined_test_names_ and return true
611  // if the test case hasn't been registered; otherwise aborts the
612  // program.
613  bool AddTestName(const char* file, int line, const char* case_name,
614                   const char* test_name) {
615    if (registered_) {
616      fprintf(stderr, "%s Test %s must be defined before "
617              "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n",
618              FormatFileLocation(file, line).c_str(), test_name, case_name);
619      fflush(stderr);
620      abort();
621    }
622    defined_test_names_.insert(test_name);
623    return true;
624  }
625
626  // Verifies that registered_tests match the test names in
627  // defined_test_names_; returns registered_tests if successful, or
628  // aborts the program otherwise.
629  const char* VerifyRegisteredTestNames(
630      const char* file, int line, const char* registered_tests);
631
632 private:
633  bool registered_;
634  ::std::set<const char*> defined_test_names_;
635};
636
637// Skips to the first non-space char after the first comma in 'str';
638// returns NULL if no comma is found in 'str'.
639inline const char* SkipComma(const char* str) {
640  const char* comma = strchr(str, ',');
641  if (comma == NULL) {
642    return NULL;
643  }
644  while (isspace(*(++comma))) {}
645  return comma;
646}
647
648// Returns the prefix of 'str' before the first comma in it; returns
649// the entire string if it contains no comma.
650inline String GetPrefixUntilComma(const char* str) {
651  const char* comma = strchr(str, ',');
652  return comma == NULL ? String(str) : String(str, comma - str);
653}
654
655// TypeParameterizedTest<Fixture, TestSel, Types>::Register()
656// registers a list of type-parameterized tests with Google Test.  The
657// return value is insignificant - we just need to return something
658// such that we can call this function in a namespace scope.
659//
660// Implementation note: The GTEST_TEMPLATE_ macro declares a template
661// template parameter.  It's defined in gtest-type-util.h.
662template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>
663class TypeParameterizedTest {
664 public:
665  // 'index' is the index of the test in the type list 'Types'
666  // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase,
667  // Types).  Valid values for 'index' are [0, N - 1] where N is the
668  // length of Types.
669  static bool Register(const char* prefix, const char* case_name,
670                       const char* test_names, int index) {
671    typedef typename Types::Head Type;
672    typedef Fixture<Type> FixtureClass;
673    typedef typename GTEST_BIND_(TestSel, Type) TestClass;
674
675    // First, registers the first type-parameterized test in the type
676    // list.
677    MakeAndRegisterTestInfo(
678        String::Format("%s%s%s/%d", prefix, prefix[0] == '\0' ? "" : "/",
679                       case_name, index).c_str(),
680        GetPrefixUntilComma(test_names).c_str(),
681        String::Format("TypeParam = %s", GetTypeName<Type>().c_str()).c_str(),
682        "",
683        GetTypeId<FixtureClass>(),
684        TestClass::SetUpTestCase,
685        TestClass::TearDownTestCase,
686        new TestFactoryImpl<TestClass>);
687
688    // Next, recurses (at compile time) with the tail of the type list.
689    return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail>
690        ::Register(prefix, case_name, test_names, index + 1);
691  }
692};
693
694// The base case for the compile time recursion.
695template <GTEST_TEMPLATE_ Fixture, class TestSel>
696class TypeParameterizedTest<Fixture, TestSel, Types0> {
697 public:
698  static bool Register(const char* /*prefix*/, const char* /*case_name*/,
699                       const char* /*test_names*/, int /*index*/) {
700    return true;
701  }
702};
703
704// TypeParameterizedTestCase<Fixture, Tests, Types>::Register()
705// registers *all combinations* of 'Tests' and 'Types' with Google
706// Test.  The return value is insignificant - we just need to return
707// something such that we can call this function in a namespace scope.
708template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>
709class TypeParameterizedTestCase {
710 public:
711  static bool Register(const char* prefix, const char* case_name,
712                       const char* test_names) {
713    typedef typename Tests::Head Head;
714
715    // First, register the first test in 'Test' for each type in 'Types'.
716    TypeParameterizedTest<Fixture, Head, Types>::Register(
717        prefix, case_name, test_names, 0);
718
719    // Next, recurses (at compile time) with the tail of the test list.
720    return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types>
721        ::Register(prefix, case_name, SkipComma(test_names));
722  }
723};
724
725// The base case for the compile time recursion.
726template <GTEST_TEMPLATE_ Fixture, typename Types>
727class TypeParameterizedTestCase<Fixture, Templates0, Types> {
728 public:
729  static bool Register(const char* prefix, const char* case_name,
730                       const char* test_names) {
731    return true;
732  }
733};
734
735#endif  // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P
736
737// Returns the current OS stack trace as a String.
738//
739// The maximum number of stack frames to be included is specified by
740// the gtest_stack_trace_depth flag.  The skip_count parameter
741// specifies the number of top frames to be skipped, which doesn't
742// count against the number of frames to be included.
743//
744// For example, if Foo() calls Bar(), which in turn calls
745// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
746// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
747String GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count);
748
749// Returns the number of failed test parts in the given test result object.
750int GetFailedPartCount(const TestResult* result);
751
752// A helper for suppressing warnings on unreachable code in some macros.
753bool AlwaysTrue();
754
755}  // namespace internal
756}  // namespace testing
757
758#define GTEST_MESSAGE_(message, result_type) \
759  ::testing::internal::AssertHelper(result_type, __FILE__, __LINE__, message) \
760    = ::testing::Message()
761
762#define GTEST_FATAL_FAILURE_(message) \
763  return GTEST_MESSAGE_(message, ::testing::TPRT_FATAL_FAILURE)
764
765#define GTEST_NONFATAL_FAILURE_(message) \
766  GTEST_MESSAGE_(message, ::testing::TPRT_NONFATAL_FAILURE)
767
768#define GTEST_SUCCESS_(message) \
769  GTEST_MESSAGE_(message, ::testing::TPRT_SUCCESS)
770
771// Suppresses MSVC warnings 4072 (unreachable code) for the code following
772// statement if it returns or throws (or doesn't return or throw in some
773// situations).
774#define GTEST_HIDE_UNREACHABLE_CODE_(statement) \
775  if (::testing::internal::AlwaysTrue()) { statement; }
776
777#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
778  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
779  if (const char* gtest_msg = "") { \
780    bool gtest_caught_expected = false; \
781    try { \
782      GTEST_HIDE_UNREACHABLE_CODE_(statement); \
783    } \
784    catch (expected_exception const&) { \
785      gtest_caught_expected = true; \
786    } \
787    catch (...) { \
788      gtest_msg = "Expected: " #statement " throws an exception of type " \
789                  #expected_exception ".\n  Actual: it throws a different " \
790                  "type."; \
791      goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
792    } \
793    if (!gtest_caught_expected) { \
794      gtest_msg = "Expected: " #statement " throws an exception of type " \
795                  #expected_exception ".\n  Actual: it throws nothing."; \
796      goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
797    } \
798  } else \
799    GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
800      fail(gtest_msg)
801
802#define GTEST_TEST_NO_THROW_(statement, fail) \
803  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
804  if (const char* gtest_msg = "") { \
805    try { \
806      GTEST_HIDE_UNREACHABLE_CODE_(statement); \
807    } \
808    catch (...) { \
809      gtest_msg = "Expected: " #statement " doesn't throw an exception.\n" \
810                  "  Actual: it throws."; \
811      goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
812    } \
813  } else \
814    GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
815      fail(gtest_msg)
816
817#define GTEST_TEST_ANY_THROW_(statement, fail) \
818  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
819  if (const char* gtest_msg = "") { \
820    bool gtest_caught_any = false; \
821    try { \
822      GTEST_HIDE_UNREACHABLE_CODE_(statement); \
823    } \
824    catch (...) { \
825      gtest_caught_any = true; \
826    } \
827    if (!gtest_caught_any) { \
828      gtest_msg = "Expected: " #statement " throws an exception.\n" \
829                  "  Actual: it doesn't."; \
830      goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
831    } \
832  } else \
833    GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
834      fail(gtest_msg)
835
836
837#define GTEST_TEST_BOOLEAN_(boolexpr, booltext, actual, expected, fail) \
838  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
839  if (boolexpr) \
840    ; \
841  else \
842    fail("Value of: " booltext "\n  Actual: " #actual "\nExpected: " #expected)
843
844#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
845  GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
846  if (const char* gtest_msg = "") { \
847    ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
848    GTEST_HIDE_UNREACHABLE_CODE_(statement); \
849    if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
850      gtest_msg = "Expected: " #statement " doesn't generate new fatal " \
851                  "failures in the current thread.\n" \
852                  "  Actual: it does."; \
853      goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
854    } \
855  } else \
856    GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
857      fail(gtest_msg)
858
859// Expands to the name of the class that implements the given test.
860#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
861  test_case_name##_##test_name##_Test
862
863// Helper macro for defining tests.
864#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
865class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
866 public:\
867  GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
868 private:\
869  virtual void TestBody();\
870  static ::testing::TestInfo* const test_info_;\
871  GTEST_DISALLOW_COPY_AND_ASSIGN_(\
872      GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
873};\
874\
875::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
876  ::test_info_ =\
877    ::testing::internal::MakeAndRegisterTestInfo(\
878        #test_case_name, #test_name, "", "", \
879        (parent_id), \
880        parent_class::SetUpTestCase, \
881        parent_class::TearDownTestCase, \
882        new ::testing::internal::TestFactoryImpl<\
883            GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
884void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
885
886#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
887