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