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