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// Author: wan@google.com (Zhanyong Wan) 31// 32// The Google C++ Testing Framework (Google Test) 33// 34// This header file defines the public API for Google Test. It should be 35// included by any test program that uses Google Test. 36// 37// IMPORTANT NOTE: Due to limitation of the C++ language, we have to 38// leave some internal implementation details in this header file. 39// They are clearly marked by comments like this: 40// 41// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 42// 43// Such code is NOT meant to be used by a user directly, and is subject 44// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user 45// program! 46// 47// Acknowledgment: Google Test borrowed the idea of automatic test 48// registration from Barthelemy Dagenais' (barthelemy@prologique.com) 49// easyUnit framework. 50 51#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ 52#define GTEST_INCLUDE_GTEST_GTEST_H_ 53 54#include <limits> 55#include <gtest/internal/gtest-internal.h> 56#include <gtest/internal/gtest-string.h> 57#include <gtest/gtest-death-test.h> 58#include <gtest/gtest-message.h> 59#include <gtest/gtest-param-test.h> 60#include <gtest/gtest_prod.h> 61#include <gtest/gtest-test-part.h> 62#include <gtest/gtest-typed-test.h> 63 64// Depending on the platform, different string classes are available. 65// On Windows, ::std::string compiles only when exceptions are 66// enabled. On Linux, in addition to ::std::string, Google also makes 67// use of class ::string, which has the same interface as 68// ::std::string, but has a different implementation. 69// 70// The user can tell us whether ::std::string is available in his 71// environment by defining the macro GTEST_HAS_STD_STRING to either 1 72// or 0 on the compiler command line. He can also define 73// GTEST_HAS_GLOBAL_STRING to 1 to indicate that ::string is available 74// AND is a distinct type to ::std::string, or define it to 0 to 75// indicate otherwise. 76// 77// If the user's ::std::string and ::string are the same class due to 78// aliasing, he should define GTEST_HAS_STD_STRING to 1 and 79// GTEST_HAS_GLOBAL_STRING to 0. 80// 81// If the user doesn't define GTEST_HAS_STD_STRING and/or 82// GTEST_HAS_GLOBAL_STRING, they are defined heuristically. 83 84namespace testing { 85 86// Declares the flags. 87 88// This flag temporary enables the disabled tests. 89GTEST_DECLARE_bool_(also_run_disabled_tests); 90 91// This flag brings the debugger on an assertion failure. 92GTEST_DECLARE_bool_(break_on_failure); 93 94// This flag controls whether Google Test catches all test-thrown exceptions 95// and logs them as failures. 96GTEST_DECLARE_bool_(catch_exceptions); 97 98// This flag enables using colors in terminal output. Available values are 99// "yes" to enable colors, "no" (disable colors), or "auto" (the default) 100// to let Google Test decide. 101GTEST_DECLARE_string_(color); 102 103// This flag sets up the filter to select by name using a glob pattern 104// the tests to run. If the filter is not given all tests are executed. 105GTEST_DECLARE_string_(filter); 106 107// This flag causes the Google Test to list tests. None of the tests listed 108// are actually run if the flag is provided. 109GTEST_DECLARE_bool_(list_tests); 110 111// This flag controls whether Google Test emits a detailed XML report to a file 112// in addition to its normal textual output. 113GTEST_DECLARE_string_(output); 114 115// This flags control whether Google Test prints the elapsed time for each 116// test. 117GTEST_DECLARE_bool_(print_time); 118 119// This flag specifies the random number seed. 120GTEST_DECLARE_int32_(random_seed); 121 122// This flag sets how many times the tests are repeated. The default value 123// is 1. If the value is -1 the tests are repeating forever. 124GTEST_DECLARE_int32_(repeat); 125 126// This flag controls whether Google Test includes Google Test internal 127// stack frames in failure stack traces. 128GTEST_DECLARE_bool_(show_internal_stack_frames); 129 130// When this flag is specified, tests' order is randomized on every iteration. 131GTEST_DECLARE_bool_(shuffle); 132 133// This flag specifies the maximum number of stack frames to be 134// printed in a failure message. 135GTEST_DECLARE_int32_(stack_trace_depth); 136 137// When this flag is specified, a failed assertion will throw an 138// exception if exceptions are enabled, or exit the program with a 139// non-zero code otherwise. 140GTEST_DECLARE_bool_(throw_on_failure); 141 142// The upper limit for valid stack trace depths. 143const int kMaxStackTraceDepth = 100; 144 145namespace internal { 146 147class AssertHelper; 148class DefaultGlobalTestPartResultReporter; 149class ExecDeathTest; 150class NoExecDeathTest; 151class FinalSuccessChecker; 152class GTestFlagSaver; 153class TestInfoImpl; 154class TestResultAccessor; 155class TestEventListenersAccessor; 156class TestEventRepeater; 157class WindowsDeathTest; 158class UnitTestImpl* GetUnitTestImpl(); 159void ReportFailureInUnknownLocation(TestPartResult::Type result_type, 160 const String& message); 161class PrettyUnitTestResultPrinter; 162class XmlUnitTestResultPrinter; 163 164// Converts a streamable value to a String. A NULL pointer is 165// converted to "(null)". When the input value is a ::string, 166// ::std::string, ::wstring, or ::std::wstring object, each NUL 167// character in it is replaced with "\\0". 168// Declared in gtest-internal.h but defined here, so that it has access 169// to the definition of the Message class, required by the ARM 170// compiler. 171template <typename T> 172String StreamableToString(const T& streamable) { 173 return (Message() << streamable).GetString(); 174} 175 176} // namespace internal 177 178// A class for indicating whether an assertion was successful. When 179// the assertion wasn't successful, the AssertionResult object 180// remembers a non-empty message that describes how it failed. 181// 182// To create an instance of this class, use one of the factory functions 183// (AssertionSuccess() and AssertionFailure()). 184// 185// This class is useful for two purposes: 186// 1. Defining predicate functions to be used with Boolean test assertions 187// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts 188// 2. Defining predicate-format functions to be 189// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). 190// 191// For example, if you define IsEven predicate: 192// 193// testing::AssertionResult IsEven(int n) { 194// if ((n % 2) == 0) 195// return testing::AssertionSuccess(); 196// else 197// return testing::AssertionFailure() << n << " is odd"; 198// } 199// 200// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) 201// will print the message 202// 203// Value of: IsEven(Fib(5)) 204// Actual: false (5 is odd) 205// Expected: true 206// 207// instead of a more opaque 208// 209// Value of: IsEven(Fib(5)) 210// Actual: false 211// Expected: true 212// 213// in case IsEven is a simple Boolean predicate. 214// 215// If you expect your predicate to be reused and want to support informative 216// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up 217// about half as often as positive ones in our tests), supply messages for 218// both success and failure cases: 219// 220// testing::AssertionResult IsEven(int n) { 221// if ((n % 2) == 0) 222// return testing::AssertionSuccess() << n << " is even"; 223// else 224// return testing::AssertionFailure() << n << " is odd"; 225// } 226// 227// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print 228// 229// Value of: IsEven(Fib(6)) 230// Actual: true (8 is even) 231// Expected: false 232// 233// NB: Predicates that support negative Boolean assertions have reduced 234// performance in positive ones so be careful not to use them in tests 235// that have lots (tens of thousands) of positive Boolean assertions. 236// 237// To use this class with EXPECT_PRED_FORMAT assertions such as: 238// 239// // Verifies that Foo() returns an even number. 240// EXPECT_PRED_FORMAT1(IsEven, Foo()); 241// 242// you need to define: 243// 244// testing::AssertionResult IsEven(const char* expr, int n) { 245// if ((n % 2) == 0) 246// return testing::AssertionSuccess(); 247// else 248// return testing::AssertionFailure() 249// << "Expected: " << expr << " is even\n Actual: it's " << n; 250// } 251// 252// If Foo() returns 5, you will see the following message: 253// 254// Expected: Foo() is even 255// Actual: it's 5 256// 257class AssertionResult { 258 public: 259 // Copy constructor. 260 // Used in EXPECT_TRUE/FALSE(assertion_result). 261 AssertionResult(const AssertionResult& other); 262 // Used in the EXPECT_TRUE/FALSE(bool_expression). 263 explicit AssertionResult(bool success) : success_(success) {} 264 265 // Returns true iff the assertion succeeded. 266 operator bool() const { return success_; } // NOLINT 267 268 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. 269 AssertionResult operator!() const; 270 271 // Returns the text streamed into this AssertionResult. Test assertions 272 // use it when they fail (i.e., the predicate's outcome doesn't match the 273 // assertion's expectation). When nothing has been streamed into the 274 // object, returns an empty string. 275 const char* message() const { 276 return message_.get() != NULL && message_->c_str() != NULL ? 277 message_->c_str() : ""; 278 } 279 // TODO(vladl@google.com): Remove this after making sure no clients use it. 280 // Deprecated; please use message() instead. 281 const char* failure_message() const { return message(); } 282 283 // Streams a custom failure message into this object. 284 template <typename T> AssertionResult& operator<<(const T& value); 285 286 private: 287 // No implementation - we want AssertionResult to be 288 // copy-constructible but not assignable. 289 void operator=(const AssertionResult& other); 290 291 // Stores result of the assertion predicate. 292 bool success_; 293 // Stores the message describing the condition in case the expectation 294 // construct is not satisfied with the predicate's outcome. 295 // Referenced via a pointer to avoid taking too much stack frame space 296 // with test assertions. 297 internal::scoped_ptr<internal::String> message_; 298}; // class AssertionResult 299 300// Streams a custom failure message into this object. 301template <typename T> 302AssertionResult& AssertionResult::operator<<(const T& value) { 303 Message msg; 304 if (message_.get() != NULL) 305 msg << *message_; 306 msg << value; 307 message_.reset(new internal::String(msg.GetString())); 308 return *this; 309} 310 311// Makes a successful assertion result. 312AssertionResult AssertionSuccess(); 313 314// Makes a failed assertion result. 315AssertionResult AssertionFailure(); 316 317// Makes a failed assertion result with the given failure message. 318// Deprecated; use AssertionFailure() << msg. 319AssertionResult AssertionFailure(const Message& msg); 320 321// The abstract class that all tests inherit from. 322// 323// In Google Test, a unit test program contains one or many TestCases, and 324// each TestCase contains one or many Tests. 325// 326// When you define a test using the TEST macro, you don't need to 327// explicitly derive from Test - the TEST macro automatically does 328// this for you. 329// 330// The only time you derive from Test is when defining a test fixture 331// to be used a TEST_F. For example: 332// 333// class FooTest : public testing::Test { 334// protected: 335// virtual void SetUp() { ... } 336// virtual void TearDown() { ... } 337// ... 338// }; 339// 340// TEST_F(FooTest, Bar) { ... } 341// TEST_F(FooTest, Baz) { ... } 342// 343// Test is not copyable. 344class Test { 345 public: 346 friend class internal::TestInfoImpl; 347 348 // Defines types for pointers to functions that set up and tear down 349 // a test case. 350 typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; 351 typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; 352 353 // The d'tor is virtual as we intend to inherit from Test. 354 virtual ~Test(); 355 356 // Sets up the stuff shared by all tests in this test case. 357 // 358 // Google Test will call Foo::SetUpTestCase() before running the first 359 // test in test case Foo. Hence a sub-class can define its own 360 // SetUpTestCase() method to shadow the one defined in the super 361 // class. 362 static void SetUpTestCase() {} 363 364 // Tears down the stuff shared by all tests in this test case. 365 // 366 // Google Test will call Foo::TearDownTestCase() after running the last 367 // test in test case Foo. Hence a sub-class can define its own 368 // TearDownTestCase() method to shadow the one defined in the super 369 // class. 370 static void TearDownTestCase() {} 371 372 // Returns true iff the current test has a fatal failure. 373 static bool HasFatalFailure(); 374 375 // Returns true iff the current test has a non-fatal failure. 376 static bool HasNonfatalFailure(); 377 378 // Returns true iff the current test has a (either fatal or 379 // non-fatal) failure. 380 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } 381 382 // Logs a property for the current test. Only the last value for a given 383 // key is remembered. 384 // These are public static so they can be called from utility functions 385 // that are not members of the test fixture. 386 // The arguments are const char* instead strings, as Google Test is used 387 // on platforms where string doesn't compile. 388 // 389 // Note that a driving consideration for these RecordProperty methods 390 // was to produce xml output suited to the Greenspan charting utility, 391 // which at present will only chart values that fit in a 32-bit int. It 392 // is the user's responsibility to restrict their values to 32-bit ints 393 // if they intend them to be used with Greenspan. 394 static void RecordProperty(const char* key, const char* value); 395 static void RecordProperty(const char* key, int value); 396 397 protected: 398 // Creates a Test object. 399 Test(); 400 401 // Sets up the test fixture. 402 virtual void SetUp(); 403 404 // Tears down the test fixture. 405 virtual void TearDown(); 406 407 private: 408 // Returns true iff the current test has the same fixture class as 409 // the first test in the current test case. 410 static bool HasSameFixtureClass(); 411 412 // Runs the test after the test fixture has been set up. 413 // 414 // A sub-class must implement this to define the test logic. 415 // 416 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. 417 // Instead, use the TEST or TEST_F macro. 418 virtual void TestBody() = 0; 419 420 // Sets up, executes, and tears down the test. 421 void Run(); 422 423 // Uses a GTestFlagSaver to save and restore all Google Test flags. 424 const internal::GTestFlagSaver* const gtest_flag_saver_; 425 426 // Often a user mis-spells SetUp() as Setup() and spends a long time 427 // wondering why it is never called by Google Test. The declaration of 428 // the following method is solely for catching such an error at 429 // compile time: 430 // 431 // - The return type is deliberately chosen to be not void, so it 432 // will be a conflict if a user declares void Setup() in his test 433 // fixture. 434 // 435 // - This method is private, so it will be another compiler error 436 // if a user calls it from his test fixture. 437 // 438 // DO NOT OVERRIDE THIS FUNCTION. 439 // 440 // If you see an error about overriding the following function or 441 // about it being private, you have mis-spelled SetUp() as Setup(). 442 struct Setup_should_be_spelled_SetUp {}; 443 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } 444 445 // We disallow copying Tests. 446 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); 447}; 448 449typedef internal::TimeInMillis TimeInMillis; 450 451// A copyable object representing a user specified test property which can be 452// output as a key/value string pair. 453// 454// Don't inherit from TestProperty as its destructor is not virtual. 455class TestProperty { 456 public: 457 // C'tor. TestProperty does NOT have a default constructor. 458 // Always use this constructor (with parameters) to create a 459 // TestProperty object. 460 TestProperty(const char* key, const char* value) : 461 key_(key), value_(value) { 462 } 463 464 // Gets the user supplied key. 465 const char* key() const { 466 return key_.c_str(); 467 } 468 469 // Gets the user supplied value. 470 const char* value() const { 471 return value_.c_str(); 472 } 473 474 // Sets a new value, overriding the one supplied in the constructor. 475 void SetValue(const char* new_value) { 476 value_ = new_value; 477 } 478 479 private: 480 // The key supplied by the user. 481 internal::String key_; 482 // The value supplied by the user. 483 internal::String value_; 484}; 485 486// The result of a single Test. This includes a list of 487// TestPartResults, a list of TestProperties, a count of how many 488// death tests there are in the Test, and how much time it took to run 489// the Test. 490// 491// TestResult is not copyable. 492class TestResult { 493 public: 494 // Creates an empty TestResult. 495 TestResult(); 496 497 // D'tor. Do not inherit from TestResult. 498 ~TestResult(); 499 500 // Gets the number of all test parts. This is the sum of the number 501 // of successful test parts and the number of failed test parts. 502 int total_part_count() const; 503 504 // Returns the number of the test properties. 505 int test_property_count() const; 506 507 // Returns true iff the test passed (i.e. no test part failed). 508 bool Passed() const { return !Failed(); } 509 510 // Returns true iff the test failed. 511 bool Failed() const; 512 513 // Returns true iff the test fatally failed. 514 bool HasFatalFailure() const; 515 516 // Returns true iff the test has a non-fatal failure. 517 bool HasNonfatalFailure() const; 518 519 // Returns the elapsed time, in milliseconds. 520 TimeInMillis elapsed_time() const { return elapsed_time_; } 521 522 // Returns the i-th test part result among all the results. i can range 523 // from 0 to test_property_count() - 1. If i is not in that range, aborts 524 // the program. 525 const TestPartResult& GetTestPartResult(int i) const; 526 527 // Returns the i-th test property. i can range from 0 to 528 // test_property_count() - 1. If i is not in that range, aborts the 529 // program. 530 const TestProperty& GetTestProperty(int i) const; 531 532 private: 533 friend class TestInfo; 534 friend class UnitTest; 535 friend class internal::DefaultGlobalTestPartResultReporter; 536 friend class internal::ExecDeathTest; 537 friend class internal::TestInfoImpl; 538 friend class internal::TestResultAccessor; 539 friend class internal::UnitTestImpl; 540 friend class internal::WindowsDeathTest; 541 542 // Gets the vector of TestPartResults. 543 const internal::Vector<TestPartResult>& test_part_results() const { 544 return *test_part_results_; 545 } 546 547 // Gets the vector of TestProperties. 548 const internal::Vector<TestProperty>& test_properties() const { 549 return *test_properties_; 550 } 551 552 // Sets the elapsed time. 553 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } 554 555 // Adds a test property to the list. The property is validated and may add 556 // a non-fatal failure if invalid (e.g., if it conflicts with reserved 557 // key names). If a property is already recorded for the same key, the 558 // value will be updated, rather than storing multiple values for the same 559 // key. 560 void RecordProperty(const TestProperty& test_property); 561 562 // Adds a failure if the key is a reserved attribute of Google Test 563 // testcase tags. Returns true if the property is valid. 564 // TODO(russr): Validate attribute names are legal and human readable. 565 static bool ValidateTestProperty(const TestProperty& test_property); 566 567 // Adds a test part result to the list. 568 void AddTestPartResult(const TestPartResult& test_part_result); 569 570 // Returns the death test count. 571 int death_test_count() const { return death_test_count_; } 572 573 // Increments the death test count, returning the new count. 574 int increment_death_test_count() { return ++death_test_count_; } 575 576 // Clears the test part results. 577 void ClearTestPartResults(); 578 579 // Clears the object. 580 void Clear(); 581 582 // Protects mutable state of the property vector and of owned 583 // properties, whose values may be updated. 584 internal::Mutex test_properites_mutex_; 585 586 // The vector of TestPartResults 587 internal::scoped_ptr<internal::Vector<TestPartResult> > test_part_results_; 588 // The vector of TestProperties 589 internal::scoped_ptr<internal::Vector<TestProperty> > test_properties_; 590 // Running count of death tests. 591 int death_test_count_; 592 // The elapsed time, in milliseconds. 593 TimeInMillis elapsed_time_; 594 595 // We disallow copying TestResult. 596 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); 597}; // class TestResult 598 599// A TestInfo object stores the following information about a test: 600// 601// Test case name 602// Test name 603// Whether the test should be run 604// A function pointer that creates the test object when invoked 605// Test result 606// 607// The constructor of TestInfo registers itself with the UnitTest 608// singleton such that the RUN_ALL_TESTS() macro knows which tests to 609// run. 610class TestInfo { 611 public: 612 // Destructs a TestInfo object. This function is not virtual, so 613 // don't inherit from TestInfo. 614 ~TestInfo(); 615 616 // Returns the test case name. 617 const char* test_case_name() const; 618 619 // Returns the test name. 620 const char* name() const; 621 622 // Returns the test case comment. 623 const char* test_case_comment() const; 624 625 // Returns the test comment. 626 const char* comment() const; 627 628 // Returns true if this test should run, that is if the test is not disabled 629 // (or it is disabled but the also_run_disabled_tests flag has been specified) 630 // and its full name matches the user-specified filter. 631 // 632 // Google Test allows the user to filter the tests by their full names. 633 // The full name of a test Bar in test case Foo is defined as 634 // "Foo.Bar". Only the tests that match the filter will run. 635 // 636 // A filter is a colon-separated list of glob (not regex) patterns, 637 // optionally followed by a '-' and a colon-separated list of 638 // negative patterns (tests to exclude). A test is run if it 639 // matches one of the positive patterns and does not match any of 640 // the negative patterns. 641 // 642 // For example, *A*:Foo.* is a filter that matches any string that 643 // contains the character 'A' or starts with "Foo.". 644 bool should_run() const; 645 646 // Returns the result of the test. 647 const TestResult* result() const; 648 649 private: 650#if GTEST_HAS_DEATH_TEST 651 friend class internal::DefaultDeathTestFactory; 652#endif // GTEST_HAS_DEATH_TEST 653 friend class Test; 654 friend class TestCase; 655 friend class internal::TestInfoImpl; 656 friend class internal::UnitTestImpl; 657 friend TestInfo* internal::MakeAndRegisterTestInfo( 658 const char* test_case_name, const char* name, 659 const char* test_case_comment, const char* comment, 660 internal::TypeId fixture_class_id, 661 Test::SetUpTestCaseFunc set_up_tc, 662 Test::TearDownTestCaseFunc tear_down_tc, 663 internal::TestFactoryBase* factory); 664 665 // Returns true if this test matches the user-specified filter. 666 bool matches_filter() const; 667 668 // Increments the number of death tests encountered in this test so 669 // far. 670 int increment_death_test_count(); 671 672 // Accessors for the implementation object. 673 internal::TestInfoImpl* impl() { return impl_; } 674 const internal::TestInfoImpl* impl() const { return impl_; } 675 676 // Constructs a TestInfo object. The newly constructed instance assumes 677 // ownership of the factory object. 678 TestInfo(const char* test_case_name, const char* name, 679 const char* test_case_comment, const char* comment, 680 internal::TypeId fixture_class_id, 681 internal::TestFactoryBase* factory); 682 683 // An opaque implementation object. 684 internal::TestInfoImpl* impl_; 685 686 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); 687}; 688 689// A test case, which consists of a vector of TestInfos. 690// 691// TestCase is not copyable. 692class TestCase { 693 public: 694 // Creates a TestCase with the given name. 695 // 696 // TestCase does NOT have a default constructor. Always use this 697 // constructor to create a TestCase object. 698 // 699 // Arguments: 700 // 701 // name: name of the test case 702 // set_up_tc: pointer to the function that sets up the test case 703 // tear_down_tc: pointer to the function that tears down the test case 704 TestCase(const char* name, const char* comment, 705 Test::SetUpTestCaseFunc set_up_tc, 706 Test::TearDownTestCaseFunc tear_down_tc); 707 708 // Destructor of TestCase. 709 virtual ~TestCase(); 710 711 // Gets the name of the TestCase. 712 const char* name() const { return name_.c_str(); } 713 714 // Returns the test case comment. 715 const char* comment() const { return comment_.c_str(); } 716 717 // Returns true if any test in this test case should run. 718 bool should_run() const { return should_run_; } 719 720 // Gets the number of successful tests in this test case. 721 int successful_test_count() const; 722 723 // Gets the number of failed tests in this test case. 724 int failed_test_count() const; 725 726 // Gets the number of disabled tests in this test case. 727 int disabled_test_count() const; 728 729 // Get the number of tests in this test case that should run. 730 int test_to_run_count() const; 731 732 // Gets the number of all tests in this test case. 733 int total_test_count() const; 734 735 // Returns true iff the test case passed. 736 bool Passed() const { return !Failed(); } 737 738 // Returns true iff the test case failed. 739 bool Failed() const { return failed_test_count() > 0; } 740 741 // Returns the elapsed time, in milliseconds. 742 TimeInMillis elapsed_time() const { return elapsed_time_; } 743 744 // Returns the i-th test among all the tests. i can range from 0 to 745 // total_test_count() - 1. If i is not in that range, returns NULL. 746 const TestInfo* GetTestInfo(int i) const; 747 748 private: 749 friend class Test; 750 friend class internal::UnitTestImpl; 751 752 // Gets the (mutable) vector of TestInfos in this TestCase. 753 internal::Vector<TestInfo*>& test_info_list() { return *test_info_list_; } 754 755 // Gets the (immutable) vector of TestInfos in this TestCase. 756 const internal::Vector<TestInfo *> & test_info_list() const { 757 return *test_info_list_; 758 } 759 760 // Returns the i-th test among all the tests. i can range from 0 to 761 // total_test_count() - 1. If i is not in that range, returns NULL. 762 TestInfo* GetMutableTestInfo(int i); 763 764 // Sets the should_run member. 765 void set_should_run(bool should) { should_run_ = should; } 766 767 // Adds a TestInfo to this test case. Will delete the TestInfo upon 768 // destruction of the TestCase object. 769 void AddTestInfo(TestInfo * test_info); 770 771 // Clears the results of all tests in this test case. 772 void ClearResult(); 773 774 // Clears the results of all tests in the given test case. 775 static void ClearTestCaseResult(TestCase* test_case) { 776 test_case->ClearResult(); 777 } 778 779 // Runs every test in this TestCase. 780 void Run(); 781 782 // Returns true iff test passed. 783 static bool TestPassed(const TestInfo * test_info); 784 785 // Returns true iff test failed. 786 static bool TestFailed(const TestInfo * test_info); 787 788 // Returns true iff test is disabled. 789 static bool TestDisabled(const TestInfo * test_info); 790 791 // Returns true if the given test should run. 792 static bool ShouldRunTest(const TestInfo *test_info); 793 794 // Shuffles the tests in this test case. 795 void ShuffleTests(internal::Random* random); 796 797 // Restores the test order to before the first shuffle. 798 void UnshuffleTests(); 799 800 // Name of the test case. 801 internal::String name_; 802 // Comment on the test case. 803 internal::String comment_; 804 // The vector of TestInfos in their original order. It owns the 805 // elements in the vector. 806 const internal::scoped_ptr<internal::Vector<TestInfo*> > test_info_list_; 807 // Provides a level of indirection for the test list to allow easy 808 // shuffling and restoring the test order. The i-th element in this 809 // vector is the index of the i-th test in the shuffled test list. 810 const internal::scoped_ptr<internal::Vector<int> > test_indices_; 811 // Pointer to the function that sets up the test case. 812 Test::SetUpTestCaseFunc set_up_tc_; 813 // Pointer to the function that tears down the test case. 814 Test::TearDownTestCaseFunc tear_down_tc_; 815 // True iff any test in this test case should run. 816 bool should_run_; 817 // Elapsed time, in milliseconds. 818 TimeInMillis elapsed_time_; 819 820 // We disallow copying TestCases. 821 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); 822}; 823 824// An Environment object is capable of setting up and tearing down an 825// environment. The user should subclass this to define his own 826// environment(s). 827// 828// An Environment object does the set-up and tear-down in virtual 829// methods SetUp() and TearDown() instead of the constructor and the 830// destructor, as: 831// 832// 1. You cannot safely throw from a destructor. This is a problem 833// as in some cases Google Test is used where exceptions are enabled, and 834// we may want to implement ASSERT_* using exceptions where they are 835// available. 836// 2. You cannot use ASSERT_* directly in a constructor or 837// destructor. 838class Environment { 839 public: 840 // The d'tor is virtual as we need to subclass Environment. 841 virtual ~Environment() {} 842 843 // Override this to define how to set up the environment. 844 virtual void SetUp() {} 845 846 // Override this to define how to tear down the environment. 847 virtual void TearDown() {} 848 private: 849 // If you see an error about overriding the following function or 850 // about it being private, you have mis-spelled SetUp() as Setup(). 851 struct Setup_should_be_spelled_SetUp {}; 852 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } 853}; 854 855// The interface for tracing execution of tests. The methods are organized in 856// the order the corresponding events are fired. 857class TestEventListener { 858 public: 859 virtual ~TestEventListener() {} 860 861 // Fired before any test activity starts. 862 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; 863 864 // Fired before each iteration of tests starts. There may be more than 865 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration 866 // index, starting from 0. 867 virtual void OnTestIterationStart(const UnitTest& unit_test, 868 int iteration) = 0; 869 870 // Fired before environment set-up for each iteration of tests starts. 871 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; 872 873 // Fired after environment set-up for each iteration of tests ends. 874 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; 875 876 // Fired before the test case starts. 877 virtual void OnTestCaseStart(const TestCase& test_case) = 0; 878 879 // Fired before the test starts. 880 virtual void OnTestStart(const TestInfo& test_info) = 0; 881 882 // Fired after a failed assertion or a SUCCESS(). 883 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; 884 885 // Fired after the test ends. 886 virtual void OnTestEnd(const TestInfo& test_info) = 0; 887 888 // Fired after the test case ends. 889 virtual void OnTestCaseEnd(const TestCase& test_case) = 0; 890 891 // Fired before environment tear-down for each iteration of tests starts. 892 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; 893 894 // Fired after environment tear-down for each iteration of tests ends. 895 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; 896 897 // Fired after each iteration of tests finishes. 898 virtual void OnTestIterationEnd(const UnitTest& unit_test, 899 int iteration) = 0; 900 901 // Fired after all test activities have ended. 902 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; 903}; 904 905// The convenience class for users who need to override just one or two 906// methods and are not concerned that a possible change to a signature of 907// the methods they override will not be caught during the build. For 908// comments about each method please see the definition of TestEventListener 909// above. 910class EmptyTestEventListener : public TestEventListener { 911 public: 912 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} 913 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, 914 int /*iteration*/) {} 915 virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} 916 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} 917 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} 918 virtual void OnTestStart(const TestInfo& /*test_info*/) {} 919 virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} 920 virtual void OnTestEnd(const TestInfo& /*test_info*/) {} 921 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} 922 virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} 923 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} 924 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, 925 int /*iteration*/) {} 926 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} 927}; 928 929// TestEventListeners lets users add listeners to track events in Google Test. 930class TestEventListeners { 931 public: 932 TestEventListeners(); 933 ~TestEventListeners(); 934 935 // Appends an event listener to the end of the list. Google Test assumes 936 // the ownership of the listener (i.e. it will delete the listener when 937 // the test program finishes). 938 void Append(TestEventListener* listener); 939 940 // Removes the given event listener from the list and returns it. It then 941 // becomes the caller's responsibility to delete the listener. Returns 942 // NULL if the listener is not found in the list. 943 TestEventListener* Release(TestEventListener* listener); 944 945 // Returns the standard listener responsible for the default console 946 // output. Can be removed from the listeners list to shut down default 947 // console output. Note that removing this object from the listener list 948 // with Release transfers its ownership to the caller and makes this 949 // function return NULL the next time. 950 TestEventListener* default_result_printer() const { 951 return default_result_printer_; 952 } 953 954 // Returns the standard listener responsible for the default XML output 955 // controlled by the --gtest_output=xml flag. Can be removed from the 956 // listeners list by users who want to shut down the default XML output 957 // controlled by this flag and substitute it with custom one. Note that 958 // removing this object from the listener list with Release transfers its 959 // ownership to the caller and makes this function return NULL the next 960 // time. 961 TestEventListener* default_xml_generator() const { 962 return default_xml_generator_; 963 } 964 965 private: 966 friend class TestCase; 967 friend class internal::DefaultGlobalTestPartResultReporter; 968 friend class internal::NoExecDeathTest; 969 friend class internal::TestEventListenersAccessor; 970 friend class internal::TestInfoImpl; 971 friend class internal::UnitTestImpl; 972 973 // Returns repeater that broadcasts the TestEventListener events to all 974 // subscribers. 975 TestEventListener* repeater(); 976 977 // Sets the default_result_printer attribute to the provided listener. 978 // The listener is also added to the listener list and previous 979 // default_result_printer is removed from it and deleted. The listener can 980 // also be NULL in which case it will not be added to the list. Does 981 // nothing if the previous and the current listener objects are the same. 982 void SetDefaultResultPrinter(TestEventListener* listener); 983 984 // Sets the default_xml_generator attribute to the provided listener. The 985 // listener is also added to the listener list and previous 986 // default_xml_generator is removed from it and deleted. The listener can 987 // also be NULL in which case it will not be added to the list. Does 988 // nothing if the previous and the current listener objects are the same. 989 void SetDefaultXmlGenerator(TestEventListener* listener); 990 991 // Controls whether events will be forwarded by the repeater to the 992 // listeners in the list. 993 bool EventForwardingEnabled() const; 994 void SuppressEventForwarding(); 995 996 // The actual list of listeners. 997 internal::TestEventRepeater* repeater_; 998 // Listener responsible for the standard result output. 999 TestEventListener* default_result_printer_; 1000 // Listener responsible for the creation of the XML output file. 1001 TestEventListener* default_xml_generator_; 1002 1003 // We disallow copying TestEventListeners. 1004 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); 1005}; 1006 1007// A UnitTest consists of a vector of TestCases. 1008// 1009// This is a singleton class. The only instance of UnitTest is 1010// created when UnitTest::GetInstance() is first called. This 1011// instance is never deleted. 1012// 1013// UnitTest is not copyable. 1014// 1015// This class is thread-safe as long as the methods are called 1016// according to their specification. 1017class UnitTest { 1018 public: 1019 // Gets the singleton UnitTest object. The first time this method 1020 // is called, a UnitTest object is constructed and returned. 1021 // Consecutive calls will return the same object. 1022 static UnitTest* GetInstance(); 1023 1024 // Runs all tests in this UnitTest object and prints the result. 1025 // Returns 0 if successful, or 1 otherwise. 1026 // 1027 // This method can only be called from the main thread. 1028 // 1029 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1030 int Run() GTEST_MUST_USE_RESULT_; 1031 1032 // Returns the working directory when the first TEST() or TEST_F() 1033 // was executed. The UnitTest object owns the string. 1034 const char* original_working_dir() const; 1035 1036 // Returns the TestCase object for the test that's currently running, 1037 // or NULL if no test is running. 1038 const TestCase* current_test_case() const; 1039 1040 // Returns the TestInfo object for the test that's currently running, 1041 // or NULL if no test is running. 1042 const TestInfo* current_test_info() const; 1043 1044 // Returns the random seed used at the start of the current test run. 1045 int random_seed() const; 1046 1047#if GTEST_HAS_PARAM_TEST 1048 // Returns the ParameterizedTestCaseRegistry object used to keep track of 1049 // value-parameterized tests and instantiate and register them. 1050 // 1051 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1052 internal::ParameterizedTestCaseRegistry& parameterized_test_registry(); 1053#endif // GTEST_HAS_PARAM_TEST 1054 1055 // Gets the number of successful test cases. 1056 int successful_test_case_count() const; 1057 1058 // Gets the number of failed test cases. 1059 int failed_test_case_count() const; 1060 1061 // Gets the number of all test cases. 1062 int total_test_case_count() const; 1063 1064 // Gets the number of all test cases that contain at least one test 1065 // that should run. 1066 int test_case_to_run_count() const; 1067 1068 // Gets the number of successful tests. 1069 int successful_test_count() const; 1070 1071 // Gets the number of failed tests. 1072 int failed_test_count() const; 1073 1074 // Gets the number of disabled tests. 1075 int disabled_test_count() const; 1076 1077 // Gets the number of all tests. 1078 int total_test_count() const; 1079 1080 // Gets the number of tests that should run. 1081 int test_to_run_count() const; 1082 1083 // Gets the elapsed time, in milliseconds. 1084 TimeInMillis elapsed_time() const; 1085 1086 // Returns true iff the unit test passed (i.e. all test cases passed). 1087 bool Passed() const; 1088 1089 // Returns true iff the unit test failed (i.e. some test case failed 1090 // or something outside of all tests failed). 1091 bool Failed() const; 1092 1093 // Gets the i-th test case among all the test cases. i can range from 0 to 1094 // total_test_case_count() - 1. If i is not in that range, returns NULL. 1095 const TestCase* GetTestCase(int i) const; 1096 1097 // Returns the list of event listeners that can be used to track events 1098 // inside Google Test. 1099 TestEventListeners& listeners(); 1100 1101 private: 1102 // Registers and returns a global test environment. When a test 1103 // program is run, all global test environments will be set-up in 1104 // the order they were registered. After all tests in the program 1105 // have finished, all global test environments will be torn-down in 1106 // the *reverse* order they were registered. 1107 // 1108 // The UnitTest object takes ownership of the given environment. 1109 // 1110 // This method can only be called from the main thread. 1111 Environment* AddEnvironment(Environment* env); 1112 1113 // Adds a TestPartResult to the current TestResult object. All 1114 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) 1115 // eventually call this to report their results. The user code 1116 // should use the assertion macros instead of calling this directly. 1117 void AddTestPartResult(TestPartResult::Type result_type, 1118 const char* file_name, 1119 int line_number, 1120 const internal::String& message, 1121 const internal::String& os_stack_trace); 1122 1123 // Adds a TestProperty to the current TestResult object. If the result already 1124 // contains a property with the same key, the value will be updated. 1125 void RecordPropertyForCurrentTest(const char* key, const char* value); 1126 1127 // Gets the i-th test case among all the test cases. i can range from 0 to 1128 // total_test_case_count() - 1. If i is not in that range, returns NULL. 1129 TestCase* GetMutableTestCase(int i); 1130 1131 // Accessors for the implementation object. 1132 internal::UnitTestImpl* impl() { return impl_; } 1133 const internal::UnitTestImpl* impl() const { return impl_; } 1134 1135 // These classes and funcions are friends as they need to access private 1136 // members of UnitTest. 1137 friend class Test; 1138 friend class internal::AssertHelper; 1139 friend class internal::ScopedTrace; 1140 friend Environment* AddGlobalTestEnvironment(Environment* env); 1141 friend internal::UnitTestImpl* internal::GetUnitTestImpl(); 1142 friend void internal::ReportFailureInUnknownLocation( 1143 TestPartResult::Type result_type, 1144 const internal::String& message); 1145 1146 // Creates an empty UnitTest. 1147 UnitTest(); 1148 1149 // D'tor 1150 virtual ~UnitTest(); 1151 1152 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread 1153 // Google Test trace stack. 1154 void PushGTestTrace(const internal::TraceInfo& trace); 1155 1156 // Pops a trace from the per-thread Google Test trace stack. 1157 void PopGTestTrace(); 1158 1159 // Protects mutable state in *impl_. This is mutable as some const 1160 // methods need to lock it too. 1161 mutable internal::Mutex mutex_; 1162 1163 // Opaque implementation object. This field is never changed once 1164 // the object is constructed. We don't mark it as const here, as 1165 // doing so will cause a warning in the constructor of UnitTest. 1166 // Mutable state in *impl_ is protected by mutex_. 1167 internal::UnitTestImpl* impl_; 1168 1169 // We disallow copying UnitTest. 1170 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); 1171}; 1172 1173// A convenient wrapper for adding an environment for the test 1174// program. 1175// 1176// You should call this before RUN_ALL_TESTS() is called, probably in 1177// main(). If you use gtest_main, you need to call this before main() 1178// starts for it to take effect. For example, you can define a global 1179// variable like this: 1180// 1181// testing::Environment* const foo_env = 1182// testing::AddGlobalTestEnvironment(new FooEnvironment); 1183// 1184// However, we strongly recommend you to write your own main() and 1185// call AddGlobalTestEnvironment() there, as relying on initialization 1186// of global variables makes the code harder to read and may cause 1187// problems when you register multiple environments from different 1188// translation units and the environments have dependencies among them 1189// (remember that the compiler doesn't guarantee the order in which 1190// global variables from different translation units are initialized). 1191inline Environment* AddGlobalTestEnvironment(Environment* env) { 1192 return UnitTest::GetInstance()->AddEnvironment(env); 1193} 1194 1195// Initializes Google Test. This must be called before calling 1196// RUN_ALL_TESTS(). In particular, it parses a command line for the 1197// flags that Google Test recognizes. Whenever a Google Test flag is 1198// seen, it is removed from argv, and *argc is decremented. 1199// 1200// No value is returned. Instead, the Google Test flag variables are 1201// updated. 1202// 1203// Calling the function for the second time has no user-visible effect. 1204void InitGoogleTest(int* argc, char** argv); 1205 1206// This overloaded version can be used in Windows programs compiled in 1207// UNICODE mode. 1208void InitGoogleTest(int* argc, wchar_t** argv); 1209 1210namespace internal { 1211 1212// These overloaded versions handle ::std::string and ::std::wstring. 1213#if GTEST_HAS_STD_STRING 1214inline String FormatForFailureMessage(const ::std::string& str) { 1215 return (Message() << '"' << str << '"').GetString(); 1216} 1217#endif // GTEST_HAS_STD_STRING 1218 1219#if GTEST_HAS_STD_WSTRING 1220inline String FormatForFailureMessage(const ::std::wstring& wstr) { 1221 return (Message() << "L\"" << wstr << '"').GetString(); 1222} 1223#endif // GTEST_HAS_STD_WSTRING 1224 1225// These overloaded versions handle ::string and ::wstring. 1226#if GTEST_HAS_GLOBAL_STRING 1227inline String FormatForFailureMessage(const ::string& str) { 1228 return (Message() << '"' << str << '"').GetString(); 1229} 1230#endif // GTEST_HAS_GLOBAL_STRING 1231 1232#if GTEST_HAS_GLOBAL_WSTRING 1233inline String FormatForFailureMessage(const ::wstring& wstr) { 1234 return (Message() << "L\"" << wstr << '"').GetString(); 1235} 1236#endif // GTEST_HAS_GLOBAL_WSTRING 1237 1238// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) 1239// operand to be used in a failure message. The type (but not value) 1240// of the other operand may affect the format. This allows us to 1241// print a char* as a raw pointer when it is compared against another 1242// char*, and print it as a C string when it is compared against an 1243// std::string object, for example. 1244// 1245// The default implementation ignores the type of the other operand. 1246// Some specialized versions are used to handle formatting wide or 1247// narrow C strings. 1248// 1249// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1250template <typename T1, typename T2> 1251String FormatForComparisonFailureMessage(const T1& value, 1252 const T2& /* other_operand */) { 1253 return FormatForFailureMessage(value); 1254} 1255 1256// The helper function for {ASSERT|EXPECT}_EQ. 1257template <typename T1, typename T2> 1258AssertionResult CmpHelperEQ(const char* expected_expression, 1259 const char* actual_expression, 1260 const T1& expected, 1261 const T2& actual) { 1262#ifdef _MSC_VER 1263#pragma warning(push) // Saves the current warning state. 1264#pragma warning(disable:4389) // Temporarily disables warning on 1265 // signed/unsigned mismatch. 1266#endif 1267 1268 if (expected == actual) { 1269 return AssertionSuccess(); 1270 } 1271 1272#ifdef _MSC_VER 1273#pragma warning(pop) // Restores the warning state. 1274#endif 1275 1276 return EqFailure(expected_expression, 1277 actual_expression, 1278 FormatForComparisonFailureMessage(expected, actual), 1279 FormatForComparisonFailureMessage(actual, expected), 1280 false); 1281} 1282 1283// With this overloaded version, we allow anonymous enums to be used 1284// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums 1285// can be implicitly cast to BiggestInt. 1286AssertionResult CmpHelperEQ(const char* expected_expression, 1287 const char* actual_expression, 1288 BiggestInt expected, 1289 BiggestInt actual); 1290 1291// The helper class for {ASSERT|EXPECT}_EQ. The template argument 1292// lhs_is_null_literal is true iff the first argument to ASSERT_EQ() 1293// is a null pointer literal. The following default implementation is 1294// for lhs_is_null_literal being false. 1295template <bool lhs_is_null_literal> 1296class EqHelper { 1297 public: 1298 // This templatized version is for the general case. 1299 template <typename T1, typename T2> 1300 static AssertionResult Compare(const char* expected_expression, 1301 const char* actual_expression, 1302 const T1& expected, 1303 const T2& actual) { 1304 return CmpHelperEQ(expected_expression, actual_expression, expected, 1305 actual); 1306 } 1307 1308 // With this overloaded version, we allow anonymous enums to be used 1309 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous 1310 // enums can be implicitly cast to BiggestInt. 1311 // 1312 // Even though its body looks the same as the above version, we 1313 // cannot merge the two, as it will make anonymous enums unhappy. 1314 static AssertionResult Compare(const char* expected_expression, 1315 const char* actual_expression, 1316 BiggestInt expected, 1317 BiggestInt actual) { 1318 return CmpHelperEQ(expected_expression, actual_expression, expected, 1319 actual); 1320 } 1321}; 1322 1323// This specialization is used when the first argument to ASSERT_EQ() 1324// is a null pointer literal. 1325template <> 1326class EqHelper<true> { 1327 public: 1328 // We define two overloaded versions of Compare(). The first 1329 // version will be picked when the second argument to ASSERT_EQ() is 1330 // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or 1331 // EXPECT_EQ(false, a_bool). 1332 template <typename T1, typename T2> 1333 static AssertionResult Compare(const char* expected_expression, 1334 const char* actual_expression, 1335 const T1& expected, 1336 const T2& actual) { 1337 return CmpHelperEQ(expected_expression, actual_expression, expected, 1338 actual); 1339 } 1340 1341 // This version will be picked when the second argument to 1342 // ASSERT_EQ() is a pointer, e.g. ASSERT_EQ(NULL, a_pointer). 1343 template <typename T1, typename T2> 1344 static AssertionResult Compare(const char* expected_expression, 1345 const char* actual_expression, 1346 const T1& /* expected */, 1347 T2* actual) { 1348 // We already know that 'expected' is a null pointer. 1349 return CmpHelperEQ(expected_expression, actual_expression, 1350 static_cast<T2*>(NULL), actual); 1351 } 1352}; 1353 1354// A macro for implementing the helper functions needed to implement 1355// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste 1356// of similar code. 1357// 1358// For each templatized helper function, we also define an overloaded 1359// version for BiggestInt in order to reduce code bloat and allow 1360// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled 1361// with gcc 4. 1362// 1363// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1364#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ 1365template <typename T1, typename T2>\ 1366AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ 1367 const T1& val1, const T2& val2) {\ 1368 if (val1 op val2) {\ 1369 return AssertionSuccess();\ 1370 } else {\ 1371 Message msg;\ 1372 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\ 1373 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ 1374 << " vs " << FormatForComparisonFailureMessage(val2, val1);\ 1375 return AssertionFailure(msg);\ 1376 }\ 1377}\ 1378AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ 1379 BiggestInt val1, BiggestInt val2); 1380 1381// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1382 1383// Implements the helper function for {ASSERT|EXPECT}_NE 1384GTEST_IMPL_CMP_HELPER_(NE, !=) 1385// Implements the helper function for {ASSERT|EXPECT}_LE 1386GTEST_IMPL_CMP_HELPER_(LE, <=) 1387// Implements the helper function for {ASSERT|EXPECT}_LT 1388GTEST_IMPL_CMP_HELPER_(LT, < ) 1389// Implements the helper function for {ASSERT|EXPECT}_GE 1390GTEST_IMPL_CMP_HELPER_(GE, >=) 1391// Implements the helper function for {ASSERT|EXPECT}_GT 1392GTEST_IMPL_CMP_HELPER_(GT, > ) 1393 1394#undef GTEST_IMPL_CMP_HELPER_ 1395 1396// The helper function for {ASSERT|EXPECT}_STREQ. 1397// 1398// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1399AssertionResult CmpHelperSTREQ(const char* expected_expression, 1400 const char* actual_expression, 1401 const char* expected, 1402 const char* actual); 1403 1404// The helper function for {ASSERT|EXPECT}_STRCASEEQ. 1405// 1406// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1407AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, 1408 const char* actual_expression, 1409 const char* expected, 1410 const char* actual); 1411 1412// The helper function for {ASSERT|EXPECT}_STRNE. 1413// 1414// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1415AssertionResult CmpHelperSTRNE(const char* s1_expression, 1416 const char* s2_expression, 1417 const char* s1, 1418 const char* s2); 1419 1420// The helper function for {ASSERT|EXPECT}_STRCASENE. 1421// 1422// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1423AssertionResult CmpHelperSTRCASENE(const char* s1_expression, 1424 const char* s2_expression, 1425 const char* s1, 1426 const char* s2); 1427 1428 1429// Helper function for *_STREQ on wide strings. 1430// 1431// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1432AssertionResult CmpHelperSTREQ(const char* expected_expression, 1433 const char* actual_expression, 1434 const wchar_t* expected, 1435 const wchar_t* actual); 1436 1437// Helper function for *_STRNE on wide strings. 1438// 1439// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1440AssertionResult CmpHelperSTRNE(const char* s1_expression, 1441 const char* s2_expression, 1442 const wchar_t* s1, 1443 const wchar_t* s2); 1444 1445} // namespace internal 1446 1447// IsSubstring() and IsNotSubstring() are intended to be used as the 1448// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by 1449// themselves. They check whether needle is a substring of haystack 1450// (NULL is considered a substring of itself only), and return an 1451// appropriate error message when they fail. 1452// 1453// The {needle,haystack}_expr arguments are the stringified 1454// expressions that generated the two real arguments. 1455AssertionResult IsSubstring( 1456 const char* needle_expr, const char* haystack_expr, 1457 const char* needle, const char* haystack); 1458AssertionResult IsSubstring( 1459 const char* needle_expr, const char* haystack_expr, 1460 const wchar_t* needle, const wchar_t* haystack); 1461AssertionResult IsNotSubstring( 1462 const char* needle_expr, const char* haystack_expr, 1463 const char* needle, const char* haystack); 1464AssertionResult IsNotSubstring( 1465 const char* needle_expr, const char* haystack_expr, 1466 const wchar_t* needle, const wchar_t* haystack); 1467#if GTEST_HAS_STD_STRING 1468AssertionResult IsSubstring( 1469 const char* needle_expr, const char* haystack_expr, 1470 const ::std::string& needle, const ::std::string& haystack); 1471AssertionResult IsNotSubstring( 1472 const char* needle_expr, const char* haystack_expr, 1473 const ::std::string& needle, const ::std::string& haystack); 1474#endif // GTEST_HAS_STD_STRING 1475 1476#if GTEST_HAS_STD_WSTRING 1477AssertionResult IsSubstring( 1478 const char* needle_expr, const char* haystack_expr, 1479 const ::std::wstring& needle, const ::std::wstring& haystack); 1480AssertionResult IsNotSubstring( 1481 const char* needle_expr, const char* haystack_expr, 1482 const ::std::wstring& needle, const ::std::wstring& haystack); 1483#endif // GTEST_HAS_STD_WSTRING 1484 1485namespace internal { 1486 1487// Helper template function for comparing floating-points. 1488// 1489// Template parameter: 1490// 1491// RawType: the raw floating-point type (either float or double) 1492// 1493// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1494template <typename RawType> 1495AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, 1496 const char* actual_expression, 1497 RawType expected, 1498 RawType actual) { 1499 const FloatingPoint<RawType> lhs(expected), rhs(actual); 1500 1501 if (lhs.AlmostEquals(rhs)) { 1502 return AssertionSuccess(); 1503 } 1504 1505 StrStream expected_ss; 1506 expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) 1507 << expected; 1508 1509 StrStream actual_ss; 1510 actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) 1511 << actual; 1512 1513 return EqFailure(expected_expression, 1514 actual_expression, 1515 StrStreamToString(&expected_ss), 1516 StrStreamToString(&actual_ss), 1517 false); 1518} 1519 1520// Helper function for implementing ASSERT_NEAR. 1521// 1522// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 1523AssertionResult DoubleNearPredFormat(const char* expr1, 1524 const char* expr2, 1525 const char* abs_error_expr, 1526 double val1, 1527 double val2, 1528 double abs_error); 1529 1530// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. 1531// A class that enables one to stream messages to assertion macros 1532class AssertHelper { 1533 public: 1534 // Constructor. 1535 AssertHelper(TestPartResult::Type type, 1536 const char* file, 1537 int line, 1538 const char* message); 1539 ~AssertHelper(); 1540 1541 // Message assignment is a semantic trick to enable assertion 1542 // streaming; see the GTEST_MESSAGE_ macro below. 1543 void operator=(const Message& message) const; 1544 1545 private: 1546 // We put our data in a struct so that the size of the AssertHelper class can 1547 // be as small as possible. This is important because gcc is incapable of 1548 // re-using stack space even for temporary variables, so every EXPECT_EQ 1549 // reserves stack space for another AssertHelper. 1550 struct AssertHelperData { 1551 AssertHelperData(TestPartResult::Type t, 1552 const char* srcfile, 1553 int line_num, 1554 const char* msg) 1555 : type(t), file(srcfile), line(line_num), message(msg) { } 1556 1557 TestPartResult::Type const type; 1558 const char* const file; 1559 int const line; 1560 String const message; 1561 1562 private: 1563 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); 1564 }; 1565 1566 AssertHelperData* const data_; 1567 1568 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); 1569}; 1570 1571} // namespace internal 1572 1573#if GTEST_HAS_PARAM_TEST 1574// The abstract base class that all value-parameterized tests inherit from. 1575// 1576// This class adds support for accessing the test parameter value via 1577// the GetParam() method. 1578// 1579// Use it with one of the parameter generator defining functions, like Range(), 1580// Values(), ValuesIn(), Bool(), and Combine(). 1581// 1582// class FooTest : public ::testing::TestWithParam<int> { 1583// protected: 1584// FooTest() { 1585// // Can use GetParam() here. 1586// } 1587// virtual ~FooTest() { 1588// // Can use GetParam() here. 1589// } 1590// virtual void SetUp() { 1591// // Can use GetParam() here. 1592// } 1593// virtual void TearDown { 1594// // Can use GetParam() here. 1595// } 1596// }; 1597// TEST_P(FooTest, DoesBar) { 1598// // Can use GetParam() method here. 1599// Foo foo; 1600// ASSERT_TRUE(foo.DoesBar(GetParam())); 1601// } 1602// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); 1603 1604template <typename T> 1605class TestWithParam : public Test { 1606 public: 1607 typedef T ParamType; 1608 1609 // The current parameter value. Is also available in the test fixture's 1610 // constructor. 1611 const ParamType& GetParam() const { return *parameter_; } 1612 1613 private: 1614 // Sets parameter value. The caller is responsible for making sure the value 1615 // remains alive and unchanged throughout the current test. 1616 static void SetParam(const ParamType* parameter) { 1617 parameter_ = parameter; 1618 } 1619 1620 // Static value used for accessing parameter during a test lifetime. 1621 static const ParamType* parameter_; 1622 1623 // TestClass must be a subclass of TestWithParam<T>. 1624 template <class TestClass> friend class internal::ParameterizedTestFactory; 1625}; 1626 1627template <typename T> 1628const T* TestWithParam<T>::parameter_ = NULL; 1629 1630#endif // GTEST_HAS_PARAM_TEST 1631 1632// Macros for indicating success/failure in test code. 1633 1634// ADD_FAILURE unconditionally adds a failure to the current test. 1635// SUCCEED generates a success - it doesn't automatically make the 1636// current test successful, as a test is only successful when it has 1637// no failure. 1638// 1639// EXPECT_* verifies that a certain condition is satisfied. If not, 1640// it behaves like ADD_FAILURE. In particular: 1641// 1642// EXPECT_TRUE verifies that a Boolean condition is true. 1643// EXPECT_FALSE verifies that a Boolean condition is false. 1644// 1645// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except 1646// that they will also abort the current function on failure. People 1647// usually want the fail-fast behavior of FAIL and ASSERT_*, but those 1648// writing data-driven tests often find themselves using ADD_FAILURE 1649// and EXPECT_* more. 1650// 1651// Examples: 1652// 1653// EXPECT_TRUE(server.StatusIsOK()); 1654// ASSERT_FALSE(server.HasPendingRequest(port)) 1655// << "There are still pending requests " << "on port " << port; 1656 1657// Generates a nonfatal failure with a generic message. 1658#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") 1659 1660// Generates a fatal failure with a generic message. 1661#define FAIL() GTEST_FATAL_FAILURE_("Failed") 1662 1663// Generates a success with a generic message. 1664#define SUCCEED() GTEST_SUCCESS_("Succeeded") 1665 1666// Macros for testing exceptions. 1667// 1668// * {ASSERT|EXPECT}_THROW(statement, expected_exception): 1669// Tests that the statement throws the expected exception. 1670// * {ASSERT|EXPECT}_NO_THROW(statement): 1671// Tests that the statement doesn't throw any exception. 1672// * {ASSERT|EXPECT}_ANY_THROW(statement): 1673// Tests that the statement throws an exception. 1674 1675#define EXPECT_THROW(statement, expected_exception) \ 1676 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) 1677#define EXPECT_NO_THROW(statement) \ 1678 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) 1679#define EXPECT_ANY_THROW(statement) \ 1680 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) 1681#define ASSERT_THROW(statement, expected_exception) \ 1682 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) 1683#define ASSERT_NO_THROW(statement) \ 1684 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) 1685#define ASSERT_ANY_THROW(statement) \ 1686 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) 1687 1688// Boolean assertions. Condition can be either a Boolean expression or an 1689// AssertionResult. For more information on how to use AssertionResult with 1690// these macros see comments on that class. 1691#define EXPECT_TRUE(condition) \ 1692 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ 1693 GTEST_NONFATAL_FAILURE_) 1694#define EXPECT_FALSE(condition) \ 1695 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ 1696 GTEST_NONFATAL_FAILURE_) 1697#define ASSERT_TRUE(condition) \ 1698 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ 1699 GTEST_FATAL_FAILURE_) 1700#define ASSERT_FALSE(condition) \ 1701 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ 1702 GTEST_FATAL_FAILURE_) 1703 1704// Includes the auto-generated header that implements a family of 1705// generic predicate assertion macros. 1706#include <gtest/gtest_pred_impl.h> 1707 1708// Macros for testing equalities and inequalities. 1709// 1710// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual 1711// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 1712// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 1713// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 1714// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 1715// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 1716// 1717// When they are not, Google Test prints both the tested expressions and 1718// their actual values. The values must be compatible built-in types, 1719// or you will get a compiler error. By "compatible" we mean that the 1720// values can be compared by the respective operator. 1721// 1722// Note: 1723// 1724// 1. It is possible to make a user-defined type work with 1725// {ASSERT|EXPECT}_??(), but that requires overloading the 1726// comparison operators and is thus discouraged by the Google C++ 1727// Usage Guide. Therefore, you are advised to use the 1728// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are 1729// equal. 1730// 1731// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on 1732// pointers (in particular, C strings). Therefore, if you use it 1733// with two C strings, you are testing how their locations in memory 1734// are related, not how their content is related. To compare two C 1735// strings by content, use {ASSERT|EXPECT}_STR*(). 1736// 1737// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to 1738// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you 1739// what the actual value is when it fails, and similarly for the 1740// other comparisons. 1741// 1742// 4. Do not depend on the order in which {ASSERT|EXPECT}_??() 1743// evaluate their arguments, which is undefined. 1744// 1745// 5. These macros evaluate their arguments exactly once. 1746// 1747// Examples: 1748// 1749// EXPECT_NE(5, Foo()); 1750// EXPECT_EQ(NULL, a_pointer); 1751// ASSERT_LT(i, array_size); 1752// ASSERT_GT(records.size(), 0) << "There is no record left."; 1753 1754#define EXPECT_EQ(expected, actual) \ 1755 EXPECT_PRED_FORMAT2(::testing::internal:: \ 1756 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \ 1757 expected, actual) 1758#define EXPECT_NE(expected, actual) \ 1759 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) 1760#define EXPECT_LE(val1, val2) \ 1761 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) 1762#define EXPECT_LT(val1, val2) \ 1763 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) 1764#define EXPECT_GE(val1, val2) \ 1765 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) 1766#define EXPECT_GT(val1, val2) \ 1767 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) 1768 1769#define ASSERT_EQ(expected, actual) \ 1770 ASSERT_PRED_FORMAT2(::testing::internal:: \ 1771 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \ 1772 expected, actual) 1773#define ASSERT_NE(val1, val2) \ 1774 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) 1775#define ASSERT_LE(val1, val2) \ 1776 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) 1777#define ASSERT_LT(val1, val2) \ 1778 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) 1779#define ASSERT_GE(val1, val2) \ 1780 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) 1781#define ASSERT_GT(val1, val2) \ 1782 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) 1783 1784// C String Comparisons. All tests treat NULL and any non-NULL string 1785// as different. Two NULLs are equal. 1786// 1787// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 1788// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 1789// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case 1790// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case 1791// 1792// For wide or narrow string objects, you can use the 1793// {ASSERT|EXPECT}_??() macros. 1794// 1795// Don't depend on the order in which the arguments are evaluated, 1796// which is undefined. 1797// 1798// These macros evaluate their arguments exactly once. 1799 1800#define EXPECT_STREQ(expected, actual) \ 1801 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) 1802#define EXPECT_STRNE(s1, s2) \ 1803 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) 1804#define EXPECT_STRCASEEQ(expected, actual) \ 1805 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) 1806#define EXPECT_STRCASENE(s1, s2)\ 1807 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) 1808 1809#define ASSERT_STREQ(expected, actual) \ 1810 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) 1811#define ASSERT_STRNE(s1, s2) \ 1812 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) 1813#define ASSERT_STRCASEEQ(expected, actual) \ 1814 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) 1815#define ASSERT_STRCASENE(s1, s2)\ 1816 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) 1817 1818// Macros for comparing floating-point numbers. 1819// 1820// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): 1821// Tests that two float values are almost equal. 1822// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): 1823// Tests that two double values are almost equal. 1824// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): 1825// Tests that v1 and v2 are within the given distance to each other. 1826// 1827// Google Test uses ULP-based comparison to automatically pick a default 1828// error bound that is appropriate for the operands. See the 1829// FloatingPoint template class in gtest-internal.h if you are 1830// interested in the implementation details. 1831 1832#define EXPECT_FLOAT_EQ(expected, actual)\ 1833 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ 1834 expected, actual) 1835 1836#define EXPECT_DOUBLE_EQ(expected, actual)\ 1837 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ 1838 expected, actual) 1839 1840#define ASSERT_FLOAT_EQ(expected, actual)\ 1841 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ 1842 expected, actual) 1843 1844#define ASSERT_DOUBLE_EQ(expected, actual)\ 1845 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ 1846 expected, actual) 1847 1848#define EXPECT_NEAR(val1, val2, abs_error)\ 1849 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ 1850 val1, val2, abs_error) 1851 1852#define ASSERT_NEAR(val1, val2, abs_error)\ 1853 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ 1854 val1, val2, abs_error) 1855 1856// These predicate format functions work on floating-point values, and 1857// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. 1858// 1859// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); 1860 1861// Asserts that val1 is less than, or almost equal to, val2. Fails 1862// otherwise. In particular, it fails if either val1 or val2 is NaN. 1863AssertionResult FloatLE(const char* expr1, const char* expr2, 1864 float val1, float val2); 1865AssertionResult DoubleLE(const char* expr1, const char* expr2, 1866 double val1, double val2); 1867 1868 1869#if GTEST_OS_WINDOWS 1870 1871// Macros that test for HRESULT failure and success, these are only useful 1872// on Windows, and rely on Windows SDK macros and APIs to compile. 1873// 1874// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) 1875// 1876// When expr unexpectedly fails or succeeds, Google Test prints the 1877// expected result and the actual result with both a human-readable 1878// string representation of the error, if available, as well as the 1879// hex result code. 1880#define EXPECT_HRESULT_SUCCEEDED(expr) \ 1881 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) 1882 1883#define ASSERT_HRESULT_SUCCEEDED(expr) \ 1884 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) 1885 1886#define EXPECT_HRESULT_FAILED(expr) \ 1887 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) 1888 1889#define ASSERT_HRESULT_FAILED(expr) \ 1890 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) 1891 1892#endif // GTEST_OS_WINDOWS 1893 1894// Macros that execute statement and check that it doesn't generate new fatal 1895// failures in the current thread. 1896// 1897// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); 1898// 1899// Examples: 1900// 1901// EXPECT_NO_FATAL_FAILURE(Process()); 1902// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; 1903// 1904#define ASSERT_NO_FATAL_FAILURE(statement) \ 1905 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) 1906#define EXPECT_NO_FATAL_FAILURE(statement) \ 1907 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) 1908 1909// Causes a trace (including the source file path, the current line 1910// number, and the given message) to be included in every test failure 1911// message generated by code in the current scope. The effect is 1912// undone when the control leaves the current scope. 1913// 1914// The message argument can be anything streamable to std::ostream. 1915// 1916// In the implementation, we include the current line number as part 1917// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s 1918// to appear in the same block - as long as they are on different 1919// lines. 1920#define SCOPED_TRACE(message) \ 1921 ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ 1922 __FILE__, __LINE__, ::testing::Message() << (message)) 1923 1924namespace internal { 1925 1926// This template is declared, but intentionally undefined. 1927template <typename T1, typename T2> 1928struct StaticAssertTypeEqHelper; 1929 1930template <typename T> 1931struct StaticAssertTypeEqHelper<T, T> {}; 1932 1933} // namespace internal 1934 1935// Compile-time assertion for type equality. 1936// StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are 1937// the same type. The value it returns is not interesting. 1938// 1939// Instead of making StaticAssertTypeEq a class template, we make it a 1940// function template that invokes a helper class template. This 1941// prevents a user from misusing StaticAssertTypeEq<T1, T2> by 1942// defining objects of that type. 1943// 1944// CAVEAT: 1945// 1946// When used inside a method of a class template, 1947// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is 1948// instantiated. For example, given: 1949// 1950// template <typename T> class Foo { 1951// public: 1952// void Bar() { testing::StaticAssertTypeEq<int, T>(); } 1953// }; 1954// 1955// the code: 1956// 1957// void Test1() { Foo<bool> foo; } 1958// 1959// will NOT generate a compiler error, as Foo<bool>::Bar() is never 1960// actually instantiated. Instead, you need: 1961// 1962// void Test2() { Foo<bool> foo; foo.Bar(); } 1963// 1964// to cause a compiler error. 1965template <typename T1, typename T2> 1966bool StaticAssertTypeEq() { 1967 internal::StaticAssertTypeEqHelper<T1, T2>(); 1968 return true; 1969} 1970 1971// Defines a test. 1972// 1973// The first parameter is the name of the test case, and the second 1974// parameter is the name of the test within the test case. 1975// 1976// The convention is to end the test case name with "Test". For 1977// example, a test case for the Foo class can be named FooTest. 1978// 1979// The user should put his test code between braces after using this 1980// macro. Example: 1981// 1982// TEST(FooTest, InitializesCorrectly) { 1983// Foo foo; 1984// EXPECT_TRUE(foo.StatusIsOK()); 1985// } 1986 1987// Note that we call GetTestTypeId() instead of GetTypeId< 1988// ::testing::Test>() here to get the type ID of testing::Test. This 1989// is to work around a suspected linker bug when using Google Test as 1990// a framework on Mac OS X. The bug causes GetTypeId< 1991// ::testing::Test>() to return different values depending on whether 1992// the call is from the Google Test framework itself or from user test 1993// code. GetTestTypeId() is guaranteed to always return the same 1994// value, as it always calls GetTypeId<>() from the Google Test 1995// framework. 1996#define TEST(test_case_name, test_name)\ 1997 GTEST_TEST_(test_case_name, test_name, \ 1998 ::testing::Test, ::testing::internal::GetTestTypeId()) 1999 2000 2001// Defines a test that uses a test fixture. 2002// 2003// The first parameter is the name of the test fixture class, which 2004// also doubles as the test case name. The second parameter is the 2005// name of the test within the test case. 2006// 2007// A test fixture class must be declared earlier. The user should put 2008// his test code between braces after using this macro. Example: 2009// 2010// class FooTest : public testing::Test { 2011// protected: 2012// virtual void SetUp() { b_.AddElement(3); } 2013// 2014// Foo a_; 2015// Foo b_; 2016// }; 2017// 2018// TEST_F(FooTest, InitializesCorrectly) { 2019// EXPECT_TRUE(a_.StatusIsOK()); 2020// } 2021// 2022// TEST_F(FooTest, ReturnsElementCountCorrectly) { 2023// EXPECT_EQ(0, a_.size()); 2024// EXPECT_EQ(1, b_.size()); 2025// } 2026 2027#define TEST_F(test_fixture, test_name)\ 2028 GTEST_TEST_(test_fixture, test_name, test_fixture, \ 2029 ::testing::internal::GetTypeId<test_fixture>()) 2030 2031// Use this macro in main() to run all tests. It returns 0 if all 2032// tests are successful, or 1 otherwise. 2033// 2034// RUN_ALL_TESTS() should be invoked after the command line has been 2035// parsed by InitGoogleTest(). 2036 2037#define RUN_ALL_TESTS()\ 2038 (::testing::UnitTest::GetInstance()->Run()) 2039 2040} // namespace testing 2041 2042#endif // GTEST_INCLUDE_GTEST_GTEST_H_ 2043