osb/source/test/gtest/gtest.h

2319 lines
88 KiB
C
Raw Normal View History

2023-06-20 04:33:09 +00:00
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2023-07-14 11:45:11 +00:00
// The Google C++ Testing and Mocking Framework (Google Test)
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// This header file defines the public API for Google Test. It should be
// included by any test program that uses Google Test.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
// leave some internal implementation details in this header file.
// They are clearly marked by comments like this:
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// Such code is NOT meant to be used by a user directly, and is subject
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
// program!
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// Acknowledgment: Google Test borrowed the idea of automatic test
// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
// easyUnit framework.
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_
#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#include <cstddef>
#include <cstdint>
#include <iomanip>
#include <limits>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
2023-06-20 04:33:09 +00:00
#include <vector>
2023-07-14 11:45:11 +00:00
#include "gtest/gtest-assertion-result.h"
#include "gtest/gtest-death-test.h"
#include "gtest/gtest-matchers.h"
#include "gtest/gtest-message.h"
#include "gtest/gtest-param-test.h"
#include "gtest/gtest-printers.h"
#include "gtest/gtest-test-part.h"
#include "gtest/gtest-typed-test.h"
#include "gtest/gtest_pred_impl.h"
#include "gtest/gtest_prod.h"
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h"
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)
2023-06-20 04:33:09 +00:00
// Declares the flags.
// This flag temporary enables the disabled tests.
GTEST_DECLARE_bool_(also_run_disabled_tests);
// This flag brings the debugger on an assertion failure.
GTEST_DECLARE_bool_(break_on_failure);
// This flag controls whether Google Test catches all test-thrown exceptions
// and logs them as failures.
GTEST_DECLARE_bool_(catch_exceptions);
// This flag enables using colors in terminal output. Available values are
// "yes" to enable colors, "no" (disable colors), or "auto" (the default)
// to let Google Test decide.
GTEST_DECLARE_string_(color);
2023-07-14 11:45:11 +00:00
// This flag controls whether the test runner should continue execution past
// first failure.
GTEST_DECLARE_bool_(fail_fast);
2023-06-20 04:33:09 +00:00
// This flag sets up the filter to select by name using a glob pattern
// the tests to run. If the filter is not given all tests are executed.
GTEST_DECLARE_string_(filter);
2023-07-14 11:45:11 +00:00
// This flag controls whether Google Test installs a signal handler that dumps
// debugging information when fatal signals are raised.
GTEST_DECLARE_bool_(install_failure_signal_handler);
2023-06-20 04:33:09 +00:00
// This flag causes the Google Test to list tests. None of the tests listed
// are actually run if the flag is provided.
GTEST_DECLARE_bool_(list_tests);
// This flag controls whether Google Test emits a detailed XML report to a file
// in addition to its normal textual output.
GTEST_DECLARE_string_(output);
2023-07-14 11:45:11 +00:00
// This flags control whether Google Test prints only test failures.
GTEST_DECLARE_bool_(brief);
2023-06-20 04:33:09 +00:00
// This flags control whether Google Test prints the elapsed time for each
// test.
GTEST_DECLARE_bool_(print_time);
2023-07-14 11:45:11 +00:00
// This flags control whether Google Test prints UTF8 characters as text.
GTEST_DECLARE_bool_(print_utf8);
2023-06-20 04:33:09 +00:00
// This flag specifies the random number seed.
GTEST_DECLARE_int32_(random_seed);
// This flag sets how many times the tests are repeated. The default value
// is 1. If the value is -1 the tests are repeating forever.
GTEST_DECLARE_int32_(repeat);
2023-07-14 11:45:11 +00:00
// This flag controls whether Google Test Environments are recreated for each
// repeat of the tests. The default value is true. If set to false the global
// test Environment objects are only set up once, for the first iteration, and
// only torn down once, for the last.
GTEST_DECLARE_bool_(recreate_environments_when_repeating);
2023-06-20 04:33:09 +00:00
// This flag controls whether Google Test includes Google Test internal
// stack frames in failure stack traces.
GTEST_DECLARE_bool_(show_internal_stack_frames);
// When this flag is specified, tests' order is randomized on every iteration.
GTEST_DECLARE_bool_(shuffle);
// This flag specifies the maximum number of stack frames to be
// printed in a failure message.
GTEST_DECLARE_int32_(stack_trace_depth);
// When this flag is specified, a failed assertion will throw an
// exception if exceptions are enabled, or exit the program with a
2023-07-14 11:45:11 +00:00
// non-zero code otherwise. For use with an external test framework.
2023-06-20 04:33:09 +00:00
GTEST_DECLARE_bool_(throw_on_failure);
// When this flag is set with a "host:port" string, on supported
// platforms test results are streamed to the specified port on
// the specified host machine.
GTEST_DECLARE_string_(stream_result_to);
2023-07-14 11:45:11 +00:00
#if GTEST_USE_OWN_FLAGFILE_FLAG_
GTEST_DECLARE_string_(flagfile);
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
namespace testing {
// Silence C4100 (unreferenced formal parameter) and 4805
// unsafe mix of type 'const int' and type 'const bool'
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4805)
#pragma warning(disable : 4100)
#endif
2023-06-20 04:33:09 +00:00
// The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100;
namespace internal {
class AssertHelper;
class DefaultGlobalTestPartResultReporter;
class ExecDeathTest;
2023-07-14 11:45:11 +00:00
class NoExecDeathTest;
class FinalSuccessChecker;
class GTestFlagSaver;
class StreamingListenerTest;
class TestResultAccessor;
class TestEventListenersAccessor;
class TestEventRepeater;
class UnitTestRecordPropertyTestHelper;
class WindowsDeathTest;
class FuchsiaDeathTest;
class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message);
std::set<std::string>* GetIgnoredParameterizedTestSuites();
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// A base class that prevents subclasses from being copyable.
// We do this instead of using '= delete' so as to avoid triggering warnings
// inside user code regarding any of our declarations.
class GTestNonCopyable {
public:
GTestNonCopyable() = default;
GTestNonCopyable(const GTestNonCopyable &) = delete;
GTestNonCopyable &operator=(const GTestNonCopyable &) = delete;
~GTestNonCopyable() = default;
2023-06-20 04:33:09 +00:00
};
2023-07-14 11:45:11 +00:00
} // namespace internal
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// The friend relationship of some of these classes is cyclic.
// If we don't forward declare them the compiler might confuse the classes
// in friendship clauses with same named classes on the scope.
class Test;
class TestSuite;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Old API is still available but deprecated
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
using TestCase = TestSuite;
#endif
class TestInfo;
class UnitTest;
2023-06-20 04:33:09 +00:00
// The abstract class that all tests inherit from.
//
2023-07-14 11:45:11 +00:00
// In Google Test, a unit test program contains one or many TestSuites, and
// each TestSuite contains one or many Tests.
2023-06-20 04:33:09 +00:00
//
// When you define a test using the TEST macro, you don't need to
// explicitly derive from Test - the TEST macro automatically does
// this for you.
//
// The only time you derive from Test is when defining a test fixture
2023-07-14 11:45:11 +00:00
// to be used in a TEST_F. For example:
2023-06-20 04:33:09 +00:00
//
// class FooTest : public testing::Test {
// protected:
2023-07-14 11:45:11 +00:00
// void SetUp() override { ... }
// void TearDown() override { ... }
2023-06-20 04:33:09 +00:00
// ...
// };
//
// TEST_F(FooTest, Bar) { ... }
// TEST_F(FooTest, Baz) { ... }
//
// Test is not copyable.
class GTEST_API_ Test {
public:
friend class TestInfo;
// The d'tor is virtual as we intend to inherit from Test.
virtual ~Test();
2023-07-14 11:45:11 +00:00
// Sets up the stuff shared by all tests in this test suite.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// Google Test will call Foo::SetUpTestSuite() before running the first
// test in test suite Foo. Hence a sub-class can define its own
// SetUpTestSuite() method to shadow the one defined in the super
2023-06-20 04:33:09 +00:00
// class.
2023-07-14 11:45:11 +00:00
static void SetUpTestSuite() {}
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Tears down the stuff shared by all tests in this test suite.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// Google Test will call Foo::TearDownTestSuite() after running the last
// test in test suite Foo. Hence a sub-class can define its own
// TearDownTestSuite() method to shadow the one defined in the super
2023-06-20 04:33:09 +00:00
// class.
2023-07-14 11:45:11 +00:00
static void TearDownTestSuite() {}
// Legacy API is deprecated but still available. Use SetUpTestSuite and
// TearDownTestSuite instead.
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
static void TearDownTestCase() {}
2023-07-14 11:45:11 +00:00
static void SetUpTestCase() {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Returns true if and only if the current test has a fatal failure.
2023-06-20 04:33:09 +00:00
static bool HasFatalFailure();
2023-07-14 11:45:11 +00:00
// Returns true if and only if the current test has a non-fatal failure.
2023-06-20 04:33:09 +00:00
static bool HasNonfatalFailure();
2023-07-14 11:45:11 +00:00
// Returns true if and only if the current test was skipped.
static bool IsSkipped();
// Returns true if and only if the current test has a (either fatal or
2023-06-20 04:33:09 +00:00
// non-fatal) failure.
static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
2023-07-14 11:45:11 +00:00
// Logs a property for the current test, test suite, or for the entire
2023-06-20 04:33:09 +00:00
// invocation of the test program when used outside of the context of a
2023-07-14 11:45:11 +00:00
// test suite. Only the last value for a given key is remembered. These
2023-06-20 04:33:09 +00:00
// are public static so they can be called from utility functions that are
// not members of the test fixture. Calls to RecordProperty made during
// lifespan of the test (from the moment its constructor starts to the
// moment its destructor finishes) will be output in XML as attributes of
// the <testcase> element. Properties recorded from fixture's
2023-07-14 11:45:11 +00:00
// SetUpTestSuite or TearDownTestSuite are logged as attributes of the
2023-06-20 04:33:09 +00:00
// corresponding <testsuite> element. Calls to RecordProperty made in the
// global context (before or after invocation of RUN_ALL_TESTS and from
// SetUp/TearDown method of Environment objects registered with Google
// Test) will be output as attributes of the <testsuites> element.
static void RecordProperty(const std::string& key, const std::string& value);
2023-07-14 11:45:11 +00:00
static void RecordProperty(const std::string& key, int64_t value);
2023-06-20 04:33:09 +00:00
protected:
// Creates a Test object.
Test();
// Sets up the test fixture.
virtual void SetUp();
// Tears down the test fixture.
virtual void TearDown();
private:
2023-07-14 11:45:11 +00:00
// Returns true if and only if the current test has the same fixture class
// as the first test in the current test suite.
2023-06-20 04:33:09 +00:00
static bool HasSameFixtureClass();
// Runs the test after the test fixture has been set up.
//
// A sub-class must implement this to define the test logic.
//
// DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
// Instead, use the TEST or TEST_F macro.
virtual void TestBody() = 0;
// Sets up, executes, and tears down the test.
void Run();
// Deletes self. We deliberately pick an unusual name for this
// internal method to avoid clashing with names used in user TESTs.
void DeleteSelf_() { delete this; }
2023-07-14 11:45:11 +00:00
const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Often a user misspells SetUp() as Setup() and spends a long time
2023-06-20 04:33:09 +00:00
// wondering why it is never called by Google Test. The declaration of
// the following method is solely for catching such an error at
// compile time:
//
// - The return type is deliberately chosen to be not void, so it
2023-07-14 11:45:11 +00:00
// will be a conflict if void Setup() is declared in the user's
// test fixture.
2023-06-20 04:33:09 +00:00
//
// - This method is private, so it will be another compiler error
2023-07-14 11:45:11 +00:00
// if the method is called from the user's test fixture.
2023-06-20 04:33:09 +00:00
//
// DO NOT OVERRIDE THIS FUNCTION.
//
// If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup().
struct Setup_should_be_spelled_SetUp {};
2023-07-14 11:45:11 +00:00
virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
2023-06-20 04:33:09 +00:00
// We disallow copying Tests.
2023-07-14 11:45:11 +00:00
Test(const Test&) = delete;
Test& operator=(const Test&) = delete;
2023-06-20 04:33:09 +00:00
};
typedef internal::TimeInMillis TimeInMillis;
// A copyable object representing a user specified test property which can be
// output as a key/value string pair.
//
// Don't inherit from TestProperty as its destructor is not virtual.
class TestProperty {
public:
// C'tor. TestProperty does NOT have a default constructor.
// Always use this constructor (with parameters) to create a
// TestProperty object.
2023-07-14 11:45:11 +00:00
TestProperty(const std::string& a_key, const std::string& a_value)
: key_(a_key), value_(a_value) {}
2023-06-20 04:33:09 +00:00
// Gets the user supplied key.
2023-07-14 11:45:11 +00:00
const char* key() const { return key_.c_str(); }
2023-06-20 04:33:09 +00:00
// Gets the user supplied value.
2023-07-14 11:45:11 +00:00
const char* value() const { return value_.c_str(); }
2023-06-20 04:33:09 +00:00
// Sets a new value, overriding the one supplied in the constructor.
2023-07-14 11:45:11 +00:00
void SetValue(const std::string& new_value) { value_ = new_value; }
2023-06-20 04:33:09 +00:00
private:
// The key supplied by the user.
std::string key_;
// The value supplied by the user.
std::string value_;
};
// The result of a single Test. This includes a list of
// TestPartResults, a list of TestProperties, a count of how many
// death tests there are in the Test, and how much time it took to run
// the Test.
//
// TestResult is not copyable.
class GTEST_API_ TestResult {
public:
// Creates an empty TestResult.
TestResult();
// D'tor. Do not inherit from TestResult.
~TestResult();
// Gets the number of all test parts. This is the sum of the number
// of successful test parts and the number of failed test parts.
int total_part_count() const;
// Returns the number of the test properties.
int test_property_count() const;
2023-07-14 11:45:11 +00:00
// Returns true if and only if the test passed (i.e. no test part failed).
bool Passed() const { return !Skipped() && !Failed(); }
// Returns true if and only if the test was skipped.
bool Skipped() const;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Returns true if and only if the test failed.
2023-06-20 04:33:09 +00:00
bool Failed() const;
2023-07-14 11:45:11 +00:00
// Returns true if and only if the test fatally failed.
2023-06-20 04:33:09 +00:00
bool HasFatalFailure() const;
2023-07-14 11:45:11 +00:00
// Returns true if and only if the test has a non-fatal failure.
2023-06-20 04:33:09 +00:00
bool HasNonfatalFailure() const;
// Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
2023-07-14 11:45:11 +00:00
// Gets the time of the test case start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const { return start_timestamp_; }
// Returns the i-th test part result among all the results. i can range from 0
// to total_part_count() - 1. If i is not in that range, aborts the program.
2023-06-20 04:33:09 +00:00
const TestPartResult& GetTestPartResult(int i) const;
// Returns the i-th test property. i can range from 0 to
// test_property_count() - 1. If i is not in that range, aborts the
// program.
const TestProperty& GetTestProperty(int i) const;
private:
friend class TestInfo;
2023-07-14 11:45:11 +00:00
friend class TestSuite;
2023-06-20 04:33:09 +00:00
friend class UnitTest;
friend class internal::DefaultGlobalTestPartResultReporter;
friend class internal::ExecDeathTest;
friend class internal::TestResultAccessor;
friend class internal::UnitTestImpl;
friend class internal::WindowsDeathTest;
2023-07-14 11:45:11 +00:00
friend class internal::FuchsiaDeathTest;
2023-06-20 04:33:09 +00:00
// Gets the vector of TestPartResults.
const std::vector<TestPartResult>& test_part_results() const {
return test_part_results_;
}
// Gets the vector of TestProperties.
const std::vector<TestProperty>& test_properties() const {
return test_properties_;
}
2023-07-14 11:45:11 +00:00
// Sets the start time.
void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }
2023-06-20 04:33:09 +00:00
// Sets the elapsed time.
void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
// Adds a test property to the list. The property is validated and may add
// a non-fatal failure if invalid (e.g., if it conflicts with reserved
// key names). If a property is already recorded for the same key, the
// value will be updated, rather than storing multiple values for the same
// key. xml_element specifies the element for which the property is being
// recorded and is used for validation.
void RecordProperty(const std::string& xml_element,
const TestProperty& test_property);
// Adds a failure if the key is a reserved attribute of Google Test
2023-07-14 11:45:11 +00:00
// testsuite tags. Returns true if the property is valid.
// FIXME: Validate attribute names are legal and human readable.
2023-06-20 04:33:09 +00:00
static bool ValidateTestProperty(const std::string& xml_element,
const TestProperty& test_property);
// Adds a test part result to the list.
void AddTestPartResult(const TestPartResult& test_part_result);
// Returns the death test count.
int death_test_count() const { return death_test_count_; }
// Increments the death test count, returning the new count.
int increment_death_test_count() { return ++death_test_count_; }
// Clears the test part results.
void ClearTestPartResults();
// Clears the object.
void Clear();
// Protects mutable state of the property vector and of owned
// properties, whose values may be updated.
2023-07-14 11:45:11 +00:00
internal::Mutex test_properties_mutex_;
2023-06-20 04:33:09 +00:00
// The vector of TestPartResults
std::vector<TestPartResult> test_part_results_;
// The vector of TestProperties
std::vector<TestProperty> test_properties_;
// Running count of death tests.
int death_test_count_;
2023-07-14 11:45:11 +00:00
// The start time, in milliseconds since UNIX Epoch.
TimeInMillis start_timestamp_;
2023-06-20 04:33:09 +00:00
// The elapsed time, in milliseconds.
TimeInMillis elapsed_time_;
// We disallow copying TestResult.
2023-07-14 11:45:11 +00:00
TestResult(const TestResult&) = delete;
TestResult& operator=(const TestResult&) = delete;
2023-06-20 04:33:09 +00:00
}; // class TestResult
// A TestInfo object stores the following information about a test:
//
2023-07-14 11:45:11 +00:00
// Test suite name
2023-06-20 04:33:09 +00:00
// Test name
// Whether the test should be run
// A function pointer that creates the test object when invoked
// Test result
//
// The constructor of TestInfo registers itself with the UnitTest
// singleton such that the RUN_ALL_TESTS() macro knows which tests to
// run.
class GTEST_API_ TestInfo {
public:
// Destructs a TestInfo object. This function is not virtual, so
// don't inherit from TestInfo.
~TestInfo();
2023-07-14 11:45:11 +00:00
// Returns the test suite name.
const char* test_suite_name() const { return test_suite_name_.c_str(); }
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const char* test_case_name() const { return test_suite_name(); }
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
// Returns the test name.
const char* name() const { return name_.c_str(); }
// Returns the name of the parameter type, or NULL if this is not a typed
// or a type-parameterized test.
const char* type_param() const {
2023-07-14 11:45:11 +00:00
if (type_param_.get() != nullptr) return type_param_->c_str();
return nullptr;
2023-06-20 04:33:09 +00:00
}
// Returns the text representation of the value parameter, or NULL if this
// is not a value-parameterized test.
const char* value_param() const {
2023-07-14 11:45:11 +00:00
if (value_param_.get() != nullptr) return value_param_->c_str();
return nullptr;
2023-06-20 04:33:09 +00:00
}
2023-07-14 11:45:11 +00:00
// Returns the file name where this test is defined.
const char* file() const { return location_.file.c_str(); }
// Returns the line where this test is defined.
int line() const { return location_.line; }
// Return true if this test should not be run because it's in another shard.
bool is_in_another_shard() const { return is_in_another_shard_; }
2023-06-20 04:33:09 +00:00
// Returns true if this test should run, that is if the test is not
// disabled (or it is disabled but the also_run_disabled_tests flag has
// been specified) and its full name matches the user-specified filter.
//
// Google Test allows the user to filter the tests by their full names.
2023-07-14 11:45:11 +00:00
// The full name of a test Bar in test suite Foo is defined as
2023-06-20 04:33:09 +00:00
// "Foo.Bar". Only the tests that match the filter will run.
//
// A filter is a colon-separated list of glob (not regex) patterns,
// optionally followed by a '-' and a colon-separated list of
// negative patterns (tests to exclude). A test is run if it
// matches one of the positive patterns and does not match any of
// the negative patterns.
//
// For example, *A*:Foo.* is a filter that matches any string that
// contains the character 'A' or starts with "Foo.".
bool should_run() const { return should_run_; }
2023-07-14 11:45:11 +00:00
// Returns true if and only if this test will appear in the XML report.
2023-06-20 04:33:09 +00:00
bool is_reportable() const {
2023-07-14 11:45:11 +00:00
// The XML report includes tests matching the filter, excluding those
// run in other shards.
return matches_filter_ && !is_in_another_shard_;
2023-06-20 04:33:09 +00:00
}
// Returns the result of the test.
const TestResult* result() const { return &result_; }
private:
#if GTEST_HAS_DEATH_TEST
friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
friend class Test;
2023-07-14 11:45:11 +00:00
friend class TestSuite;
2023-06-20 04:33:09 +00:00
friend class internal::UnitTestImpl;
friend class internal::StreamingListenerTest;
friend TestInfo* internal::MakeAndRegisterTestInfo(
2023-07-14 11:45:11 +00:00
const char* test_suite_name, const char* name, const char* type_param,
const char* value_param, internal::CodeLocation code_location,
internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc,
2023-06-20 04:33:09 +00:00
internal::TestFactoryBase* factory);
// Constructs a TestInfo object. The newly constructed instance assumes
// ownership of the factory object.
2023-07-14 11:45:11 +00:00
TestInfo(const std::string& test_suite_name, const std::string& name,
2023-06-20 04:33:09 +00:00
const char* a_type_param, // NULL if not a type-parameterized test
const char* a_value_param, // NULL if not a value-parameterized test
2023-07-14 11:45:11 +00:00
internal::CodeLocation a_code_location,
2023-06-20 04:33:09 +00:00
internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory);
// Increments the number of death tests encountered in this test so
// far.
int increment_death_test_count() {
return result_.increment_death_test_count();
}
// Creates the test object, runs it, records its result, and then
// deletes it.
void Run();
2023-07-14 11:45:11 +00:00
// Skip and records the test result for this object.
void Skip();
2023-06-20 04:33:09 +00:00
static void ClearTestResult(TestInfo* test_info) {
test_info->result_.Clear();
}
// These fields are immutable properties of the test.
2023-07-14 11:45:11 +00:00
const std::string test_suite_name_; // test suite name
const std::string name_; // Test name
2023-06-20 04:33:09 +00:00
// Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test.
2023-07-14 11:45:11 +00:00
const std::unique_ptr<const ::std::string> type_param_;
2023-06-20 04:33:09 +00:00
// Text representation of the value parameter, or NULL if this is not a
// value-parameterized test.
2023-07-14 11:45:11 +00:00
const std::unique_ptr<const ::std::string> value_param_;
internal::CodeLocation location_;
const internal::TypeId fixture_class_id_; // ID of the test fixture class
bool should_run_; // True if and only if this test should run
bool is_disabled_; // True if and only if this test is disabled
bool matches_filter_; // True if this test matches the
// user-specified filter.
bool is_in_another_shard_; // Will be run in another shard.
2023-06-20 04:33:09 +00:00
internal::TestFactoryBase* const factory_; // The factory that creates
// the test object
// This field is mutable and needs to be reset before running the
// test for the second time.
TestResult result_;
2023-07-14 11:45:11 +00:00
TestInfo(const TestInfo&) = delete;
TestInfo& operator=(const TestInfo&) = delete;
2023-06-20 04:33:09 +00:00
};
2023-07-14 11:45:11 +00:00
// A test suite, which consists of a vector of TestInfos.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// TestSuite is not copyable.
class GTEST_API_ TestSuite {
2023-06-20 04:33:09 +00:00
public:
2023-07-14 11:45:11 +00:00
// Creates a TestSuite with the given name.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// TestSuite does NOT have a default constructor. Always use this
// constructor to create a TestSuite object.
2023-06-20 04:33:09 +00:00
//
// Arguments:
//
2023-07-14 11:45:11 +00:00
// name: name of the test suite
2023-06-20 04:33:09 +00:00
// a_type_param: the name of the test's type parameter, or NULL if
// this is not a type-parameterized test.
2023-07-14 11:45:11 +00:00
// set_up_tc: pointer to the function that sets up the test suite
// tear_down_tc: pointer to the function that tears down the test suite
TestSuite(const char* name, const char* a_type_param,
internal::SetUpTestSuiteFunc set_up_tc,
internal::TearDownTestSuiteFunc tear_down_tc);
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Destructor of TestSuite.
virtual ~TestSuite();
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Gets the name of the TestSuite.
2023-06-20 04:33:09 +00:00
const char* name() const { return name_.c_str(); }
// Returns the name of the parameter type, or NULL if this is not a
2023-07-14 11:45:11 +00:00
// type-parameterized test suite.
2023-06-20 04:33:09 +00:00
const char* type_param() const {
2023-07-14 11:45:11 +00:00
if (type_param_.get() != nullptr) return type_param_->c_str();
return nullptr;
2023-06-20 04:33:09 +00:00
}
2023-07-14 11:45:11 +00:00
// Returns true if any test in this test suite should run.
2023-06-20 04:33:09 +00:00
bool should_run() const { return should_run_; }
2023-07-14 11:45:11 +00:00
// Gets the number of successful tests in this test suite.
2023-06-20 04:33:09 +00:00
int successful_test_count() const;
2023-07-14 11:45:11 +00:00
// Gets the number of skipped tests in this test suite.
int skipped_test_count() const;
// Gets the number of failed tests in this test suite.
2023-06-20 04:33:09 +00:00
int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const;
2023-07-14 11:45:11 +00:00
// Gets the number of disabled tests in this test suite.
2023-06-20 04:33:09 +00:00
int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report.
int reportable_test_count() const;
2023-07-14 11:45:11 +00:00
// Get the number of tests in this test suite that should run.
2023-06-20 04:33:09 +00:00
int test_to_run_count() const;
2023-07-14 11:45:11 +00:00
// Gets the number of all tests in this test suite.
2023-06-20 04:33:09 +00:00
int total_test_count() const;
2023-07-14 11:45:11 +00:00
// Returns true if and only if the test suite passed.
2023-06-20 04:33:09 +00:00
bool Passed() const { return !Failed(); }
2023-07-14 11:45:11 +00:00
// Returns true if and only if the test suite failed.
bool Failed() const {
return failed_test_count() > 0 || ad_hoc_test_result().Failed();
}
2023-06-20 04:33:09 +00:00
// Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
2023-07-14 11:45:11 +00:00
// Gets the time of the test suite start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const { return start_timestamp_; }
2023-06-20 04:33:09 +00:00
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
const TestInfo* GetTestInfo(int i) const;
// Returns the TestResult that holds test properties recorded during
2023-07-14 11:45:11 +00:00
// execution of SetUpTestSuite and TearDownTestSuite.
2023-06-20 04:33:09 +00:00
const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }
private:
friend class Test;
friend class internal::UnitTestImpl;
2023-07-14 11:45:11 +00:00
// Gets the (mutable) vector of TestInfos in this TestSuite.
2023-06-20 04:33:09 +00:00
std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
2023-07-14 11:45:11 +00:00
// Gets the (immutable) vector of TestInfos in this TestSuite.
2023-06-20 04:33:09 +00:00
const std::vector<TestInfo*>& test_info_list() const {
return test_info_list_;
}
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
TestInfo* GetMutableTestInfo(int i);
// Sets the should_run member.
void set_should_run(bool should) { should_run_ = should; }
2023-07-14 11:45:11 +00:00
// Adds a TestInfo to this test suite. Will delete the TestInfo upon
// destruction of the TestSuite object.
void AddTestInfo(TestInfo* test_info);
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Clears the results of all tests in this test suite.
2023-06-20 04:33:09 +00:00
void ClearResult();
2023-07-14 11:45:11 +00:00
// Clears the results of all tests in the given test suite.
static void ClearTestSuiteResult(TestSuite* test_suite) {
test_suite->ClearResult();
2023-06-20 04:33:09 +00:00
}
2023-07-14 11:45:11 +00:00
// Runs every test in this TestSuite.
2023-06-20 04:33:09 +00:00
void Run();
2023-07-14 11:45:11 +00:00
// Skips the execution of tests under this TestSuite
void Skip();
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
// for catching exceptions thrown from SetUpTestSuite().
void RunSetUpTestSuite() {
if (set_up_tc_ != nullptr) {
(*set_up_tc_)();
}
}
// Runs TearDownTestSuite() for this TestSuite. This wrapper is
// needed for catching exceptions thrown from TearDownTestSuite().
void RunTearDownTestSuite() {
if (tear_down_tc_ != nullptr) {
(*tear_down_tc_)();
}
}
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Returns true if and only if test passed.
2023-06-20 04:33:09 +00:00
static bool TestPassed(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Passed();
}
2023-07-14 11:45:11 +00:00
// Returns true if and only if test skipped.
static bool TestSkipped(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Skipped();
}
// Returns true if and only if test failed.
2023-06-20 04:33:09 +00:00
static bool TestFailed(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Failed();
}
2023-07-14 11:45:11 +00:00
// Returns true if and only if the test is disabled and will be reported in
// the XML report.
2023-06-20 04:33:09 +00:00
static bool TestReportableDisabled(const TestInfo* test_info) {
return test_info->is_reportable() && test_info->is_disabled_;
}
2023-07-14 11:45:11 +00:00
// Returns true if and only if test is disabled.
2023-06-20 04:33:09 +00:00
static bool TestDisabled(const TestInfo* test_info) {
return test_info->is_disabled_;
}
2023-07-14 11:45:11 +00:00
// Returns true if and only if this test will appear in the XML report.
2023-06-20 04:33:09 +00:00
static bool TestReportable(const TestInfo* test_info) {
return test_info->is_reportable();
}
// Returns true if the given test should run.
static bool ShouldRunTest(const TestInfo* test_info) {
return test_info->should_run();
}
2023-07-14 11:45:11 +00:00
// Shuffles the tests in this test suite.
2023-06-20 04:33:09 +00:00
void ShuffleTests(internal::Random* random);
// Restores the test order to before the first shuffle.
void UnshuffleTests();
2023-07-14 11:45:11 +00:00
// Name of the test suite.
2023-06-20 04:33:09 +00:00
std::string name_;
// Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test.
2023-07-14 11:45:11 +00:00
const std::unique_ptr<const ::std::string> type_param_;
2023-06-20 04:33:09 +00:00
// The vector of TestInfos in their original order. It owns the
// elements in the vector.
std::vector<TestInfo*> test_info_list_;
// Provides a level of indirection for the test list to allow easy
// shuffling and restoring the test order. The i-th element in this
// vector is the index of the i-th test in the shuffled test list.
std::vector<int> test_indices_;
2023-07-14 11:45:11 +00:00
// Pointer to the function that sets up the test suite.
internal::SetUpTestSuiteFunc set_up_tc_;
// Pointer to the function that tears down the test suite.
internal::TearDownTestSuiteFunc tear_down_tc_;
// True if and only if any test in this test suite should run.
2023-06-20 04:33:09 +00:00
bool should_run_;
2023-07-14 11:45:11 +00:00
// The start time, in milliseconds since UNIX Epoch.
TimeInMillis start_timestamp_;
2023-06-20 04:33:09 +00:00
// Elapsed time, in milliseconds.
TimeInMillis elapsed_time_;
2023-07-14 11:45:11 +00:00
// Holds test properties recorded during execution of SetUpTestSuite and
// TearDownTestSuite.
2023-06-20 04:33:09 +00:00
TestResult ad_hoc_test_result_;
2023-07-14 11:45:11 +00:00
// We disallow copying TestSuites.
TestSuite(const TestSuite&) = delete;
TestSuite& operator=(const TestSuite&) = delete;
2023-06-20 04:33:09 +00:00
};
// An Environment object is capable of setting up and tearing down an
2023-07-14 11:45:11 +00:00
// environment. You should subclass this to define your own
2023-06-20 04:33:09 +00:00
// environment(s).
//
// An Environment object does the set-up and tear-down in virtual
// methods SetUp() and TearDown() instead of the constructor and the
// destructor, as:
//
// 1. You cannot safely throw from a destructor. This is a problem
// as in some cases Google Test is used where exceptions are enabled, and
// we may want to implement ASSERT_* using exceptions where they are
// available.
// 2. You cannot use ASSERT_* directly in a constructor or
// destructor.
class Environment {
public:
// The d'tor is virtual as we need to subclass Environment.
virtual ~Environment() {}
// Override this to define how to set up the environment.
virtual void SetUp() {}
// Override this to define how to tear down the environment.
virtual void TearDown() {}
2023-07-14 11:45:11 +00:00
2023-06-20 04:33:09 +00:00
private:
// If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup().
struct Setup_should_be_spelled_SetUp {};
2023-07-14 11:45:11 +00:00
virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }
};
#if GTEST_HAS_EXCEPTIONS
// Exception which can be thrown from TestEventListener::OnTestPartResult.
class GTEST_API_ AssertionException
: public internal::GoogleTestFailureException {
public:
explicit AssertionException(const TestPartResult& result)
: GoogleTestFailureException(result) {}
2023-06-20 04:33:09 +00:00
};
2023-07-14 11:45:11 +00:00
#endif // GTEST_HAS_EXCEPTIONS
2023-06-20 04:33:09 +00:00
// The interface for tracing execution of tests. The methods are organized in
// the order the corresponding events are fired.
class TestEventListener {
public:
virtual ~TestEventListener() {}
// Fired before any test activity starts.
virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
// Fired before each iteration of tests starts. There may be more than
// one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
// index, starting from 0.
virtual void OnTestIterationStart(const UnitTest& unit_test,
int iteration) = 0;
// Fired before environment set-up for each iteration of tests starts.
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
// Fired after environment set-up for each iteration of tests ends.
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
2023-07-14 11:45:11 +00:00
// Fired before the test suite starts.
virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
// Fired before the test starts.
virtual void OnTestStart(const TestInfo& test_info) = 0;
2023-07-14 11:45:11 +00:00
// Fired when a test is disabled
virtual void OnTestDisabled(const TestInfo& /*test_info*/) {}
2023-06-20 04:33:09 +00:00
// Fired after a failed assertion or a SUCCEED() invocation.
2023-07-14 11:45:11 +00:00
// If you want to throw an exception from this function to skip to the next
// TEST, it must be AssertionException defined above, or inherited from it.
2023-06-20 04:33:09 +00:00
virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
// Fired after the test ends.
virtual void OnTestEnd(const TestInfo& test_info) = 0;
2023-07-14 11:45:11 +00:00
// Fired after the test suite ends.
virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
// Fired before environment tear-down for each iteration of tests starts.
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
// Fired after environment tear-down for each iteration of tests ends.
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
// Fired after each iteration of tests finishes.
2023-07-14 11:45:11 +00:00
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0;
2023-06-20 04:33:09 +00:00
// Fired after all test activities have ended.
virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
};
// The convenience class for users who need to override just one or two
// methods and are not concerned that a possible change to a signature of
// the methods they override will not be caught during the build. For
// comments about each method please see the definition of TestEventListener
// above.
class EmptyTestEventListener : public TestEventListener {
public:
2023-07-14 11:45:11 +00:00
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
void OnTestIterationStart(const UnitTest& /*unit_test*/,
int /*iteration*/) override {}
void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestCaseStart(const TestCase& /*test_case*/) override {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestStart(const TestInfo& /*test_info*/) override {}
void OnTestDisabled(const TestInfo& /*test_info*/) override {}
void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}
void OnTestEnd(const TestInfo& /*test_info*/) override {}
void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int /*iteration*/) override {}
void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
2023-06-20 04:33:09 +00:00
};
// TestEventListeners lets users add listeners to track events in Google Test.
class GTEST_API_ TestEventListeners {
public:
TestEventListeners();
~TestEventListeners();
// Appends an event listener to the end of the list. Google Test assumes
// the ownership of the listener (i.e. it will delete the listener when
// the test program finishes).
void Append(TestEventListener* listener);
// Removes the given event listener from the list and returns it. It then
// becomes the caller's responsibility to delete the listener. Returns
// NULL if the listener is not found in the list.
TestEventListener* Release(TestEventListener* listener);
// Returns the standard listener responsible for the default console
// output. Can be removed from the listeners list to shut down default
// console output. Note that removing this object from the listener list
// with Release transfers its ownership to the caller and makes this
// function return NULL the next time.
TestEventListener* default_result_printer() const {
return default_result_printer_;
}
// Returns the standard listener responsible for the default XML output
// controlled by the --gtest_output=xml flag. Can be removed from the
// listeners list by users who want to shut down the default XML output
// controlled by this flag and substitute it with custom one. Note that
// removing this object from the listener list with Release transfers its
// ownership to the caller and makes this function return NULL the next
// time.
TestEventListener* default_xml_generator() const {
return default_xml_generator_;
}
private:
2023-07-14 11:45:11 +00:00
friend class TestSuite;
2023-06-20 04:33:09 +00:00
friend class TestInfo;
friend class internal::DefaultGlobalTestPartResultReporter;
friend class internal::NoExecDeathTest;
friend class internal::TestEventListenersAccessor;
friend class internal::UnitTestImpl;
// Returns repeater that broadcasts the TestEventListener events to all
// subscribers.
TestEventListener* repeater();
// Sets the default_result_printer attribute to the provided listener.
// The listener is also added to the listener list and previous
// default_result_printer is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void SetDefaultResultPrinter(TestEventListener* listener);
// Sets the default_xml_generator attribute to the provided listener. The
// listener is also added to the listener list and previous
// default_xml_generator is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void SetDefaultXmlGenerator(TestEventListener* listener);
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
bool EventForwardingEnabled() const;
void SuppressEventForwarding();
// The actual list of listeners.
internal::TestEventRepeater* repeater_;
// Listener responsible for the standard result output.
TestEventListener* default_result_printer_;
// Listener responsible for the creation of the XML output file.
TestEventListener* default_xml_generator_;
// We disallow copying TestEventListeners.
2023-07-14 11:45:11 +00:00
TestEventListeners(const TestEventListeners&) = delete;
TestEventListeners& operator=(const TestEventListeners&) = delete;
2023-06-20 04:33:09 +00:00
};
2023-07-14 11:45:11 +00:00
// A UnitTest consists of a vector of TestSuites.
2023-06-20 04:33:09 +00:00
//
// This is a singleton class. The only instance of UnitTest is
// created when UnitTest::GetInstance() is first called. This
// instance is never deleted.
//
// UnitTest is not copyable.
//
// This class is thread-safe as long as the methods are called
// according to their specification.
class GTEST_API_ UnitTest {
public:
// Gets the singleton UnitTest object. The first time this method
// is called, a UnitTest object is constructed and returned.
// Consecutive calls will return the same object.
static UnitTest* GetInstance();
// Runs all tests in this UnitTest object and prints the result.
// Returns 0 if successful, or 1 otherwise.
//
// This method can only be called from the main thread.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
int Run() GTEST_MUST_USE_RESULT_;
// Returns the working directory when the first TEST() or TEST_F()
// was executed. The UnitTest object owns the string.
const char* original_working_dir() const;
2023-07-14 11:45:11 +00:00
// Returns the TestSuite object for the test that's currently running,
2023-06-20 04:33:09 +00:00
// or NULL if no test is running.
2023-07-14 11:45:11 +00:00
const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);
// Legacy API is still available but deprecated
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);
#endif
2023-06-20 04:33:09 +00:00
// Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running.
2023-07-14 11:45:11 +00:00
const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_);
2023-06-20 04:33:09 +00:00
// Returns the random seed used at the start of the current test run.
int random_seed() const;
2023-07-14 11:45:11 +00:00
// Returns the ParameterizedTestSuiteRegistry object used to keep track of
2023-06-20 04:33:09 +00:00
// value-parameterized tests and instantiate and register them.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2023-07-14 11:45:11 +00:00
internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()
2023-06-20 04:33:09 +00:00
GTEST_LOCK_EXCLUDED_(mutex_);
2023-07-14 11:45:11 +00:00
// Gets the number of successful test suites.
int successful_test_suite_count() const;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Gets the number of failed test suites.
int failed_test_suite_count() const;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Gets the number of all test suites.
int total_test_suite_count() const;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Gets the number of all test suites that contain at least one test
2023-06-20 04:33:09 +00:00
// that should run.
2023-07-14 11:45:11 +00:00
int test_suite_to_run_count() const;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
int successful_test_case_count() const;
int failed_test_case_count() const;
int total_test_case_count() const;
2023-06-20 04:33:09 +00:00
int test_case_to_run_count() const;
2023-07-14 11:45:11 +00:00
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
// Gets the number of successful tests.
int successful_test_count() const;
2023-07-14 11:45:11 +00:00
// Gets the number of skipped tests.
int skipped_test_count() const;
2023-06-20 04:33:09 +00:00
// Gets the number of failed tests.
int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const;
// Gets the number of disabled tests.
int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report.
int reportable_test_count() const;
// Gets the number of all tests.
int total_test_count() const;
// Gets the number of tests that should run.
int test_to_run_count() const;
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const;
// Gets the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const;
2023-07-14 11:45:11 +00:00
// Returns true if and only if the unit test passed (i.e. all test suites
// passed).
2023-06-20 04:33:09 +00:00
bool Passed() const;
2023-07-14 11:45:11 +00:00
// Returns true if and only if the unit test failed (i.e. some test suite
// failed or something outside of all tests failed).
2023-06-20 04:33:09 +00:00
bool Failed() const;
2023-07-14 11:45:11 +00:00
// Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
const TestSuite* GetTestSuite(int i) const;
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
const TestCase* GetTestCase(int i) const;
2023-07-14 11:45:11 +00:00
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
2023-06-20 04:33:09 +00:00
// Returns the TestResult containing information on test failures and
2023-07-14 11:45:11 +00:00
// properties logged outside of individual test suites.
2023-06-20 04:33:09 +00:00
const TestResult& ad_hoc_test_result() const;
// Returns the list of event listeners that can be used to track events
// inside Google Test.
TestEventListeners& listeners();
private:
// Registers and returns a global test environment. When a test
// program is run, all global test environments will be set-up in
// the order they were registered. After all tests in the program
// have finished, all global test environments will be torn-down in
// the *reverse* order they were registered.
//
// The UnitTest object takes ownership of the given environment.
//
// This method can only be called from the main thread.
Environment* AddEnvironment(Environment* env);
// Adds a TestPartResult to the current TestResult object. All
// Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
// eventually call this to report their results. The user code
// should use the assertion macros instead of calling this directly.
void AddTestPartResult(TestPartResult::Type result_type,
2023-07-14 11:45:11 +00:00
const char* file_name, int line_number,
2023-06-20 04:33:09 +00:00
const std::string& message,
const std::string& os_stack_trace)
GTEST_LOCK_EXCLUDED_(mutex_);
// Adds a TestProperty to the current TestResult object when invoked from
2023-07-14 11:45:11 +00:00
// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked
// from SetUpTestSuite or TearDownTestSuite, or to the global property set
2023-06-20 04:33:09 +00:00
// when invoked elsewhere. If the result already contains a property with
// the same key, the value will be updated.
void RecordProperty(const std::string& key, const std::string& value);
2023-07-14 11:45:11 +00:00
// Gets the i-th test suite among all the test suites. i can range from 0 to
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
TestSuite* GetMutableTestSuite(int i);
2023-06-20 04:33:09 +00:00
// Accessors for the implementation object.
internal::UnitTestImpl* impl() { return impl_; }
const internal::UnitTestImpl* impl() const { return impl_; }
2023-07-14 11:45:11 +00:00
// These classes and functions are friends as they need to access private
2023-06-20 04:33:09 +00:00
// members of UnitTest.
2023-07-14 11:45:11 +00:00
friend class ScopedTrace;
2023-06-20 04:33:09 +00:00
friend class Test;
friend class internal::AssertHelper;
friend class internal::StreamingListenerTest;
friend class internal::UnitTestRecordPropertyTestHelper;
friend Environment* AddGlobalTestEnvironment(Environment* env);
2023-07-14 11:45:11 +00:00
friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();
2023-06-20 04:33:09 +00:00
friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation(
2023-07-14 11:45:11 +00:00
TestPartResult::Type result_type, const std::string& message);
2023-06-20 04:33:09 +00:00
// Creates an empty UnitTest.
UnitTest();
// D'tor
virtual ~UnitTest();
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack.
void PushGTestTrace(const internal::TraceInfo& trace)
GTEST_LOCK_EXCLUDED_(mutex_);
// Pops a trace from the per-thread Google Test trace stack.
2023-07-14 11:45:11 +00:00
void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_);
2023-06-20 04:33:09 +00:00
// Protects mutable state in *impl_. This is mutable as some const
// methods need to lock it too.
mutable internal::Mutex mutex_;
// Opaque implementation object. This field is never changed once
// the object is constructed. We don't mark it as const here, as
// doing so will cause a warning in the constructor of UnitTest.
// Mutable state in *impl_ is protected by mutex_.
internal::UnitTestImpl* impl_;
// We disallow copying UnitTest.
2023-07-14 11:45:11 +00:00
UnitTest(const UnitTest&) = delete;
UnitTest& operator=(const UnitTest&) = delete;
2023-06-20 04:33:09 +00:00
};
// A convenient wrapper for adding an environment for the test
// program.
//
// You should call this before RUN_ALL_TESTS() is called, probably in
// main(). If you use gtest_main, you need to call this before main()
// starts for it to take effect. For example, you can define a global
// variable like this:
//
// testing::Environment* const foo_env =
// testing::AddGlobalTestEnvironment(new FooEnvironment);
//
// However, we strongly recommend you to write your own main() and
// call AddGlobalTestEnvironment() there, as relying on initialization
// of global variables makes the code harder to read and may cause
// problems when you register multiple environments from different
// translation units and the environments have dependencies among them
// (remember that the compiler doesn't guarantee the order in which
// global variables from different translation units are initialized).
inline Environment* AddGlobalTestEnvironment(Environment* env) {
return UnitTest::GetInstance()->AddEnvironment(env);
}
// Initializes Google Test. This must be called before calling
// RUN_ALL_TESTS(). In particular, it parses a command line for the
// flags that Google Test recognizes. Whenever a Google Test flag is
// seen, it is removed from argv, and *argc is decremented.
//
// No value is returned. Instead, the Google Test flag variables are
// updated.
//
// Calling the function for the second time has no user-visible effect.
GTEST_API_ void InitGoogleTest(int* argc, char** argv);
// This overloaded version can be used in Windows programs compiled in
// UNICODE mode.
GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
2023-07-14 11:45:11 +00:00
// This overloaded version can be used on Arduino/embedded platforms where
// there is no argc/argv.
GTEST_API_ void InitGoogleTest();
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
namespace internal {
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
// Separate the error generating code from the code path to reduce the stack
// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers
// when calling EXPECT_* in a tight loop.
2023-06-20 04:33:09 +00:00
template <typename T1, typename T2>
2023-07-14 11:45:11 +00:00
AssertionResult CmpHelperEQFailure(const char* lhs_expression,
const char* rhs_expression, const T1& lhs,
const T2& rhs) {
return EqFailure(lhs_expression, rhs_expression,
FormatForComparisonFailureMessage(lhs, rhs),
FormatForComparisonFailureMessage(rhs, lhs), false);
2023-06-20 04:33:09 +00:00
}
2023-07-14 11:45:11 +00:00
// This block of code defines operator==/!=
// to block lexical scope lookup.
// It prevents using invalid operator==/!= defined at namespace scope.
struct faketype {};
inline bool operator==(faketype, faketype) { return true; }
inline bool operator!=(faketype, faketype) { return false; }
2023-06-20 04:33:09 +00:00
// The helper function for {ASSERT|EXPECT}_EQ.
template <typename T1, typename T2>
2023-07-14 11:45:11 +00:00
AssertionResult CmpHelperEQ(const char* lhs_expression,
const char* rhs_expression, const T1& lhs,
const T2& rhs) {
if (lhs == rhs) {
2023-06-20 04:33:09 +00:00
return AssertionSuccess();
}
2023-07-14 11:45:11 +00:00
return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);
2023-06-20 04:33:09 +00:00
}
class EqHelper {
public:
// This templatized version is for the general case.
2023-07-14 11:45:11 +00:00
template <
typename T1, typename T2,
// Disable this overload for cases where one argument is a pointer
// and the other is the null pointer constant.
typename std::enable_if<!std::is_integral<T1>::value ||
!std::is_pointer<T2>::value>::type* = nullptr>
static AssertionResult Compare(const char* lhs_expression,
const char* rhs_expression, const T1& lhs,
const T2& rhs) {
return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
2023-06-20 04:33:09 +00:00
}
// With this overloaded version, we allow anonymous enums to be used
// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
// enums can be implicitly cast to BiggestInt.
//
// Even though its body looks the same as the above version, we
// cannot merge the two, as it will make anonymous enums unhappy.
2023-07-14 11:45:11 +00:00
static AssertionResult Compare(const char* lhs_expression,
const char* rhs_expression, BiggestInt lhs,
BiggestInt rhs) {
return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);
2023-06-20 04:33:09 +00:00
}
template <typename T>
static AssertionResult Compare(
2023-07-14 11:45:11 +00:00
const char* lhs_expression, const char* rhs_expression,
// Handle cases where '0' is used as a null pointer literal.
std::nullptr_t /* lhs */, T* rhs) {
// We already know that 'lhs' is a null pointer.
return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),
rhs);
2023-06-20 04:33:09 +00:00
}
};
2023-07-14 11:45:11 +00:00
// Separate the error generating code from the code path to reduce the stack
// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers
// when calling EXPECT_OP in a tight loop.
template <typename T1, typename T2>
AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,
const T1& val1, const T2& val2,
const char* op) {
return AssertionFailure()
<< "Expected: (" << expr1 << ") " << op << " (" << expr2
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)
<< " vs " << FormatForComparisonFailureMessage(val2, val1);
}
2023-06-20 04:33:09 +00:00
// A macro for implementing the helper functions needed to implement
// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
// of similar code.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2023-07-14 11:45:11 +00:00
#define GTEST_IMPL_CMP_HELPER_(op_name, op) \
template <typename T1, typename T2> \
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
const T1& val1, const T2& val2) { \
if (val1 op val2) { \
return AssertionSuccess(); \
} else { \
return CmpHelperOpFailure(expr1, expr2, val1, val2, #op); \
} \
}
2023-06-20 04:33:09 +00:00
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
// Implements the helper function for {ASSERT|EXPECT}_NE
2023-07-14 11:45:11 +00:00
GTEST_IMPL_CMP_HELPER_(NE, !=)
2023-06-20 04:33:09 +00:00
// Implements the helper function for {ASSERT|EXPECT}_LE
2023-07-14 11:45:11 +00:00
GTEST_IMPL_CMP_HELPER_(LE, <=)
2023-06-20 04:33:09 +00:00
// Implements the helper function for {ASSERT|EXPECT}_LT
2023-07-14 11:45:11 +00:00
GTEST_IMPL_CMP_HELPER_(LT, <)
2023-06-20 04:33:09 +00:00
// Implements the helper function for {ASSERT|EXPECT}_GE
2023-07-14 11:45:11 +00:00
GTEST_IMPL_CMP_HELPER_(GE, >=)
2023-06-20 04:33:09 +00:00
// Implements the helper function for {ASSERT|EXPECT}_GT
2023-07-14 11:45:11 +00:00
GTEST_IMPL_CMP_HELPER_(GT, >)
2023-06-20 04:33:09 +00:00
#undef GTEST_IMPL_CMP_HELPER_
// The helper function for {ASSERT|EXPECT}_STREQ.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2023-07-14 11:45:11 +00:00
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
const char* s2_expression,
const char* s1, const char* s2);
2023-06-20 04:33:09 +00:00
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2023-07-14 11:45:11 +00:00
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,
const char* s2_expression,
const char* s1, const char* s2);
2023-06-20 04:33:09 +00:00
// The helper function for {ASSERT|EXPECT}_STRNE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
2023-07-14 11:45:11 +00:00
const char* s1, const char* s2);
2023-06-20 04:33:09 +00:00
// The helper function for {ASSERT|EXPECT}_STRCASENE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression,
2023-07-14 11:45:11 +00:00
const char* s1, const char* s2);
2023-06-20 04:33:09 +00:00
// Helper function for *_STREQ on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
2023-07-14 11:45:11 +00:00
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,
const char* s2_expression,
const wchar_t* s1, const wchar_t* s2);
2023-06-20 04:33:09 +00:00
// Helper function for *_STRNE on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
2023-07-14 11:45:11 +00:00
const wchar_t* s1, const wchar_t* s2);
2023-06-20 04:33:09 +00:00
} // namespace internal
// IsSubstring() and IsNotSubstring() are intended to be used as the
// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
// themselves. They check whether needle is a substring of haystack
// (NULL is considered a substring of itself only), and return an
// appropriate error message when they fail.
//
// The {needle,haystack}_expr arguments are the stringified
// expressions that generated the two real arguments.
2023-07-14 11:45:11 +00:00
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const char* needle,
const char* haystack);
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const wchar_t* needle,
const wchar_t* haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const char* needle,
const char* haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const wchar_t* needle,
const wchar_t* haystack);
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::string& needle,
const ::std::string& haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::string& needle,
const ::std::string& haystack);
2023-06-20 04:33:09 +00:00
#if GTEST_HAS_STD_WSTRING
2023-07-14 11:45:11 +00:00
GTEST_API_ AssertionResult IsSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::wstring& needle,
const ::std::wstring& haystack);
GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,
const char* haystack_expr,
const ::std::wstring& needle,
const ::std::wstring& haystack);
2023-06-20 04:33:09 +00:00
#endif // GTEST_HAS_STD_WSTRING
namespace internal {
// Helper template function for comparing floating-points.
//
// Template parameter:
//
// RawType: the raw floating-point type (either float or double)
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename RawType>
2023-07-14 11:45:11 +00:00
AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,
const char* rhs_expression,
RawType lhs_value, RawType rhs_value) {
const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);
2023-06-20 04:33:09 +00:00
if (lhs.AlmostEquals(rhs)) {
return AssertionSuccess();
}
2023-07-14 11:45:11 +00:00
::std::stringstream lhs_ss;
lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< lhs_value;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
::std::stringstream rhs_ss;
rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< rhs_value;
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
return EqFailure(lhs_expression, rhs_expression,
StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),
2023-06-20 04:33:09 +00:00
false);
}
// Helper function for implementing ASSERT_NEAR.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
const char* expr2,
const char* abs_error_expr,
2023-07-14 11:45:11 +00:00
double val1, double val2,
2023-06-20 04:33:09 +00:00
double abs_error);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// A class that enables one to stream messages to assertion macros
class GTEST_API_ AssertHelper {
public:
// Constructor.
2023-07-14 11:45:11 +00:00
AssertHelper(TestPartResult::Type type, const char* file, int line,
2023-06-20 04:33:09 +00:00
const char* message);
~AssertHelper();
// Message assignment is a semantic trick to enable assertion
// streaming; see the GTEST_MESSAGE_ macro below.
void operator=(const Message& message) const;
private:
// We put our data in a struct so that the size of the AssertHelper class can
// be as small as possible. This is important because gcc is incapable of
// re-using stack space even for temporary variables, so every EXPECT_EQ
// reserves stack space for another AssertHelper.
struct AssertHelperData {
2023-07-14 11:45:11 +00:00
AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num,
2023-06-20 04:33:09 +00:00
const char* msg)
2023-07-14 11:45:11 +00:00
: type(t), file(srcfile), line(line_num), message(msg) {}
2023-06-20 04:33:09 +00:00
TestPartResult::Type const type;
const char* const file;
int const line;
std::string const message;
private:
2023-07-14 11:45:11 +00:00
AssertHelperData(const AssertHelperData&) = delete;
AssertHelperData& operator=(const AssertHelperData&) = delete;
2023-06-20 04:33:09 +00:00
};
AssertHelperData* const data_;
2023-07-14 11:45:11 +00:00
AssertHelper(const AssertHelper&) = delete;
AssertHelper& operator=(const AssertHelper&) = delete;
2023-06-20 04:33:09 +00:00
};
} // namespace internal
// The pure interface class that all value-parameterized tests inherit from.
// A value-parameterized class must inherit from both ::testing::Test and
// ::testing::WithParamInterface. In most cases that just means inheriting
// from ::testing::TestWithParam, but more complicated test hierarchies
// may need to inherit from Test and WithParamInterface at different levels.
//
// This interface has support for accessing the test parameter value via
// the GetParam() method.
//
// Use it with one of the parameter generator defining functions, like Range(),
2023-07-14 11:45:11 +00:00
// Values(), ValuesIn(), Bool(), Combine(), and ConvertGenerator<T>().
2023-06-20 04:33:09 +00:00
//
// class FooTest : public ::testing::TestWithParam<int> {
// protected:
// FooTest() {
// // Can use GetParam() here.
// }
2023-07-14 11:45:11 +00:00
// ~FooTest() override {
2023-06-20 04:33:09 +00:00
// // Can use GetParam() here.
// }
2023-07-14 11:45:11 +00:00
// void SetUp() override {
2023-06-20 04:33:09 +00:00
// // Can use GetParam() here.
// }
2023-07-14 11:45:11 +00:00
// void TearDown override {
2023-06-20 04:33:09 +00:00
// // Can use GetParam() here.
// }
// };
// TEST_P(FooTest, DoesBar) {
// // Can use GetParam() method here.
// Foo foo;
// ASSERT_TRUE(foo.DoesBar(GetParam()));
// }
2023-07-14 11:45:11 +00:00
// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
2023-06-20 04:33:09 +00:00
template <typename T>
class WithParamInterface {
public:
typedef T ParamType;
virtual ~WithParamInterface() {}
// The current parameter value. Is also available in the test fixture's
2023-07-14 11:45:11 +00:00
// constructor.
static const ParamType& GetParam() {
GTEST_CHECK_(parameter_ != nullptr)
2023-06-20 04:33:09 +00:00
<< "GetParam() can only be called inside a value-parameterized test "
<< "-- did you intend to write TEST_P instead of TEST_F?";
return *parameter_;
}
private:
// Sets parameter value. The caller is responsible for making sure the value
// remains alive and unchanged throughout the current test.
2023-07-14 11:45:11 +00:00
static void SetParam(const ParamType* parameter) { parameter_ = parameter; }
2023-06-20 04:33:09 +00:00
// Static value used for accessing parameter during a test lifetime.
static const ParamType* parameter_;
// TestClass must be a subclass of WithParamInterface<T> and Test.
2023-07-14 11:45:11 +00:00
template <class TestClass>
friend class internal::ParameterizedTestFactory;
2023-06-20 04:33:09 +00:00
};
template <typename T>
2023-07-14 11:45:11 +00:00
const T* WithParamInterface<T>::parameter_ = nullptr;
2023-06-20 04:33:09 +00:00
// Most value-parameterized classes can ignore the existence of
// WithParamInterface, and can just inherit from ::testing::TestWithParam.
template <typename T>
2023-07-14 11:45:11 +00:00
class TestWithParam : public Test, public WithParamInterface<T> {};
2023-06-20 04:33:09 +00:00
// Macros for indicating success/failure in test code.
2023-07-14 11:45:11 +00:00
// Skips test in runtime.
// Skipping test aborts current function.
// Skipped tests are neither successful nor failed.
#define GTEST_SKIP() GTEST_SKIP_("")
2023-06-20 04:33:09 +00:00
// ADD_FAILURE unconditionally adds a failure to the current test.
// SUCCEED generates a success - it doesn't automatically make the
// current test successful, as a test is only successful when it has
// no failure.
//
// EXPECT_* verifies that a certain condition is satisfied. If not,
// it behaves like ADD_FAILURE. In particular:
//
// EXPECT_TRUE verifies that a Boolean condition is true.
// EXPECT_FALSE verifies that a Boolean condition is false.
//
// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
// that they will also abort the current function on failure. People
// usually want the fail-fast behavior of FAIL and ASSERT_*, but those
// writing data-driven tests often find themselves using ADD_FAILURE
// and EXPECT_* more.
// Generates a nonfatal failure with a generic message.
#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
// Generates a nonfatal failure at the given source file location with
// a generic message.
2023-07-14 11:45:11 +00:00
#define ADD_FAILURE_AT(file, line) \
2023-06-20 04:33:09 +00:00
GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kNonFatalFailure)
// Generates a fatal failure with a generic message.
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
2023-07-14 11:45:11 +00:00
// Like GTEST_FAIL(), but at the given source file location.
#define GTEST_FAIL_AT(file, line) \
return GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kFatalFailure)
2023-06-20 04:33:09 +00:00
// Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_FAIL
2023-07-14 11:45:11 +00:00
#define FAIL() GTEST_FAIL()
2023-06-20 04:33:09 +00:00
#endif
// Generates a success with a generic message.
#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
// Define this macro to 1 to omit the definition of SUCCEED(), which
// is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_SUCCEED
2023-07-14 11:45:11 +00:00
#define SUCCEED() GTEST_SUCCEED()
2023-06-20 04:33:09 +00:00
#endif
// Macros for testing exceptions.
//
// * {ASSERT|EXPECT}_THROW(statement, expected_exception):
// Tests that the statement throws the expected exception.
// * {ASSERT|EXPECT}_NO_THROW(statement):
// Tests that the statement doesn't throw any exception.
// * {ASSERT|EXPECT}_ANY_THROW(statement):
// Tests that the statement throws an exception.
#define EXPECT_THROW(statement, expected_exception) \
GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
#define EXPECT_NO_THROW(statement) \
GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
#define EXPECT_ANY_THROW(statement) \
GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
#define ASSERT_THROW(statement, expected_exception) \
GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
#define ASSERT_NO_THROW(statement) \
GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
#define ASSERT_ANY_THROW(statement) \
GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
// Boolean assertions. Condition can be either a Boolean expression or an
// AssertionResult. For more information on how to use AssertionResult with
// these macros see comments on that class.
2023-07-14 11:45:11 +00:00
#define GTEST_EXPECT_TRUE(condition) \
2023-06-20 04:33:09 +00:00
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_NONFATAL_FAILURE_)
2023-07-14 11:45:11 +00:00
#define GTEST_EXPECT_FALSE(condition) \
2023-06-20 04:33:09 +00:00
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_)
2023-07-14 11:45:11 +00:00
#define GTEST_ASSERT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_)
#define GTEST_ASSERT_FALSE(condition) \
2023-06-20 04:33:09 +00:00
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_FATAL_FAILURE_)
2023-07-14 11:45:11 +00:00
// Define these macros to 1 to omit the definition of the corresponding
// EXPECT or ASSERT, which clashes with some users' own code.
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#if !GTEST_DONT_DEFINE_EXPECT_TRUE
#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)
#endif
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#if !GTEST_DONT_DEFINE_EXPECT_FALSE
#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)
#endif
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#if !GTEST_DONT_DEFINE_ASSERT_TRUE
#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)
#endif
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#if !GTEST_DONT_DEFINE_ASSERT_FALSE
#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)
#endif
2023-06-20 04:33:09 +00:00
// Macros for testing equalities and inequalities.
//
2023-07-14 11:45:11 +00:00
// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2
// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
2023-06-20 04:33:09 +00:00
//
// When they are not, Google Test prints both the tested expressions and
// their actual values. The values must be compatible built-in types,
// or you will get a compiler error. By "compatible" we mean that the
// values can be compared by the respective operator.
//
// Note:
//
// 1. It is possible to make a user-defined type work with
// {ASSERT|EXPECT}_??(), but that requires overloading the
// comparison operators and is thus discouraged by the Google C++
// Usage Guide. Therefore, you are advised to use the
// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
// equal.
//
// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
// pointers (in particular, C strings). Therefore, if you use it
// with two C strings, you are testing how their locations in memory
// are related, not how their content is related. To compare two C
// strings by content, use {ASSERT|EXPECT}_STR*().
//
2023-07-14 11:45:11 +00:00
// 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to
// {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you
2023-06-20 04:33:09 +00:00
// what the actual value is when it fails, and similarly for the
// other comparisons.
//
// 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
// evaluate their arguments, which is undefined.
//
// 5. These macros evaluate their arguments exactly once.
//
// Examples:
//
2023-07-14 11:45:11 +00:00
// EXPECT_NE(Foo(), 5);
// EXPECT_EQ(a_pointer, NULL);
2023-06-20 04:33:09 +00:00
// ASSERT_LT(i, array_size);
// ASSERT_GT(records.size(), 0) << "There is no record left.";
2023-07-14 11:45:11 +00:00
#define EXPECT_EQ(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
#define EXPECT_NE(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
2023-06-20 04:33:09 +00:00
#define EXPECT_LE(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
#define EXPECT_LT(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
#define EXPECT_GE(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
#define EXPECT_GT(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
2023-07-14 11:45:11 +00:00
#define GTEST_ASSERT_EQ(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)
2023-06-20 04:33:09 +00:00
#define GTEST_ASSERT_NE(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
#define GTEST_ASSERT_LE(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
#define GTEST_ASSERT_LT(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
#define GTEST_ASSERT_GE(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
#define GTEST_ASSERT_GT(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
// ASSERT_XY(), which clashes with some users' own code.
#if !GTEST_DONT_DEFINE_ASSERT_EQ
2023-07-14 11:45:11 +00:00
#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
2023-06-20 04:33:09 +00:00
#endif
#if !GTEST_DONT_DEFINE_ASSERT_NE
2023-07-14 11:45:11 +00:00
#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
2023-06-20 04:33:09 +00:00
#endif
#if !GTEST_DONT_DEFINE_ASSERT_LE
2023-07-14 11:45:11 +00:00
#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
2023-06-20 04:33:09 +00:00
#endif
#if !GTEST_DONT_DEFINE_ASSERT_LT
2023-07-14 11:45:11 +00:00
#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
2023-06-20 04:33:09 +00:00
#endif
#if !GTEST_DONT_DEFINE_ASSERT_GE
2023-07-14 11:45:11 +00:00
#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
2023-06-20 04:33:09 +00:00
#endif
#if !GTEST_DONT_DEFINE_ASSERT_GT
2023-07-14 11:45:11 +00:00
#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
2023-06-20 04:33:09 +00:00
#endif
// C-string Comparisons. All tests treat NULL and any non-NULL string
// as different. Two NULLs are equal.
//
// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
//
// For wide or narrow string objects, you can use the
// {ASSERT|EXPECT}_??() macros.
//
// Don't depend on the order in which the arguments are evaluated,
// which is undefined.
//
// These macros evaluate their arguments exactly once.
2023-07-14 11:45:11 +00:00
#define EXPECT_STREQ(s1, s2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
2023-06-20 04:33:09 +00:00
#define EXPECT_STRNE(s1, s2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2023-07-14 11:45:11 +00:00
#define EXPECT_STRCASEEQ(s1, s2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
#define EXPECT_STRCASENE(s1, s2) \
2023-06-20 04:33:09 +00:00
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
2023-07-14 11:45:11 +00:00
#define ASSERT_STREQ(s1, s2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)
2023-06-20 04:33:09 +00:00
#define ASSERT_STRNE(s1, s2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
2023-07-14 11:45:11 +00:00
#define ASSERT_STRCASEEQ(s1, s2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)
#define ASSERT_STRCASENE(s1, s2) \
2023-06-20 04:33:09 +00:00
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
// Macros for comparing floating-point numbers.
//
2023-07-14 11:45:11 +00:00
// * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):
2023-06-20 04:33:09 +00:00
// Tests that two float values are almost equal.
2023-07-14 11:45:11 +00:00
// * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):
2023-06-20 04:33:09 +00:00
// Tests that two double values are almost equal.
// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
// Tests that v1 and v2 are within the given distance to each other.
//
// Google Test uses ULP-based comparison to automatically pick a default
// error bound that is appropriate for the operands. See the
// FloatingPoint template class in gtest-internal.h if you are
// interested in the implementation details.
2023-07-14 11:45:11 +00:00
#define EXPECT_FLOAT_EQ(val1, val2) \
2023-06-20 04:33:09 +00:00
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2023-07-14 11:45:11 +00:00
val1, val2)
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define EXPECT_DOUBLE_EQ(val1, val2) \
2023-06-20 04:33:09 +00:00
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2023-07-14 11:45:11 +00:00
val1, val2)
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define ASSERT_FLOAT_EQ(val1, val2) \
2023-06-20 04:33:09 +00:00
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
2023-07-14 11:45:11 +00:00
val1, val2)
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define ASSERT_DOUBLE_EQ(val1, val2) \
2023-06-20 04:33:09 +00:00
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
2023-07-14 11:45:11 +00:00
val1, val2)
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define EXPECT_NEAR(val1, val2, abs_error) \
EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
abs_error)
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define ASSERT_NEAR(val1, val2, abs_error) \
ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \
abs_error)
2023-06-20 04:33:09 +00:00
// These predicate format functions work on floating-point values, and
// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
//
// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
float val1, float val2);
GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2);
#if GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful
// on Windows, and rely on Windows SDK macros and APIs to compile.
//
// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
//
// When expr unexpectedly fails or succeeds, Google Test prints the
// expected result and the actual result with both a human-readable
// string representation of the error, if available, as well as the
// hex result code.
2023-07-14 11:45:11 +00:00
#define EXPECT_HRESULT_SUCCEEDED(expr) \
EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define ASSERT_HRESULT_SUCCEEDED(expr) \
ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define EXPECT_HRESULT_FAILED(expr) \
EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#define ASSERT_HRESULT_FAILED(expr) \
ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
2023-06-20 04:33:09 +00:00
#endif // GTEST_OS_WINDOWS
// Macros that execute statement and check that it doesn't generate new fatal
// failures in the current thread.
//
// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
//
// Examples:
//
// EXPECT_NO_FATAL_FAILURE(Process());
// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
//
#define ASSERT_NO_FATAL_FAILURE(statement) \
2023-07-14 11:45:11 +00:00
GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
2023-06-20 04:33:09 +00:00
#define EXPECT_NO_FATAL_FAILURE(statement) \
2023-07-14 11:45:11 +00:00
GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
// Causes a trace (including the given source file path and line number,
// and the given message) to be included in every test failure message generated
// by code in the scope of the lifetime of an instance of this class. The effect
// is undone with the destruction of the instance.
//
// The message argument can be anything streamable to std::ostream.
//
// Example:
// testing::ScopedTrace trace("file.cc", 123, "message");
//
class GTEST_API_ ScopedTrace {
public:
// The c'tor pushes the given source file location and message onto
// a trace stack maintained by Google Test.
// Template version. Uses Message() to convert the values into strings.
// Slow, but flexible.
template <typename T>
ScopedTrace(const char* file, int line, const T& message) {
PushTrace(file, line, (Message() << message).GetString());
}
// Optimize for some known types.
ScopedTrace(const char* file, int line, const char* message) {
PushTrace(file, line, message ? message : "(null)");
}
ScopedTrace(const char* file, int line, const std::string& message) {
PushTrace(file, line, message);
}
// The d'tor pops the info pushed by the c'tor.
//
// Note that the d'tor is not virtual in order to be efficient.
// Don't inherit from ScopedTrace!
~ScopedTrace();
private:
void PushTrace(const char* file, int line, std::string message);
ScopedTrace(const ScopedTrace&) = delete;
ScopedTrace& operator=(const ScopedTrace&) = delete;
};
2023-06-20 04:33:09 +00:00
// Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure
// message generated by code in the current scope. The effect is
// undone when the control leaves the current scope.
//
// The message argument can be anything streamable to std::ostream.
//
// In the implementation, we include the current line number as part
// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
// to appear in the same block - as long as they are on different
// lines.
2023-07-14 11:45:11 +00:00
//
// Assuming that each thread maintains its own stack of traces.
// Therefore, a SCOPED_TRACE() would (correctly) only affect the
// assertions in its own thread.
#define SCOPED_TRACE(message) \
::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \
__FILE__, __LINE__, (message))
2023-06-20 04:33:09 +00:00
// Compile-time assertion for type equality.
2023-07-14 11:45:11 +00:00
// StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2
// are the same type. The value it returns is not interesting.
2023-06-20 04:33:09 +00:00
//
// Instead of making StaticAssertTypeEq a class template, we make it a
// function template that invokes a helper class template. This
// prevents a user from misusing StaticAssertTypeEq<T1, T2> by
// defining objects of that type.
//
// CAVEAT:
//
// When used inside a method of a class template,
// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
// instantiated. For example, given:
//
// template <typename T> class Foo {
// public:
// void Bar() { testing::StaticAssertTypeEq<int, T>(); }
// };
//
// the code:
//
// void Test1() { Foo<bool> foo; }
//
// will NOT generate a compiler error, as Foo<bool>::Bar() is never
// actually instantiated. Instead, you need:
//
// void Test2() { Foo<bool> foo; foo.Bar(); }
//
// to cause a compiler error.
template <typename T1, typename T2>
2023-07-14 11:45:11 +00:00
constexpr bool StaticAssertTypeEq() noexcept {
static_assert(std::is_same<T1, T2>::value, "T1 and T2 are not the same type");
2023-06-20 04:33:09 +00:00
return true;
}
// Defines a test.
//
2023-07-14 11:45:11 +00:00
// The first parameter is the name of the test suite, and the second
// parameter is the name of the test within the test suite.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// The convention is to end the test suite name with "Test". For
// example, a test suite for the Foo class can be named FooTest.
2023-06-20 04:33:09 +00:00
//
2023-07-14 11:45:11 +00:00
// Test code should appear between braces after an invocation of
// this macro. Example:
2023-06-20 04:33:09 +00:00
//
// TEST(FooTest, InitializesCorrectly) {
// Foo foo;
// EXPECT_TRUE(foo.StatusIsOK());
// }
// Note that we call GetTestTypeId() instead of GetTypeId<
// ::testing::Test>() here to get the type ID of testing::Test. This
// is to work around a suspected linker bug when using Google Test as
// a framework on Mac OS X. The bug causes GetTypeId<
// ::testing::Test>() to return different values depending on whether
// the call is from the Google Test framework itself or from user test
// code. GetTestTypeId() is guaranteed to always return the same
// value, as it always calls GetTypeId<>() from the Google Test
// framework.
2023-07-14 11:45:11 +00:00
#define GTEST_TEST(test_suite_name, test_name) \
GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \
::testing::internal::GetTestTypeId())
2023-06-20 04:33:09 +00:00
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_TEST
2023-07-14 11:45:11 +00:00
#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
2023-06-20 04:33:09 +00:00
#endif
// Defines a test that uses a test fixture.
//
// The first parameter is the name of the test fixture class, which
2023-07-14 11:45:11 +00:00
// also doubles as the test suite name. The second parameter is the
// name of the test within the test suite.
2023-06-20 04:33:09 +00:00
//
// A test fixture class must be declared earlier. The user should put
2023-07-14 11:45:11 +00:00
// the test code between braces after using this macro. Example:
2023-06-20 04:33:09 +00:00
//
// class FooTest : public testing::Test {
// protected:
2023-07-14 11:45:11 +00:00
// void SetUp() override { b_.AddElement(3); }
2023-06-20 04:33:09 +00:00
//
// Foo a_;
// Foo b_;
// };
//
// TEST_F(FooTest, InitializesCorrectly) {
// EXPECT_TRUE(a_.StatusIsOK());
// }
//
// TEST_F(FooTest, ReturnsElementCountCorrectly) {
2023-07-14 11:45:11 +00:00
// EXPECT_EQ(a_.size(), 0);
// EXPECT_EQ(b_.size(), 1);
2023-06-20 04:33:09 +00:00
// }
2023-07-14 11:45:11 +00:00
#define GTEST_TEST_F(test_fixture, test_name) \
2023-06-20 04:33:09 +00:00
GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>())
2023-07-14 11:45:11 +00:00
#if !GTEST_DONT_DEFINE_TEST_F
#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name)
#endif
// Returns a path to a temporary directory, which should be writable. It is
// implementation-dependent whether or not the path is terminated by the
// directory-separator character.
GTEST_API_ std::string TempDir();
// Returns a path to a directory that contains ancillary data files that might
// be used by tests. It is implementation dependent whether or not the path is
// terminated by the directory-separator character. The directory and the files
// in it should be considered read-only.
GTEST_API_ std::string SrcDir();
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// Dynamically registers a test with the framework.
//
// This is an advanced API only to be used when the `TEST` macros are
// insufficient. The macros should be preferred when possible, as they avoid
// most of the complexity of calling this function.
//
// The `factory` argument is a factory callable (move-constructible) object or
// function pointer that creates a new instance of the Test object. It
// handles ownership to the caller. The signature of the callable is
// `Fixture*()`, where `Fixture` is the test fixture class for the test. All
// tests registered with the same `test_suite_name` must return the same
// fixture type. This is checked at runtime.
//
// The framework will infer the fixture class from the factory and will call
// the `SetUpTestSuite` and `TearDownTestSuite` for it.
//
// Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is
// undefined.
//
// Use case example:
//
// class MyFixture : public ::testing::Test {
// public:
// // All of these optional, just like in regular macro usage.
// static void SetUpTestSuite() { ... }
// static void TearDownTestSuite() { ... }
// void SetUp() override { ... }
// void TearDown() override { ... }
// };
//
// class MyTest : public MyFixture {
// public:
// explicit MyTest(int data) : data_(data) {}
// void TestBody() override { ... }
//
// private:
// int data_;
// };
//
// void RegisterMyTests(const std::vector<int>& values) {
// for (int v : values) {
// ::testing::RegisterTest(
// "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr,
// std::to_string(v).c_str(),
// __FILE__, __LINE__,
// // Important to use the fixture type as the return type here.
// [=]() -> MyFixture* { return new MyTest(v); });
// }
// }
// ...
// int main(int argc, char** argv) {
// ::testing::InitGoogleTest(&argc, argv);
// std::vector<int> values_to_test = LoadValuesFromConfig();
// RegisterMyTests(values_to_test);
// ...
// return RUN_ALL_TESTS();
// }
//
template <int&... ExplicitParameterBarrier, typename Factory>
TestInfo* RegisterTest(const char* test_suite_name, const char* test_name,
const char* type_param, const char* value_param,
const char* file, int line, Factory factory) {
using TestT = typename std::remove_pointer<decltype(factory())>::type;
class FactoryImpl : public internal::TestFactoryBase {
public:
explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}
Test* CreateTest() override { return factory_(); }
private:
Factory factory_;
};
return internal::MakeAndRegisterTestInfo(
test_suite_name, test_name, type_param, value_param,
internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),
internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),
internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),
new FactoryImpl{std::move(factory)});
}
2023-06-20 04:33:09 +00:00
} // namespace testing
// Use this function in main() to run all tests. It returns 0 if all
// tests are successful, or 1 otherwise.
//
// RUN_ALL_TESTS() should be invoked after the command line has been
// parsed by InitGoogleTest().
//
// This function was formerly a macro; thus, it is in the global
// namespace and has an all-caps name.
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;
2023-07-14 11:45:11 +00:00
inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2023-06-20 04:33:09 +00:00
2023-07-14 11:45:11 +00:00
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_H_