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