diff options
author | bulatman <bulatman@yandex-team.ru> | 2022-02-10 16:45:50 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:50 +0300 |
commit | 2f6ca198245aeffd5e2d82b65927c2465b68b4f5 (patch) | |
tree | 9142afc54d335ea52910662635b898e79e192e49 /contrib/restricted/googletest/googlemock/include/gmock/gmock-spec-builders.h | |
parent | 6560e4993b14d193f8c879e33a3de5e5eba6e21d (diff) | |
download | ydb-2f6ca198245aeffd5e2d82b65927c2465b68b4f5.tar.gz |
Restoring authorship annotation for <bulatman@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'contrib/restricted/googletest/googlemock/include/gmock/gmock-spec-builders.h')
-rw-r--r-- | contrib/restricted/googletest/googlemock/include/gmock/gmock-spec-builders.h | 944 |
1 files changed, 472 insertions, 472 deletions
diff --git a/contrib/restricted/googletest/googlemock/include/gmock/gmock-spec-builders.h b/contrib/restricted/googletest/googlemock/include/gmock/gmock-spec-builders.h index 22c427de8c..41323c1cc0 100644 --- a/contrib/restricted/googletest/googlemock/include/gmock/gmock-spec-builders.h +++ b/contrib/restricted/googletest/googlemock/include/gmock/gmock-spec-builders.h @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - + // Google Mock - a framework for writing C++ mock classes. // // This file implements the ON_CALL() and EXPECT_CALL() macros. @@ -56,19 +56,19 @@ // where all clauses are optional, and .InSequence()/.After()/ // .WillOnce() can appear any number of times. -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ -#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ +// GOOGLETEST_CM0002 DO NOT DELETE + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ -#include <functional> +#include <functional> #include <map> -#include <memory> +#include <memory> #include <set> #include <sstream> #include <string> -#include <type_traits> -#include <utility> +#include <type_traits> +#include <utility> #include <vector> #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" @@ -77,13 +77,13 @@ #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" -#if GTEST_HAS_EXCEPTIONS -# include <stdexcept> // NOLINT -#endif - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - +#if GTEST_HAS_EXCEPTIONS +# include <stdexcept> // NOLINT +#endif + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ +/* class A needs to have dll-interface to be used by clients of class B */) + namespace testing { // An abstract handle of an expectation. @@ -108,14 +108,14 @@ template <typename F> class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; -// Helper classes for implementing NiceMock, StrictMock, and NaggyMock. -template <typename MockClass> -class NiceMockImpl; -template <typename MockClass> -class StrictMockImpl; -template <typename MockClass> -class NaggyMockImpl; - +// Helper classes for implementing NiceMock, StrictMock, and NaggyMock. +template <typename MockClass> +class NiceMockImpl; +template <typename MockClass> +class StrictMockImpl; +template <typename MockClass> +class NaggyMockImpl; + // Protects the mock object registry (in class Mock), all function // mockers, and all expectations. // @@ -132,9 +132,9 @@ GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); // Untyped base class for ActionResultHolder<R>. class UntypedActionResultHolderBase; -// Abstract base class of FunctionMocker. This is the +// Abstract base class of FunctionMocker. This is the // type-agnostic part of the function mocker interface. Its pure -// virtual methods are implemented by FunctionMocker. +// virtual methods are implemented by FunctionMocker. class GTEST_API_ UntypedFunctionMockerBase { public: UntypedFunctionMockerBase(); @@ -160,13 +160,13 @@ class GTEST_API_ UntypedFunctionMockerBase { // action fails. // L = * virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( - void* untyped_args, const std::string& call_description) const = 0; + void* untyped_args, const std::string& call_description) const = 0; // Performs the given action with the given arguments and returns // the action's result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformAction( - const void* untyped_action, void* untyped_args) const = 0; + const void* untyped_action, void* untyped_args) const = 0; // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given @@ -220,13 +220,13 @@ class GTEST_API_ UntypedFunctionMockerBase { // arguments. This function can be safely called from multiple // threads concurrently. The caller is responsible for deleting the // result. - UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector<const void*> UntypedOnCallSpecs; - using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>; + using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>; // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. @@ -245,14 +245,14 @@ class GTEST_API_ UntypedFunctionMockerBase { UntypedOnCallSpecs untyped_on_call_specs_; // All expectations for this function mocker. - // - // It's undefined behavior to interleave expectations (EXPECT_CALLs - // or ON_CALLs) and mock function calls. Also, the order of - // expectations is important. Therefore it's a logic race condition - // to read/write untyped_expectations_ concurrently. In order for - // tools like tsan to catch concurrent read/write accesses to - // untyped_expectations, we deliberately leave accesses to it - // unprotected. + // + // It's undefined behavior to interleave expectations (EXPECT_CALLs + // or ON_CALLs) and mock function calls. Also, the order of + // expectations is important. Therefore it's a logic race condition + // to read/write untyped_expectations_ concurrently. In order for + // tools like tsan to catch concurrent read/write accesses to + // untyped_expectations, we deliberately leave accesses to it + // unprotected. UntypedExpectations untyped_expectations_; }; // class UntypedFunctionMockerBase @@ -278,14 +278,14 @@ class UntypedOnCallSpecBase { }; // Asserts that the ON_CALL() statement has a certain property. - void AssertSpecProperty(bool property, - const std::string& failure_message) const { + void AssertSpecProperty(bool property, + const std::string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the ON_CALL() statement has a certain property. - void ExpectSpecProperty(bool property, - const std::string& failure_message) const { + void ExpectSpecProperty(bool property, + const std::string& failure_message) const { Expect(property, file_, line_, failure_message); } @@ -311,9 +311,9 @@ class OnCallSpec : public UntypedOnCallSpecBase { : UntypedOnCallSpecBase(a_file, a_line), matchers_(matchers), // By default, extra_matcher_ should match anything. However, - // we cannot initialize it with _ as that causes ambiguity between - // Matcher's copy and move constructor for some argument types. - extra_matcher_(A<const ArgumentTuple&>()) {} + // we cannot initialize it with _ as that causes ambiguity between + // Matcher's copy and move constructor for some argument types. + extra_matcher_(A<const ArgumentTuple&>()) {} // Implements the .With() clause. OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) { @@ -340,7 +340,7 @@ class OnCallSpec : public UntypedOnCallSpecBase { return *this; } - // Returns true if and only if the given arguments match the matchers. + // Returns true if and only if the given arguments match the matchers. bool Matches(const ArgumentTuple& args) const { return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } @@ -398,35 +398,35 @@ class GTEST_API_ Mock { GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies all expectations on the given mock object and clears its - // default actions and expectations. Returns true if and only if the + // default actions and expectations. Returns true if and only if the // verification was successful. static bool VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); - // Returns whether the mock was created as a naggy mock (default) - static bool IsNaggy(void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); - // Returns whether the mock was created as a nice mock - static bool IsNice(void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); - // Returns whether the mock was created as a strict mock - static bool IsStrict(void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); - + // Returns whether the mock was created as a naggy mock (default) + static bool IsNaggy(void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + // Returns whether the mock was created as a nice mock + static bool IsNice(void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + // Returns whether the mock was created as a strict mock + static bool IsStrict(void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + private: friend class internal::UntypedFunctionMockerBase; // Needed for a function mocker to register itself (so that we know // how to clear a mock object). template <typename F> - friend class internal::FunctionMocker; + friend class internal::FunctionMocker; - template <typename MockClass> - friend class internal::NiceMockImpl; - template <typename MockClass> - friend class internal::NaggyMockImpl; - template <typename MockClass> - friend class internal::StrictMockImpl; + template <typename MockClass> + friend class internal::NiceMockImpl; + template <typename MockClass> + friend class internal::NaggyMockImpl; + template <typename MockClass> + friend class internal::StrictMockImpl; // Tells Google Mock to allow uninteresting calls on the given mock // object. @@ -480,7 +480,7 @@ class GTEST_API_ Mock { // Unregisters a mock method; removes the owning mock object from // the registry when the last mock method associated with it has // been unregistered. This is called only in the destructor of - // FunctionMocker. + // FunctionMocker. static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); }; // class Mock @@ -500,15 +500,15 @@ class GTEST_API_ Mock { // - Constness is shallow: a const Expectation object itself cannot // be modified, but the mutable methods of the ExpectationBase // object it references can be called via expectation_base(). - + class GTEST_API_ Expectation { public: // Constructs a null object that doesn't reference any expectation. Expectation(); - Expectation(Expectation&&) = default; - Expectation(const Expectation&) = default; - Expectation& operator=(Expectation&&) = default; - Expectation& operator=(const Expectation&) = default; + Expectation(Expectation&&) = default; + Expectation(const Expectation&) = default; + Expectation& operator=(Expectation&&) = default; + Expectation& operator=(const Expectation&) = default; ~Expectation(); // This single-argument ctor must not be explicit, in order to support the @@ -525,8 +525,8 @@ class GTEST_API_ Expectation { // The compiler-generated copy ctor and operator= work exactly as // intended, so we don't need to define our own. - // Returns true if and only if rhs references the same expectation as this - // object does. + // Returns true if and only if rhs references the same expectation as this + // object does. bool operator==(const Expectation& rhs) const { return expectation_base_ == rhs.expectation_base_; } @@ -540,7 +540,7 @@ class GTEST_API_ Expectation { friend class ::testing::internal::UntypedFunctionMockerBase; template <typename F> - friend class ::testing::internal::FunctionMocker; + friend class ::testing::internal::FunctionMocker; template <typename F> friend class ::testing::internal::TypedExpectation; @@ -556,15 +556,15 @@ class GTEST_API_ Expectation { typedef ::std::set<Expectation, Less> Set; Expectation( - const std::shared_ptr<internal::ExpectationBase>& expectation_base); + const std::shared_ptr<internal::ExpectationBase>& expectation_base); // Returns the expectation this object references. - const std::shared_ptr<internal::ExpectationBase>& expectation_base() const { + const std::shared_ptr<internal::ExpectationBase>& expectation_base() const { return expectation_base_; } - // A shared_ptr that co-owns the expectation this handle references. - std::shared_ptr<internal::ExpectationBase> expectation_base_; + // A shared_ptr that co-owns the expectation this handle references. + std::shared_ptr<internal::ExpectationBase> expectation_base_; }; // A set of expectation handles. Useful in the .After() clause of @@ -608,8 +608,8 @@ class ExpectationSet { // The compiler-generator ctor and operator= works exactly as // intended, so we don't need to define our own. - // Returns true if and only if rhs contains the same set of Expectation - // objects as this does. + // Returns true if and only if rhs contains the same set of Expectation + // objects as this does. bool operator==(const ExpectationSet& rhs) const { return expectations_ == rhs.expectations_; } @@ -646,8 +646,8 @@ class GTEST_API_ Sequence { void AddExpectation(const Expectation& expectation) const; private: - // The last expectation in this sequence. - std::shared_ptr<Expectation> last_expectation_; + // The last expectation in this sequence. + std::shared_ptr<Expectation> last_expectation_; }; // class Sequence // An object of this type causes all EXPECT_CALL() statements @@ -707,7 +707,7 @@ GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; class GTEST_API_ ExpectationBase { public: // source_text is the EXPECT_CALL(...) source that created this Expectation. - ExpectationBase(const char* file, int line, const std::string& source_text); + ExpectationBase(const char* file, int line, const std::string& source_text); virtual ~ExpectationBase(); @@ -755,14 +755,14 @@ class GTEST_API_ ExpectationBase { virtual Expectation GetHandle() = 0; // Asserts that the EXPECT_CALL() statement has the given property. - void AssertSpecProperty(bool property, - const std::string& failure_message) const { + void AssertSpecProperty(bool property, + const std::string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the EXPECT_CALL() statement has the given property. - void ExpectSpecProperty(bool property, - const std::string& failure_message) const { + void ExpectSpecProperty(bool property, + const std::string& failure_message) const { Expect(property, file_, line_, failure_message); } @@ -770,8 +770,8 @@ class GTEST_API_ ExpectationBase { // by the subclasses to implement the .Times() clause. void SpecifyCardinality(const Cardinality& cardinality); - // Returns true if and only if the user specified the cardinality - // explicitly using a .Times(). + // Returns true if and only if the user specified the cardinality + // explicitly using a .Times(). bool cardinality_specified() const { return cardinality_specified_; } // Sets the cardinality of this expectation spec. @@ -787,7 +787,7 @@ class GTEST_API_ ExpectationBase { void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); - // Returns true if and only if this expectation is retired. + // Returns true if and only if this expectation is retired. bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); @@ -801,29 +801,29 @@ class GTEST_API_ ExpectationBase { retired_ = true; } - // Returns true if and only if this expectation is satisfied. + // Returns true if and only if this expectation is satisfied. bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } - // Returns true if and only if this expectation is saturated. + // Returns true if and only if this expectation is saturated. bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } - // Returns true if and only if this expectation is over-saturated. + // Returns true if and only if this expectation is over-saturated. bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } - // Returns true if and only if all pre-requisites of this expectation are - // satisfied. + // Returns true if and only if all pre-requisites of this expectation are + // satisfied. bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); @@ -865,13 +865,13 @@ class GTEST_API_ ExpectationBase { // an EXPECT_CALL() statement finishes. const char* file_; // The file that contains the expectation. int line_; // The line number of the expectation. - const std::string source_text_; // The EXPECT_CALL(...) source text. - // True if and only if the cardinality is specified explicitly. + const std::string source_text_; // The EXPECT_CALL(...) source text. + // True if and only if the cardinality is specified explicitly. bool cardinality_specified_; Cardinality cardinality_; // The cardinality of the expectation. // The immediate pre-requisites (i.e. expectations that must be // satisfied before this expectation can be matched) of this - // expectation. We use std::shared_ptr in the set because we want an + // expectation. We use std::shared_ptr in the set because we want an // Expectation object to be co-owned by its FunctionMocker and its // successors. This allows multiple mock objects to be deleted at // different times. @@ -880,7 +880,7 @@ class GTEST_API_ ExpectationBase { // This group of fields are the current state of the expectation, // and can change as the mock function is called. int call_count_; // How many times this expectation has been invoked. - bool retired_; // True if and only if this expectation has retired. + bool retired_; // True if and only if this expectation has retired. UntypedActions untyped_actions_; bool extra_matcher_specified_; bool repeated_action_specified_; // True if a WillRepeatedly() was specified. @@ -898,19 +898,19 @@ class TypedExpectation : public ExpectationBase { typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; typedef typename Function<F>::Result Result; - TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line, - const std::string& a_source_text, + TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line, + const std::string& a_source_text, const ArgumentMatcherTuple& m) : ExpectationBase(a_file, a_line, a_source_text), owner_(owner), matchers_(m), // By default, extra_matcher_ should match anything. However, - // we cannot initialize it with _ as that causes ambiguity between - // Matcher's copy and move constructor for some argument types. + // we cannot initialize it with _ as that causes ambiguity between + // Matcher's copy and move constructor for some argument types. extra_matcher_(A<const ArgumentTuple&>()), repeated_action_(DoDefault()) {} - ~TypedExpectation() override { + ~TypedExpectation() override { // Check the validity of the action count if it hasn't been done // yet (for example, if the expectation was never used). CheckActionCountIfNotDone(); @@ -1076,7 +1076,7 @@ class TypedExpectation : public ExpectationBase { // If this mock method has an extra matcher (i.e. .With(matcher)), // describes it to the ostream. - void MaybeDescribeExtraMatcherTo(::std::ostream* os) override { + void MaybeDescribeExtraMatcherTo(::std::ostream* os) override { if (extra_matcher_specified_) { *os << " Expected args: "; extra_matcher_.DescribeTo(os); @@ -1086,25 +1086,25 @@ class TypedExpectation : public ExpectationBase { private: template <typename Function> - friend class FunctionMocker; + friend class FunctionMocker; // Returns an Expectation object that references and co-owns this // expectation. - Expectation GetHandle() override { return owner_->GetHandleOf(this); } + Expectation GetHandle() override { return owner_->GetHandleOf(this); } // The following methods will be called only after the EXPECT_CALL() // statement finishes and when the current thread holds // g_gmock_mutex. - // Returns true if and only if this expectation matches the given arguments. + // Returns true if and only if this expectation matches the given arguments. bool Matches(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } - // Returns true if and only if this expectation should handle the given - // arguments. + // Returns true if and only if this expectation should handle the given + // arguments. bool ShouldHandleArguments(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); @@ -1164,9 +1164,9 @@ class TypedExpectation : public ExpectationBase { } // Returns the action that should be taken for the current invocation. - const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker, - const ArgumentTuple& args) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker, + const ArgumentTuple& args) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const int count = call_count(); Assert(count >= 1, __FILE__, __LINE__, @@ -1188,10 +1188,10 @@ class TypedExpectation : public ExpectationBase { Log(kWarning, ss.str(), 1); } - return count <= action_count - ? *static_cast<const Action<F>*>( - untyped_actions_[static_cast<size_t>(count - 1)]) - : repeated_action(); + return count <= action_count + ? *static_cast<const Action<F>*>( + untyped_actions_[static_cast<size_t>(count - 1)]) + : repeated_action(); } // Given the arguments of a mock function call, if the call will @@ -1201,11 +1201,11 @@ class TypedExpectation : public ExpectationBase { // Mock does it to 'why'. This method is not const as it calls // IncrementCallCount(). A return value of NULL means the default // action. - const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker, - const ArgumentTuple& args, - ::std::ostream* what, - ::std::ostream* why) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker, + const ArgumentTuple& args, + ::std::ostream* what, + ::std::ostream* why) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (IsSaturated()) { // We have an excessive call. @@ -1214,7 +1214,7 @@ class TypedExpectation : public ExpectationBase { mocker->DescribeDefaultActionTo(args, what); DescribeCallCountTo(why); - return nullptr; + return nullptr; } IncrementCallCount(); @@ -1231,7 +1231,7 @@ class TypedExpectation : public ExpectationBase { // All the fields below won't change once the EXPECT_CALL() // statement finishes. - FunctionMocker<F>* const owner_; + FunctionMocker<F>* const owner_; ArgumentMatcherTuple matchers_; Matcher<const ArgumentTuple&> extra_matcher_; Action<F> repeated_action_; @@ -1252,7 +1252,7 @@ class TypedExpectation : public ExpectationBase { // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, - const std::string& message); + const std::string& message); template <typename F> class MockSpec { @@ -1263,16 +1263,16 @@ class MockSpec { // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. - MockSpec(internal::FunctionMocker<F>* function_mocker, - const ArgumentMatcherTuple& matchers) - : function_mocker_(function_mocker), matchers_(matchers) {} + MockSpec(internal::FunctionMocker<F>* function_mocker, + const ArgumentMatcherTuple& matchers) + : function_mocker_(function_mocker), matchers_(matchers) {} // Adds a new default action spec to the function mocker and returns // the newly created spec. internal::OnCallSpec<F>& InternalDefaultActionSetAt( const char* file, int line, const char* obj, const char* call) { LogWithLocation(internal::kInfo, file, line, - std::string("ON_CALL(") + obj + ", " + call + ") invoked"); + std::string("ON_CALL(") + obj + ", " + call + ") invoked"); return function_mocker_->AddNewOnCallSpec(file, line, matchers_); } @@ -1280,26 +1280,26 @@ class MockSpec { // the newly created spec. internal::TypedExpectation<F>& InternalExpectedAt( const char* file, int line, const char* obj, const char* call) { - const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + - call + ")"); + const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); return function_mocker_->AddNewExpectation( file, line, source_text, matchers_); } - // This operator overload is used to swallow the superfluous parameter list - // introduced by the ON/EXPECT_CALL macros. See the macro comments for more - // explanation. - MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) { - return *this; - } - + // This operator overload is used to swallow the superfluous parameter list + // introduced by the ON/EXPECT_CALL macros. See the macro comments for more + // explanation. + MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) { + return *this; + } + private: template <typename Function> friend class internal::FunctionMocker; // The function mocker that owns this spec. - internal::FunctionMocker<F>* const function_mocker_; + internal::FunctionMocker<F>* const function_mocker_; // The argument matchers specified in the spec. ArgumentMatcherTuple matchers_; }; // class MockSpec @@ -1318,18 +1318,18 @@ class ReferenceOrValueWrapper { public: // Constructs a wrapper from the given value/reference. explicit ReferenceOrValueWrapper(T value) - : value_(std::move(value)) { + : value_(std::move(value)) { } // Unwraps and returns the underlying value/reference, exactly as // originally passed. The behavior of calling this more than once on // the same object is unspecified. - T Unwrap() { return std::move(value_); } + T Unwrap() { return std::move(value_); } // Provides nondestructive access to the underlying value/reference. // Always returns a const reference (more precisely, - // const std::add_lvalue_reference<T>::type). The behavior of calling this - // after calling Unwrap on the same object is unspecified. + // const std::add_lvalue_reference<T>::type). The behavior of calling this + // after calling Unwrap on the same object is unspecified. const T& Peek() const { return value_; } @@ -1382,7 +1382,7 @@ class ActionResultHolder : public UntypedActionResultHolderBase { } // Prints the held value as an action's result to os. - void PrintAsActionResult(::std::ostream* os) const override { + void PrintAsActionResult(::std::ostream* os) const override { *os << "\n Returns: "; // T may be a reference type, so we don't use UniversalPrint(). UniversalPrinter<T>::Print(result_.Peek(), os); @@ -1392,27 +1392,27 @@ class ActionResultHolder : public UntypedActionResultHolderBase { // result in a new-ed ActionResultHolder. template <typename F> static ActionResultHolder* PerformDefaultAction( - const FunctionMocker<F>* func_mocker, - typename Function<F>::ArgumentTuple&& args, - const std::string& call_description) { - return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction( - std::move(args), call_description))); + const FunctionMocker<F>* func_mocker, + typename Function<F>::ArgumentTuple&& args, + const std::string& call_description) { + return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction( + std::move(args), call_description))); } // Performs the given action and returns the result in a new-ed // ActionResultHolder. template <typename F> - static ActionResultHolder* PerformAction( - const Action<F>& action, typename Function<F>::ArgumentTuple&& args) { - return new ActionResultHolder( - Wrapper(action.Perform(std::move(args)))); + static ActionResultHolder* PerformAction( + const Action<F>& action, typename Function<F>::ArgumentTuple&& args) { + return new ActionResultHolder( + Wrapper(action.Perform(std::move(args)))); } private: typedef ReferenceOrValueWrapper<T> Wrapper; explicit ActionResultHolder(Wrapper result) - : result_(std::move(result)) { + : result_(std::move(result)) { } Wrapper result_; @@ -1426,16 +1426,16 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase { public: void Unwrap() { } - void PrintAsActionResult(::std::ostream* /* os */) const override {} + void PrintAsActionResult(::std::ostream* /* os */) const override {} // Performs the given mock function's default action and returns ownership // of an empty ActionResultHolder*. template <typename F> static ActionResultHolder* PerformDefaultAction( - const FunctionMocker<F>* func_mocker, - typename Function<F>::ArgumentTuple&& args, - const std::string& call_description) { - func_mocker->PerformDefaultAction(std::move(args), call_description); + const FunctionMocker<F>* func_mocker, + typename Function<F>::ArgumentTuple&& args, + const std::string& call_description) { + func_mocker->PerformDefaultAction(std::move(args), call_description); return new ActionResultHolder; } @@ -1443,8 +1443,8 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase { // ActionResultHolder*. template <typename F> static ActionResultHolder* PerformAction( - const Action<F>& action, typename Function<F>::ArgumentTuple&& args) { - action.Perform(std::move(args)); + const Action<F>& action, typename Function<F>::ArgumentTuple&& args) { + action.Perform(std::move(args)); return new ActionResultHolder; } @@ -1454,38 +1454,38 @@ class ActionResultHolder<void> : public UntypedActionResultHolderBase { }; template <typename F> -class FunctionMocker; - -template <typename R, typename... Args> -class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { - using F = R(Args...); - +class FunctionMocker; + +template <typename R, typename... Args> +class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { + using F = R(Args...); + public: - using Result = R; - using ArgumentTuple = std::tuple<Args...>; - using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; - - FunctionMocker() {} - - // There is no generally useful and implementable semantics of - // copying a mock object, so copying a mock is usually a user error. - // Thus we disallow copying function mockers. If the user really - // wants to copy a mock object, they should implement their own copy - // operation, for example: - // - // class MockFoo : public Foo { - // public: - // // Defines a copy constructor explicitly. - // MockFoo(const MockFoo& src) {} - // ... - // }; - FunctionMocker(const FunctionMocker&) = delete; - FunctionMocker& operator=(const FunctionMocker&) = delete; - + using Result = R; + using ArgumentTuple = std::tuple<Args...>; + using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>; + + FunctionMocker() {} + + // There is no generally useful and implementable semantics of + // copying a mock object, so copying a mock is usually a user error. + // Thus we disallow copying function mockers. If the user really + // wants to copy a mock object, they should implement their own copy + // operation, for example: + // + // class MockFoo : public Foo { + // public: + // // Defines a copy constructor explicitly. + // MockFoo(const MockFoo& src) {} + // ... + // }; + FunctionMocker(const FunctionMocker&) = delete; + FunctionMocker& operator=(const FunctionMocker&) = delete; + // The destructor verifies that all expectations on this mock // function have been satisfied. If not, it will report Google Test // non-fatal failures for the violations. - ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { MutexLock l(&g_gmock_mutex); VerifyAndClearExpectationsLocked(); Mock::UnregisterLocked(this); @@ -1505,7 +1505,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { return spec; } - return nullptr; + return nullptr; } // Performs the default action of this mock function on the given @@ -1515,15 +1515,15 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // mutable state of this object, and thus can be called concurrently // without locking. // L = * - Result PerformDefaultAction(ArgumentTuple&& args, - const std::string& call_description) const { + Result PerformDefaultAction(ArgumentTuple&& args, + const std::string& call_description) const { const OnCallSpec<F>* const spec = this->FindOnCallSpec(args); - if (spec != nullptr) { - return spec->GetAction().Perform(std::move(args)); + if (spec != nullptr) { + return spec->GetAction().Perform(std::move(args)); } - const std::string message = - call_description + + const std::string message = + call_description + "\n The mock function has no default action " "set, and its return type has no default value set."; #if GTEST_HAS_EXCEPTIONS @@ -1541,30 +1541,30 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // the error message to describe the call in the case the default // action fails. The caller is responsible for deleting the result. // L = * - UntypedActionResultHolderBase* UntypedPerformDefaultAction( - void* untyped_args, // must point to an ArgumentTuple - const std::string& call_description) const override { - ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args); - return ResultHolder::PerformDefaultAction(this, std::move(*args), - call_description); + UntypedActionResultHolderBase* UntypedPerformDefaultAction( + void* untyped_args, // must point to an ArgumentTuple + const std::string& call_description) const override { + ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args); + return ResultHolder::PerformDefaultAction(this, std::move(*args), + call_description); } // Performs the given action with the given arguments and returns // the action's result. The caller is responsible for deleting the // result. // L = * - UntypedActionResultHolderBase* UntypedPerformAction( - const void* untyped_action, void* untyped_args) const override { + UntypedActionResultHolderBase* UntypedPerformAction( + const void* untyped_action, void* untyped_args) const override { // Make a copy of the action before performing it, in case the // action deletes the mock object (and thus deletes itself). const Action<F> action = *static_cast<const Action<F>*>(untyped_action); - ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args); - return ResultHolder::PerformAction(action, std::move(*args)); + ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args); + return ResultHolder::PerformAction(action, std::move(*args)); } // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): // clears the ON_CALL()s set on this mock function. - void ClearDefaultActionsLocked() override + void ClearDefaultActionsLocked() override GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); @@ -1590,20 +1590,20 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { g_gmock_mutex.Lock(); } - // Returns the result of invoking this mock function with the given - // arguments. This function can be safely called from multiple - // threads concurrently. - Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { - ArgumentTuple tuple(std::forward<Args>(args)...); - std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>( - this->UntypedInvokeWith(static_cast<void*>(&tuple)))); - return holder->Unwrap(); - } - - MockSpec<F> With(Matcher<Args>... m) { - return MockSpec<F>(this, ::std::make_tuple(std::move(m)...)); - } - + // Returns the result of invoking this mock function with the given + // arguments. This function can be safely called from multiple + // threads concurrently. + Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + ArgumentTuple tuple(std::forward<Args>(args)...); + std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>( + this->UntypedInvokeWith(static_cast<void*>(&tuple)))); + return holder->Unwrap(); + } + + MockSpec<F> With(Matcher<Args>... m) { + return MockSpec<F>(this, ::std::make_tuple(std::move(m)...)); + } + protected: template <typename Function> friend class MockSpec; @@ -1622,21 +1622,21 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { } // Adds and returns an expectation spec for this mock function. - TypedExpectation<F>& AddNewExpectation(const char* file, int line, - const std::string& source_text, - const ArgumentMatcherTuple& m) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + TypedExpectation<F>& AddNewExpectation(const char* file, int line, + const std::string& source_text, + const ArgumentMatcherTuple& m) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); TypedExpectation<F>* const expectation = new TypedExpectation<F>(this, file, line, source_text, m); - const std::shared_ptr<ExpectationBase> untyped_expectation(expectation); - // See the definition of untyped_expectations_ for why access to - // it is unprotected here. + const std::shared_ptr<ExpectationBase> untyped_expectation(expectation); + // See the definition of untyped_expectations_ for why access to + // it is unprotected here. untyped_expectations_.push_back(untyped_expectation); // Adds this expectation into the implicit sequence if there is one. Sequence* const implicit_sequence = g_gmock_implicit_sequence.get(); - if (implicit_sequence != nullptr) { + if (implicit_sequence != nullptr) { implicit_sequence->AddExpectation(Expectation(untyped_expectation)); } @@ -1655,9 +1655,9 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { ::std::ostream* os) const { const OnCallSpec<F>* const spec = FindOnCallSpec(args); - if (spec == nullptr) { - *os << (std::is_void<Result>::value ? "returning directly.\n" - : "returning default value.\n"); + if (spec == nullptr) { + *os << (std::is_void<Result>::value ? "returning directly.\n" + : "returning default value.\n"); } else { *os << "taking default action specified at:\n" << FormatFileLocation(spec->file(), spec->line()) << "\n"; @@ -1667,9 +1667,9 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. - void UntypedDescribeUninterestingCall(const void* untyped_args, - ::std::ostream* os) const override - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + void UntypedDescribeUninterestingCall(const void* untyped_args, + ::std::ostream* os) const override + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); *os << "Uninteresting mock function call - "; @@ -1694,17 +1694,17 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // section. The reason is that we have no control on what the // action does (it can invoke an arbitrary user function or even a // mock function) and excessive locking could cause a dead lock. - const ExpectationBase* UntypedFindMatchingExpectation( - const void* untyped_args, const void** untyped_action, bool* is_excessive, - ::std::ostream* what, ::std::ostream* why) override - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + const ExpectationBase* UntypedFindMatchingExpectation( + const void* untyped_args, const void** untyped_action, bool* is_excessive, + ::std::ostream* what, ::std::ostream* why) override + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); MutexLock l(&g_gmock_mutex); TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args); - if (exp == nullptr) { // A match wasn't found. + if (exp == nullptr) { // A match wasn't found. this->FormatUnexpectedCallMessageLocked(args, what, why); - return nullptr; + return nullptr; } // This line must be done before calling GetActionForArguments(), @@ -1712,15 +1712,15 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { // its saturation status. *is_excessive = exp->IsSaturated(); const Action<F>* action = exp->GetActionForArguments(this, args, what, why); - if (action != nullptr && action->IsDoDefault()) - action = nullptr; // Normalize "do default" to NULL. + if (action != nullptr && action->IsDoDefault()) + action = nullptr; // Normalize "do default" to NULL. *untyped_action = action; return exp; } // Prints the given function arguments to the ostream. - void UntypedPrintArgs(const void* untyped_args, - ::std::ostream* os) const override { + void UntypedPrintArgs(const void* untyped_args, + ::std::ostream* os) const override { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); UniversalPrint(args, os); @@ -1732,8 +1732,8 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - // See the definition of untyped_expectations_ for why access to - // it is unprotected here. + // See the definition of untyped_expectations_ for why access to + // it is unprotected here. for (typename UntypedExpectations::const_reverse_iterator it = untyped_expectations_.rbegin(); it != untyped_expectations_.rend(); ++it) { @@ -1743,7 +1743,7 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { return exp; } } - return nullptr; + return nullptr; } // Returns a message that the arguments don't match any expectation. @@ -1765,12 +1765,12 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { ::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - const size_t count = untyped_expectations_.size(); + const size_t count = untyped_expectations_.size(); *why << "Google Mock tried the following " << count << " " << (count == 1 ? "expectation, but it didn't match" : "expectations, but none matched") << ":\n"; - for (size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { TypedExpectation<F>* const expectation = static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get()); *why << "\n"; @@ -1783,152 +1783,152 @@ class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase { expectation->DescribeCallCountTo(why); } } -}; // class FunctionMocker - -// Reports an uninteresting call (whose description is in msg) in the -// manner specified by 'reaction'. -void ReportUninterestingCall(CallReaction reaction, const std::string& msg); - -} // namespace internal - -namespace internal { - -template <typename F> -class MockFunction; - -template <typename R, typename... Args> -class MockFunction<R(Args...)> { - public: - MockFunction(const MockFunction&) = delete; - MockFunction& operator=(const MockFunction&) = delete; - - std::function<R(Args...)> AsStdFunction() { - return [this](Args... args) -> R { - return this->Call(std::forward<Args>(args)...); - }; - } - - // Implementation detail: the expansion of the MOCK_METHOD macro. - R Call(Args... args) { - mock_.SetOwnerAndName(this, "Call"); - return mock_.Invoke(std::forward<Args>(args)...); - } - - MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) { - mock_.RegisterOwner(this); - return mock_.With(std::move(m)...); - } - - MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) { - return this->gmock_Call(::testing::A<Args>()...); - } - - protected: - MockFunction() = default; - ~MockFunction() = default; - - private: - FunctionMocker<R(Args...)> mock_; -}; - -/* -The SignatureOf<F> struct is a meta-function returning function signature -corresponding to the provided F argument. - -It makes use of MockFunction easier by allowing it to accept more F arguments -than just function signatures. - -Specializations provided here cover a signature type itself and any template -that can be parameterized with a signature, including std::function and -boost::function. -*/ - -template <typename F, typename = void> -struct SignatureOf; - -template <typename R, typename... Args> -struct SignatureOf<R(Args...)> { - using type = R(Args...); -}; - -template <template <typename> class C, typename F> -struct SignatureOf<C<F>, - typename std::enable_if<std::is_function<F>::value>::type> - : SignatureOf<F> {}; - -template <typename F> -using SignatureOfT = typename SignatureOf<F>::type; - -} // namespace internal - -// A MockFunction<F> type has one mock method whose type is -// internal::SignatureOfT<F>. It is useful when you just want your -// test code to emit some messages and have Google Mock verify the -// right messages are sent (and perhaps at the right times). For -// example, if you are exercising code: -// -// Foo(1); -// Foo(2); -// Foo(3); -// -// and want to verify that Foo(1) and Foo(3) both invoke -// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write: -// -// TEST(FooTest, InvokesBarCorrectly) { -// MyMock mock; -// MockFunction<void(string check_point_name)> check; -// { -// InSequence s; -// -// EXPECT_CALL(mock, Bar("a")); -// EXPECT_CALL(check, Call("1")); -// EXPECT_CALL(check, Call("2")); -// EXPECT_CALL(mock, Bar("a")); -// } -// Foo(1); -// check.Call("1"); -// Foo(2); -// check.Call("2"); -// Foo(3); -// } -// -// The expectation spec says that the first Bar("a") must happen -// before check point "1", the second Bar("a") must happen after check -// point "2", and nothing should happen between the two check -// points. The explicit check points make it easy to tell which -// Bar("a") is called by which call to Foo(). -// -// MockFunction<F> can also be used to exercise code that accepts -// std::function<internal::SignatureOfT<F>> callbacks. To do so, use -// AsStdFunction() method to create std::function proxy forwarding to -// original object's Call. Example: -// -// TEST(FooTest, RunsCallbackWithBarArgument) { -// MockFunction<int(string)> callback; -// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1)); -// Foo(callback.AsStdFunction()); -// } -// -// The internal::SignatureOfT<F> indirection allows to use other types -// than just function signature type. This is typically useful when -// providing a mock for a predefined std::function type. Example: -// -// using FilterPredicate = std::function<bool(string)>; -// void MyFilterAlgorithm(FilterPredicate predicate); -// -// TEST(FooTest, FilterPredicateAlwaysAccepts) { -// MockFunction<FilterPredicate> predicateMock; -// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true)); -// MyFilterAlgorithm(predicateMock.AsStdFunction()); -// } -template <typename F> -class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> { - using Base = internal::MockFunction<internal::SignatureOfT<F>>; - - public: - using Base::Base; -}; - +}; // class FunctionMocker + +// Reports an uninteresting call (whose description is in msg) in the +// manner specified by 'reaction'. +void ReportUninterestingCall(CallReaction reaction, const std::string& msg); + +} // namespace internal + +namespace internal { + +template <typename F> +class MockFunction; + +template <typename R, typename... Args> +class MockFunction<R(Args...)> { + public: + MockFunction(const MockFunction&) = delete; + MockFunction& operator=(const MockFunction&) = delete; + + std::function<R(Args...)> AsStdFunction() { + return [this](Args... args) -> R { + return this->Call(std::forward<Args>(args)...); + }; + } + + // Implementation detail: the expansion of the MOCK_METHOD macro. + R Call(Args... args) { + mock_.SetOwnerAndName(this, "Call"); + return mock_.Invoke(std::forward<Args>(args)...); + } + + MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) { + mock_.RegisterOwner(this); + return mock_.With(std::move(m)...); + } + + MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) { + return this->gmock_Call(::testing::A<Args>()...); + } + + protected: + MockFunction() = default; + ~MockFunction() = default; + + private: + FunctionMocker<R(Args...)> mock_; +}; + +/* +The SignatureOf<F> struct is a meta-function returning function signature +corresponding to the provided F argument. + +It makes use of MockFunction easier by allowing it to accept more F arguments +than just function signatures. + +Specializations provided here cover a signature type itself and any template +that can be parameterized with a signature, including std::function and +boost::function. +*/ + +template <typename F, typename = void> +struct SignatureOf; + +template <typename R, typename... Args> +struct SignatureOf<R(Args...)> { + using type = R(Args...); +}; + +template <template <typename> class C, typename F> +struct SignatureOf<C<F>, + typename std::enable_if<std::is_function<F>::value>::type> + : SignatureOf<F> {}; + +template <typename F> +using SignatureOfT = typename SignatureOf<F>::type; + +} // namespace internal + +// A MockFunction<F> type has one mock method whose type is +// internal::SignatureOfT<F>. It is useful when you just want your +// test code to emit some messages and have Google Mock verify the +// right messages are sent (and perhaps at the right times). For +// example, if you are exercising code: +// +// Foo(1); +// Foo(2); +// Foo(3); +// +// and want to verify that Foo(1) and Foo(3) both invoke +// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write: +// +// TEST(FooTest, InvokesBarCorrectly) { +// MyMock mock; +// MockFunction<void(string check_point_name)> check; +// { +// InSequence s; +// +// EXPECT_CALL(mock, Bar("a")); +// EXPECT_CALL(check, Call("1")); +// EXPECT_CALL(check, Call("2")); +// EXPECT_CALL(mock, Bar("a")); +// } +// Foo(1); +// check.Call("1"); +// Foo(2); +// check.Call("2"); +// Foo(3); +// } +// +// The expectation spec says that the first Bar("a") must happen +// before check point "1", the second Bar("a") must happen after check +// point "2", and nothing should happen between the two check +// points. The explicit check points make it easy to tell which +// Bar("a") is called by which call to Foo(). +// +// MockFunction<F> can also be used to exercise code that accepts +// std::function<internal::SignatureOfT<F>> callbacks. To do so, use +// AsStdFunction() method to create std::function proxy forwarding to +// original object's Call. Example: +// +// TEST(FooTest, RunsCallbackWithBarArgument) { +// MockFunction<int(string)> callback; +// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1)); +// Foo(callback.AsStdFunction()); +// } +// +// The internal::SignatureOfT<F> indirection allows to use other types +// than just function signature type. This is typically useful when +// providing a mock for a predefined std::function type. Example: +// +// using FilterPredicate = std::function<bool(string)>; +// void MyFilterAlgorithm(FilterPredicate predicate); +// +// TEST(FooTest, FilterPredicateAlwaysAccepts) { +// MockFunction<FilterPredicate> predicateMock; +// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true)); +// MyFilterAlgorithm(predicateMock.AsStdFunction()); +// } +template <typename F> +class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> { + using Base = internal::MockFunction<internal::SignatureOfT<F>>; + + public: + using Base::Base; +}; + // The style guide prohibits "using" statements in a namespace scope // inside a header file. However, the MockSpec class template is // meant to be defined in the ::testing namespace. The following line @@ -1960,79 +1960,79 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT } // namespace testing -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is -// required to avoid compile errors when the name of the method used in call is -// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro -// tests in internal/gmock-spec-builders_test.cc for more details. -// -// This macro supports statements both with and without parameter matchers. If -// the parameter list is omitted, gMock will accept any parameters, which allows -// tests to be written that don't need to encode the number of method -// parameter. This technique may only be used for non-overloaded methods. -// -// // These are the same: -// ON_CALL(mock, NoArgsMethod()).WillByDefault(...); -// ON_CALL(mock, NoArgsMethod).WillByDefault(...); -// -// // As are these: -// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...); -// ON_CALL(mock, TwoArgsMethod).WillByDefault(...); -// -// // Can also specify args if you want, of course: -// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...); -// -// // Overloads work as long as you specify parameters: -// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...); -// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...); -// -// // Oops! Which overload did you want? -// ON_CALL(mock, OverloadedMethod).WillByDefault(...); -// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous -// -// How this works: The mock class uses two overloads of the gmock_Method -// expectation setter method plus an operator() overload on the MockSpec object. -// In the matcher list form, the macro expands to: -// -// // This statement: -// ON_CALL(mock, TwoArgsMethod(_, 45))... -// -// // ...expands to: -// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)... -// |-------------v---------------||------------v-------------| -// invokes first overload swallowed by operator() -// -// // ...which is essentially: -// mock.gmock_TwoArgsMethod(_, 45)... -// -// Whereas the form without a matcher list: -// -// // This statement: -// ON_CALL(mock, TwoArgsMethod)... -// -// // ...expands to: -// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)... -// |-----------------------v--------------------------| -// invokes second overload -// -// // ...which is essentially: -// mock.gmock_TwoArgsMethod(_, _)... -// -// The WithoutMatchers() argument is used to disambiguate overloads and to -// block the caller from accidentally invoking the second overload directly. The -// second argument is an internal type derived from the method signature. The -// failure to disambiguate two overloads of this method in the ON_CALL statement -// is how we block callers from setting expectations on overloaded methods. -#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \ - ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \ - nullptr) \ - .Setter(__FILE__, __LINE__, #mock_expr, #call) - -#define ON_CALL(obj, call) \ - GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call) - -#define EXPECT_CALL(obj, call) \ - GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call) - -#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 + +// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is +// required to avoid compile errors when the name of the method used in call is +// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro +// tests in internal/gmock-spec-builders_test.cc for more details. +// +// This macro supports statements both with and without parameter matchers. If +// the parameter list is omitted, gMock will accept any parameters, which allows +// tests to be written that don't need to encode the number of method +// parameter. This technique may only be used for non-overloaded methods. +// +// // These are the same: +// ON_CALL(mock, NoArgsMethod()).WillByDefault(...); +// ON_CALL(mock, NoArgsMethod).WillByDefault(...); +// +// // As are these: +// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...); +// ON_CALL(mock, TwoArgsMethod).WillByDefault(...); +// +// // Can also specify args if you want, of course: +// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...); +// +// // Overloads work as long as you specify parameters: +// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...); +// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...); +// +// // Oops! Which overload did you want? +// ON_CALL(mock, OverloadedMethod).WillByDefault(...); +// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous +// +// How this works: The mock class uses two overloads of the gmock_Method +// expectation setter method plus an operator() overload on the MockSpec object. +// In the matcher list form, the macro expands to: +// +// // This statement: +// ON_CALL(mock, TwoArgsMethod(_, 45))... +// +// // ...expands to: +// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)... +// |-------------v---------------||------------v-------------| +// invokes first overload swallowed by operator() +// +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, 45)... +// +// Whereas the form without a matcher list: +// +// // This statement: +// ON_CALL(mock, TwoArgsMethod)... +// +// // ...expands to: +// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)... +// |-----------------------v--------------------------| +// invokes second overload +// +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, _)... +// +// The WithoutMatchers() argument is used to disambiguate overloads and to +// block the caller from accidentally invoking the second overload directly. The +// second argument is an internal type derived from the method signature. The +// failure to disambiguate two overloads of this method in the ON_CALL statement +// is how we block callers from setting expectations on overloaded methods. +#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \ + ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \ + nullptr) \ + .Setter(__FILE__, __LINE__, #mock_expr, #call) + +#define ON_CALL(obj, call) \ + GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call) + +#define EXPECT_CALL(obj, call) \ + GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call) + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ |