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