1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: wan@google.com (Zhanyong Wan)
32 // The Google C++ Testing Framework (Google Test)
34 // This header file defines the public API for Google Test. It should be
35 // included by any test program that uses Google Test.
37 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
38 // leave some internal implementation details in this header file.
39 // They are clearly marked by comments like this:
41 // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
43 // Such code is NOT meant to be used by a user directly, and is subject
44 // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
47 // Acknowledgment: Google Test borrowed the idea of automatic test
48 // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
49 // easyUnit framework.
51 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
52 #define GTEST_INCLUDE_GTEST_GTEST_H_
58 #include "gtest/internal/gtest-internal.h"
59 #include "gtest/internal/gtest-string.h"
60 #include "gtest/gtest-death-test.h"
61 #include "gtest/gtest-message.h"
62 #include "gtest/gtest-param-test.h"
63 #include "gtest/gtest-printers.h"
64 #include "gtest/gtest_prod.h"
65 #include "gtest/gtest-test-part.h"
66 #include "gtest/gtest-typed-test.h"
68 // Depending on the platform, different string classes are available.
69 // On Linux, in addition to ::std::string, Google also makes use of
70 // class ::string, which has the same interface as ::std::string, but
71 // has a different implementation.
73 // The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
74 // ::string is available AND is a distinct type to ::std::string, or
75 // define it to 0 to indicate otherwise.
77 // If the user's ::std::string and ::string are the same class due to
78 // aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0.
80 // If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined
85 // Declares the flags.
87 // This flag temporary enables the disabled tests.
88 GTEST_DECLARE_bool_(also_run_disabled_tests);
90 // This flag brings the debugger on an assertion failure.
91 GTEST_DECLARE_bool_(break_on_failure);
93 // This flag controls whether Google Test catches all test-thrown exceptions
94 // and logs them as failures.
95 GTEST_DECLARE_bool_(catch_exceptions);
97 // This flag enables using colors in terminal output. Available values are
98 // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
99 // to let Google Test decide.
100 GTEST_DECLARE_string_(color);
102 // This flag sets up the filter to select by name using a glob pattern
103 // the tests to run. If the filter is not given all tests are executed.
104 GTEST_DECLARE_string_(filter);
106 // This flag causes the Google Test to list tests. None of the tests listed
107 // are actually run if the flag is provided.
108 GTEST_DECLARE_bool_(list_tests);
110 // This flag controls whether Google Test emits a detailed XML report to a file
111 // in addition to its normal textual output.
112 GTEST_DECLARE_string_(output);
114 // This flags control whether Google Test prints the elapsed time for each
116 GTEST_DECLARE_bool_(print_time);
118 // This flag specifies the random number seed.
119 GTEST_DECLARE_int32_(random_seed);
121 // This flag sets how many times the tests are repeated. The default value
122 // is 1. If the value is -1 the tests are repeating forever.
123 GTEST_DECLARE_int32_(repeat);
125 // This flag controls whether Google Test includes Google Test internal
126 // stack frames in failure stack traces.
127 GTEST_DECLARE_bool_(show_internal_stack_frames);
129 // When this flag is specified, tests' order is randomized on every iteration.
130 GTEST_DECLARE_bool_(shuffle);
132 // This flag specifies the maximum number of stack frames to be
133 // printed in a failure message.
134 GTEST_DECLARE_int32_(stack_trace_depth);
136 // When this flag is specified, a failed assertion will throw an
137 // exception if exceptions are enabled, or exit the program with a
138 // non-zero code otherwise.
139 GTEST_DECLARE_bool_(throw_on_failure);
141 // When this flag is set with a "host:port" string, on supported
142 // platforms test results are streamed to the specified port on
143 // the specified host machine.
144 GTEST_DECLARE_string_(stream_result_to);
146 // The upper limit for valid stack trace depths.
147 const int kMaxStackTraceDepth = 100;
152 class DefaultGlobalTestPartResultReporter;
154 class NoExecDeathTest;
155 class FinalSuccessChecker;
156 class GTestFlagSaver;
157 class TestResultAccessor;
158 class TestEventListenersAccessor;
159 class TestEventRepeater;
160 class WindowsDeathTest;
161 class UnitTestImpl* GetUnitTestImpl();
162 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
163 const std::string& message);
165 // Converts a streamable value to an std::string. A NULL pointer is
166 // converted to "(null)". When the input value is a ::string,
167 // ::std::string, ::wstring, or ::std::wstring object, each NUL
168 // character in it is replaced with "\\0".
169 // Declared in gtest-internal.h but defined here, so that it has access
170 // to the definition of the Message class, required by the ARM
172 template <typename T>
173 std::string StreamableToString(const T& streamable) {
174 return (Message() << streamable).GetString();
177 } // namespace internal
179 // The friend relationship of some of these classes is cyclic.
180 // If we don't forward declare them the compiler might confuse the classes
181 // in friendship clauses with same named classes on the scope.
187 // A class for indicating whether an assertion was successful. When
188 // the assertion wasn't successful, the AssertionResult object
189 // remembers a non-empty message that describes how it failed.
191 // To create an instance of this class, use one of the factory functions
192 // (AssertionSuccess() and AssertionFailure()).
194 // This class is useful for two purposes:
195 // 1. Defining predicate functions to be used with Boolean test assertions
196 // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
197 // 2. Defining predicate-format functions to be
198 // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
200 // For example, if you define IsEven predicate:
202 // testing::AssertionResult IsEven(int n) {
204 // return testing::AssertionSuccess();
206 // return testing::AssertionFailure() << n << " is odd";
209 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
210 // will print the message
212 // Value of: IsEven(Fib(5))
213 // Actual: false (5 is odd)
216 // instead of a more opaque
218 // Value of: IsEven(Fib(5))
222 // in case IsEven is a simple Boolean predicate.
224 // If you expect your predicate to be reused and want to support informative
225 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
226 // about half as often as positive ones in our tests), supply messages for
227 // both success and failure cases:
229 // testing::AssertionResult IsEven(int n) {
231 // return testing::AssertionSuccess() << n << " is even";
233 // return testing::AssertionFailure() << n << " is odd";
236 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
238 // Value of: IsEven(Fib(6))
239 // Actual: true (8 is even)
242 // NB: Predicates that support negative Boolean assertions have reduced
243 // performance in positive ones so be careful not to use them in tests
244 // that have lots (tens of thousands) of positive Boolean assertions.
246 // To use this class with EXPECT_PRED_FORMAT assertions such as:
248 // // Verifies that Foo() returns an even number.
249 // EXPECT_PRED_FORMAT1(IsEven, Foo());
251 // you need to define:
253 // testing::AssertionResult IsEven(const char* expr, int n) {
255 // return testing::AssertionSuccess();
257 // return testing::AssertionFailure()
258 // << "Expected: " << expr << " is even\n Actual: it's " << n;
261 // If Foo() returns 5, you will see the following message:
263 // Expected: Foo() is even
266 class GTEST_API_ AssertionResult {
269 // Used in EXPECT_TRUE/FALSE(assertion_result).
270 AssertionResult(const AssertionResult& other);
271 // Used in the EXPECT_TRUE/FALSE(bool_expression).
272 explicit AssertionResult(bool success) : success_(success) {}
274 // Returns true iff the assertion succeeded.
275 operator bool() const { return success_; } // NOLINT
277 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
278 AssertionResult operator!() const;
280 // Returns the text streamed into this AssertionResult. Test assertions
281 // use it when they fail (i.e., the predicate's outcome doesn't match the
282 // assertion's expectation). When nothing has been streamed into the
283 // object, returns an empty string.
284 const char* message() const {
285 return message_.get() != NULL ? message_->c_str() : "";
287 // TODO(vladl@google.com): Remove this after making sure no clients use it.
288 // Deprecated; please use message() instead.
289 const char* failure_message() const { return message(); }
291 // Streams a custom failure message into this object.
292 template <typename T> AssertionResult& operator<<(const T& value) {
293 AppendMessage(Message() << value);
297 // Allows streaming basic output manipulators such as endl or flush into
299 AssertionResult& operator<<(
300 ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
301 AppendMessage(Message() << basic_manipulator);
306 // Appends the contents of message to message_.
307 void AppendMessage(const Message& a_message) {
308 if (message_.get() == NULL)
309 message_.reset(new ::std::string);
310 message_->append(a_message.GetString().c_str());
313 // Stores result of the assertion predicate.
315 // Stores the message describing the condition in case the expectation
316 // construct is not satisfied with the predicate's outcome.
317 // Referenced via a pointer to avoid taking too much stack frame space
318 // with test assertions.
319 internal::scoped_ptr< ::std::string> message_;
321 GTEST_DISALLOW_ASSIGN_(AssertionResult);
324 // Makes a successful assertion result.
325 GTEST_API_ AssertionResult AssertionSuccess();
327 // Makes a failed assertion result.
328 GTEST_API_ AssertionResult AssertionFailure();
330 // Makes a failed assertion result with the given failure message.
331 // Deprecated; use AssertionFailure() << msg.
332 GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
334 // The abstract class that all tests inherit from.
336 // In Google Test, a unit test program contains one or many TestCases, and
337 // each TestCase contains one or many Tests.
339 // When you define a test using the TEST macro, you don't need to
340 // explicitly derive from Test - the TEST macro automatically does
343 // The only time you derive from Test is when defining a test fixture
344 // to be used a TEST_F. For example:
346 // class FooTest : public testing::Test {
348 // virtual void SetUp() { ... }
349 // virtual void TearDown() { ... }
353 // TEST_F(FooTest, Bar) { ... }
354 // TEST_F(FooTest, Baz) { ... }
356 // Test is not copyable.
357 class GTEST_API_ Test {
359 friend class TestInfo;
361 // Defines types for pointers to functions that set up and tear down
363 typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
364 typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
366 // The d'tor is virtual as we intend to inherit from Test.
369 // Sets up the stuff shared by all tests in this test case.
371 // Google Test will call Foo::SetUpTestCase() before running the first
372 // test in test case Foo. Hence a sub-class can define its own
373 // SetUpTestCase() method to shadow the one defined in the super
375 static void SetUpTestCase() {}
377 // Tears down the stuff shared by all tests in this test case.
379 // Google Test will call Foo::TearDownTestCase() after running the last
380 // test in test case Foo. Hence a sub-class can define its own
381 // TearDownTestCase() method to shadow the one defined in the super
383 static void TearDownTestCase() {}
385 // Returns true iff the current test has a fatal failure.
386 static bool HasFatalFailure();
388 // Returns true iff the current test has a non-fatal failure.
389 static bool HasNonfatalFailure();
391 // Returns true iff the current test has a (either fatal or
392 // non-fatal) failure.
393 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
395 // Logs a property for the current test. Only the last value for a given
396 // key is remembered.
397 // These are public static so they can be called from utility functions
398 // that are not members of the test fixture.
399 // The arguments are const char* instead strings, as Google Test is used
400 // on platforms where string doesn't compile.
402 // Note that a driving consideration for these RecordProperty methods
403 // was to produce xml output suited to the Greenspan charting utility,
404 // which at present will only chart values that fit in a 32-bit int. It
405 // is the user's responsibility to restrict their values to 32-bit ints
406 // if they intend them to be used with Greenspan.
407 static void RecordProperty(const char* key, const char* value);
408 static void RecordProperty(const char* key, int value);
411 // Creates a Test object.
414 // Sets up the test fixture.
415 virtual void SetUp();
417 // Tears down the test fixture.
418 virtual void TearDown();
421 // Returns true iff the current test has the same fixture class as
422 // the first test in the current test case.
423 static bool HasSameFixtureClass();
425 // Runs the test after the test fixture has been set up.
427 // A sub-class must implement this to define the test logic.
429 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
430 // Instead, use the TEST or TEST_F macro.
431 virtual void TestBody() = 0;
433 // Sets up, executes, and tears down the test.
436 // Deletes self. We deliberately pick an unusual name for this
437 // internal method to avoid clashing with names used in user TESTs.
438 void DeleteSelf_() { delete this; }
440 // Uses a GTestFlagSaver to save and restore all Google Test flags.
441 const internal::GTestFlagSaver* const gtest_flag_saver_;
443 // Often a user mis-spells SetUp() as Setup() and spends a long time
444 // wondering why it is never called by Google Test. The declaration of
445 // the following method is solely for catching such an error at
448 // - The return type is deliberately chosen to be not void, so it
449 // will be a conflict if a user declares void Setup() in his test
452 // - This method is private, so it will be another compiler error
453 // if a user calls it from his test fixture.
455 // DO NOT OVERRIDE THIS FUNCTION.
457 // If you see an error about overriding the following function or
458 // about it being private, you have mis-spelled SetUp() as Setup().
459 struct Setup_should_be_spelled_SetUp {};
460 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
462 // We disallow copying Tests.
463 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
466 typedef internal::TimeInMillis TimeInMillis;
468 // A copyable object representing a user specified test property which can be
469 // output as a key/value string pair.
471 // Don't inherit from TestProperty as its destructor is not virtual.
474 // C'tor. TestProperty does NOT have a default constructor.
475 // Always use this constructor (with parameters) to create a
476 // TestProperty object.
477 TestProperty(const char* a_key, const char* a_value) :
478 key_(a_key), value_(a_value) {
481 // Gets the user supplied key.
482 const char* key() const {
486 // Gets the user supplied value.
487 const char* value() const {
488 return value_.c_str();
491 // Sets a new value, overriding the one supplied in the constructor.
492 void SetValue(const char* new_value) {
497 // The key supplied by the user.
499 // The value supplied by the user.
503 // The result of a single Test. This includes a list of
504 // TestPartResults, a list of TestProperties, a count of how many
505 // death tests there are in the Test, and how much time it took to run
508 // TestResult is not copyable.
509 class GTEST_API_ TestResult {
511 // Creates an empty TestResult.
514 // D'tor. Do not inherit from TestResult.
517 // Gets the number of all test parts. This is the sum of the number
518 // of successful test parts and the number of failed test parts.
519 int total_part_count() const;
521 // Returns the number of the test properties.
522 int test_property_count() const;
524 // Returns true iff the test passed (i.e. no test part failed).
525 bool Passed() const { return !Failed(); }
527 // Returns true iff the test failed.
530 // Returns true iff the test fatally failed.
531 bool HasFatalFailure() const;
533 // Returns true iff the test has a non-fatal failure.
534 bool HasNonfatalFailure() const;
536 // Returns the elapsed time, in milliseconds.
537 TimeInMillis elapsed_time() const { return elapsed_time_; }
539 // Returns the i-th test part result among all the results. i can range
540 // from 0 to test_property_count() - 1. If i is not in that range, aborts
542 const TestPartResult& GetTestPartResult(int i) const;
544 // Returns the i-th test property. i can range from 0 to
545 // test_property_count() - 1. If i is not in that range, aborts the
547 const TestProperty& GetTestProperty(int i) const;
550 friend class TestInfo;
551 friend class UnitTest;
552 friend class internal::DefaultGlobalTestPartResultReporter;
553 friend class internal::ExecDeathTest;
554 friend class internal::TestResultAccessor;
555 friend class internal::UnitTestImpl;
556 friend class internal::WindowsDeathTest;
558 // Gets the vector of TestPartResults.
559 const std::vector<TestPartResult>& test_part_results() const {
560 return test_part_results_;
563 // Gets the vector of TestProperties.
564 const std::vector<TestProperty>& test_properties() const {
565 return test_properties_;
568 // Sets the elapsed time.
569 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
571 // Adds a test property to the list. The property is validated and may add
572 // a non-fatal failure if invalid (e.g., if it conflicts with reserved
573 // key names). If a property is already recorded for the same key, the
574 // value will be updated, rather than storing multiple values for the same
576 void RecordProperty(const TestProperty& test_property);
578 // Adds a failure if the key is a reserved attribute of Google Test
579 // testcase tags. Returns true if the property is valid.
580 // TODO(russr): Validate attribute names are legal and human readable.
581 static bool ValidateTestProperty(const TestProperty& test_property);
583 // Adds a test part result to the list.
584 void AddTestPartResult(const TestPartResult& test_part_result);
586 // Returns the death test count.
587 int death_test_count() const { return death_test_count_; }
589 // Increments the death test count, returning the new count.
590 int increment_death_test_count() { return ++death_test_count_; }
592 // Clears the test part results.
593 void ClearTestPartResults();
595 // Clears the object.
598 // Protects mutable state of the property vector and of owned
599 // properties, whose values may be updated.
600 internal::Mutex test_properites_mutex_;
602 // The vector of TestPartResults
603 std::vector<TestPartResult> test_part_results_;
604 // The vector of TestProperties
605 std::vector<TestProperty> test_properties_;
606 // Running count of death tests.
607 int death_test_count_;
608 // The elapsed time, in milliseconds.
609 TimeInMillis elapsed_time_;
611 // We disallow copying TestResult.
612 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
613 }; // class TestResult
615 // A TestInfo object stores the following information about a test:
619 // Whether the test should be run
620 // A function pointer that creates the test object when invoked
623 // The constructor of TestInfo registers itself with the UnitTest
624 // singleton such that the RUN_ALL_TESTS() macro knows which tests to
626 class GTEST_API_ TestInfo {
628 // Destructs a TestInfo object. This function is not virtual, so
629 // don't inherit from TestInfo.
632 // Returns the test case name.
633 const char* test_case_name() const { return test_case_name_.c_str(); }
635 // Returns the test name.
636 const char* name() const { return name_.c_str(); }
638 // Returns the name of the parameter type, or NULL if this is not a typed
639 // or a type-parameterized test.
640 const char* type_param() const {
641 if (type_param_.get() != NULL)
642 return type_param_->c_str();
646 // Returns the text representation of the value parameter, or NULL if this
647 // is not a value-parameterized test.
648 const char* value_param() const {
649 if (value_param_.get() != NULL)
650 return value_param_->c_str();
654 // Returns true if this test should run, that is if the test is not disabled
655 // (or it is disabled but the also_run_disabled_tests flag has been specified)
656 // and its full name matches the user-specified filter.
658 // Google Test allows the user to filter the tests by their full names.
659 // The full name of a test Bar in test case Foo is defined as
660 // "Foo.Bar". Only the tests that match the filter will run.
662 // A filter is a colon-separated list of glob (not regex) patterns,
663 // optionally followed by a '-' and a colon-separated list of
664 // negative patterns (tests to exclude). A test is run if it
665 // matches one of the positive patterns and does not match any of
666 // the negative patterns.
668 // For example, *A*:Foo.* is a filter that matches any string that
669 // contains the character 'A' or starts with "Foo.".
670 bool should_run() const { return should_run_; }
672 // Returns the result of the test.
673 const TestResult* result() const { return &result_; }
676 #if GTEST_HAS_DEATH_TEST
677 friend class internal::DefaultDeathTestFactory;
678 #endif // GTEST_HAS_DEATH_TEST
680 friend class TestCase;
681 friend class internal::UnitTestImpl;
682 friend TestInfo* internal::MakeAndRegisterTestInfo(
683 const char* test_case_name, const char* name,
684 const char* type_param,
685 const char* value_param,
686 internal::TypeId fixture_class_id,
687 Test::SetUpTestCaseFunc set_up_tc,
688 Test::TearDownTestCaseFunc tear_down_tc,
689 internal::TestFactoryBase* factory);
691 // Constructs a TestInfo object. The newly constructed instance assumes
692 // ownership of the factory object.
693 TestInfo(const char* test_case_name, const char* name,
694 const char* a_type_param,
695 const char* a_value_param,
696 internal::TypeId fixture_class_id,
697 internal::TestFactoryBase* factory);
699 // Increments the number of death tests encountered in this test so
701 int increment_death_test_count() {
702 return result_.increment_death_test_count();
705 // Creates the test object, runs it, records its result, and then
709 static void ClearTestResult(TestInfo* test_info) {
710 test_info->result_.Clear();
713 // These fields are immutable properties of the test.
714 const std::string test_case_name_; // Test case name
715 const std::string name_; // Test name
716 // Name of the parameter type, or NULL if this is not a typed or a
717 // type-parameterized test.
718 const internal::scoped_ptr<const ::std::string> type_param_;
719 // Text representation of the value parameter, or NULL if this is not a
720 // value-parameterized test.
721 const internal::scoped_ptr<const ::std::string> value_param_;
722 const internal::TypeId fixture_class_id_; // ID of the test fixture class
723 bool should_run_; // True iff this test should run
724 bool is_disabled_; // True iff this test is disabled
725 bool matches_filter_; // True if this test matches the
726 // user-specified filter.
727 internal::TestFactoryBase* const factory_; // The factory that creates
730 // This field is mutable and needs to be reset before running the
731 // test for the second time.
734 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
737 // A test case, which consists of a vector of TestInfos.
739 // TestCase is not copyable.
740 class GTEST_API_ TestCase {
742 // Creates a TestCase with the given name.
744 // TestCase does NOT have a default constructor. Always use this
745 // constructor to create a TestCase object.
749 // name: name of the test case
750 // a_type_param: the name of the test's type parameter, or NULL if
751 // this is not a type-parameterized test.
752 // set_up_tc: pointer to the function that sets up the test case
753 // tear_down_tc: pointer to the function that tears down the test case
754 TestCase(const char* name, const char* a_type_param,
755 Test::SetUpTestCaseFunc set_up_tc,
756 Test::TearDownTestCaseFunc tear_down_tc);
758 // Destructor of TestCase.
761 // Gets the name of the TestCase.
762 const char* name() const { return name_.c_str(); }
764 // Returns the name of the parameter type, or NULL if this is not a
765 // type-parameterized test case.
766 const char* type_param() const {
767 if (type_param_.get() != NULL)
768 return type_param_->c_str();
772 // Returns true if any test in this test case should run.
773 bool should_run() const { return should_run_; }
775 // Gets the number of successful tests in this test case.
776 int successful_test_count() const;
778 // Gets the number of failed tests in this test case.
779 int failed_test_count() const;
781 // Gets the number of disabled tests in this test case.
782 int disabled_test_count() const;
784 // Get the number of tests in this test case that should run.
785 int test_to_run_count() const;
787 // Gets the number of all tests in this test case.
788 int total_test_count() const;
790 // Returns true iff the test case passed.
791 bool Passed() const { return !Failed(); }
793 // Returns true iff the test case failed.
794 bool Failed() const { return failed_test_count() > 0; }
796 // Returns the elapsed time, in milliseconds.
797 TimeInMillis elapsed_time() const { return elapsed_time_; }
799 // Returns the i-th test among all the tests. i can range from 0 to
800 // total_test_count() - 1. If i is not in that range, returns NULL.
801 const TestInfo* GetTestInfo(int i) const;
805 friend class internal::UnitTestImpl;
807 // Gets the (mutable) vector of TestInfos in this TestCase.
808 std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
810 // Gets the (immutable) vector of TestInfos in this TestCase.
811 const std::vector<TestInfo*>& test_info_list() const {
812 return test_info_list_;
815 // Returns the i-th test among all the tests. i can range from 0 to
816 // total_test_count() - 1. If i is not in that range, returns NULL.
817 TestInfo* GetMutableTestInfo(int i);
819 // Sets the should_run member.
820 void set_should_run(bool should) { should_run_ = should; }
822 // Adds a TestInfo to this test case. Will delete the TestInfo upon
823 // destruction of the TestCase object.
824 void AddTestInfo(TestInfo * test_info);
826 // Clears the results of all tests in this test case.
829 // Clears the results of all tests in the given test case.
830 static void ClearTestCaseResult(TestCase* test_case) {
831 test_case->ClearResult();
834 // Runs every test in this TestCase.
837 // Runs SetUpTestCase() for this TestCase. This wrapper is needed
838 // for catching exceptions thrown from SetUpTestCase().
839 void RunSetUpTestCase() { (*set_up_tc_)(); }
841 // Runs TearDownTestCase() for this TestCase. This wrapper is
842 // needed for catching exceptions thrown from TearDownTestCase().
843 void RunTearDownTestCase() { (*tear_down_tc_)(); }
845 // Returns true iff test passed.
846 static bool TestPassed(const TestInfo* test_info) {
847 return test_info->should_run() && test_info->result()->Passed();
850 // Returns true iff test failed.
851 static bool TestFailed(const TestInfo* test_info) {
852 return test_info->should_run() && test_info->result()->Failed();
855 // Returns true iff test is disabled.
856 static bool TestDisabled(const TestInfo* test_info) {
857 return test_info->is_disabled_;
860 // Returns true if the given test should run.
861 static bool ShouldRunTest(const TestInfo* test_info) {
862 return test_info->should_run();
865 // Shuffles the tests in this test case.
866 void ShuffleTests(internal::Random* random);
868 // Restores the test order to before the first shuffle.
869 void UnshuffleTests();
871 // Name of the test case.
873 // Name of the parameter type, or NULL if this is not a typed or a
874 // type-parameterized test.
875 const internal::scoped_ptr<const ::std::string> type_param_;
876 // The vector of TestInfos in their original order. It owns the
877 // elements in the vector.
878 std::vector<TestInfo*> test_info_list_;
879 // Provides a level of indirection for the test list to allow easy
880 // shuffling and restoring the test order. The i-th element in this
881 // vector is the index of the i-th test in the shuffled test list.
882 std::vector<int> test_indices_;
883 // Pointer to the function that sets up the test case.
884 Test::SetUpTestCaseFunc set_up_tc_;
885 // Pointer to the function that tears down the test case.
886 Test::TearDownTestCaseFunc tear_down_tc_;
887 // True iff any test in this test case should run.
889 // Elapsed time, in milliseconds.
890 TimeInMillis elapsed_time_;
892 // We disallow copying TestCases.
893 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
896 // An Environment object is capable of setting up and tearing down an
897 // environment. The user should subclass this to define his own
900 // An Environment object does the set-up and tear-down in virtual
901 // methods SetUp() and TearDown() instead of the constructor and the
904 // 1. You cannot safely throw from a destructor. This is a problem
905 // as in some cases Google Test is used where exceptions are enabled, and
906 // we may want to implement ASSERT_* using exceptions where they are
908 // 2. You cannot use ASSERT_* directly in a constructor or
912 // The d'tor is virtual as we need to subclass Environment.
913 virtual ~Environment() {}
915 // Override this to define how to set up the environment.
916 virtual void SetUp() {}
918 // Override this to define how to tear down the environment.
919 virtual void TearDown() {}
921 // If you see an error about overriding the following function or
922 // about it being private, you have mis-spelled SetUp() as Setup().
923 struct Setup_should_be_spelled_SetUp {};
924 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
927 // The interface for tracing execution of tests. The methods are organized in
928 // the order the corresponding events are fired.
929 class TestEventListener {
931 virtual ~TestEventListener() {}
933 // Fired before any test activity starts.
934 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
936 // Fired before each iteration of tests starts. There may be more than
937 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
938 // index, starting from 0.
939 virtual void OnTestIterationStart(const UnitTest& unit_test,
942 // Fired before environment set-up for each iteration of tests starts.
943 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
945 // Fired after environment set-up for each iteration of tests ends.
946 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
948 // Fired before the test case starts.
949 virtual void OnTestCaseStart(const TestCase& test_case) = 0;
951 // Fired before the test starts.
952 virtual void OnTestStart(const TestInfo& test_info) = 0;
954 // Fired after a failed assertion or a SUCCEED() invocation.
955 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
957 // Fired after the test ends.
958 virtual void OnTestEnd(const TestInfo& test_info) = 0;
960 // Fired after the test case ends.
961 virtual void OnTestCaseEnd(const TestCase& test_case) = 0;
963 // Fired before environment tear-down for each iteration of tests starts.
964 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
966 // Fired after environment tear-down for each iteration of tests ends.
967 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
969 // Fired after each iteration of tests finishes.
970 virtual void OnTestIterationEnd(const UnitTest& unit_test,
973 // Fired after all test activities have ended.
974 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
977 // The convenience class for users who need to override just one or two
978 // methods and are not concerned that a possible change to a signature of
979 // the methods they override will not be caught during the build. For
980 // comments about each method please see the definition of TestEventListener
982 class EmptyTestEventListener : public TestEventListener {
984 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
985 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
986 int /*iteration*/) {}
987 virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}
988 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
989 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
990 virtual void OnTestStart(const TestInfo& /*test_info*/) {}
991 virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}
992 virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
993 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
994 virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
995 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
996 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
997 int /*iteration*/) {}
998 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
1001 // TestEventListeners lets users add listeners to track events in Google Test.
1002 class GTEST_API_ TestEventListeners {
1004 TestEventListeners();
1005 ~TestEventListeners();
1007 // Appends an event listener to the end of the list. Google Test assumes
1008 // the ownership of the listener (i.e. it will delete the listener when
1009 // the test program finishes).
1010 void Append(TestEventListener* listener);
1012 // Removes the given event listener from the list and returns it. It then
1013 // becomes the caller's responsibility to delete the listener. Returns
1014 // NULL if the listener is not found in the list.
1015 TestEventListener* Release(TestEventListener* listener);
1017 // Returns the standard listener responsible for the default console
1018 // output. Can be removed from the listeners list to shut down default
1019 // console output. Note that removing this object from the listener list
1020 // with Release transfers its ownership to the caller and makes this
1021 // function return NULL the next time.
1022 TestEventListener* default_result_printer() const {
1023 return default_result_printer_;
1026 // Returns the standard listener responsible for the default XML output
1027 // controlled by the --gtest_output=xml flag. Can be removed from the
1028 // listeners list by users who want to shut down the default XML output
1029 // controlled by this flag and substitute it with custom one. Note that
1030 // removing this object from the listener list with Release transfers its
1031 // ownership to the caller and makes this function return NULL the next
1033 TestEventListener* default_xml_generator() const {
1034 return default_xml_generator_;
1038 friend class TestCase;
1039 friend class TestInfo;
1040 friend class internal::DefaultGlobalTestPartResultReporter;
1041 friend class internal::NoExecDeathTest;
1042 friend class internal::TestEventListenersAccessor;
1043 friend class internal::UnitTestImpl;
1045 // Returns repeater that broadcasts the TestEventListener events to all
1047 TestEventListener* repeater();
1049 // Sets the default_result_printer attribute to the provided listener.
1050 // The listener is also added to the listener list and previous
1051 // default_result_printer is removed from it and deleted. The listener can
1052 // also be NULL in which case it will not be added to the list. Does
1053 // nothing if the previous and the current listener objects are the same.
1054 void SetDefaultResultPrinter(TestEventListener* listener);
1056 // Sets the default_xml_generator attribute to the provided listener. The
1057 // listener is also added to the listener list and previous
1058 // default_xml_generator is removed from it and deleted. The listener can
1059 // also be NULL in which case it will not be added to the list. Does
1060 // nothing if the previous and the current listener objects are the same.
1061 void SetDefaultXmlGenerator(TestEventListener* listener);
1063 // Controls whether events will be forwarded by the repeater to the
1064 // listeners in the list.
1065 bool EventForwardingEnabled() const;
1066 void SuppressEventForwarding();
1068 // The actual list of listeners.
1069 internal::TestEventRepeater* repeater_;
1070 // Listener responsible for the standard result output.
1071 TestEventListener* default_result_printer_;
1072 // Listener responsible for the creation of the XML output file.
1073 TestEventListener* default_xml_generator_;
1075 // We disallow copying TestEventListeners.
1076 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
1079 // A UnitTest consists of a vector of TestCases.
1081 // This is a singleton class. The only instance of UnitTest is
1082 // created when UnitTest::GetInstance() is first called. This
1083 // instance is never deleted.
1085 // UnitTest is not copyable.
1087 // This class is thread-safe as long as the methods are called
1088 // according to their specification.
1089 class GTEST_API_ UnitTest {
1091 // Gets the singleton UnitTest object. The first time this method
1092 // is called, a UnitTest object is constructed and returned.
1093 // Consecutive calls will return the same object.
1094 static UnitTest* GetInstance();
1096 // Runs all tests in this UnitTest object and prints the result.
1097 // Returns 0 if successful, or 1 otherwise.
1099 // This method can only be called from the main thread.
1101 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1102 int Run() GTEST_MUST_USE_RESULT_;
1104 // Returns the working directory when the first TEST() or TEST_F()
1105 // was executed. The UnitTest object owns the string.
1106 const char* original_working_dir() const;
1108 // Returns the TestCase object for the test that's currently running,
1109 // or NULL if no test is running.
1110 const TestCase* current_test_case() const
1111 GTEST_LOCK_EXCLUDED_(mutex_);
1113 // Returns the TestInfo object for the test that's currently running,
1114 // or NULL if no test is running.
1115 const TestInfo* current_test_info() const
1116 GTEST_LOCK_EXCLUDED_(mutex_);
1118 // Returns the random seed used at the start of the current test run.
1119 int random_seed() const;
1121 #if GTEST_HAS_PARAM_TEST
1122 // Returns the ParameterizedTestCaseRegistry object used to keep track of
1123 // value-parameterized tests and instantiate and register them.
1125 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1126 internal::ParameterizedTestCaseRegistry& parameterized_test_registry()
1127 GTEST_LOCK_EXCLUDED_(mutex_);
1128 #endif // GTEST_HAS_PARAM_TEST
1130 // Gets the number of successful test cases.
1131 int successful_test_case_count() const;
1133 // Gets the number of failed test cases.
1134 int failed_test_case_count() const;
1136 // Gets the number of all test cases.
1137 int total_test_case_count() const;
1139 // Gets the number of all test cases that contain at least one test
1141 int test_case_to_run_count() const;
1143 // Gets the number of successful tests.
1144 int successful_test_count() const;
1146 // Gets the number of failed tests.
1147 int failed_test_count() const;
1149 // Gets the number of disabled tests.
1150 int disabled_test_count() const;
1152 // Gets the number of all tests.
1153 int total_test_count() const;
1155 // Gets the number of tests that should run.
1156 int test_to_run_count() const;
1158 // Gets the time of the test program start, in ms from the start of the
1160 TimeInMillis start_timestamp() const;
1162 // Gets the elapsed time, in milliseconds.
1163 TimeInMillis elapsed_time() const;
1165 // Returns true iff the unit test passed (i.e. all test cases passed).
1166 bool Passed() const;
1168 // Returns true iff the unit test failed (i.e. some test case failed
1169 // or something outside of all tests failed).
1170 bool Failed() const;
1172 // Gets the i-th test case among all the test cases. i can range from 0 to
1173 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1174 const TestCase* GetTestCase(int i) const;
1176 // Returns the list of event listeners that can be used to track events
1177 // inside Google Test.
1178 TestEventListeners& listeners();
1181 // Registers and returns a global test environment. When a test
1182 // program is run, all global test environments will be set-up in
1183 // the order they were registered. After all tests in the program
1184 // have finished, all global test environments will be torn-down in
1185 // the *reverse* order they were registered.
1187 // The UnitTest object takes ownership of the given environment.
1189 // This method can only be called from the main thread.
1190 Environment* AddEnvironment(Environment* env);
1192 // Adds a TestPartResult to the current TestResult object. All
1193 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
1194 // eventually call this to report their results. The user code
1195 // should use the assertion macros instead of calling this directly.
1196 void AddTestPartResult(TestPartResult::Type result_type,
1197 const char* file_name,
1199 const std::string& message,
1200 const std::string& os_stack_trace)
1201 GTEST_LOCK_EXCLUDED_(mutex_);
1203 // Adds a TestProperty to the current TestResult object. If the result already
1204 // contains a property with the same key, the value will be updated.
1205 void RecordPropertyForCurrentTest(const char* key, const char* value);
1207 // Gets the i-th test case among all the test cases. i can range from 0 to
1208 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1209 TestCase* GetMutableTestCase(int i);
1211 // Accessors for the implementation object.
1212 internal::UnitTestImpl* impl() { return impl_; }
1213 const internal::UnitTestImpl* impl() const { return impl_; }
1215 // These classes and funcions are friends as they need to access private
1216 // members of UnitTest.
1218 friend class internal::AssertHelper;
1219 friend class internal::ScopedTrace;
1220 friend Environment* AddGlobalTestEnvironment(Environment* env);
1221 friend internal::UnitTestImpl* internal::GetUnitTestImpl();
1222 friend void internal::ReportFailureInUnknownLocation(
1223 TestPartResult::Type result_type,
1224 const std::string& message);
1226 // Creates an empty UnitTest.
1230 virtual ~UnitTest();
1232 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
1233 // Google Test trace stack.
1234 void PushGTestTrace(const internal::TraceInfo& trace)
1235 GTEST_LOCK_EXCLUDED_(mutex_);
1237 // Pops a trace from the per-thread Google Test trace stack.
1238 void PopGTestTrace()
1239 GTEST_LOCK_EXCLUDED_(mutex_);
1241 // Protects mutable state in *impl_. This is mutable as some const
1242 // methods need to lock it too.
1243 mutable internal::Mutex mutex_;
1245 // Opaque implementation object. This field is never changed once
1246 // the object is constructed. We don't mark it as const here, as
1247 // doing so will cause a warning in the constructor of UnitTest.
1248 // Mutable state in *impl_ is protected by mutex_.
1249 internal::UnitTestImpl* impl_;
1251 // We disallow copying UnitTest.
1252 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
1255 // A convenient wrapper for adding an environment for the test
1258 // You should call this before RUN_ALL_TESTS() is called, probably in
1259 // main(). If you use gtest_main, you need to call this before main()
1260 // starts for it to take effect. For example, you can define a global
1261 // variable like this:
1263 // testing::Environment* const foo_env =
1264 // testing::AddGlobalTestEnvironment(new FooEnvironment);
1266 // However, we strongly recommend you to write your own main() and
1267 // call AddGlobalTestEnvironment() there, as relying on initialization
1268 // of global variables makes the code harder to read and may cause
1269 // problems when you register multiple environments from different
1270 // translation units and the environments have dependencies among them
1271 // (remember that the compiler doesn't guarantee the order in which
1272 // global variables from different translation units are initialized).
1273 inline Environment* AddGlobalTestEnvironment(Environment* env) {
1274 return UnitTest::GetInstance()->AddEnvironment(env);
1277 // Initializes Google Test. This must be called before calling
1278 // RUN_ALL_TESTS(). In particular, it parses a command line for the
1279 // flags that Google Test recognizes. Whenever a Google Test flag is
1280 // seen, it is removed from argv, and *argc is decremented.
1282 // No value is returned. Instead, the Google Test flag variables are
1285 // Calling the function for the second time has no user-visible effect.
1286 GTEST_API_ void InitGoogleTest(int* argc, char** argv);
1288 // This overloaded version can be used in Windows programs compiled in
1290 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
1292 namespace internal {
1294 // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
1295 // value of type ToPrint that is an operand of a comparison assertion
1296 // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
1297 // the comparison, and is used to help determine the best way to
1298 // format the value. In particular, when the value is a C string
1299 // (char pointer) and the other operand is an STL string object, we
1300 // want to format the C string as a string, since we know it is
1301 // compared by value with the string object. If the value is a char
1302 // pointer but the other operand is not an STL string object, we don't
1303 // know whether the pointer is supposed to point to a NUL-terminated
1304 // string, and thus want to print it as a pointer to be safe.
1306 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1308 // The default case.
1309 template <typename ToPrint, typename OtherOperand>
1310 class FormatForComparison {
1312 static ::std::string Format(const ToPrint& value) {
1313 return ::testing::PrintToString(value);
1318 template <typename ToPrint, size_t N, typename OtherOperand>
1319 class FormatForComparison<ToPrint[N], OtherOperand> {
1321 static ::std::string Format(const ToPrint* value) {
1322 return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
1326 // By default, print C string as pointers to be safe, as we don't know
1327 // whether they actually point to a NUL-terminated string.
1329 #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
1330 template <typename OtherOperand> \
1331 class FormatForComparison<CharType*, OtherOperand> { \
1333 static ::std::string Format(CharType* value) { \
1334 return ::testing::PrintToString(static_cast<const void*>(value)); \
1338 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
1339 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
1340 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
1341 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
1343 #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
1345 // If a C string is compared with an STL string object, we know it's meant
1346 // to point to a NUL-terminated string, and thus can print it as a string.
1348 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
1350 class FormatForComparison<CharType*, OtherStringType> { \
1352 static ::std::string Format(CharType* value) { \
1353 return ::testing::PrintToString(value); \
1357 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
1358 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
1360 #if GTEST_HAS_GLOBAL_STRING
1361 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string);
1362 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string);
1365 #if GTEST_HAS_GLOBAL_WSTRING
1366 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring);
1367 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring);
1370 #if GTEST_HAS_STD_WSTRING
1371 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
1372 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
1375 #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
1377 // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
1378 // operand to be used in a failure message. The type (but not value)
1379 // of the other operand may affect the format. This allows us to
1380 // print a char* as a raw pointer when it is compared against another
1381 // char* or void*, and print it as a C string when it is compared
1382 // against an std::string object, for example.
1384 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1385 template <typename T1, typename T2>
1386 std::string FormatForComparisonFailureMessage(
1387 const T1& value, const T2& /* other_operand */) {
1388 return FormatForComparison<T1, T2>::Format(value);
1391 // The helper function for {ASSERT|EXPECT}_EQ.
1392 template <typename T1, typename T2>
1393 AssertionResult CmpHelperEQ(const char* expected_expression,
1394 const char* actual_expression,
1398 # pragma warning(push) // Saves the current warning state.
1399 # pragma warning(disable:4389) // Temporarily disables warning on
1400 // signed/unsigned mismatch.
1403 if (expected == actual) {
1404 return AssertionSuccess();
1408 # pragma warning(pop) // Restores the warning state.
1411 return EqFailure(expected_expression,
1413 FormatForComparisonFailureMessage(expected, actual),
1414 FormatForComparisonFailureMessage(actual, expected),
1418 // With this overloaded version, we allow anonymous enums to be used
1419 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
1420 // can be implicitly cast to BiggestInt.
1421 GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression,
1422 const char* actual_expression,
1423 BiggestInt expected,
1426 // The helper class for {ASSERT|EXPECT}_EQ. The template argument
1427 // lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
1428 // is a null pointer literal. The following default implementation is
1429 // for lhs_is_null_literal being false.
1430 template <bool lhs_is_null_literal>
1433 // This templatized version is for the general case.
1434 template <typename T1, typename T2>
1435 static AssertionResult Compare(const char* expected_expression,
1436 const char* actual_expression,
1439 return CmpHelperEQ(expected_expression, actual_expression, expected,
1443 // With this overloaded version, we allow anonymous enums to be used
1444 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
1445 // enums can be implicitly cast to BiggestInt.
1447 // Even though its body looks the same as the above version, we
1448 // cannot merge the two, as it will make anonymous enums unhappy.
1449 static AssertionResult Compare(const char* expected_expression,
1450 const char* actual_expression,
1451 BiggestInt expected,
1452 BiggestInt actual) {
1453 return CmpHelperEQ(expected_expression, actual_expression, expected,
1458 // This specialization is used when the first argument to ASSERT_EQ()
1459 // is a null pointer literal, like NULL, false, or 0.
1461 class EqHelper<true> {
1463 // We define two overloaded versions of Compare(). The first
1464 // version will be picked when the second argument to ASSERT_EQ() is
1465 // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
1466 // EXPECT_EQ(false, a_bool).
1467 template <typename T1, typename T2>
1468 static AssertionResult Compare(
1469 const char* expected_expression,
1470 const char* actual_expression,
1473 // The following line prevents this overload from being considered if T2
1474 // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr)
1475 // expands to Compare("", "", NULL, my_ptr), which requires a conversion
1476 // to match the Secret* in the other overload, which would otherwise make
1477 // this template match better.
1478 typename EnableIf<!is_pointer<T2>::value>::type* = 0) {
1479 return CmpHelperEQ(expected_expression, actual_expression, expected,
1483 // This version will be picked when the second argument to ASSERT_EQ() is a
1484 // pointer, e.g. ASSERT_EQ(NULL, a_pointer).
1485 template <typename T>
1486 static AssertionResult Compare(
1487 const char* expected_expression,
1488 const char* actual_expression,
1489 // We used to have a second template parameter instead of Secret*. That
1490 // template parameter would deduce to 'long', making this a better match
1491 // than the first overload even without the first overload's EnableIf.
1492 // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to
1493 // non-pointer argument" (even a deduced integral argument), so the old
1494 // implementation caused warnings in user code.
1495 Secret* /* expected (NULL) */,
1497 // We already know that 'expected' is a null pointer.
1498 return CmpHelperEQ(expected_expression, actual_expression,
1499 static_cast<T*>(NULL), actual);
1503 // A macro for implementing the helper functions needed to implement
1504 // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
1507 // For each templatized helper function, we also define an overloaded
1508 // version for BiggestInt in order to reduce code bloat and allow
1509 // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
1512 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1513 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1514 template <typename T1, typename T2>\
1515 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1516 const T1& val1, const T2& val2) {\
1517 if (val1 op val2) {\
1518 return AssertionSuccess();\
1520 return AssertionFailure() \
1521 << "Expected: (" << expr1 << ") " #op " (" << expr2\
1522 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1523 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1526 GTEST_API_ AssertionResult CmpHelper##op_name(\
1527 const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
1529 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1531 // Implements the helper function for {ASSERT|EXPECT}_NE
1532 GTEST_IMPL_CMP_HELPER_(NE, !=);
1533 // Implements the helper function for {ASSERT|EXPECT}_LE
1534 GTEST_IMPL_CMP_HELPER_(LE, <=);
1535 // Implements the helper function for {ASSERT|EXPECT}_LT
1536 GTEST_IMPL_CMP_HELPER_(LT, <);
1537 // Implements the helper function for {ASSERT|EXPECT}_GE
1538 GTEST_IMPL_CMP_HELPER_(GE, >=);
1539 // Implements the helper function for {ASSERT|EXPECT}_GT
1540 GTEST_IMPL_CMP_HELPER_(GT, >);
1542 #undef GTEST_IMPL_CMP_HELPER_
1544 // The helper function for {ASSERT|EXPECT}_STREQ.
1546 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1547 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression,
1548 const char* actual_expression,
1549 const char* expected,
1550 const char* actual);
1552 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1554 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1555 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1556 const char* actual_expression,
1557 const char* expected,
1558 const char* actual);
1560 // The helper function for {ASSERT|EXPECT}_STRNE.
1562 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1563 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1564 const char* s2_expression,
1568 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1570 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1571 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1572 const char* s2_expression,
1577 // Helper function for *_STREQ on wide strings.
1579 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1580 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression,
1581 const char* actual_expression,
1582 const wchar_t* expected,
1583 const wchar_t* actual);
1585 // Helper function for *_STRNE on wide strings.
1587 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1588 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1589 const char* s2_expression,
1593 } // namespace internal
1595 // IsSubstring() and IsNotSubstring() are intended to be used as the
1596 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
1597 // themselves. They check whether needle is a substring of haystack
1598 // (NULL is considered a substring of itself only), and return an
1599 // appropriate error message when they fail.
1601 // The {needle,haystack}_expr arguments are the stringified
1602 // expressions that generated the two real arguments.
1603 GTEST_API_ AssertionResult IsSubstring(
1604 const char* needle_expr, const char* haystack_expr,
1605 const char* needle, const char* haystack);
1606 GTEST_API_ AssertionResult IsSubstring(
1607 const char* needle_expr, const char* haystack_expr,
1608 const wchar_t* needle, const wchar_t* haystack);
1609 GTEST_API_ AssertionResult IsNotSubstring(
1610 const char* needle_expr, const char* haystack_expr,
1611 const char* needle, const char* haystack);
1612 GTEST_API_ AssertionResult IsNotSubstring(
1613 const char* needle_expr, const char* haystack_expr,
1614 const wchar_t* needle, const wchar_t* haystack);
1615 GTEST_API_ AssertionResult IsSubstring(
1616 const char* needle_expr, const char* haystack_expr,
1617 const ::std::string& needle, const ::std::string& haystack);
1618 GTEST_API_ AssertionResult IsNotSubstring(
1619 const char* needle_expr, const char* haystack_expr,
1620 const ::std::string& needle, const ::std::string& haystack);
1622 #if GTEST_HAS_STD_WSTRING
1623 GTEST_API_ AssertionResult IsSubstring(
1624 const char* needle_expr, const char* haystack_expr,
1625 const ::std::wstring& needle, const ::std::wstring& haystack);
1626 GTEST_API_ AssertionResult IsNotSubstring(
1627 const char* needle_expr, const char* haystack_expr,
1628 const ::std::wstring& needle, const ::std::wstring& haystack);
1629 #endif // GTEST_HAS_STD_WSTRING
1631 namespace internal {
1633 // Helper template function for comparing floating-points.
1635 // Template parameter:
1637 // RawType: the raw floating-point type (either float or double)
1639 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1640 template <typename RawType>
1641 AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression,
1642 const char* actual_expression,
1645 const FloatingPoint<RawType> lhs(expected), rhs(actual);
1647 if (lhs.AlmostEquals(rhs)) {
1648 return AssertionSuccess();
1651 ::std::stringstream expected_ss;
1652 expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1655 ::std::stringstream actual_ss;
1656 actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1659 return EqFailure(expected_expression,
1661 StringStreamToString(&expected_ss),
1662 StringStreamToString(&actual_ss),
1666 // Helper function for implementing ASSERT_NEAR.
1668 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1669 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
1671 const char* abs_error_expr,
1676 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1677 // A class that enables one to stream messages to assertion macros
1678 class GTEST_API_ AssertHelper {
1681 AssertHelper(TestPartResult::Type type,
1684 const char* message);
1687 // Message assignment is a semantic trick to enable assertion
1688 // streaming; see the GTEST_MESSAGE_ macro below.
1689 void operator=(const Message& message) const;
1692 // We put our data in a struct so that the size of the AssertHelper class can
1693 // be as small as possible. This is important because gcc is incapable of
1694 // re-using stack space even for temporary variables, so every EXPECT_EQ
1695 // reserves stack space for another AssertHelper.
1696 struct AssertHelperData {
1697 AssertHelperData(TestPartResult::Type t,
1698 const char* srcfile,
1701 : type(t), file(srcfile), line(line_num), message(msg) { }
1703 TestPartResult::Type const type;
1704 const char* const file;
1706 std::string const message;
1709 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
1712 AssertHelperData* const data_;
1714 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
1717 } // namespace internal
1719 #if GTEST_HAS_PARAM_TEST
1720 // The pure interface class that all value-parameterized tests inherit from.
1721 // A value-parameterized class must inherit from both ::testing::Test and
1722 // ::testing::WithParamInterface. In most cases that just means inheriting
1723 // from ::testing::TestWithParam, but more complicated test hierarchies
1724 // may need to inherit from Test and WithParamInterface at different levels.
1726 // This interface has support for accessing the test parameter value via
1727 // the GetParam() method.
1729 // Use it with one of the parameter generator defining functions, like Range(),
1730 // Values(), ValuesIn(), Bool(), and Combine().
1732 // class FooTest : public ::testing::TestWithParam<int> {
1735 // // Can use GetParam() here.
1737 // virtual ~FooTest() {
1738 // // Can use GetParam() here.
1740 // virtual void SetUp() {
1741 // // Can use GetParam() here.
1743 // virtual void TearDown {
1744 // // Can use GetParam() here.
1747 // TEST_P(FooTest, DoesBar) {
1748 // // Can use GetParam() method here.
1750 // ASSERT_TRUE(foo.DoesBar(GetParam()));
1752 // INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
1754 template <typename T>
1755 class WithParamInterface {
1757 typedef T ParamType;
1758 virtual ~WithParamInterface() {}
1760 // The current parameter value. Is also available in the test fixture's
1761 // constructor. This member function is non-static, even though it only
1762 // references static data, to reduce the opportunity for incorrect uses
1763 // like writing 'WithParamInterface<bool>::GetParam()' for a test that
1764 // uses a fixture whose parameter type is int.
1765 const ParamType& GetParam() const { return *parameter_; }
1768 // Sets parameter value. The caller is responsible for making sure the value
1769 // remains alive and unchanged throughout the current test.
1770 static void SetParam(const ParamType* parameter) {
1771 parameter_ = parameter;
1774 // Static value used for accessing parameter during a test lifetime.
1775 static const ParamType* parameter_;
1777 // TestClass must be a subclass of WithParamInterface<T> and Test.
1778 template <class TestClass> friend class internal::ParameterizedTestFactory;
1781 template <typename T>
1782 const T* WithParamInterface<T>::parameter_ = NULL;
1784 // Most value-parameterized classes can ignore the existence of
1785 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
1787 template <typename T>
1788 class TestWithParam : public Test, public WithParamInterface<T> {
1791 #endif // GTEST_HAS_PARAM_TEST
1793 // Macros for indicating success/failure in test code.
1795 // ADD_FAILURE unconditionally adds a failure to the current test.
1796 // SUCCEED generates a success - it doesn't automatically make the
1797 // current test successful, as a test is only successful when it has
1800 // EXPECT_* verifies that a certain condition is satisfied. If not,
1801 // it behaves like ADD_FAILURE. In particular:
1803 // EXPECT_TRUE verifies that a Boolean condition is true.
1804 // EXPECT_FALSE verifies that a Boolean condition is false.
1806 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
1807 // that they will also abort the current function on failure. People
1808 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
1809 // writing data-driven tests often find themselves using ADD_FAILURE
1810 // and EXPECT_* more.
1812 // Generates a nonfatal failure with a generic message.
1813 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
1815 // Generates a nonfatal failure at the given source file location with
1816 // a generic message.
1817 #define ADD_FAILURE_AT(file, line) \
1818 GTEST_MESSAGE_AT_(file, line, "Failed", \
1819 ::testing::TestPartResult::kNonFatalFailure)
1821 // Generates a fatal failure with a generic message.
1822 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
1824 // Define this macro to 1 to omit the definition of FAIL(), which is a
1825 // generic name and clashes with some other libraries.
1826 #if !GTEST_DONT_DEFINE_FAIL
1827 # define FAIL() GTEST_FAIL()
1830 // Generates a success with a generic message.
1831 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
1833 // Define this macro to 1 to omit the definition of SUCCEED(), which
1834 // is a generic name and clashes with some other libraries.
1835 #if !GTEST_DONT_DEFINE_SUCCEED
1836 # define SUCCEED() GTEST_SUCCEED()
1839 // Macros for testing exceptions.
1841 // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
1842 // Tests that the statement throws the expected exception.
1843 // * {ASSERT|EXPECT}_NO_THROW(statement):
1844 // Tests that the statement doesn't throw any exception.
1845 // * {ASSERT|EXPECT}_ANY_THROW(statement):
1846 // Tests that the statement throws an exception.
1848 #define EXPECT_THROW(statement, expected_exception) \
1849 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
1850 #define EXPECT_NO_THROW(statement) \
1851 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1852 #define EXPECT_ANY_THROW(statement) \
1853 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1854 #define ASSERT_THROW(statement, expected_exception) \
1855 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
1856 #define ASSERT_NO_THROW(statement) \
1857 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
1858 #define ASSERT_ANY_THROW(statement) \
1859 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
1861 // Boolean assertions. Condition can be either a Boolean expression or an
1862 // AssertionResult. For more information on how to use AssertionResult with
1863 // these macros see comments on that class.
1864 #define EXPECT_TRUE(condition) \
1865 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1866 GTEST_NONFATAL_FAILURE_)
1867 #define EXPECT_FALSE(condition) \
1868 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1869 GTEST_NONFATAL_FAILURE_)
1870 #define ASSERT_TRUE(condition) \
1871 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1872 GTEST_FATAL_FAILURE_)
1873 #define ASSERT_FALSE(condition) \
1874 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1875 GTEST_FATAL_FAILURE_)
1877 // Includes the auto-generated header that implements a family of
1878 // generic predicate assertion macros.
1879 #include "gtest/gtest_pred_impl.h"
1881 // Macros for testing equalities and inequalities.
1883 // * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual
1884 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
1885 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
1886 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
1887 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
1888 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
1890 // When they are not, Google Test prints both the tested expressions and
1891 // their actual values. The values must be compatible built-in types,
1892 // or you will get a compiler error. By "compatible" we mean that the
1893 // values can be compared by the respective operator.
1897 // 1. It is possible to make a user-defined type work with
1898 // {ASSERT|EXPECT}_??(), but that requires overloading the
1899 // comparison operators and is thus discouraged by the Google C++
1900 // Usage Guide. Therefore, you are advised to use the
1901 // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
1904 // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
1905 // pointers (in particular, C strings). Therefore, if you use it
1906 // with two C strings, you are testing how their locations in memory
1907 // are related, not how their content is related. To compare two C
1908 // strings by content, use {ASSERT|EXPECT}_STR*().
1910 // 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to
1911 // {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you
1912 // what the actual value is when it fails, and similarly for the
1913 // other comparisons.
1915 // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
1916 // evaluate their arguments, which is undefined.
1918 // 5. These macros evaluate their arguments exactly once.
1922 // EXPECT_NE(5, Foo());
1923 // EXPECT_EQ(NULL, a_pointer);
1924 // ASSERT_LT(i, array_size);
1925 // ASSERT_GT(records.size(), 0) << "There is no record left.";
1927 #define EXPECT_EQ(expected, actual) \
1928 EXPECT_PRED_FORMAT2(::testing::internal:: \
1929 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
1931 #define EXPECT_NE(expected, actual) \
1932 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual)
1933 #define EXPECT_LE(val1, val2) \
1934 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1935 #define EXPECT_LT(val1, val2) \
1936 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1937 #define EXPECT_GE(val1, val2) \
1938 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1939 #define EXPECT_GT(val1, val2) \
1940 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1942 #define GTEST_ASSERT_EQ(expected, actual) \
1943 ASSERT_PRED_FORMAT2(::testing::internal:: \
1944 EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
1946 #define GTEST_ASSERT_NE(val1, val2) \
1947 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
1948 #define GTEST_ASSERT_LE(val1, val2) \
1949 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1950 #define GTEST_ASSERT_LT(val1, val2) \
1951 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1952 #define GTEST_ASSERT_GE(val1, val2) \
1953 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1954 #define GTEST_ASSERT_GT(val1, val2) \
1955 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1957 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
1958 // ASSERT_XY(), which clashes with some users' own code.
1960 #if !GTEST_DONT_DEFINE_ASSERT_EQ
1961 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
1964 #if !GTEST_DONT_DEFINE_ASSERT_NE
1965 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
1968 #if !GTEST_DONT_DEFINE_ASSERT_LE
1969 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
1972 #if !GTEST_DONT_DEFINE_ASSERT_LT
1973 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
1976 #if !GTEST_DONT_DEFINE_ASSERT_GE
1977 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
1980 #if !GTEST_DONT_DEFINE_ASSERT_GT
1981 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
1984 // C-string Comparisons. All tests treat NULL and any non-NULL string
1985 // as different. Two NULLs are equal.
1987 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
1988 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
1989 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
1990 // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
1992 // For wide or narrow string objects, you can use the
1993 // {ASSERT|EXPECT}_??() macros.
1995 // Don't depend on the order in which the arguments are evaluated,
1996 // which is undefined.
1998 // These macros evaluate their arguments exactly once.
2000 #define EXPECT_STREQ(expected, actual) \
2001 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
2002 #define EXPECT_STRNE(s1, s2) \
2003 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2004 #define EXPECT_STRCASEEQ(expected, actual) \
2005 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
2006 #define EXPECT_STRCASENE(s1, s2)\
2007 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2009 #define ASSERT_STREQ(expected, actual) \
2010 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
2011 #define ASSERT_STRNE(s1, s2) \
2012 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2013 #define ASSERT_STRCASEEQ(expected, actual) \
2014 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
2015 #define ASSERT_STRCASENE(s1, s2)\
2016 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2018 // Macros for comparing floating-point numbers.
2020 // * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual):
2021 // Tests that two float values are almost equal.
2022 // * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual):
2023 // Tests that two double values are almost equal.
2024 // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
2025 // Tests that v1 and v2 are within the given distance to each other.
2027 // Google Test uses ULP-based comparison to automatically pick a default
2028 // error bound that is appropriate for the operands. See the
2029 // FloatingPoint template class in gtest-internal.h if you are
2030 // interested in the implementation details.
2032 #define EXPECT_FLOAT_EQ(expected, actual)\
2033 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2036 #define EXPECT_DOUBLE_EQ(expected, actual)\
2037 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2040 #define ASSERT_FLOAT_EQ(expected, actual)\
2041 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2044 #define ASSERT_DOUBLE_EQ(expected, actual)\
2045 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2048 #define EXPECT_NEAR(val1, val2, abs_error)\
2049 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2050 val1, val2, abs_error)
2052 #define ASSERT_NEAR(val1, val2, abs_error)\
2053 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2054 val1, val2, abs_error)
2056 // These predicate format functions work on floating-point values, and
2057 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
2059 // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
2061 // Asserts that val1 is less than, or almost equal to, val2. Fails
2062 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2063 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
2064 float val1, float val2);
2065 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
2066 double val1, double val2);
2069 #if GTEST_OS_WINDOWS
2071 // Macros that test for HRESULT failure and success, these are only useful
2072 // on Windows, and rely on Windows SDK macros and APIs to compile.
2074 // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
2076 // When expr unexpectedly fails or succeeds, Google Test prints the
2077 // expected result and the actual result with both a human-readable
2078 // string representation of the error, if available, as well as the
2080 # define EXPECT_HRESULT_SUCCEEDED(expr) \
2081 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2083 # define ASSERT_HRESULT_SUCCEEDED(expr) \
2084 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2086 # define EXPECT_HRESULT_FAILED(expr) \
2087 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2089 # define ASSERT_HRESULT_FAILED(expr) \
2090 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2092 #endif // GTEST_OS_WINDOWS
2094 // Macros that execute statement and check that it doesn't generate new fatal
2095 // failures in the current thread.
2097 // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
2101 // EXPECT_NO_FATAL_FAILURE(Process());
2102 // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
2104 #define ASSERT_NO_FATAL_FAILURE(statement) \
2105 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
2106 #define EXPECT_NO_FATAL_FAILURE(statement) \
2107 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
2109 // Causes a trace (including the source file path, the current line
2110 // number, and the given message) to be included in every test failure
2111 // message generated by code in the current scope. The effect is
2112 // undone when the control leaves the current scope.
2114 // The message argument can be anything streamable to std::ostream.
2116 // In the implementation, we include the current line number as part
2117 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
2118 // to appear in the same block - as long as they are on different
2120 #define SCOPED_TRACE(message) \
2121 ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
2122 __FILE__, __LINE__, ::testing::Message() << (message))
2124 // Compile-time assertion for type equality.
2125 // StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are
2126 // the same type. The value it returns is not interesting.
2128 // Instead of making StaticAssertTypeEq a class template, we make it a
2129 // function template that invokes a helper class template. This
2130 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
2131 // defining objects of that type.
2135 // When used inside a method of a class template,
2136 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
2137 // instantiated. For example, given:
2139 // template <typename T> class Foo {
2141 // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
2146 // void Test1() { Foo<bool> foo; }
2148 // will NOT generate a compiler error, as Foo<bool>::Bar() is never
2149 // actually instantiated. Instead, you need:
2151 // void Test2() { Foo<bool> foo; foo.Bar(); }
2153 // to cause a compiler error.
2154 template <typename T1, typename T2>
2155 bool StaticAssertTypeEq() {
2156 (void)internal::StaticAssertTypeEqHelper<T1, T2>();
2162 // The first parameter is the name of the test case, and the second
2163 // parameter is the name of the test within the test case.
2165 // The convention is to end the test case name with "Test". For
2166 // example, a test case for the Foo class can be named FooTest.
2168 // The user should put his test code between braces after using this
2171 // TEST(FooTest, InitializesCorrectly) {
2173 // EXPECT_TRUE(foo.StatusIsOK());
2176 // Note that we call GetTestTypeId() instead of GetTypeId<
2177 // ::testing::Test>() here to get the type ID of testing::Test. This
2178 // is to work around a suspected linker bug when using Google Test as
2179 // a framework on Mac OS X. The bug causes GetTypeId<
2180 // ::testing::Test>() to return different values depending on whether
2181 // the call is from the Google Test framework itself or from user test
2182 // code. GetTestTypeId() is guaranteed to always return the same
2183 // value, as it always calls GetTypeId<>() from the Google Test
2185 #define GTEST_TEST(test_case_name, test_name)\
2186 GTEST_TEST_(test_case_name, test_name, \
2187 ::testing::Test, ::testing::internal::GetTestTypeId())
2189 // Define this macro to 1 to omit the definition of TEST(), which
2190 // is a generic name and clashes with some other libraries.
2191 #if !GTEST_DONT_DEFINE_TEST
2192 # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
2195 // Defines a test that uses a test fixture.
2197 // The first parameter is the name of the test fixture class, which
2198 // also doubles as the test case name. The second parameter is the
2199 // name of the test within the test case.
2201 // A test fixture class must be declared earlier. The user should put
2202 // his test code between braces after using this macro. Example:
2204 // class FooTest : public testing::Test {
2206 // virtual void SetUp() { b_.AddElement(3); }
2212 // TEST_F(FooTest, InitializesCorrectly) {
2213 // EXPECT_TRUE(a_.StatusIsOK());
2216 // TEST_F(FooTest, ReturnsElementCountCorrectly) {
2217 // EXPECT_EQ(0, a_.size());
2218 // EXPECT_EQ(1, b_.size());
2221 #define TEST_F(test_fixture, test_name)\
2222 GTEST_TEST_(test_fixture, test_name, test_fixture, \
2223 ::testing::internal::GetTypeId<test_fixture>())
2225 // Use this macro in main() to run all tests. It returns 0 if all
2226 // tests are successful, or 1 otherwise.
2228 // RUN_ALL_TESTS() should be invoked after the command line has been
2229 // parsed by InitGoogleTest().
2231 #define RUN_ALL_TESTS()\
2232 (::testing::UnitTest::GetInstance()->Run())
2234 } // namespace testing
2236 #endif // GTEST_INCLUDE_GTEST_GTEST_H_