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.
31 // The Google C++ Testing and Mocking Framework (Google Test)
33 // This header file defines the public API for Google Test. It should be
34 // included by any test program that uses Google Test.
36 // IMPORTANT NOTE: Due to limitation of the C++ language, we have to
37 // leave some internal implementation details in this header file.
38 // They are clearly marked by comments like this:
40 // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
42 // Such code is NOT meant to be used by a user directly, and is subject
43 // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
46 // Acknowledgment: Google Test borrowed the idea of automatic test
47 // registration from Barthelemy Dagenais' (barthelemy@prologique.com)
48 // easyUnit framework.
50 // GOOGLETEST_CM0001 DO NOT DELETE
52 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
53 #define GTEST_INCLUDE_GTEST_GTEST_H_
59 #include "gtest/internal/gtest-internal.h"
60 #include "gtest/internal/gtest-string.h"
61 #include "gtest/gtest-death-test.h"
62 #include "gtest/gtest-message.h"
63 #include "gtest/gtest-param-test.h"
64 #include "gtest/gtest-printers.h"
65 #include "gtest/gtest_prod.h"
66 #include "gtest/gtest-test-part.h"
67 #include "gtest/gtest-typed-test.h"
69 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
70 /* class A needs to have dll-interface to be used by clients of class B */)
72 // Depending on the platform, different string classes are available.
73 // On Linux, in addition to ::std::string, Google also makes use of
74 // class ::string, which has the same interface as ::std::string, but
75 // has a different implementation.
77 // You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
78 // ::string is available AND is a distinct type to ::std::string, or
79 // define it to 0 to indicate otherwise.
81 // If ::std::string and ::string are the same class on your platform
82 // due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0.
84 // If you do not define GTEST_HAS_GLOBAL_STRING, it is defined
89 // Silence C4100 (unreferenced formal parameter) and 4805
90 // unsafe mix of type 'const int' and type 'const bool'
92 # pragma warning(push)
93 # pragma warning(disable:4805)
94 # pragma warning(disable:4100)
98 // Declares the flags.
100 // This flag temporary enables the disabled tests.
101 GTEST_DECLARE_bool_(also_run_disabled_tests);
103 // This flag brings the debugger on an assertion failure.
104 GTEST_DECLARE_bool_(break_on_failure);
106 // This flag controls whether Google Test catches all test-thrown exceptions
107 // and logs them as failures.
108 GTEST_DECLARE_bool_(catch_exceptions);
110 // This flag enables using colors in terminal output. Available values are
111 // "yes" to enable colors, "no" (disable colors), or "auto" (the default)
112 // to let Google Test decide.
113 GTEST_DECLARE_string_(color);
115 // This flag sets up the filter to select by name using a glob pattern
116 // the tests to run. If the filter is not given all tests are executed.
117 GTEST_DECLARE_string_(filter);
119 // This flag controls whether Google Test installs a signal handler that dumps
120 // debugging information when fatal signals are raised.
121 GTEST_DECLARE_bool_(install_failure_signal_handler);
123 // This flag causes the Google Test to list tests. None of the tests listed
124 // are actually run if the flag is provided.
125 GTEST_DECLARE_bool_(list_tests);
127 // This flag controls whether Google Test emits a detailed XML report to a file
128 // in addition to its normal textual output.
129 GTEST_DECLARE_string_(output);
131 // This flags control whether Google Test prints the elapsed time for each
133 GTEST_DECLARE_bool_(print_time);
135 // This flags control whether Google Test prints UTF8 characters as text.
136 GTEST_DECLARE_bool_(print_utf8);
138 // This flag specifies the random number seed.
139 GTEST_DECLARE_int32_(random_seed);
141 // This flag sets how many times the tests are repeated. The default value
142 // is 1. If the value is -1 the tests are repeating forever.
143 GTEST_DECLARE_int32_(repeat);
145 // This flag controls whether Google Test includes Google Test internal
146 // stack frames in failure stack traces.
147 GTEST_DECLARE_bool_(show_internal_stack_frames);
149 // When this flag is specified, tests' order is randomized on every iteration.
150 GTEST_DECLARE_bool_(shuffle);
152 // This flag specifies the maximum number of stack frames to be
153 // printed in a failure message.
154 GTEST_DECLARE_int32_(stack_trace_depth);
156 // When this flag is specified, a failed assertion will throw an
157 // exception if exceptions are enabled, or exit the program with a
158 // non-zero code otherwise. For use with an external test framework.
159 GTEST_DECLARE_bool_(throw_on_failure);
161 // When this flag is set with a "host:port" string, on supported
162 // platforms test results are streamed to the specified port on
163 // the specified host machine.
164 GTEST_DECLARE_string_(stream_result_to);
166 #if GTEST_USE_OWN_FLAGFILE_FLAG_
167 GTEST_DECLARE_string_(flagfile);
168 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
170 // The upper limit for valid stack trace depths.
171 const int kMaxStackTraceDepth = 100;
176 class DefaultGlobalTestPartResultReporter;
178 class NoExecDeathTest;
179 class FinalSuccessChecker;
180 class GTestFlagSaver;
181 class StreamingListenerTest;
182 class TestResultAccessor;
183 class TestEventListenersAccessor;
184 class TestEventRepeater;
185 class UnitTestRecordPropertyTestHelper;
186 class WindowsDeathTest;
187 class FuchsiaDeathTest;
188 class UnitTestImpl* GetUnitTestImpl();
189 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
190 const std::string& message);
192 } // namespace internal
194 // The friend relationship of some of these classes is cyclic.
195 // If we don't forward declare them the compiler might confuse the classes
196 // in friendship clauses with same named classes on the scope.
202 // A class for indicating whether an assertion was successful. When
203 // the assertion wasn't successful, the AssertionResult object
204 // remembers a non-empty message that describes how it failed.
206 // To create an instance of this class, use one of the factory functions
207 // (AssertionSuccess() and AssertionFailure()).
209 // This class is useful for two purposes:
210 // 1. Defining predicate functions to be used with Boolean test assertions
211 // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
212 // 2. Defining predicate-format functions to be
213 // used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
215 // For example, if you define IsEven predicate:
217 // testing::AssertionResult IsEven(int n) {
219 // return testing::AssertionSuccess();
221 // return testing::AssertionFailure() << n << " is odd";
224 // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
225 // will print the message
227 // Value of: IsEven(Fib(5))
228 // Actual: false (5 is odd)
231 // instead of a more opaque
233 // Value of: IsEven(Fib(5))
237 // in case IsEven is a simple Boolean predicate.
239 // If you expect your predicate to be reused and want to support informative
240 // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
241 // about half as often as positive ones in our tests), supply messages for
242 // both success and failure cases:
244 // testing::AssertionResult IsEven(int n) {
246 // return testing::AssertionSuccess() << n << " is even";
248 // return testing::AssertionFailure() << n << " is odd";
251 // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
253 // Value of: IsEven(Fib(6))
254 // Actual: true (8 is even)
257 // NB: Predicates that support negative Boolean assertions have reduced
258 // performance in positive ones so be careful not to use them in tests
259 // that have lots (tens of thousands) of positive Boolean assertions.
261 // To use this class with EXPECT_PRED_FORMAT assertions such as:
263 // // Verifies that Foo() returns an even number.
264 // EXPECT_PRED_FORMAT1(IsEven, Foo());
266 // you need to define:
268 // testing::AssertionResult IsEven(const char* expr, int n) {
270 // return testing::AssertionSuccess();
272 // return testing::AssertionFailure()
273 // << "Expected: " << expr << " is even\n Actual: it's " << n;
276 // If Foo() returns 5, you will see the following message:
278 // Expected: Foo() is even
281 class GTEST_API_ AssertionResult {
284 // Used in EXPECT_TRUE/FALSE(assertion_result).
285 AssertionResult(const AssertionResult& other);
287 #if defined(_MSC_VER) && _MSC_VER < 1910
288 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
291 // Used in the EXPECT_TRUE/FALSE(bool_expression).
293 // T must be contextually convertible to bool.
295 // The second parameter prevents this overload from being considered if
296 // the argument is implicitly convertible to AssertionResult. In that case
297 // we want AssertionResult's copy constructor to be used.
298 template <typename T>
299 explicit AssertionResult(
301 typename internal::EnableIf<
302 !internal::ImplicitlyConvertible<T, AssertionResult>::value>::type*
304 : success_(success) {}
306 #if defined(_MSC_VER) && _MSC_VER < 1910
307 GTEST_DISABLE_MSC_WARNINGS_POP_()
310 // Assignment operator.
311 AssertionResult& operator=(AssertionResult other) {
316 // Returns true iff the assertion succeeded.
317 operator bool() const { return success_; } // NOLINT
319 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
320 AssertionResult operator!() const;
322 // Returns the text streamed into this AssertionResult. Test assertions
323 // use it when they fail (i.e., the predicate's outcome doesn't match the
324 // assertion's expectation). When nothing has been streamed into the
325 // object, returns an empty string.
326 const char* message() const {
327 return message_.get() != NULL ? message_->c_str() : "";
329 // FIXME: Remove this after making sure no clients use it.
330 // Deprecated; please use message() instead.
331 const char* failure_message() const { return message(); }
333 // Streams a custom failure message into this object.
334 template <typename T> AssertionResult& operator<<(const T& value) {
335 AppendMessage(Message() << value);
339 // Allows streaming basic output manipulators such as endl or flush into
341 AssertionResult& operator<<(
342 ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
343 AppendMessage(Message() << basic_manipulator);
348 // Appends the contents of message to message_.
349 void AppendMessage(const Message& a_message) {
350 if (message_.get() == NULL)
351 message_.reset(new ::std::string);
352 message_->append(a_message.GetString().c_str());
355 // Swap the contents of this AssertionResult with other.
356 void swap(AssertionResult& other);
358 // Stores result of the assertion predicate.
360 // Stores the message describing the condition in case the expectation
361 // construct is not satisfied with the predicate's outcome.
362 // Referenced via a pointer to avoid taking too much stack frame space
363 // with test assertions.
364 internal::scoped_ptr< ::std::string> message_;
367 // Makes a successful assertion result.
368 GTEST_API_ AssertionResult AssertionSuccess();
370 // Makes a failed assertion result.
371 GTEST_API_ AssertionResult AssertionFailure();
373 // Makes a failed assertion result with the given failure message.
374 // Deprecated; use AssertionFailure() << msg.
375 GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
377 } // namespace testing
379 // Includes the auto-generated header that implements a family of generic
380 // predicate assertion macros. This include comes late because it relies on
381 // APIs declared above.
382 #include "gtest/gtest_pred_impl.h"
386 // The abstract class that all tests inherit from.
388 // In Google Test, a unit test program contains one or many TestCases, and
389 // each TestCase contains one or many Tests.
391 // When you define a test using the TEST macro, you don't need to
392 // explicitly derive from Test - the TEST macro automatically does
395 // The only time you derive from Test is when defining a test fixture
396 // to be used in a TEST_F. For example:
398 // class FooTest : public testing::Test {
400 // void SetUp() override { ... }
401 // void TearDown() override { ... }
405 // TEST_F(FooTest, Bar) { ... }
406 // TEST_F(FooTest, Baz) { ... }
408 // Test is not copyable.
409 class GTEST_API_ Test {
411 friend class TestInfo;
413 // Defines types for pointers to functions that set up and tear down
415 typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
416 typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
418 // The d'tor is virtual as we intend to inherit from Test.
421 // Sets up the stuff shared by all tests in this test case.
423 // Google Test will call Foo::SetUpTestCase() before running the first
424 // test in test case Foo. Hence a sub-class can define its own
425 // SetUpTestCase() method to shadow the one defined in the super
427 static void SetUpTestCase() {}
429 // Tears down the stuff shared by all tests in this test case.
431 // Google Test will call Foo::TearDownTestCase() after running the last
432 // test in test case Foo. Hence a sub-class can define its own
433 // TearDownTestCase() method to shadow the one defined in the super
435 static void TearDownTestCase() {}
437 // Returns true iff the current test has a fatal failure.
438 static bool HasFatalFailure();
440 // Returns true iff the current test has a non-fatal failure.
441 static bool HasNonfatalFailure();
443 // Returns true iff the current test has a (either fatal or
444 // non-fatal) failure.
445 static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
447 // Logs a property for the current test, test case, or for the entire
448 // invocation of the test program when used outside of the context of a
449 // test case. Only the last value for a given key is remembered. These
450 // are public static so they can be called from utility functions that are
451 // not members of the test fixture. Calls to RecordProperty made during
452 // lifespan of the test (from the moment its constructor starts to the
453 // moment its destructor finishes) will be output in XML as attributes of
454 // the <testcase> element. Properties recorded from fixture's
455 // SetUpTestCase or TearDownTestCase are logged as attributes of the
456 // corresponding <testsuite> element. Calls to RecordProperty made in the
457 // global context (before or after invocation of RUN_ALL_TESTS and from
458 // SetUp/TearDown method of Environment objects registered with Google
459 // Test) will be output as attributes of the <testsuites> element.
460 static void RecordProperty(const std::string& key, const std::string& value);
461 static void RecordProperty(const std::string& key, int value);
464 // Creates a Test object.
467 // Sets up the test fixture.
468 virtual void SetUp();
470 // Tears down the test fixture.
471 virtual void TearDown();
474 // Returns true iff the current test has the same fixture class as
475 // the first test in the current test case.
476 static bool HasSameFixtureClass();
478 // Runs the test after the test fixture has been set up.
480 // A sub-class must implement this to define the test logic.
482 // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
483 // Instead, use the TEST or TEST_F macro.
484 virtual void TestBody() = 0;
486 // Sets up, executes, and tears down the test.
489 // Deletes self. We deliberately pick an unusual name for this
490 // internal method to avoid clashing with names used in user TESTs.
491 void DeleteSelf_() { delete this; }
493 const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_;
495 // Often a user misspells SetUp() as Setup() and spends a long time
496 // wondering why it is never called by Google Test. The declaration of
497 // the following method is solely for catching such an error at
500 // - The return type is deliberately chosen to be not void, so it
501 // will be a conflict if void Setup() is declared in the user's
504 // - This method is private, so it will be another compiler error
505 // if the method is called from the user's test fixture.
507 // DO NOT OVERRIDE THIS FUNCTION.
509 // If you see an error about overriding the following function or
510 // about it being private, you have mis-spelled SetUp() as Setup().
511 struct Setup_should_be_spelled_SetUp {};
512 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
514 // We disallow copying Tests.
515 GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
518 typedef internal::TimeInMillis TimeInMillis;
520 // A copyable object representing a user specified test property which can be
521 // output as a key/value string pair.
523 // Don't inherit from TestProperty as its destructor is not virtual.
526 // C'tor. TestProperty does NOT have a default constructor.
527 // Always use this constructor (with parameters) to create a
528 // TestProperty object.
529 TestProperty(const std::string& a_key, const std::string& a_value) :
530 key_(a_key), value_(a_value) {
533 // Gets the user supplied key.
534 const char* key() const {
538 // Gets the user supplied value.
539 const char* value() const {
540 return value_.c_str();
543 // Sets a new value, overriding the one supplied in the constructor.
544 void SetValue(const std::string& new_value) {
549 // The key supplied by the user.
551 // The value supplied by the user.
555 // The result of a single Test. This includes a list of
556 // TestPartResults, a list of TestProperties, a count of how many
557 // death tests there are in the Test, and how much time it took to run
560 // TestResult is not copyable.
561 class GTEST_API_ TestResult {
563 // Creates an empty TestResult.
566 // D'tor. Do not inherit from TestResult.
569 // Gets the number of all test parts. This is the sum of the number
570 // of successful test parts and the number of failed test parts.
571 int total_part_count() const;
573 // Returns the number of the test properties.
574 int test_property_count() const;
576 // Returns true iff the test passed (i.e. no test part failed).
577 bool Passed() const { return !Failed(); }
579 // Returns true iff the test failed.
582 // Returns true iff the test fatally failed.
583 bool HasFatalFailure() const;
585 // Returns true iff the test has a non-fatal failure.
586 bool HasNonfatalFailure() const;
588 // Returns the elapsed time, in milliseconds.
589 TimeInMillis elapsed_time() const { return elapsed_time_; }
591 // Returns the i-th test part result among all the results. i can range from 0
592 // to total_part_count() - 1. If i is not in that range, aborts the program.
593 const TestPartResult& GetTestPartResult(int i) const;
595 // Returns the i-th test property. i can range from 0 to
596 // test_property_count() - 1. If i is not in that range, aborts the
598 const TestProperty& GetTestProperty(int i) const;
601 friend class TestInfo;
602 friend class TestCase;
603 friend class UnitTest;
604 friend class internal::DefaultGlobalTestPartResultReporter;
605 friend class internal::ExecDeathTest;
606 friend class internal::TestResultAccessor;
607 friend class internal::UnitTestImpl;
608 friend class internal::WindowsDeathTest;
609 friend class internal::FuchsiaDeathTest;
611 // Gets the vector of TestPartResults.
612 const std::vector<TestPartResult>& test_part_results() const {
613 return test_part_results_;
616 // Gets the vector of TestProperties.
617 const std::vector<TestProperty>& test_properties() const {
618 return test_properties_;
621 // Sets the elapsed time.
622 void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
624 // Adds a test property to the list. The property is validated and may add
625 // a non-fatal failure if invalid (e.g., if it conflicts with reserved
626 // key names). If a property is already recorded for the same key, the
627 // value will be updated, rather than storing multiple values for the same
628 // key. xml_element specifies the element for which the property is being
629 // recorded and is used for validation.
630 void RecordProperty(const std::string& xml_element,
631 const TestProperty& test_property);
633 // Adds a failure if the key is a reserved attribute of Google Test
634 // testcase tags. Returns true if the property is valid.
635 // FIXME: Validate attribute names are legal and human readable.
636 static bool ValidateTestProperty(const std::string& xml_element,
637 const TestProperty& test_property);
639 // Adds a test part result to the list.
640 void AddTestPartResult(const TestPartResult& test_part_result);
642 // Returns the death test count.
643 int death_test_count() const { return death_test_count_; }
645 // Increments the death test count, returning the new count.
646 int increment_death_test_count() { return ++death_test_count_; }
648 // Clears the test part results.
649 void ClearTestPartResults();
651 // Clears the object.
654 // Protects mutable state of the property vector and of owned
655 // properties, whose values may be updated.
656 internal::Mutex test_properites_mutex_;
658 // The vector of TestPartResults
659 std::vector<TestPartResult> test_part_results_;
660 // The vector of TestProperties
661 std::vector<TestProperty> test_properties_;
662 // Running count of death tests.
663 int death_test_count_;
664 // The elapsed time, in milliseconds.
665 TimeInMillis elapsed_time_;
667 // We disallow copying TestResult.
668 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
669 }; // class TestResult
671 // A TestInfo object stores the following information about a test:
675 // Whether the test should be run
676 // A function pointer that creates the test object when invoked
679 // The constructor of TestInfo registers itself with the UnitTest
680 // singleton such that the RUN_ALL_TESTS() macro knows which tests to
682 class GTEST_API_ TestInfo {
684 // Destructs a TestInfo object. This function is not virtual, so
685 // don't inherit from TestInfo.
688 // Returns the test case name.
689 const char* test_case_name() const { return test_case_name_.c_str(); }
691 // Returns the test name.
692 const char* name() const { return name_.c_str(); }
694 // Returns the name of the parameter type, or NULL if this is not a typed
695 // or a type-parameterized test.
696 const char* type_param() const {
697 if (type_param_.get() != NULL)
698 return type_param_->c_str();
702 // Returns the text representation of the value parameter, or NULL if this
703 // is not a value-parameterized test.
704 const char* value_param() const {
705 if (value_param_.get() != NULL)
706 return value_param_->c_str();
710 // Returns the file name where this test is defined.
711 const char* file() const { return location_.file.c_str(); }
713 // Returns the line where this test is defined.
714 int line() const { return location_.line; }
716 // Return true if this test should not be run because it's in another shard.
717 bool is_in_another_shard() const { return is_in_another_shard_; }
719 // Returns true if this test should run, that is if the test is not
720 // disabled (or it is disabled but the also_run_disabled_tests flag has
721 // been specified) and its full name matches the user-specified filter.
723 // Google Test allows the user to filter the tests by their full names.
724 // The full name of a test Bar in test case Foo is defined as
725 // "Foo.Bar". Only the tests that match the filter will run.
727 // A filter is a colon-separated list of glob (not regex) patterns,
728 // optionally followed by a '-' and a colon-separated list of
729 // negative patterns (tests to exclude). A test is run if it
730 // matches one of the positive patterns and does not match any of
731 // the negative patterns.
733 // For example, *A*:Foo.* is a filter that matches any string that
734 // contains the character 'A' or starts with "Foo.".
735 bool should_run() const { return should_run_; }
737 // Returns true iff this test will appear in the XML report.
738 bool is_reportable() const {
739 // The XML report includes tests matching the filter, excluding those
740 // run in other shards.
741 return matches_filter_ && !is_in_another_shard_;
744 // Returns the result of the test.
745 const TestResult* result() const { return &result_; }
748 #if GTEST_HAS_DEATH_TEST
749 friend class internal::DefaultDeathTestFactory;
750 #endif // GTEST_HAS_DEATH_TEST
752 friend class TestCase;
753 friend class internal::UnitTestImpl;
754 friend class internal::StreamingListenerTest;
755 friend TestInfo* internal::MakeAndRegisterTestInfo(
756 const char* test_case_name,
758 const char* type_param,
759 const char* value_param,
760 internal::CodeLocation code_location,
761 internal::TypeId fixture_class_id,
762 Test::SetUpTestCaseFunc set_up_tc,
763 Test::TearDownTestCaseFunc tear_down_tc,
764 internal::TestFactoryBase* factory);
766 // Constructs a TestInfo object. The newly constructed instance assumes
767 // ownership of the factory object.
768 TestInfo(const std::string& test_case_name,
769 const std::string& name,
770 const char* a_type_param, // NULL if not a type-parameterized test
771 const char* a_value_param, // NULL if not a value-parameterized test
772 internal::CodeLocation a_code_location,
773 internal::TypeId fixture_class_id,
774 internal::TestFactoryBase* factory);
776 // Increments the number of death tests encountered in this test so
778 int increment_death_test_count() {
779 return result_.increment_death_test_count();
782 // Creates the test object, runs it, records its result, and then
786 static void ClearTestResult(TestInfo* test_info) {
787 test_info->result_.Clear();
790 // These fields are immutable properties of the test.
791 const std::string test_case_name_; // Test case name
792 const std::string name_; // Test name
793 // Name of the parameter type, or NULL if this is not a typed or a
794 // type-parameterized test.
795 const internal::scoped_ptr<const ::std::string> type_param_;
796 // Text representation of the value parameter, or NULL if this is not a
797 // value-parameterized test.
798 const internal::scoped_ptr<const ::std::string> value_param_;
799 internal::CodeLocation location_;
800 const internal::TypeId fixture_class_id_; // ID of the test fixture class
801 bool should_run_; // True iff this test should run
802 bool is_disabled_; // True iff this test is disabled
803 bool matches_filter_; // True if this test matches the
804 // user-specified filter.
805 bool is_in_another_shard_; // Will be run in another shard.
806 internal::TestFactoryBase* const factory_; // The factory that creates
809 // This field is mutable and needs to be reset before running the
810 // test for the second time.
813 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
816 // A test case, which consists of a vector of TestInfos.
818 // TestCase is not copyable.
819 class GTEST_API_ TestCase {
821 // Creates a TestCase with the given name.
823 // TestCase does NOT have a default constructor. Always use this
824 // constructor to create a TestCase object.
828 // name: name of the test case
829 // a_type_param: the name of the test's type parameter, or NULL if
830 // this is not a type-parameterized test.
831 // set_up_tc: pointer to the function that sets up the test case
832 // tear_down_tc: pointer to the function that tears down the test case
833 TestCase(const char* name, const char* a_type_param,
834 Test::SetUpTestCaseFunc set_up_tc,
835 Test::TearDownTestCaseFunc tear_down_tc);
837 // Destructor of TestCase.
840 // Gets the name of the TestCase.
841 const char* name() const { return name_.c_str(); }
843 // Returns the name of the parameter type, or NULL if this is not a
844 // type-parameterized test case.
845 const char* type_param() const {
846 if (type_param_.get() != NULL)
847 return type_param_->c_str();
851 // Returns true if any test in this test case should run.
852 bool should_run() const { return should_run_; }
854 // Gets the number of successful tests in this test case.
855 int successful_test_count() const;
857 // Gets the number of failed tests in this test case.
858 int failed_test_count() const;
860 // Gets the number of disabled tests that will be reported in the XML report.
861 int reportable_disabled_test_count() const;
863 // Gets the number of disabled tests in this test case.
864 int disabled_test_count() const;
866 // Gets the number of tests to be printed in the XML report.
867 int reportable_test_count() const;
869 // Get the number of tests in this test case that should run.
870 int test_to_run_count() const;
872 // Gets the number of all tests in this test case.
873 int total_test_count() const;
875 // Returns true iff the test case passed.
876 bool Passed() const { return !Failed(); }
878 // Returns true iff the test case failed.
879 bool Failed() const { return failed_test_count() > 0; }
881 // Returns the elapsed time, in milliseconds.
882 TimeInMillis elapsed_time() const { return elapsed_time_; }
884 // Returns the i-th test among all the tests. i can range from 0 to
885 // total_test_count() - 1. If i is not in that range, returns NULL.
886 const TestInfo* GetTestInfo(int i) const;
888 // Returns the TestResult that holds test properties recorded during
889 // execution of SetUpTestCase and TearDownTestCase.
890 const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
894 friend class internal::UnitTestImpl;
896 // Gets the (mutable) vector of TestInfos in this TestCase.
897 std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
899 // Gets the (immutable) vector of TestInfos in this TestCase.
900 const std::vector<TestInfo*>& test_info_list() const {
901 return test_info_list_;
904 // Returns the i-th test among all the tests. i can range from 0 to
905 // total_test_count() - 1. If i is not in that range, returns NULL.
906 TestInfo* GetMutableTestInfo(int i);
908 // Sets the should_run member.
909 void set_should_run(bool should) { should_run_ = should; }
911 // Adds a TestInfo to this test case. Will delete the TestInfo upon
912 // destruction of the TestCase object.
913 void AddTestInfo(TestInfo * test_info);
915 // Clears the results of all tests in this test case.
918 // Clears the results of all tests in the given test case.
919 static void ClearTestCaseResult(TestCase* test_case) {
920 test_case->ClearResult();
923 // Runs every test in this TestCase.
926 // Runs SetUpTestCase() for this TestCase. This wrapper is needed
927 // for catching exceptions thrown from SetUpTestCase().
928 void RunSetUpTestCase() { (*set_up_tc_)(); }
930 // Runs TearDownTestCase() for this TestCase. This wrapper is
931 // needed for catching exceptions thrown from TearDownTestCase().
932 void RunTearDownTestCase() { (*tear_down_tc_)(); }
934 // Returns true iff test passed.
935 static bool TestPassed(const TestInfo* test_info) {
936 return test_info->should_run() && test_info->result()->Passed();
939 // Returns true iff test failed.
940 static bool TestFailed(const TestInfo* test_info) {
941 return test_info->should_run() && test_info->result()->Failed();
944 // Returns true iff the test is disabled and will be reported in the XML
946 static bool TestReportableDisabled(const TestInfo* test_info) {
947 return test_info->is_reportable() && test_info->is_disabled_;
950 // Returns true iff test is disabled.
951 static bool TestDisabled(const TestInfo* test_info) {
952 return test_info->is_disabled_;
955 // Returns true iff this test will appear in the XML report.
956 static bool TestReportable(const TestInfo* test_info) {
957 return test_info->is_reportable();
960 // Returns true if the given test should run.
961 static bool ShouldRunTest(const TestInfo* test_info) {
962 return test_info->should_run();
965 // Shuffles the tests in this test case.
966 void ShuffleTests(internal::Random* random);
968 // Restores the test order to before the first shuffle.
969 void UnshuffleTests();
971 // Name of the test case.
973 // Name of the parameter type, or NULL if this is not a typed or a
974 // type-parameterized test.
975 const internal::scoped_ptr<const ::std::string> type_param_;
976 // The vector of TestInfos in their original order. It owns the
977 // elements in the vector.
978 std::vector<TestInfo*> test_info_list_;
979 // Provides a level of indirection for the test list to allow easy
980 // shuffling and restoring the test order. The i-th element in this
981 // vector is the index of the i-th test in the shuffled test list.
982 std::vector<int> test_indices_;
983 // Pointer to the function that sets up the test case.
984 Test::SetUpTestCaseFunc set_up_tc_;
985 // Pointer to the function that tears down the test case.
986 Test::TearDownTestCaseFunc tear_down_tc_;
987 // True iff any test in this test case should run.
989 // Elapsed time, in milliseconds.
990 TimeInMillis elapsed_time_;
991 // Holds test properties recorded during execution of SetUpTestCase and
993 TestResult ad_hoc_test_result_;
995 // We disallow copying TestCases.
996 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
999 // An Environment object is capable of setting up and tearing down an
1000 // environment. You should subclass this to define your own
1003 // An Environment object does the set-up and tear-down in virtual
1004 // methods SetUp() and TearDown() instead of the constructor and the
1007 // 1. You cannot safely throw from a destructor. This is a problem
1008 // as in some cases Google Test is used where exceptions are enabled, and
1009 // we may want to implement ASSERT_* using exceptions where they are
1011 // 2. You cannot use ASSERT_* directly in a constructor or
1015 // The d'tor is virtual as we need to subclass Environment.
1016 virtual ~Environment() {}
1018 // Override this to define how to set up the environment.
1019 virtual void SetUp() {}
1021 // Override this to define how to tear down the environment.
1022 virtual void TearDown() {}
1024 // If you see an error about overriding the following function or
1025 // about it being private, you have mis-spelled SetUp() as Setup().
1026 struct Setup_should_be_spelled_SetUp {};
1027 virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
1030 #if GTEST_HAS_EXCEPTIONS
1032 // Exception which can be thrown from TestEventListener::OnTestPartResult.
1033 class GTEST_API_ AssertionException
1034 : public internal::GoogleTestFailureException {
1036 explicit AssertionException(const TestPartResult& result)
1037 : GoogleTestFailureException(result) {}
1040 #endif // GTEST_HAS_EXCEPTIONS
1042 // The interface for tracing execution of tests. The methods are organized in
1043 // the order the corresponding events are fired.
1044 class TestEventListener {
1046 virtual ~TestEventListener() {}
1048 // Fired before any test activity starts.
1049 virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
1051 // Fired before each iteration of tests starts. There may be more than
1052 // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
1053 // index, starting from 0.
1054 virtual void OnTestIterationStart(const UnitTest& unit_test,
1057 // Fired before environment set-up for each iteration of tests starts.
1058 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
1060 // Fired after environment set-up for each iteration of tests ends.
1061 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
1063 // Fired before the test case starts.
1064 virtual void OnTestCaseStart(const TestCase& test_case) = 0;
1066 // Fired before the test starts.
1067 virtual void OnTestStart(const TestInfo& test_info) = 0;
1069 // Fired after a failed assertion or a SUCCEED() invocation.
1070 // If you want to throw an exception from this function to skip to the next
1071 // TEST, it must be AssertionException defined above, or inherited from it.
1072 virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
1074 // Fired after the test ends.
1075 virtual void OnTestEnd(const TestInfo& test_info) = 0;
1077 // Fired after the test case ends.
1078 virtual void OnTestCaseEnd(const TestCase& test_case) = 0;
1080 // Fired before environment tear-down for each iteration of tests starts.
1081 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
1083 // Fired after environment tear-down for each iteration of tests ends.
1084 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
1086 // Fired after each iteration of tests finishes.
1087 virtual void OnTestIterationEnd(const UnitTest& unit_test,
1090 // Fired after all test activities have ended.
1091 virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
1094 // The convenience class for users who need to override just one or two
1095 // methods and are not concerned that a possible change to a signature of
1096 // the methods they override will not be caught during the build. For
1097 // comments about each method please see the definition of TestEventListener
1099 class EmptyTestEventListener : public TestEventListener {
1101 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
1102 virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
1103 int /*iteration*/) {}
1104 virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}
1105 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
1106 virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
1107 virtual void OnTestStart(const TestInfo& /*test_info*/) {}
1108 virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}
1109 virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
1110 virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
1111 virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
1112 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
1113 virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
1114 int /*iteration*/) {}
1115 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
1118 // TestEventListeners lets users add listeners to track events in Google Test.
1119 class GTEST_API_ TestEventListeners {
1121 TestEventListeners();
1122 ~TestEventListeners();
1124 // Appends an event listener to the end of the list. Google Test assumes
1125 // the ownership of the listener (i.e. it will delete the listener when
1126 // the test program finishes).
1127 void Append(TestEventListener* listener);
1129 // Removes the given event listener from the list and returns it. It then
1130 // becomes the caller's responsibility to delete the listener. Returns
1131 // NULL if the listener is not found in the list.
1132 TestEventListener* Release(TestEventListener* listener);
1134 // Returns the standard listener responsible for the default console
1135 // output. Can be removed from the listeners list to shut down default
1136 // console output. Note that removing this object from the listener list
1137 // with Release transfers its ownership to the caller and makes this
1138 // function return NULL the next time.
1139 TestEventListener* default_result_printer() const {
1140 return default_result_printer_;
1143 // Returns the standard listener responsible for the default XML output
1144 // controlled by the --gtest_output=xml flag. Can be removed from the
1145 // listeners list by users who want to shut down the default XML output
1146 // controlled by this flag and substitute it with custom one. Note that
1147 // removing this object from the listener list with Release transfers its
1148 // ownership to the caller and makes this function return NULL the next
1150 TestEventListener* default_xml_generator() const {
1151 return default_xml_generator_;
1155 friend class TestCase;
1156 friend class TestInfo;
1157 friend class internal::DefaultGlobalTestPartResultReporter;
1158 friend class internal::NoExecDeathTest;
1159 friend class internal::TestEventListenersAccessor;
1160 friend class internal::UnitTestImpl;
1162 // Returns repeater that broadcasts the TestEventListener events to all
1164 TestEventListener* repeater();
1166 // Sets the default_result_printer attribute to the provided listener.
1167 // The listener is also added to the listener list and previous
1168 // default_result_printer is removed from it and deleted. The listener can
1169 // also be NULL in which case it will not be added to the list. Does
1170 // nothing if the previous and the current listener objects are the same.
1171 void SetDefaultResultPrinter(TestEventListener* listener);
1173 // Sets the default_xml_generator attribute to the provided listener. The
1174 // listener is also added to the listener list and previous
1175 // default_xml_generator is removed from it and deleted. The listener can
1176 // also be NULL in which case it will not be added to the list. Does
1177 // nothing if the previous and the current listener objects are the same.
1178 void SetDefaultXmlGenerator(TestEventListener* listener);
1180 // Controls whether events will be forwarded by the repeater to the
1181 // listeners in the list.
1182 bool EventForwardingEnabled() const;
1183 void SuppressEventForwarding();
1185 // The actual list of listeners.
1186 internal::TestEventRepeater* repeater_;
1187 // Listener responsible for the standard result output.
1188 TestEventListener* default_result_printer_;
1189 // Listener responsible for the creation of the XML output file.
1190 TestEventListener* default_xml_generator_;
1192 // We disallow copying TestEventListeners.
1193 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
1196 // A UnitTest consists of a vector of TestCases.
1198 // This is a singleton class. The only instance of UnitTest is
1199 // created when UnitTest::GetInstance() is first called. This
1200 // instance is never deleted.
1202 // UnitTest is not copyable.
1204 // This class is thread-safe as long as the methods are called
1205 // according to their specification.
1206 class GTEST_API_ UnitTest {
1208 // Gets the singleton UnitTest object. The first time this method
1209 // is called, a UnitTest object is constructed and returned.
1210 // Consecutive calls will return the same object.
1211 static UnitTest* GetInstance();
1213 // Runs all tests in this UnitTest object and prints the result.
1214 // Returns 0 if successful, or 1 otherwise.
1216 // This method can only be called from the main thread.
1218 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1219 int Run() GTEST_MUST_USE_RESULT_;
1221 // Returns the working directory when the first TEST() or TEST_F()
1222 // was executed. The UnitTest object owns the string.
1223 const char* original_working_dir() const;
1225 // Returns the TestCase object for the test that's currently running,
1226 // or NULL if no test is running.
1227 const TestCase* current_test_case() const
1228 GTEST_LOCK_EXCLUDED_(mutex_);
1230 // Returns the TestInfo object for the test that's currently running,
1231 // or NULL if no test is running.
1232 const TestInfo* current_test_info() const
1233 GTEST_LOCK_EXCLUDED_(mutex_);
1235 // Returns the random seed used at the start of the current test run.
1236 int random_seed() const;
1238 // Returns the ParameterizedTestCaseRegistry object used to keep track of
1239 // value-parameterized tests and instantiate and register them.
1241 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1242 internal::ParameterizedTestCaseRegistry& parameterized_test_registry()
1243 GTEST_LOCK_EXCLUDED_(mutex_);
1245 // Gets the number of successful test cases.
1246 int successful_test_case_count() const;
1248 // Gets the number of failed test cases.
1249 int failed_test_case_count() const;
1251 // Gets the number of all test cases.
1252 int total_test_case_count() const;
1254 // Gets the number of all test cases that contain at least one test
1256 int test_case_to_run_count() const;
1258 // Gets the number of successful tests.
1259 int successful_test_count() const;
1261 // Gets the number of failed tests.
1262 int failed_test_count() const;
1264 // Gets the number of disabled tests that will be reported in the XML report.
1265 int reportable_disabled_test_count() const;
1267 // Gets the number of disabled tests.
1268 int disabled_test_count() const;
1270 // Gets the number of tests to be printed in the XML report.
1271 int reportable_test_count() const;
1273 // Gets the number of all tests.
1274 int total_test_count() const;
1276 // Gets the number of tests that should run.
1277 int test_to_run_count() const;
1279 // Gets the time of the test program start, in ms from the start of the
1281 TimeInMillis start_timestamp() const;
1283 // Gets the elapsed time, in milliseconds.
1284 TimeInMillis elapsed_time() const;
1286 // Returns true iff the unit test passed (i.e. all test cases passed).
1287 bool Passed() const;
1289 // Returns true iff the unit test failed (i.e. some test case failed
1290 // or something outside of all tests failed).
1291 bool Failed() const;
1293 // Gets the i-th test case among all the test cases. i can range from 0 to
1294 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1295 const TestCase* GetTestCase(int i) const;
1297 // Returns the TestResult containing information on test failures and
1298 // properties logged outside of individual test cases.
1299 const TestResult& ad_hoc_test_result() const;
1301 // Returns the list of event listeners that can be used to track events
1302 // inside Google Test.
1303 TestEventListeners& listeners();
1306 // Registers and returns a global test environment. When a test
1307 // program is run, all global test environments will be set-up in
1308 // the order they were registered. After all tests in the program
1309 // have finished, all global test environments will be torn-down in
1310 // the *reverse* order they were registered.
1312 // The UnitTest object takes ownership of the given environment.
1314 // This method can only be called from the main thread.
1315 Environment* AddEnvironment(Environment* env);
1317 // Adds a TestPartResult to the current TestResult object. All
1318 // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
1319 // eventually call this to report their results. The user code
1320 // should use the assertion macros instead of calling this directly.
1321 void AddTestPartResult(TestPartResult::Type result_type,
1322 const char* file_name,
1324 const std::string& message,
1325 const std::string& os_stack_trace)
1326 GTEST_LOCK_EXCLUDED_(mutex_);
1328 // Adds a TestProperty to the current TestResult object when invoked from
1329 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
1330 // from SetUpTestCase or TearDownTestCase, or to the global property set
1331 // when invoked elsewhere. If the result already contains a property with
1332 // the same key, the value will be updated.
1333 void RecordProperty(const std::string& key, const std::string& value);
1335 // Gets the i-th test case among all the test cases. i can range from 0 to
1336 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1337 TestCase* GetMutableTestCase(int i);
1339 // Accessors for the implementation object.
1340 internal::UnitTestImpl* impl() { return impl_; }
1341 const internal::UnitTestImpl* impl() const { return impl_; }
1343 // These classes and functions are friends as they need to access private
1344 // members of UnitTest.
1345 friend class ScopedTrace;
1347 friend class internal::AssertHelper;
1348 friend class internal::StreamingListenerTest;
1349 friend class internal::UnitTestRecordPropertyTestHelper;
1350 friend Environment* AddGlobalTestEnvironment(Environment* env);
1351 friend internal::UnitTestImpl* internal::GetUnitTestImpl();
1352 friend void internal::ReportFailureInUnknownLocation(
1353 TestPartResult::Type result_type,
1354 const std::string& message);
1356 // Creates an empty UnitTest.
1360 virtual ~UnitTest();
1362 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
1363 // Google Test trace stack.
1364 void PushGTestTrace(const internal::TraceInfo& trace)
1365 GTEST_LOCK_EXCLUDED_(mutex_);
1367 // Pops a trace from the per-thread Google Test trace stack.
1368 void PopGTestTrace()
1369 GTEST_LOCK_EXCLUDED_(mutex_);
1371 // Protects mutable state in *impl_. This is mutable as some const
1372 // methods need to lock it too.
1373 mutable internal::Mutex mutex_;
1375 // Opaque implementation object. This field is never changed once
1376 // the object is constructed. We don't mark it as const here, as
1377 // doing so will cause a warning in the constructor of UnitTest.
1378 // Mutable state in *impl_ is protected by mutex_.
1379 internal::UnitTestImpl* impl_;
1381 // We disallow copying UnitTest.
1382 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
1385 // A convenient wrapper for adding an environment for the test
1388 // You should call this before RUN_ALL_TESTS() is called, probably in
1389 // main(). If you use gtest_main, you need to call this before main()
1390 // starts for it to take effect. For example, you can define a global
1391 // variable like this:
1393 // testing::Environment* const foo_env =
1394 // testing::AddGlobalTestEnvironment(new FooEnvironment);
1396 // However, we strongly recommend you to write your own main() and
1397 // call AddGlobalTestEnvironment() there, as relying on initialization
1398 // of global variables makes the code harder to read and may cause
1399 // problems when you register multiple environments from different
1400 // translation units and the environments have dependencies among them
1401 // (remember that the compiler doesn't guarantee the order in which
1402 // global variables from different translation units are initialized).
1403 inline Environment* AddGlobalTestEnvironment(Environment* env) {
1404 return UnitTest::GetInstance()->AddEnvironment(env);
1407 // Initializes Google Test. This must be called before calling
1408 // RUN_ALL_TESTS(). In particular, it parses a command line for the
1409 // flags that Google Test recognizes. Whenever a Google Test flag is
1410 // seen, it is removed from argv, and *argc is decremented.
1412 // No value is returned. Instead, the Google Test flag variables are
1415 // Calling the function for the second time has no user-visible effect.
1416 GTEST_API_ void InitGoogleTest(int* argc, char** argv);
1418 // This overloaded version can be used in Windows programs compiled in
1420 GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
1422 namespace internal {
1424 // Separate the error generating code from the code path to reduce the stack
1425 // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
1426 // when calling EXPECT_* in a tight loop.
1427 template <typename T1, typename T2>
1428 AssertionResult CmpHelperEQFailure(const char* lhs_expression,
1429 const char* rhs_expression,
1430 const T1& lhs, const T2& rhs) {
1431 return EqFailure(lhs_expression,
1433 FormatForComparisonFailureMessage(lhs, rhs),
1434 FormatForComparisonFailureMessage(rhs, lhs),
1438 // The helper function for {ASSERT|EXPECT}_EQ.
1439 template <typename T1, typename T2>
1440 AssertionResult CmpHelperEQ(const char* lhs_expression,
1441 const char* rhs_expression,
1445 return AssertionSuccess();
1448 return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
1451 // With this overloaded version, we allow anonymous enums to be used
1452 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
1453 // can be implicitly cast to BiggestInt.
1454 GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression,
1455 const char* rhs_expression,
1459 // The helper class for {ASSERT|EXPECT}_EQ. The template argument
1460 // lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
1461 // is a null pointer literal. The following default implementation is
1462 // for lhs_is_null_literal being false.
1463 template <bool lhs_is_null_literal>
1466 // This templatized version is for the general case.
1467 template <typename T1, typename T2>
1468 static AssertionResult Compare(const char* lhs_expression,
1469 const char* rhs_expression,
1472 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
1475 // With this overloaded version, we allow anonymous enums to be used
1476 // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
1477 // enums can be implicitly cast to BiggestInt.
1479 // Even though its body looks the same as the above version, we
1480 // cannot merge the two, as it will make anonymous enums unhappy.
1481 static AssertionResult Compare(const char* lhs_expression,
1482 const char* rhs_expression,
1485 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
1489 // This specialization is used when the first argument to ASSERT_EQ()
1490 // is a null pointer literal, like NULL, false, or 0.
1492 class EqHelper<true> {
1494 // We define two overloaded versions of Compare(). The first
1495 // version will be picked when the second argument to ASSERT_EQ() is
1496 // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
1497 // EXPECT_EQ(false, a_bool).
1498 template <typename T1, typename T2>
1499 static AssertionResult Compare(
1500 const char* lhs_expression,
1501 const char* rhs_expression,
1504 // The following line prevents this overload from being considered if T2
1505 // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr)
1506 // expands to Compare("", "", NULL, my_ptr), which requires a conversion
1507 // to match the Secret* in the other overload, which would otherwise make
1508 // this template match better.
1509 typename EnableIf<!is_pointer<T2>::value>::type* = 0) {
1510 return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
1513 // This version will be picked when the second argument to ASSERT_EQ() is a
1514 // pointer, e.g. ASSERT_EQ(NULL, a_pointer).
1515 template <typename T>
1516 static AssertionResult Compare(
1517 const char* lhs_expression,
1518 const char* rhs_expression,
1519 // We used to have a second template parameter instead of Secret*. That
1520 // template parameter would deduce to 'long', making this a better match
1521 // than the first overload even without the first overload's EnableIf.
1522 // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to
1523 // non-pointer argument" (even a deduced integral argument), so the old
1524 // implementation caused warnings in user code.
1525 Secret* /* lhs (NULL) */,
1527 // We already know that 'lhs' is a null pointer.
1528 return CmpHelperEQ(lhs_expression, rhs_expression,
1529 static_cast<T*>(NULL), rhs);
1533 // Separate the error generating code from the code path to reduce the stack
1534 // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
1535 // when calling EXPECT_OP in a tight loop.
1536 template <typename T1, typename T2>
1537 AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
1538 const T1& val1, const T2& val2,
1540 return AssertionFailure()
1541 << "Expected: (" << expr1 << ") " << op << " (" << expr2
1542 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)
1543 << " vs " << FormatForComparisonFailureMessage(val2, val1);
1546 // A macro for implementing the helper functions needed to implement
1547 // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
1550 // For each templatized helper function, we also define an overloaded
1551 // version for BiggestInt in order to reduce code bloat and allow
1552 // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
1555 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1557 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1558 template <typename T1, typename T2>\
1559 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1560 const T1& val1, const T2& val2) {\
1561 if (val1 op val2) {\
1562 return AssertionSuccess();\
1564 return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\
1567 GTEST_API_ AssertionResult CmpHelper##op_name(\
1568 const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
1570 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1572 // Implements the helper function for {ASSERT|EXPECT}_NE
1573 GTEST_IMPL_CMP_HELPER_(NE, !=);
1574 // Implements the helper function for {ASSERT|EXPECT}_LE
1575 GTEST_IMPL_CMP_HELPER_(LE, <=);
1576 // Implements the helper function for {ASSERT|EXPECT}_LT
1577 GTEST_IMPL_CMP_HELPER_(LT, <);
1578 // Implements the helper function for {ASSERT|EXPECT}_GE
1579 GTEST_IMPL_CMP_HELPER_(GE, >=);
1580 // Implements the helper function for {ASSERT|EXPECT}_GT
1581 GTEST_IMPL_CMP_HELPER_(GT, >);
1583 #undef GTEST_IMPL_CMP_HELPER_
1585 // The helper function for {ASSERT|EXPECT}_STREQ.
1587 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1588 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
1589 const char* s2_expression,
1593 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1595 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1596 GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
1597 const char* s2_expression,
1601 // The helper function for {ASSERT|EXPECT}_STRNE.
1603 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1604 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1605 const char* s2_expression,
1609 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1611 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1612 GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1613 const char* s2_expression,
1618 // Helper function for *_STREQ on wide strings.
1620 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1621 GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
1622 const char* s2_expression,
1626 // Helper function for *_STRNE on wide strings.
1628 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1629 GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
1630 const char* s2_expression,
1634 } // namespace internal
1636 // IsSubstring() and IsNotSubstring() are intended to be used as the
1637 // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
1638 // themselves. They check whether needle is a substring of haystack
1639 // (NULL is considered a substring of itself only), and return an
1640 // appropriate error message when they fail.
1642 // The {needle,haystack}_expr arguments are the stringified
1643 // expressions that generated the two real arguments.
1644 GTEST_API_ AssertionResult IsSubstring(
1645 const char* needle_expr, const char* haystack_expr,
1646 const char* needle, const char* haystack);
1647 GTEST_API_ AssertionResult IsSubstring(
1648 const char* needle_expr, const char* haystack_expr,
1649 const wchar_t* needle, const wchar_t* haystack);
1650 GTEST_API_ AssertionResult IsNotSubstring(
1651 const char* needle_expr, const char* haystack_expr,
1652 const char* needle, const char* haystack);
1653 GTEST_API_ AssertionResult IsNotSubstring(
1654 const char* needle_expr, const char* haystack_expr,
1655 const wchar_t* needle, const wchar_t* haystack);
1656 GTEST_API_ AssertionResult IsSubstring(
1657 const char* needle_expr, const char* haystack_expr,
1658 const ::std::string& needle, const ::std::string& haystack);
1659 GTEST_API_ AssertionResult IsNotSubstring(
1660 const char* needle_expr, const char* haystack_expr,
1661 const ::std::string& needle, const ::std::string& haystack);
1663 #if GTEST_HAS_STD_WSTRING
1664 GTEST_API_ AssertionResult IsSubstring(
1665 const char* needle_expr, const char* haystack_expr,
1666 const ::std::wstring& needle, const ::std::wstring& haystack);
1667 GTEST_API_ AssertionResult IsNotSubstring(
1668 const char* needle_expr, const char* haystack_expr,
1669 const ::std::wstring& needle, const ::std::wstring& haystack);
1670 #endif // GTEST_HAS_STD_WSTRING
1672 namespace internal {
1674 // Helper template function for comparing floating-points.
1676 // Template parameter:
1678 // RawType: the raw floating-point type (either float or double)
1680 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1681 template <typename RawType>
1682 AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
1683 const char* rhs_expression,
1685 RawType rhs_value) {
1686 const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
1688 if (lhs.AlmostEquals(rhs)) {
1689 return AssertionSuccess();
1692 ::std::stringstream lhs_ss;
1693 lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1696 ::std::stringstream rhs_ss;
1697 rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1700 return EqFailure(lhs_expression,
1702 StringStreamToString(&lhs_ss),
1703 StringStreamToString(&rhs_ss),
1707 // Helper function for implementing ASSERT_NEAR.
1709 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
1710 GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
1712 const char* abs_error_expr,
1717 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
1718 // A class that enables one to stream messages to assertion macros
1719 class GTEST_API_ AssertHelper {
1722 AssertHelper(TestPartResult::Type type,
1725 const char* message);
1728 // Message assignment is a semantic trick to enable assertion
1729 // streaming; see the GTEST_MESSAGE_ macro below.
1730 void operator=(const Message& message) const;
1733 // We put our data in a struct so that the size of the AssertHelper class can
1734 // be as small as possible. This is important because gcc is incapable of
1735 // re-using stack space even for temporary variables, so every EXPECT_EQ
1736 // reserves stack space for another AssertHelper.
1737 struct AssertHelperData {
1738 AssertHelperData(TestPartResult::Type t,
1739 const char* srcfile,
1742 : type(t), file(srcfile), line(line_num), message(msg) { }
1744 TestPartResult::Type const type;
1745 const char* const file;
1747 std::string const message;
1750 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
1753 AssertHelperData* const data_;
1755 GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
1758 } // namespace internal
1760 // The pure interface class that all value-parameterized tests inherit from.
1761 // A value-parameterized class must inherit from both ::testing::Test and
1762 // ::testing::WithParamInterface. In most cases that just means inheriting
1763 // from ::testing::TestWithParam, but more complicated test hierarchies
1764 // may need to inherit from Test and WithParamInterface at different levels.
1766 // This interface has support for accessing the test parameter value via
1767 // the GetParam() method.
1769 // Use it with one of the parameter generator defining functions, like Range(),
1770 // Values(), ValuesIn(), Bool(), and Combine().
1772 // class FooTest : public ::testing::TestWithParam<int> {
1775 // // Can use GetParam() here.
1777 // virtual ~FooTest() {
1778 // // Can use GetParam() here.
1780 // virtual void SetUp() {
1781 // // Can use GetParam() here.
1783 // virtual void TearDown {
1784 // // Can use GetParam() here.
1787 // TEST_P(FooTest, DoesBar) {
1788 // // Can use GetParam() method here.
1790 // ASSERT_TRUE(foo.DoesBar(GetParam()));
1792 // INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
1794 template <typename T>
1795 class WithParamInterface {
1797 typedef T ParamType;
1798 virtual ~WithParamInterface() {}
1800 // The current parameter value. Is also available in the test fixture's
1801 // constructor. This member function is non-static, even though it only
1802 // references static data, to reduce the opportunity for incorrect uses
1803 // like writing 'WithParamInterface<bool>::GetParam()' for a test that
1804 // uses a fixture whose parameter type is int.
1805 const ParamType& GetParam() const {
1806 GTEST_CHECK_(parameter_ != NULL)
1807 << "GetParam() can only be called inside a value-parameterized test "
1808 << "-- did you intend to write TEST_P instead of TEST_F?";
1813 // Sets parameter value. The caller is responsible for making sure the value
1814 // remains alive and unchanged throughout the current test.
1815 static void SetParam(const ParamType* parameter) {
1816 parameter_ = parameter;
1819 // Static value used for accessing parameter during a test lifetime.
1820 static const ParamType* parameter_;
1822 // TestClass must be a subclass of WithParamInterface<T> and Test.
1823 template <class TestClass> friend class internal::ParameterizedTestFactory;
1826 template <typename T>
1827 const T* WithParamInterface<T>::parameter_ = NULL;
1829 // Most value-parameterized classes can ignore the existence of
1830 // WithParamInterface, and can just inherit from ::testing::TestWithParam.
1832 template <typename T>
1833 class TestWithParam : public Test, public WithParamInterface<T> {
1836 // Macros for indicating success/failure in test code.
1838 // ADD_FAILURE unconditionally adds a failure to the current test.
1839 // SUCCEED generates a success - it doesn't automatically make the
1840 // current test successful, as a test is only successful when it has
1843 // EXPECT_* verifies that a certain condition is satisfied. If not,
1844 // it behaves like ADD_FAILURE. In particular:
1846 // EXPECT_TRUE verifies that a Boolean condition is true.
1847 // EXPECT_FALSE verifies that a Boolean condition is false.
1849 // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
1850 // that they will also abort the current function on failure. People
1851 // usually want the fail-fast behavior of FAIL and ASSERT_*, but those
1852 // writing data-driven tests often find themselves using ADD_FAILURE
1853 // and EXPECT_* more.
1855 // Generates a nonfatal failure with a generic message.
1856 #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
1858 // Generates a nonfatal failure at the given source file location with
1859 // a generic message.
1860 #define ADD_FAILURE_AT(file, line) \
1861 GTEST_MESSAGE_AT_(file, line, "Failed", \
1862 ::testing::TestPartResult::kNonFatalFailure)
1864 // Generates a fatal failure with a generic message.
1865 #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
1867 // Define this macro to 1 to omit the definition of FAIL(), which is a
1868 // generic name and clashes with some other libraries.
1869 #if !GTEST_DONT_DEFINE_FAIL
1870 # define FAIL() GTEST_FAIL()
1873 // Generates a success with a generic message.
1874 #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
1876 // Define this macro to 1 to omit the definition of SUCCEED(), which
1877 // is a generic name and clashes with some other libraries.
1878 #if !GTEST_DONT_DEFINE_SUCCEED
1879 # define SUCCEED() GTEST_SUCCEED()
1882 // Macros for testing exceptions.
1884 // * {ASSERT|EXPECT}_THROW(statement, expected_exception):
1885 // Tests that the statement throws the expected exception.
1886 // * {ASSERT|EXPECT}_NO_THROW(statement):
1887 // Tests that the statement doesn't throw any exception.
1888 // * {ASSERT|EXPECT}_ANY_THROW(statement):
1889 // Tests that the statement throws an exception.
1891 #define EXPECT_THROW(statement, expected_exception) \
1892 GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
1893 #define EXPECT_NO_THROW(statement) \
1894 GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1895 #define EXPECT_ANY_THROW(statement) \
1896 GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
1897 #define ASSERT_THROW(statement, expected_exception) \
1898 GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
1899 #define ASSERT_NO_THROW(statement) \
1900 GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
1901 #define ASSERT_ANY_THROW(statement) \
1902 GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
1904 // Boolean assertions. Condition can be either a Boolean expression or an
1905 // AssertionResult. For more information on how to use AssertionResult with
1906 // these macros see comments on that class.
1907 #define EXPECT_TRUE(condition) \
1908 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1909 GTEST_NONFATAL_FAILURE_)
1910 #define EXPECT_FALSE(condition) \
1911 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1912 GTEST_NONFATAL_FAILURE_)
1913 #define ASSERT_TRUE(condition) \
1914 GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
1915 GTEST_FATAL_FAILURE_)
1916 #define ASSERT_FALSE(condition) \
1917 GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
1918 GTEST_FATAL_FAILURE_)
1920 // Macros for testing equalities and inequalities.
1922 // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
1923 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
1924 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
1925 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
1926 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
1927 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
1929 // When they are not, Google Test prints both the tested expressions and
1930 // their actual values. The values must be compatible built-in types,
1931 // or you will get a compiler error. By "compatible" we mean that the
1932 // values can be compared by the respective operator.
1936 // 1. It is possible to make a user-defined type work with
1937 // {ASSERT|EXPECT}_??(), but that requires overloading the
1938 // comparison operators and is thus discouraged by the Google C++
1939 // Usage Guide. Therefore, you are advised to use the
1940 // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
1943 // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
1944 // pointers (in particular, C strings). Therefore, if you use it
1945 // with two C strings, you are testing how their locations in memory
1946 // are related, not how their content is related. To compare two C
1947 // strings by content, use {ASSERT|EXPECT}_STR*().
1949 // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
1950 // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
1951 // what the actual value is when it fails, and similarly for the
1952 // other comparisons.
1954 // 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
1955 // evaluate their arguments, which is undefined.
1957 // 5. These macros evaluate their arguments exactly once.
1961 // EXPECT_NE(Foo(), 5);
1962 // EXPECT_EQ(a_pointer, NULL);
1963 // ASSERT_LT(i, array_size);
1964 // ASSERT_GT(records.size(), 0) << "There is no record left.";
1966 #define EXPECT_EQ(val1, val2) \
1967 EXPECT_PRED_FORMAT2(::testing::internal:: \
1968 EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
1970 #define EXPECT_NE(val1, val2) \
1971 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
1972 #define EXPECT_LE(val1, val2) \
1973 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1974 #define EXPECT_LT(val1, val2) \
1975 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1976 #define EXPECT_GE(val1, val2) \
1977 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1978 #define EXPECT_GT(val1, val2) \
1979 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1981 #define GTEST_ASSERT_EQ(val1, val2) \
1982 ASSERT_PRED_FORMAT2(::testing::internal:: \
1983 EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \
1985 #define GTEST_ASSERT_NE(val1, val2) \
1986 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
1987 #define GTEST_ASSERT_LE(val1, val2) \
1988 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
1989 #define GTEST_ASSERT_LT(val1, val2) \
1990 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
1991 #define GTEST_ASSERT_GE(val1, val2) \
1992 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
1993 #define GTEST_ASSERT_GT(val1, val2) \
1994 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
1996 // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
1997 // ASSERT_XY(), which clashes with some users' own code.
1999 #if !GTEST_DONT_DEFINE_ASSERT_EQ
2000 # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
2003 #if !GTEST_DONT_DEFINE_ASSERT_NE
2004 # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
2007 #if !GTEST_DONT_DEFINE_ASSERT_LE
2008 # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
2011 #if !GTEST_DONT_DEFINE_ASSERT_LT
2012 # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
2015 #if !GTEST_DONT_DEFINE_ASSERT_GE
2016 # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
2019 #if !GTEST_DONT_DEFINE_ASSERT_GT
2020 # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
2023 // C-string Comparisons. All tests treat NULL and any non-NULL string
2024 // as different. Two NULLs are equal.
2026 // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
2027 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
2028 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
2029 // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
2031 // For wide or narrow string objects, you can use the
2032 // {ASSERT|EXPECT}_??() macros.
2034 // Don't depend on the order in which the arguments are evaluated,
2035 // which is undefined.
2037 // These macros evaluate their arguments exactly once.
2039 #define EXPECT_STREQ(s1, s2) \
2040 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
2041 #define EXPECT_STRNE(s1, s2) \
2042 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2043 #define EXPECT_STRCASEEQ(s1, s2) \
2044 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
2045 #define EXPECT_STRCASENE(s1, s2)\
2046 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2048 #define ASSERT_STREQ(s1, s2) \
2049 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
2050 #define ASSERT_STRNE(s1, s2) \
2051 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2052 #define ASSERT_STRCASEEQ(s1, s2) \
2053 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
2054 #define ASSERT_STRCASENE(s1, s2)\
2055 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2057 // Macros for comparing floating-point numbers.
2059 // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
2060 // Tests that two float values are almost equal.
2061 // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
2062 // Tests that two double values are almost equal.
2063 // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
2064 // Tests that v1 and v2 are within the given distance to each other.
2066 // Google Test uses ULP-based comparison to automatically pick a default
2067 // error bound that is appropriate for the operands. See the
2068 // FloatingPoint template class in gtest-internal.h if you are
2069 // interested in the implementation details.
2071 #define EXPECT_FLOAT_EQ(val1, val2)\
2072 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2075 #define EXPECT_DOUBLE_EQ(val1, val2)\
2076 EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2079 #define ASSERT_FLOAT_EQ(val1, val2)\
2080 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2083 #define ASSERT_DOUBLE_EQ(val1, val2)\
2084 ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2087 #define EXPECT_NEAR(val1, val2, abs_error)\
2088 EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2089 val1, val2, abs_error)
2091 #define ASSERT_NEAR(val1, val2, abs_error)\
2092 ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
2093 val1, val2, abs_error)
2095 // These predicate format functions work on floating-point values, and
2096 // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
2098 // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
2100 // Asserts that val1 is less than, or almost equal to, val2. Fails
2101 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2102 GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
2103 float val1, float val2);
2104 GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
2105 double val1, double val2);
2108 #if GTEST_OS_WINDOWS
2110 // Macros that test for HRESULT failure and success, these are only useful
2111 // on Windows, and rely on Windows SDK macros and APIs to compile.
2113 // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
2115 // When expr unexpectedly fails or succeeds, Google Test prints the
2116 // expected result and the actual result with both a human-readable
2117 // string representation of the error, if available, as well as the
2119 # define EXPECT_HRESULT_SUCCEEDED(expr) \
2120 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2122 # define ASSERT_HRESULT_SUCCEEDED(expr) \
2123 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2125 # define EXPECT_HRESULT_FAILED(expr) \
2126 EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2128 # define ASSERT_HRESULT_FAILED(expr) \
2129 ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2131 #endif // GTEST_OS_WINDOWS
2133 // Macros that execute statement and check that it doesn't generate new fatal
2134 // failures in the current thread.
2136 // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
2140 // EXPECT_NO_FATAL_FAILURE(Process());
2141 // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
2143 #define ASSERT_NO_FATAL_FAILURE(statement) \
2144 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
2145 #define EXPECT_NO_FATAL_FAILURE(statement) \
2146 GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
2148 // Causes a trace (including the given source file path and line number,
2149 // and the given message) to be included in every test failure message generated
2150 // by code in the scope of the lifetime of an instance of this class. The effect
2151 // is undone with the destruction of the instance.
2153 // The message argument can be anything streamable to std::ostream.
2156 // testing::ScopedTrace trace("file.cc", 123, "message");
2158 class GTEST_API_ ScopedTrace {
2160 // The c'tor pushes the given source file location and message onto
2161 // a trace stack maintained by Google Test.
2163 // Template version. Uses Message() to convert the values into strings.
2164 // Slow, but flexible.
2165 template <typename T>
2166 ScopedTrace(const char* file, int line, const T& message) {
2167 PushTrace(file, line, (Message() << message).GetString());
2170 // Optimize for some known types.
2171 ScopedTrace(const char* file, int line, const char* message) {
2172 PushTrace(file, line, message ? message : "(null)");
2175 #if GTEST_HAS_GLOBAL_STRING
2176 ScopedTrace(const char* file, int line, const ::string& message) {
2177 PushTrace(file, line, message);
2181 ScopedTrace(const char* file, int line, const std::string& message) {
2182 PushTrace(file, line, message);
2185 // The d'tor pops the info pushed by the c'tor.
2187 // Note that the d'tor is not virtual in order to be efficient.
2188 // Don't inherit from ScopedTrace!
2192 void PushTrace(const char* file, int line, std::string message);
2194 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace);
2195 } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its
2196 // c'tor and d'tor. Therefore it doesn't
2197 // need to be used otherwise.
2199 // Causes a trace (including the source file path, the current line
2200 // number, and the given message) to be included in every test failure
2201 // message generated by code in the current scope. The effect is
2202 // undone when the control leaves the current scope.
2204 // The message argument can be anything streamable to std::ostream.
2206 // In the implementation, we include the current line number as part
2207 // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
2208 // to appear in the same block - as long as they are on different
2211 // Assuming that each thread maintains its own stack of traces.
2212 // Therefore, a SCOPED_TRACE() would (correctly) only affect the
2213 // assertions in its own thread.
2214 #define SCOPED_TRACE(message) \
2215 ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
2216 __FILE__, __LINE__, (message))
2219 // Compile-time assertion for type equality.
2220 // StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are
2221 // the same type. The value it returns is not interesting.
2223 // Instead of making StaticAssertTypeEq a class template, we make it a
2224 // function template that invokes a helper class template. This
2225 // prevents a user from misusing StaticAssertTypeEq<T1, T2> by
2226 // defining objects of that type.
2230 // When used inside a method of a class template,
2231 // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
2232 // instantiated. For example, given:
2234 // template <typename T> class Foo {
2236 // void Bar() { testing::StaticAssertTypeEq<int, T>(); }
2241 // void Test1() { Foo<bool> foo; }
2243 // will NOT generate a compiler error, as Foo<bool>::Bar() is never
2244 // actually instantiated. Instead, you need:
2246 // void Test2() { Foo<bool> foo; foo.Bar(); }
2248 // to cause a compiler error.
2249 template <typename T1, typename T2>
2250 bool StaticAssertTypeEq() {
2251 (void)internal::StaticAssertTypeEqHelper<T1, T2>();
2257 // The first parameter is the name of the test case, and the second
2258 // parameter is the name of the test within the test case.
2260 // The convention is to end the test case name with "Test". For
2261 // example, a test case for the Foo class can be named FooTest.
2263 // Test code should appear between braces after an invocation of
2264 // this macro. Example:
2266 // TEST(FooTest, InitializesCorrectly) {
2268 // EXPECT_TRUE(foo.StatusIsOK());
2271 // Note that we call GetTestTypeId() instead of GetTypeId<
2272 // ::testing::Test>() here to get the type ID of testing::Test. This
2273 // is to work around a suspected linker bug when using Google Test as
2274 // a framework on Mac OS X. The bug causes GetTypeId<
2275 // ::testing::Test>() to return different values depending on whether
2276 // the call is from the Google Test framework itself or from user test
2277 // code. GetTestTypeId() is guaranteed to always return the same
2278 // value, as it always calls GetTypeId<>() from the Google Test
2280 #define GTEST_TEST(test_case_name, test_name)\
2281 GTEST_TEST_(test_case_name, test_name, \
2282 ::testing::Test, ::testing::internal::GetTestTypeId())
2284 // Define this macro to 1 to omit the definition of TEST(), which
2285 // is a generic name and clashes with some other libraries.
2286 #if !GTEST_DONT_DEFINE_TEST
2287 # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
2290 // Defines a test that uses a test fixture.
2292 // The first parameter is the name of the test fixture class, which
2293 // also doubles as the test case name. The second parameter is the
2294 // name of the test within the test case.
2296 // A test fixture class must be declared earlier. The user should put
2297 // the test code between braces after using this macro. Example:
2299 // class FooTest : public testing::Test {
2301 // virtual void SetUp() { b_.AddElement(3); }
2307 // TEST_F(FooTest, InitializesCorrectly) {
2308 // EXPECT_TRUE(a_.StatusIsOK());
2311 // TEST_F(FooTest, ReturnsElementCountCorrectly) {
2312 // EXPECT_EQ(a_.size(), 0);
2313 // EXPECT_EQ(b_.size(), 1);
2316 #define TEST_F(test_fixture, test_name)\
2317 GTEST_TEST_(test_fixture, test_name, test_fixture, \
2318 ::testing::internal::GetTypeId<test_fixture>())
2320 // Returns a path to temporary directory.
2321 // Tries to determine an appropriate directory for the platform.
2322 GTEST_API_ std::string TempDir();
2325 # pragma warning(pop)
2328 } // namespace testing
2330 // Use this function in main() to run all tests. It returns 0 if all
2331 // tests are successful, or 1 otherwise.
2333 // RUN_ALL_TESTS() should be invoked after the command line has been
2334 // parsed by InitGoogleTest().
2336 // This function was formerly a macro; thus, it is in the global
2337 // namespace and has an all-caps name.
2338 int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
2340 inline int RUN_ALL_TESTS() {
2341 return ::testing::UnitTest::GetInstance()->Run();
2344 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2346 #endif // GTEST_INCLUDE_GTEST_GTEST_H_