Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-02-21 10:03:08

0001 // Copyright 2007, Google Inc.
0002 // All rights reserved.
0003 //
0004 // Redistribution and use in source and binary forms, with or without
0005 // modification, are permitted provided that the following conditions are
0006 // met:
0007 //
0008 //     * Redistributions of source code must retain the above copyright
0009 // notice, this list of conditions and the following disclaimer.
0010 //     * Redistributions in binary form must reproduce the above
0011 // copyright notice, this list of conditions and the following disclaimer
0012 // in the documentation and/or other materials provided with the
0013 // distribution.
0014 //     * Neither the name of Google Inc. nor the names of its
0015 // contributors may be used to endorse or promote products derived from
0016 // this software without specific prior written permission.
0017 //
0018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0029 
0030 // Google Mock - a framework for writing C++ mock classes.
0031 //
0032 // This file implements the ON_CALL() and EXPECT_CALL() macros.
0033 //
0034 // A user can use the ON_CALL() macro to specify the default action of
0035 // a mock method.  The syntax is:
0036 //
0037 //   ON_CALL(mock_object, Method(argument-matchers))
0038 //       .With(multi-argument-matcher)
0039 //       .WillByDefault(action);
0040 //
0041 //  where the .With() clause is optional.
0042 //
0043 // A user can use the EXPECT_CALL() macro to specify an expectation on
0044 // a mock method.  The syntax is:
0045 //
0046 //   EXPECT_CALL(mock_object, Method(argument-matchers))
0047 //       .With(multi-argument-matchers)
0048 //       .Times(cardinality)
0049 //       .InSequence(sequences)
0050 //       .After(expectations)
0051 //       .WillOnce(action)
0052 //       .WillRepeatedly(action)
0053 //       .RetiresOnSaturation();
0054 //
0055 // where all clauses are optional, and .InSequence()/.After()/
0056 // .WillOnce() can appear any number of times.
0057 
0058 // IWYU pragma: private, include "gmock/gmock.h"
0059 // IWYU pragma: friend gmock/.*
0060 
0061 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
0062 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
0063 
0064 #include <cstdint>
0065 #include <functional>
0066 #include <map>
0067 #include <memory>
0068 #include <set>
0069 #include <sstream>
0070 #include <string>
0071 #include <type_traits>
0072 #include <utility>
0073 #include <vector>
0074 
0075 #include "gmock/gmock-actions.h"
0076 #include "gmock/gmock-cardinalities.h"
0077 #include "gmock/gmock-matchers.h"
0078 #include "gmock/internal/gmock-internal-utils.h"
0079 #include "gmock/internal/gmock-port.h"
0080 #include "gtest/gtest.h"
0081 
0082 #if GTEST_HAS_EXCEPTIONS
0083 #include <stdexcept>  // NOLINT
0084 #endif
0085 
0086 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
0087 /* class A needs to have dll-interface to be used by clients of class B */)
0088 
0089 namespace testing {
0090 
0091 // An abstract handle of an expectation.
0092 class Expectation;
0093 
0094 // A set of expectation handles.
0095 class ExpectationSet;
0096 
0097 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
0098 // and MUST NOT BE USED IN USER CODE!!!
0099 namespace internal {
0100 
0101 // Implements a mock function.
0102 template <typename F>
0103 class FunctionMocker;
0104 
0105 // Base class for expectations.
0106 class ExpectationBase;
0107 
0108 // Implements an expectation.
0109 template <typename F>
0110 class TypedExpectation;
0111 
0112 // Helper class for testing the Expectation class template.
0113 class ExpectationTester;
0114 
0115 // Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
0116 template <typename MockClass>
0117 class NiceMockImpl;
0118 template <typename MockClass>
0119 class StrictMockImpl;
0120 template <typename MockClass>
0121 class NaggyMockImpl;
0122 
0123 // Protects the mock object registry (in class Mock), all function
0124 // mockers, and all expectations.
0125 //
0126 // The reason we don't use more fine-grained protection is: when a
0127 // mock function Foo() is called, it needs to consult its expectations
0128 // to see which one should be picked.  If another thread is allowed to
0129 // call a mock function (either Foo() or a different one) at the same
0130 // time, it could affect the "retired" attributes of Foo()'s
0131 // expectations when InSequence() is used, and thus affect which
0132 // expectation gets picked.  Therefore, we sequence all mock function
0133 // calls to ensure the integrity of the mock objects' states.
0134 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
0135 
0136 // Abstract base class of FunctionMocker.  This is the
0137 // type-agnostic part of the function mocker interface.  Its pure
0138 // virtual methods are implemented by FunctionMocker.
0139 class GTEST_API_ UntypedFunctionMockerBase {
0140  public:
0141   UntypedFunctionMockerBase();
0142   virtual ~UntypedFunctionMockerBase();
0143 
0144   // Verifies that all expectations on this mock function have been
0145   // satisfied.  Reports one or more Google Test non-fatal failures
0146   // and returns false if not.
0147   bool VerifyAndClearExpectationsLocked()
0148       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0149 
0150   // Clears the ON_CALL()s set on this mock function.
0151   virtual void ClearDefaultActionsLocked()
0152       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
0153 
0154   // In all of the following Untyped* functions, it's the caller's
0155   // responsibility to guarantee the correctness of the arguments'
0156   // types.
0157 
0158   // Writes a message that the call is uninteresting (i.e. neither
0159   // explicitly expected nor explicitly unexpected) to the given
0160   // ostream.
0161   virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
0162                                                 ::std::ostream* os) const
0163       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
0164 
0165   // Returns the expectation that matches the given function arguments
0166   // (or NULL is there's no match); when a match is found,
0167   // untyped_action is set to point to the action that should be
0168   // performed (or NULL if the action is "do default"), and
0169   // is_excessive is modified to indicate whether the call exceeds the
0170   // expected number.
0171   virtual const ExpectationBase* UntypedFindMatchingExpectation(
0172       const void* untyped_args, const void** untyped_action, bool* is_excessive,
0173       ::std::ostream* what, ::std::ostream* why)
0174       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
0175 
0176   // Prints the given function arguments to the ostream.
0177   virtual void UntypedPrintArgs(const void* untyped_args,
0178                                 ::std::ostream* os) const = 0;
0179 
0180   // Sets the mock object this mock method belongs to, and registers
0181   // this information in the global mock registry.  Will be called
0182   // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
0183   // method.
0184   void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0185 
0186   // Sets the mock object this mock method belongs to, and sets the
0187   // name of the mock function.  Will be called upon each invocation
0188   // of this mock function.
0189   void SetOwnerAndName(const void* mock_obj, const char* name)
0190       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0191 
0192   // Returns the mock object this mock method belongs to.  Must be
0193   // called after RegisterOwner() or SetOwnerAndName() has been
0194   // called.
0195   const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0196 
0197   // Returns the name of this mock method.  Must be called after
0198   // SetOwnerAndName() has been called.
0199   const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
0200 
0201  protected:
0202   typedef std::vector<const void*> UntypedOnCallSpecs;
0203 
0204   using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
0205 
0206   // Returns an Expectation object that references and co-owns exp,
0207   // which must be an expectation on this mock function.
0208   Expectation GetHandleOf(ExpectationBase* exp);
0209 
0210   // Address of the mock object this mock method belongs to.  Only
0211   // valid after this mock method has been called or
0212   // ON_CALL/EXPECT_CALL has been invoked on it.
0213   const void* mock_obj_;  // Protected by g_gmock_mutex.
0214 
0215   // Name of the function being mocked.  Only valid after this mock
0216   // method has been called.
0217   const char* name_;  // Protected by g_gmock_mutex.
0218 
0219   // All default action specs for this function mocker.
0220   UntypedOnCallSpecs untyped_on_call_specs_;
0221 
0222   // All expectations for this function mocker.
0223   //
0224   // It's undefined behavior to interleave expectations (EXPECT_CALLs
0225   // or ON_CALLs) and mock function calls.  Also, the order of
0226   // expectations is important.  Therefore it's a logic race condition
0227   // to read/write untyped_expectations_ concurrently.  In order for
0228   // tools like tsan to catch concurrent read/write accesses to
0229   // untyped_expectations, we deliberately leave accesses to it
0230   // unprotected.
0231   UntypedExpectations untyped_expectations_;
0232 };  // class UntypedFunctionMockerBase
0233 
0234 // Untyped base class for OnCallSpec<F>.
0235 class UntypedOnCallSpecBase {
0236  public:
0237   // The arguments are the location of the ON_CALL() statement.
0238   UntypedOnCallSpecBase(const char* a_file, int a_line)
0239       : file_(a_file), line_(a_line), last_clause_(kNone) {}
0240 
0241   // Where in the source file was the default action spec defined?
0242   const char* file() const { return file_; }
0243   int line() const { return line_; }
0244 
0245  protected:
0246   // Gives each clause in the ON_CALL() statement a name.
0247   enum Clause {
0248     // Do not change the order of the enum members!  The run-time
0249     // syntax checking relies on it.
0250     kNone,
0251     kWith,
0252     kWillByDefault
0253   };
0254 
0255   // Asserts that the ON_CALL() statement has a certain property.
0256   void AssertSpecProperty(bool property,
0257                           const std::string& failure_message) const {
0258     Assert(property, file_, line_, failure_message);
0259   }
0260 
0261   // Expects that the ON_CALL() statement has a certain property.
0262   void ExpectSpecProperty(bool property,
0263                           const std::string& failure_message) const {
0264     Expect(property, file_, line_, failure_message);
0265   }
0266 
0267   const char* file_;
0268   int line_;
0269 
0270   // The last clause in the ON_CALL() statement as seen so far.
0271   // Initially kNone and changes as the statement is parsed.
0272   Clause last_clause_;
0273 };  // class UntypedOnCallSpecBase
0274 
0275 // This template class implements an ON_CALL spec.
0276 template <typename F>
0277 class OnCallSpec : public UntypedOnCallSpecBase {
0278  public:
0279   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
0280   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
0281 
0282   // Constructs an OnCallSpec object from the information inside
0283   // the parenthesis of an ON_CALL() statement.
0284   OnCallSpec(const char* a_file, int a_line,
0285              const ArgumentMatcherTuple& matchers)
0286       : UntypedOnCallSpecBase(a_file, a_line),
0287         matchers_(matchers),
0288         // By default, extra_matcher_ should match anything.  However,
0289         // we cannot initialize it with _ as that causes ambiguity between
0290         // Matcher's copy and move constructor for some argument types.
0291         extra_matcher_(A<const ArgumentTuple&>()) {}
0292 
0293   // Implements the .With() clause.
0294   OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
0295     // Makes sure this is called at most once.
0296     ExpectSpecProperty(last_clause_ < kWith,
0297                        ".With() cannot appear "
0298                        "more than once in an ON_CALL().");
0299     last_clause_ = kWith;
0300 
0301     extra_matcher_ = m;
0302     return *this;
0303   }
0304 
0305   // Implements the .WillByDefault() clause.
0306   OnCallSpec& WillByDefault(const Action<F>& action) {
0307     ExpectSpecProperty(last_clause_ < kWillByDefault,
0308                        ".WillByDefault() must appear "
0309                        "exactly once in an ON_CALL().");
0310     last_clause_ = kWillByDefault;
0311 
0312     ExpectSpecProperty(!action.IsDoDefault(),
0313                        "DoDefault() cannot be used in ON_CALL().");
0314     action_ = action;
0315     return *this;
0316   }
0317 
0318   // Returns true if and only if the given arguments match the matchers.
0319   bool Matches(const ArgumentTuple& args) const {
0320     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
0321   }
0322 
0323   // Returns the action specified by the user.
0324   const Action<F>& GetAction() const {
0325     AssertSpecProperty(last_clause_ == kWillByDefault,
0326                        ".WillByDefault() must appear exactly "
0327                        "once in an ON_CALL().");
0328     return action_;
0329   }
0330 
0331  private:
0332   // The information in statement
0333   //
0334   //   ON_CALL(mock_object, Method(matchers))
0335   //       .With(multi-argument-matcher)
0336   //       .WillByDefault(action);
0337   //
0338   // is recorded in the data members like this:
0339   //
0340   //   source file that contains the statement => file_
0341   //   line number of the statement            => line_
0342   //   matchers                                => matchers_
0343   //   multi-argument-matcher                  => extra_matcher_
0344   //   action                                  => action_
0345   ArgumentMatcherTuple matchers_;
0346   Matcher<const ArgumentTuple&> extra_matcher_;
0347   Action<F> action_;
0348 };  // class OnCallSpec
0349 
0350 // Possible reactions on uninteresting calls.
0351 enum CallReaction {
0352   kAllow,
0353   kWarn,
0354   kFail,
0355 };
0356 
0357 }  // namespace internal
0358 
0359 // Utilities for manipulating mock objects.
0360 class GTEST_API_ Mock {
0361  public:
0362   // The following public methods can be called concurrently.
0363 
0364   // Tells Google Mock to ignore mock_obj when checking for leaked
0365   // mock objects.
0366   static void AllowLeak(const void* mock_obj)
0367       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0368 
0369   // Verifies and clears all expectations on the given mock object.
0370   // If the expectations aren't satisfied, generates one or more
0371   // Google Test non-fatal failures and returns false.
0372   static bool VerifyAndClearExpectations(void* mock_obj)
0373       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0374 
0375   // Verifies all expectations on the given mock object and clears its
0376   // default actions and expectations.  Returns true if and only if the
0377   // verification was successful.
0378   static bool VerifyAndClear(void* mock_obj)
0379       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0380 
0381   // Returns whether the mock was created as a naggy mock (default)
0382   static bool IsNaggy(void* mock_obj)
0383       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0384   // Returns whether the mock was created as a nice mock
0385   static bool IsNice(void* mock_obj)
0386       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0387   // Returns whether the mock was created as a strict mock
0388   static bool IsStrict(void* mock_obj)
0389       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0390 
0391  private:
0392   friend class internal::UntypedFunctionMockerBase;
0393 
0394   // Needed for a function mocker to register itself (so that we know
0395   // how to clear a mock object).
0396   template <typename F>
0397   friend class internal::FunctionMocker;
0398 
0399   template <typename MockClass>
0400   friend class internal::NiceMockImpl;
0401   template <typename MockClass>
0402   friend class internal::NaggyMockImpl;
0403   template <typename MockClass>
0404   friend class internal::StrictMockImpl;
0405 
0406   // Tells Google Mock to allow uninteresting calls on the given mock
0407   // object.
0408   static void AllowUninterestingCalls(uintptr_t mock_obj)
0409       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0410 
0411   // Tells Google Mock to warn the user about uninteresting calls on
0412   // the given mock object.
0413   static void WarnUninterestingCalls(uintptr_t mock_obj)
0414       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0415 
0416   // Tells Google Mock to fail uninteresting calls on the given mock
0417   // object.
0418   static void FailUninterestingCalls(uintptr_t mock_obj)
0419       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0420 
0421   // Tells Google Mock the given mock object is being destroyed and
0422   // its entry in the call-reaction table should be removed.
0423   static void UnregisterCallReaction(uintptr_t mock_obj)
0424       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0425 
0426   // Returns the reaction Google Mock will have on uninteresting calls
0427   // made on the given mock object.
0428   static internal::CallReaction GetReactionOnUninterestingCalls(
0429       const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0430 
0431   // Verifies that all expectations on the given mock object have been
0432   // satisfied.  Reports one or more Google Test non-fatal failures
0433   // and returns false if not.
0434   static bool VerifyAndClearExpectationsLocked(void* mock_obj)
0435       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
0436 
0437   // Clears all ON_CALL()s set on the given mock object.
0438   static void ClearDefaultActionsLocked(void* mock_obj)
0439       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
0440 
0441   // Registers a mock object and a mock method it owns.
0442   static void Register(const void* mock_obj,
0443                        internal::UntypedFunctionMockerBase* mocker)
0444       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0445 
0446   // Tells Google Mock where in the source code mock_obj is used in an
0447   // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
0448   // information helps the user identify which object it is.
0449   static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,
0450                                               const char* file, int line)
0451       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
0452 
0453   // Unregisters a mock method; removes the owning mock object from
0454   // the registry when the last mock method associated with it has
0455   // been unregistered.  This is called only in the destructor of
0456   // FunctionMocker.
0457   static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
0458       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
0459 };  // class Mock
0460 
0461 // An abstract handle of an expectation.  Useful in the .After()
0462 // clause of EXPECT_CALL() for setting the (partial) order of
0463 // expectations.  The syntax:
0464 //
0465 //   Expectation e1 = EXPECT_CALL(...)...;
0466 //   EXPECT_CALL(...).After(e1)...;
0467 //
0468 // sets two expectations where the latter can only be matched after
0469 // the former has been satisfied.
0470 //
0471 // Notes:
0472 //   - This class is copyable and has value semantics.
0473 //   - Constness is shallow: a const Expectation object itself cannot
0474 //     be modified, but the mutable methods of the ExpectationBase
0475 //     object it references can be called via expectation_base().
0476 
0477 class GTEST_API_ Expectation {
0478  public:
0479   // Constructs a null object that doesn't reference any expectation.
0480   Expectation();
0481   Expectation(Expectation&&) = default;
0482   Expectation(const Expectation&) = default;
0483   Expectation& operator=(Expectation&&) = default;
0484   Expectation& operator=(const Expectation&) = default;
0485   ~Expectation();
0486 
0487   // This single-argument ctor must not be explicit, in order to support the
0488   //   Expectation e = EXPECT_CALL(...);
0489   // syntax.
0490   //
0491   // A TypedExpectation object stores its pre-requisites as
0492   // Expectation objects, and needs to call the non-const Retire()
0493   // method on the ExpectationBase objects they reference.  Therefore
0494   // Expectation must receive a *non-const* reference to the
0495   // ExpectationBase object.
0496   Expectation(internal::ExpectationBase& exp);  // NOLINT
0497 
0498   // The compiler-generated copy ctor and operator= work exactly as
0499   // intended, so we don't need to define our own.
0500 
0501   // Returns true if and only if rhs references the same expectation as this
0502   // object does.
0503   bool operator==(const Expectation& rhs) const {
0504     return expectation_base_ == rhs.expectation_base_;
0505   }
0506 
0507   bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
0508 
0509  private:
0510   friend class ExpectationSet;
0511   friend class Sequence;
0512   friend class ::testing::internal::ExpectationBase;
0513   friend class ::testing::internal::UntypedFunctionMockerBase;
0514 
0515   template <typename F>
0516   friend class ::testing::internal::FunctionMocker;
0517 
0518   template <typename F>
0519   friend class ::testing::internal::TypedExpectation;
0520 
0521   // This comparator is needed for putting Expectation objects into a set.
0522   class Less {
0523    public:
0524     bool operator()(const Expectation& lhs, const Expectation& rhs) const {
0525       return lhs.expectation_base_.get() < rhs.expectation_base_.get();
0526     }
0527   };
0528 
0529   typedef ::std::set<Expectation, Less> Set;
0530 
0531   Expectation(
0532       const std::shared_ptr<internal::ExpectationBase>& expectation_base);
0533 
0534   // Returns the expectation this object references.
0535   const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
0536     return expectation_base_;
0537   }
0538 
0539   // A shared_ptr that co-owns the expectation this handle references.
0540   std::shared_ptr<internal::ExpectationBase> expectation_base_;
0541 };
0542 
0543 // A set of expectation handles.  Useful in the .After() clause of
0544 // EXPECT_CALL() for setting the (partial) order of expectations.  The
0545 // syntax:
0546 //
0547 //   ExpectationSet es;
0548 //   es += EXPECT_CALL(...)...;
0549 //   es += EXPECT_CALL(...)...;
0550 //   EXPECT_CALL(...).After(es)...;
0551 //
0552 // sets three expectations where the last one can only be matched
0553 // after the first two have both been satisfied.
0554 //
0555 // This class is copyable and has value semantics.
0556 class ExpectationSet {
0557  public:
0558   // A bidirectional iterator that can read a const element in the set.
0559   typedef Expectation::Set::const_iterator const_iterator;
0560 
0561   // An object stored in the set.  This is an alias of Expectation.
0562   typedef Expectation::Set::value_type value_type;
0563 
0564   // Constructs an empty set.
0565   ExpectationSet() {}
0566 
0567   // This single-argument ctor must not be explicit, in order to support the
0568   //   ExpectationSet es = EXPECT_CALL(...);
0569   // syntax.
0570   ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT
0571     *this += Expectation(exp);
0572   }
0573 
0574   // This single-argument ctor implements implicit conversion from
0575   // Expectation and thus must not be explicit.  This allows either an
0576   // Expectation or an ExpectationSet to be used in .After().
0577   ExpectationSet(const Expectation& e) {  // NOLINT
0578     *this += e;
0579   }
0580 
0581   // The compiler-generator ctor and operator= works exactly as
0582   // intended, so we don't need to define our own.
0583 
0584   // Returns true if and only if rhs contains the same set of Expectation
0585   // objects as this does.
0586   bool operator==(const ExpectationSet& rhs) const {
0587     return expectations_ == rhs.expectations_;
0588   }
0589 
0590   bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
0591 
0592   // Implements the syntax
0593   //   expectation_set += EXPECT_CALL(...);
0594   ExpectationSet& operator+=(const Expectation& e) {
0595     expectations_.insert(e);
0596     return *this;
0597   }
0598 
0599   int size() const { return static_cast<int>(expectations_.size()); }
0600 
0601   const_iterator begin() const { return expectations_.begin(); }
0602   const_iterator end() const { return expectations_.end(); }
0603 
0604  private:
0605   Expectation::Set expectations_;
0606 };
0607 
0608 // Sequence objects are used by a user to specify the relative order
0609 // in which the expectations should match.  They are copyable (we rely
0610 // on the compiler-defined copy constructor and assignment operator).
0611 class GTEST_API_ Sequence {
0612  public:
0613   // Constructs an empty sequence.
0614   Sequence() : last_expectation_(new Expectation) {}
0615 
0616   // Adds an expectation to this sequence.  The caller must ensure
0617   // that no other thread is accessing this Sequence object.
0618   void AddExpectation(const Expectation& expectation) const;
0619 
0620  private:
0621   // The last expectation in this sequence.
0622   std::shared_ptr<Expectation> last_expectation_;
0623 };  // class Sequence
0624 
0625 // An object of this type causes all EXPECT_CALL() statements
0626 // encountered in its scope to be put in an anonymous sequence.  The
0627 // work is done in the constructor and destructor.  You should only
0628 // create an InSequence object on the stack.
0629 //
0630 // The sole purpose for this class is to support easy definition of
0631 // sequential expectations, e.g.
0632 //
0633 //   {
0634 //     InSequence dummy;  // The name of the object doesn't matter.
0635 //
0636 //     // The following expectations must match in the order they appear.
0637 //     EXPECT_CALL(a, Bar())...;
0638 //     EXPECT_CALL(a, Baz())...;
0639 //     ...
0640 //     EXPECT_CALL(b, Xyz())...;
0641 //   }
0642 //
0643 // You can create InSequence objects in multiple threads, as long as
0644 // they are used to affect different mock objects.  The idea is that
0645 // each thread can create and set up its own mocks as if it's the only
0646 // thread.  However, for clarity of your tests we recommend you to set
0647 // up mocks in the main thread unless you have a good reason not to do
0648 // so.
0649 class GTEST_API_ InSequence {
0650  public:
0651   InSequence();
0652   ~InSequence();
0653 
0654  private:
0655   bool sequence_created_;
0656 
0657   InSequence(const InSequence&) = delete;
0658   InSequence& operator=(const InSequence&) = delete;
0659 } GTEST_ATTRIBUTE_UNUSED_;
0660 
0661 namespace internal {
0662 
0663 // Points to the implicit sequence introduced by a living InSequence
0664 // object (if any) in the current thread or NULL.
0665 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
0666 
0667 // Base class for implementing expectations.
0668 //
0669 // There are two reasons for having a type-agnostic base class for
0670 // Expectation:
0671 //
0672 //   1. We need to store collections of expectations of different
0673 //   types (e.g. all pre-requisites of a particular expectation, all
0674 //   expectations in a sequence).  Therefore these expectation objects
0675 //   must share a common base class.
0676 //
0677 //   2. We can avoid binary code bloat by moving methods not depending
0678 //   on the template argument of Expectation to the base class.
0679 //
0680 // This class is internal and mustn't be used by user code directly.
0681 class GTEST_API_ ExpectationBase {
0682  public:
0683   // source_text is the EXPECT_CALL(...) source that created this Expectation.
0684   ExpectationBase(const char* file, int line, const std::string& source_text);
0685 
0686   virtual ~ExpectationBase();
0687 
0688   // Where in the source file was the expectation spec defined?
0689   const char* file() const { return file_; }
0690   int line() const { return line_; }
0691   const char* source_text() const { return source_text_.c_str(); }
0692   // Returns the cardinality specified in the expectation spec.
0693   const Cardinality& cardinality() const { return cardinality_; }
0694 
0695   // Describes the source file location of this expectation.
0696   void DescribeLocationTo(::std::ostream* os) const {
0697     *os << FormatFileLocation(file(), line()) << " ";
0698   }
0699 
0700   // Describes how many times a function call matching this
0701   // expectation has occurred.
0702   void DescribeCallCountTo(::std::ostream* os) const
0703       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0704 
0705   // If this mock method has an extra matcher (i.e. .With(matcher)),
0706   // describes it to the ostream.
0707   virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
0708 
0709  protected:
0710   friend class ::testing::Expectation;
0711   friend class UntypedFunctionMockerBase;
0712 
0713   enum Clause {
0714     // Don't change the order of the enum members!
0715     kNone,
0716     kWith,
0717     kTimes,
0718     kInSequence,
0719     kAfter,
0720     kWillOnce,
0721     kWillRepeatedly,
0722     kRetiresOnSaturation
0723   };
0724 
0725   typedef std::vector<const void*> UntypedActions;
0726 
0727   // Returns an Expectation object that references and co-owns this
0728   // expectation.
0729   virtual Expectation GetHandle() = 0;
0730 
0731   // Asserts that the EXPECT_CALL() statement has the given property.
0732   void AssertSpecProperty(bool property,
0733                           const std::string& failure_message) const {
0734     Assert(property, file_, line_, failure_message);
0735   }
0736 
0737   // Expects that the EXPECT_CALL() statement has the given property.
0738   void ExpectSpecProperty(bool property,
0739                           const std::string& failure_message) const {
0740     Expect(property, file_, line_, failure_message);
0741   }
0742 
0743   // Explicitly specifies the cardinality of this expectation.  Used
0744   // by the subclasses to implement the .Times() clause.
0745   void SpecifyCardinality(const Cardinality& cardinality);
0746 
0747   // Returns true if and only if the user specified the cardinality
0748   // explicitly using a .Times().
0749   bool cardinality_specified() const { return cardinality_specified_; }
0750 
0751   // Sets the cardinality of this expectation spec.
0752   void set_cardinality(const Cardinality& a_cardinality) {
0753     cardinality_ = a_cardinality;
0754   }
0755 
0756   // The following group of methods should only be called after the
0757   // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
0758   // the current thread.
0759 
0760   // Retires all pre-requisites of this expectation.
0761   void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0762 
0763   // Returns true if and only if this expectation is retired.
0764   bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0765     g_gmock_mutex.AssertHeld();
0766     return retired_;
0767   }
0768 
0769   // Retires this expectation.
0770   void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0771     g_gmock_mutex.AssertHeld();
0772     retired_ = true;
0773   }
0774 
0775   // Returns true if and only if this expectation is satisfied.
0776   bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0777     g_gmock_mutex.AssertHeld();
0778     return cardinality().IsSatisfiedByCallCount(call_count_);
0779   }
0780 
0781   // Returns true if and only if this expectation is saturated.
0782   bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0783     g_gmock_mutex.AssertHeld();
0784     return cardinality().IsSaturatedByCallCount(call_count_);
0785   }
0786 
0787   // Returns true if and only if this expectation is over-saturated.
0788   bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0789     g_gmock_mutex.AssertHeld();
0790     return cardinality().IsOverSaturatedByCallCount(call_count_);
0791   }
0792 
0793   // Returns true if and only if all pre-requisites of this expectation are
0794   // satisfied.
0795   bool AllPrerequisitesAreSatisfied() const
0796       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0797 
0798   // Adds unsatisfied pre-requisites of this expectation to 'result'.
0799   void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
0800       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
0801 
0802   // Returns the number this expectation has been invoked.
0803   int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0804     g_gmock_mutex.AssertHeld();
0805     return call_count_;
0806   }
0807 
0808   // Increments the number this expectation has been invoked.
0809   void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0810     g_gmock_mutex.AssertHeld();
0811     call_count_++;
0812   }
0813 
0814   // Checks the action count (i.e. the number of WillOnce() and
0815   // WillRepeatedly() clauses) against the cardinality if this hasn't
0816   // been done before.  Prints a warning if there are too many or too
0817   // few actions.
0818   void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);
0819 
0820   friend class ::testing::Sequence;
0821   friend class ::testing::internal::ExpectationTester;
0822 
0823   template <typename Function>
0824   friend class TypedExpectation;
0825 
0826   // Implements the .Times() clause.
0827   void UntypedTimes(const Cardinality& a_cardinality);
0828 
0829   // This group of fields are part of the spec and won't change after
0830   // an EXPECT_CALL() statement finishes.
0831   const char* file_;               // The file that contains the expectation.
0832   int line_;                       // The line number of the expectation.
0833   const std::string source_text_;  // The EXPECT_CALL(...) source text.
0834   // True if and only if the cardinality is specified explicitly.
0835   bool cardinality_specified_;
0836   Cardinality cardinality_;  // The cardinality of the expectation.
0837   // The immediate pre-requisites (i.e. expectations that must be
0838   // satisfied before this expectation can be matched) of this
0839   // expectation.  We use std::shared_ptr in the set because we want an
0840   // Expectation object to be co-owned by its FunctionMocker and its
0841   // successors.  This allows multiple mock objects to be deleted at
0842   // different times.
0843   ExpectationSet immediate_prerequisites_;
0844 
0845   // This group of fields are the current state of the expectation,
0846   // and can change as the mock function is called.
0847   int call_count_;  // How many times this expectation has been invoked.
0848   bool retired_;    // True if and only if this expectation has retired.
0849   UntypedActions untyped_actions_;
0850   bool extra_matcher_specified_;
0851   bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.
0852   bool retires_on_saturation_;
0853   Clause last_clause_;
0854   mutable bool action_count_checked_;  // Under mutex_.
0855   mutable Mutex mutex_;                // Protects action_count_checked_.
0856 };                                     // class ExpectationBase
0857 
0858 template <typename F>
0859 class TypedExpectation;
0860 
0861 // Implements an expectation for the given function type.
0862 template <typename R, typename... Args>
0863 class TypedExpectation<R(Args...)> : public ExpectationBase {
0864  private:
0865   using F = R(Args...);
0866 
0867  public:
0868   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
0869   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
0870   typedef typename Function<F>::Result Result;
0871 
0872   TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
0873                    const std::string& a_source_text,
0874                    const ArgumentMatcherTuple& m)
0875       : ExpectationBase(a_file, a_line, a_source_text),
0876         owner_(owner),
0877         matchers_(m),
0878         // By default, extra_matcher_ should match anything.  However,
0879         // we cannot initialize it with _ as that causes ambiguity between
0880         // Matcher's copy and move constructor for some argument types.
0881         extra_matcher_(A<const ArgumentTuple&>()),
0882         repeated_action_(DoDefault()) {}
0883 
0884   ~TypedExpectation() override {
0885     // Check the validity of the action count if it hasn't been done
0886     // yet (for example, if the expectation was never used).
0887     CheckActionCountIfNotDone();
0888     for (UntypedActions::const_iterator it = untyped_actions_.begin();
0889          it != untyped_actions_.end(); ++it) {
0890       delete static_cast<const Action<F>*>(*it);
0891     }
0892   }
0893 
0894   // Implements the .With() clause.
0895   TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
0896     if (last_clause_ == kWith) {
0897       ExpectSpecProperty(false,
0898                          ".With() cannot appear "
0899                          "more than once in an EXPECT_CALL().");
0900     } else {
0901       ExpectSpecProperty(last_clause_ < kWith,
0902                          ".With() must be the first "
0903                          "clause in an EXPECT_CALL().");
0904     }
0905     last_clause_ = kWith;
0906 
0907     extra_matcher_ = m;
0908     extra_matcher_specified_ = true;
0909     return *this;
0910   }
0911 
0912   // Implements the .Times() clause.
0913   TypedExpectation& Times(const Cardinality& a_cardinality) {
0914     ExpectationBase::UntypedTimes(a_cardinality);
0915     return *this;
0916   }
0917 
0918   // Implements the .Times() clause.
0919   TypedExpectation& Times(int n) { return Times(Exactly(n)); }
0920 
0921   // Implements the .InSequence() clause.
0922   TypedExpectation& InSequence(const Sequence& s) {
0923     ExpectSpecProperty(last_clause_ <= kInSequence,
0924                        ".InSequence() cannot appear after .After(),"
0925                        " .WillOnce(), .WillRepeatedly(), or "
0926                        ".RetiresOnSaturation().");
0927     last_clause_ = kInSequence;
0928 
0929     s.AddExpectation(GetHandle());
0930     return *this;
0931   }
0932   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
0933     return InSequence(s1).InSequence(s2);
0934   }
0935   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
0936                                const Sequence& s3) {
0937     return InSequence(s1, s2).InSequence(s3);
0938   }
0939   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
0940                                const Sequence& s3, const Sequence& s4) {
0941     return InSequence(s1, s2, s3).InSequence(s4);
0942   }
0943   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
0944                                const Sequence& s3, const Sequence& s4,
0945                                const Sequence& s5) {
0946     return InSequence(s1, s2, s3, s4).InSequence(s5);
0947   }
0948 
0949   // Implements that .After() clause.
0950   TypedExpectation& After(const ExpectationSet& s) {
0951     ExpectSpecProperty(last_clause_ <= kAfter,
0952                        ".After() cannot appear after .WillOnce(),"
0953                        " .WillRepeatedly(), or "
0954                        ".RetiresOnSaturation().");
0955     last_clause_ = kAfter;
0956 
0957     for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
0958       immediate_prerequisites_ += *it;
0959     }
0960     return *this;
0961   }
0962   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
0963     return After(s1).After(s2);
0964   }
0965   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
0966                           const ExpectationSet& s3) {
0967     return After(s1, s2).After(s3);
0968   }
0969   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
0970                           const ExpectationSet& s3, const ExpectationSet& s4) {
0971     return After(s1, s2, s3).After(s4);
0972   }
0973   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
0974                           const ExpectationSet& s3, const ExpectationSet& s4,
0975                           const ExpectationSet& s5) {
0976     return After(s1, s2, s3, s4).After(s5);
0977   }
0978 
0979   // Preferred, type-safe overload: consume anything that can be directly
0980   // converted to a OnceAction, except for Action<F> objects themselves.
0981   TypedExpectation& WillOnce(OnceAction<F> once_action) {
0982     // Call the overload below, smuggling the OnceAction as a copyable callable.
0983     // We know this is safe because a WillOnce action will not be called more
0984     // than once.
0985     return WillOnce(Action<F>(ActionAdaptor{
0986         std::make_shared<OnceAction<F>>(std::move(once_action)),
0987     }));
0988   }
0989 
0990   // Fallback overload: accept Action<F> objects and those actions that define
0991   // `operator Action<F>` but not `operator OnceAction<F>`.
0992   //
0993   // This is templated in order to cause the overload above to be preferred
0994   // when the input is convertible to either type.
0995   template <int&... ExplicitArgumentBarrier, typename = void>
0996   TypedExpectation& WillOnce(Action<F> action) {
0997     ExpectSpecProperty(last_clause_ <= kWillOnce,
0998                        ".WillOnce() cannot appear after "
0999                        ".WillRepeatedly() or .RetiresOnSaturation().");
1000     last_clause_ = kWillOnce;
1001 
1002     untyped_actions_.push_back(new Action<F>(std::move(action)));
1003 
1004     if (!cardinality_specified()) {
1005       set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1006     }
1007     return *this;
1008   }
1009 
1010   // Implements the .WillRepeatedly() clause.
1011   TypedExpectation& WillRepeatedly(const Action<F>& action) {
1012     if (last_clause_ == kWillRepeatedly) {
1013       ExpectSpecProperty(false,
1014                          ".WillRepeatedly() cannot appear "
1015                          "more than once in an EXPECT_CALL().");
1016     } else {
1017       ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1018                          ".WillRepeatedly() cannot appear "
1019                          "after .RetiresOnSaturation().");
1020     }
1021     last_clause_ = kWillRepeatedly;
1022     repeated_action_specified_ = true;
1023 
1024     repeated_action_ = action;
1025     if (!cardinality_specified()) {
1026       set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1027     }
1028 
1029     // Now that no more action clauses can be specified, we check
1030     // whether their count makes sense.
1031     CheckActionCountIfNotDone();
1032     return *this;
1033   }
1034 
1035   // Implements the .RetiresOnSaturation() clause.
1036   TypedExpectation& RetiresOnSaturation() {
1037     ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1038                        ".RetiresOnSaturation() cannot appear "
1039                        "more than once.");
1040     last_clause_ = kRetiresOnSaturation;
1041     retires_on_saturation_ = true;
1042 
1043     // Now that no more action clauses can be specified, we check
1044     // whether their count makes sense.
1045     CheckActionCountIfNotDone();
1046     return *this;
1047   }
1048 
1049   // Returns the matchers for the arguments as specified inside the
1050   // EXPECT_CALL() macro.
1051   const ArgumentMatcherTuple& matchers() const { return matchers_; }
1052 
1053   // Returns the matcher specified by the .With() clause.
1054   const Matcher<const ArgumentTuple&>& extra_matcher() const {
1055     return extra_matcher_;
1056   }
1057 
1058   // Returns the action specified by the .WillRepeatedly() clause.
1059   const Action<F>& repeated_action() const { return repeated_action_; }
1060 
1061   // If this mock method has an extra matcher (i.e. .With(matcher)),
1062   // describes it to the ostream.
1063   void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
1064     if (extra_matcher_specified_) {
1065       *os << "    Expected args: ";
1066       extra_matcher_.DescribeTo(os);
1067       *os << "\n";
1068     }
1069   }
1070 
1071  private:
1072   template <typename Function>
1073   friend class FunctionMocker;
1074 
1075   // An adaptor that turns a OneAction<F> into something compatible with
1076   // Action<F>. Must be called at most once.
1077   struct ActionAdaptor {
1078     std::shared_ptr<OnceAction<R(Args...)>> once_action;
1079 
1080     R operator()(Args&&... args) const {
1081       return std::move(*once_action).Call(std::forward<Args>(args)...);
1082     }
1083   };
1084 
1085   // Returns an Expectation object that references and co-owns this
1086   // expectation.
1087   Expectation GetHandle() override { return owner_->GetHandleOf(this); }
1088 
1089   // The following methods will be called only after the EXPECT_CALL()
1090   // statement finishes and when the current thread holds
1091   // g_gmock_mutex.
1092 
1093   // Returns true if and only if this expectation matches the given arguments.
1094   bool Matches(const ArgumentTuple& args) const
1095       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1096     g_gmock_mutex.AssertHeld();
1097     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1098   }
1099 
1100   // Returns true if and only if this expectation should handle the given
1101   // arguments.
1102   bool ShouldHandleArguments(const ArgumentTuple& args) const
1103       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1104     g_gmock_mutex.AssertHeld();
1105 
1106     // In case the action count wasn't checked when the expectation
1107     // was defined (e.g. if this expectation has no WillRepeatedly()
1108     // or RetiresOnSaturation() clause), we check it when the
1109     // expectation is used for the first time.
1110     CheckActionCountIfNotDone();
1111     return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1112   }
1113 
1114   // Describes the result of matching the arguments against this
1115   // expectation to the given ostream.
1116   void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const
1117       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1118     g_gmock_mutex.AssertHeld();
1119 
1120     if (is_retired()) {
1121       *os << "         Expected: the expectation is active\n"
1122           << "           Actual: it is retired\n";
1123     } else if (!Matches(args)) {
1124       if (!TupleMatches(matchers_, args)) {
1125         ExplainMatchFailureTupleTo(matchers_, args, os);
1126       }
1127       StringMatchResultListener listener;
1128       if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1129         *os << "    Expected args: ";
1130         extra_matcher_.DescribeTo(os);
1131         *os << "\n           Actual: don't match";
1132 
1133         internal::PrintIfNotEmpty(listener.str(), os);
1134         *os << "\n";
1135       }
1136     } else if (!AllPrerequisitesAreSatisfied()) {
1137       *os << "         Expected: all pre-requisites are satisfied\n"
1138           << "           Actual: the following immediate pre-requisites "
1139           << "are not satisfied:\n";
1140       ExpectationSet unsatisfied_prereqs;
1141       FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1142       int i = 0;
1143       for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1144            it != unsatisfied_prereqs.end(); ++it) {
1145         it->expectation_base()->DescribeLocationTo(os);
1146         *os << "pre-requisite #" << i++ << "\n";
1147       }
1148       *os << "                   (end of pre-requisites)\n";
1149     } else {
1150       // This line is here just for completeness' sake.  It will never
1151       // be executed as currently the ExplainMatchResultTo() function
1152       // is called only when the mock function call does NOT match the
1153       // expectation.
1154       *os << "The call matches the expectation.\n";
1155     }
1156   }
1157 
1158   // Returns the action that should be taken for the current invocation.
1159   const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
1160                                     const ArgumentTuple& args) const
1161       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1162     g_gmock_mutex.AssertHeld();
1163     const int count = call_count();
1164     Assert(count >= 1, __FILE__, __LINE__,
1165            "call_count() is <= 0 when GetCurrentAction() is "
1166            "called - this should never happen.");
1167 
1168     const int action_count = static_cast<int>(untyped_actions_.size());
1169     if (action_count > 0 && !repeated_action_specified_ &&
1170         count > action_count) {
1171       // If there is at least one WillOnce() and no WillRepeatedly(),
1172       // we warn the user when the WillOnce() clauses ran out.
1173       ::std::stringstream ss;
1174       DescribeLocationTo(&ss);
1175       ss << "Actions ran out in " << source_text() << "...\n"
1176          << "Called " << count << " times, but only " << action_count
1177          << " WillOnce()" << (action_count == 1 ? " is" : "s are")
1178          << " specified - ";
1179       mocker->DescribeDefaultActionTo(args, &ss);
1180       Log(kWarning, ss.str(), 1);
1181     }
1182 
1183     return count <= action_count
1184                ? *static_cast<const Action<F>*>(
1185                      untyped_actions_[static_cast<size_t>(count - 1)])
1186                : repeated_action();
1187   }
1188 
1189   // Given the arguments of a mock function call, if the call will
1190   // over-saturate this expectation, returns the default action;
1191   // otherwise, returns the next action in this expectation.  Also
1192   // describes *what* happened to 'what', and explains *why* Google
1193   // Mock does it to 'why'.  This method is not const as it calls
1194   // IncrementCallCount().  A return value of NULL means the default
1195   // action.
1196   const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
1197                                          const ArgumentTuple& args,
1198                                          ::std::ostream* what,
1199                                          ::std::ostream* why)
1200       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1201     g_gmock_mutex.AssertHeld();
1202     if (IsSaturated()) {
1203       // We have an excessive call.
1204       IncrementCallCount();
1205       *what << "Mock function called more times than expected - ";
1206       mocker->DescribeDefaultActionTo(args, what);
1207       DescribeCallCountTo(why);
1208 
1209       return nullptr;
1210     }
1211 
1212     IncrementCallCount();
1213     RetireAllPreRequisites();
1214 
1215     if (retires_on_saturation_ && IsSaturated()) {
1216       Retire();
1217     }
1218 
1219     // Must be done after IncrementCount()!
1220     *what << "Mock function call matches " << source_text() << "...\n";
1221     return &(GetCurrentAction(mocker, args));
1222   }
1223 
1224   // All the fields below won't change once the EXPECT_CALL()
1225   // statement finishes.
1226   FunctionMocker<F>* const owner_;
1227   ArgumentMatcherTuple matchers_;
1228   Matcher<const ArgumentTuple&> extra_matcher_;
1229   Action<F> repeated_action_;
1230 
1231   TypedExpectation(const TypedExpectation&) = delete;
1232   TypedExpectation& operator=(const TypedExpectation&) = delete;
1233 };  // class TypedExpectation
1234 
1235 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1236 // specifying the default behavior of, or expectation on, a mock
1237 // function.
1238 
1239 // Note: class MockSpec really belongs to the ::testing namespace.
1240 // However if we define it in ::testing, MSVC will complain when
1241 // classes in ::testing::internal declare it as a friend class
1242 // template.  To workaround this compiler bug, we define MockSpec in
1243 // ::testing::internal and import it into ::testing.
1244 
1245 // Logs a message including file and line number information.
1246 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1247                                 const char* file, int line,
1248                                 const std::string& message);
1249 
1250 template <typename F>
1251 class MockSpec {
1252  public:
1253   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1254   typedef
1255       typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1256 
1257   // Constructs a MockSpec object, given the function mocker object
1258   // that the spec is associated with.
1259   MockSpec(internal::FunctionMocker<F>* function_mocker,
1260            const ArgumentMatcherTuple& matchers)
1261       : function_mocker_(function_mocker), matchers_(matchers) {}
1262 
1263   // Adds a new default action spec to the function mocker and returns
1264   // the newly created spec.
1265   internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,
1266                                                       int line, const char* obj,
1267                                                       const char* call) {
1268     LogWithLocation(internal::kInfo, file, line,
1269                     std::string("ON_CALL(") + obj + ", " + call + ") invoked");
1270     return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1271   }
1272 
1273   // Adds a new expectation spec to the function mocker and returns
1274   // the newly created spec.
1275   internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,
1276                                                     const char* obj,
1277                                                     const char* call) {
1278     const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1279                                   call + ")");
1280     LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1281     return function_mocker_->AddNewExpectation(file, line, source_text,
1282                                                matchers_);
1283   }
1284 
1285   // This operator overload is used to swallow the superfluous parameter list
1286   // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1287   // explanation.
1288   MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1289     return *this;
1290   }
1291 
1292  private:
1293   template <typename Function>
1294   friend class internal::FunctionMocker;
1295 
1296   // The function mocker that owns this spec.
1297   internal::FunctionMocker<F>* const function_mocker_;
1298   // The argument matchers specified in the spec.
1299   ArgumentMatcherTuple matchers_;
1300 };  // class MockSpec
1301 
1302 // Wrapper type for generically holding an ordinary value or lvalue reference.
1303 // If T is not a reference type, it must be copyable or movable.
1304 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1305 // T is a move-only value type (which means that it will always be copyable
1306 // if the current platform does not support move semantics).
1307 //
1308 // The primary template defines handling for values, but function header
1309 // comments describe the contract for the whole template (including
1310 // specializations).
1311 template <typename T>
1312 class ReferenceOrValueWrapper {
1313  public:
1314   // Constructs a wrapper from the given value/reference.
1315   explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
1316 
1317   // Unwraps and returns the underlying value/reference, exactly as
1318   // originally passed. The behavior of calling this more than once on
1319   // the same object is unspecified.
1320   T Unwrap() { return std::move(value_); }
1321 
1322   // Provides nondestructive access to the underlying value/reference.
1323   // Always returns a const reference (more precisely,
1324   // const std::add_lvalue_reference<T>::type). The behavior of calling this
1325   // after calling Unwrap on the same object is unspecified.
1326   const T& Peek() const { return value_; }
1327 
1328  private:
1329   T value_;
1330 };
1331 
1332 // Specialization for lvalue reference types. See primary template
1333 // for documentation.
1334 template <typename T>
1335 class ReferenceOrValueWrapper<T&> {
1336  public:
1337   // Workaround for debatable pass-by-reference lint warning (c-library-team
1338   // policy precludes NOLINT in this context)
1339   typedef T& reference;
1340   explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
1341   T& Unwrap() { return *value_ptr_; }
1342   const T& Peek() const { return *value_ptr_; }
1343 
1344  private:
1345   T* value_ptr_;
1346 };
1347 
1348 // Prints the held value as an action's result to os.
1349 template <typename T>
1350 void PrintAsActionResult(const T& result, std::ostream& os) {
1351   os << "\n          Returns: ";
1352   // T may be a reference type, so we don't use UniversalPrint().
1353   UniversalPrinter<T>::Print(result, &os);
1354 }
1355 
1356 // Reports an uninteresting call (whose description is in msg) in the
1357 // manner specified by 'reaction'.
1358 GTEST_API_ void ReportUninterestingCall(CallReaction reaction,
1359                                         const std::string& msg);
1360 
1361 // A generic RAII type that runs a user-provided function in its destructor.
1362 class Cleanup final {
1363  public:
1364   explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}
1365   ~Cleanup() { f_(); }
1366 
1367  private:
1368   std::function<void()> f_;
1369 };
1370 
1371 template <typename F>
1372 class FunctionMocker;
1373 
1374 template <typename R, typename... Args>
1375 class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
1376   using F = R(Args...);
1377 
1378  public:
1379   using Result = R;
1380   using ArgumentTuple = std::tuple<Args...>;
1381   using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1382 
1383   FunctionMocker() {}
1384 
1385   // There is no generally useful and implementable semantics of
1386   // copying a mock object, so copying a mock is usually a user error.
1387   // Thus we disallow copying function mockers.  If the user really
1388   // wants to copy a mock object, they should implement their own copy
1389   // operation, for example:
1390   //
1391   //   class MockFoo : public Foo {
1392   //    public:
1393   //     // Defines a copy constructor explicitly.
1394   //     MockFoo(const MockFoo& src) {}
1395   //     ...
1396   //   };
1397   FunctionMocker(const FunctionMocker&) = delete;
1398   FunctionMocker& operator=(const FunctionMocker&) = delete;
1399 
1400   // The destructor verifies that all expectations on this mock
1401   // function have been satisfied.  If not, it will report Google Test
1402   // non-fatal failures for the violations.
1403   ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1404     MutexLock l(&g_gmock_mutex);
1405     VerifyAndClearExpectationsLocked();
1406     Mock::UnregisterLocked(this);
1407     ClearDefaultActionsLocked();
1408   }
1409 
1410   // Returns the ON_CALL spec that matches this mock function with the
1411   // given arguments; returns NULL if no matching ON_CALL is found.
1412   // L = *
1413   const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {
1414     for (UntypedOnCallSpecs::const_reverse_iterator it =
1415              untyped_on_call_specs_.rbegin();
1416          it != untyped_on_call_specs_.rend(); ++it) {
1417       const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1418       if (spec->Matches(args)) return spec;
1419     }
1420 
1421     return nullptr;
1422   }
1423 
1424   // Performs the default action of this mock function on the given
1425   // arguments and returns the result. Asserts (or throws if
1426   // exceptions are enabled) with a helpful call description if there
1427   // is no valid return value. This method doesn't depend on the
1428   // mutable state of this object, and thus can be called concurrently
1429   // without locking.
1430   // L = *
1431   Result PerformDefaultAction(ArgumentTuple&& args,
1432                               const std::string& call_description) const {
1433     const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);
1434     if (spec != nullptr) {
1435       return spec->GetAction().Perform(std::move(args));
1436     }
1437     const std::string message =
1438         call_description +
1439         "\n    The mock function has no default action "
1440         "set, and its return type has no default value set.";
1441 #if GTEST_HAS_EXCEPTIONS
1442     if (!DefaultValue<Result>::Exists()) {
1443       throw std::runtime_error(message);
1444     }
1445 #else
1446     Assert(DefaultValue<Result>::Exists(), "", -1, message);
1447 #endif
1448     return DefaultValue<Result>::Get();
1449   }
1450 
1451   // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1452   // clears the ON_CALL()s set on this mock function.
1453   void ClearDefaultActionsLocked() override
1454       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1455     g_gmock_mutex.AssertHeld();
1456 
1457     // Deleting our default actions may trigger other mock objects to be
1458     // deleted, for example if an action contains a reference counted smart
1459     // pointer to that mock object, and that is the last reference. So if we
1460     // delete our actions within the context of the global mutex we may deadlock
1461     // when this method is called again. Instead, make a copy of the set of
1462     // actions to delete, clear our set within the mutex, and then delete the
1463     // actions outside of the mutex.
1464     UntypedOnCallSpecs specs_to_delete;
1465     untyped_on_call_specs_.swap(specs_to_delete);
1466 
1467     g_gmock_mutex.Unlock();
1468     for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
1469          it != specs_to_delete.end(); ++it) {
1470       delete static_cast<const OnCallSpec<F>*>(*it);
1471     }
1472 
1473     // Lock the mutex again, since the caller expects it to be locked when we
1474     // return.
1475     g_gmock_mutex.Lock();
1476   }
1477 
1478   // Returns the result of invoking this mock function with the given
1479   // arguments.  This function can be safely called from multiple
1480   // threads concurrently.
1481   Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1482     return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));
1483   }
1484 
1485   MockSpec<F> With(Matcher<Args>... m) {
1486     return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
1487   }
1488 
1489  protected:
1490   template <typename Function>
1491   friend class MockSpec;
1492 
1493   // Adds and returns a default action spec for this mock function.
1494   OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
1495                                   const ArgumentMatcherTuple& m)
1496       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1497     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1498     OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1499     untyped_on_call_specs_.push_back(on_call_spec);
1500     return *on_call_spec;
1501   }
1502 
1503   // Adds and returns an expectation spec for this mock function.
1504   TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1505                                          const std::string& source_text,
1506                                          const ArgumentMatcherTuple& m)
1507       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1508     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1509     TypedExpectation<F>* const expectation =
1510         new TypedExpectation<F>(this, file, line, source_text, m);
1511     const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1512     // See the definition of untyped_expectations_ for why access to
1513     // it is unprotected here.
1514     untyped_expectations_.push_back(untyped_expectation);
1515 
1516     // Adds this expectation into the implicit sequence if there is one.
1517     Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1518     if (implicit_sequence != nullptr) {
1519       implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1520     }
1521 
1522     return *expectation;
1523   }
1524 
1525  private:
1526   template <typename Func>
1527   friend class TypedExpectation;
1528 
1529   // Some utilities needed for implementing UntypedInvokeWith().
1530 
1531   // Describes what default action will be performed for the given
1532   // arguments.
1533   // L = *
1534   void DescribeDefaultActionTo(const ArgumentTuple& args,
1535                                ::std::ostream* os) const {
1536     const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1537 
1538     if (spec == nullptr) {
1539       *os << (std::is_void<Result>::value ? "returning directly.\n"
1540                                           : "returning default value.\n");
1541     } else {
1542       *os << "taking default action specified at:\n"
1543           << FormatFileLocation(spec->file(), spec->line()) << "\n";
1544     }
1545   }
1546 
1547   // Writes a message that the call is uninteresting (i.e. neither
1548   // explicitly expected nor explicitly unexpected) to the given
1549   // ostream.
1550   void UntypedDescribeUninterestingCall(const void* untyped_args,
1551                                         ::std::ostream* os) const override
1552       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1553     const ArgumentTuple& args =
1554         *static_cast<const ArgumentTuple*>(untyped_args);
1555     *os << "Uninteresting mock function call - ";
1556     DescribeDefaultActionTo(args, os);
1557     *os << "    Function call: " << Name();
1558     UniversalPrint(args, os);
1559   }
1560 
1561   // Returns the expectation that matches the given function arguments
1562   // (or NULL is there's no match); when a match is found,
1563   // untyped_action is set to point to the action that should be
1564   // performed (or NULL if the action is "do default"), and
1565   // is_excessive is modified to indicate whether the call exceeds the
1566   // expected number.
1567   //
1568   // Critical section: We must find the matching expectation and the
1569   // corresponding action that needs to be taken in an ATOMIC
1570   // transaction.  Otherwise another thread may call this mock
1571   // method in the middle and mess up the state.
1572   //
1573   // However, performing the action has to be left out of the critical
1574   // section.  The reason is that we have no control on what the
1575   // action does (it can invoke an arbitrary user function or even a
1576   // mock function) and excessive locking could cause a dead lock.
1577   const ExpectationBase* UntypedFindMatchingExpectation(
1578       const void* untyped_args, const void** untyped_action, bool* is_excessive,
1579       ::std::ostream* what, ::std::ostream* why) override
1580       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1581     const ArgumentTuple& args =
1582         *static_cast<const ArgumentTuple*>(untyped_args);
1583     MutexLock l(&g_gmock_mutex);
1584     TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1585     if (exp == nullptr) {  // A match wasn't found.
1586       this->FormatUnexpectedCallMessageLocked(args, what, why);
1587       return nullptr;
1588     }
1589 
1590     // This line must be done before calling GetActionForArguments(),
1591     // which will increment the call count for *exp and thus affect
1592     // its saturation status.
1593     *is_excessive = exp->IsSaturated();
1594     const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1595     if (action != nullptr && action->IsDoDefault())
1596       action = nullptr;  // Normalize "do default" to NULL.
1597     *untyped_action = action;
1598     return exp;
1599   }
1600 
1601   // Prints the given function arguments to the ostream.
1602   void UntypedPrintArgs(const void* untyped_args,
1603                         ::std::ostream* os) const override {
1604     const ArgumentTuple& args =
1605         *static_cast<const ArgumentTuple*>(untyped_args);
1606     UniversalPrint(args, os);
1607   }
1608 
1609   // Returns the expectation that matches the arguments, or NULL if no
1610   // expectation matches them.
1611   TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)
1612       const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1613     g_gmock_mutex.AssertHeld();
1614     // See the definition of untyped_expectations_ for why access to
1615     // it is unprotected here.
1616     for (typename UntypedExpectations::const_reverse_iterator it =
1617              untyped_expectations_.rbegin();
1618          it != untyped_expectations_.rend(); ++it) {
1619       TypedExpectation<F>* const exp =
1620           static_cast<TypedExpectation<F>*>(it->get());
1621       if (exp->ShouldHandleArguments(args)) {
1622         return exp;
1623       }
1624     }
1625     return nullptr;
1626   }
1627 
1628   // Returns a message that the arguments don't match any expectation.
1629   void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1630                                          ::std::ostream* os,
1631                                          ::std::ostream* why) const
1632       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1633     g_gmock_mutex.AssertHeld();
1634     *os << "\nUnexpected mock function call - ";
1635     DescribeDefaultActionTo(args, os);
1636     PrintTriedExpectationsLocked(args, why);
1637   }
1638 
1639   // Prints a list of expectations that have been tried against the
1640   // current mock function call.
1641   void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1642                                     ::std::ostream* why) const
1643       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1644     g_gmock_mutex.AssertHeld();
1645     const size_t count = untyped_expectations_.size();
1646     *why << "Google Mock tried the following " << count << " "
1647          << (count == 1 ? "expectation, but it didn't match"
1648                         : "expectations, but none matched")
1649          << ":\n";
1650     for (size_t i = 0; i < count; i++) {
1651       TypedExpectation<F>* const expectation =
1652           static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1653       *why << "\n";
1654       expectation->DescribeLocationTo(why);
1655       if (count > 1) {
1656         *why << "tried expectation #" << i << ": ";
1657       }
1658       *why << expectation->source_text() << "...\n";
1659       expectation->ExplainMatchResultTo(args, why);
1660       expectation->DescribeCallCountTo(why);
1661     }
1662   }
1663 
1664   // Performs the given action (or the default if it's null) with the given
1665   // arguments and returns the action's result.
1666   // L = *
1667   R PerformAction(const void* untyped_action, ArgumentTuple&& args,
1668                   const std::string& call_description) const {
1669     if (untyped_action == nullptr) {
1670       return PerformDefaultAction(std::move(args), call_description);
1671     }
1672 
1673     // Make a copy of the action before performing it, in case the
1674     // action deletes the mock object (and thus deletes itself).
1675     const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1676     return action.Perform(std::move(args));
1677   }
1678 
1679   // Is it possible to store an object of the supplied type in a local variable
1680   // for the sake of printing it, then return it on to the caller?
1681   template <typename T>
1682   using can_print_result = internal::conjunction<
1683       // void can't be stored as an object (and we also don't need to print it).
1684       internal::negation<std::is_void<T>>,
1685       // Non-moveable types can't be returned on to the user, so there's no way
1686       // for us to intercept and print them.
1687       std::is_move_constructible<T>>;
1688 
1689   // Perform the supplied action, printing the result to os.
1690   template <typename T = R,
1691             typename std::enable_if<can_print_result<T>::value, int>::type = 0>
1692   R PerformActionAndPrintResult(const void* const untyped_action,
1693                                 ArgumentTuple&& args,
1694                                 const std::string& call_description,
1695                                 std::ostream& os) {
1696     R result = PerformAction(untyped_action, std::move(args), call_description);
1697 
1698     PrintAsActionResult(result, os);
1699     return std::forward<R>(result);
1700   }
1701 
1702   // An overload for when it's not possible to print the result. In this case we
1703   // simply perform the action.
1704   template <typename T = R,
1705             typename std::enable_if<
1706                 internal::negation<can_print_result<T>>::value, int>::type = 0>
1707   R PerformActionAndPrintResult(const void* const untyped_action,
1708                                 ArgumentTuple&& args,
1709                                 const std::string& call_description,
1710                                 std::ostream&) {
1711     return PerformAction(untyped_action, std::move(args), call_description);
1712   }
1713 
1714   // Returns the result of invoking this mock function with the given
1715   // arguments. This function can be safely called from multiple
1716   // threads concurrently.
1717   R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
1718 };  // class FunctionMocker
1719 
1720 // Calculates the result of invoking this mock function with the given
1721 // arguments, prints it, and returns it.
1722 template <typename R, typename... Args>
1723 R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
1724     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1725   // See the definition of untyped_expectations_ for why access to it
1726   // is unprotected here.
1727   if (untyped_expectations_.size() == 0) {
1728     // No expectation is set on this mock method - we have an
1729     // uninteresting call.
1730 
1731     // We must get Google Mock's reaction on uninteresting calls
1732     // made on this mock object BEFORE performing the action,
1733     // because the action may DELETE the mock object and make the
1734     // following expression meaningless.
1735     const CallReaction reaction =
1736         Mock::GetReactionOnUninterestingCalls(MockObject());
1737 
1738     // True if and only if we need to print this call's arguments and return
1739     // value.  This definition must be kept in sync with
1740     // the behavior of ReportUninterestingCall().
1741     const bool need_to_report_uninteresting_call =
1742         // If the user allows this uninteresting call, we print it
1743         // only when they want informational messages.
1744         reaction == kAllow ? LogIsVisible(kInfo) :
1745                            // If the user wants this to be a warning, we print
1746                            // it only when they want to see warnings.
1747             reaction == kWarn
1748             ? LogIsVisible(kWarning)
1749             :
1750             // Otherwise, the user wants this to be an error, and we
1751             // should always print detailed information in the error.
1752             true;
1753 
1754     if (!need_to_report_uninteresting_call) {
1755       // Perform the action without printing the call information.
1756       return this->PerformDefaultAction(
1757           std::move(args), "Function call: " + std::string(Name()));
1758     }
1759 
1760     // Warns about the uninteresting call.
1761     ::std::stringstream ss;
1762     this->UntypedDescribeUninterestingCall(&args, &ss);
1763 
1764     // Perform the action, print the result, and then report the uninteresting
1765     // call.
1766     //
1767     // We use RAII to do the latter in case R is void or a non-moveable type. In
1768     // either case we can't assign it to a local variable.
1769     const Cleanup report_uninteresting_call(
1770         [&] { ReportUninterestingCall(reaction, ss.str()); });
1771 
1772     return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
1773   }
1774 
1775   bool is_excessive = false;
1776   ::std::stringstream ss;
1777   ::std::stringstream why;
1778   ::std::stringstream loc;
1779   const void* untyped_action = nullptr;
1780 
1781   // The UntypedFindMatchingExpectation() function acquires and
1782   // releases g_gmock_mutex.
1783 
1784   const ExpectationBase* const untyped_expectation =
1785       this->UntypedFindMatchingExpectation(&args, &untyped_action,
1786                                            &is_excessive, &ss, &why);
1787   const bool found = untyped_expectation != nullptr;
1788 
1789   // True if and only if we need to print the call's arguments
1790   // and return value.
1791   // This definition must be kept in sync with the uses of Expect()
1792   // and Log() in this function.
1793   const bool need_to_report_call =
1794       !found || is_excessive || LogIsVisible(kInfo);
1795   if (!need_to_report_call) {
1796     // Perform the action without printing the call information.
1797     return PerformAction(untyped_action, std::move(args), "");
1798   }
1799 
1800   ss << "    Function call: " << Name();
1801   this->UntypedPrintArgs(&args, &ss);
1802 
1803   // In case the action deletes a piece of the expectation, we
1804   // generate the message beforehand.
1805   if (found && !is_excessive) {
1806     untyped_expectation->DescribeLocationTo(&loc);
1807   }
1808 
1809   // Perform the action, print the result, and then fail or log in whatever way
1810   // is appropriate.
1811   //
1812   // We use RAII to do the latter in case R is void or a non-moveable type. In
1813   // either case we can't assign it to a local variable.
1814   const Cleanup handle_failures([&] {
1815     ss << "\n" << why.str();
1816 
1817     if (!found) {
1818       // No expectation matches this call - reports a failure.
1819       Expect(false, nullptr, -1, ss.str());
1820     } else if (is_excessive) {
1821       // We had an upper-bound violation and the failure message is in ss.
1822       Expect(false, untyped_expectation->file(), untyped_expectation->line(),
1823              ss.str());
1824     } else {
1825       // We had an expected call and the matching expectation is
1826       // described in ss.
1827       Log(kInfo, loc.str() + ss.str(), 2);
1828     }
1829   });
1830 
1831   return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
1832                                      ss);
1833 }
1834 
1835 }  // namespace internal
1836 
1837 namespace internal {
1838 
1839 template <typename F>
1840 class MockFunction;
1841 
1842 template <typename R, typename... Args>
1843 class MockFunction<R(Args...)> {
1844  public:
1845   MockFunction(const MockFunction&) = delete;
1846   MockFunction& operator=(const MockFunction&) = delete;
1847 
1848   std::function<R(Args...)> AsStdFunction() {
1849     return [this](Args... args) -> R {
1850       return this->Call(std::forward<Args>(args)...);
1851     };
1852   }
1853 
1854   // Implementation detail: the expansion of the MOCK_METHOD macro.
1855   R Call(Args... args) {
1856     mock_.SetOwnerAndName(this, "Call");
1857     return mock_.Invoke(std::forward<Args>(args)...);
1858   }
1859 
1860   MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1861     mock_.RegisterOwner(this);
1862     return mock_.With(std::move(m)...);
1863   }
1864 
1865   MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
1866     return this->gmock_Call(::testing::A<Args>()...);
1867   }
1868 
1869  protected:
1870   MockFunction() = default;
1871   ~MockFunction() = default;
1872 
1873  private:
1874   FunctionMocker<R(Args...)> mock_;
1875 };
1876 
1877 /*
1878 The SignatureOf<F> struct is a meta-function returning function signature
1879 corresponding to the provided F argument.
1880 
1881 It makes use of MockFunction easier by allowing it to accept more F arguments
1882 than just function signatures.
1883 
1884 Specializations provided here cover a signature type itself and any template
1885 that can be parameterized with a signature, including std::function and
1886 boost::function.
1887 */
1888 
1889 template <typename F, typename = void>
1890 struct SignatureOf;
1891 
1892 template <typename R, typename... Args>
1893 struct SignatureOf<R(Args...)> {
1894   using type = R(Args...);
1895 };
1896 
1897 template <template <typename> class C, typename F>
1898 struct SignatureOf<C<F>,
1899                    typename std::enable_if<std::is_function<F>::value>::type>
1900     : SignatureOf<F> {};
1901 
1902 template <typename F>
1903 using SignatureOfT = typename SignatureOf<F>::type;
1904 
1905 }  // namespace internal
1906 
1907 // A MockFunction<F> type has one mock method whose type is
1908 // internal::SignatureOfT<F>.  It is useful when you just want your
1909 // test code to emit some messages and have Google Mock verify the
1910 // right messages are sent (and perhaps at the right times).  For
1911 // example, if you are exercising code:
1912 //
1913 //   Foo(1);
1914 //   Foo(2);
1915 //   Foo(3);
1916 //
1917 // and want to verify that Foo(1) and Foo(3) both invoke
1918 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1919 //
1920 // TEST(FooTest, InvokesBarCorrectly) {
1921 //   MyMock mock;
1922 //   MockFunction<void(string check_point_name)> check;
1923 //   {
1924 //     InSequence s;
1925 //
1926 //     EXPECT_CALL(mock, Bar("a"));
1927 //     EXPECT_CALL(check, Call("1"));
1928 //     EXPECT_CALL(check, Call("2"));
1929 //     EXPECT_CALL(mock, Bar("a"));
1930 //   }
1931 //   Foo(1);
1932 //   check.Call("1");
1933 //   Foo(2);
1934 //   check.Call("2");
1935 //   Foo(3);
1936 // }
1937 //
1938 // The expectation spec says that the first Bar("a") must happen
1939 // before check point "1", the second Bar("a") must happen after check
1940 // point "2", and nothing should happen between the two check
1941 // points. The explicit check points make it easy to tell which
1942 // Bar("a") is called by which call to Foo().
1943 //
1944 // MockFunction<F> can also be used to exercise code that accepts
1945 // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
1946 // AsStdFunction() method to create std::function proxy forwarding to
1947 // original object's Call. Example:
1948 //
1949 // TEST(FooTest, RunsCallbackWithBarArgument) {
1950 //   MockFunction<int(string)> callback;
1951 //   EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1952 //   Foo(callback.AsStdFunction());
1953 // }
1954 //
1955 // The internal::SignatureOfT<F> indirection allows to use other types
1956 // than just function signature type. This is typically useful when
1957 // providing a mock for a predefined std::function type. Example:
1958 //
1959 // using FilterPredicate = std::function<bool(string)>;
1960 // void MyFilterAlgorithm(FilterPredicate predicate);
1961 //
1962 // TEST(FooTest, FilterPredicateAlwaysAccepts) {
1963 //   MockFunction<FilterPredicate> predicateMock;
1964 //   EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
1965 //   MyFilterAlgorithm(predicateMock.AsStdFunction());
1966 // }
1967 template <typename F>
1968 class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
1969   using Base = internal::MockFunction<internal::SignatureOfT<F>>;
1970 
1971  public:
1972   using Base::Base;
1973 };
1974 
1975 // The style guide prohibits "using" statements in a namespace scope
1976 // inside a header file.  However, the MockSpec class template is
1977 // meant to be defined in the ::testing namespace.  The following line
1978 // is just a trick for working around a bug in MSVC 8.0, which cannot
1979 // handle it if we define MockSpec in ::testing.
1980 using internal::MockSpec;
1981 
1982 // Const(x) is a convenient function for obtaining a const reference
1983 // to x.  This is useful for setting expectations on an overloaded
1984 // const mock method, e.g.
1985 //
1986 //   class MockFoo : public FooInterface {
1987 //    public:
1988 //     MOCK_METHOD0(Bar, int());
1989 //     MOCK_CONST_METHOD0(Bar, int&());
1990 //   };
1991 //
1992 //   MockFoo foo;
1993 //   // Expects a call to non-const MockFoo::Bar().
1994 //   EXPECT_CALL(foo, Bar());
1995 //   // Expects a call to const MockFoo::Bar().
1996 //   EXPECT_CALL(Const(foo), Bar());
1997 template <typename T>
1998 inline const T& Const(const T& x) {
1999   return x;
2000 }
2001 
2002 // Constructs an Expectation object that references and co-owns exp.
2003 inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
2004     : expectation_base_(exp.GetHandle().expectation_base()) {}
2005 
2006 }  // namespace testing
2007 
2008 GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251
2009 
2010 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
2011 // required to avoid compile errors when the name of the method used in call is
2012 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
2013 // tests in internal/gmock-spec-builders_test.cc for more details.
2014 //
2015 // This macro supports statements both with and without parameter matchers. If
2016 // the parameter list is omitted, gMock will accept any parameters, which allows
2017 // tests to be written that don't need to encode the number of method
2018 // parameter. This technique may only be used for non-overloaded methods.
2019 //
2020 //   // These are the same:
2021 //   ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
2022 //   ON_CALL(mock, NoArgsMethod).WillByDefault(...);
2023 //
2024 //   // As are these:
2025 //   ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
2026 //   ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
2027 //
2028 //   // Can also specify args if you want, of course:
2029 //   ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
2030 //
2031 //   // Overloads work as long as you specify parameters:
2032 //   ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
2033 //   ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
2034 //
2035 //   // Oops! Which overload did you want?
2036 //   ON_CALL(mock, OverloadedMethod).WillByDefault(...);
2037 //     => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
2038 //
2039 // How this works: The mock class uses two overloads of the gmock_Method
2040 // expectation setter method plus an operator() overload on the MockSpec object.
2041 // In the matcher list form, the macro expands to:
2042 //
2043 //   // This statement:
2044 //   ON_CALL(mock, TwoArgsMethod(_, 45))...
2045 //
2046 //   // ...expands to:
2047 //   mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
2048 //   |-------------v---------------||------------v-------------|
2049 //       invokes first overload        swallowed by operator()
2050 //
2051 //   // ...which is essentially:
2052 //   mock.gmock_TwoArgsMethod(_, 45)...
2053 //
2054 // Whereas the form without a matcher list:
2055 //
2056 //   // This statement:
2057 //   ON_CALL(mock, TwoArgsMethod)...
2058 //
2059 //   // ...expands to:
2060 //   mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
2061 //   |-----------------------v--------------------------|
2062 //                 invokes second overload
2063 //
2064 //   // ...which is essentially:
2065 //   mock.gmock_TwoArgsMethod(_, _)...
2066 //
2067 // The WithoutMatchers() argument is used to disambiguate overloads and to
2068 // block the caller from accidentally invoking the second overload directly. The
2069 // second argument is an internal type derived from the method signature. The
2070 // failure to disambiguate two overloads of this method in the ON_CALL statement
2071 // is how we block callers from setting expectations on overloaded methods.
2072 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call)                    \
2073   ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
2074                              nullptr)                                   \
2075       .Setter(__FILE__, __LINE__, #mock_expr, #call)
2076 
2077 #define ON_CALL(obj, call) \
2078   GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
2079 
2080 #define EXPECT_CALL(obj, call) \
2081   GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
2082 
2083 #endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_