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