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