00001 // Copyright 2005, Google Inc. 00002 // All rights reserved. 00003 // 00004 // Redistribution and use in source and binary forms, with or without 00005 // modification, are permitted provided that the following conditions are 00006 // met: 00007 // 00008 // * Redistributions of source code must retain the above copyright 00009 // notice, this list of conditions and the following disclaimer. 00010 // * Redistributions in binary form must reproduce the above 00011 // copyright notice, this list of conditions and the following disclaimer 00012 // in the documentation and/or other materials provided with the 00013 // distribution. 00014 // * Neither the name of Google Inc. nor the names of its 00015 // contributors may be used to endorse or promote products derived from 00016 // this software without specific prior written permission. 00017 // 00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 00029 // 00030 // Author: wan@google.com (Zhanyong Wan) 00031 // 00032 // The Google C++ Testing Framework (Google Test) 00033 // 00034 // This header file defines the public API for Google Test. It should be 00035 // included by any test program that uses Google Test. 00036 // 00037 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to 00038 // leave some internal implementation details in this header file. 00039 // They are clearly marked by comments like this: 00040 // 00041 // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 00042 // 00043 // Such code is NOT meant to be used by a user directly, and is subject 00044 // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user 00045 // program! 00046 // 00047 // Acknowledgment: Google Test borrowed the idea of automatic test 00048 // registration from Barthelemy Dagenais' (barthelemy@prologique.com) 00049 // easyUnit framework. 00050 00051 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ 00052 #define GTEST_INCLUDE_GTEST_GTEST_H_ 00053 00054 #include <limits> 00055 #include <ostream> 00056 #include <vector> 00057 00058 #include "gtest/internal/gtest-internal.h" 00059 #include "gtest/internal/gtest-string.h" 00060 #include "gtest/gtest-death-test.h" 00061 #include "gtest/gtest-message.h" 00062 #include "gtest/gtest-param-test.h" 00063 #include "gtest/gtest-printers.h" 00064 #include "gtest/gtest_prod.h" 00065 #include "gtest/gtest-test-part.h" 00066 #include "gtest/gtest-typed-test.h" 00067 00068 // Depending on the platform, different string classes are available. 00069 // On Linux, in addition to ::std::string, Google also makes use of 00070 // class ::string, which has the same interface as ::std::string, but 00071 // has a different implementation. 00072 // 00073 // You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that 00074 // ::string is available AND is a distinct type to ::std::string, or 00075 // define it to 0 to indicate otherwise. 00076 // 00077 // If ::std::string and ::string are the same class on your platform 00078 // due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0. 00079 // 00080 // If you do not define GTEST_HAS_GLOBAL_STRING, it is defined 00081 // heuristically. 00082 00083 namespace testing { 00084 00085 // Declares the flags. 00086 00087 // This flag temporary enables the disabled tests. 00088 GTEST_DECLARE_bool_(also_run_disabled_tests); 00089 00090 // This flag brings the debugger on an assertion failure. 00091 GTEST_DECLARE_bool_(break_on_failure); 00092 00093 // This flag controls whether Google Test catches all test-thrown exceptions 00094 // and logs them as failures. 00095 GTEST_DECLARE_bool_(catch_exceptions); 00096 00097 // This flag enables using colors in terminal output. Available values are 00098 // "yes" to enable colors, "no" (disable colors), or "auto" (the default) 00099 // to let Google Test decide. 00100 GTEST_DECLARE_string_(color); 00101 00102 // This flag sets up the filter to select by name using a glob pattern 00103 // the tests to run. If the filter is not given all tests are executed. 00104 GTEST_DECLARE_string_(filter); 00105 00106 // This flag causes the Google Test to list tests. None of the tests listed 00107 // are actually run if the flag is provided. 00108 GTEST_DECLARE_bool_(list_tests); 00109 00110 // This flag controls whether Google Test emits a detailed XML report to a file 00111 // in addition to its normal textual output. 00112 GTEST_DECLARE_string_(output); 00113 00114 // This flags control whether Google Test prints the elapsed time for each 00115 // test. 00116 GTEST_DECLARE_bool_(print_time); 00117 00118 // This flag specifies the random number seed. 00119 GTEST_DECLARE_int32_(random_seed); 00120 00121 // This flag sets how many times the tests are repeated. The default value 00122 // is 1. If the value is -1 the tests are repeating forever. 00123 GTEST_DECLARE_int32_(repeat); 00124 00125 // This flag controls whether Google Test includes Google Test internal 00126 // stack frames in failure stack traces. 00127 GTEST_DECLARE_bool_(show_internal_stack_frames); 00128 00129 // When this flag is specified, tests' order is randomized on every iteration. 00130 GTEST_DECLARE_bool_(shuffle); 00131 00132 // This flag specifies the maximum number of stack frames to be 00133 // printed in a failure message. 00134 GTEST_DECLARE_int32_(stack_trace_depth); 00135 00136 // When this flag is specified, a failed assertion will throw an 00137 // exception if exceptions are enabled, or exit the program with a 00138 // non-zero code otherwise. 00139 GTEST_DECLARE_bool_(throw_on_failure); 00140 00141 // When this flag is set with a "host:port" string, on supported 00142 // platforms test results are streamed to the specified port on 00143 // the specified host machine. 00144 GTEST_DECLARE_string_(stream_result_to); 00145 00146 // The upper limit for valid stack trace depths. 00147 const int kMaxStackTraceDepth = 100; 00148 00149 namespace internal { 00150 00151 class AssertHelper; 00152 class DefaultGlobalTestPartResultReporter; 00153 class ExecDeathTest; 00154 class NoExecDeathTest; 00155 class FinalSuccessChecker; 00156 class GTestFlagSaver; 00157 class StreamingListenerTest; 00158 class TestResultAccessor; 00159 class TestEventListenersAccessor; 00160 class TestEventRepeater; 00161 class UnitTestRecordPropertyTestHelper; 00162 class WindowsDeathTest; 00163 class UnitTestImpl* GetUnitTestImpl(); 00164 void ReportFailureInUnknownLocation(TestPartResult::Type result_type, 00165 const std::string& message); 00166 00167 } // namespace internal 00168 00169 // The friend relationship of some of these classes is cyclic. 00170 // If we don't forward declare them the compiler might confuse the classes 00171 // in friendship clauses with same named classes on the scope. 00172 class Test; 00173 class TestCase; 00174 class TestInfo; 00175 class UnitTest; 00176 00177 // A class for indicating whether an assertion was successful. When 00178 // the assertion wasn't successful, the AssertionResult object 00179 // remembers a non-empty message that describes how it failed. 00180 // 00181 // To create an instance of this class, use one of the factory functions 00182 // (AssertionSuccess() and AssertionFailure()). 00183 // 00184 // This class is useful for two purposes: 00185 // 1. Defining predicate functions to be used with Boolean test assertions 00186 // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts 00187 // 2. Defining predicate-format functions to be 00188 // used with predicate assertions (ASSERT_PRED_FORMAT*, etc). 00189 // 00190 // For example, if you define IsEven predicate: 00191 // 00192 // testing::AssertionResult IsEven(int n) { 00193 // if ((n % 2) == 0) 00194 // return testing::AssertionSuccess(); 00195 // else 00196 // return testing::AssertionFailure() << n << " is odd"; 00197 // } 00198 // 00199 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) 00200 // will print the message 00201 // 00202 // Value of: IsEven(Fib(5)) 00203 // Actual: false (5 is odd) 00204 // Expected: true 00205 // 00206 // instead of a more opaque 00207 // 00208 // Value of: IsEven(Fib(5)) 00209 // Actual: false 00210 // Expected: true 00211 // 00212 // in case IsEven is a simple Boolean predicate. 00213 // 00214 // If you expect your predicate to be reused and want to support informative 00215 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up 00216 // about half as often as positive ones in our tests), supply messages for 00217 // both success and failure cases: 00218 // 00219 // testing::AssertionResult IsEven(int n) { 00220 // if ((n % 2) == 0) 00221 // return testing::AssertionSuccess() << n << " is even"; 00222 // else 00223 // return testing::AssertionFailure() << n << " is odd"; 00224 // } 00225 // 00226 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print 00227 // 00228 // Value of: IsEven(Fib(6)) 00229 // Actual: true (8 is even) 00230 // Expected: false 00231 // 00232 // NB: Predicates that support negative Boolean assertions have reduced 00233 // performance in positive ones so be careful not to use them in tests 00234 // that have lots (tens of thousands) of positive Boolean assertions. 00235 // 00236 // To use this class with EXPECT_PRED_FORMAT assertions such as: 00237 // 00238 // // Verifies that Foo() returns an even number. 00239 // EXPECT_PRED_FORMAT1(IsEven, Foo()); 00240 // 00241 // you need to define: 00242 // 00243 // testing::AssertionResult IsEven(const char* expr, int n) { 00244 // if ((n % 2) == 0) 00245 // return testing::AssertionSuccess(); 00246 // else 00247 // return testing::AssertionFailure() 00248 // << "Expected: " << expr << " is even\n Actual: it's " << n; 00249 // } 00250 // 00251 // If Foo() returns 5, you will see the following message: 00252 // 00253 // Expected: Foo() is even 00254 // Actual: it's 5 00255 // 00256 class GTEST_API_ AssertionResult { 00257 public: 00258 // Copy constructor. 00259 // Used in EXPECT_TRUE/FALSE(assertion_result). 00260 AssertionResult(const AssertionResult& other); 00261 00262 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) 00263 00264 // Used in the EXPECT_TRUE/FALSE(bool_expression). 00265 // 00266 // T must be contextually convertible to bool. 00267 // 00268 // The second parameter prevents this overload from being considered if 00269 // the argument is implicitly convertible to AssertionResult. In that case 00270 // we want AssertionResult's copy constructor to be used. 00271 template <typename T> 00272 explicit AssertionResult( 00273 const T& success, 00274 typename internal::EnableIf< 00275 !internal::ImplicitlyConvertible<T, AssertionResult>::value>::type* 00276 /*enabler*/ = NULL) 00277 : success_(success) {} 00278 00279 GTEST_DISABLE_MSC_WARNINGS_POP_() 00280 00281 // Assignment operator. 00282 AssertionResult& operator=(AssertionResult other) { 00283 swap(other); 00284 return *this; 00285 } 00286 00287 // Returns true iff the assertion succeeded. 00288 operator bool() const { return success_; } // NOLINT 00289 00290 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. 00291 AssertionResult operator!() const; 00292 00293 // Returns the text streamed into this AssertionResult. Test assertions 00294 // use it when they fail (i.e., the predicate's outcome doesn't match the 00295 // assertion's expectation). When nothing has been streamed into the 00296 // object, returns an empty string. 00297 const char* message() const { 00298 return message_.get() != NULL ? message_->c_str() : ""; 00299 } 00300 // TODO(vladl@google.com): Remove this after making sure no clients use it. 00301 // Deprecated; please use message() instead. 00302 const char* failure_message() const { return message(); } 00303 00304 // Streams a custom failure message into this object. 00305 template <typename T> AssertionResult& operator<<(const T& value) { 00306 AppendMessage(Message() << value); 00307 return *this; 00308 } 00309 00310 // Allows streaming basic output manipulators such as endl or flush into 00311 // this object. 00312 AssertionResult& operator<<( 00313 ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { 00314 AppendMessage(Message() << basic_manipulator); 00315 return *this; 00316 } 00317 00318 private: 00319 // Appends the contents of message to message_. 00320 void AppendMessage(const Message& a_message) { 00321 if (message_.get() == NULL) 00322 message_.reset(new ::std::string); 00323 message_->append(a_message.GetString().c_str()); 00324 } 00325 00326 // Swap the contents of this AssertionResult with other. 00327 void swap(AssertionResult& other); 00328 00329 // Stores result of the assertion predicate. 00330 bool success_; 00331 // Stores the message describing the condition in case the expectation 00332 // construct is not satisfied with the predicate's outcome. 00333 // Referenced via a pointer to avoid taking too much stack frame space 00334 // with test assertions. 00335 internal::scoped_ptr< ::std::string> message_; 00336 }; 00337 00338 // Makes a successful assertion result. 00339 GTEST_API_ AssertionResult AssertionSuccess(); 00340 00341 // Makes a failed assertion result. 00342 GTEST_API_ AssertionResult AssertionFailure(); 00343 00344 // Makes a failed assertion result with the given failure message. 00345 // Deprecated; use AssertionFailure() << msg. 00346 GTEST_API_ AssertionResult AssertionFailure(const Message& msg); 00347 00348 // The abstract class that all tests inherit from. 00349 // 00350 // In Google Test, a unit test program contains one or many TestCases, and 00351 // each TestCase contains one or many Tests. 00352 // 00353 // When you define a test using the TEST macro, you don't need to 00354 // explicitly derive from Test - the TEST macro automatically does 00355 // this for you. 00356 // 00357 // The only time you derive from Test is when defining a test fixture 00358 // to be used a TEST_F. For example: 00359 // 00360 // class FooTest : public testing::Test { 00361 // protected: 00362 // void SetUp() override { ... } 00363 // void TearDown() override { ... } 00364 // ... 00365 // }; 00366 // 00367 // TEST_F(FooTest, Bar) { ... } 00368 // TEST_F(FooTest, Baz) { ... } 00369 // 00370 // Test is not copyable. 00371 class GTEST_API_ Test { 00372 public: 00373 friend class TestInfo; 00374 00375 // Defines types for pointers to functions that set up and tear down 00376 // a test case. 00377 typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; 00378 typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; 00379 00380 // The d'tor is virtual as we intend to inherit from Test. 00381 virtual ~Test(); 00382 00383 // Sets up the stuff shared by all tests in this test case. 00384 // 00385 // Google Test will call Foo::SetUpTestCase() before running the first 00386 // test in test case Foo. Hence a sub-class can define its own 00387 // SetUpTestCase() method to shadow the one defined in the super 00388 // class. 00389 static void SetUpTestCase() {} 00390 00391 // Tears down the stuff shared by all tests in this test case. 00392 // 00393 // Google Test will call Foo::TearDownTestCase() after running the last 00394 // test in test case Foo. Hence a sub-class can define its own 00395 // TearDownTestCase() method to shadow the one defined in the super 00396 // class. 00397 static void TearDownTestCase() {} 00398 00399 // Returns true iff the current test has a fatal failure. 00400 static bool HasFatalFailure(); 00401 00402 // Returns true iff the current test has a non-fatal failure. 00403 static bool HasNonfatalFailure(); 00404 00405 // Returns true iff the current test has a (either fatal or 00406 // non-fatal) failure. 00407 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } 00408 00409 // Logs a property for the current test, test case, or for the entire 00410 // invocation of the test program when used outside of the context of a 00411 // test case. Only the last value for a given key is remembered. These 00412 // are public static so they can be called from utility functions that are 00413 // not members of the test fixture. Calls to RecordProperty made during 00414 // lifespan of the test (from the moment its constructor starts to the 00415 // moment its destructor finishes) will be output in XML as attributes of 00416 // the <testcase> element. Properties recorded from fixture's 00417 // SetUpTestCase or TearDownTestCase are logged as attributes of the 00418 // corresponding <testsuite> element. Calls to RecordProperty made in the 00419 // global context (before or after invocation of RUN_ALL_TESTS and from 00420 // SetUp/TearDown method of Environment objects registered with Google 00421 // Test) will be output as attributes of the <testsuites> element. 00422 static void RecordProperty(const std::string& key, const std::string& value); 00423 static void RecordProperty(const std::string& key, int value); 00424 00425 protected: 00426 // Creates a Test object. 00427 Test(); 00428 00429 // Sets up the test fixture. 00430 virtual void SetUp(); 00431 00432 // Tears down the test fixture. 00433 virtual void TearDown(); 00434 00435 private: 00436 // Returns true iff the current test has the same fixture class as 00437 // the first test in the current test case. 00438 static bool HasSameFixtureClass(); 00439 00440 // Runs the test after the test fixture has been set up. 00441 // 00442 // A sub-class must implement this to define the test logic. 00443 // 00444 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. 00445 // Instead, use the TEST or TEST_F macro. 00446 virtual void TestBody() = 0; 00447 00448 // Sets up, executes, and tears down the test. 00449 void Run(); 00450 00451 // Deletes self. We deliberately pick an unusual name for this 00452 // internal method to avoid clashing with names used in user TESTs. 00453 void DeleteSelf_() { delete this; } 00454 00455 const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_; 00456 00457 // Often a user misspells SetUp() as Setup() and spends a long time 00458 // wondering why it is never called by Google Test. The declaration of 00459 // the following method is solely for catching such an error at 00460 // compile time: 00461 // 00462 // - The return type is deliberately chosen to be not void, so it 00463 // will be a conflict if void Setup() is declared in the user's 00464 // test fixture. 00465 // 00466 // - This method is private, so it will be another compiler error 00467 // if the method is called from the user's test fixture. 00468 // 00469 // DO NOT OVERRIDE THIS FUNCTION. 00470 // 00471 // If you see an error about overriding the following function or 00472 // about it being private, you have mis-spelled SetUp() as Setup(). 00473 struct Setup_should_be_spelled_SetUp {}; 00474 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } 00475 00476 // We disallow copying Tests. 00477 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); 00478 }; 00479 00480 typedef internal::TimeInMillis TimeInMillis; 00481 00482 // A copyable object representing a user specified test property which can be 00483 // output as a key/value string pair. 00484 // 00485 // Don't inherit from TestProperty as its destructor is not virtual. 00486 class TestProperty { 00487 public: 00488 // C'tor. TestProperty does NOT have a default constructor. 00489 // Always use this constructor (with parameters) to create a 00490 // TestProperty object. 00491 TestProperty(const std::string& a_key, const std::string& a_value) : 00492 key_(a_key), value_(a_value) { 00493 } 00494 00495 // Gets the user supplied key. 00496 const char* key() const { 00497 return key_.c_str(); 00498 } 00499 00500 // Gets the user supplied value. 00501 const char* value() const { 00502 return value_.c_str(); 00503 } 00504 00505 // Sets a new value, overriding the one supplied in the constructor. 00506 void SetValue(const std::string& new_value) { 00507 value_ = new_value; 00508 } 00509 00510 private: 00511 // The key supplied by the user. 00512 std::string key_; 00513 // The value supplied by the user. 00514 std::string value_; 00515 }; 00516 00517 // The result of a single Test. This includes a list of 00518 // TestPartResults, a list of TestProperties, a count of how many 00519 // death tests there are in the Test, and how much time it took to run 00520 // the Test. 00521 // 00522 // TestResult is not copyable. 00523 class GTEST_API_ TestResult { 00524 public: 00525 // Creates an empty TestResult. 00526 TestResult(); 00527 00528 // D'tor. Do not inherit from TestResult. 00529 ~TestResult(); 00530 00531 // Gets the number of all test parts. This is the sum of the number 00532 // of successful test parts and the number of failed test parts. 00533 int total_part_count() const; 00534 00535 // Returns the number of the test properties. 00536 int test_property_count() const; 00537 00538 // Returns true iff the test passed (i.e. no test part failed). 00539 bool Passed() const { return !Failed(); } 00540 00541 // Returns true iff the test failed. 00542 bool Failed() const; 00543 00544 // Returns true iff the test fatally failed. 00545 bool HasFatalFailure() const; 00546 00547 // Returns true iff the test has a non-fatal failure. 00548 bool HasNonfatalFailure() const; 00549 00550 // Returns the elapsed time, in milliseconds. 00551 TimeInMillis elapsed_time() const { return elapsed_time_; } 00552 00553 // Returns the i-th test part result among all the results. i can range 00554 // from 0 to test_property_count() - 1. If i is not in that range, aborts 00555 // the program. 00556 const TestPartResult& GetTestPartResult(int i) const; 00557 00558 // Returns the i-th test property. i can range from 0 to 00559 // test_property_count() - 1. If i is not in that range, aborts the 00560 // program. 00561 const TestProperty& GetTestProperty(int i) const; 00562 00563 private: 00564 friend class TestInfo; 00565 friend class TestCase; 00566 friend class UnitTest; 00567 friend class internal::DefaultGlobalTestPartResultReporter; 00568 friend class internal::ExecDeathTest; 00569 friend class internal::TestResultAccessor; 00570 friend class internal::UnitTestImpl; 00571 friend class internal::WindowsDeathTest; 00572 00573 // Gets the vector of TestPartResults. 00574 const std::vector<TestPartResult>& test_part_results() const { 00575 return test_part_results_; 00576 } 00577 00578 // Gets the vector of TestProperties. 00579 const std::vector<TestProperty>& test_properties() const { 00580 return test_properties_; 00581 } 00582 00583 // Sets the elapsed time. 00584 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } 00585 00586 // Adds a test property to the list. The property is validated and may add 00587 // a non-fatal failure if invalid (e.g., if it conflicts with reserved 00588 // key names). If a property is already recorded for the same key, the 00589 // value will be updated, rather than storing multiple values for the same 00590 // key. xml_element specifies the element for which the property is being 00591 // recorded and is used for validation. 00592 void RecordProperty(const std::string& xml_element, 00593 const TestProperty& test_property); 00594 00595 // Adds a failure if the key is a reserved attribute of Google Test 00596 // testcase tags. Returns true if the property is valid. 00597 // TODO(russr): Validate attribute names are legal and human readable. 00598 static bool ValidateTestProperty(const std::string& xml_element, 00599 const TestProperty& test_property); 00600 00601 // Adds a test part result to the list. 00602 void AddTestPartResult(const TestPartResult& test_part_result); 00603 00604 // Returns the death test count. 00605 int death_test_count() const { return death_test_count_; } 00606 00607 // Increments the death test count, returning the new count. 00608 int increment_death_test_count() { return ++death_test_count_; } 00609 00610 // Clears the test part results. 00611 void ClearTestPartResults(); 00612 00613 // Clears the object. 00614 void Clear(); 00615 00616 // Protects mutable state of the property vector and of owned 00617 // properties, whose values may be updated. 00618 internal::Mutex test_properites_mutex_; 00619 00620 // The vector of TestPartResults 00621 std::vector<TestPartResult> test_part_results_; 00622 // The vector of TestProperties 00623 std::vector<TestProperty> test_properties_; 00624 // Running count of death tests. 00625 int death_test_count_; 00626 // The elapsed time, in milliseconds. 00627 TimeInMillis elapsed_time_; 00628 00629 // We disallow copying TestResult. 00630 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); 00631 }; // class TestResult 00632 00633 // A TestInfo object stores the following information about a test: 00634 // 00635 // Test case name 00636 // Test name 00637 // Whether the test should be run 00638 // A function pointer that creates the test object when invoked 00639 // Test result 00640 // 00641 // The constructor of TestInfo registers itself with the UnitTest 00642 // singleton such that the RUN_ALL_TESTS() macro knows which tests to 00643 // run. 00644 class GTEST_API_ TestInfo { 00645 public: 00646 // Destructs a TestInfo object. This function is not virtual, so 00647 // don't inherit from TestInfo. 00648 ~TestInfo(); 00649 00650 // Returns the test case name. 00651 const char* test_case_name() const { return test_case_name_.c_str(); } 00652 00653 // Returns the test name. 00654 const char* name() const { return name_.c_str(); } 00655 00656 // Returns the name of the parameter type, or NULL if this is not a typed 00657 // or a type-parameterized test. 00658 const char* type_param() const { 00659 if (type_param_.get() != NULL) 00660 return type_param_->c_str(); 00661 return NULL; 00662 } 00663 00664 // Returns the text representation of the value parameter, or NULL if this 00665 // is not a value-parameterized test. 00666 const char* value_param() const { 00667 if (value_param_.get() != NULL) 00668 return value_param_->c_str(); 00669 return NULL; 00670 } 00671 00672 // Returns the file name where this test is defined. 00673 const char* file() const { return location_.file.c_str(); } 00674 00675 // Returns the line where this test is defined. 00676 int line() const { return location_.line; } 00677 00678 // Returns true if this test should run, that is if the test is not 00679 // disabled (or it is disabled but the also_run_disabled_tests flag has 00680 // been specified) and its full name matches the user-specified filter. 00681 // 00682 // Google Test allows the user to filter the tests by their full names. 00683 // The full name of a test Bar in test case Foo is defined as 00684 // "Foo.Bar". Only the tests that match the filter will run. 00685 // 00686 // A filter is a colon-separated list of glob (not regex) patterns, 00687 // optionally followed by a '-' and a colon-separated list of 00688 // negative patterns (tests to exclude). A test is run if it 00689 // matches one of the positive patterns and does not match any of 00690 // the negative patterns. 00691 // 00692 // For example, *A*:Foo.* is a filter that matches any string that 00693 // contains the character 'A' or starts with "Foo.". 00694 bool should_run() const { return should_run_; } 00695 00696 // Returns true iff this test will appear in the XML report. 00697 bool is_reportable() const { 00698 // For now, the XML report includes all tests matching the filter. 00699 // In the future, we may trim tests that are excluded because of 00700 // sharding. 00701 return matches_filter_; 00702 } 00703 00704 // Returns the result of the test. 00705 const TestResult* result() const { return &result_; } 00706 00707 private: 00708 #if GTEST_HAS_DEATH_TEST 00709 friend class internal::DefaultDeathTestFactory; 00710 #endif // GTEST_HAS_DEATH_TEST 00711 friend class Test; 00712 friend class TestCase; 00713 friend class internal::UnitTestImpl; 00714 friend class internal::StreamingListenerTest; 00715 friend TestInfo* internal::MakeAndRegisterTestInfo( 00716 const char* test_case_name, 00717 const char* name, 00718 const char* type_param, 00719 const char* value_param, 00720 internal::CodeLocation code_location, 00721 internal::TypeId fixture_class_id, 00722 Test::SetUpTestCaseFunc set_up_tc, 00723 Test::TearDownTestCaseFunc tear_down_tc, 00724 internal::TestFactoryBase* factory); 00725 00726 // Constructs a TestInfo object. The newly constructed instance assumes 00727 // ownership of the factory object. 00728 TestInfo(const std::string& test_case_name, 00729 const std::string& name, 00730 const char* a_type_param, // NULL if not a type-parameterized test 00731 const char* a_value_param, // NULL if not a value-parameterized test 00732 internal::CodeLocation a_code_location, 00733 internal::TypeId fixture_class_id, 00734 internal::TestFactoryBase* factory); 00735 00736 // Increments the number of death tests encountered in this test so 00737 // far. 00738 int increment_death_test_count() { 00739 return result_.increment_death_test_count(); 00740 } 00741 00742 // Creates the test object, runs it, records its result, and then 00743 // deletes it. 00744 void Run(); 00745 00746 static void ClearTestResult(TestInfo* test_info) { 00747 test_info->result_.Clear(); 00748 } 00749 00750 // These fields are immutable properties of the test. 00751 const std::string test_case_name_; // Test case name 00752 const std::string name_; // Test name 00753 // Name of the parameter type, or NULL if this is not a typed or a 00754 // type-parameterized test. 00755 const internal::scoped_ptr<const ::std::string> type_param_; 00756 // Text representation of the value parameter, or NULL if this is not a 00757 // value-parameterized test. 00758 const internal::scoped_ptr<const ::std::string> value_param_; 00759 internal::CodeLocation location_; 00760 const internal::TypeId fixture_class_id_; // ID of the test fixture class 00761 bool should_run_; // True iff this test should run 00762 bool is_disabled_; // True iff this test is disabled 00763 bool matches_filter_; // True if this test matches the 00764 // user-specified filter. 00765 internal::TestFactoryBase* const factory_; // The factory that creates 00766 // the test object 00767 00768 // This field is mutable and needs to be reset before running the 00769 // test for the second time. 00770 TestResult result_; 00771 00772 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); 00773 }; 00774 00775 // A test case, which consists of a vector of TestInfos. 00776 // 00777 // TestCase is not copyable. 00778 class GTEST_API_ TestCase { 00779 public: 00780 // Creates a TestCase with the given name. 00781 // 00782 // TestCase does NOT have a default constructor. Always use this 00783 // constructor to create a TestCase object. 00784 // 00785 // Arguments: 00786 // 00787 // name: name of the test case 00788 // a_type_param: the name of the test's type parameter, or NULL if 00789 // this is not a type-parameterized test. 00790 // set_up_tc: pointer to the function that sets up the test case 00791 // tear_down_tc: pointer to the function that tears down the test case 00792 TestCase(const char* name, const char* a_type_param, 00793 Test::SetUpTestCaseFunc set_up_tc, 00794 Test::TearDownTestCaseFunc tear_down_tc); 00795 00796 // Destructor of TestCase. 00797 virtual ~TestCase(); 00798 00799 // Gets the name of the TestCase. 00800 const char* name() const { return name_.c_str(); } 00801 00802 // Returns the name of the parameter type, or NULL if this is not a 00803 // type-parameterized test case. 00804 const char* type_param() const { 00805 if (type_param_.get() != NULL) 00806 return type_param_->c_str(); 00807 return NULL; 00808 } 00809 00810 // Returns true if any test in this test case should run. 00811 bool should_run() const { return should_run_; } 00812 00813 // Gets the number of successful tests in this test case. 00814 int successful_test_count() const; 00815 00816 // Gets the number of failed tests in this test case. 00817 int failed_test_count() const; 00818 00819 // Gets the number of disabled tests that will be reported in the XML report. 00820 int reportable_disabled_test_count() const; 00821 00822 // Gets the number of disabled tests in this test case. 00823 int disabled_test_count() const; 00824 00825 // Gets the number of tests to be printed in the XML report. 00826 int reportable_test_count() const; 00827 00828 // Get the number of tests in this test case that should run. 00829 int test_to_run_count() const; 00830 00831 // Gets the number of all tests in this test case. 00832 int total_test_count() const; 00833 00834 // Returns true iff the test case passed. 00835 bool Passed() const { return !Failed(); } 00836 00837 // Returns true iff the test case failed. 00838 bool Failed() const { return failed_test_count() > 0; } 00839 00840 // Returns the elapsed time, in milliseconds. 00841 TimeInMillis elapsed_time() const { return elapsed_time_; } 00842 00843 // Returns the i-th test among all the tests. i can range from 0 to 00844 // total_test_count() - 1. If i is not in that range, returns NULL. 00845 const TestInfo* GetTestInfo(int i) const; 00846 00847 // Returns the TestResult that holds test properties recorded during 00848 // execution of SetUpTestCase and TearDownTestCase. 00849 const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } 00850 00851 private: 00852 friend class Test; 00853 friend class internal::UnitTestImpl; 00854 00855 // Gets the (mutable) vector of TestInfos in this TestCase. 00856 std::vector<TestInfo*>& test_info_list() { return test_info_list_; } 00857 00858 // Gets the (immutable) vector of TestInfos in this TestCase. 00859 const std::vector<TestInfo*>& test_info_list() const { 00860 return test_info_list_; 00861 } 00862 00863 // Returns the i-th test among all the tests. i can range from 0 to 00864 // total_test_count() - 1. If i is not in that range, returns NULL. 00865 TestInfo* GetMutableTestInfo(int i); 00866 00867 // Sets the should_run member. 00868 void set_should_run(bool should) { should_run_ = should; } 00869 00870 // Adds a TestInfo to this test case. Will delete the TestInfo upon 00871 // destruction of the TestCase object. 00872 void AddTestInfo(TestInfo * test_info); 00873 00874 // Clears the results of all tests in this test case. 00875 void ClearResult(); 00876 00877 // Clears the results of all tests in the given test case. 00878 static void ClearTestCaseResult(TestCase* test_case) { 00879 test_case->ClearResult(); 00880 } 00881 00882 // Runs every test in this TestCase. 00883 void Run(); 00884 00885 // Runs SetUpTestCase() for this TestCase. This wrapper is needed 00886 // for catching exceptions thrown from SetUpTestCase(). 00887 void RunSetUpTestCase() { (*set_up_tc_)(); } 00888 00889 // Runs TearDownTestCase() for this TestCase. This wrapper is 00890 // needed for catching exceptions thrown from TearDownTestCase(). 00891 void RunTearDownTestCase() { (*tear_down_tc_)(); } 00892 00893 // Returns true iff test passed. 00894 static bool TestPassed(const TestInfo* test_info) { 00895 return test_info->should_run() && test_info->result()->Passed(); 00896 } 00897 00898 // Returns true iff test failed. 00899 static bool TestFailed(const TestInfo* test_info) { 00900 return test_info->should_run() && test_info->result()->Failed(); 00901 } 00902 00903 // Returns true iff the test is disabled and will be reported in the XML 00904 // report. 00905 static bool TestReportableDisabled(const TestInfo* test_info) { 00906 return test_info->is_reportable() && test_info->is_disabled_; 00907 } 00908 00909 // Returns true iff test is disabled. 00910 static bool TestDisabled(const TestInfo* test_info) { 00911 return test_info->is_disabled_; 00912 } 00913 00914 // Returns true iff this test will appear in the XML report. 00915 static bool TestReportable(const TestInfo* test_info) { 00916 return test_info->is_reportable(); 00917 } 00918 00919 // Returns true if the given test should run. 00920 static bool ShouldRunTest(const TestInfo* test_info) { 00921 return test_info->should_run(); 00922 } 00923 00924 // Shuffles the tests in this test case. 00925 void ShuffleTests(internal::Random* random); 00926 00927 // Restores the test order to before the first shuffle. 00928 void UnshuffleTests(); 00929 00930 // Name of the test case. 00931 std::string name_; 00932 // Name of the parameter type, or NULL if this is not a typed or a 00933 // type-parameterized test. 00934 const internal::scoped_ptr<const ::std::string> type_param_; 00935 // The vector of TestInfos in their original order. It owns the 00936 // elements in the vector. 00937 std::vector<TestInfo*> test_info_list_; 00938 // Provides a level of indirection for the test list to allow easy 00939 // shuffling and restoring the test order. The i-th element in this 00940 // vector is the index of the i-th test in the shuffled test list. 00941 std::vector<int> test_indices_; 00942 // Pointer to the function that sets up the test case. 00943 Test::SetUpTestCaseFunc set_up_tc_; 00944 // Pointer to the function that tears down the test case. 00945 Test::TearDownTestCaseFunc tear_down_tc_; 00946 // True iff any test in this test case should run. 00947 bool should_run_; 00948 // Elapsed time, in milliseconds. 00949 TimeInMillis elapsed_time_; 00950 // Holds test properties recorded during execution of SetUpTestCase and 00951 // TearDownTestCase. 00952 TestResult ad_hoc_test_result_; 00953 00954 // We disallow copying TestCases. 00955 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); 00956 }; 00957 00958 // An Environment object is capable of setting up and tearing down an 00959 // environment. You should subclass this to define your own 00960 // environment(s). 00961 // 00962 // An Environment object does the set-up and tear-down in virtual 00963 // methods SetUp() and TearDown() instead of the constructor and the 00964 // destructor, as: 00965 // 00966 // 1. You cannot safely throw from a destructor. This is a problem 00967 // as in some cases Google Test is used where exceptions are enabled, and 00968 // we may want to implement ASSERT_* using exceptions where they are 00969 // available. 00970 // 2. You cannot use ASSERT_* directly in a constructor or 00971 // destructor. 00972 class Environment { 00973 public: 00974 // The d'tor is virtual as we need to subclass Environment. 00975 virtual ~Environment() {} 00976 00977 // Override this to define how to set up the environment. 00978 virtual void SetUp() {} 00979 00980 // Override this to define how to tear down the environment. 00981 virtual void TearDown() {} 00982 private: 00983 // If you see an error about overriding the following function or 00984 // about it being private, you have mis-spelled SetUp() as Setup(). 00985 struct Setup_should_be_spelled_SetUp {}; 00986 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } 00987 }; 00988 00989 // The interface for tracing execution of tests. The methods are organized in 00990 // the order the corresponding events are fired. 00991 class TestEventListener { 00992 public: 00993 virtual ~TestEventListener() {} 00994 00995 // Fired before any test activity starts. 00996 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; 00997 00998 // Fired before each iteration of tests starts. There may be more than 00999 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration 01000 // index, starting from 0. 01001 virtual void OnTestIterationStart(const UnitTest& unit_test, 01002 int iteration) = 0; 01003 01004 // Fired before environment set-up for each iteration of tests starts. 01005 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; 01006 01007 // Fired after environment set-up for each iteration of tests ends. 01008 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; 01009 01010 // Fired before the test case starts. 01011 virtual void OnTestCaseStart(const TestCase& test_case) = 0; 01012 01013 // Fired before the test starts. 01014 virtual void OnTestStart(const TestInfo& test_info) = 0; 01015 01016 // Fired after a failed assertion or a SUCCEED() invocation. 01017 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; 01018 01019 // Fired after the test ends. 01020 virtual void OnTestEnd(const TestInfo& test_info) = 0; 01021 01022 // Fired after the test case ends. 01023 virtual void OnTestCaseEnd(const TestCase& test_case) = 0; 01024 01025 // Fired before environment tear-down for each iteration of tests starts. 01026 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; 01027 01028 // Fired after environment tear-down for each iteration of tests ends. 01029 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; 01030 01031 // Fired after each iteration of tests finishes. 01032 virtual void OnTestIterationEnd(const UnitTest& unit_test, 01033 int iteration) = 0; 01034 01035 // Fired after all test activities have ended. 01036 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; 01037 }; 01038 01039 // The convenience class for users who need to override just one or two 01040 // methods and are not concerned that a possible change to a signature of 01041 // the methods they override will not be caught during the build. For 01042 // comments about each method please see the definition of TestEventListener 01043 // above. 01044 class EmptyTestEventListener : public TestEventListener { 01045 public: 01046 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} 01047 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, 01048 int /*iteration*/) {} 01049 virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} 01050 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} 01051 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} 01052 virtual void OnTestStart(const TestInfo& /*test_info*/) {} 01053 virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} 01054 virtual void OnTestEnd(const TestInfo& /*test_info*/) {} 01055 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} 01056 virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} 01057 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} 01058 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, 01059 int /*iteration*/) {} 01060 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} 01061 }; 01062 01063 // TestEventListeners lets users add listeners to track events in Google Test. 01064 class GTEST_API_ TestEventListeners { 01065 public: 01066 TestEventListeners(); 01067 ~TestEventListeners(); 01068 01069 // Appends an event listener to the end of the list. Google Test assumes 01070 // the ownership of the listener (i.e. it will delete the listener when 01071 // the test program finishes). 01072 void Append(TestEventListener* listener); 01073 01074 // Removes the given event listener from the list and returns it. It then 01075 // becomes the caller's responsibility to delete the listener. Returns 01076 // NULL if the listener is not found in the list. 01077 TestEventListener* Release(TestEventListener* listener); 01078 01079 // Returns the standard listener responsible for the default console 01080 // output. Can be removed from the listeners list to shut down default 01081 // console output. Note that removing this object from the listener list 01082 // with Release transfers its ownership to the caller and makes this 01083 // function return NULL the next time. 01084 TestEventListener* default_result_printer() const { 01085 return default_result_printer_; 01086 } 01087 01088 // Returns the standard listener responsible for the default XML output 01089 // controlled by the --gtest_output=xml flag. Can be removed from the 01090 // listeners list by users who want to shut down the default XML output 01091 // controlled by this flag and substitute it with custom one. Note that 01092 // removing this object from the listener list with Release transfers its 01093 // ownership to the caller and makes this function return NULL the next 01094 // time. 01095 TestEventListener* default_xml_generator() const { 01096 return default_xml_generator_; 01097 } 01098 01099 private: 01100 friend class TestCase; 01101 friend class TestInfo; 01102 friend class internal::DefaultGlobalTestPartResultReporter; 01103 friend class internal::NoExecDeathTest; 01104 friend class internal::TestEventListenersAccessor; 01105 friend class internal::UnitTestImpl; 01106 01107 // Returns repeater that broadcasts the TestEventListener events to all 01108 // subscribers. 01109 TestEventListener* repeater(); 01110 01111 // Sets the default_result_printer attribute to the provided listener. 01112 // The listener is also added to the listener list and previous 01113 // default_result_printer is removed from it and deleted. The listener can 01114 // also be NULL in which case it will not be added to the list. Does 01115 // nothing if the previous and the current listener objects are the same. 01116 void SetDefaultResultPrinter(TestEventListener* listener); 01117 01118 // Sets the default_xml_generator attribute to the provided listener. The 01119 // listener is also added to the listener list and previous 01120 // default_xml_generator is removed from it and deleted. The listener can 01121 // also be NULL in which case it will not be added to the list. Does 01122 // nothing if the previous and the current listener objects are the same. 01123 void SetDefaultXmlGenerator(TestEventListener* listener); 01124 01125 // Controls whether events will be forwarded by the repeater to the 01126 // listeners in the list. 01127 bool EventForwardingEnabled() const; 01128 void SuppressEventForwarding(); 01129 01130 // The actual list of listeners. 01131 internal::TestEventRepeater* repeater_; 01132 // Listener responsible for the standard result output. 01133 TestEventListener* default_result_printer_; 01134 // Listener responsible for the creation of the XML output file. 01135 TestEventListener* default_xml_generator_; 01136 01137 // We disallow copying TestEventListeners. 01138 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); 01139 }; 01140 01141 // A UnitTest consists of a vector of TestCases. 01142 // 01143 // This is a singleton class. The only instance of UnitTest is 01144 // created when UnitTest::GetInstance() is first called. This 01145 // instance is never deleted. 01146 // 01147 // UnitTest is not copyable. 01148 // 01149 // This class is thread-safe as long as the methods are called 01150 // according to their specification. 01151 class GTEST_API_ UnitTest { 01152 public: 01153 // Gets the singleton UnitTest object. The first time this method 01154 // is called, a UnitTest object is constructed and returned. 01155 // Consecutive calls will return the same object. 01156 static UnitTest* GetInstance(); 01157 01158 // Runs all tests in this UnitTest object and prints the result. 01159 // Returns 0 if successful, or 1 otherwise. 01160 // 01161 // This method can only be called from the main thread. 01162 // 01163 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01164 int Run() GTEST_MUST_USE_RESULT_; 01165 01166 // Returns the working directory when the first TEST() or TEST_F() 01167 // was executed. The UnitTest object owns the string. 01168 const char* original_working_dir() const; 01169 01170 // Returns the TestCase object for the test that's currently running, 01171 // or NULL if no test is running. 01172 const TestCase* current_test_case() const 01173 GTEST_LOCK_EXCLUDED_(mutex_); 01174 01175 // Returns the TestInfo object for the test that's currently running, 01176 // or NULL if no test is running. 01177 const TestInfo* current_test_info() const 01178 GTEST_LOCK_EXCLUDED_(mutex_); 01179 01180 // Returns the random seed used at the start of the current test run. 01181 int random_seed() const; 01182 01183 #if GTEST_HAS_PARAM_TEST 01184 // Returns the ParameterizedTestCaseRegistry object used to keep track of 01185 // value-parameterized tests and instantiate and register them. 01186 // 01187 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01188 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() 01189 GTEST_LOCK_EXCLUDED_(mutex_); 01190 #endif // GTEST_HAS_PARAM_TEST 01191 01192 // Gets the number of successful test cases. 01193 int successful_test_case_count() const; 01194 01195 // Gets the number of failed test cases. 01196 int failed_test_case_count() const; 01197 01198 // Gets the number of all test cases. 01199 int total_test_case_count() const; 01200 01201 // Gets the number of all test cases that contain at least one test 01202 // that should run. 01203 int test_case_to_run_count() const; 01204 01205 // Gets the number of successful tests. 01206 int successful_test_count() const; 01207 01208 // Gets the number of failed tests. 01209 int failed_test_count() const; 01210 01211 // Gets the number of disabled tests that will be reported in the XML report. 01212 int reportable_disabled_test_count() const; 01213 01214 // Gets the number of disabled tests. 01215 int disabled_test_count() const; 01216 01217 // Gets the number of tests to be printed in the XML report. 01218 int reportable_test_count() const; 01219 01220 // Gets the number of all tests. 01221 int total_test_count() const; 01222 01223 // Gets the number of tests that should run. 01224 int test_to_run_count() const; 01225 01226 // Gets the time of the test program start, in ms from the start of the 01227 // UNIX epoch. 01228 TimeInMillis start_timestamp() const; 01229 01230 // Gets the elapsed time, in milliseconds. 01231 TimeInMillis elapsed_time() const; 01232 01233 // Returns true iff the unit test passed (i.e. all test cases passed). 01234 bool Passed() const; 01235 01236 // Returns true iff the unit test failed (i.e. some test case failed 01237 // or something outside of all tests failed). 01238 bool Failed() const; 01239 01240 // Gets the i-th test case among all the test cases. i can range from 0 to 01241 // total_test_case_count() - 1. If i is not in that range, returns NULL. 01242 const TestCase* GetTestCase(int i) const; 01243 01244 // Returns the TestResult containing information on test failures and 01245 // properties logged outside of individual test cases. 01246 const TestResult& ad_hoc_test_result() const; 01247 01248 // Returns the list of event listeners that can be used to track events 01249 // inside Google Test. 01250 TestEventListeners& listeners(); 01251 01252 private: 01253 // Registers and returns a global test environment. When a test 01254 // program is run, all global test environments will be set-up in 01255 // the order they were registered. After all tests in the program 01256 // have finished, all global test environments will be torn-down in 01257 // the *reverse* order they were registered. 01258 // 01259 // The UnitTest object takes ownership of the given environment. 01260 // 01261 // This method can only be called from the main thread. 01262 Environment* AddEnvironment(Environment* env); 01263 01264 // Adds a TestPartResult to the current TestResult object. All 01265 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) 01266 // eventually call this to report their results. The user code 01267 // should use the assertion macros instead of calling this directly. 01268 void AddTestPartResult(TestPartResult::Type result_type, 01269 const char* file_name, 01270 int line_number, 01271 const std::string& message, 01272 const std::string& os_stack_trace) 01273 GTEST_LOCK_EXCLUDED_(mutex_); 01274 01275 // Adds a TestProperty to the current TestResult object when invoked from 01276 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked 01277 // from SetUpTestCase or TearDownTestCase, or to the global property set 01278 // when invoked elsewhere. If the result already contains a property with 01279 // the same key, the value will be updated. 01280 void RecordProperty(const std::string& key, const std::string& value); 01281 01282 // Gets the i-th test case among all the test cases. i can range from 0 to 01283 // total_test_case_count() - 1. If i is not in that range, returns NULL. 01284 TestCase* GetMutableTestCase(int i); 01285 01286 // Accessors for the implementation object. 01287 internal::UnitTestImpl* impl() { return impl_; } 01288 const internal::UnitTestImpl* impl() const { return impl_; } 01289 01290 // These classes and funcions are friends as they need to access private 01291 // members of UnitTest. 01292 friend class Test; 01293 friend class internal::AssertHelper; 01294 friend class internal::ScopedTrace; 01295 friend class internal::StreamingListenerTest; 01296 friend class internal::UnitTestRecordPropertyTestHelper; 01297 friend Environment* AddGlobalTestEnvironment(Environment* env); 01298 friend internal::UnitTestImpl* internal::GetUnitTestImpl(); 01299 friend void internal::ReportFailureInUnknownLocation( 01300 TestPartResult::Type result_type, 01301 const std::string& message); 01302 01303 // Creates an empty UnitTest. 01304 UnitTest(); 01305 01306 // D'tor 01307 virtual ~UnitTest(); 01308 01309 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread 01310 // Google Test trace stack. 01311 void PushGTestTrace(const internal::TraceInfo& trace) 01312 GTEST_LOCK_EXCLUDED_(mutex_); 01313 01314 // Pops a trace from the per-thread Google Test trace stack. 01315 void PopGTestTrace() 01316 GTEST_LOCK_EXCLUDED_(mutex_); 01317 01318 // Protects mutable state in *impl_. This is mutable as some const 01319 // methods need to lock it too. 01320 mutable internal::Mutex mutex_; 01321 01322 // Opaque implementation object. This field is never changed once 01323 // the object is constructed. We don't mark it as const here, as 01324 // doing so will cause a warning in the constructor of UnitTest. 01325 // Mutable state in *impl_ is protected by mutex_. 01326 internal::UnitTestImpl* impl_; 01327 01328 // We disallow copying UnitTest. 01329 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); 01330 }; 01331 01332 // A convenient wrapper for adding an environment for the test 01333 // program. 01334 // 01335 // You should call this before RUN_ALL_TESTS() is called, probably in 01336 // main(). If you use gtest_main, you need to call this before main() 01337 // starts for it to take effect. For example, you can define a global 01338 // variable like this: 01339 // 01340 // testing::Environment* const foo_env = 01341 // testing::AddGlobalTestEnvironment(new FooEnvironment); 01342 // 01343 // However, we strongly recommend you to write your own main() and 01344 // call AddGlobalTestEnvironment() there, as relying on initialization 01345 // of global variables makes the code harder to read and may cause 01346 // problems when you register multiple environments from different 01347 // translation units and the environments have dependencies among them 01348 // (remember that the compiler doesn't guarantee the order in which 01349 // global variables from different translation units are initialized). 01350 inline Environment* AddGlobalTestEnvironment(Environment* env) { 01351 return UnitTest::GetInstance()->AddEnvironment(env); 01352 } 01353 01354 // Initializes Google Test. This must be called before calling 01355 // RUN_ALL_TESTS(). In particular, it parses a command line for the 01356 // flags that Google Test recognizes. Whenever a Google Test flag is 01357 // seen, it is removed from argv, and *argc is decremented. 01358 // 01359 // No value is returned. Instead, the Google Test flag variables are 01360 // updated. 01361 // 01362 // Calling the function for the second time has no user-visible effect. 01363 GTEST_API_ void InitGoogleTest(int* argc, char** argv); 01364 01365 // This overloaded version can be used in Windows programs compiled in 01366 // UNICODE mode. 01367 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); 01368 01369 namespace internal { 01370 01371 // Separate the error generating code from the code path to reduce the stack 01372 // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers 01373 // when calling EXPECT_* in a tight loop. 01374 template <typename T1, typename T2> 01375 AssertionResult CmpHelperEQFailure(const char* expected_expression, 01376 const char* actual_expression, 01377 const T1& expected, const T2& actual) { 01378 return EqFailure(expected_expression, 01379 actual_expression, 01380 FormatForComparisonFailureMessage(expected, actual), 01381 FormatForComparisonFailureMessage(actual, expected), 01382 false); 01383 } 01384 01385 // The helper function for {ASSERT|EXPECT}_EQ. 01386 template <typename T1, typename T2> 01387 AssertionResult CmpHelperEQ(const char* expected_expression, 01388 const char* actual_expression, 01389 const T1& expected, 01390 const T2& actual) { 01391 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */) 01392 if (expected == actual) { 01393 return AssertionSuccess(); 01394 } 01395 GTEST_DISABLE_MSC_WARNINGS_POP_() 01396 01397 return CmpHelperEQFailure(expected_expression, actual_expression, expected, 01398 actual); 01399 } 01400 01401 // With this overloaded version, we allow anonymous enums to be used 01402 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums 01403 // can be implicitly cast to BiggestInt. 01404 GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression, 01405 const char* actual_expression, 01406 BiggestInt expected, 01407 BiggestInt actual); 01408 01409 // The helper class for {ASSERT|EXPECT}_EQ. The template argument 01410 // lhs_is_null_literal is true iff the first argument to ASSERT_EQ() 01411 // is a null pointer literal. The following default implementation is 01412 // for lhs_is_null_literal being false. 01413 template <bool lhs_is_null_literal> 01414 class EqHelper { 01415 public: 01416 // This templatized version is for the general case. 01417 template <typename T1, typename T2> 01418 static AssertionResult Compare(const char* expected_expression, 01419 const char* actual_expression, 01420 const T1& expected, 01421 const T2& actual) { 01422 return CmpHelperEQ(expected_expression, actual_expression, expected, 01423 actual); 01424 } 01425 01426 // With this overloaded version, we allow anonymous enums to be used 01427 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous 01428 // enums can be implicitly cast to BiggestInt. 01429 // 01430 // Even though its body looks the same as the above version, we 01431 // cannot merge the two, as it will make anonymous enums unhappy. 01432 static AssertionResult Compare(const char* expected_expression, 01433 const char* actual_expression, 01434 BiggestInt expected, 01435 BiggestInt actual) { 01436 return CmpHelperEQ(expected_expression, actual_expression, expected, 01437 actual); 01438 } 01439 }; 01440 01441 // This specialization is used when the first argument to ASSERT_EQ() 01442 // is a null pointer literal, like NULL, false, or 0. 01443 template <> 01444 class EqHelper<true> { 01445 public: 01446 // We define two overloaded versions of Compare(). The first 01447 // version will be picked when the second argument to ASSERT_EQ() is 01448 // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or 01449 // EXPECT_EQ(false, a_bool). 01450 template <typename T1, typename T2> 01451 static AssertionResult Compare( 01452 const char* expected_expression, 01453 const char* actual_expression, 01454 const T1& expected, 01455 const T2& actual, 01456 // The following line prevents this overload from being considered if T2 01457 // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) 01458 // expands to Compare("", "", NULL, my_ptr), which requires a conversion 01459 // to match the Secret* in the other overload, which would otherwise make 01460 // this template match better. 01461 typename EnableIf<!is_pointer<T2>::value>::type* = 0) { 01462 return CmpHelperEQ(expected_expression, actual_expression, expected, 01463 actual); 01464 } 01465 01466 // This version will be picked when the second argument to ASSERT_EQ() is a 01467 // pointer, e.g. ASSERT_EQ(NULL, a_pointer). 01468 template <typename T> 01469 static AssertionResult Compare( 01470 const char* expected_expression, 01471 const char* actual_expression, 01472 // We used to have a second template parameter instead of Secret*. That 01473 // template parameter would deduce to 'long', making this a better match 01474 // than the first overload even without the first overload's EnableIf. 01475 // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to 01476 // non-pointer argument" (even a deduced integral argument), so the old 01477 // implementation caused warnings in user code. 01478 Secret* /* expected (NULL) */, 01479 T* actual) { 01480 // We already know that 'expected' is a null pointer. 01481 return CmpHelperEQ(expected_expression, actual_expression, 01482 static_cast<T*>(NULL), actual); 01483 } 01484 }; 01485 01486 // Separate the error generating code from the code path to reduce the stack 01487 // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers 01488 // when calling EXPECT_OP in a tight loop. 01489 template <typename T1, typename T2> 01490 AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, 01491 const T1& val1, const T2& val2, 01492 const char* op) { 01493 return AssertionFailure() 01494 << "Expected: (" << expr1 << ") " << op << " (" << expr2 01495 << "), actual: " << FormatForComparisonFailureMessage(val1, val2) 01496 << " vs " << FormatForComparisonFailureMessage(val2, val1); 01497 } 01498 01499 // A macro for implementing the helper functions needed to implement 01500 // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste 01501 // of similar code. 01502 // 01503 // For each templatized helper function, we also define an overloaded 01504 // version for BiggestInt in order to reduce code bloat and allow 01505 // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled 01506 // with gcc 4. 01507 // 01508 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01509 01510 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ 01511 template <typename T1, typename T2>\ 01512 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ 01513 const T1& val1, const T2& val2) {\ 01514 if (val1 op val2) {\ 01515 return AssertionSuccess();\ 01516 } else {\ 01517 return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ 01518 }\ 01519 }\ 01520 GTEST_API_ AssertionResult CmpHelper##op_name(\ 01521 const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) 01522 01523 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01524 01525 // Implements the helper function for {ASSERT|EXPECT}_NE 01526 GTEST_IMPL_CMP_HELPER_(NE, !=); 01527 // Implements the helper function for {ASSERT|EXPECT}_LE 01528 GTEST_IMPL_CMP_HELPER_(LE, <=); 01529 // Implements the helper function for {ASSERT|EXPECT}_LT 01530 GTEST_IMPL_CMP_HELPER_(LT, <); 01531 // Implements the helper function for {ASSERT|EXPECT}_GE 01532 GTEST_IMPL_CMP_HELPER_(GE, >=); 01533 // Implements the helper function for {ASSERT|EXPECT}_GT 01534 GTEST_IMPL_CMP_HELPER_(GT, >); 01535 01536 #undef GTEST_IMPL_CMP_HELPER_ 01537 01538 // The helper function for {ASSERT|EXPECT}_STREQ. 01539 // 01540 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01541 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, 01542 const char* actual_expression, 01543 const char* expected, 01544 const char* actual); 01545 01546 // The helper function for {ASSERT|EXPECT}_STRCASEEQ. 01547 // 01548 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01549 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression, 01550 const char* actual_expression, 01551 const char* expected, 01552 const char* actual); 01553 01554 // The helper function for {ASSERT|EXPECT}_STRNE. 01555 // 01556 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01557 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, 01558 const char* s2_expression, 01559 const char* s1, 01560 const char* s2); 01561 01562 // The helper function for {ASSERT|EXPECT}_STRCASENE. 01563 // 01564 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01565 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, 01566 const char* s2_expression, 01567 const char* s1, 01568 const char* s2); 01569 01570 01571 // Helper function for *_STREQ on wide strings. 01572 // 01573 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01574 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression, 01575 const char* actual_expression, 01576 const wchar_t* expected, 01577 const wchar_t* actual); 01578 01579 // Helper function for *_STRNE on wide strings. 01580 // 01581 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01582 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, 01583 const char* s2_expression, 01584 const wchar_t* s1, 01585 const wchar_t* s2); 01586 01587 } // namespace internal 01588 01589 // IsSubstring() and IsNotSubstring() are intended to be used as the 01590 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by 01591 // themselves. They check whether needle is a substring of haystack 01592 // (NULL is considered a substring of itself only), and return an 01593 // appropriate error message when they fail. 01594 // 01595 // The {needle,haystack}_expr arguments are the stringified 01596 // expressions that generated the two real arguments. 01597 GTEST_API_ AssertionResult IsSubstring( 01598 const char* needle_expr, const char* haystack_expr, 01599 const char* needle, const char* haystack); 01600 GTEST_API_ AssertionResult IsSubstring( 01601 const char* needle_expr, const char* haystack_expr, 01602 const wchar_t* needle, const wchar_t* haystack); 01603 GTEST_API_ AssertionResult IsNotSubstring( 01604 const char* needle_expr, const char* haystack_expr, 01605 const char* needle, const char* haystack); 01606 GTEST_API_ AssertionResult IsNotSubstring( 01607 const char* needle_expr, const char* haystack_expr, 01608 const wchar_t* needle, const wchar_t* haystack); 01609 GTEST_API_ AssertionResult IsSubstring( 01610 const char* needle_expr, const char* haystack_expr, 01611 const ::std::string& needle, const ::std::string& haystack); 01612 GTEST_API_ AssertionResult IsNotSubstring( 01613 const char* needle_expr, const char* haystack_expr, 01614 const ::std::string& needle, const ::std::string& haystack); 01615 01616 #if GTEST_HAS_STD_WSTRING 01617 GTEST_API_ AssertionResult IsSubstring( 01618 const char* needle_expr, const char* haystack_expr, 01619 const ::std::wstring& needle, const ::std::wstring& haystack); 01620 GTEST_API_ AssertionResult IsNotSubstring( 01621 const char* needle_expr, const char* haystack_expr, 01622 const ::std::wstring& needle, const ::std::wstring& haystack); 01623 #endif // GTEST_HAS_STD_WSTRING 01624 01625 namespace internal { 01626 01627 // Helper template function for comparing floating-points. 01628 // 01629 // Template parameter: 01630 // 01631 // RawType: the raw floating-point type (either float or double) 01632 // 01633 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01634 template <typename RawType> 01635 AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression, 01636 const char* actual_expression, 01637 RawType expected, 01638 RawType actual) { 01639 const FloatingPoint<RawType> lhs(expected), rhs(actual); 01640 01641 if (lhs.AlmostEquals(rhs)) { 01642 return AssertionSuccess(); 01643 } 01644 01645 ::std::stringstream expected_ss; 01646 expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) 01647 << expected; 01648 01649 ::std::stringstream actual_ss; 01650 actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) 01651 << actual; 01652 01653 return EqFailure(expected_expression, 01654 actual_expression, 01655 StringStreamToString(&expected_ss), 01656 StringStreamToString(&actual_ss), 01657 false); 01658 } 01659 01660 // Helper function for implementing ASSERT_NEAR. 01661 // 01662 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. 01663 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, 01664 const char* expr2, 01665 const char* abs_error_expr, 01666 double val1, 01667 double val2, 01668 double abs_error); 01669 01670 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. 01671 // A class that enables one to stream messages to assertion macros 01672 class GTEST_API_ AssertHelper { 01673 public: 01674 // Constructor. 01675 AssertHelper(TestPartResult::Type type, 01676 const char* file, 01677 int line, 01678 const char* message); 01679 ~AssertHelper(); 01680 01681 // Message assignment is a semantic trick to enable assertion 01682 // streaming; see the GTEST_MESSAGE_ macro below. 01683 void operator=(const Message& message) const; 01684 01685 private: 01686 // We put our data in a struct so that the size of the AssertHelper class can 01687 // be as small as possible. This is important because gcc is incapable of 01688 // re-using stack space even for temporary variables, so every EXPECT_EQ 01689 // reserves stack space for another AssertHelper. 01690 struct AssertHelperData { 01691 AssertHelperData(TestPartResult::Type t, 01692 const char* srcfile, 01693 int line_num, 01694 const char* msg) 01695 : type(t), file(srcfile), line(line_num), message(msg) { } 01696 01697 TestPartResult::Type const type; 01698 const char* const file; 01699 int const line; 01700 std::string const message; 01701 01702 private: 01703 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); 01704 }; 01705 01706 AssertHelperData* const data_; 01707 01708 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); 01709 }; 01710 01711 } // namespace internal 01712 01713 #if GTEST_HAS_PARAM_TEST 01714 // The pure interface class that all value-parameterized tests inherit from. 01715 // A value-parameterized class must inherit from both ::testing::Test and 01716 // ::testing::WithParamInterface. In most cases that just means inheriting 01717 // from ::testing::TestWithParam, but more complicated test hierarchies 01718 // may need to inherit from Test and WithParamInterface at different levels. 01719 // 01720 // This interface has support for accessing the test parameter value via 01721 // the GetParam() method. 01722 // 01723 // Use it with one of the parameter generator defining functions, like Range(), 01724 // Values(), ValuesIn(), Bool(), and Combine(). 01725 // 01726 // class FooTest : public ::testing::TestWithParam<int> { 01727 // protected: 01728 // FooTest() { 01729 // // Can use GetParam() here. 01730 // } 01731 // virtual ~FooTest() { 01732 // // Can use GetParam() here. 01733 // } 01734 // virtual void SetUp() { 01735 // // Can use GetParam() here. 01736 // } 01737 // virtual void TearDown { 01738 // // Can use GetParam() here. 01739 // } 01740 // }; 01741 // TEST_P(FooTest, DoesBar) { 01742 // // Can use GetParam() method here. 01743 // Foo foo; 01744 // ASSERT_TRUE(foo.DoesBar(GetParam())); 01745 // } 01746 // INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); 01747 01748 template <typename T> 01749 class WithParamInterface { 01750 public: 01751 typedef T ParamType; 01752 virtual ~WithParamInterface() {} 01753 01754 // The current parameter value. Is also available in the test fixture's 01755 // constructor. This member function is non-static, even though it only 01756 // references static data, to reduce the opportunity for incorrect uses 01757 // like writing 'WithParamInterface<bool>::GetParam()' for a test that 01758 // uses a fixture whose parameter type is int. 01759 const ParamType& GetParam() const { 01760 GTEST_CHECK_(parameter_ != NULL) 01761 << "GetParam() can only be called inside a value-parameterized test " 01762 << "-- did you intend to write TEST_P instead of TEST_F?"; 01763 return *parameter_; 01764 } 01765 01766 private: 01767 // Sets parameter value. The caller is responsible for making sure the value 01768 // remains alive and unchanged throughout the current test. 01769 static void SetParam(const ParamType* parameter) { 01770 parameter_ = parameter; 01771 } 01772 01773 // Static value used for accessing parameter during a test lifetime. 01774 static const ParamType* parameter_; 01775 01776 // TestClass must be a subclass of WithParamInterface<T> and Test. 01777 template <class TestClass> friend class internal::ParameterizedTestFactory; 01778 }; 01779 01780 template <typename T> 01781 const T* WithParamInterface<T>::parameter_ = NULL; 01782 01783 // Most value-parameterized classes can ignore the existence of 01784 // WithParamInterface, and can just inherit from ::testing::TestWithParam. 01785 01786 template <typename T> 01787 class TestWithParam : public Test, public WithParamInterface<T> { 01788 }; 01789 01790 #endif // GTEST_HAS_PARAM_TEST 01791 01792 // Macros for indicating success/failure in test code. 01793 01794 // ADD_FAILURE unconditionally adds a failure to the current test. 01795 // SUCCEED generates a success - it doesn't automatically make the 01796 // current test successful, as a test is only successful when it has 01797 // no failure. 01798 // 01799 // EXPECT_* verifies that a certain condition is satisfied. If not, 01800 // it behaves like ADD_FAILURE. In particular: 01801 // 01802 // EXPECT_TRUE verifies that a Boolean condition is true. 01803 // EXPECT_FALSE verifies that a Boolean condition is false. 01804 // 01805 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except 01806 // that they will also abort the current function on failure. People 01807 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those 01808 // writing data-driven tests often find themselves using ADD_FAILURE 01809 // and EXPECT_* more. 01810 01811 // Generates a nonfatal failure with a generic message. 01812 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") 01813 01814 // Generates a nonfatal failure at the given source file location with 01815 // a generic message. 01816 #define ADD_FAILURE_AT(file, line) \ 01817 GTEST_MESSAGE_AT_(file, line, "Failed", \ 01818 ::testing::TestPartResult::kNonFatalFailure) 01819 01820 // Generates a fatal failure with a generic message. 01821 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") 01822 01823 // Define this macro to 1 to omit the definition of FAIL(), which is a 01824 // generic name and clashes with some other libraries. 01825 #if !GTEST_DONT_DEFINE_FAIL 01826 # define FAIL() GTEST_FAIL() 01827 #endif 01828 01829 // Generates a success with a generic message. 01830 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") 01831 01832 // Define this macro to 1 to omit the definition of SUCCEED(), which 01833 // is a generic name and clashes with some other libraries. 01834 #if !GTEST_DONT_DEFINE_SUCCEED 01835 # define SUCCEED() GTEST_SUCCEED() 01836 #endif 01837 01838 // Macros for testing exceptions. 01839 // 01840 // * {ASSERT|EXPECT}_THROW(statement, expected_exception): 01841 // Tests that the statement throws the expected exception. 01842 // * {ASSERT|EXPECT}_NO_THROW(statement): 01843 // Tests that the statement doesn't throw any exception. 01844 // * {ASSERT|EXPECT}_ANY_THROW(statement): 01845 // Tests that the statement throws an exception. 01846 01847 #define EXPECT_THROW(statement, expected_exception) \ 01848 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) 01849 #define EXPECT_NO_THROW(statement) \ 01850 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) 01851 #define EXPECT_ANY_THROW(statement) \ 01852 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) 01853 #define ASSERT_THROW(statement, expected_exception) \ 01854 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) 01855 #define ASSERT_NO_THROW(statement) \ 01856 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) 01857 #define ASSERT_ANY_THROW(statement) \ 01858 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) 01859 01860 // Boolean assertions. Condition can be either a Boolean expression or an 01861 // AssertionResult. For more information on how to use AssertionResult with 01862 // these macros see comments on that class. 01863 #define EXPECT_TRUE(condition) \ 01864 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ 01865 GTEST_NONFATAL_FAILURE_) 01866 #define EXPECT_FALSE(condition) \ 01867 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ 01868 GTEST_NONFATAL_FAILURE_) 01869 #define ASSERT_TRUE(condition) \ 01870 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ 01871 GTEST_FATAL_FAILURE_) 01872 #define ASSERT_FALSE(condition) \ 01873 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ 01874 GTEST_FATAL_FAILURE_) 01875 01876 // Includes the auto-generated header that implements a family of 01877 // generic predicate assertion macros. 01878 #include "gtest/gtest_pred_impl.h" 01879 01880 // Macros for testing equalities and inequalities. 01881 // 01882 // * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual 01883 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 01884 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 01885 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 01886 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 01887 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 01888 // 01889 // When they are not, Google Test prints both the tested expressions and 01890 // their actual values. The values must be compatible built-in types, 01891 // or you will get a compiler error. By "compatible" we mean that the 01892 // values can be compared by the respective operator. 01893 // 01894 // Note: 01895 // 01896 // 1. It is possible to make a user-defined type work with 01897 // {ASSERT|EXPECT}_??(), but that requires overloading the 01898 // comparison operators and is thus discouraged by the Google C++ 01899 // Usage Guide. Therefore, you are advised to use the 01900 // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are 01901 // equal. 01902 // 01903 // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on 01904 // pointers (in particular, C strings). Therefore, if you use it 01905 // with two C strings, you are testing how their locations in memory 01906 // are related, not how their content is related. To compare two C 01907 // strings by content, use {ASSERT|EXPECT}_STR*(). 01908 // 01909 // 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to 01910 // {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you 01911 // what the actual value is when it fails, and similarly for the 01912 // other comparisons. 01913 // 01914 // 4. Do not depend on the order in which {ASSERT|EXPECT}_??() 01915 // evaluate their arguments, which is undefined. 01916 // 01917 // 5. These macros evaluate their arguments exactly once. 01918 // 01919 // Examples: 01920 // 01921 // EXPECT_NE(5, Foo()); 01922 // EXPECT_EQ(NULL, a_pointer); 01923 // ASSERT_LT(i, array_size); 01924 // ASSERT_GT(records.size(), 0) << "There is no record left."; 01925 01926 #define EXPECT_EQ(expected, actual) \ 01927 EXPECT_PRED_FORMAT2(::testing::internal:: \ 01928 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \ 01929 expected, actual) 01930 #define EXPECT_NE(expected, actual) \ 01931 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual) 01932 #define EXPECT_LE(val1, val2) \ 01933 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) 01934 #define EXPECT_LT(val1, val2) \ 01935 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) 01936 #define EXPECT_GE(val1, val2) \ 01937 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) 01938 #define EXPECT_GT(val1, val2) \ 01939 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) 01940 01941 #define GTEST_ASSERT_EQ(expected, actual) \ 01942 ASSERT_PRED_FORMAT2(::testing::internal:: \ 01943 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \ 01944 expected, actual) 01945 #define GTEST_ASSERT_NE(val1, val2) \ 01946 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) 01947 #define GTEST_ASSERT_LE(val1, val2) \ 01948 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) 01949 #define GTEST_ASSERT_LT(val1, val2) \ 01950 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) 01951 #define GTEST_ASSERT_GE(val1, val2) \ 01952 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) 01953 #define GTEST_ASSERT_GT(val1, val2) \ 01954 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) 01955 01956 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of 01957 // ASSERT_XY(), which clashes with some users' own code. 01958 01959 #if !GTEST_DONT_DEFINE_ASSERT_EQ 01960 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) 01961 #endif 01962 01963 #if !GTEST_DONT_DEFINE_ASSERT_NE 01964 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) 01965 #endif 01966 01967 #if !GTEST_DONT_DEFINE_ASSERT_LE 01968 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) 01969 #endif 01970 01971 #if !GTEST_DONT_DEFINE_ASSERT_LT 01972 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) 01973 #endif 01974 01975 #if !GTEST_DONT_DEFINE_ASSERT_GE 01976 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) 01977 #endif 01978 01979 #if !GTEST_DONT_DEFINE_ASSERT_GT 01980 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) 01981 #endif 01982 01983 // C-string Comparisons. All tests treat NULL and any non-NULL string 01984 // as different. Two NULLs are equal. 01985 // 01986 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 01987 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 01988 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case 01989 // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case 01990 // 01991 // For wide or narrow string objects, you can use the 01992 // {ASSERT|EXPECT}_??() macros. 01993 // 01994 // Don't depend on the order in which the arguments are evaluated, 01995 // which is undefined. 01996 // 01997 // These macros evaluate their arguments exactly once. 01998 01999 #define EXPECT_STREQ(expected, actual) \ 02000 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) 02001 #define EXPECT_STRNE(s1, s2) \ 02002 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) 02003 #define EXPECT_STRCASEEQ(expected, actual) \ 02004 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) 02005 #define EXPECT_STRCASENE(s1, s2)\ 02006 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) 02007 02008 #define ASSERT_STREQ(expected, actual) \ 02009 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual) 02010 #define ASSERT_STRNE(s1, s2) \ 02011 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) 02012 #define ASSERT_STRCASEEQ(expected, actual) \ 02013 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual) 02014 #define ASSERT_STRCASENE(s1, s2)\ 02015 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) 02016 02017 // Macros for comparing floating-point numbers. 02018 // 02019 // * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual): 02020 // Tests that two float values are almost equal. 02021 // * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual): 02022 // Tests that two double values are almost equal. 02023 // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): 02024 // Tests that v1 and v2 are within the given distance to each other. 02025 // 02026 // Google Test uses ULP-based comparison to automatically pick a default 02027 // error bound that is appropriate for the operands. See the 02028 // FloatingPoint template class in gtest-internal.h if you are 02029 // interested in the implementation details. 02030 02031 #define EXPECT_FLOAT_EQ(expected, actual)\ 02032 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ 02033 expected, actual) 02034 02035 #define EXPECT_DOUBLE_EQ(expected, actual)\ 02036 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ 02037 expected, actual) 02038 02039 #define ASSERT_FLOAT_EQ(expected, actual)\ 02040 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ 02041 expected, actual) 02042 02043 #define ASSERT_DOUBLE_EQ(expected, actual)\ 02044 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ 02045 expected, actual) 02046 02047 #define EXPECT_NEAR(val1, val2, abs_error)\ 02048 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ 02049 val1, val2, abs_error) 02050 02051 #define ASSERT_NEAR(val1, val2, abs_error)\ 02052 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ 02053 val1, val2, abs_error) 02054 02055 // These predicate format functions work on floating-point values, and 02056 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. 02057 // 02058 // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); 02059 02060 // Asserts that val1 is less than, or almost equal to, val2. Fails 02061 // otherwise. In particular, it fails if either val1 or val2 is NaN. 02062 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, 02063 float val1, float val2); 02064 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, 02065 double val1, double val2); 02066 02067 02068 #if GTEST_OS_WINDOWS 02069 02070 // Macros that test for HRESULT failure and success, these are only useful 02071 // on Windows, and rely on Windows SDK macros and APIs to compile. 02072 // 02073 // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) 02074 // 02075 // When expr unexpectedly fails or succeeds, Google Test prints the 02076 // expected result and the actual result with both a human-readable 02077 // string representation of the error, if available, as well as the 02078 // hex result code. 02079 # define EXPECT_HRESULT_SUCCEEDED(expr) \ 02080 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) 02081 02082 # define ASSERT_HRESULT_SUCCEEDED(expr) \ 02083 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) 02084 02085 # define EXPECT_HRESULT_FAILED(expr) \ 02086 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) 02087 02088 # define ASSERT_HRESULT_FAILED(expr) \ 02089 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) 02090 02091 #endif // GTEST_OS_WINDOWS 02092 02093 // Macros that execute statement and check that it doesn't generate new fatal 02094 // failures in the current thread. 02095 // 02096 // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); 02097 // 02098 // Examples: 02099 // 02100 // EXPECT_NO_FATAL_FAILURE(Process()); 02101 // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; 02102 // 02103 #define ASSERT_NO_FATAL_FAILURE(statement) \ 02104 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) 02105 #define EXPECT_NO_FATAL_FAILURE(statement) \ 02106 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) 02107 02108 // Causes a trace (including the source file path, the current line 02109 // number, and the given message) to be included in every test failure 02110 // message generated by code in the current scope. The effect is 02111 // undone when the control leaves the current scope. 02112 // 02113 // The message argument can be anything streamable to std::ostream. 02114 // 02115 // In the implementation, we include the current line number as part 02116 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s 02117 // to appear in the same block - as long as they are on different 02118 // lines. 02119 #define SCOPED_TRACE(message) \ 02120 ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ 02121 __FILE__, __LINE__, ::testing::Message() << (message)) 02122 02123 // Compile-time assertion for type equality. 02124 // StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are 02125 // the same type. The value it returns is not interesting. 02126 // 02127 // Instead of making StaticAssertTypeEq a class template, we make it a 02128 // function template that invokes a helper class template. This 02129 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by 02130 // defining objects of that type. 02131 // 02132 // CAVEAT: 02133 // 02134 // When used inside a method of a class template, 02135 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is 02136 // instantiated. For example, given: 02137 // 02138 // template <typename T> class Foo { 02139 // public: 02140 // void Bar() { testing::StaticAssertTypeEq<int, T>(); } 02141 // }; 02142 // 02143 // the code: 02144 // 02145 // void Test1() { Foo<bool> foo; } 02146 // 02147 // will NOT generate a compiler error, as Foo<bool>::Bar() is never 02148 // actually instantiated. Instead, you need: 02149 // 02150 // void Test2() { Foo<bool> foo; foo.Bar(); } 02151 // 02152 // to cause a compiler error. 02153 template <typename T1, typename T2> 02154 bool StaticAssertTypeEq() { 02155 (void)internal::StaticAssertTypeEqHelper<T1, T2>(); 02156 return true; 02157 } 02158 02159 // Defines a test. 02160 // 02161 // The first parameter is the name of the test case, and the second 02162 // parameter is the name of the test within the test case. 02163 // 02164 // The convention is to end the test case name with "Test". For 02165 // example, a test case for the Foo class can be named FooTest. 02166 // 02167 // Test code should appear between braces after an invocation of 02168 // this macro. Example: 02169 // 02170 // TEST(FooTest, InitializesCorrectly) { 02171 // Foo foo; 02172 // EXPECT_TRUE(foo.StatusIsOK()); 02173 // } 02174 02175 // Note that we call GetTestTypeId() instead of GetTypeId< 02176 // ::testing::Test>() here to get the type ID of testing::Test. This 02177 // is to work around a suspected linker bug when using Google Test as 02178 // a framework on Mac OS X. The bug causes GetTypeId< 02179 // ::testing::Test>() to return different values depending on whether 02180 // the call is from the Google Test framework itself or from user test 02181 // code. GetTestTypeId() is guaranteed to always return the same 02182 // value, as it always calls GetTypeId<>() from the Google Test 02183 // framework. 02184 #define GTEST_TEST(test_case_name, test_name)\ 02185 GTEST_TEST_(test_case_name, test_name, \ 02186 ::testing::Test, ::testing::internal::GetTestTypeId()) 02187 02188 // Define this macro to 1 to omit the definition of TEST(), which 02189 // is a generic name and clashes with some other libraries. 02190 #if !GTEST_DONT_DEFINE_TEST 02191 # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) 02192 #endif 02193 02194 // Defines a test that uses a test fixture. 02195 // 02196 // The first parameter is the name of the test fixture class, which 02197 // also doubles as the test case name. The second parameter is the 02198 // name of the test within the test case. 02199 // 02200 // A test fixture class must be declared earlier. The user should put 02201 // his test code between braces after using this macro. Example: 02202 // 02203 // class FooTest : public testing::Test { 02204 // protected: 02205 // virtual void SetUp() { b_.AddElement(3); } 02206 // 02207 // Foo a_; 02208 // Foo b_; 02209 // }; 02210 // 02211 // TEST_F(FooTest, InitializesCorrectly) { 02212 // EXPECT_TRUE(a_.StatusIsOK()); 02213 // } 02214 // 02215 // TEST_F(FooTest, ReturnsElementCountCorrectly) { 02216 // EXPECT_EQ(0, a_.size()); 02217 // EXPECT_EQ(1, b_.size()); 02218 // } 02219 02220 #define TEST_F(test_fixture, test_name)\ 02221 GTEST_TEST_(test_fixture, test_name, test_fixture, \ 02222 ::testing::internal::GetTypeId<test_fixture>()) 02223 02224 } // namespace testing 02225 02226 // Use this function in main() to run all tests. It returns 0 if all 02227 // tests are successful, or 1 otherwise. 02228 // 02229 // RUN_ALL_TESTS() should be invoked after the command line has been 02230 // parsed by InitGoogleTest(). 02231 // 02232 // This function was formerly a macro; thus, it is in the global 02233 // namespace and has an all-caps name. 02234 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; 02235 02236 inline int RUN_ALL_TESTS() { 02237 return ::testing::UnitTest::GetInstance()->Run(); 02238 } 02239 02240 #endif // GTEST_INCLUDE_GTEST_GTEST_H_