Path: blob/master/dep/googletest/include/gtest/gtest.h
4806 views
// Copyright 2005, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// The Google C++ Testing and Mocking Framework (Google Test)30//31// This header file defines the public API for Google Test. It should be32// included by any test program that uses Google Test.33//34// IMPORTANT NOTE: Due to limitation of the C++ language, we have to35// leave some internal implementation details in this header file.36// They are clearly marked by comments like this:37//38// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.39//40// Such code is NOT meant to be used by a user directly, and is subject41// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user42// program!43//44// Acknowledgment: Google Test borrowed the idea of automatic test45// registration from Barthelemy Dagenais' ([email protected])46// easyUnit framework.4748#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_49#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_5051#include <cstddef>52#include <cstdint>53#include <limits>54#include <memory>55#include <ostream>56#include <set>57#include <sstream>58#include <string>59#include <type_traits>60#include <vector>6162#include "gtest/gtest-assertion-result.h" // IWYU pragma: export63#include "gtest/gtest-death-test.h" // IWYU pragma: export64#include "gtest/gtest-matchers.h" // IWYU pragma: export65#include "gtest/gtest-message.h" // IWYU pragma: export66#include "gtest/gtest-param-test.h" // IWYU pragma: export67#include "gtest/gtest-printers.h" // IWYU pragma: export68#include "gtest/gtest-test-part.h" // IWYU pragma: export69#include "gtest/gtest-typed-test.h" // IWYU pragma: export70#include "gtest/gtest_pred_impl.h" // IWYU pragma: export71#include "gtest/gtest_prod.h" // IWYU pragma: export72#include "gtest/internal/gtest-internal.h"73#include "gtest/internal/gtest-string.h"7475GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \76/* class A needs to have dll-interface to be used by clients of class B */)7778// Declares the flags.7980// This flag temporary enables the disabled tests.81GTEST_DECLARE_bool_(also_run_disabled_tests);8283// This flag brings the debugger on an assertion failure.84GTEST_DECLARE_bool_(break_on_failure);8586// This flag controls whether Google Test catches all test-thrown exceptions87// and logs them as failures.88GTEST_DECLARE_bool_(catch_exceptions);8990// This flag enables using colors in terminal output. Available values are91// "yes" to enable colors, "no" (disable colors), or "auto" (the default)92// to let Google Test decide.93GTEST_DECLARE_string_(color);9495// This flag controls whether the test runner should continue execution past96// first failure.97GTEST_DECLARE_bool_(fail_fast);9899// This flag sets up the filter to select by name using a glob pattern100// the tests to run. If the filter is not given all tests are executed.101GTEST_DECLARE_string_(filter);102103// This flag controls whether Google Test installs a signal handler that dumps104// debugging information when fatal signals are raised.105GTEST_DECLARE_bool_(install_failure_signal_handler);106107// This flag causes the Google Test to list tests. None of the tests listed108// are actually run if the flag is provided.109GTEST_DECLARE_bool_(list_tests);110111// This flag controls whether Google Test emits a detailed XML report to a file112// in addition to its normal textual output.113GTEST_DECLARE_string_(output);114115// This flags control whether Google Test prints only test failures.116GTEST_DECLARE_bool_(brief);117118// This flags control whether Google Test prints the elapsed time for each119// test.120GTEST_DECLARE_bool_(print_time);121122// This flags control whether Google Test prints UTF8 characters as text.123GTEST_DECLARE_bool_(print_utf8);124125// This flag specifies the random number seed.126GTEST_DECLARE_int32_(random_seed);127128// This flag sets how many times the tests are repeated. The default value129// is 1. If the value is -1 the tests are repeating forever.130GTEST_DECLARE_int32_(repeat);131132// This flag controls whether Google Test Environments are recreated for each133// repeat of the tests. The default value is true. If set to false the global134// test Environment objects are only set up once, for the first iteration, and135// only torn down once, for the last.136GTEST_DECLARE_bool_(recreate_environments_when_repeating);137138// This flag controls whether Google Test includes Google Test internal139// stack frames in failure stack traces.140GTEST_DECLARE_bool_(show_internal_stack_frames);141142// When this flag is specified, tests' order is randomized on every iteration.143GTEST_DECLARE_bool_(shuffle);144145// This flag specifies the maximum number of stack frames to be146// printed in a failure message.147GTEST_DECLARE_int32_(stack_trace_depth);148149// When this flag is specified, a failed assertion will throw an150// exception if exceptions are enabled, or exit the program with a151// non-zero code otherwise. For use with an external test framework.152GTEST_DECLARE_bool_(throw_on_failure);153154// When this flag is set with a "host:port" string, on supported155// platforms test results are streamed to the specified port on156// the specified host machine.157GTEST_DECLARE_string_(stream_result_to);158159#if GTEST_USE_OWN_FLAGFILE_FLAG_160GTEST_DECLARE_string_(flagfile);161#endif // GTEST_USE_OWN_FLAGFILE_FLAG_162163namespace testing {164165// Silence C4100 (unreferenced formal parameter) and 4805166// unsafe mix of type 'const int' and type 'const bool'167GTEST_DISABLE_MSC_WARNINGS_PUSH_(4805 4100)168169// The upper limit for valid stack trace depths.170const int kMaxStackTraceDepth = 100;171172namespace internal {173174class AssertHelper;175class DefaultGlobalTestPartResultReporter;176class ExecDeathTest;177class NoExecDeathTest;178class FinalSuccessChecker;179class GTestFlagSaver;180class StreamingListenerTest;181class TestResultAccessor;182class TestEventListenersAccessor;183class TestEventRepeater;184class UnitTestRecordPropertyTestHelper;185class WindowsDeathTest;186class FuchsiaDeathTest;187class UnitTestImpl* GetUnitTestImpl();188void ReportFailureInUnknownLocation(TestPartResult::Type result_type,189const std::string& message);190std::set<std::string>* GetIgnoredParameterizedTestSuites();191192// A base class that prevents subclasses from being copyable.193// We do this instead of using '= delete' so as to avoid triggering warnings194// inside user code regarding any of our declarations.195class GTestNonCopyable {196public:197GTestNonCopyable() = default;198GTestNonCopyable(const GTestNonCopyable&) = delete;199GTestNonCopyable& operator=(const GTestNonCopyable&) = delete;200~GTestNonCopyable() = default;201};202203} // namespace internal204205// The friend relationship of some of these classes is cyclic.206// If we don't forward declare them the compiler might confuse the classes207// in friendship clauses with same named classes on the scope.208class Test;209class TestSuite;210211// Old API is still available but deprecated212#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_213using TestCase = TestSuite;214#endif215class TestInfo;216class UnitTest;217218// The abstract class that all tests inherit from.219//220// In Google Test, a unit test program contains one or many TestSuites, and221// each TestSuite contains one or many Tests.222//223// When you define a test using the TEST macro, you don't need to224// explicitly derive from Test - the TEST macro automatically does225// this for you.226//227// The only time you derive from Test is when defining a test fixture228// to be used in a TEST_F. For example:229//230// class FooTest : public testing::Test {231// protected:232// void SetUp() override { ... }233// void TearDown() override { ... }234// ...235// };236//237// TEST_F(FooTest, Bar) { ... }238// TEST_F(FooTest, Baz) { ... }239//240// Test is not copyable.241class GTEST_API_ Test {242public:243friend class TestInfo;244245// The d'tor is virtual as we intend to inherit from Test.246virtual ~Test();247248// Sets up the stuff shared by all tests in this test suite.249//250// Google Test will call Foo::SetUpTestSuite() before running the first251// test in test suite Foo. Hence a sub-class can define its own252// SetUpTestSuite() method to shadow the one defined in the super253// class.254static void SetUpTestSuite() {}255256// Tears down the stuff shared by all tests in this test suite.257//258// Google Test will call Foo::TearDownTestSuite() after running the last259// test in test suite Foo. Hence a sub-class can define its own260// TearDownTestSuite() method to shadow the one defined in the super261// class.262static void TearDownTestSuite() {}263264// Legacy API is deprecated but still available. Use SetUpTestSuite and265// TearDownTestSuite instead.266#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_267static void TearDownTestCase() {}268static void SetUpTestCase() {}269#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_270271// Returns true if and only if the current test has a fatal failure.272static bool HasFatalFailure();273274// Returns true if and only if the current test has a non-fatal failure.275static bool HasNonfatalFailure();276277// Returns true if and only if the current test was skipped.278static bool IsSkipped();279280// Returns true if and only if the current test has a (either fatal or281// non-fatal) failure.282static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }283284// Logs a property for the current test, test suite, or for the entire285// invocation of the test program when used outside of the context of a286// test suite. Only the last value for a given key is remembered. These287// are public static so they can be called from utility functions that are288// not members of the test fixture. Calls to RecordProperty made during289// lifespan of the test (from the moment its constructor starts to the290// moment its destructor finishes) will be output in XML as attributes of291// the <testcase> element. Properties recorded from fixture's292// SetUpTestSuite or TearDownTestSuite are logged as attributes of the293// corresponding <testsuite> element. Calls to RecordProperty made in the294// global context (before or after invocation of RUN_ALL_TESTS and from295// SetUp/TearDown method of Environment objects registered with Google296// Test) will be output as attributes of the <testsuites> element.297static void RecordProperty(const std::string& key, const std::string& value);298// We do not define a custom serialization except for values that can be299// converted to int64_t, but other values could be logged in this way.300template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value,301bool> = true>302static void RecordProperty(const std::string& key, const T& value) {303RecordProperty(key, (Message() << value).GetString());304}305306protected:307// Creates a Test object.308Test();309310// Sets up the test fixture.311virtual void SetUp();312313// Tears down the test fixture.314virtual void TearDown();315316private:317// Returns true if and only if the current test has the same fixture class318// as the first test in the current test suite.319static bool HasSameFixtureClass();320321// Runs the test after the test fixture has been set up.322//323// A sub-class must implement this to define the test logic.324//325// DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.326// Instead, use the TEST or TEST_F macro.327virtual void TestBody() = 0;328329// Sets up, executes, and tears down the test.330void Run();331332// Deletes self. We deliberately pick an unusual name for this333// internal method to avoid clashing with names used in user TESTs.334void DeleteSelf_() { delete this; }335336const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;337338// Often a user misspells SetUp() as Setup() and spends a long time339// wondering why it is never called by Google Test. The declaration of340// the following method is solely for catching such an error at341// compile time:342//343// - The return type is deliberately chosen to be not void, so it344// will be a conflict if void Setup() is declared in the user's345// test fixture.346//347// - This method is private, so it will be another compiler error348// if the method is called from the user's test fixture.349//350// DO NOT OVERRIDE THIS FUNCTION.351//352// If you see an error about overriding the following function or353// about it being private, you have mis-spelled SetUp() as Setup().354struct Setup_should_be_spelled_SetUp {};355virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }356357// We disallow copying Tests.358Test(const Test&) = delete;359Test& operator=(const Test&) = delete;360};361362typedef internal::TimeInMillis TimeInMillis;363364// A copyable object representing a user specified test property which can be365// output as a key/value string pair.366//367// Don't inherit from TestProperty as its destructor is not virtual.368class TestProperty {369public:370// C'tor. TestProperty does NOT have a default constructor.371// Always use this constructor (with parameters) to create a372// TestProperty object.373TestProperty(const std::string& a_key, const std::string& a_value)374: key_(a_key), value_(a_value) {}375376// Gets the user supplied key.377const char* key() const { return key_.c_str(); }378379// Gets the user supplied value.380const char* value() const { return value_.c_str(); }381382// Sets a new value, overriding the one supplied in the constructor.383void SetValue(const std::string& new_value) { value_ = new_value; }384385private:386// The key supplied by the user.387std::string key_;388// The value supplied by the user.389std::string value_;390};391392// The result of a single Test. This includes a list of393// TestPartResults, a list of TestProperties, a count of how many394// death tests there are in the Test, and how much time it took to run395// the Test.396//397// TestResult is not copyable.398class GTEST_API_ TestResult {399public:400// Creates an empty TestResult.401TestResult();402403// D'tor. Do not inherit from TestResult.404~TestResult();405406// Gets the number of all test parts. This is the sum of the number407// of successful test parts and the number of failed test parts.408int total_part_count() const;409410// Returns the number of the test properties.411int test_property_count() const;412413// Returns true if and only if the test passed (i.e. no test part failed).414bool Passed() const { return !Skipped() && !Failed(); }415416// Returns true if and only if the test was skipped.417bool Skipped() const;418419// Returns true if and only if the test failed.420bool Failed() const;421422// Returns true if and only if the test fatally failed.423bool HasFatalFailure() const;424425// Returns true if and only if the test has a non-fatal failure.426bool HasNonfatalFailure() const;427428// Returns the elapsed time, in milliseconds.429TimeInMillis elapsed_time() const { return elapsed_time_; }430431// Gets the time of the test case start, in ms from the start of the432// UNIX epoch.433TimeInMillis start_timestamp() const { return start_timestamp_; }434435// Returns the i-th test part result among all the results. i can range from 0436// to total_part_count() - 1. If i is not in that range, aborts the program.437const TestPartResult& GetTestPartResult(int i) const;438439// Returns the i-th test property. i can range from 0 to440// test_property_count() - 1. If i is not in that range, aborts the441// program.442const TestProperty& GetTestProperty(int i) const;443444private:445friend class TestInfo;446friend class TestSuite;447friend class UnitTest;448friend class internal::DefaultGlobalTestPartResultReporter;449friend class internal::ExecDeathTest;450friend class internal::TestResultAccessor;451friend class internal::UnitTestImpl;452friend class internal::WindowsDeathTest;453friend class internal::FuchsiaDeathTest;454455// Gets the vector of TestPartResults.456const std::vector<TestPartResult>& test_part_results() const {457return test_part_results_;458}459460// Gets the vector of TestProperties.461const std::vector<TestProperty>& test_properties() const {462return test_properties_;463}464465// Sets the start time.466void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }467468// Sets the elapsed time.469void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }470471// Adds a test property to the list. The property is validated and may add472// a non-fatal failure if invalid (e.g., if it conflicts with reserved473// key names). If a property is already recorded for the same key, the474// value will be updated, rather than storing multiple values for the same475// key. xml_element specifies the element for which the property is being476// recorded and is used for validation.477void RecordProperty(const std::string& xml_element,478const TestProperty& test_property);479480// Adds a failure if the key is a reserved attribute of Google Test481// testsuite tags. Returns true if the property is valid.482// FIXME: Validate attribute names are legal and human readable.483static bool ValidateTestProperty(const std::string& xml_element,484const TestProperty& test_property);485486// Adds a test part result to the list.487void AddTestPartResult(const TestPartResult& test_part_result);488489// Returns the death test count.490int death_test_count() const { return death_test_count_; }491492// Increments the death test count, returning the new count.493int increment_death_test_count() { return ++death_test_count_; }494495// Clears the test part results.496void ClearTestPartResults();497498// Clears the object.499void Clear();500501// Protects mutable state of the property vector and of owned502// properties, whose values may be updated.503internal::Mutex test_properties_mutex_;504505// The vector of TestPartResults506std::vector<TestPartResult> test_part_results_;507// The vector of TestProperties508std::vector<TestProperty> test_properties_;509// Running count of death tests.510int death_test_count_;511// The start time, in milliseconds since UNIX Epoch.512TimeInMillis start_timestamp_;513// The elapsed time, in milliseconds.514TimeInMillis elapsed_time_;515516// We disallow copying TestResult.517TestResult(const TestResult&) = delete;518TestResult& operator=(const TestResult&) = delete;519}; // class TestResult520521// A TestInfo object stores the following information about a test:522//523// Test suite name524// Test name525// Whether the test should be run526// A function pointer that creates the test object when invoked527// Test result528//529// The constructor of TestInfo registers itself with the UnitTest530// singleton such that the RUN_ALL_TESTS() macro knows which tests to531// run.532class GTEST_API_ TestInfo {533public:534// Destructs a TestInfo object. This function is not virtual, so535// don't inherit from TestInfo.536~TestInfo();537538// Returns the test suite name.539const char* test_suite_name() const { return test_suite_name_.c_str(); }540541// Legacy API is deprecated but still available542#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_543const char* test_case_name() const { return test_suite_name(); }544#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_545546// Returns the test name.547const char* name() const { return name_.c_str(); }548549// Returns the name of the parameter type, or NULL if this is not a typed550// or a type-parameterized test.551const char* type_param() const {552if (type_param_ != nullptr) return type_param_->c_str();553return nullptr;554}555556// Returns the text representation of the value parameter, or NULL if this557// is not a value-parameterized test.558const char* value_param() const {559if (value_param_ != nullptr) return value_param_->c_str();560return nullptr;561}562563// Returns the file name where this test is defined.564const char* file() const { return location_.file.c_str(); }565566// Returns the line where this test is defined.567int line() const { return location_.line; }568569// Return true if this test should not be run because it's in another shard.570bool is_in_another_shard() const { return is_in_another_shard_; }571572// Returns true if this test should run, that is if the test is not573// disabled (or it is disabled but the also_run_disabled_tests flag has574// been specified) and its full name matches the user-specified filter.575//576// Google Test allows the user to filter the tests by their full names.577// The full name of a test Bar in test suite Foo is defined as578// "Foo.Bar". Only the tests that match the filter will run.579//580// A filter is a colon-separated list of glob (not regex) patterns,581// optionally followed by a '-' and a colon-separated list of582// negative patterns (tests to exclude). A test is run if it583// matches one of the positive patterns and does not match any of584// the negative patterns.585//586// For example, *A*:Foo.* is a filter that matches any string that587// contains the character 'A' or starts with "Foo.".588bool should_run() const { return should_run_; }589590// Returns true if and only if this test will appear in the XML report.591bool is_reportable() const {592// The XML report includes tests matching the filter, excluding those593// run in other shards.594return matches_filter_ && !is_in_another_shard_;595}596597// Returns the result of the test.598const TestResult* result() const { return &result_; }599600private:601#ifdef GTEST_HAS_DEATH_TEST602friend class internal::DefaultDeathTestFactory;603#endif // GTEST_HAS_DEATH_TEST604friend class Test;605friend class TestSuite;606friend class internal::UnitTestImpl;607friend class internal::StreamingListenerTest;608friend TestInfo* internal::MakeAndRegisterTestInfo(609std::string test_suite_name, const char* name, const char* type_param,610const char* value_param, internal::CodeLocation code_location,611internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,612internal::TearDownTestSuiteFunc tear_down_tc,613internal::TestFactoryBase* factory);614615// Constructs a TestInfo object. The newly constructed instance assumes616// ownership of the factory object.617TestInfo(std::string test_suite_name, std::string name,618const char* a_type_param, // NULL if not a type-parameterized test619const char* a_value_param, // NULL if not a value-parameterized test620internal::CodeLocation a_code_location,621internal::TypeId fixture_class_id,622internal::TestFactoryBase* factory);623624// Increments the number of death tests encountered in this test so625// far.626int increment_death_test_count() {627return result_.increment_death_test_count();628}629630// Creates the test object, runs it, records its result, and then631// deletes it.632void Run();633634// Skip and records the test result for this object.635void Skip();636637static void ClearTestResult(TestInfo* test_info) {638test_info->result_.Clear();639}640641// These fields are immutable properties of the test.642const std::string test_suite_name_; // test suite name643const std::string name_; // Test name644// Name of the parameter type, or NULL if this is not a typed or a645// type-parameterized test.646const std::unique_ptr<const ::std::string> type_param_;647// Text representation of the value parameter, or NULL if this is not a648// value-parameterized test.649const std::unique_ptr<const ::std::string> value_param_;650internal::CodeLocation location_;651const internal::TypeId fixture_class_id_; // ID of the test fixture class652bool should_run_; // True if and only if this test should run653bool is_disabled_; // True if and only if this test is disabled654bool matches_filter_; // True if this test matches the655// user-specified filter.656bool is_in_another_shard_; // Will be run in another shard.657internal::TestFactoryBase* const factory_; // The factory that creates658// the test object659660// This field is mutable and needs to be reset before running the661// test for the second time.662TestResult result_;663664TestInfo(const TestInfo&) = delete;665TestInfo& operator=(const TestInfo&) = delete;666};667668// A test suite, which consists of a vector of TestInfos.669//670// TestSuite is not copyable.671class GTEST_API_ TestSuite {672public:673// Creates a TestSuite with the given name.674//675// TestSuite does NOT have a default constructor. Always use this676// constructor to create a TestSuite object.677//678// Arguments:679//680// name: name of the test suite681// a_type_param: the name of the test's type parameter, or NULL if682// this is not a type-parameterized test.683// set_up_tc: pointer to the function that sets up the test suite684// tear_down_tc: pointer to the function that tears down the test suite685TestSuite(const std::string& name, const char* a_type_param,686internal::SetUpTestSuiteFunc set_up_tc,687internal::TearDownTestSuiteFunc tear_down_tc);688689// Destructor of TestSuite.690virtual ~TestSuite();691692// Gets the name of the TestSuite.693const char* name() const { return name_.c_str(); }694695// Returns the name of the parameter type, or NULL if this is not a696// type-parameterized test suite.697const char* type_param() const {698if (type_param_ != nullptr) return type_param_->c_str();699return nullptr;700}701702// Returns true if any test in this test suite should run.703bool should_run() const { return should_run_; }704705// Gets the number of successful tests in this test suite.706int successful_test_count() const;707708// Gets the number of skipped tests in this test suite.709int skipped_test_count() const;710711// Gets the number of failed tests in this test suite.712int failed_test_count() const;713714// Gets the number of disabled tests that will be reported in the XML report.715int reportable_disabled_test_count() const;716717// Gets the number of disabled tests in this test suite.718int disabled_test_count() const;719720// Gets the number of tests to be printed in the XML report.721int reportable_test_count() const;722723// Get the number of tests in this test suite that should run.724int test_to_run_count() const;725726// Gets the number of all tests in this test suite.727int total_test_count() const;728729// Returns true if and only if the test suite passed.730bool Passed() const { return !Failed(); }731732// Returns true if and only if the test suite failed.733bool Failed() const {734return failed_test_count() > 0 || ad_hoc_test_result().Failed();735}736737// Returns the elapsed time, in milliseconds.738TimeInMillis elapsed_time() const { return elapsed_time_; }739740// Gets the time of the test suite start, in ms from the start of the741// UNIX epoch.742TimeInMillis start_timestamp() const { return start_timestamp_; }743744// Returns the i-th test among all the tests. i can range from 0 to745// total_test_count() - 1. If i is not in that range, returns NULL.746const TestInfo* GetTestInfo(int i) const;747748// Returns the TestResult that holds test properties recorded during749// execution of SetUpTestSuite and TearDownTestSuite.750const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }751752private:753friend class Test;754friend class internal::UnitTestImpl;755756// Gets the (mutable) vector of TestInfos in this TestSuite.757std::vector<TestInfo*>& test_info_list() { return test_info_list_; }758759// Gets the (immutable) vector of TestInfos in this TestSuite.760const std::vector<TestInfo*>& test_info_list() const {761return test_info_list_;762}763764// Returns the i-th test among all the tests. i can range from 0 to765// total_test_count() - 1. If i is not in that range, returns NULL.766TestInfo* GetMutableTestInfo(int i);767768// Sets the should_run member.769void set_should_run(bool should) { should_run_ = should; }770771// Adds a TestInfo to this test suite. Will delete the TestInfo upon772// destruction of the TestSuite object.773void AddTestInfo(TestInfo* test_info);774775// Clears the results of all tests in this test suite.776void ClearResult();777778// Clears the results of all tests in the given test suite.779static void ClearTestSuiteResult(TestSuite* test_suite) {780test_suite->ClearResult();781}782783// Runs every test in this TestSuite.784void Run();785786// Skips the execution of tests under this TestSuite787void Skip();788789// Runs SetUpTestSuite() for this TestSuite. This wrapper is needed790// for catching exceptions thrown from SetUpTestSuite().791void RunSetUpTestSuite() {792if (set_up_tc_ != nullptr) {793(*set_up_tc_)();794}795}796797// Runs TearDownTestSuite() for this TestSuite. This wrapper is798// needed for catching exceptions thrown from TearDownTestSuite().799void RunTearDownTestSuite() {800if (tear_down_tc_ != nullptr) {801(*tear_down_tc_)();802}803}804805// Returns true if and only if test passed.806static bool TestPassed(const TestInfo* test_info) {807return test_info->should_run() && test_info->result()->Passed();808}809810// Returns true if and only if test skipped.811static bool TestSkipped(const TestInfo* test_info) {812return test_info->should_run() && test_info->result()->Skipped();813}814815// Returns true if and only if test failed.816static bool TestFailed(const TestInfo* test_info) {817return test_info->should_run() && test_info->result()->Failed();818}819820// Returns true if and only if the test is disabled and will be reported in821// the XML report.822static bool TestReportableDisabled(const TestInfo* test_info) {823return test_info->is_reportable() && test_info->is_disabled_;824}825826// Returns true if and only if test is disabled.827static bool TestDisabled(const TestInfo* test_info) {828return test_info->is_disabled_;829}830831// Returns true if and only if this test will appear in the XML report.832static bool TestReportable(const TestInfo* test_info) {833return test_info->is_reportable();834}835836// Returns true if the given test should run.837static bool ShouldRunTest(const TestInfo* test_info) {838return test_info->should_run();839}840841// Shuffles the tests in this test suite.842void ShuffleTests(internal::Random* random);843844// Restores the test order to before the first shuffle.845void UnshuffleTests();846847// Name of the test suite.848std::string name_;849// Name of the parameter type, or NULL if this is not a typed or a850// type-parameterized test.851const std::unique_ptr<const ::std::string> type_param_;852// The vector of TestInfos in their original order. It owns the853// elements in the vector.854std::vector<TestInfo*> test_info_list_;855// Provides a level of indirection for the test list to allow easy856// shuffling and restoring the test order. The i-th element in this857// vector is the index of the i-th test in the shuffled test list.858std::vector<int> test_indices_;859// Pointer to the function that sets up the test suite.860internal::SetUpTestSuiteFunc set_up_tc_;861// Pointer to the function that tears down the test suite.862internal::TearDownTestSuiteFunc tear_down_tc_;863// True if and only if any test in this test suite should run.864bool should_run_;865// The start time, in milliseconds since UNIX Epoch.866TimeInMillis start_timestamp_;867// Elapsed time, in milliseconds.868TimeInMillis elapsed_time_;869// Holds test properties recorded during execution of SetUpTestSuite and870// TearDownTestSuite.871TestResult ad_hoc_test_result_;872873// We disallow copying TestSuites.874TestSuite(const TestSuite&) = delete;875TestSuite& operator=(const TestSuite&) = delete;876};877878// An Environment object is capable of setting up and tearing down an879// environment. You should subclass this to define your own880// environment(s).881//882// An Environment object does the set-up and tear-down in virtual883// methods SetUp() and TearDown() instead of the constructor and the884// destructor, as:885//886// 1. You cannot safely throw from a destructor. This is a problem887// as in some cases Google Test is used where exceptions are enabled, and888// we may want to implement ASSERT_* using exceptions where they are889// available.890// 2. You cannot use ASSERT_* directly in a constructor or891// destructor.892class Environment {893public:894// The d'tor is virtual as we need to subclass Environment.895virtual ~Environment() = default;896897// Override this to define how to set up the environment.898virtual void SetUp() {}899900// Override this to define how to tear down the environment.901virtual void TearDown() {}902903private:904// If you see an error about overriding the following function or905// about it being private, you have mis-spelled SetUp() as Setup().906struct Setup_should_be_spelled_SetUp {};907virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }908};909910#if GTEST_HAS_EXCEPTIONS911912// Exception which can be thrown from TestEventListener::OnTestPartResult.913class GTEST_API_ AssertionException914: public internal::GoogleTestFailureException {915public:916explicit AssertionException(const TestPartResult& result)917: GoogleTestFailureException(result) {}918};919920#endif // GTEST_HAS_EXCEPTIONS921922// The interface for tracing execution of tests. The methods are organized in923// the order the corresponding events are fired.924class TestEventListener {925public:926virtual ~TestEventListener() = default;927928// Fired before any test activity starts.929virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;930931// Fired before each iteration of tests starts. There may be more than932// one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration933// index, starting from 0.934virtual void OnTestIterationStart(const UnitTest& unit_test,935int iteration) = 0;936937// Fired before environment set-up for each iteration of tests starts.938virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;939940// Fired after environment set-up for each iteration of tests ends.941virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;942943// Fired before the test suite starts.944virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}945946// Legacy API is deprecated but still available947#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_948virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}949#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_950951// Fired before the test starts.952virtual void OnTestStart(const TestInfo& test_info) = 0;953954// Fired when a test is disabled955virtual void OnTestDisabled(const TestInfo& /*test_info*/) {}956957// Fired after a failed assertion or a SUCCEED() invocation.958// If you want to throw an exception from this function to skip to the next959// TEST, it must be AssertionException defined above, or inherited from it.960virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;961962// Fired after the test ends.963virtual void OnTestEnd(const TestInfo& test_info) = 0;964965// Fired after the test suite ends.966virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}967968// Legacy API is deprecated but still available969#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_970virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}971#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_972973// Fired before environment tear-down for each iteration of tests starts.974virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;975976// Fired after environment tear-down for each iteration of tests ends.977virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;978979// Fired after each iteration of tests finishes.980virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0;981982// Fired after all test activities have ended.983virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;984};985986// The convenience class for users who need to override just one or two987// methods and are not concerned that a possible change to a signature of988// the methods they override will not be caught during the build. For989// comments about each method please see the definition of TestEventListener990// above.991class EmptyTestEventListener : public TestEventListener {992public:993void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}994void OnTestIterationStart(const UnitTest& /*unit_test*/,995int /*iteration*/) override {}996void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}997void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}998void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}999// Legacy API is deprecated but still available1000#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_1001void OnTestCaseStart(const TestCase& /*test_case*/) override {}1002#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_10031004void OnTestStart(const TestInfo& /*test_info*/) override {}1005void OnTestDisabled(const TestInfo& /*test_info*/) override {}1006void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}1007void OnTestEnd(const TestInfo& /*test_info*/) override {}1008void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}1009#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_1010void OnTestCaseEnd(const TestCase& /*test_case*/) override {}1011#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_10121013void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}1014void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}1015void OnTestIterationEnd(const UnitTest& /*unit_test*/,1016int /*iteration*/) override {}1017void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}1018};10191020// TestEventListeners lets users add listeners to track events in Google Test.1021class GTEST_API_ TestEventListeners {1022public:1023TestEventListeners();1024~TestEventListeners();10251026// Appends an event listener to the end of the list. Google Test assumes1027// the ownership of the listener (i.e. it will delete the listener when1028// the test program finishes).1029void Append(TestEventListener* listener);10301031// Removes the given event listener from the list and returns it. It then1032// becomes the caller's responsibility to delete the listener. Returns1033// NULL if the listener is not found in the list.1034TestEventListener* Release(TestEventListener* listener);10351036// Returns the standard listener responsible for the default console1037// output. Can be removed from the listeners list to shut down default1038// console output. Note that removing this object from the listener list1039// with Release transfers its ownership to the caller and makes this1040// function return NULL the next time.1041TestEventListener* default_result_printer() const {1042return default_result_printer_;1043}10441045// Returns the standard listener responsible for the default XML output1046// controlled by the --gtest_output=xml flag. Can be removed from the1047// listeners list by users who want to shut down the default XML output1048// controlled by this flag and substitute it with custom one. Note that1049// removing this object from the listener list with Release transfers its1050// ownership to the caller and makes this function return NULL the next1051// time.1052TestEventListener* default_xml_generator() const {1053return default_xml_generator_;1054}10551056// Controls whether events will be forwarded by the repeater to the1057// listeners in the list.1058void SuppressEventForwarding(bool);10591060private:1061friend class TestSuite;1062friend class TestInfo;1063friend class internal::DefaultGlobalTestPartResultReporter;1064friend class internal::NoExecDeathTest;1065friend class internal::TestEventListenersAccessor;1066friend class internal::UnitTestImpl;10671068// Returns repeater that broadcasts the TestEventListener events to all1069// subscribers.1070TestEventListener* repeater();10711072// Sets the default_result_printer attribute to the provided listener.1073// The listener is also added to the listener list and previous1074// default_result_printer is removed from it and deleted. The listener can1075// also be NULL in which case it will not be added to the list. Does1076// nothing if the previous and the current listener objects are the same.1077void SetDefaultResultPrinter(TestEventListener* listener);10781079// Sets the default_xml_generator attribute to the provided listener. The1080// listener is also added to the listener list and previous1081// default_xml_generator is removed from it and deleted. The listener can1082// also be NULL in which case it will not be added to the list. Does1083// nothing if the previous and the current listener objects are the same.1084void SetDefaultXmlGenerator(TestEventListener* listener);10851086// Controls whether events will be forwarded by the repeater to the1087// listeners in the list.1088bool EventForwardingEnabled() const;10891090// The actual list of listeners.1091internal::TestEventRepeater* repeater_;1092// Listener responsible for the standard result output.1093TestEventListener* default_result_printer_;1094// Listener responsible for the creation of the XML output file.1095TestEventListener* default_xml_generator_;10961097// We disallow copying TestEventListeners.1098TestEventListeners(const TestEventListeners&) = delete;1099TestEventListeners& operator=(const TestEventListeners&) = delete;1100};11011102// A UnitTest consists of a vector of TestSuites.1103//1104// This is a singleton class. The only instance of UnitTest is1105// created when UnitTest::GetInstance() is first called. This1106// instance is never deleted.1107//1108// UnitTest is not copyable.1109//1110// This class is thread-safe as long as the methods are called1111// according to their specification.1112class GTEST_API_ UnitTest {1113public:1114// Gets the singleton UnitTest object. The first time this method1115// is called, a UnitTest object is constructed and returned.1116// Consecutive calls will return the same object.1117static UnitTest* GetInstance();11181119// Runs all tests in this UnitTest object and prints the result.1120// Returns 0 if successful, or 1 otherwise.1121//1122// This method can only be called from the main thread.1123//1124// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1125[[nodiscard]] int Run();11261127// Returns the working directory when the first TEST() or TEST_F()1128// was executed. The UnitTest object owns the string.1129const char* original_working_dir() const;11301131// Returns the TestSuite object for the test that's currently running,1132// or NULL if no test is running.1133const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);11341135// Legacy API is still available but deprecated1136#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_1137const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);1138#endif11391140// Returns the TestInfo object for the test that's currently running,1141// or NULL if no test is running.1142const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_);11431144// Returns the random seed used at the start of the current test run.1145int random_seed() const;11461147// Returns the ParameterizedTestSuiteRegistry object used to keep track of1148// value-parameterized tests and instantiate and register them.1149//1150// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1151internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()1152GTEST_LOCK_EXCLUDED_(mutex_);11531154// Gets the number of successful test suites.1155int successful_test_suite_count() const;11561157// Gets the number of failed test suites.1158int failed_test_suite_count() const;11591160// Gets the number of all test suites.1161int total_test_suite_count() const;11621163// Gets the number of all test suites that contain at least one test1164// that should run.1165int test_suite_to_run_count() const;11661167// Legacy API is deprecated but still available1168#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_1169int successful_test_case_count() const;1170int failed_test_case_count() const;1171int total_test_case_count() const;1172int test_case_to_run_count() const;1173#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_11741175// Gets the number of successful tests.1176int successful_test_count() const;11771178// Gets the number of skipped tests.1179int skipped_test_count() const;11801181// Gets the number of failed tests.1182int failed_test_count() const;11831184// Gets the number of disabled tests that will be reported in the XML report.1185int reportable_disabled_test_count() const;11861187// Gets the number of disabled tests.1188int disabled_test_count() const;11891190// Gets the number of tests to be printed in the XML report.1191int reportable_test_count() const;11921193// Gets the number of all tests.1194int total_test_count() const;11951196// Gets the number of tests that should run.1197int test_to_run_count() const;11981199// Gets the time of the test program start, in ms from the start of the1200// UNIX epoch.1201TimeInMillis start_timestamp() const;12021203// Gets the elapsed time, in milliseconds.1204TimeInMillis elapsed_time() const;12051206// Returns true if and only if the unit test passed (i.e. all test suites1207// passed).1208bool Passed() const;12091210// Returns true if and only if the unit test failed (i.e. some test suite1211// failed or something outside of all tests failed).1212bool Failed() const;12131214// Gets the i-th test suite among all the test suites. i can range from 0 to1215// total_test_suite_count() - 1. If i is not in that range, returns NULL.1216const TestSuite* GetTestSuite(int i) const;12171218// Legacy API is deprecated but still available1219#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_1220const TestCase* GetTestCase(int i) const;1221#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_12221223// Returns the TestResult containing information on test failures and1224// properties logged outside of individual test suites.1225const TestResult& ad_hoc_test_result() const;12261227// Returns the list of event listeners that can be used to track events1228// inside Google Test.1229TestEventListeners& listeners();12301231private:1232// Registers and returns a global test environment. When a test1233// program is run, all global test environments will be set-up in1234// the order they were registered. After all tests in the program1235// have finished, all global test environments will be torn-down in1236// the *reverse* order they were registered.1237//1238// The UnitTest object takes ownership of the given environment.1239//1240// This method can only be called from the main thread.1241Environment* AddEnvironment(Environment* env);12421243// Adds a TestPartResult to the current TestResult object. All1244// Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)1245// eventually call this to report their results. The user code1246// should use the assertion macros instead of calling this directly.1247void AddTestPartResult(TestPartResult::Type result_type,1248const char* file_name, int line_number,1249const std::string& message,1250const std::string& os_stack_trace)1251GTEST_LOCK_EXCLUDED_(mutex_);12521253// Adds a TestProperty to the current TestResult object when invoked from1254// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked1255// from SetUpTestSuite or TearDownTestSuite, or to the global property set1256// when invoked elsewhere. If the result already contains a property with1257// the same key, the value will be updated.1258void RecordProperty(const std::string& key, const std::string& value);12591260// Gets the i-th test suite among all the test suites. i can range from 0 to1261// total_test_suite_count() - 1. If i is not in that range, returns NULL.1262TestSuite* GetMutableTestSuite(int i);12631264// Invokes OsStackTrackGetterInterface::UponLeavingGTest. UponLeavingGTest()1265// should be called immediately before Google Test calls user code. It saves1266// some information about the current stack that CurrentStackTrace() will use1267// to find and hide Google Test stack frames.1268void UponLeavingGTest();12691270// Sets the TestSuite object for the test that's currently running.1271void set_current_test_suite(TestSuite* a_current_test_suite)1272GTEST_LOCK_EXCLUDED_(mutex_);12731274// Sets the TestInfo object for the test that's currently running.1275void set_current_test_info(TestInfo* a_current_test_info)1276GTEST_LOCK_EXCLUDED_(mutex_);12771278// Accessors for the implementation object.1279internal::UnitTestImpl* impl() { return impl_; }1280const internal::UnitTestImpl* impl() const { return impl_; }12811282// These classes and functions are friends as they need to access private1283// members of UnitTest.1284friend class ScopedTrace;1285friend class Test;1286friend class TestInfo;1287friend class TestSuite;1288friend class internal::AssertHelper;1289friend class internal::StreamingListenerTest;1290friend class internal::UnitTestRecordPropertyTestHelper;1291friend Environment* AddGlobalTestEnvironment(Environment* env);1292friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();1293friend internal::UnitTestImpl* internal::GetUnitTestImpl();1294friend void internal::ReportFailureInUnknownLocation(1295TestPartResult::Type result_type, const std::string& message);12961297// Creates an empty UnitTest.1298UnitTest();12991300// D'tor1301virtual ~UnitTest();13021303// Pushes a trace defined by SCOPED_TRACE() on to the per-thread1304// Google Test trace stack.1305void PushGTestTrace(const internal::TraceInfo& trace)1306GTEST_LOCK_EXCLUDED_(mutex_);13071308// Pops a trace from the per-thread Google Test trace stack.1309void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_);13101311// Protects mutable state in *impl_. This is mutable as some const1312// methods need to lock it too.1313mutable internal::Mutex mutex_;13141315// Opaque implementation object. This field is never changed once1316// the object is constructed. We don't mark it as const here, as1317// doing so will cause a warning in the constructor of UnitTest.1318// Mutable state in *impl_ is protected by mutex_.1319internal::UnitTestImpl* impl_;13201321// We disallow copying UnitTest.1322UnitTest(const UnitTest&) = delete;1323UnitTest& operator=(const UnitTest&) = delete;1324};13251326// A convenient wrapper for adding an environment for the test1327// program.1328//1329// You should call this before RUN_ALL_TESTS() is called, probably in1330// main(). If you use gtest_main, you need to call this before main()1331// starts for it to take effect. For example, you can define a global1332// variable like this:1333//1334// testing::Environment* const foo_env =1335// testing::AddGlobalTestEnvironment(new FooEnvironment);1336//1337// However, we strongly recommend you to write your own main() and1338// call AddGlobalTestEnvironment() there, as relying on initialization1339// of global variables makes the code harder to read and may cause1340// problems when you register multiple environments from different1341// translation units and the environments have dependencies among them1342// (remember that the compiler doesn't guarantee the order in which1343// global variables from different translation units are initialized).1344inline Environment* AddGlobalTestEnvironment(Environment* env) {1345return UnitTest::GetInstance()->AddEnvironment(env);1346}13471348// Initializes Google Test. This must be called before calling1349// RUN_ALL_TESTS(). In particular, it parses a command line for the1350// flags that Google Test recognizes. Whenever a Google Test flag is1351// seen, it is removed from argv, and *argc is decremented.1352//1353// No value is returned. Instead, the Google Test flag variables are1354// updated.1355//1356// Calling the function for the second time has no user-visible effect.1357GTEST_API_ void InitGoogleTest(int* argc, char** argv);13581359// This overloaded version can be used in Windows programs compiled in1360// UNICODE mode.1361GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);13621363// This overloaded version can be used on Arduino/embedded platforms where1364// there is no argc/argv.1365GTEST_API_ void InitGoogleTest();13661367namespace internal {13681369// Separate the error generating code from the code path to reduce the stack1370// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers1371// when calling EXPECT_* in a tight loop.1372template <typename T1, typename T2>1373AssertionResult CmpHelperEQFailure(const char* lhs_expression,1374const char* rhs_expression, const T1& lhs,1375const T2& rhs) {1376return EqFailure(lhs_expression, rhs_expression,1377FormatForComparisonFailureMessage(lhs, rhs),1378FormatForComparisonFailureMessage(rhs, lhs), false);1379}13801381// This block of code defines operator==/!=1382// to block lexical scope lookup.1383// It prevents using invalid operator==/!= defined at namespace scope.1384struct faketype {};1385inline bool operator==(faketype, faketype) { return true; }1386inline bool operator!=(faketype, faketype) { return false; }13871388// The helper function for {ASSERT|EXPECT}_EQ.1389template <typename T1, typename T2>1390AssertionResult CmpHelperEQ(const char* lhs_expression,1391const char* rhs_expression, const T1& lhs,1392const T2& rhs) {1393if (lhs == rhs) {1394return AssertionSuccess();1395}13961397return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);1398}13991400class EqHelper {1401public:1402// This templatized version is for the general case.1403template <1404typename T1, typename T2,1405// Disable this overload for cases where one argument is a pointer1406// and the other is the null pointer constant.1407typename std::enable_if<!std::is_integral<T1>::value ||1408!std::is_pointer<T2>::value>::type* = nullptr>1409static AssertionResult Compare(const char* lhs_expression,1410const char* rhs_expression, const T1& lhs,1411const T2& rhs) {1412return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);1413}14141415// With this overloaded version, we allow anonymous enums to be used1416// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous1417// enums can be implicitly cast to BiggestInt.1418//1419// Even though its body looks the same as the above version, we1420// cannot merge the two, as it will make anonymous enums unhappy.1421static AssertionResult Compare(const char* lhs_expression,1422const char* rhs_expression, BiggestInt lhs,1423BiggestInt rhs) {1424return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);1425}14261427template <typename T>1428static AssertionResult Compare(1429const char* lhs_expression, const char* rhs_expression,1430// Handle cases where '0' is used as a null pointer literal.1431std::nullptr_t /* lhs */, T* rhs) {1432// We already know that 'lhs' is a null pointer.1433return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),1434rhs);1435}1436};14371438// Separate the error generating code from the code path to reduce the stack1439// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers1440// when calling EXPECT_OP in a tight loop.1441template <typename T1, typename T2>1442AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,1443const T1& val1, const T2& val2,1444const char* op) {1445return AssertionFailure()1446<< "Expected: (" << expr1 << ") " << op << " (" << expr21447<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)1448<< " vs " << FormatForComparisonFailureMessage(val2, val1);1449}14501451// A macro for implementing the helper functions needed to implement1452// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste1453// of similar code.1454//1455// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.14561457#define GTEST_IMPL_CMP_HELPER_(op_name, op) \1458template <typename T1, typename T2> \1459AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \1460const T1& val1, const T2& val2) { \1461if (val1 op val2) { \1462return AssertionSuccess(); \1463} else { \1464return CmpHelperOpFailure(expr1, expr2, val1, val2, #op); \1465} \1466}14671468// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.14691470// Implements the helper function for {ASSERT|EXPECT}_NE1471GTEST_IMPL_CMP_HELPER_(NE, !=)1472// Implements the helper function for {ASSERT|EXPECT}_LE1473GTEST_IMPL_CMP_HELPER_(LE, <=)1474// Implements the helper function for {ASSERT|EXPECT}_LT1475GTEST_IMPL_CMP_HELPER_(LT, <)1476// Implements the helper function for {ASSERT|EXPECT}_GE1477GTEST_IMPL_CMP_HELPER_(GE, >=)1478// Implements the helper function for {ASSERT|EXPECT}_GT1479GTEST_IMPL_CMP_HELPER_(GT, >)14801481#undef GTEST_IMPL_CMP_HELPER_14821483// The helper function for {ASSERT|EXPECT}_STREQ.1484//1485// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1486GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,1487const char* s2_expression,1488const char* s1, const char* s2);14891490// The helper function for {ASSERT|EXPECT}_STRCASEEQ.1491//1492// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1493GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,1494const char* s2_expression,1495const char* s1, const char* s2);14961497// The helper function for {ASSERT|EXPECT}_STRNE.1498//1499// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1500GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,1501const char* s2_expression,1502const char* s1, const char* s2);15031504// The helper function for {ASSERT|EXPECT}_STRCASENE.1505//1506// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1507GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,1508const char* s2_expression,1509const char* s1, const char* s2);15101511// Helper function for *_STREQ on wide strings.1512//1513// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1514GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,1515const char* s2_expression,1516const wchar_t* s1, const wchar_t* s2);15171518// Helper function for *_STRNE on wide strings.1519//1520// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1521GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,1522const char* s2_expression,1523const wchar_t* s1, const wchar_t* s2);15241525} // namespace internal15261527// IsSubstring() and IsNotSubstring() are intended to be used as the1528// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by1529// themselves. They check whether needle is a substring of haystack1530// (NULL is considered a substring of itself only), and return an1531// appropriate error message when they fail.1532//1533// The {needle,haystack}_expr arguments are the stringified1534// expressions that generated the two real arguments.1535GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,1536const char* haystack_expr,1537const char* needle,1538const char* haystack);1539GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,1540const char* haystack_expr,1541const wchar_t* needle,1542const wchar_t* haystack);1543GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,1544const char* haystack_expr,1545const char* needle,1546const char* haystack);1547GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,1548const char* haystack_expr,1549const wchar_t* needle,1550const wchar_t* haystack);1551GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,1552const char* haystack_expr,1553const ::std::string& needle,1554const ::std::string& haystack);1555GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,1556const char* haystack_expr,1557const ::std::string& needle,1558const ::std::string& haystack);15591560#if GTEST_HAS_STD_WSTRING1561GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,1562const char* haystack_expr,1563const ::std::wstring& needle,1564const ::std::wstring& haystack);1565GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,1566const char* haystack_expr,1567const ::std::wstring& needle,1568const ::std::wstring& haystack);1569#endif // GTEST_HAS_STD_WSTRING15701571namespace internal {15721573// Helper template function for comparing floating-points.1574//1575// Template parameter:1576//1577// RawType: the raw floating-point type (either float or double)1578//1579// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1580template <typename RawType>1581AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,1582const char* rhs_expression,1583RawType lhs_value, RawType rhs_value) {1584const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);15851586if (lhs.AlmostEquals(rhs)) {1587return AssertionSuccess();1588}15891590::std::stringstream lhs_ss;1591lhs_ss.precision(std::numeric_limits<RawType>::digits10 + 2);1592lhs_ss << lhs_value;15931594::std::stringstream rhs_ss;1595rhs_ss.precision(std::numeric_limits<RawType>::digits10 + 2);1596rhs_ss << rhs_value;15971598return EqFailure(lhs_expression, rhs_expression,1599StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),1600false);1601}16021603// Helper function for implementing ASSERT_NEAR.1604//1605// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.1606GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,1607const char* expr2,1608const char* abs_error_expr,1609double val1, double val2,1610double abs_error);16111612// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.1613// A class that enables one to stream messages to assertion macros1614class GTEST_API_ AssertHelper {1615public:1616// Constructor.1617AssertHelper(TestPartResult::Type type, const char* file, int line,1618const char* message);1619~AssertHelper();16201621// Message assignment is a semantic trick to enable assertion1622// streaming; see the GTEST_MESSAGE_ macro below.1623void operator=(const Message& message) const;16241625private:1626// We put our data in a struct so that the size of the AssertHelper class can1627// be as small as possible. This is important because gcc is incapable of1628// re-using stack space even for temporary variables, so every EXPECT_EQ1629// reserves stack space for another AssertHelper.1630struct AssertHelperData {1631AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num,1632const char* msg)1633: type(t), file(srcfile), line(line_num), message(msg) {}16341635TestPartResult::Type const type;1636const char* const file;1637int const line;1638std::string const message;16391640private:1641AssertHelperData(const AssertHelperData&) = delete;1642AssertHelperData& operator=(const AssertHelperData&) = delete;1643};16441645AssertHelperData* const data_;16461647AssertHelper(const AssertHelper&) = delete;1648AssertHelper& operator=(const AssertHelper&) = delete;1649};16501651} // namespace internal16521653// The pure interface class that all value-parameterized tests inherit from.1654// A value-parameterized class must inherit from both ::testing::Test and1655// ::testing::WithParamInterface. In most cases that just means inheriting1656// from ::testing::TestWithParam, but more complicated test hierarchies1657// may need to inherit from Test and WithParamInterface at different levels.1658//1659// This interface has support for accessing the test parameter value via1660// the GetParam() method.1661//1662// Use it with one of the parameter generator defining functions, like Range(),1663// Values(), ValuesIn(), Bool(), Combine(), and ConvertGenerator<T>().1664//1665// class FooTest : public ::testing::TestWithParam<int> {1666// protected:1667// FooTest() {1668// // Can use GetParam() here.1669// }1670// ~FooTest() override {1671// // Can use GetParam() here.1672// }1673// void SetUp() override {1674// // Can use GetParam() here.1675// }1676// void TearDown override {1677// // Can use GetParam() here.1678// }1679// };1680// TEST_P(FooTest, DoesBar) {1681// // Can use GetParam() method here.1682// Foo foo;1683// ASSERT_TRUE(foo.DoesBar(GetParam()));1684// }1685// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));16861687template <typename T>1688class WithParamInterface {1689public:1690typedef T ParamType;1691virtual ~WithParamInterface() = default;16921693// The current parameter value. Is also available in the test fixture's1694// constructor.1695static const ParamType& GetParam() {1696GTEST_CHECK_(parameter_ != nullptr)1697<< "GetParam() can only be called inside a value-parameterized test "1698<< "-- did you intend to write TEST_P instead of TEST_F?";1699return *parameter_;1700}17011702private:1703// Sets parameter value. The caller is responsible for making sure the value1704// remains alive and unchanged throughout the current test.1705static void SetParam(const ParamType* parameter) { parameter_ = parameter; }17061707// Static value used for accessing parameter during a test lifetime.1708static const ParamType* parameter_;17091710// TestClass must be a subclass of WithParamInterface<T> and Test.1711template <class TestClass>1712friend class internal::ParameterizedTestFactory;1713};17141715template <typename T>1716const T* WithParamInterface<T>::parameter_ = nullptr;17171718// Most value-parameterized classes can ignore the existence of1719// WithParamInterface, and can just inherit from ::testing::TestWithParam.17201721template <typename T>1722class TestWithParam : public Test, public WithParamInterface<T> {};17231724// Macros for indicating success/failure in test code.17251726// Skips test in runtime.1727// Skipping test aborts current function.1728// Skipped tests are neither successful nor failed.1729#define GTEST_SKIP() GTEST_SKIP_("")17301731// ADD_FAILURE unconditionally adds a failure to the current test.1732// SUCCEED generates a success - it doesn't automatically make the1733// current test successful, as a test is only successful when it has1734// no failure.1735//1736// EXPECT_* verifies that a certain condition is satisfied. If not,1737// it behaves like ADD_FAILURE. In particular:1738//1739// EXPECT_TRUE verifies that a Boolean condition is true.1740// EXPECT_FALSE verifies that a Boolean condition is false.1741//1742// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except1743// that they will also abort the current function on failure. People1744// usually want the fail-fast behavior of FAIL and ASSERT_*, but those1745// writing data-driven tests often find themselves using ADD_FAILURE1746// and EXPECT_* more.17471748// Generates a nonfatal failure with a generic message.1749#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")17501751// Generates a nonfatal failure at the given source file location with1752// a generic message.1753#define ADD_FAILURE_AT(file, line) \1754GTEST_MESSAGE_AT_(file, line, "Failed", \1755::testing::TestPartResult::kNonFatalFailure)17561757// Generates a fatal failure with a generic message.1758#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")17591760// Like GTEST_FAIL(), but at the given source file location.1761#define GTEST_FAIL_AT(file, line) \1762return GTEST_MESSAGE_AT_(file, line, "Failed", \1763::testing::TestPartResult::kFatalFailure)17641765// Define this macro to 1 to omit the definition of FAIL(), which is a1766// generic name and clashes with some other libraries.1767#if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL)1768#define FAIL() GTEST_FAIL()1769#define FAIL_AT(file, line) GTEST_FAIL_AT(file, line)1770#endif17711772// Generates a success with a generic message.1773#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")17741775// Define this macro to 1 to omit the definition of SUCCEED(), which1776// is a generic name and clashes with some other libraries.1777#if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED)1778#define SUCCEED() GTEST_SUCCEED()1779#endif17801781// Macros for testing exceptions.1782//1783// * {ASSERT|EXPECT}_THROW(statement, expected_exception):1784// Tests that the statement throws the expected exception.1785// * {ASSERT|EXPECT}_NO_THROW(statement):1786// Tests that the statement doesn't throw any exception.1787// * {ASSERT|EXPECT}_ANY_THROW(statement):1788// Tests that the statement throws an exception.17891790#define EXPECT_THROW(statement, expected_exception) \1791GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)1792#define EXPECT_NO_THROW(statement) \1793GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)1794#define EXPECT_ANY_THROW(statement) \1795GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)1796#define ASSERT_THROW(statement, expected_exception) \1797GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)1798#define ASSERT_NO_THROW(statement) \1799GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)1800#define ASSERT_ANY_THROW(statement) \1801GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)18021803// Boolean assertions. Condition can be either a Boolean expression or an1804// AssertionResult. For more information on how to use AssertionResult with1805// these macros see comments on that class.1806#define GTEST_EXPECT_TRUE(condition) \1807GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \1808GTEST_NONFATAL_FAILURE_)1809#define GTEST_EXPECT_FALSE(condition) \1810GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \1811GTEST_NONFATAL_FAILURE_)1812#define GTEST_ASSERT_TRUE(condition) \1813GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_)1814#define GTEST_ASSERT_FALSE(condition) \1815GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \1816GTEST_FATAL_FAILURE_)18171818// Define these macros to 1 to omit the definition of the corresponding1819// EXPECT or ASSERT, which clashes with some users' own code.18201821#if !(defined(GTEST_DONT_DEFINE_EXPECT_TRUE) && GTEST_DONT_DEFINE_EXPECT_TRUE)1822#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)1823#endif18241825#if !(defined(GTEST_DONT_DEFINE_EXPECT_FALSE) && GTEST_DONT_DEFINE_EXPECT_FALSE)1826#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)1827#endif18281829#if !(defined(GTEST_DONT_DEFINE_ASSERT_TRUE) && GTEST_DONT_DEFINE_ASSERT_TRUE)1830#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)1831#endif18321833#if !(defined(GTEST_DONT_DEFINE_ASSERT_FALSE) && GTEST_DONT_DEFINE_ASSERT_FALSE)1834#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)1835#endif18361837// Macros for testing equalities and inequalities.1838//1839// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v21840// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v21841// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v21842// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v21843// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v21844// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v21845//1846// When they are not, Google Test prints both the tested expressions and1847// their actual values. The values must be compatible built-in types,1848// or you will get a compiler error. By "compatible" we mean that the1849// values can be compared by the respective operator.1850//1851// Note:1852//1853// 1. It is possible to make a user-defined type work with1854// {ASSERT|EXPECT}_??(), but that requires overloading the1855// comparison operators and is thus discouraged by the Google C++1856// Usage Guide. Therefore, you are advised to use the1857// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are1858// equal.1859//1860// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on1861// pointers (in particular, C strings). Therefore, if you use it1862// with two C strings, you are testing how their locations in memory1863// are related, not how their content is related. To compare two C1864// strings by content, use {ASSERT|EXPECT}_STR*().1865//1866// 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to1867// {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you1868// what the actual value is when it fails, and similarly for the1869// other comparisons.1870//1871// 4. Do not depend on the order in which {ASSERT|EXPECT}_??()1872// evaluate their arguments, which is undefined.1873//1874// 5. These macros evaluate their arguments exactly once.1875//1876// Examples:1877//1878// EXPECT_NE(Foo(), 5);1879// EXPECT_EQ(a_pointer, NULL);1880// ASSERT_LT(i, array_size);1881// ASSERT_GT(records.size(), 0) << "There is no record left.";18821883#define EXPECT_EQ(val1, val2) \1884EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)1885#define EXPECT_NE(val1, val2) \1886EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)1887#define EXPECT_LE(val1, val2) \1888EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)1889#define EXPECT_LT(val1, val2) \1890EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)1891#define EXPECT_GE(val1, val2) \1892EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)1893#define EXPECT_GT(val1, val2) \1894EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)18951896#define GTEST_ASSERT_EQ(val1, val2) \1897ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)1898#define GTEST_ASSERT_NE(val1, val2) \1899ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)1900#define GTEST_ASSERT_LE(val1, val2) \1901ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)1902#define GTEST_ASSERT_LT(val1, val2) \1903ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)1904#define GTEST_ASSERT_GE(val1, val2) \1905ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)1906#define GTEST_ASSERT_GT(val1, val2) \1907ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)19081909// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of1910// ASSERT_XY(), which clashes with some users' own code.19111912#if !(defined(GTEST_DONT_DEFINE_ASSERT_EQ) && GTEST_DONT_DEFINE_ASSERT_EQ)1913#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)1914#endif19151916#if !(defined(GTEST_DONT_DEFINE_ASSERT_NE) && GTEST_DONT_DEFINE_ASSERT_NE)1917#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)1918#endif19191920#if !(defined(GTEST_DONT_DEFINE_ASSERT_LE) && GTEST_DONT_DEFINE_ASSERT_LE)1921#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)1922#endif19231924#if !(defined(GTEST_DONT_DEFINE_ASSERT_LT) && GTEST_DONT_DEFINE_ASSERT_LT)1925#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)1926#endif19271928#if !(defined(GTEST_DONT_DEFINE_ASSERT_GE) && GTEST_DONT_DEFINE_ASSERT_GE)1929#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)1930#endif19311932#if !(defined(GTEST_DONT_DEFINE_ASSERT_GT) && GTEST_DONT_DEFINE_ASSERT_GT)1933#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)1934#endif19351936// C-string Comparisons. All tests treat NULL and any non-NULL string1937// as different. Two NULLs are equal.1938//1939// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s21940// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s21941// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case1942// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case1943//1944// For wide or narrow string objects, you can use the1945// {ASSERT|EXPECT}_??() macros.1946//1947// Don't depend on the order in which the arguments are evaluated,1948// which is undefined.1949//1950// These macros evaluate their arguments exactly once.19511952#define EXPECT_STREQ(s1, s2) \1953EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)1954#define EXPECT_STRNE(s1, s2) \1955EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)1956#define EXPECT_STRCASEEQ(s1, s2) \1957EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)1958#define EXPECT_STRCASENE(s1, s2) \1959EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)19601961#define ASSERT_STREQ(s1, s2) \1962ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)1963#define ASSERT_STRNE(s1, s2) \1964ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)1965#define ASSERT_STRCASEEQ(s1, s2) \1966ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)1967#define ASSERT_STRCASENE(s1, s2) \1968ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)19691970// Macros for comparing floating-point numbers.1971//1972// * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):1973// Tests that two float values are almost equal.1974// * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):1975// Tests that two double values are almost equal.1976// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):1977// Tests that v1 and v2 are within the given distance to each other.1978//1979// Google Test uses ULP-based comparison to automatically pick a default1980// error bound that is appropriate for the operands. See the1981// FloatingPoint template class in gtest-internal.h if you are1982// interested in the implementation details.19831984#define EXPECT_FLOAT_EQ(val1, val2) \1985EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \1986val1, val2)19871988#define EXPECT_DOUBLE_EQ(val1, val2) \1989EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \1990val1, val2)19911992#define ASSERT_FLOAT_EQ(val1, val2) \1993ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \1994val1, val2)19951996#define ASSERT_DOUBLE_EQ(val1, val2) \1997ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \1998val1, val2)19992000#define EXPECT_NEAR(val1, val2, abs_error) \2001EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \2002abs_error)20032004#define ASSERT_NEAR(val1, val2, abs_error) \2005ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \2006abs_error)20072008// These predicate format functions work on floating-point values, and2009// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.2010//2011// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);20122013// Asserts that val1 is less than, or almost equal to, val2. Fails2014// otherwise. In particular, it fails if either val1 or val2 is NaN.2015GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,2016float val1, float val2);2017GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,2018double val1, double val2);20192020#ifdef GTEST_OS_WINDOWS20212022// Macros that test for HRESULT failure and success, these are only useful2023// on Windows, and rely on Windows SDK macros and APIs to compile.2024//2025// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)2026//2027// When expr unexpectedly fails or succeeds, Google Test prints the2028// expected result and the actual result with both a human-readable2029// string representation of the error, if available, as well as the2030// hex result code.2031#define EXPECT_HRESULT_SUCCEEDED(expr) \2032EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))20332034#define ASSERT_HRESULT_SUCCEEDED(expr) \2035ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))20362037#define EXPECT_HRESULT_FAILED(expr) \2038EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))20392040#define ASSERT_HRESULT_FAILED(expr) \2041ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))20422043#endif // GTEST_OS_WINDOWS20442045// Macros that execute statement and check that it doesn't generate new fatal2046// failures in the current thread.2047//2048// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);2049//2050// Examples:2051//2052// EXPECT_NO_FATAL_FAILURE(Process());2053// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";2054//2055#define ASSERT_NO_FATAL_FAILURE(statement) \2056GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)2057#define EXPECT_NO_FATAL_FAILURE(statement) \2058GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)20592060// Causes a trace (including the given source file path and line number,2061// and the given message) to be included in every test failure message generated2062// by code in the scope of the lifetime of an instance of this class. The effect2063// is undone with the destruction of the instance.2064//2065// The message argument can be anything streamable to std::ostream.2066//2067// Example:2068// testing::ScopedTrace trace("file.cc", 123, "message");2069//2070class GTEST_API_ ScopedTrace {2071public:2072// The c'tor pushes the given source file location and message onto2073// a trace stack maintained by Google Test.20742075// Template version. Uses Message() to convert the values into strings.2076// Slow, but flexible.2077template <typename T>2078ScopedTrace(const char* file, int line, const T& message) {2079PushTrace(file, line, (Message() << message).GetString());2080}20812082// Optimize for some known types.2083ScopedTrace(const char* file, int line, const char* message) {2084PushTrace(file, line, message ? message : "(null)");2085}20862087ScopedTrace(const char* file, int line, const std::string& message) {2088PushTrace(file, line, message);2089}20902091// The d'tor pops the info pushed by the c'tor.2092//2093// Note that the d'tor is not virtual in order to be efficient.2094// Don't inherit from ScopedTrace!2095~ScopedTrace();20962097private:2098void PushTrace(const char* file, int line, std::string message);20992100ScopedTrace(const ScopedTrace&) = delete;2101ScopedTrace& operator=(const ScopedTrace&) = delete;2102};21032104// Causes a trace (including the source file path, the current line2105// number, and the given message) to be included in every test failure2106// message generated by code in the current scope. The effect is2107// undone when the control leaves the current scope.2108//2109// The message argument can be anything streamable to std::ostream.2110//2111// In the implementation, we include the current line number as part2112// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s2113// to appear in the same block - as long as they are on different2114// lines.2115//2116// Assuming that each thread maintains its own stack of traces.2117// Therefore, a SCOPED_TRACE() would (correctly) only affect the2118// assertions in its own thread.2119#define SCOPED_TRACE(message) \2120const ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \2121__FILE__, __LINE__, (message))21222123// Compile-time assertion for type equality.2124// StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type22125// are the same type. The value it returns is not interesting.2126//2127// Instead of making StaticAssertTypeEq a class template, we make it a2128// function template that invokes a helper class template. This2129// prevents a user from misusing StaticAssertTypeEq<T1, T2> by2130// defining objects of that type.2131//2132// CAVEAT:2133//2134// When used inside a method of a class template,2135// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is2136// instantiated. For example, given:2137//2138// template <typename T> class Foo {2139// public:2140// void Bar() { testing::StaticAssertTypeEq<int, T>(); }2141// };2142//2143// the code:2144//2145// void Test1() { Foo<bool> foo; }2146//2147// will NOT generate a compiler error, as Foo<bool>::Bar() is never2148// actually instantiated. Instead, you need:2149//2150// void Test2() { Foo<bool> foo; foo.Bar(); }2151//2152// to cause a compiler error.2153template <typename T1, typename T2>2154constexpr bool StaticAssertTypeEq() noexcept {2155static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");2156return true;2157}21582159// Defines a test.2160//2161// The first parameter is the name of the test suite, and the second2162// parameter is the name of the test within the test suite.2163//2164// The convention is to end the test suite name with "Test". For2165// example, a test suite for the Foo class can be named FooTest.2166//2167// Test code should appear between braces after an invocation of2168// this macro. Example:2169//2170// TEST(FooTest, InitializesCorrectly) {2171// Foo foo;2172// EXPECT_TRUE(foo.StatusIsOK());2173// }21742175// Note that we call GetTestTypeId() instead of GetTypeId<2176// ::testing::Test>() here to get the type ID of testing::Test. This2177// is to work around a suspected linker bug when using Google Test as2178// a framework on Mac OS X. The bug causes GetTypeId<2179// ::testing::Test>() to return different values depending on whether2180// the call is from the Google Test framework itself or from user test2181// code. GetTestTypeId() is guaranteed to always return the same2182// value, as it always calls GetTypeId<>() from the Google Test2183// framework.2184#define GTEST_TEST(test_suite_name, test_name) \2185GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \2186::testing::internal::GetTestTypeId())21872188// Define this macro to 1 to omit the definition of TEST(), which2189// is a generic name and clashes with some other libraries.2190#if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST)2191#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)2192#endif21932194// Defines a test that uses a test fixture.2195//2196// The first parameter is the name of the test fixture class, which2197// also doubles as the test suite name. The second parameter is the2198// name of the test within the test suite.2199//2200// A test fixture class must be declared earlier. The user should put2201// the test code between braces after using this macro. Example:2202//2203// class FooTest : public testing::Test {2204// protected:2205// void SetUp() override { b_.AddElement(3); }2206//2207// Foo a_;2208// Foo b_;2209// };2210//2211// TEST_F(FooTest, InitializesCorrectly) {2212// EXPECT_TRUE(a_.StatusIsOK());2213// }2214//2215// TEST_F(FooTest, ReturnsElementCountCorrectly) {2216// EXPECT_EQ(a_.size(), 0);2217// EXPECT_EQ(b_.size(), 1);2218// }2219#define GTEST_TEST_F(test_fixture, test_name) \2220GTEST_TEST_(test_fixture, test_name, test_fixture, \2221::testing::internal::GetTypeId<test_fixture>())2222#if !(defined(GTEST_DONT_DEFINE_TEST_F) && GTEST_DONT_DEFINE_TEST_F)2223#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name)2224#endif22252226// Returns a path to a temporary directory, which should be writable. It is2227// implementation-dependent whether or not the path is terminated by the2228// directory-separator character.2229GTEST_API_ std::string TempDir();22302231// Returns a path to a directory that contains ancillary data files that might2232// be used by tests. It is implementation dependent whether or not the path is2233// terminated by the directory-separator character. The directory and the files2234// in it should be considered read-only.2235GTEST_API_ std::string SrcDir();22362237GTEST_DISABLE_MSC_WARNINGS_POP_() // 4805 410022382239// Dynamically registers a test with the framework.2240//2241// This is an advanced API only to be used when the `TEST` macros are2242// insufficient. The macros should be preferred when possible, as they avoid2243// most of the complexity of calling this function.2244//2245// The `factory` argument is a factory callable (move-constructible) object or2246// function pointer that creates a new instance of the Test object. It2247// handles ownership to the caller. The signature of the callable is2248// `Fixture*()`, where `Fixture` is the test fixture class for the test. All2249// tests registered with the same `test_suite_name` must return the same2250// fixture type. This is checked at runtime.2251//2252// The framework will infer the fixture class from the factory and will call2253// the `SetUpTestSuite` and `TearDownTestSuite` for it.2254//2255// Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is2256// undefined.2257//2258// Use case example:2259//2260// class MyFixture : public ::testing::Test {2261// public:2262// // All of these optional, just like in regular macro usage.2263// static void SetUpTestSuite() { ... }2264// static void TearDownTestSuite() { ... }2265// void SetUp() override { ... }2266// void TearDown() override { ... }2267// };2268//2269// class MyTest : public MyFixture {2270// public:2271// explicit MyTest(int data) : data_(data) {}2272// void TestBody() override { ... }2273//2274// private:2275// int data_;2276// };2277//2278// void RegisterMyTests(const std::vector<int>& values) {2279// for (int v : values) {2280// ::testing::RegisterTest(2281// "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,2282// std::to_string(v).c_str(),2283// __FILE__, __LINE__,2284// // Important to use the fixture type as the return type here.2285// [=]() -> MyFixture* { return new MyTest(v); });2286// }2287// }2288// ...2289// int main(int argc, char** argv) {2290// ::testing::InitGoogleTest(&argc, argv);2291// std::vector<int> values_to_test = LoadValuesFromConfig();2292// RegisterMyTests(values_to_test);2293// ...2294// return RUN_ALL_TESTS();2295// }2296//2297template <int&... ExplicitParameterBarrier, typename Factory>2298TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,2299const char* type_param, const char* value_param,2300const char* file, int line, Factory factory) {2301using TestT = typename std::remove_pointer<decltype(factory())>::type;23022303class FactoryImpl : public internal::TestFactoryBase {2304public:2305explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}2306Test* CreateTest() override { return factory_(); }23072308private:2309Factory factory_;2310};23112312return internal::MakeAndRegisterTestInfo(2313test_suite_name, test_name, type_param, value_param,2314internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),2315internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),2316internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),2317new FactoryImpl{std::move(factory)});2318}23192320} // namespace testing23212322// Use this function in main() to run all tests. It returns 0 if all2323// tests are successful, or 1 otherwise.2324//2325// RUN_ALL_TESTS() should be invoked after the command line has been2326// parsed by InitGoogleTest(). RUN_ALL_TESTS will tear down and delete any2327// installed environments and should only be called once per binary.2328//2329// This function was formerly a macro; thus, it is in the global2330// namespace and has an all-caps name.2331[[nodiscard]] int RUN_ALL_TESTS();23322333inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }23342335GTEST_DISABLE_MSC_WARNINGS_POP_() // 425123362337#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_233823392340