]> git.proxmox.com Git - rustc.git/blob - src/llvm/utils/unittest/googletest/include/gtest/internal/gtest-internal.h
Imported Upstream version 1.0.0+dfsg1
[rustc.git] / src / llvm / utils / unittest / googletest / include / gtest / internal / gtest-internal.h
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 #if !GTEST_NO_LLVM_RAW_OSTREAM
60 #include "llvm/Support/raw_os_ostream.h"
61 #endif
62
63 // Due to C++ preprocessor weirdness, we need double indirection to
64 // concatenate two tokens when one of them is __LINE__. Writing
65 //
66 // foo ## __LINE__
67 //
68 // will result in the token foo__LINE__, instead of foo followed by
69 // the current line number. For more details, see
70 // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6
71 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)
72 #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar
73
74 // Google Test defines the testing::Message class to allow construction of
75 // test messages via the << operator. The idea is that anything
76 // streamable to std::ostream can be streamed to a testing::Message.
77 // This allows a user to use his own types in Google Test assertions by
78 // overloading the << operator.
79 //
80 // util/gtl/stl_logging-inl.h overloads << for STL containers. These
81 // overloads cannot be defined in the std namespace, as that will be
82 // undefined behavior. Therefore, they are defined in the global
83 // namespace instead.
84 //
85 // C++'s symbol lookup rule (i.e. Koenig lookup) says that these
86 // overloads are visible in either the std namespace or the global
87 // namespace, but not other namespaces, including the testing
88 // namespace which Google Test's Message class is in.
89 //
90 // To allow STL containers (and other types that has a << operator
91 // defined in the global namespace) to be used in Google Test assertions,
92 // testing::Message must access the custom << operator from the global
93 // namespace. Hence this helper function.
94 //
95 // Note: Jeffrey Yasskin suggested an alternative fix by "using
96 // ::operator<<;" in the definition of Message's operator<<. That fix
97 // doesn't require a helper function, but unfortunately doesn't
98 // compile with MSVC.
99
100 // LLVM INTERNAL CHANGE: To allow operator<< to work with both
101 // std::ostreams and LLVM's raw_ostreams, we define a special
102 // std::ostream with an implicit conversion to raw_ostream& and stream
103 // to that. This causes the compiler to prefer std::ostream overloads
104 // but still find raw_ostream& overloads.
105 #if !GTEST_NO_LLVM_RAW_OSTREAM
106 namespace llvm {
107 class convertible_fwd_ostream : public std::ostream {
108 virtual void anchor();
109 raw_os_ostream ros_;
110
111 public:
112 convertible_fwd_ostream(std::ostream& os)
113 : std::ostream(os.rdbuf()), ros_(*this) {}
114 operator raw_ostream&() { return ros_; }
115 };
116 }
117 template <typename T>
118 inline void GTestStreamToHelper(std::ostream* os, const T& val) {
119 llvm::convertible_fwd_ostream cos(*os);
120 cos << val;
121 }
122 #else
123 template <typename T>
124 inline void GTestStreamToHelper(std::ostream* os, const T& val) {
125 *os << val;
126 }
127 #endif
128
129 class ProtocolMessage;
130 namespace proto2 { class Message; }
131
132 namespace testing {
133
134 // Forward declarations.
135
136 class AssertionResult; // Result of an assertion.
137 class Message; // Represents a failure message.
138 class Test; // Represents a test.
139 class TestInfo; // Information about a test.
140 class TestPartResult; // Result of a test part.
141 class UnitTest; // A collection of test cases.
142
143 template <typename T>
144 ::std::string PrintToString(const T& value);
145
146 namespace internal {
147
148 struct TraceInfo; // Information about a trace point.
149 class ScopedTrace; // Implements scoped trace.
150 class TestInfoImpl; // Opaque implementation of TestInfo
151 class UnitTestImpl; // Opaque implementation of UnitTest
152
153 // How many times InitGoogleTest() has been called.
154 extern int g_init_gtest_count;
155
156 // The text used in failure messages to indicate the start of the
157 // stack trace.
158 GTEST_API_ extern const char kStackTraceMarker[];
159
160 // A secret type that Google Test users don't know about. It has no
161 // definition on purpose. Therefore it's impossible to create a
162 // Secret object, which is what we want.
163 class Secret;
164
165 // Two overloaded helpers for checking at compile time whether an
166 // expression is a null pointer literal (i.e. NULL or any 0-valued
167 // compile-time integral constant). Their return values have
168 // different sizes, so we can use sizeof() to test which version is
169 // picked by the compiler. These helpers have no implementations, as
170 // we only need their signatures.
171 //
172 // Given IsNullLiteralHelper(x), the compiler will pick the first
173 // version if x can be implicitly converted to Secret*, and pick the
174 // second version otherwise. Since Secret is a secret and incomplete
175 // type, the only expression a user can write that has type Secret* is
176 // a null pointer literal. Therefore, we know that x is a null
177 // pointer literal if and only if the first version is picked by the
178 // compiler.
179 char IsNullLiteralHelper(Secret* p);
180 char (&IsNullLiteralHelper(...))[2]; // NOLINT
181
182 // A compile-time bool constant that is true if and only if x is a
183 // null pointer literal (i.e. NULL or any 0-valued compile-time
184 // integral constant).
185 #ifdef GTEST_ELLIPSIS_NEEDS_POD_
186 // We lose support for NULL detection where the compiler doesn't like
187 // passing non-POD classes through ellipsis (...).
188 # define GTEST_IS_NULL_LITERAL_(x) false
189 #else
190 # define GTEST_IS_NULL_LITERAL_(x) \
191 (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1)
192 #endif // GTEST_ELLIPSIS_NEEDS_POD_
193
194 // Appends the user-supplied message to the Google-Test-generated message.
195 GTEST_API_ String AppendUserMessage(const String& gtest_msg,
196 const Message& user_msg);
197
198 // A helper class for creating scoped traces in user programs.
199 class GTEST_API_ ScopedTrace {
200 public:
201 // The c'tor pushes the given source file location and message onto
202 // a trace stack maintained by Google Test.
203 ScopedTrace(const char* file, int line, const Message& message);
204
205 // The d'tor pops the info pushed by the c'tor.
206 //
207 // Note that the d'tor is not virtual in order to be efficient.
208 // Don't inherit from ScopedTrace!
209 ~ScopedTrace();
210
211 private:
212 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
213 } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
214 // c'tor and d'tor. Therefore it doesn't
215 // need to be used otherwise.
216
217 // Converts a streamable value to a String. A NULL pointer is
218 // converted to "(null)". When the input value is a ::string,
219 // ::std::string, ::wstring, or ::std::wstring object, each NUL
220 // character in it is replaced with "\\0".
221 // Declared here but defined in gtest.h, so that it has access
222 // to the definition of the Message class, required by the ARM
223 // compiler.
224 template <typename T>
225 String StreamableToString(const T& streamable);
226
227 // The Symbian compiler has a bug that prevents it from selecting the
228 // correct overload of FormatForComparisonFailureMessage (see below)
229 // unless we pass the first argument by reference. If we do that,
230 // however, Visual Age C++ 10.1 generates a compiler error. Therefore
231 // we only apply the work-around for Symbian.
232 #if defined(__SYMBIAN32__)
233 # define GTEST_CREF_WORKAROUND_ const&
234 #else
235 # define GTEST_CREF_WORKAROUND_
236 #endif
237
238 // When this operand is a const char* or char*, if the other operand
239 // is a ::std::string or ::string, we print this operand as a C string
240 // rather than a pointer (we do the same for wide strings); otherwise
241 // we print it as a pointer to be safe.
242
243 // This internal macro is used to avoid duplicated code.
244 #define GTEST_FORMAT_IMPL_(operand2_type, operand1_printer)\
245 inline String FormatForComparisonFailureMessage(\
246 operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \
247 const operand2_type& /*operand2*/) {\
248 return operand1_printer(str);\
249 }\
250 inline String FormatForComparisonFailureMessage(\
251 const operand2_type::value_type* GTEST_CREF_WORKAROUND_ str, \
252 const operand2_type& /*operand2*/) {\
253 return operand1_printer(str);\
254 }
255
256 GTEST_FORMAT_IMPL_(::std::string, String::ShowCStringQuoted)
257 #if GTEST_HAS_STD_WSTRING
258 GTEST_FORMAT_IMPL_(::std::wstring, String::ShowWideCStringQuoted)
259 #endif // GTEST_HAS_STD_WSTRING
260
261 #if GTEST_HAS_GLOBAL_STRING
262 GTEST_FORMAT_IMPL_(::string, String::ShowCStringQuoted)
263 #endif // GTEST_HAS_GLOBAL_STRING
264 #if GTEST_HAS_GLOBAL_WSTRING
265 GTEST_FORMAT_IMPL_(::wstring, String::ShowWideCStringQuoted)
266 #endif // GTEST_HAS_GLOBAL_WSTRING
267
268 #undef GTEST_FORMAT_IMPL_
269
270 // The next four overloads handle the case where the operand being
271 // printed is a char/wchar_t pointer and the other operand is not a
272 // string/wstring object. In such cases, we just print the operand as
273 // a pointer to be safe.
274 #define GTEST_FORMAT_CHAR_PTR_IMPL_(CharType) \
275 template <typename T> \
276 String FormatForComparisonFailureMessage(CharType* GTEST_CREF_WORKAROUND_ p, \
277 const T&) { \
278 return PrintToString(static_cast<const void*>(p)); \
279 }
280
281 GTEST_FORMAT_CHAR_PTR_IMPL_(char)
282 GTEST_FORMAT_CHAR_PTR_IMPL_(const char)
283 GTEST_FORMAT_CHAR_PTR_IMPL_(wchar_t)
284 GTEST_FORMAT_CHAR_PTR_IMPL_(const wchar_t)
285
286 #undef GTEST_FORMAT_CHAR_PTR_IMPL_
287
288 // Constructs and returns the message for an equality assertion
289 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
290 //
291 // The first four parameters are the expressions used in the assertion
292 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
293 // where foo is 5 and bar is 6, we have:
294 //
295 // expected_expression: "foo"
296 // actual_expression: "bar"
297 // expected_value: "5"
298 // actual_value: "6"
299 //
300 // The ignoring_case parameter is true iff the assertion is a
301 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
302 // be inserted into the message.
303 GTEST_API_ AssertionResult EqFailure(const char* expected_expression,
304 const char* actual_expression,
305 const String& expected_value,
306 const String& actual_value,
307 bool ignoring_case);
308
309 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
310 GTEST_API_ String GetBoolAssertionFailureMessage(
311 const AssertionResult& assertion_result,
312 const char* expression_text,
313 const char* actual_predicate_value,
314 const char* expected_predicate_value);
315
316 // This template class represents an IEEE floating-point number
317 // (either single-precision or double-precision, depending on the
318 // template parameters).
319 //
320 // The purpose of this class is to do more sophisticated number
321 // comparison. (Due to round-off error, etc, it's very unlikely that
322 // two floating-points will be equal exactly. Hence a naive
323 // comparison by the == operation often doesn't work.)
324 //
325 // Format of IEEE floating-point:
326 //
327 // The most-significant bit being the leftmost, an IEEE
328 // floating-point looks like
329 //
330 // sign_bit exponent_bits fraction_bits
331 //
332 // Here, sign_bit is a single bit that designates the sign of the
333 // number.
334 //
335 // For float, there are 8 exponent bits and 23 fraction bits.
336 //
337 // For double, there are 11 exponent bits and 52 fraction bits.
338 //
339 // More details can be found at
340 // http://en.wikipedia.org/wiki/IEEE_floating-point_standard.
341 //
342 // Template parameter:
343 //
344 // RawType: the raw floating-point type (either float or double)
345 template <typename RawType>
346 class FloatingPoint {
347 public:
348 // Defines the unsigned integer type that has the same size as the
349 // floating point number.
350 typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;
351
352 // Constants.
353
354 // # of bits in a number.
355 static const size_t kBitCount = 8*sizeof(RawType);
356
357 // # of fraction bits in a number.
358 static const size_t kFractionBitCount =
359 std::numeric_limits<RawType>::digits - 1;
360
361 // # of exponent bits in a number.
362 static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;
363
364 // The mask for the sign bit.
365 static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);
366
367 // The mask for the fraction bits.
368 static const Bits kFractionBitMask =
369 ~static_cast<Bits>(0) >> (kExponentBitCount + 1);
370
371 // The mask for the exponent bits.
372 static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);
373
374 // How many ULP's (Units in the Last Place) we want to tolerate when
375 // comparing two numbers. The larger the value, the more error we
376 // allow. A 0 value means that two numbers must be exactly the same
377 // to be considered equal.
378 //
379 // The maximum error of a single floating-point operation is 0.5
380 // units in the last place. On Intel CPU's, all floating-point
381 // calculations are done with 80-bit precision, while double has 64
382 // bits. Therefore, 4 should be enough for ordinary use.
383 //
384 // See the following article for more details on ULP:
385 // http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm.
386 static const size_t kMaxUlps = 4;
387
388 // Constructs a FloatingPoint from a raw floating-point number.
389 //
390 // On an Intel CPU, passing a non-normalized NAN (Not a Number)
391 // around may change its bits, although the new value is guaranteed
392 // to be also a NAN. Therefore, don't expect this constructor to
393 // preserve the bits in x when x is a NAN.
394 explicit FloatingPoint(const RawType& x) { u_.value_ = x; }
395
396 // Static methods
397
398 // Reinterprets a bit pattern as a floating-point number.
399 //
400 // This function is needed to test the AlmostEquals() method.
401 static RawType ReinterpretBits(const Bits bits) {
402 FloatingPoint fp(0);
403 fp.u_.bits_ = bits;
404 return fp.u_.value_;
405 }
406
407 // Returns the floating-point number that represent positive infinity.
408 static RawType Infinity() {
409 return ReinterpretBits(kExponentBitMask);
410 }
411
412 // Non-static methods
413
414 // Returns the bits that represents this number.
415 const Bits &bits() const { return u_.bits_; }
416
417 // Returns the exponent bits of this number.
418 Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }
419
420 // Returns the fraction bits of this number.
421 Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }
422
423 // Returns the sign bit of this number.
424 Bits sign_bit() const { return kSignBitMask & u_.bits_; }
425
426 // Returns true iff this is NAN (not a number).
427 bool is_nan() const {
428 // It's a NAN if the exponent bits are all ones and the fraction
429 // bits are not entirely zeros.
430 return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);
431 }
432
433 // Returns true iff this number is at most kMaxUlps ULP's away from
434 // rhs. In particular, this function:
435 //
436 // - returns false if either number is (or both are) NAN.
437 // - treats really large numbers as almost equal to infinity.
438 // - thinks +0.0 and -0.0 are 0 DLP's apart.
439 bool AlmostEquals(const FloatingPoint& rhs) const {
440 // The IEEE standard says that any comparison operation involving
441 // a NAN must return false.
442 if (is_nan() || rhs.is_nan()) return false;
443
444 return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_)
445 <= kMaxUlps;
446 }
447
448 private:
449 // The data type used to store the actual floating-point number.
450 union FloatingPointUnion {
451 RawType value_; // The raw floating-point number.
452 Bits bits_; // The bits that represent the number.
453 };
454
455 // Converts an integer from the sign-and-magnitude representation to
456 // the biased representation. More precisely, let N be 2 to the
457 // power of (kBitCount - 1), an integer x is represented by the
458 // unsigned number x + N.
459 //
460 // For instance,
461 //
462 // -N + 1 (the most negative number representable using
463 // sign-and-magnitude) is represented by 1;
464 // 0 is represented by N; and
465 // N - 1 (the biggest number representable using
466 // sign-and-magnitude) is represented by 2N - 1.
467 //
468 // Read http://en.wikipedia.org/wiki/Signed_number_representations
469 // for more details on signed number representations.
470 static Bits SignAndMagnitudeToBiased(const Bits &sam) {
471 if (kSignBitMask & sam) {
472 // sam represents a negative number.
473 return ~sam + 1;
474 } else {
475 // sam represents a positive number.
476 return kSignBitMask | sam;
477 }
478 }
479
480 // Given two numbers in the sign-and-magnitude representation,
481 // returns the distance between them as an unsigned number.
482 static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1,
483 const Bits &sam2) {
484 const Bits biased1 = SignAndMagnitudeToBiased(sam1);
485 const Bits biased2 = SignAndMagnitudeToBiased(sam2);
486 return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
487 }
488
489 FloatingPointUnion u_;
490 };
491
492 // Typedefs the instances of the FloatingPoint template class that we
493 // care to use.
494 typedef FloatingPoint<float> Float;
495 typedef FloatingPoint<double> Double;
496
497 // In order to catch the mistake of putting tests that use different
498 // test fixture classes in the same test case, we need to assign
499 // unique IDs to fixture classes and compare them. The TypeId type is
500 // used to hold such IDs. The user should treat TypeId as an opaque
501 // type: the only operation allowed on TypeId values is to compare
502 // them for equality using the == operator.
503 typedef const void* TypeId;
504
505 template <typename T>
506 class TypeIdHelper {
507 public:
508 // dummy_ must not have a const type. Otherwise an overly eager
509 // compiler (e.g. MSVC 7.1 & 8.0) may try to merge
510 // TypeIdHelper<T>::dummy_ for different Ts as an "optimization".
511 static bool dummy_;
512 };
513
514 template <typename T>
515 bool TypeIdHelper<T>::dummy_ = false;
516
517 // GetTypeId<T>() returns the ID of type T. Different values will be
518 // returned for different types. Calling the function twice with the
519 // same type argument is guaranteed to return the same ID.
520 template <typename T>
521 TypeId GetTypeId() {
522 // The compiler is required to allocate a different
523 // TypeIdHelper<T>::dummy_ variable for each T used to instantiate
524 // the template. Therefore, the address of dummy_ is guaranteed to
525 // be unique.
526 return &(TypeIdHelper<T>::dummy_);
527 }
528
529 // Returns the type ID of ::testing::Test. Always call this instead
530 // of GetTypeId< ::testing::Test>() to get the type ID of
531 // ::testing::Test, as the latter may give the wrong result due to a
532 // suspected linker bug when compiling Google Test as a Mac OS X
533 // framework.
534 GTEST_API_ TypeId GetTestTypeId();
535
536 // Defines the abstract factory interface that creates instances
537 // of a Test object.
538 class TestFactoryBase {
539 public:
540 virtual ~TestFactoryBase();
541
542 // Creates a test instance to run. The instance is both created and destroyed
543 // within TestInfoImpl::Run()
544 virtual Test* CreateTest() = 0;
545
546 protected:
547 TestFactoryBase() {}
548
549 private:
550 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase);
551 };
552
553 // This class provides implementation of TeastFactoryBase interface.
554 // It is used in TEST and TEST_F macros.
555 template <class TestClass>
556 class TestFactoryImpl : public TestFactoryBase {
557 public:
558 virtual Test* CreateTest() { return new TestClass; }
559 };
560
561 #if GTEST_OS_WINDOWS
562
563 // Predicate-formatters for implementing the HRESULT checking macros
564 // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}
565 // We pass a long instead of HRESULT to avoid causing an
566 // include dependency for the HRESULT type.
567 GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,
568 long hr); // NOLINT
569 GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,
570 long hr); // NOLINT
571
572 #endif // GTEST_OS_WINDOWS
573
574 // Types of SetUpTestCase() and TearDownTestCase() functions.
575 typedef void (*SetUpTestCaseFunc)();
576 typedef 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 // type_param the name of the test's type parameter, or NULL if
586 // this is not a typed or a type-parameterized test.
587 // value_param text representation of the test's value parameter,
588 // or NULL if this is not a type-parameterized test.
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.
595 GTEST_API_ TestInfo* MakeAndRegisterTestInfo(
596 const char* test_case_name, const char* name,
597 const char* type_param,
598 const char* value_param,
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 GTEST_API_ 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:
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.
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'.
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.
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.
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 GetTypeName<Type>().c_str(),
688 NULL, // No value parameter.
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:
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:
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:
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.
763 inline bool AlwaysFalse() { return !AlwaysTrue(); }
764
765 // Helper for suppressing false warning from Clang on a const char*
766 // variable declared in a conditional expression always being NULL in
767 // the else branch.
768 struct GTEST_API_ ConstCharPtr {
769 ConstCharPtr(const char* str) : value(str) {}
770 operator bool() const { return true; }
771 const char* value;
772 };
773
774 // A simple Linear Congruential Generator for generating random
775 // numbers with a uniform distribution. Unlike rand() and srand(), it
776 // doesn't use global state (and therefore can't interfere with user
777 // code). Unlike rand_r(), it's portable. An LCG isn't very random,
778 // but it's good enough for our purposes.
779 class GTEST_API_ Random {
780 public:
781 static const UInt32 kMaxRange = 1u << 31;
782
783 explicit Random(UInt32 seed) : state_(seed) {}
784
785 void Reseed(UInt32 seed) { state_ = seed; }
786
787 // Generates a random number from [0, range). Crashes if 'range' is
788 // 0 or greater than kMaxRange.
789 UInt32 Generate(UInt32 range);
790
791 private:
792 UInt32 state_;
793 GTEST_DISALLOW_COPY_AND_ASSIGN_(Random);
794 };
795
796 // Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a
797 // compiler error iff T1 and T2 are different types.
798 template <typename T1, typename T2>
799 struct CompileAssertTypesEqual;
800
801 template <typename T>
802 struct CompileAssertTypesEqual<T, T> {
803 };
804
805 // Removes the reference from a type if it is a reference type,
806 // otherwise leaves it unchanged. This is the same as
807 // tr1::remove_reference, which is not widely available yet.
808 template <typename T>
809 struct RemoveReference { typedef T type; }; // NOLINT
810 template <typename T>
811 struct RemoveReference<T&> { typedef T type; }; // NOLINT
812
813 // A handy wrapper around RemoveReference that works when the argument
814 // T depends on template parameters.
815 #define GTEST_REMOVE_REFERENCE_(T) \
816 typename ::testing::internal::RemoveReference<T>::type
817
818 // Removes const from a type if it is a const type, otherwise leaves
819 // it unchanged. This is the same as tr1::remove_const, which is not
820 // widely available yet.
821 template <typename T>
822 struct RemoveConst { typedef T type; }; // NOLINT
823 template <typename T>
824 struct RemoveConst<const T> { typedef T type; }; // NOLINT
825
826 // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above
827 // definition to fail to remove the const in 'const int[3]' and 'const
828 // char[3][4]'. The following specialization works around the bug.
829 // However, it causes trouble with GCC and thus needs to be
830 // conditionally compiled.
831 #if defined(_MSC_VER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
832 template <typename T, size_t N>
833 struct RemoveConst<const T[N]> {
834 typedef typename RemoveConst<T>::type type[N];
835 };
836 #endif
837
838 // A handy wrapper around RemoveConst that works when the argument
839 // T depends on template parameters.
840 #define GTEST_REMOVE_CONST_(T) \
841 typename ::testing::internal::RemoveConst<T>::type
842
843 // Turns const U&, U&, const U, and U all into U.
844 #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \
845 GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T))
846
847 // Adds reference to a type if it is not a reference type,
848 // otherwise leaves it unchanged. This is the same as
849 // tr1::add_reference, which is not widely available yet.
850 template <typename T>
851 struct AddReference { typedef T& type; }; // NOLINT
852 template <typename T>
853 struct AddReference<T&> { typedef T& type; }; // NOLINT
854
855 // A handy wrapper around AddReference that works when the argument T
856 // depends on template parameters.
857 #define GTEST_ADD_REFERENCE_(T) \
858 typename ::testing::internal::AddReference<T>::type
859
860 // Adds a reference to const on top of T as necessary. For example,
861 // it transforms
862 //
863 // char ==> const char&
864 // const char ==> const char&
865 // char& ==> const char&
866 // const char& ==> const char&
867 //
868 // The argument T must depend on some template parameters.
869 #define GTEST_REFERENCE_TO_CONST_(T) \
870 GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T))
871
872 // ImplicitlyConvertible<From, To>::value is a compile-time bool
873 // constant that's true iff type From can be implicitly converted to
874 // type To.
875 template <typename From, typename To>
876 class ImplicitlyConvertible {
877 private:
878 // We need the following helper functions only for their types.
879 // They have no implementations.
880
881 // MakeFrom() is an expression whose type is From. We cannot simply
882 // use From(), as the type From may not have a public default
883 // constructor.
884 static From MakeFrom();
885
886 // These two functions are overloaded. Given an expression
887 // Helper(x), the compiler will pick the first version if x can be
888 // implicitly converted to type To; otherwise it will pick the
889 // second version.
890 //
891 // The first version returns a value of size 1, and the second
892 // version returns a value of size 2. Therefore, by checking the
893 // size of Helper(x), which can be done at compile time, we can tell
894 // which version of Helper() is used, and hence whether x can be
895 // implicitly converted to type To.
896 static char Helper(To);
897 static char (&Helper(...))[2]; // NOLINT
898
899 // We have to put the 'public' section after the 'private' section,
900 // or MSVC refuses to compile the code.
901 public:
902 // MSVC warns about implicitly converting from double to int for
903 // possible loss of data, so we need to temporarily disable the
904 // warning.
905 #ifdef _MSC_VER
906 # pragma warning(push) // Saves the current warning state.
907 # pragma warning(disable:4244) // Temporarily disables warning 4244.
908
909 static const bool value =
910 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
911 # pragma warning(pop) // Restores the warning state.
912 #elif defined(__BORLANDC__)
913 // C++Builder cannot use member overload resolution during template
914 // instantiation. The simplest workaround is to use its C++0x type traits
915 // functions (C++Builder 2009 and above only).
916 static const bool value = __is_convertible(From, To);
917 #else
918 static const bool value =
919 sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;
920 #endif // _MSV_VER
921 };
922 template <typename From, typename To>
923 const bool ImplicitlyConvertible<From, To>::value;
924
925 // IsAProtocolMessage<T>::value is a compile-time bool constant that's
926 // true iff T is type ProtocolMessage, proto2::Message, or a subclass
927 // of those.
928 template <typename T>
929 struct IsAProtocolMessage
930 : public bool_constant<
931 ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value ||
932 ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> {
933 };
934
935 // When the compiler sees expression IsContainerTest<C>(0), if C is an
936 // STL-style container class, the first overload of IsContainerTest
937 // will be viable (since both C::iterator* and C::const_iterator* are
938 // valid types and NULL can be implicitly converted to them). It will
939 // be picked over the second overload as 'int' is a perfect match for
940 // the type of argument 0. If C::iterator or C::const_iterator is not
941 // a valid type, the first overload is not viable, and the second
942 // overload will be picked. Therefore, we can determine whether C is
943 // a container class by checking the type of IsContainerTest<C>(0).
944 // The value of the expression is insignificant.
945 //
946 // Note that we look for both C::iterator and C::const_iterator. The
947 // reason is that C++ injects the name of a class as a member of the
948 // class itself (e.g. you can refer to class iterator as either
949 // 'iterator' or 'iterator::iterator'). If we look for C::iterator
950 // only, for example, we would mistakenly think that a class named
951 // iterator is an STL container.
952 //
953 // Also note that the simpler approach of overloading
954 // IsContainerTest(typename C::const_iterator*) and
955 // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.
956 typedef int IsContainer;
957 template <class C>
958 IsContainer IsContainerTest(int /* dummy */,
959 typename C::iterator* /* it */ = NULL,
960 typename C::const_iterator* /* const_it */ = NULL) {
961 return 0;
962 }
963
964 typedef char IsNotContainer;
965 template <class C>
966 IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; }
967
968 // EnableIf<condition>::type is void when 'Cond' is true, and
969 // undefined when 'Cond' is false. To use SFINAE to make a function
970 // overload only apply when a particular expression is true, add
971 // "typename EnableIf<expression>::type* = 0" as the last parameter.
972 template<bool> struct EnableIf;
973 template<> struct EnableIf<true> { typedef void type; }; // NOLINT
974
975 // Utilities for native arrays.
976
977 // ArrayEq() compares two k-dimensional native arrays using the
978 // elements' operator==, where k can be any integer >= 0. When k is
979 // 0, ArrayEq() degenerates into comparing a single pair of values.
980
981 template <typename T, typename U>
982 bool ArrayEq(const T* lhs, size_t size, const U* rhs);
983
984 // This generic version is used when k is 0.
985 template <typename T, typename U>
986 inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; }
987
988 // This overload is used when k >= 1.
989 template <typename T, typename U, size_t N>
990 inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) {
991 return internal::ArrayEq(lhs, N, rhs);
992 }
993
994 // This helper reduces code bloat. If we instead put its logic inside
995 // the previous ArrayEq() function, arrays with different sizes would
996 // lead to different copies of the template code.
997 template <typename T, typename U>
998 bool ArrayEq(const T* lhs, size_t size, const U* rhs) {
999 for (size_t i = 0; i != size; i++) {
1000 if (!internal::ArrayEq(lhs[i], rhs[i]))
1001 return false;
1002 }
1003 return true;
1004 }
1005
1006 // Finds the first element in the iterator range [begin, end) that
1007 // equals elem. Element may be a native array type itself.
1008 template <typename Iter, typename Element>
1009 Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {
1010 for (Iter it = begin; it != end; ++it) {
1011 if (internal::ArrayEq(*it, elem))
1012 return it;
1013 }
1014 return end;
1015 }
1016
1017 // CopyArray() copies a k-dimensional native array using the elements'
1018 // operator=, where k can be any integer >= 0. When k is 0,
1019 // CopyArray() degenerates into copying a single value.
1020
1021 template <typename T, typename U>
1022 void CopyArray(const T* from, size_t size, U* to);
1023
1024 // This generic version is used when k is 0.
1025 template <typename T, typename U>
1026 inline void CopyArray(const T& from, U* to) { *to = from; }
1027
1028 // This overload is used when k >= 1.
1029 template <typename T, typename U, size_t N>
1030 inline void CopyArray(const T(&from)[N], U(*to)[N]) {
1031 internal::CopyArray(from, N, *to);
1032 }
1033
1034 // This helper reduces code bloat. If we instead put its logic inside
1035 // the previous CopyArray() function, arrays with different sizes
1036 // would lead to different copies of the template code.
1037 template <typename T, typename U>
1038 void CopyArray(const T* from, size_t size, U* to) {
1039 for (size_t i = 0; i != size; i++) {
1040 internal::CopyArray(from[i], to + i);
1041 }
1042 }
1043
1044 // The relation between an NativeArray object (see below) and the
1045 // native array it represents.
1046 enum RelationToSource {
1047 kReference, // The NativeArray references the native array.
1048 kCopy // The NativeArray makes a copy of the native array and
1049 // owns the copy.
1050 };
1051
1052 // Adapts a native array to a read-only STL-style container. Instead
1053 // of the complete STL container concept, this adaptor only implements
1054 // members useful for Google Mock's container matchers. New members
1055 // should be added as needed. To simplify the implementation, we only
1056 // support Element being a raw type (i.e. having no top-level const or
1057 // reference modifier). It's the client's responsibility to satisfy
1058 // this requirement. Element can be an array type itself (hence
1059 // multi-dimensional arrays are supported).
1060 template <typename Element>
1061 class NativeArray {
1062 public:
1063 // STL-style container typedefs.
1064 typedef Element value_type;
1065 typedef Element* iterator;
1066 typedef const Element* const_iterator;
1067
1068 // Constructs from a native array.
1069 NativeArray(const Element* array, size_t count, RelationToSource relation) {
1070 Init(array, count, relation);
1071 }
1072
1073 // Copy constructor.
1074 NativeArray(const NativeArray& rhs) {
1075 Init(rhs.array_, rhs.size_, rhs.relation_to_source_);
1076 }
1077
1078 ~NativeArray() {
1079 // Ensures that the user doesn't instantiate NativeArray with a
1080 // const or reference type.
1081 static_cast<void>(StaticAssertTypeEqHelper<Element,
1082 GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>());
1083 if (relation_to_source_ == kCopy)
1084 delete[] array_;
1085 }
1086
1087 // STL-style container methods.
1088 size_t size() const { return size_; }
1089 const_iterator begin() const { return array_; }
1090 const_iterator end() const { return array_ + size_; }
1091 bool operator==(const NativeArray& rhs) const {
1092 return size() == rhs.size() &&
1093 ArrayEq(begin(), size(), rhs.begin());
1094 }
1095
1096 private:
1097 // Initializes this object; makes a copy of the input array if
1098 // 'relation' is kCopy.
1099 void Init(const Element* array, size_t a_size, RelationToSource relation) {
1100 if (relation == kReference) {
1101 array_ = array;
1102 } else {
1103 Element* const copy = new Element[a_size];
1104 CopyArray(array, a_size, copy);
1105 array_ = copy;
1106 }
1107 size_ = a_size;
1108 relation_to_source_ = relation;
1109 }
1110
1111 const Element* array_;
1112 size_t size_;
1113 RelationToSource relation_to_source_;
1114
1115 GTEST_DISALLOW_ASSIGN_(NativeArray);
1116 };
1117
1118 } // namespace internal
1119 } // namespace testing
1120
1121 #define GTEST_MESSAGE_AT_(file, line, message, result_type) \
1122 ::testing::internal::AssertHelper(result_type, file, line, message) \
1123 = ::testing::Message()
1124
1125 #define GTEST_MESSAGE_(message, result_type) \
1126 GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)
1127
1128 #define GTEST_FATAL_FAILURE_(message) \
1129 return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)
1130
1131 #define GTEST_NONFATAL_FAILURE_(message) \
1132 GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)
1133
1134 #define GTEST_SUCCESS_(message) \
1135 GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)
1136
1137 // Suppresses MSVC warnings 4072 (unreachable code) for the code following
1138 // statement if it returns or throws (or doesn't return or throw in some
1139 // situations).
1140 #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
1141 if (::testing::internal::AlwaysTrue()) { statement; }
1142
1143 #define GTEST_TEST_THROW_(statement, expected_exception, fail) \
1144 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1145 if (::testing::internal::ConstCharPtr gtest_msg = "") { \
1146 bool gtest_caught_expected = false; \
1147 try { \
1148 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1149 } \
1150 catch (expected_exception const&) { \
1151 gtest_caught_expected = true; \
1152 } \
1153 catch (...) { \
1154 gtest_msg.value = \
1155 "Expected: " #statement " throws an exception of type " \
1156 #expected_exception ".\n Actual: it throws a different type."; \
1157 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1158 } \
1159 if (!gtest_caught_expected) { \
1160 gtest_msg.value = \
1161 "Expected: " #statement " throws an exception of type " \
1162 #expected_exception ".\n Actual: it throws nothing."; \
1163 goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \
1164 } \
1165 } else \
1166 GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \
1167 fail(gtest_msg.value)
1168
1169 #define GTEST_TEST_NO_THROW_(statement, fail) \
1170 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1171 if (::testing::internal::AlwaysTrue()) { \
1172 try { \
1173 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1174 } \
1175 catch (...) { \
1176 goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \
1177 } \
1178 } else \
1179 GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \
1180 fail("Expected: " #statement " doesn't throw an exception.\n" \
1181 " Actual: it throws.")
1182
1183 #define GTEST_TEST_ANY_THROW_(statement, fail) \
1184 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1185 if (::testing::internal::AlwaysTrue()) { \
1186 bool gtest_caught_any = false; \
1187 try { \
1188 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1189 } \
1190 catch (...) { \
1191 gtest_caught_any = true; \
1192 } \
1193 if (!gtest_caught_any) { \
1194 goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \
1195 } \
1196 } else \
1197 GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \
1198 fail("Expected: " #statement " throws an exception.\n" \
1199 " Actual: it doesn't.")
1200
1201
1202 // Implements Boolean test assertions such as EXPECT_TRUE. expression can be
1203 // either a boolean expression or an AssertionResult. text is a textual
1204 // represenation of expression as it was passed into the EXPECT_TRUE.
1205 #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \
1206 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1207 if (const ::testing::AssertionResult gtest_ar_ = \
1208 ::testing::AssertionResult(expression)) \
1209 ; \
1210 else \
1211 fail(::testing::internal::GetBoolAssertionFailureMessage(\
1212 gtest_ar_, text, #actual, #expected).c_str())
1213
1214 #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \
1215 GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
1216 if (::testing::internal::AlwaysTrue()) { \
1217 ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \
1218 GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
1219 if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \
1220 goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \
1221 } \
1222 } else \
1223 GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \
1224 fail("Expected: " #statement " doesn't generate new fatal " \
1225 "failures in the current thread.\n" \
1226 " Actual: it does.")
1227
1228 // Expands to the name of the class that implements the given test.
1229 #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
1230 test_case_name##_##test_name##_Test
1231
1232 // Helper macro for defining tests.
1233 #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\
1234 class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\
1235 public:\
1236 GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\
1237 private:\
1238 virtual void TestBody();\
1239 static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
1240 GTEST_DISALLOW_COPY_AND_ASSIGN_(\
1241 GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
1242 };\
1243 \
1244 ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\
1245 ::test_info_ =\
1246 ::testing::internal::MakeAndRegisterTestInfo(\
1247 #test_case_name, #test_name, NULL, NULL, \
1248 (parent_id), \
1249 parent_class::SetUpTestCase, \
1250 parent_class::TearDownTestCase, \
1251 new ::testing::internal::TestFactoryImpl<\
1252 GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
1253 void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
1254
1255 #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_