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