Path: blob/main/contrib/googletest/googlemock/include/gmock/gmock-spec-builders.h
48375 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// This file implements the ON_CALL() and EXPECT_CALL() macros.32//33// A user can use the ON_CALL() macro to specify the default action of34// a mock method. The syntax is:35//36// ON_CALL(mock_object, Method(argument-matchers))37// .With(multi-argument-matcher)38// .WillByDefault(action);39//40// where the .With() clause is optional.41//42// A user can use the EXPECT_CALL() macro to specify an expectation on43// a mock method. The syntax is:44//45// EXPECT_CALL(mock_object, Method(argument-matchers))46// .With(multi-argument-matchers)47// .Times(cardinality)48// .InSequence(sequences)49// .After(expectations)50// .WillOnce(action)51// .WillRepeatedly(action)52// .RetiresOnSaturation();53//54// where all clauses are optional, and .InSequence()/.After()/55// .WillOnce() can appear any number of times.5657// IWYU pragma: private, include "gmock/gmock.h"58// IWYU pragma: friend gmock/.*5960#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_61#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_6263#include <cstdint>64#include <functional>65#include <map>66#include <memory>67#include <ostream>68#include <set>69#include <sstream>70#include <string>71#include <type_traits>72#include <utility>73#include <vector>7475#include "gmock/gmock-actions.h"76#include "gmock/gmock-cardinalities.h"77#include "gmock/gmock-matchers.h"78#include "gmock/internal/gmock-internal-utils.h"79#include "gmock/internal/gmock-port.h"80#include "gtest/gtest.h"8182#if GTEST_HAS_EXCEPTIONS83#include <stdexcept> // NOLINT84#endif8586GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \87/* class A needs to have dll-interface to be used by clients of class B */)8889namespace testing {9091// An abstract handle of an expectation.92class Expectation;9394// A set of expectation handles.95class ExpectationSet;9697// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION98// and MUST NOT BE USED IN USER CODE!!!99namespace internal {100101// Implements a mock function.102template <typename F>103class FunctionMocker;104105// Base class for expectations.106class ExpectationBase;107108// Implements an expectation.109template <typename F>110class TypedExpectation;111112// Helper class for testing the Expectation class template.113class ExpectationTester;114115// Helper classes for implementing NiceMock, StrictMock, and NaggyMock.116template <typename MockClass>117class NiceMockImpl;118template <typename MockClass>119class StrictMockImpl;120template <typename MockClass>121class NaggyMockImpl;122123// Protects the mock object registry (in class Mock), all function124// mockers, and all expectations.125//126// The reason we don't use more fine-grained protection is: when a127// mock function Foo() is called, it needs to consult its expectations128// to see which one should be picked. If another thread is allowed to129// call a mock function (either Foo() or a different one) at the same130// time, it could affect the "retired" attributes of Foo()'s131// expectations when InSequence() is used, and thus affect which132// expectation gets picked. Therefore, we sequence all mock function133// calls to ensure the integrity of the mock objects' states.134GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);135136// Abstract base class of FunctionMocker. This is the137// type-agnostic part of the function mocker interface. Its pure138// virtual methods are implemented by FunctionMocker.139class GTEST_API_ UntypedFunctionMockerBase {140public:141UntypedFunctionMockerBase();142virtual ~UntypedFunctionMockerBase();143144// Verifies that all expectations on this mock function have been145// satisfied. Reports one or more Google Test non-fatal failures146// and returns false if not.147bool VerifyAndClearExpectationsLocked()148GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);149150// Clears the ON_CALL()s set on this mock function.151virtual void ClearDefaultActionsLocked()152GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;153154// In all of the following Untyped* functions, it's the caller's155// responsibility to guarantee the correctness of the arguments'156// types.157158// Writes a message that the call is uninteresting (i.e. neither159// explicitly expected nor explicitly unexpected) to the given160// ostream.161virtual void UntypedDescribeUninterestingCall(const void* untyped_args,162::std::ostream* os) const163GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;164165// Returns the expectation that matches the given function arguments166// (or NULL is there's no match); when a match is found,167// untyped_action is set to point to the action that should be168// performed (or NULL if the action is "do default"), and169// is_excessive is modified to indicate whether the call exceeds the170// expected number.171virtual const ExpectationBase* UntypedFindMatchingExpectation(172const void* untyped_args, const void** untyped_action, bool* is_excessive,173::std::ostream* what, ::std::ostream* why)174GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;175176// Prints the given function arguments to the ostream.177virtual void UntypedPrintArgs(const void* untyped_args,178::std::ostream* os) const = 0;179180// Sets the mock object this mock method belongs to, and registers181// this information in the global mock registry. Will be called182// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock183// method.184void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);185186// Sets the mock object this mock method belongs to, and sets the187// name of the mock function. Will be called upon each invocation188// of this mock function.189void SetOwnerAndName(const void* mock_obj, const char* name)190GTEST_LOCK_EXCLUDED_(g_gmock_mutex);191192// Returns the mock object this mock method belongs to. Must be193// called after RegisterOwner() or SetOwnerAndName() has been194// called.195const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);196197// Returns the name of this mock method. Must be called after198// SetOwnerAndName() has been called.199const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);200201protected:202typedef std::vector<const void*> UntypedOnCallSpecs;203204using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;205206struct UninterestingCallCleanupHandler;207struct FailureCleanupHandler;208209// Returns an Expectation object that references and co-owns exp,210// which must be an expectation on this mock function.211Expectation GetHandleOf(ExpectationBase* exp);212213// Address of the mock object this mock method belongs to. Only214// valid after this mock method has been called or215// ON_CALL/EXPECT_CALL has been invoked on it.216const void* mock_obj_; // Protected by g_gmock_mutex.217218// Name of the function being mocked. Only valid after this mock219// method has been called.220const char* name_; // Protected by g_gmock_mutex.221222// All default action specs for this function mocker.223UntypedOnCallSpecs untyped_on_call_specs_;224225// All expectations for this function mocker.226//227// It's undefined behavior to interleave expectations (EXPECT_CALLs228// or ON_CALLs) and mock function calls. Also, the order of229// expectations is important. Therefore it's a logic race condition230// to read/write untyped_expectations_ concurrently. In order for231// tools like tsan to catch concurrent read/write accesses to232// untyped_expectations, we deliberately leave accesses to it233// unprotected.234UntypedExpectations untyped_expectations_;235}; // class UntypedFunctionMockerBase236237// Untyped base class for OnCallSpec<F>.238class UntypedOnCallSpecBase {239public:240// The arguments are the location of the ON_CALL() statement.241UntypedOnCallSpecBase(const char* a_file, int a_line)242: file_(a_file), line_(a_line), last_clause_(kNone) {}243244// Where in the source file was the default action spec defined?245const char* file() const { return file_; }246int line() const { return line_; }247248protected:249// Gives each clause in the ON_CALL() statement a name.250enum Clause {251// Do not change the order of the enum members! The run-time252// syntax checking relies on it.253kNone,254kWith,255kWillByDefault256};257258// Asserts that the ON_CALL() statement has a certain property.259void AssertSpecProperty(bool property,260const std::string& failure_message) const {261Assert(property, file_, line_, failure_message);262}263264// Expects that the ON_CALL() statement has a certain property.265void ExpectSpecProperty(bool property,266const std::string& failure_message) const {267Expect(property, file_, line_, failure_message);268}269270const char* file_;271int line_;272273// The last clause in the ON_CALL() statement as seen so far.274// Initially kNone and changes as the statement is parsed.275Clause last_clause_;276}; // class UntypedOnCallSpecBase277278// This template class implements an ON_CALL spec.279template <typename F>280class OnCallSpec : public UntypedOnCallSpecBase {281public:282typedef typename Function<F>::ArgumentTuple ArgumentTuple;283typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;284285// Constructs an OnCallSpec object from the information inside286// the parenthesis of an ON_CALL() statement.287OnCallSpec(const char* a_file, int a_line,288const ArgumentMatcherTuple& matchers)289: UntypedOnCallSpecBase(a_file, a_line),290matchers_(matchers),291// By default, extra_matcher_ should match anything. However,292// we cannot initialize it with _ as that causes ambiguity between293// Matcher's copy and move constructor for some argument types.294extra_matcher_(A<const ArgumentTuple&>()) {}295296// Implements the .With() clause.297OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {298// Makes sure this is called at most once.299ExpectSpecProperty(last_clause_ < kWith,300".With() cannot appear "301"more than once in an ON_CALL().");302last_clause_ = kWith;303304extra_matcher_ = m;305return *this;306}307308// Implements the .WillByDefault() clause.309OnCallSpec& WillByDefault(const Action<F>& action) {310ExpectSpecProperty(last_clause_ < kWillByDefault,311".WillByDefault() must appear "312"exactly once in an ON_CALL().");313last_clause_ = kWillByDefault;314315ExpectSpecProperty(!action.IsDoDefault(),316"DoDefault() cannot be used in ON_CALL().");317action_ = action;318return *this;319}320321// Returns true if and only if the given arguments match the matchers.322bool Matches(const ArgumentTuple& args) const {323return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);324}325326// Returns the action specified by the user.327const Action<F>& GetAction() const {328AssertSpecProperty(last_clause_ == kWillByDefault,329".WillByDefault() must appear exactly "330"once in an ON_CALL().");331return action_;332}333334private:335// The information in statement336//337// ON_CALL(mock_object, Method(matchers))338// .With(multi-argument-matcher)339// .WillByDefault(action);340//341// is recorded in the data members like this:342//343// source file that contains the statement => file_344// line number of the statement => line_345// matchers => matchers_346// multi-argument-matcher => extra_matcher_347// action => action_348ArgumentMatcherTuple matchers_;349Matcher<const ArgumentTuple&> extra_matcher_;350Action<F> action_;351}; // class OnCallSpec352353// Possible reactions on uninteresting calls.354enum CallReaction {355kAllow,356kWarn,357kFail,358};359360} // namespace internal361362// Utilities for manipulating mock objects.363class GTEST_API_ Mock {364public:365// The following public methods can be called concurrently.366367// Tells Google Mock to ignore mock_obj when checking for leaked368// mock objects.369static void AllowLeak(const void* mock_obj)370GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);371372// Verifies and clears all expectations on the given mock object.373// If the expectations aren't satisfied, generates one or more374// Google Test non-fatal failures and returns false.375static bool VerifyAndClearExpectations(void* mock_obj)376GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);377378// Verifies all expectations on the given mock object and clears its379// default actions and expectations. Returns true if and only if the380// verification was successful.381static bool VerifyAndClear(void* mock_obj)382GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);383384// Returns whether the mock was created as a naggy mock (default)385static bool IsNaggy(void* mock_obj)386GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);387// Returns whether the mock was created as a nice mock388static bool IsNice(void* mock_obj)389GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);390// Returns whether the mock was created as a strict mock391static bool IsStrict(void* mock_obj)392GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);393394private:395friend class internal::UntypedFunctionMockerBase;396397// Needed for a function mocker to register itself (so that we know398// how to clear a mock object).399template <typename F>400friend class internal::FunctionMocker;401402template <typename MockClass>403friend class internal::NiceMockImpl;404template <typename MockClass>405friend class internal::NaggyMockImpl;406template <typename MockClass>407friend class internal::StrictMockImpl;408409// Tells Google Mock to allow uninteresting calls on the given mock410// object.411static void AllowUninterestingCalls(uintptr_t mock_obj)412GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);413414// Tells Google Mock to warn the user about uninteresting calls on415// the given mock object.416static void WarnUninterestingCalls(uintptr_t mock_obj)417GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);418419// Tells Google Mock to fail uninteresting calls on the given mock420// object.421static void FailUninterestingCalls(uintptr_t mock_obj)422GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);423424// Tells Google Mock the given mock object is being destroyed and425// its entry in the call-reaction table should be removed.426static void UnregisterCallReaction(uintptr_t mock_obj)427GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);428429// Returns the reaction Google Mock will have on uninteresting calls430// made on the given mock object.431static internal::CallReaction GetReactionOnUninterestingCalls(432const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);433434// Verifies that all expectations on the given mock object have been435// satisfied. Reports one or more Google Test non-fatal failures436// and returns false if not.437static bool VerifyAndClearExpectationsLocked(void* mock_obj)438GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);439440// Clears all ON_CALL()s set on the given mock object.441static void ClearDefaultActionsLocked(void* mock_obj)442GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);443444// Registers a mock object and a mock method it owns.445static void Register(const void* mock_obj,446internal::UntypedFunctionMockerBase* mocker)447GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);448449// Tells Google Mock where in the source code mock_obj is used in an450// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this451// information helps the user identify which object it is.452static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,453const char* file, int line)454GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);455456// Unregisters a mock method; removes the owning mock object from457// the registry when the last mock method associated with it has458// been unregistered. This is called only in the destructor of459// FunctionMocker.460static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)461GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);462}; // class Mock463464// An abstract handle of an expectation. Useful in the .After()465// clause of EXPECT_CALL() for setting the (partial) order of466// expectations. The syntax:467//468// Expectation e1 = EXPECT_CALL(...)...;469// EXPECT_CALL(...).After(e1)...;470//471// sets two expectations where the latter can only be matched after472// the former has been satisfied.473//474// Notes:475// - This class is copyable and has value semantics.476// - Constness is shallow: a const Expectation object itself cannot477// be modified, but the mutable methods of the ExpectationBase478// object it references can be called via expectation_base().479480class GTEST_API_ Expectation {481public:482// Constructs a null object that doesn't reference any expectation.483Expectation();484Expectation(Expectation&&) = default;485Expectation(const Expectation&) = default;486Expectation& operator=(Expectation&&) = default;487Expectation& operator=(const Expectation&) = default;488~Expectation();489490// This single-argument ctor must not be explicit, in order to support the491// Expectation e = EXPECT_CALL(...);492// syntax.493//494// A TypedExpectation object stores its pre-requisites as495// Expectation objects, and needs to call the non-const Retire()496// method on the ExpectationBase objects they reference. Therefore497// Expectation must receive a *non-const* reference to the498// ExpectationBase object.499Expectation(internal::ExpectationBase& exp); // NOLINT500501// The compiler-generated copy ctor and operator= work exactly as502// intended, so we don't need to define our own.503504// Returns true if and only if rhs references the same expectation as this505// object does.506bool operator==(const Expectation& rhs) const {507return expectation_base_ == rhs.expectation_base_;508}509510bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }511512private:513friend class ExpectationSet;514friend class Sequence;515friend class ::testing::internal::ExpectationBase;516friend class ::testing::internal::UntypedFunctionMockerBase;517518template <typename F>519friend class ::testing::internal::FunctionMocker;520521template <typename F>522friend class ::testing::internal::TypedExpectation;523524// This comparator is needed for putting Expectation objects into a set.525class Less {526public:527bool operator()(const Expectation& lhs, const Expectation& rhs) const {528return lhs.expectation_base_.get() < rhs.expectation_base_.get();529}530};531532typedef ::std::set<Expectation, Less> Set;533534Expectation(535const std::shared_ptr<internal::ExpectationBase>& expectation_base);536537// Returns the expectation this object references.538const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {539return expectation_base_;540}541542// A shared_ptr that co-owns the expectation this handle references.543std::shared_ptr<internal::ExpectationBase> expectation_base_;544};545546// A set of expectation handles. Useful in the .After() clause of547// EXPECT_CALL() for setting the (partial) order of expectations. The548// syntax:549//550// ExpectationSet es;551// es += EXPECT_CALL(...)...;552// es += EXPECT_CALL(...)...;553// EXPECT_CALL(...).After(es)...;554//555// sets three expectations where the last one can only be matched556// after the first two have both been satisfied.557//558// This class is copyable and has value semantics.559class ExpectationSet {560public:561// A bidirectional iterator that can read a const element in the set.562typedef Expectation::Set::const_iterator const_iterator;563564// An object stored in the set. This is an alias of Expectation.565typedef Expectation::Set::value_type value_type;566567// Constructs an empty set.568ExpectationSet() = default;569570// This single-argument ctor must not be explicit, in order to support the571// ExpectationSet es = EXPECT_CALL(...);572// syntax.573ExpectationSet(internal::ExpectationBase& exp) { // NOLINT574*this += Expectation(exp);575}576577// This single-argument ctor implements implicit conversion from578// Expectation and thus must not be explicit. This allows either an579// Expectation or an ExpectationSet to be used in .After().580ExpectationSet(const Expectation& e) { // NOLINT581*this += e;582}583584// The compiler-generator ctor and operator= works exactly as585// intended, so we don't need to define our own.586587// Returns true if and only if rhs contains the same set of Expectation588// objects as this does.589bool operator==(const ExpectationSet& rhs) const {590return expectations_ == rhs.expectations_;591}592593bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }594595// Implements the syntax596// expectation_set += EXPECT_CALL(...);597ExpectationSet& operator+=(const Expectation& e) {598expectations_.insert(e);599return *this;600}601602int size() const { return static_cast<int>(expectations_.size()); }603604const_iterator begin() const { return expectations_.begin(); }605const_iterator end() const { return expectations_.end(); }606607private:608Expectation::Set expectations_;609};610611// Sequence objects are used by a user to specify the relative order612// in which the expectations should match. They are copyable (we rely613// on the compiler-defined copy constructor and assignment operator).614class GTEST_API_ Sequence {615public:616// Constructs an empty sequence.617Sequence() : last_expectation_(new Expectation) {}618619// Adds an expectation to this sequence. The caller must ensure620// that no other thread is accessing this Sequence object.621void AddExpectation(const Expectation& expectation) const;622623private:624// The last expectation in this sequence.625std::shared_ptr<Expectation> last_expectation_;626}; // class Sequence627628// An object of this type causes all EXPECT_CALL() statements629// encountered in its scope to be put in an anonymous sequence. The630// work is done in the constructor and destructor. You should only631// create an InSequence object on the stack.632//633// The sole purpose for this class is to support easy definition of634// sequential expectations, e.g.635//636// {637// InSequence dummy; // The name of the object doesn't matter.638//639// // The following expectations must match in the order they appear.640// EXPECT_CALL(a, Bar())...;641// EXPECT_CALL(a, Baz())...;642// ...643// EXPECT_CALL(b, Xyz())...;644// }645//646// You can create InSequence objects in multiple threads, as long as647// they are used to affect different mock objects. The idea is that648// each thread can create and set up its own mocks as if it's the only649// thread. However, for clarity of your tests we recommend you to set650// up mocks in the main thread unless you have a good reason not to do651// so.652class GTEST_API_ InSequence {653public:654InSequence();655~InSequence();656657private:658bool sequence_created_;659660InSequence(const InSequence&) = delete;661InSequence& operator=(const InSequence&) = delete;662};663664namespace internal {665666// Points to the implicit sequence introduced by a living InSequence667// object (if any) in the current thread or NULL.668GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;669670// Base class for implementing expectations.671//672// There are two reasons for having a type-agnostic base class for673// Expectation:674//675// 1. We need to store collections of expectations of different676// types (e.g. all pre-requisites of a particular expectation, all677// expectations in a sequence). Therefore these expectation objects678// must share a common base class.679//680// 2. We can avoid binary code bloat by moving methods not depending681// on the template argument of Expectation to the base class.682//683// This class is internal and mustn't be used by user code directly.684class GTEST_API_ ExpectationBase {685public:686// source_text is the EXPECT_CALL(...) source that created this Expectation.687ExpectationBase(const char* file, int line, const std::string& source_text);688689virtual ~ExpectationBase();690691// Where in the source file was the expectation spec defined?692const char* file() const { return file_; }693int line() const { return line_; }694const char* source_text() const { return source_text_.c_str(); }695// Returns the cardinality specified in the expectation spec.696const Cardinality& cardinality() const { return cardinality_; }697698// Describes the source file location of this expectation.699void DescribeLocationTo(::std::ostream* os) const {700*os << FormatFileLocation(file(), line()) << " ";701}702703// Describes how many times a function call matching this704// expectation has occurred.705void DescribeCallCountTo(::std::ostream* os) const706GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);707708// If this mock method has an extra matcher (i.e. .With(matcher)),709// describes it to the ostream.710virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;711712// Do not rely on this for correctness.713// This is only for making human-readable test output easier to understand.714void UntypedDescription(std::string description) {715description_ = std::move(description);716}717718protected:719friend class ::testing::Expectation;720friend class UntypedFunctionMockerBase;721722enum Clause {723// Don't change the order of the enum members!724kNone,725kWith,726kTimes,727kInSequence,728kAfter,729kWillOnce,730kWillRepeatedly,731kRetiresOnSaturation732};733734typedef std::vector<const void*> UntypedActions;735736// Returns an Expectation object that references and co-owns this737// expectation.738virtual Expectation GetHandle() = 0;739740// Asserts that the EXPECT_CALL() statement has the given property.741void AssertSpecProperty(bool property,742const std::string& failure_message) const {743Assert(property, file_, line_, failure_message);744}745746// Expects that the EXPECT_CALL() statement has the given property.747void ExpectSpecProperty(bool property,748const std::string& failure_message) const {749Expect(property, file_, line_, failure_message);750}751752// Explicitly specifies the cardinality of this expectation. Used753// by the subclasses to implement the .Times() clause.754void SpecifyCardinality(const Cardinality& cardinality);755756// Returns true if and only if the user specified the cardinality757// explicitly using a .Times().758bool cardinality_specified() const { return cardinality_specified_; }759760// Sets the cardinality of this expectation spec.761void set_cardinality(const Cardinality& a_cardinality) {762cardinality_ = a_cardinality;763}764765// The following group of methods should only be called after the766// EXPECT_CALL() statement, and only when g_gmock_mutex is held by767// the current thread.768769// Retires all pre-requisites of this expectation.770void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);771772// Returns true if and only if this expectation is retired.773bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {774g_gmock_mutex.AssertHeld();775return retired_;776}777778// Retires this expectation.779void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {780g_gmock_mutex.AssertHeld();781retired_ = true;782}783784// Returns a human-readable description of this expectation.785// Do not rely on this for correctness. It is only for human readability.786const std::string& GetDescription() const { return description_; }787788// Returns true if and only if this expectation is satisfied.789bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {790g_gmock_mutex.AssertHeld();791return cardinality().IsSatisfiedByCallCount(call_count_);792}793794// Returns true if and only if this expectation is saturated.795bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {796g_gmock_mutex.AssertHeld();797return cardinality().IsSaturatedByCallCount(call_count_);798}799800// Returns true if and only if this expectation is over-saturated.801bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {802g_gmock_mutex.AssertHeld();803return cardinality().IsOverSaturatedByCallCount(call_count_);804}805806// Returns true if and only if all pre-requisites of this expectation are807// satisfied.808bool AllPrerequisitesAreSatisfied() const809GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);810811// Adds unsatisfied pre-requisites of this expectation to 'result'.812void FindUnsatisfiedPrerequisites(ExpectationSet* result) const813GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);814815// Returns the number this expectation has been invoked.816int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {817g_gmock_mutex.AssertHeld();818return call_count_;819}820821// Increments the number this expectation has been invoked.822void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {823g_gmock_mutex.AssertHeld();824call_count_++;825}826827// Checks the action count (i.e. the number of WillOnce() and828// WillRepeatedly() clauses) against the cardinality if this hasn't829// been done before. Prints a warning if there are too many or too830// few actions.831void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);832833friend class ::testing::Sequence;834friend class ::testing::internal::ExpectationTester;835836template <typename Function>837friend class TypedExpectation;838839// Implements the .Times() clause.840void UntypedTimes(const Cardinality& a_cardinality);841842// This group of fields are part of the spec and won't change after843// an EXPECT_CALL() statement finishes.844const char* file_; // The file that contains the expectation.845int line_; // The line number of the expectation.846const std::string source_text_; // The EXPECT_CALL(...) source text.847std::string description_; // User-readable name for the expectation.848// True if and only if the cardinality is specified explicitly.849bool cardinality_specified_;850Cardinality cardinality_; // The cardinality of the expectation.851// The immediate pre-requisites (i.e. expectations that must be852// satisfied before this expectation can be matched) of this853// expectation. We use std::shared_ptr in the set because we want an854// Expectation object to be co-owned by its FunctionMocker and its855// successors. This allows multiple mock objects to be deleted at856// different times.857ExpectationSet immediate_prerequisites_;858859// This group of fields are the current state of the expectation,860// and can change as the mock function is called.861int call_count_; // How many times this expectation has been invoked.862bool retired_; // True if and only if this expectation has retired.863UntypedActions untyped_actions_;864bool extra_matcher_specified_;865bool repeated_action_specified_; // True if a WillRepeatedly() was specified.866bool retires_on_saturation_;867Clause last_clause_;868mutable bool action_count_checked_; // Under mutex_.869mutable Mutex mutex_; // Protects action_count_checked_.870}; // class ExpectationBase871872template <typename F>873class TypedExpectation;874875// Implements an expectation for the given function type.876template <typename R, typename... Args>877class TypedExpectation<R(Args...)> : public ExpectationBase {878private:879using F = R(Args...);880881public:882typedef typename Function<F>::ArgumentTuple ArgumentTuple;883typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;884typedef typename Function<F>::Result Result;885886TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,887const std::string& a_source_text,888const ArgumentMatcherTuple& m)889: ExpectationBase(a_file, a_line, a_source_text),890owner_(owner),891matchers_(m),892// By default, extra_matcher_ should match anything. However,893// we cannot initialize it with _ as that causes ambiguity between894// Matcher's copy and move constructor for some argument types.895extra_matcher_(A<const ArgumentTuple&>()),896repeated_action_(DoDefault()) {}897898~TypedExpectation() override {899// Check the validity of the action count if it hasn't been done900// yet (for example, if the expectation was never used).901CheckActionCountIfNotDone();902for (UntypedActions::const_iterator it = untyped_actions_.begin();903it != untyped_actions_.end(); ++it) {904delete static_cast<const Action<F>*>(*it);905}906}907908// Implements the .With() clause.909TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {910if (last_clause_ == kWith) {911ExpectSpecProperty(false,912".With() cannot appear "913"more than once in an EXPECT_CALL().");914} else {915ExpectSpecProperty(last_clause_ < kWith,916".With() must be the first "917"clause in an EXPECT_CALL().");918}919last_clause_ = kWith;920921extra_matcher_ = m;922extra_matcher_specified_ = true;923return *this;924}925926// Do not rely on this for correctness.927// This is only for making human-readable test output easier to understand.928TypedExpectation& Description(std::string name) {929ExpectationBase::UntypedDescription(std::move(name));930return *this;931}932933// Implements the .Times() clause.934TypedExpectation& Times(const Cardinality& a_cardinality) {935ExpectationBase::UntypedTimes(a_cardinality);936return *this;937}938939// Implements the .Times() clause.940TypedExpectation& Times(int n) { return Times(Exactly(n)); }941942// Implements the .InSequence() clause.943TypedExpectation& InSequence(const Sequence& s) {944ExpectSpecProperty(last_clause_ <= kInSequence,945".InSequence() cannot appear after .After(),"946" .WillOnce(), .WillRepeatedly(), or "947".RetiresOnSaturation().");948last_clause_ = kInSequence;949950s.AddExpectation(GetHandle());951return *this;952}953TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {954return InSequence(s1).InSequence(s2);955}956TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,957const Sequence& s3) {958return InSequence(s1, s2).InSequence(s3);959}960TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,961const Sequence& s3, const Sequence& s4) {962return InSequence(s1, s2, s3).InSequence(s4);963}964TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,965const Sequence& s3, const Sequence& s4,966const Sequence& s5) {967return InSequence(s1, s2, s3, s4).InSequence(s5);968}969970// Implements that .After() clause.971TypedExpectation& After(const ExpectationSet& s) {972ExpectSpecProperty(last_clause_ <= kAfter,973".After() cannot appear after .WillOnce(),"974" .WillRepeatedly(), or "975".RetiresOnSaturation().");976last_clause_ = kAfter;977978for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {979immediate_prerequisites_ += *it;980}981return *this;982}983TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {984return After(s1).After(s2);985}986TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,987const ExpectationSet& s3) {988return After(s1, s2).After(s3);989}990TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,991const ExpectationSet& s3, const ExpectationSet& s4) {992return After(s1, s2, s3).After(s4);993}994TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,995const ExpectationSet& s3, const ExpectationSet& s4,996const ExpectationSet& s5) {997return After(s1, s2, s3, s4).After(s5);998}9991000// Preferred, type-safe overload: consume anything that can be directly1001// converted to a OnceAction, except for Action<F> objects themselves.1002TypedExpectation& WillOnce(OnceAction<F> once_action) {1003// Call the overload below, smuggling the OnceAction as a copyable callable.1004// We know this is safe because a WillOnce action will not be called more1005// than once.1006return WillOnce(Action<F>(ActionAdaptor{1007std::make_shared<OnceAction<F>>(std::move(once_action)),1008}));1009}10101011// Fallback overload: accept Action<F> objects and those actions that define1012// `operator Action<F>` but not `operator OnceAction<F>`.1013//1014// This is templated in order to cause the overload above to be preferred1015// when the input is convertible to either type.1016template <int&... ExplicitArgumentBarrier, typename = void>1017TypedExpectation& WillOnce(Action<F> action) {1018ExpectSpecProperty(last_clause_ <= kWillOnce,1019".WillOnce() cannot appear after "1020".WillRepeatedly() or .RetiresOnSaturation().");1021last_clause_ = kWillOnce;10221023untyped_actions_.push_back(new Action<F>(std::move(action)));10241025if (!cardinality_specified()) {1026set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));1027}1028return *this;1029}10301031// Implements the .WillRepeatedly() clause.1032TypedExpectation& WillRepeatedly(const Action<F>& action) {1033if (last_clause_ == kWillRepeatedly) {1034ExpectSpecProperty(false,1035".WillRepeatedly() cannot appear "1036"more than once in an EXPECT_CALL().");1037} else {1038ExpectSpecProperty(last_clause_ < kWillRepeatedly,1039".WillRepeatedly() cannot appear "1040"after .RetiresOnSaturation().");1041}1042last_clause_ = kWillRepeatedly;1043repeated_action_specified_ = true;10441045repeated_action_ = action;1046if (!cardinality_specified()) {1047set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));1048}10491050// Now that no more action clauses can be specified, we check1051// whether their count makes sense.1052CheckActionCountIfNotDone();1053return *this;1054}10551056// Implements the .RetiresOnSaturation() clause.1057TypedExpectation& RetiresOnSaturation() {1058ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,1059".RetiresOnSaturation() cannot appear "1060"more than once.");1061last_clause_ = kRetiresOnSaturation;1062retires_on_saturation_ = true;10631064// Now that no more action clauses can be specified, we check1065// whether their count makes sense.1066CheckActionCountIfNotDone();1067return *this;1068}10691070// Returns the matchers for the arguments as specified inside the1071// EXPECT_CALL() macro.1072const ArgumentMatcherTuple& matchers() const { return matchers_; }10731074// Returns the matcher specified by the .With() clause.1075const Matcher<const ArgumentTuple&>& extra_matcher() const {1076return extra_matcher_;1077}10781079// Returns the action specified by the .WillRepeatedly() clause.1080const Action<F>& repeated_action() const { return repeated_action_; }10811082// If this mock method has an extra matcher (i.e. .With(matcher)),1083// describes it to the ostream.1084void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {1085if (extra_matcher_specified_) {1086*os << " Expected args: ";1087extra_matcher_.DescribeTo(os);1088*os << "\n";1089}1090}10911092private:1093template <typename Function>1094friend class FunctionMocker;10951096// An adaptor that turns a OneAction<F> into something compatible with1097// Action<F>. Must be called at most once.1098struct ActionAdaptor {1099std::shared_ptr<OnceAction<R(Args...)>> once_action;11001101R operator()(Args&&... args) const {1102return std::move(*once_action).Call(std::forward<Args>(args)...);1103}1104};11051106// Returns an Expectation object that references and co-owns this1107// expectation.1108Expectation GetHandle() override { return owner_->GetHandleOf(this); }11091110// The following methods will be called only after the EXPECT_CALL()1111// statement finishes and when the current thread holds1112// g_gmock_mutex.11131114// Returns true if and only if this expectation matches the given arguments.1115bool Matches(const ArgumentTuple& args) const1116GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1117g_gmock_mutex.AssertHeld();1118return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);1119}11201121// Returns true if and only if this expectation should handle the given1122// arguments.1123bool ShouldHandleArguments(const ArgumentTuple& args) const1124GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1125g_gmock_mutex.AssertHeld();11261127// In case the action count wasn't checked when the expectation1128// was defined (e.g. if this expectation has no WillRepeatedly()1129// or RetiresOnSaturation() clause), we check it when the1130// expectation is used for the first time.1131CheckActionCountIfNotDone();1132return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);1133}11341135// Describes the result of matching the arguments against this1136// expectation to the given ostream.1137void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const1138GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1139g_gmock_mutex.AssertHeld();11401141if (is_retired()) {1142*os << " Expected: the expectation is active\n"1143<< " Actual: it is retired\n";1144} else if (!Matches(args)) {1145if (!TupleMatches(matchers_, args)) {1146ExplainMatchFailureTupleTo(matchers_, args, os);1147}1148StringMatchResultListener listener;1149if (!extra_matcher_.MatchAndExplain(args, &listener)) {1150*os << " Expected args: ";1151extra_matcher_.DescribeTo(os);1152*os << "\n Actual: don't match";11531154internal::PrintIfNotEmpty(listener.str(), os);1155*os << "\n";1156}1157} else if (!AllPrerequisitesAreSatisfied()) {1158*os << " Expected: all pre-requisites are satisfied\n"1159<< " Actual: the following immediate pre-requisites "1160<< "are not satisfied:\n";1161ExpectationSet unsatisfied_prereqs;1162FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);1163int i = 0;1164for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();1165it != unsatisfied_prereqs.end(); ++it) {1166it->expectation_base()->DescribeLocationTo(os);1167*os << "pre-requisite #" << i++ << "\n";1168}1169*os << " (end of pre-requisites)\n";1170} else {1171// This line is here just for completeness' sake. It will never1172// be executed as currently the ExplainMatchResultTo() function1173// is called only when the mock function call does NOT match the1174// expectation.1175*os << "The call matches the expectation.\n";1176}1177}11781179// Returns the action that should be taken for the current invocation.1180const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,1181const ArgumentTuple& args) const1182GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1183g_gmock_mutex.AssertHeld();1184const int count = call_count();1185Assert(count >= 1, __FILE__, __LINE__,1186"call_count() is <= 0 when GetCurrentAction() is "1187"called - this should never happen.");11881189const int action_count = static_cast<int>(untyped_actions_.size());1190if (action_count > 0 && !repeated_action_specified_ &&1191count > action_count) {1192// If there is at least one WillOnce() and no WillRepeatedly(),1193// we warn the user when the WillOnce() clauses ran out.1194::std::stringstream ss;1195DescribeLocationTo(&ss);1196ss << "Actions ran out in " << source_text() << "...\n"1197<< "Called " << count << " times, but only " << action_count1198<< " WillOnce()" << (action_count == 1 ? " is" : "s are")1199<< " specified - ";1200mocker->DescribeDefaultActionTo(args, &ss);1201Log(kWarning, ss.str(), 1);1202}12031204return count <= action_count1205? *static_cast<const Action<F>*>(1206untyped_actions_[static_cast<size_t>(count - 1)])1207: repeated_action();1208}12091210// Given the arguments of a mock function call, if the call will1211// over-saturate this expectation, returns the default action;1212// otherwise, returns the next action in this expectation. Also1213// describes *what* happened to 'what', and explains *why* Google1214// Mock does it to 'why'. This method is not const as it calls1215// IncrementCallCount(). A return value of NULL means the default1216// action.1217const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,1218const ArgumentTuple& args,1219::std::ostream* what,1220::std::ostream* why)1221GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1222g_gmock_mutex.AssertHeld();1223const ::std::string& expectation_description = GetDescription();1224if (IsSaturated()) {1225// We have an excessive call.1226IncrementCallCount();1227*what << "Mock function ";1228if (!expectation_description.empty()) {1229*what << "\"" << expectation_description << "\" ";1230}1231*what << "called more times than expected - ";1232mocker->DescribeDefaultActionTo(args, what);1233DescribeCallCountTo(why);12341235return nullptr;1236}12371238IncrementCallCount();1239RetireAllPreRequisites();12401241if (retires_on_saturation_ && IsSaturated()) {1242Retire();1243}12441245// Must be done after IncrementCount()!1246*what << "Mock function ";1247if (!expectation_description.empty()) {1248*what << "\"" << expectation_description << "\" ";1249}1250*what << "call matches " << source_text() << "...\n";1251return &(GetCurrentAction(mocker, args));1252}12531254// All the fields below won't change once the EXPECT_CALL()1255// statement finishes.1256FunctionMocker<F>* const owner_;1257ArgumentMatcherTuple matchers_;1258Matcher<const ArgumentTuple&> extra_matcher_;1259Action<F> repeated_action_;12601261TypedExpectation(const TypedExpectation&) = delete;1262TypedExpectation& operator=(const TypedExpectation&) = delete;1263}; // class TypedExpectation12641265// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for1266// specifying the default behavior of, or expectation on, a mock1267// function.12681269// Note: class MockSpec really belongs to the ::testing namespace.1270// However if we define it in ::testing, MSVC will complain when1271// classes in ::testing::internal declare it as a friend class1272// template. To workaround this compiler bug, we define MockSpec in1273// ::testing::internal and import it into ::testing.12741275// Logs a message including file and line number information.1276GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,1277const char* file, int line,1278const std::string& message);12791280template <typename F>1281class MockSpec {1282public:1283typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;1284typedef1285typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;12861287// Constructs a MockSpec object, given the function mocker object1288// that the spec is associated with.1289MockSpec(internal::FunctionMocker<F>* function_mocker,1290const ArgumentMatcherTuple& matchers)1291: function_mocker_(function_mocker), matchers_(matchers) {}12921293// Adds a new default action spec to the function mocker and returns1294// the newly created spec.1295internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,1296int line, const char* obj,1297const char* call) {1298LogWithLocation(internal::kInfo, file, line,1299std::string("ON_CALL(") + obj + ", " + call + ") invoked");1300return function_mocker_->AddNewOnCallSpec(file, line, matchers_);1301}13021303// Adds a new expectation spec to the function mocker and returns1304// the newly created spec.1305internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,1306const char* obj,1307const char* call) {1308const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +1309call + ")");1310LogWithLocation(internal::kInfo, file, line, source_text + " invoked");1311return function_mocker_->AddNewExpectation(file, line, source_text,1312matchers_);1313}13141315// This operator overload is used to swallow the superfluous parameter list1316// introduced by the ON/EXPECT_CALL macros. See the macro comments for more1317// explanation.1318MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {1319return *this;1320}13211322private:1323template <typename Function>1324friend class internal::FunctionMocker;13251326// The function mocker that owns this spec.1327internal::FunctionMocker<F>* const function_mocker_;1328// The argument matchers specified in the spec.1329ArgumentMatcherTuple matchers_;1330}; // class MockSpec13311332// Wrapper type for generically holding an ordinary value or lvalue reference.1333// If T is not a reference type, it must be copyable or movable.1334// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless1335// T is a move-only value type (which means that it will always be copyable1336// if the current platform does not support move semantics).1337//1338// The primary template defines handling for values, but function header1339// comments describe the contract for the whole template (including1340// specializations).1341template <typename T>1342class ReferenceOrValueWrapper {1343public:1344// Constructs a wrapper from the given value/reference.1345explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}13461347// Unwraps and returns the underlying value/reference, exactly as1348// originally passed. The behavior of calling this more than once on1349// the same object is unspecified.1350T Unwrap() { return std::move(value_); }13511352// Provides nondestructive access to the underlying value/reference.1353// Always returns a const reference (more precisely,1354// const std::add_lvalue_reference<T>::type). The behavior of calling this1355// after calling Unwrap on the same object is unspecified.1356const T& Peek() const { return value_; }13571358private:1359T value_;1360};13611362// Specialization for lvalue reference types. See primary template1363// for documentation.1364template <typename T>1365class ReferenceOrValueWrapper<T&> {1366public:1367// Workaround for debatable pass-by-reference lint warning (c-library-team1368// policy precludes NOLINT in this context)1369typedef T& reference;1370explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}1371T& Unwrap() { return *value_ptr_; }1372const T& Peek() const { return *value_ptr_; }13731374private:1375T* value_ptr_;1376};13771378// Prints the held value as an action's result to os.1379template <typename T>1380void PrintAsActionResult(const T& result, std::ostream& os) {1381os << "\n Returns: ";1382// T may be a reference type, so we don't use UniversalPrint().1383UniversalPrinter<T>::Print(result, &os);1384}13851386// Reports an uninteresting call (whose description is in msg) in the1387// manner specified by 'reaction'.1388GTEST_API_ void ReportUninterestingCall(CallReaction reaction,1389const std::string& msg);13901391// A generic RAII type that runs a user-provided function in its destructor.1392class Cleanup final {1393public:1394explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}1395~Cleanup() { f_(); }13961397private:1398std::function<void()> f_;1399};14001401struct UntypedFunctionMockerBase::UninterestingCallCleanupHandler {1402CallReaction reaction;1403std::stringstream& ss;14041405~UninterestingCallCleanupHandler() {1406ReportUninterestingCall(reaction, ss.str());1407}1408};14091410struct UntypedFunctionMockerBase::FailureCleanupHandler {1411std::stringstream& ss;1412std::stringstream& why;1413std::stringstream& loc;1414const ExpectationBase* untyped_expectation;1415bool found;1416bool is_excessive;14171418~FailureCleanupHandler() {1419ss << "\n" << why.str();14201421if (!found) {1422// No expectation matches this call - reports a failure.1423Expect(false, nullptr, -1, ss.str());1424} else if (is_excessive) {1425// We had an upper-bound violation and the failure message is in ss.1426Expect(false, untyped_expectation->file(), untyped_expectation->line(),1427ss.str());1428} else {1429// We had an expected call and the matching expectation is1430// described in ss.1431Log(kInfo, loc.str() + ss.str(), 2);1432}1433}1434};14351436template <typename F>1437class FunctionMocker;14381439template <typename R, typename... Args>1440class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {1441using F = R(Args...);14421443public:1444using Result = R;1445using ArgumentTuple = std::tuple<Args...>;1446using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;14471448FunctionMocker() = default;14491450// There is no generally useful and implementable semantics of1451// copying a mock object, so copying a mock is usually a user error.1452// Thus we disallow copying function mockers. If the user really1453// wants to copy a mock object, they should implement their own copy1454// operation, for example:1455//1456// class MockFoo : public Foo {1457// public:1458// // Defines a copy constructor explicitly.1459// MockFoo(const MockFoo& src) {}1460// ...1461// };1462FunctionMocker(const FunctionMocker&) = delete;1463FunctionMocker& operator=(const FunctionMocker&) = delete;14641465// The destructor verifies that all expectations on this mock1466// function have been satisfied. If not, it will report Google Test1467// non-fatal failures for the violations.1468~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {1469MutexLock l(&g_gmock_mutex);1470VerifyAndClearExpectationsLocked();1471Mock::UnregisterLocked(this);1472ClearDefaultActionsLocked();1473}14741475// Returns the ON_CALL spec that matches this mock function with the1476// given arguments; returns NULL if no matching ON_CALL is found.1477// L = *1478const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {1479for (UntypedOnCallSpecs::const_reverse_iterator it =1480untyped_on_call_specs_.rbegin();1481it != untyped_on_call_specs_.rend(); ++it) {1482const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);1483if (spec->Matches(args)) return spec;1484}14851486return nullptr;1487}14881489// Performs the default action of this mock function on the given1490// arguments and returns the result. Asserts (or throws if1491// exceptions are enabled) with a helpful call description if there1492// is no valid return value. This method doesn't depend on the1493// mutable state of this object, and thus can be called concurrently1494// without locking.1495// L = *1496Result PerformDefaultAction(ArgumentTuple&& args,1497const std::string& call_description) const {1498const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);1499if (spec != nullptr) {1500return spec->GetAction().Perform(std::move(args));1501}1502const std::string message =1503call_description +1504"\n The mock function has no default action "1505"set, and its return type has no default value set.";1506#if GTEST_HAS_EXCEPTIONS1507if (!DefaultValue<Result>::Exists()) {1508throw std::runtime_error(message);1509}1510#else1511Assert(DefaultValue<Result>::Exists(), "", -1, message);1512#endif1513return DefaultValue<Result>::Get();1514}15151516// Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():1517// clears the ON_CALL()s set on this mock function.1518void ClearDefaultActionsLocked() override1519GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1520g_gmock_mutex.AssertHeld();15211522// Deleting our default actions may trigger other mock objects to be1523// deleted, for example if an action contains a reference counted smart1524// pointer to that mock object, and that is the last reference. So if we1525// delete our actions within the context of the global mutex we may deadlock1526// when this method is called again. Instead, make a copy of the set of1527// actions to delete, clear our set within the mutex, and then delete the1528// actions outside of the mutex.1529UntypedOnCallSpecs specs_to_delete;1530untyped_on_call_specs_.swap(specs_to_delete);15311532g_gmock_mutex.Unlock();1533for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();1534it != specs_to_delete.end(); ++it) {1535delete static_cast<const OnCallSpec<F>*>(*it);1536}15371538// Lock the mutex again, since the caller expects it to be locked when we1539// return.1540g_gmock_mutex.Lock();1541}15421543// Returns the result of invoking this mock function with the given1544// arguments. This function can be safely called from multiple1545// threads concurrently.1546Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {1547return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));1548}15491550MockSpec<F> With(Matcher<Args>... m) {1551return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));1552}15531554protected:1555template <typename Function>1556friend class MockSpec;15571558// Adds and returns a default action spec for this mock function.1559OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,1560const ArgumentMatcherTuple& m)1561GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {1562Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);1563OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);1564untyped_on_call_specs_.push_back(on_call_spec);1565return *on_call_spec;1566}15671568// Adds and returns an expectation spec for this mock function.1569TypedExpectation<F>& AddNewExpectation(const char* file, int line,1570const std::string& source_text,1571const ArgumentMatcherTuple& m)1572GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {1573Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);1574TypedExpectation<F>* const expectation =1575new TypedExpectation<F>(this, file, line, source_text, m);1576const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);1577// See the definition of untyped_expectations_ for why access to1578// it is unprotected here.1579untyped_expectations_.push_back(untyped_expectation);15801581// Adds this expectation into the implicit sequence if there is one.1582Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();1583if (implicit_sequence != nullptr) {1584implicit_sequence->AddExpectation(Expectation(untyped_expectation));1585}15861587return *expectation;1588}15891590private:1591template <typename Func>1592friend class TypedExpectation;15931594// Some utilities needed for implementing UntypedInvokeWith().15951596// Describes what default action will be performed for the given1597// arguments.1598// L = *1599void DescribeDefaultActionTo(const ArgumentTuple& args,1600::std::ostream* os) const {1601const OnCallSpec<F>* const spec = FindOnCallSpec(args);16021603if (spec == nullptr) {1604*os << (std::is_void<Result>::value ? "returning directly.\n"1605: "returning default value.\n");1606} else {1607*os << "taking default action specified at:\n"1608<< FormatFileLocation(spec->file(), spec->line()) << "\n";1609}1610}16111612// Writes a message that the call is uninteresting (i.e. neither1613// explicitly expected nor explicitly unexpected) to the given1614// ostream.1615void UntypedDescribeUninterestingCall(const void* untyped_args,1616::std::ostream* os) const override1617GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {1618const ArgumentTuple& args =1619*static_cast<const ArgumentTuple*>(untyped_args);1620*os << "Uninteresting mock function call - ";1621DescribeDefaultActionTo(args, os);1622*os << " Function call: " << Name();1623UniversalPrint(args, os);1624}16251626// Returns the expectation that matches the given function arguments1627// (or NULL is there's no match); when a match is found,1628// untyped_action is set to point to the action that should be1629// performed (or NULL if the action is "do default"), and1630// is_excessive is modified to indicate whether the call exceeds the1631// expected number.1632//1633// Critical section: We must find the matching expectation and the1634// corresponding action that needs to be taken in an ATOMIC1635// transaction. Otherwise another thread may call this mock1636// method in the middle and mess up the state.1637//1638// However, performing the action has to be left out of the critical1639// section. The reason is that we have no control on what the1640// action does (it can invoke an arbitrary user function or even a1641// mock function) and excessive locking could cause a dead lock.1642const ExpectationBase* UntypedFindMatchingExpectation(1643const void* untyped_args, const void** untyped_action, bool* is_excessive,1644::std::ostream* what, ::std::ostream* why) override1645GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {1646const ArgumentTuple& args =1647*static_cast<const ArgumentTuple*>(untyped_args);1648MutexLock l(&g_gmock_mutex);1649TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);1650if (exp == nullptr) { // A match wasn't found.1651this->FormatUnexpectedCallMessageLocked(args, what, why);1652return nullptr;1653}16541655// This line must be done before calling GetActionForArguments(),1656// which will increment the call count for *exp and thus affect1657// its saturation status.1658*is_excessive = exp->IsSaturated();1659const Action<F>* action = exp->GetActionForArguments(this, args, what, why);1660if (action != nullptr && action->IsDoDefault())1661action = nullptr; // Normalize "do default" to NULL.1662*untyped_action = action;1663return exp;1664}16651666// Prints the given function arguments to the ostream.1667void UntypedPrintArgs(const void* untyped_args,1668::std::ostream* os) const override {1669const ArgumentTuple& args =1670*static_cast<const ArgumentTuple*>(untyped_args);1671UniversalPrint(args, os);1672}16731674// Returns the expectation that matches the arguments, or NULL if no1675// expectation matches them.1676TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)1677const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1678g_gmock_mutex.AssertHeld();1679// See the definition of untyped_expectations_ for why access to1680// it is unprotected here.1681for (typename UntypedExpectations::const_reverse_iterator it =1682untyped_expectations_.rbegin();1683it != untyped_expectations_.rend(); ++it) {1684TypedExpectation<F>* const exp =1685static_cast<TypedExpectation<F>*>(it->get());1686if (exp->ShouldHandleArguments(args)) {1687return exp;1688}1689}1690return nullptr;1691}16921693// Returns a message that the arguments don't match any expectation.1694void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,1695::std::ostream* os,1696::std::ostream* why) const1697GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1698g_gmock_mutex.AssertHeld();1699*os << "\nUnexpected mock function call - ";1700DescribeDefaultActionTo(args, os);1701PrintTriedExpectationsLocked(args, why);1702}17031704// Prints a list of expectations that have been tried against the1705// current mock function call.1706void PrintTriedExpectationsLocked(const ArgumentTuple& args,1707::std::ostream* why) const1708GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {1709g_gmock_mutex.AssertHeld();1710const size_t count = untyped_expectations_.size();1711*why << "Google Mock tried the following " << count << " "1712<< (count == 1 ? "expectation, but it didn't match"1713: "expectations, but none matched")1714<< ":\n";1715for (size_t i = 0; i < count; i++) {1716TypedExpectation<F>* const expectation =1717static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());1718*why << "\n";1719expectation->DescribeLocationTo(why);1720if (count > 1) {1721*why << "tried expectation #" << i << ": ";1722}1723*why << expectation->source_text() << "...\n";1724expectation->ExplainMatchResultTo(args, why);1725expectation->DescribeCallCountTo(why);1726}1727}17281729// Performs the given action (or the default if it's null) with the given1730// arguments and returns the action's result.1731// L = *1732R PerformAction(const void* untyped_action, ArgumentTuple&& args,1733const std::string& call_description) const {1734if (untyped_action == nullptr) {1735return PerformDefaultAction(std::move(args), call_description);1736}17371738// Make a copy of the action before performing it, in case the1739// action deletes the mock object (and thus deletes itself).1740const Action<F> action = *static_cast<const Action<F>*>(untyped_action);1741return action.Perform(std::move(args));1742}17431744// Is it possible to store an object of the supplied type in a local variable1745// for the sake of printing it, then return it on to the caller?1746template <typename T>1747using can_print_result = internal::conjunction<1748// void can't be stored as an object (and we also don't need to print it).1749internal::negation<std::is_void<T>>,1750// Non-moveable types can't be returned on to the user, so there's no way1751// for us to intercept and print them.1752std::is_move_constructible<T>>;17531754// Perform the supplied action, printing the result to os.1755template <typename T = R,1756typename std::enable_if<can_print_result<T>::value, int>::type = 0>1757R PerformActionAndPrintResult(const void* const untyped_action,1758ArgumentTuple&& args,1759const std::string& call_description,1760std::ostream& os) {1761R result = PerformAction(untyped_action, std::move(args), call_description);17621763PrintAsActionResult(result, os);1764return std::forward<R>(result);1765}17661767// An overload for when it's not possible to print the result. In this case we1768// simply perform the action.1769template <typename T = R,1770typename std::enable_if<1771internal::negation<can_print_result<T>>::value, int>::type = 0>1772R PerformActionAndPrintResult(const void* const untyped_action,1773ArgumentTuple&& args,1774const std::string& call_description,1775std::ostream&) {1776return PerformAction(untyped_action, std::move(args), call_description);1777}17781779// Returns the result of invoking this mock function with the given1780// arguments. This function can be safely called from multiple1781// threads concurrently.1782R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);1783}; // class FunctionMocker17841785// Calculates the result of invoking this mock function with the given1786// arguments, prints it, and returns it.1787template <typename R, typename... Args>1788R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)1789GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {1790// See the definition of untyped_expectations_ for why access to it1791// is unprotected here.1792if (untyped_expectations_.size() == 0) {1793// No expectation is set on this mock method - we have an1794// uninteresting call.17951796// We must get Google Mock's reaction on uninteresting calls1797// made on this mock object BEFORE performing the action,1798// because the action may DELETE the mock object and make the1799// following expression meaningless.1800const CallReaction reaction =1801Mock::GetReactionOnUninterestingCalls(MockObject());18021803// True if and only if we need to print this call's arguments and return1804// value. This definition must be kept in sync with1805// the behavior of ReportUninterestingCall().1806const bool need_to_report_uninteresting_call =1807// If the user allows this uninteresting call, we print it1808// only when they want informational messages.1809reaction == kAllow ? LogIsVisible(kInfo) :1810// If the user wants this to be a warning, we print1811// it only when they want to see warnings.1812reaction == kWarn1813? LogIsVisible(kWarning)1814:1815// Otherwise, the user wants this to be an error, and we1816// should always print detailed information in the error.1817true;18181819if (!need_to_report_uninteresting_call) {1820// Perform the action without printing the call information.1821return this->PerformDefaultAction(1822std::move(args), "Function call: " + std::string(Name()));1823}18241825// Warns about the uninteresting call.1826::std::stringstream ss;1827this->UntypedDescribeUninterestingCall(&args, &ss);18281829// Perform the action, print the result, and then report the uninteresting1830// call.1831//1832// We use RAII to do the latter in case R is void or a non-moveable type. In1833// either case we can't assign it to a local variable.1834//1835// Note that std::bind() is essential here.1836// We *don't* use any local callback types (like lambdas).1837// Doing so slows down compilation dramatically because the *constructor* of1838// std::function<T> is re-instantiated with different template1839// parameters each time.1840const UninterestingCallCleanupHandler report_uninteresting_call = {1841reaction, ss1842};18431844return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);1845}18461847bool is_excessive = false;1848::std::stringstream ss;1849::std::stringstream why;1850::std::stringstream loc;1851const void* untyped_action = nullptr;18521853// The UntypedFindMatchingExpectation() function acquires and1854// releases g_gmock_mutex.18551856const ExpectationBase* const untyped_expectation =1857this->UntypedFindMatchingExpectation(&args, &untyped_action,1858&is_excessive, &ss, &why);1859const bool found = untyped_expectation != nullptr;18601861// True if and only if we need to print the call's arguments1862// and return value.1863// This definition must be kept in sync with the uses of Expect()1864// and Log() in this function.1865const bool need_to_report_call =1866!found || is_excessive || LogIsVisible(kInfo);1867if (!need_to_report_call) {1868// Perform the action without printing the call information.1869return PerformAction(untyped_action, std::move(args), "");1870}18711872ss << " Function call: " << Name();1873this->UntypedPrintArgs(&args, &ss);18741875// In case the action deletes a piece of the expectation, we1876// generate the message beforehand.1877if (found && !is_excessive) {1878untyped_expectation->DescribeLocationTo(&loc);1879}18801881// Perform the action, print the result, and then fail or log in whatever way1882// is appropriate.1883//1884// We use RAII to do the latter in case R is void or a non-moveable type. In1885// either case we can't assign it to a local variable.1886//1887// Note that we *don't* use any local callback types (like lambdas) here.1888// Doing so slows down compilation dramatically because the *constructor* of1889// std::function<T> is re-instantiated with different template1890// parameters each time.1891const FailureCleanupHandler handle_failures = {1892ss, why, loc, untyped_expectation, found, is_excessive1893};18941895return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),1896ss);1897}18981899} // namespace internal19001901namespace internal {19021903template <typename F>1904class MockFunction;19051906template <typename R, typename... Args>1907class MockFunction<R(Args...)> {1908public:1909MockFunction(const MockFunction&) = delete;1910MockFunction& operator=(const MockFunction&) = delete;19111912std::function<R(Args...)> AsStdFunction() {1913return [this](Args... args) -> R {1914return this->Call(std::forward<Args>(args)...);1915};1916}19171918// Implementation detail: the expansion of the MOCK_METHOD macro.1919R Call(Args... args) {1920mock_.SetOwnerAndName(this, "Call");1921return mock_.Invoke(std::forward<Args>(args)...);1922}19231924MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {1925mock_.RegisterOwner(this);1926return mock_.With(std::move(m)...);1927}19281929MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {1930return this->gmock_Call(::testing::A<Args>()...);1931}19321933protected:1934MockFunction() = default;1935~MockFunction() = default;19361937private:1938FunctionMocker<R(Args...)> mock_;1939};19401941/*1942The SignatureOf<F> struct is a meta-function returning function signature1943corresponding to the provided F argument.19441945It makes use of MockFunction easier by allowing it to accept more F arguments1946than just function signatures.19471948Specializations provided here cover a signature type itself and any template1949that can be parameterized with a signature, including std::function and1950boost::function.1951*/19521953template <typename F, typename = void>1954struct SignatureOf;19551956template <typename R, typename... Args>1957struct SignatureOf<R(Args...)> {1958using type = R(Args...);1959};19601961template <template <typename> class C, typename F>1962struct SignatureOf<C<F>,1963typename std::enable_if<std::is_function<F>::value>::type>1964: SignatureOf<F> {};19651966template <typename F>1967using SignatureOfT = typename SignatureOf<F>::type;19681969} // namespace internal19701971// A MockFunction<F> type has one mock method whose type is1972// internal::SignatureOfT<F>. It is useful when you just want your1973// test code to emit some messages and have Google Mock verify the1974// right messages are sent (and perhaps at the right times). For1975// example, if you are exercising code:1976//1977// Foo(1);1978// Foo(2);1979// Foo(3);1980//1981// and want to verify that Foo(1) and Foo(3) both invoke1982// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:1983//1984// TEST(FooTest, InvokesBarCorrectly) {1985// MyMock mock;1986// MockFunction<void(string check_point_name)> check;1987// {1988// InSequence s;1989//1990// EXPECT_CALL(mock, Bar("a"));1991// EXPECT_CALL(check, Call("1"));1992// EXPECT_CALL(check, Call("2"));1993// EXPECT_CALL(mock, Bar("a"));1994// }1995// Foo(1);1996// check.Call("1");1997// Foo(2);1998// check.Call("2");1999// Foo(3);2000// }2001//2002// The expectation spec says that the first Bar("a") must happen2003// before check point "1", the second Bar("a") must happen after check2004// point "2", and nothing should happen between the two check2005// points. The explicit check points make it easy to tell which2006// Bar("a") is called by which call to Foo().2007//2008// MockFunction<F> can also be used to exercise code that accepts2009// std::function<internal::SignatureOfT<F>> callbacks. To do so, use2010// AsStdFunction() method to create std::function proxy forwarding to2011// original object's Call. Example:2012//2013// TEST(FooTest, RunsCallbackWithBarArgument) {2014// MockFunction<int(string)> callback;2015// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));2016// Foo(callback.AsStdFunction());2017// }2018//2019// The internal::SignatureOfT<F> indirection allows to use other types2020// than just function signature type. This is typically useful when2021// providing a mock for a predefined std::function type. Example:2022//2023// using FilterPredicate = std::function<bool(string)>;2024// void MyFilterAlgorithm(FilterPredicate predicate);2025//2026// TEST(FooTest, FilterPredicateAlwaysAccepts) {2027// MockFunction<FilterPredicate> predicateMock;2028// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));2029// MyFilterAlgorithm(predicateMock.AsStdFunction());2030// }2031template <typename F>2032class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {2033using Base = internal::MockFunction<internal::SignatureOfT<F>>;20342035public:2036using Base::Base;2037};20382039// The style guide prohibits "using" statements in a namespace scope2040// inside a header file. However, the MockSpec class template is2041// meant to be defined in the ::testing namespace. The following line2042// is just a trick for working around a bug in MSVC 8.0, which cannot2043// handle it if we define MockSpec in ::testing.2044using internal::MockSpec;20452046// Const(x) is a convenient function for obtaining a const reference2047// to x. This is useful for setting expectations on an overloaded2048// const mock method, e.g.2049//2050// class MockFoo : public FooInterface {2051// public:2052// MOCK_METHOD0(Bar, int());2053// MOCK_CONST_METHOD0(Bar, int&());2054// };2055//2056// MockFoo foo;2057// // Expects a call to non-const MockFoo::Bar().2058// EXPECT_CALL(foo, Bar());2059// // Expects a call to const MockFoo::Bar().2060// EXPECT_CALL(Const(foo), Bar());2061template <typename T>2062inline const T& Const(const T& x) {2063return x;2064}20652066// Constructs an Expectation object that references and co-owns exp.2067inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT2068: expectation_base_(exp.GetHandle().expectation_base()) {}20692070} // namespace testing20712072GTEST_DISABLE_MSC_WARNINGS_POP_() // 425120732074// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is2075// required to avoid compile errors when the name of the method used in call is2076// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro2077// tests in internal/gmock-spec-builders_test.cc for more details.2078//2079// This macro supports statements both with and without parameter matchers. If2080// the parameter list is omitted, gMock will accept any parameters, which allows2081// tests to be written that don't need to encode the number of method2082// parameter. This technique may only be used for non-overloaded methods.2083//2084// // These are the same:2085// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);2086// ON_CALL(mock, NoArgsMethod).WillByDefault(...);2087//2088// // As are these:2089// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);2090// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);2091//2092// // Can also specify args if you want, of course:2093// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);2094//2095// // Overloads work as long as you specify parameters:2096// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);2097// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);2098//2099// // Oops! Which overload did you want?2100// ON_CALL(mock, OverloadedMethod).WillByDefault(...);2101// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous2102//2103// How this works: The mock class uses two overloads of the gmock_Method2104// expectation setter method plus an operator() overload on the MockSpec object.2105// In the matcher list form, the macro expands to:2106//2107// // This statement:2108// ON_CALL(mock, TwoArgsMethod(_, 45))...2109//2110// // ...expands to:2111// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...2112// |-------------v---------------||------------v-------------|2113// invokes first overload swallowed by operator()2114//2115// // ...which is essentially:2116// mock.gmock_TwoArgsMethod(_, 45)...2117//2118// Whereas the form without a matcher list:2119//2120// // This statement:2121// ON_CALL(mock, TwoArgsMethod)...2122//2123// // ...expands to:2124// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...2125// |-----------------------v--------------------------|2126// invokes second overload2127//2128// // ...which is essentially:2129// mock.gmock_TwoArgsMethod(_, _)...2130//2131// The WithoutMatchers() argument is used to disambiguate overloads and to2132// block the caller from accidentally invoking the second overload directly. The2133// second argument is an internal type derived from the method signature. The2134// failure to disambiguate two overloads of this method in the ON_CALL statement2135// is how we block callers from setting expectations on overloaded methods.2136#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \2137((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \2138nullptr) \2139.Setter(__FILE__, __LINE__, #mock_expr, #call)21402141#define ON_CALL(obj, call) \2142GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)21432144#define EXPECT_CALL(obj, call) \2145GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)21462147#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_214821492150