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