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