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