Home | History | Annotate | Download | only in gmock
      1 // Copyright 2007, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      8 //     * Redistributions of source code must retain the above copyright
      9 // notice, this list of conditions and the following disclaimer.
     10 //     * Redistributions in binary form must reproduce the above
     11 // copyright notice, this list of conditions and the following disclaimer
     12 // in the documentation and/or other materials provided with the
     13 // distribution.
     14 //     * Neither the name of Google Inc. nor the names of its
     15 // contributors may be used to endorse or promote products derived from
     16 // this software without specific prior written permission.
     17 //
     18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29 //
     30 // Author: wan (at) google.com (Zhanyong Wan)
     31 
     32 // Google Mock - a framework for writing C++ mock classes.
     33 //
     34 // This file implements the ON_CALL() and EXPECT_CALL() macros.
     35 //
     36 // A user can use the ON_CALL() macro to specify the default action of
     37 // a mock method.  The syntax is:
     38 //
     39 //   ON_CALL(mock_object, Method(argument-matchers))
     40 //       .With(multi-argument-matcher)
     41 //       .WillByDefault(action);
     42 //
     43 //  where the .With() clause is optional.
     44 //
     45 // A user can use the EXPECT_CALL() macro to specify an expectation on
     46 // a mock method.  The syntax is:
     47 //
     48 //   EXPECT_CALL(mock_object, Method(argument-matchers))
     49 //       .With(multi-argument-matchers)
     50 //       .Times(cardinality)
     51 //       .InSequence(sequences)
     52 //       .After(expectations)
     53 //       .WillOnce(action)
     54 //       .WillRepeatedly(action)
     55 //       .RetiresOnSaturation();
     56 //
     57 // where all clauses are optional, and .InSequence()/.After()/
     58 // .WillOnce() can appear any number of times.
     59 
     60 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
     61 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
     62 
     63 #include <map>
     64 #include <set>
     65 #include <sstream>
     66 #include <string>
     67 #include <vector>
     68 
     69 #if GTEST_HAS_EXCEPTIONS
     70 # include <stdexcept>  // NOLINT
     71 #endif
     72 
     73 #include "gmock/gmock-actions.h"
     74 #include "gmock/gmock-cardinalities.h"
     75 #include "gmock/gmock-matchers.h"
     76 #include "gmock/internal/gmock-internal-utils.h"
     77 #include "gmock/internal/gmock-port.h"
     78 #include "gtest/gtest.h"
     79 
     80 namespace testing {
     81 
     82 // An abstract handle of an expectation.
     83 class Expectation;
     84 
     85 // A set of expectation handles.
     86 class ExpectationSet;
     87 
     88 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
     89 // and MUST NOT BE USED IN USER CODE!!!
     90 namespace internal {
     91 
     92 // Implements a mock function.
     93 template <typename F> class FunctionMocker;
     94 
     95 // Base class for expectations.
     96 class ExpectationBase;
     97 
     98 // Implements an expectation.
     99 template <typename F> class TypedExpectation;
    100 
    101 // Helper class for testing the Expectation class template.
    102 class ExpectationTester;
    103 
    104 // Base class for function mockers.
    105 template <typename F> class FunctionMockerBase;
    106 
    107 // Protects the mock object registry (in class Mock), all function
    108 // mockers, and all expectations.
    109 //
    110 // The reason we don't use more fine-grained protection is: when a
    111 // mock function Foo() is called, it needs to consult its expectations
    112 // to see which one should be picked.  If another thread is allowed to
    113 // call a mock function (either Foo() or a different one) at the same
    114 // time, it could affect the "retired" attributes of Foo()'s
    115 // expectations when InSequence() is used, and thus affect which
    116 // expectation gets picked.  Therefore, we sequence all mock function
    117 // calls to ensure the integrity of the mock objects' states.
    118 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
    119 
    120 // Untyped base class for ActionResultHolder<R>.
    121 class UntypedActionResultHolderBase;
    122 
    123 // Abstract base class of FunctionMockerBase.  This is the
    124 // type-agnostic part of the function mocker interface.  Its pure
    125 // virtual methods are implemented by FunctionMockerBase.
    126 class GTEST_API_ UntypedFunctionMockerBase {
    127  public:
    128   UntypedFunctionMockerBase();
    129   virtual ~UntypedFunctionMockerBase();
    130 
    131   // Verifies that all expectations on this mock function have been
    132   // satisfied.  Reports one or more Google Test non-fatal failures
    133   // and returns false if not.
    134   bool VerifyAndClearExpectationsLocked()
    135       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
    136 
    137   // Clears the ON_CALL()s set on this mock function.
    138   virtual void ClearDefaultActionsLocked()
    139       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
    140 
    141   // In all of the following Untyped* functions, it's the caller's
    142   // responsibility to guarantee the correctness of the arguments'
    143   // types.
    144 
    145   // Performs the default action with the given arguments and returns
    146   // the action's result.  The call description string will be used in
    147   // the error message to describe the call in the case the default
    148   // action fails.
    149   // L = *
    150   virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
    151       const void* untyped_args, const std::string& call_description) const = 0;
    152 
    153   // Performs the given action with the given arguments and returns
    154   // the action's result.
    155   // L = *
    156   virtual UntypedActionResultHolderBase* UntypedPerformAction(
    157       const void* untyped_action,
    158       const void* untyped_args) const = 0;
    159 
    160   // Writes a message that the call is uninteresting (i.e. neither
    161   // explicitly expected nor explicitly unexpected) to the given
    162   // ostream.
    163   virtual void UntypedDescribeUninterestingCall(
    164       const void* untyped_args,
    165       ::std::ostream* os) const
    166           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
    167 
    168   // Returns the expectation that matches the given function arguments
    169   // (or NULL is there's no match); when a match is found,
    170   // untyped_action is set to point to the action that should be
    171   // performed (or NULL if the action is "do default"), and
    172   // is_excessive is modified to indicate whether the call exceeds the
    173   // expected number.
    174   virtual const ExpectationBase* UntypedFindMatchingExpectation(
    175       const void* untyped_args,
    176       const void** untyped_action, bool* is_excessive,
    177       ::std::ostream* what, ::std::ostream* why)
    178           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
    179 
    180   // Prints the given function arguments to the ostream.
    181   virtual void UntypedPrintArgs(const void* untyped_args,
    182                                 ::std::ostream* os) const = 0;
    183 
    184   // Sets the mock object this mock method belongs to, and registers
    185   // this information in the global mock registry.  Will be called
    186   // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
    187   // method.
    188   // TODO(wan (at) google.com): rename to SetAndRegisterOwner().
    189   void RegisterOwner(const void* mock_obj)
    190       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
    191 
    192   // Sets the mock object this mock method belongs to, and sets the
    193   // name of the mock function.  Will be called upon each invocation
    194   // of this mock function.
    195   void SetOwnerAndName(const void* mock_obj, const char* name)
    196       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
    197 
    198   // Returns the mock object this mock method belongs to.  Must be
    199   // called after RegisterOwner() or SetOwnerAndName() has been
    200   // called.
    201   const void* MockObject() const
    202       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
    203 
    204   // Returns the name of this mock method.  Must be called after
    205   // SetOwnerAndName() has been called.
    206   const char* Name() const
    207       GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
    208 
    209   // Returns the result of invoking this mock function with the given
    210   // arguments.  This function can be safely called from multiple
    211   // threads concurrently.  The caller is responsible for deleting the
    212   // result.
    213   UntypedActionResultHolderBase* UntypedInvokeWith(
    214       const void* untyped_args)
    215           GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
    216 
    217  protected:
    218   typedef std::vector<const void*> UntypedOnCallSpecs;
    219 
    220   typedef std::vector<internal::linked_ptr<ExpectationBase> >
    221   UntypedExpectations;
    222 
    223   // Returns an Expectation object that references and co-owns exp,
    224   // which must be an expectation on this mock function.
    225   Expectation GetHandleOf(ExpectationBase* exp);
    226 
    227   // Address of the mock object this mock method belongs to.  Only
    228   // valid after this mock method has been called or
    229   // ON_CALL/EXPECT_CALL has been invoked on it.
    230   const void* mock_obj_;  // Protected by g_gmock_mutex.
    231 
    232   // Name of the function being mocked.  Only valid after this mock
    233   // method has been called.
    234   const char* name_;  // Protected by g_gmock_mutex.
    235 
    236   // All default action specs for this function mocker.
    237   UntypedOnCallSpecs untyped_on_call_specs_;
    238 
    239   // All expectations for this function mocker.
    240   UntypedExpectations untyped_expectations_;
    241 };  // class UntypedFunctionMockerBase
    242 
    243 // Untyped base class for OnCallSpec<F>.
    244 class UntypedOnCallSpecBase {
    245  public:
    246   // The arguments are the location of the ON_CALL() statement.
    247   UntypedOnCallSpecBase(const char* a_file, int a_line)
    248       : file_(a_file), line_(a_line), last_clause_(kNone) {}
    249 
    250   // Where in the source file was the default action spec defined?
    251   const char* file() const { return file_; }
    252   int line() const { return line_; }
    253 
    254  protected:
    255   // Gives each clause in the ON_CALL() statement a name.
    256   enum Clause {
    257     // Do not change the order of the enum members!  The run-time
    258     // syntax checking relies on it.
    259     kNone,
    260     kWith,
    261     kWillByDefault
    262   };
    263 
    264   // Asserts that the ON_CALL() statement has a certain property.
    265   void AssertSpecProperty(bool property,
    266                           const std::string& failure_message) const {
    267     Assert(property, file_, line_, failure_message);
    268   }
    269 
    270   // Expects that the ON_CALL() statement has a certain property.
    271   void ExpectSpecProperty(bool property,
    272                           const std::string& failure_message) const {
    273     Expect(property, file_, line_, failure_message);
    274   }
    275 
    276   const char* file_;
    277   int line_;
    278 
    279   // The last clause in the ON_CALL() statement as seen so far.
    280   // Initially kNone and changes as the statement is parsed.
    281   Clause last_clause_;
    282 };  // class UntypedOnCallSpecBase
    283 
    284 // This template class implements an ON_CALL spec.
    285 template <typename F>
    286 class OnCallSpec : public UntypedOnCallSpecBase {
    287  public:
    288   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
    289   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
    290 
    291   // Constructs an OnCallSpec object from the information inside
    292   // the parenthesis of an ON_CALL() statement.
    293   OnCallSpec(const char* a_file, int a_line,
    294              const ArgumentMatcherTuple& matchers)
    295       : UntypedOnCallSpecBase(a_file, a_line),
    296         matchers_(matchers),
    297         // By default, extra_matcher_ should match anything.  However,
    298         // we cannot initialize it with _ as that triggers a compiler
    299         // bug in Symbian's C++ compiler (cannot decide between two
    300         // overloaded constructors of Matcher<const ArgumentTuple&>).
    301         extra_matcher_(A<const ArgumentTuple&>()) {
    302   }
    303 
    304   // Implements the .With() clause.
    305   OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
    306     // Makes sure this is called at most once.
    307     ExpectSpecProperty(last_clause_ < kWith,
    308                        ".With() cannot appear "
    309                        "more than once in an ON_CALL().");
    310     last_clause_ = kWith;
    311 
    312     extra_matcher_ = m;
    313     return *this;
    314   }
    315 
    316   // Implements the .WillByDefault() clause.
    317   OnCallSpec& WillByDefault(const Action<F>& action) {
    318     ExpectSpecProperty(last_clause_ < kWillByDefault,
    319                        ".WillByDefault() must appear "
    320                        "exactly once in an ON_CALL().");
    321     last_clause_ = kWillByDefault;
    322 
    323     ExpectSpecProperty(!action.IsDoDefault(),
    324                        "DoDefault() cannot be used in ON_CALL().");
    325     action_ = action;
    326     return *this;
    327   }
    328 
    329   // Returns true iff the given arguments match the matchers.
    330   bool Matches(const ArgumentTuple& args) const {
    331     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
    332   }
    333 
    334   // Returns the action specified by the user.
    335   const Action<F>& GetAction() const {
    336     AssertSpecProperty(last_clause_ == kWillByDefault,
    337                        ".WillByDefault() must appear exactly "
    338                        "once in an ON_CALL().");
    339     return action_;
    340   }
    341 
    342  private:
    343   // The information in statement
    344   //
    345   //   ON_CALL(mock_object, Method(matchers))
    346   //       .With(multi-argument-matcher)
    347   //       .WillByDefault(action);
    348   //
    349   // is recorded in the data members like this:
    350   //
    351   //   source file that contains the statement => file_
    352   //   line number of the statement            => line_
    353   //   matchers                                => matchers_
    354   //   multi-argument-matcher                  => extra_matcher_
    355   //   action                                  => action_
    356   ArgumentMatcherTuple matchers_;
    357   Matcher<const ArgumentTuple&> extra_matcher_;
    358   Action<F> action_;
    359 };  // class OnCallSpec
    360 
    361 // Possible reactions on uninteresting calls.
    362 enum CallReaction {
    363   kAllow,
    364   kWarn,
    365   kFail,
    366 };
    367 
    368 }  // namespace internal
    369 
    370 // Utilities for manipulating mock objects.
    371 class GTEST_API_ Mock {
    372  public:
    373   // The following public methods can be called concurrently.
    374 
    375   // Tells Google Mock to ignore mock_obj when checking for leaked
    376   // mock objects.
    377   static void AllowLeak(const void* mock_obj)
    378       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    379 
    380   // Verifies and clears all expectations on the given mock object.
    381   // If the expectations aren't satisfied, generates one or more
    382   // Google Test non-fatal failures and returns false.
    383   static bool VerifyAndClearExpectations(void* mock_obj)
    384       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    385 
    386   // Verifies all expectations on the given mock object and clears its
    387   // default actions and expectations.  Returns true iff the
    388   // verification was successful.
    389   static bool VerifyAndClear(void* mock_obj)
    390       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    391 
    392  private:
    393   friend class internal::UntypedFunctionMockerBase;
    394 
    395   // Needed for a function mocker to register itself (so that we know
    396   // how to clear a mock object).
    397   template <typename F>
    398   friend class internal::FunctionMockerBase;
    399 
    400   template <typename M>
    401   friend class NiceMock;
    402 
    403   template <typename M>
    404   friend class NaggyMock;
    405 
    406   template <typename M>
    407   friend class StrictMock;
    408 
    409   // Tells Google Mock to allow uninteresting calls on the given mock
    410   // object.
    411   static void AllowUninterestingCalls(const void* mock_obj)
    412       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    413 
    414   // Tells Google Mock to warn the user about uninteresting calls on
    415   // the given mock object.
    416   static void WarnUninterestingCalls(const void* mock_obj)
    417       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    418 
    419   // Tells Google Mock to fail uninteresting calls on the given mock
    420   // object.
    421   static void FailUninterestingCalls(const void* mock_obj)
    422       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    423 
    424   // Tells Google Mock the given mock object is being destroyed and
    425   // its entry in the call-reaction table should be removed.
    426   static void UnregisterCallReaction(const void* mock_obj)
    427       GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    428 
    429   // Returns the reaction Google Mock will have on uninteresting calls
    430   // made on the given mock object.
    431   static internal::CallReaction GetReactionOnUninterestingCalls(
    432       const void* mock_obj)
    433           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    434 
    435   // Verifies that all expectations on the given mock object have been
    436   // satisfied.  Reports one or more Google Test non-fatal failures
    437   // and returns false if not.
    438   static bool VerifyAndClearExpectationsLocked(void* mock_obj)
    439       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
    440 
    441   // Clears all ON_CALL()s set on the given mock object.
    442   static void ClearDefaultActionsLocked(void* mock_obj)
    443       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
    444 
    445   // Registers a mock object and a mock method it owns.
    446   static void Register(
    447       const void* mock_obj,
    448       internal::UntypedFunctionMockerBase* mocker)
    449           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    450 
    451   // Tells Google Mock where in the source code mock_obj is used in an
    452   // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
    453   // information helps the user identify which object it is.
    454   static void RegisterUseByOnCallOrExpectCall(
    455       const void* mock_obj, const char* file, int line)
    456           GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
    457 
    458   // Unregisters a mock method; removes the owning mock object from
    459   // the registry when the last mock method associated with it has
    460   // been unregistered.  This is called only in the destructor of
    461   // FunctionMockerBase.
    462   static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
    463       GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
    464 };  // class Mock
    465 
    466 // An abstract handle of an expectation.  Useful in the .After()
    467 // clause of EXPECT_CALL() for setting the (partial) order of
    468 // expectations.  The syntax:
    469 //
    470 //   Expectation e1 = EXPECT_CALL(...)...;
    471 //   EXPECT_CALL(...).After(e1)...;
    472 //
    473 // sets two expectations where the latter can only be matched after
    474 // the former has been satisfied.
    475 //
    476 // Notes:
    477 //   - This class is copyable and has value semantics.
    478 //   - Constness is shallow: a const Expectation object itself cannot
    479 //     be modified, but the mutable methods of the ExpectationBase
    480 //     object it references can be called via expectation_base().
    481 //   - The constructors and destructor are defined out-of-line because
    482 //     the Symbian WINSCW compiler wants to otherwise instantiate them
    483 //     when it sees this class definition, at which point it doesn't have
    484 //     ExpectationBase available yet, leading to incorrect destruction
    485 //     in the linked_ptr (or compilation errors if using a checking
    486 //     linked_ptr).
    487 class GTEST_API_ Expectation {
    488  public:
    489   // Constructs a null object that doesn't reference any expectation.
    490   Expectation();
    491 
    492   ~Expectation();
    493 
    494   // This single-argument ctor must not be explicit, in order to support the
    495   //   Expectation e = EXPECT_CALL(...);
    496   // syntax.
    497   //
    498   // A TypedExpectation object stores its pre-requisites as
    499   // Expectation objects, and needs to call the non-const Retire()
    500   // method on the ExpectationBase objects they reference.  Therefore
    501   // Expectation must receive a *non-const* reference to the
    502   // ExpectationBase object.
    503   Expectation(internal::ExpectationBase& exp);  // NOLINT
    504 
    505   // The compiler-generated copy ctor and operator= work exactly as
    506   // intended, so we don't need to define our own.
    507 
    508   // Returns true iff rhs references the same expectation as this object does.
    509   bool operator==(const Expectation& rhs) const {
    510     return expectation_base_ == rhs.expectation_base_;
    511   }
    512 
    513   bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
    514 
    515  private:
    516   friend class ExpectationSet;
    517   friend class Sequence;
    518   friend class ::testing::internal::ExpectationBase;
    519   friend class ::testing::internal::UntypedFunctionMockerBase;
    520 
    521   template <typename F>
    522   friend class ::testing::internal::FunctionMockerBase;
    523 
    524   template <typename F>
    525   friend class ::testing::internal::TypedExpectation;
    526 
    527   // This comparator is needed for putting Expectation objects into a set.
    528   class Less {
    529    public:
    530     bool operator()(const Expectation& lhs, const Expectation& rhs) const {
    531       return lhs.expectation_base_.get() < rhs.expectation_base_.get();
    532     }
    533   };
    534 
    535   typedef ::std::set<Expectation, Less> Set;
    536 
    537   Expectation(
    538       const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
    539 
    540   // Returns the expectation this object references.
    541   const internal::linked_ptr<internal::ExpectationBase>&
    542   expectation_base() const {
    543     return expectation_base_;
    544   }
    545 
    546   // A linked_ptr that co-owns the expectation this handle references.
    547   internal::linked_ptr<internal::ExpectationBase> expectation_base_;
    548 };
    549 
    550 // A set of expectation handles.  Useful in the .After() clause of
    551 // EXPECT_CALL() for setting the (partial) order of expectations.  The
    552 // syntax:
    553 //
    554 //   ExpectationSet es;
    555 //   es += EXPECT_CALL(...)...;
    556 //   es += EXPECT_CALL(...)...;
    557 //   EXPECT_CALL(...).After(es)...;
    558 //
    559 // sets three expectations where the last one can only be matched
    560 // after the first two have both been satisfied.
    561 //
    562 // This class is copyable and has value semantics.
    563 class ExpectationSet {
    564  public:
    565   // A bidirectional iterator that can read a const element in the set.
    566   typedef Expectation::Set::const_iterator const_iterator;
    567 
    568   // An object stored in the set.  This is an alias of Expectation.
    569   typedef Expectation::Set::value_type value_type;
    570 
    571   // Constructs an empty set.
    572   ExpectationSet() {}
    573 
    574   // This single-argument ctor must not be explicit, in order to support the
    575   //   ExpectationSet es = EXPECT_CALL(...);
    576   // syntax.
    577   ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT
    578     *this += Expectation(exp);
    579   }
    580 
    581   // This single-argument ctor implements implicit conversion from
    582   // Expectation and thus must not be explicit.  This allows either an
    583   // Expectation or an ExpectationSet to be used in .After().
    584   ExpectationSet(const Expectation& e) {  // NOLINT
    585     *this += e;
    586   }
    587 
    588   // The compiler-generator ctor and operator= works exactly as
    589   // intended, so we don't need to define our own.
    590 
    591   // Returns true iff rhs contains the same set of Expectation objects
    592   // as this does.
    593   bool operator==(const ExpectationSet& rhs) const {
    594     return expectations_ == rhs.expectations_;
    595   }
    596 
    597   bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
    598 
    599   // Implements the syntax
    600   //   expectation_set += EXPECT_CALL(...);
    601   ExpectationSet& operator+=(const Expectation& e) {
    602     expectations_.insert(e);
    603     return *this;
    604   }
    605 
    606   int size() const { return static_cast<int>(expectations_.size()); }
    607 
    608   const_iterator begin() const { return expectations_.begin(); }
    609   const_iterator end() const { return expectations_.end(); }
    610 
    611  private:
    612   Expectation::Set expectations_;
    613 };
    614 
    615 
    616 // Sequence objects are used by a user to specify the relative order
    617 // in which the expectations should match.  They are copyable (we rely
    618 // on the compiler-defined copy constructor and assignment operator).
    619 class GTEST_API_ Sequence {
    620  public:
    621   // Constructs an empty sequence.
    622   Sequence() : last_expectation_(new Expectation) {}
    623 
    624   // Adds an expectation to this sequence.  The caller must ensure
    625   // that no other thread is accessing this Sequence object.
    626   void AddExpectation(const Expectation& expectation) const;
    627 
    628  private:
    629   // The last expectation in this sequence.  We use a linked_ptr here
    630   // because Sequence objects are copyable and we want the copies to
    631   // be aliases.  The linked_ptr allows the copies to co-own and share
    632   // the same Expectation object.
    633   internal::linked_ptr<Expectation> last_expectation_;
    634 };  // class Sequence
    635 
    636 // An object of this type causes all EXPECT_CALL() statements
    637 // encountered in its scope to be put in an anonymous sequence.  The
    638 // work is done in the constructor and destructor.  You should only
    639 // create an InSequence object on the stack.
    640 //
    641 // The sole purpose for this class is to support easy definition of
    642 // sequential expectations, e.g.
    643 //
    644 //   {
    645 //     InSequence dummy;  // The name of the object doesn't matter.
    646 //
    647 //     // The following expectations must match in the order they appear.
    648 //     EXPECT_CALL(a, Bar())...;
    649 //     EXPECT_CALL(a, Baz())...;
    650 //     ...
    651 //     EXPECT_CALL(b, Xyz())...;
    652 //   }
    653 //
    654 // You can create InSequence objects in multiple threads, as long as
    655 // they are used to affect different mock objects.  The idea is that
    656 // each thread can create and set up its own mocks as if it's the only
    657 // thread.  However, for clarity of your tests we recommend you to set
    658 // up mocks in the main thread unless you have a good reason not to do
    659 // so.
    660 class GTEST_API_ InSequence {
    661  public:
    662   InSequence();
    663   ~InSequence();
    664  private:
    665   bool sequence_created_;
    666 
    667   GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
    668 } GTEST_ATTRIBUTE_UNUSED_;
    669 
    670 namespace internal {
    671 
    672 // Points to the implicit sequence introduced by a living InSequence
    673 // object (if any) in the current thread or NULL.
    674 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
    675 
    676 // Base class for implementing expectations.
    677 //
    678 // There are two reasons for having a type-agnostic base class for
    679 // Expectation:
    680 //
    681 //   1. We need to store collections of expectations of different
    682 //   types (e.g. all pre-requisites of a particular expectation, all
    683 //   expectations in a sequence).  Therefore these expectation objects
    684 //   must share a common base class.
    685 //
    686 //   2. We can avoid binary code bloat by moving methods not depending
    687 //   on the template argument of Expectation to the base class.
    688 //
    689 // This class is internal and mustn't be used by user code directly.
    690 class GTEST_API_ ExpectationBase {
    691  public:
    692   // source_text is the EXPECT_CALL(...) source that created this Expectation.
    693   ExpectationBase(const char* file, int line, const std::string& source_text);
    694 
    695   virtual ~ExpectationBase();
    696 
    697   // Where in the source file was the expectation spec defined?
    698   const char* file() const { return file_; }
    699   int line() const { return line_; }
    700   const char* source_text() const { return source_text_.c_str(); }
    701   // Returns the cardinality specified in the expectation spec.
    702   const Cardinality& cardinality() const { return cardinality_; }
    703 
    704   // Describes the source file location of this expectation.
    705   void DescribeLocationTo(::std::ostream* os) const {
    706     *os << FormatFileLocation(file(), line()) << " ";
    707   }
    708 
    709   // Describes how many times a function call matching this
    710   // expectation has occurred.
    711   void DescribeCallCountTo(::std::ostream* os) const
    712       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
    713 
    714   // If this mock method has an extra matcher (i.e. .With(matcher)),
    715   // describes it to the ostream.
    716   virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
    717 
    718  protected:
    719   friend class ::testing::Expectation;
    720   friend class UntypedFunctionMockerBase;
    721 
    722   enum Clause {
    723     // Don't change the order of the enum members!
    724     kNone,
    725     kWith,
    726     kTimes,
    727     kInSequence,
    728     kAfter,
    729     kWillOnce,
    730     kWillRepeatedly,
    731     kRetiresOnSaturation
    732   };
    733 
    734   typedef std::vector<const void*> UntypedActions;
    735 
    736   // Returns an Expectation object that references and co-owns this
    737   // expectation.
    738   virtual Expectation GetHandle() = 0;
    739 
    740   // Asserts that the EXPECT_CALL() statement has the given property.
    741   void AssertSpecProperty(bool property,
    742                           const std::string& failure_message) const {
    743     Assert(property, file_, line_, failure_message);
    744   }
    745 
    746   // Expects that the EXPECT_CALL() statement has the given property.
    747   void ExpectSpecProperty(bool property,
    748                           const std::string& failure_message) const {
    749     Expect(property, file_, line_, failure_message);
    750   }
    751 
    752   // Explicitly specifies the cardinality of this expectation.  Used
    753   // by the subclasses to implement the .Times() clause.
    754   void SpecifyCardinality(const Cardinality& cardinality);
    755 
    756   // Returns true iff the user specified the cardinality explicitly
    757   // using a .Times().
    758   bool cardinality_specified() const { return cardinality_specified_; }
    759 
    760   // Sets the cardinality of this expectation spec.
    761   void set_cardinality(const Cardinality& a_cardinality) {
    762     cardinality_ = a_cardinality;
    763   }
    764 
    765   // The following group of methods should only be called after the
    766   // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
    767   // the current thread.
    768 
    769   // Retires all pre-requisites of this expectation.
    770   void RetireAllPreRequisites()
    771       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
    772 
    773   // Returns true iff this expectation is retired.
    774   bool is_retired() const
    775       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    776     g_gmock_mutex.AssertHeld();
    777     return retired_;
    778   }
    779 
    780   // Retires this expectation.
    781   void Retire()
    782       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    783     g_gmock_mutex.AssertHeld();
    784     retired_ = true;
    785   }
    786 
    787   // Returns true iff this expectation is satisfied.
    788   bool IsSatisfied() const
    789       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    790     g_gmock_mutex.AssertHeld();
    791     return cardinality().IsSatisfiedByCallCount(call_count_);
    792   }
    793 
    794   // Returns true iff this expectation is saturated.
    795   bool IsSaturated() const
    796       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    797     g_gmock_mutex.AssertHeld();
    798     return cardinality().IsSaturatedByCallCount(call_count_);
    799   }
    800 
    801   // Returns true iff this expectation is over-saturated.
    802   bool IsOverSaturated() const
    803       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    804     g_gmock_mutex.AssertHeld();
    805     return cardinality().IsOverSaturatedByCallCount(call_count_);
    806   }
    807 
    808   // Returns true iff all pre-requisites of this expectation are satisfied.
    809   bool AllPrerequisitesAreSatisfied() const
    810       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
    811 
    812   // Adds unsatisfied pre-requisites of this expectation to 'result'.
    813   void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
    814       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
    815 
    816   // Returns the number this expectation has been invoked.
    817   int call_count() const
    818       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    819     g_gmock_mutex.AssertHeld();
    820     return call_count_;
    821   }
    822 
    823   // Increments the number this expectation has been invoked.
    824   void IncrementCallCount()
    825       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    826     g_gmock_mutex.AssertHeld();
    827     call_count_++;
    828   }
    829 
    830   // Checks the action count (i.e. the number of WillOnce() and
    831   // WillRepeatedly() clauses) against the cardinality if this hasn't
    832   // been done before.  Prints a warning if there are too many or too
    833   // few actions.
    834   void CheckActionCountIfNotDone() const
    835       GTEST_LOCK_EXCLUDED_(mutex_);
    836 
    837   friend class ::testing::Sequence;
    838   friend class ::testing::internal::ExpectationTester;
    839 
    840   template <typename Function>
    841   friend class TypedExpectation;
    842 
    843   // Implements the .Times() clause.
    844   void UntypedTimes(const Cardinality& a_cardinality);
    845 
    846   // This group of fields are part of the spec and won't change after
    847   // an EXPECT_CALL() statement finishes.
    848   const char* file_;          // The file that contains the expectation.
    849   int line_;                  // The line number of the expectation.
    850   const std::string source_text_;  // The EXPECT_CALL(...) source text.
    851   // True iff the cardinality is specified explicitly.
    852   bool cardinality_specified_;
    853   Cardinality cardinality_;            // The cardinality of the expectation.
    854   // The immediate pre-requisites (i.e. expectations that must be
    855   // satisfied before this expectation can be matched) of this
    856   // expectation.  We use linked_ptr in the set because we want an
    857   // Expectation object to be co-owned by its FunctionMocker and its
    858   // successors.  This allows multiple mock objects to be deleted at
    859   // different times.
    860   ExpectationSet immediate_prerequisites_;
    861 
    862   // This group of fields are the current state of the expectation,
    863   // and can change as the mock function is called.
    864   int call_count_;  // How many times this expectation has been invoked.
    865   bool retired_;    // True iff this expectation has retired.
    866   UntypedActions untyped_actions_;
    867   bool extra_matcher_specified_;
    868   bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.
    869   bool retires_on_saturation_;
    870   Clause last_clause_;
    871   mutable bool action_count_checked_;  // Under mutex_.
    872   mutable Mutex mutex_;  // Protects action_count_checked_.
    873 
    874   GTEST_DISALLOW_ASSIGN_(ExpectationBase);
    875 };  // class ExpectationBase
    876 
    877 // Impements an expectation for the given function type.
    878 template <typename F>
    879 class TypedExpectation : public ExpectationBase {
    880  public:
    881   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
    882   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
    883   typedef typename Function<F>::Result Result;
    884 
    885   TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
    886                    const std::string& a_source_text,
    887                    const ArgumentMatcherTuple& m)
    888       : ExpectationBase(a_file, a_line, a_source_text),
    889         owner_(owner),
    890         matchers_(m),
    891         // By default, extra_matcher_ should match anything.  However,
    892         // we cannot initialize it with _ as that triggers a compiler
    893         // bug in Symbian's C++ compiler (cannot decide between two
    894         // overloaded constructors of Matcher<const ArgumentTuple&>).
    895         extra_matcher_(A<const ArgumentTuple&>()),
    896         repeated_action_(DoDefault()) {}
    897 
    898   virtual ~TypedExpectation() {
    899     // Check the validity of the action count if it hasn't been done
    900     // yet (for example, if the expectation was never used).
    901     CheckActionCountIfNotDone();
    902     for (UntypedActions::const_iterator it = untyped_actions_.begin();
    903          it != untyped_actions_.end(); ++it) {
    904       delete static_cast<const Action<F>*>(*it);
    905     }
    906   }
    907 
    908   // Implements the .With() clause.
    909   TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
    910     if (last_clause_ == kWith) {
    911       ExpectSpecProperty(false,
    912                          ".With() cannot appear "
    913                          "more than once in an EXPECT_CALL().");
    914     } else {
    915       ExpectSpecProperty(last_clause_ < kWith,
    916                          ".With() must be the first "
    917                          "clause in an EXPECT_CALL().");
    918     }
    919     last_clause_ = kWith;
    920 
    921     extra_matcher_ = m;
    922     extra_matcher_specified_ = true;
    923     return *this;
    924   }
    925 
    926   // Implements the .Times() clause.
    927   TypedExpectation& Times(const Cardinality& a_cardinality) {
    928     ExpectationBase::UntypedTimes(a_cardinality);
    929     return *this;
    930   }
    931 
    932   // Implements the .Times() clause.
    933   TypedExpectation& Times(int n) {
    934     return Times(Exactly(n));
    935   }
    936 
    937   // Implements the .InSequence() clause.
    938   TypedExpectation& InSequence(const Sequence& s) {
    939     ExpectSpecProperty(last_clause_ <= kInSequence,
    940                        ".InSequence() cannot appear after .After(),"
    941                        " .WillOnce(), .WillRepeatedly(), or "
    942                        ".RetiresOnSaturation().");
    943     last_clause_ = kInSequence;
    944 
    945     s.AddExpectation(GetHandle());
    946     return *this;
    947   }
    948   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
    949     return InSequence(s1).InSequence(s2);
    950   }
    951   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
    952                                const Sequence& s3) {
    953     return InSequence(s1, s2).InSequence(s3);
    954   }
    955   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
    956                                const Sequence& s3, const Sequence& s4) {
    957     return InSequence(s1, s2, s3).InSequence(s4);
    958   }
    959   TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
    960                                const Sequence& s3, const Sequence& s4,
    961                                const Sequence& s5) {
    962     return InSequence(s1, s2, s3, s4).InSequence(s5);
    963   }
    964 
    965   // Implements that .After() clause.
    966   TypedExpectation& After(const ExpectationSet& s) {
    967     ExpectSpecProperty(last_clause_ <= kAfter,
    968                        ".After() cannot appear after .WillOnce(),"
    969                        " .WillRepeatedly(), or "
    970                        ".RetiresOnSaturation().");
    971     last_clause_ = kAfter;
    972 
    973     for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
    974       immediate_prerequisites_ += *it;
    975     }
    976     return *this;
    977   }
    978   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
    979     return After(s1).After(s2);
    980   }
    981   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
    982                           const ExpectationSet& s3) {
    983     return After(s1, s2).After(s3);
    984   }
    985   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
    986                           const ExpectationSet& s3, const ExpectationSet& s4) {
    987     return After(s1, s2, s3).After(s4);
    988   }
    989   TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
    990                           const ExpectationSet& s3, const ExpectationSet& s4,
    991                           const ExpectationSet& s5) {
    992     return After(s1, s2, s3, s4).After(s5);
    993   }
    994 
    995   // Implements the .WillOnce() clause.
    996   TypedExpectation& WillOnce(const Action<F>& action) {
    997     ExpectSpecProperty(last_clause_ <= kWillOnce,
    998                        ".WillOnce() cannot appear after "
    999                        ".WillRepeatedly() or .RetiresOnSaturation().");
   1000     last_clause_ = kWillOnce;
   1001 
   1002     untyped_actions_.push_back(new Action<F>(action));
   1003     if (!cardinality_specified()) {
   1004       set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
   1005     }
   1006     return *this;
   1007   }
   1008 
   1009   // Implements the .WillRepeatedly() clause.
   1010   TypedExpectation& WillRepeatedly(const Action<F>& action) {
   1011     if (last_clause_ == kWillRepeatedly) {
   1012       ExpectSpecProperty(false,
   1013                          ".WillRepeatedly() cannot appear "
   1014                          "more than once in an EXPECT_CALL().");
   1015     } else {
   1016       ExpectSpecProperty(last_clause_ < kWillRepeatedly,
   1017                          ".WillRepeatedly() cannot appear "
   1018                          "after .RetiresOnSaturation().");
   1019     }
   1020     last_clause_ = kWillRepeatedly;
   1021     repeated_action_specified_ = true;
   1022 
   1023     repeated_action_ = action;
   1024     if (!cardinality_specified()) {
   1025       set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
   1026     }
   1027 
   1028     // Now that no more action clauses can be specified, we check
   1029     // whether their count makes sense.
   1030     CheckActionCountIfNotDone();
   1031     return *this;
   1032   }
   1033 
   1034   // Implements the .RetiresOnSaturation() clause.
   1035   TypedExpectation& RetiresOnSaturation() {
   1036     ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
   1037                        ".RetiresOnSaturation() cannot appear "
   1038                        "more than once.");
   1039     last_clause_ = kRetiresOnSaturation;
   1040     retires_on_saturation_ = true;
   1041 
   1042     // Now that no more action clauses can be specified, we check
   1043     // whether their count makes sense.
   1044     CheckActionCountIfNotDone();
   1045     return *this;
   1046   }
   1047 
   1048   // Returns the matchers for the arguments as specified inside the
   1049   // EXPECT_CALL() macro.
   1050   const ArgumentMatcherTuple& matchers() const {
   1051     return matchers_;
   1052   }
   1053 
   1054   // Returns the matcher specified by the .With() clause.
   1055   const Matcher<const ArgumentTuple&>& extra_matcher() const {
   1056     return extra_matcher_;
   1057   }
   1058 
   1059   // Returns the action specified by the .WillRepeatedly() clause.
   1060   const Action<F>& repeated_action() const { return repeated_action_; }
   1061 
   1062   // If this mock method has an extra matcher (i.e. .With(matcher)),
   1063   // describes it to the ostream.
   1064   virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
   1065     if (extra_matcher_specified_) {
   1066       *os << "    Expected args: ";
   1067       extra_matcher_.DescribeTo(os);
   1068       *os << "\n";
   1069     }
   1070   }
   1071 
   1072  private:
   1073   template <typename Function>
   1074   friend class FunctionMockerBase;
   1075 
   1076   // Returns an Expectation object that references and co-owns this
   1077   // expectation.
   1078   virtual Expectation GetHandle() {
   1079     return owner_->GetHandleOf(this);
   1080   }
   1081 
   1082   // The following methods will be called only after the EXPECT_CALL()
   1083   // statement finishes and when the current thread holds
   1084   // g_gmock_mutex.
   1085 
   1086   // Returns true iff this expectation matches the given arguments.
   1087   bool Matches(const ArgumentTuple& args) const
   1088       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1089     g_gmock_mutex.AssertHeld();
   1090     return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
   1091   }
   1092 
   1093   // Returns true iff this expectation should handle the given arguments.
   1094   bool ShouldHandleArguments(const ArgumentTuple& args) const
   1095       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1096     g_gmock_mutex.AssertHeld();
   1097 
   1098     // In case the action count wasn't checked when the expectation
   1099     // was defined (e.g. if this expectation has no WillRepeatedly()
   1100     // or RetiresOnSaturation() clause), we check it when the
   1101     // expectation is used for the first time.
   1102     CheckActionCountIfNotDone();
   1103     return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
   1104   }
   1105 
   1106   // Describes the result of matching the arguments against this
   1107   // expectation to the given ostream.
   1108   void ExplainMatchResultTo(
   1109       const ArgumentTuple& args,
   1110       ::std::ostream* os) const
   1111           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1112     g_gmock_mutex.AssertHeld();
   1113 
   1114     if (is_retired()) {
   1115       *os << "         Expected: the expectation is active\n"
   1116           << "           Actual: it is retired\n";
   1117     } else if (!Matches(args)) {
   1118       if (!TupleMatches(matchers_, args)) {
   1119         ExplainMatchFailureTupleTo(matchers_, args, os);
   1120       }
   1121       StringMatchResultListener listener;
   1122       if (!extra_matcher_.MatchAndExplain(args, &listener)) {
   1123         *os << "    Expected args: ";
   1124         extra_matcher_.DescribeTo(os);
   1125         *os << "\n           Actual: don't match";
   1126 
   1127         internal::PrintIfNotEmpty(listener.str(), os);
   1128         *os << "\n";
   1129       }
   1130     } else if (!AllPrerequisitesAreSatisfied()) {
   1131       *os << "         Expected: all pre-requisites are satisfied\n"
   1132           << "           Actual: the following immediate pre-requisites "
   1133           << "are not satisfied:\n";
   1134       ExpectationSet unsatisfied_prereqs;
   1135       FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
   1136       int i = 0;
   1137       for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
   1138            it != unsatisfied_prereqs.end(); ++it) {
   1139         it->expectation_base()->DescribeLocationTo(os);
   1140         *os << "pre-requisite #" << i++ << "\n";
   1141       }
   1142       *os << "                   (end of pre-requisites)\n";
   1143     } else {
   1144       // This line is here just for completeness' sake.  It will never
   1145       // be executed as currently the ExplainMatchResultTo() function
   1146       // is called only when the mock function call does NOT match the
   1147       // expectation.
   1148       *os << "The call matches the expectation.\n";
   1149     }
   1150   }
   1151 
   1152   // Returns the action that should be taken for the current invocation.
   1153   const Action<F>& GetCurrentAction(
   1154       const FunctionMockerBase<F>* mocker,
   1155       const ArgumentTuple& args) const
   1156           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1157     g_gmock_mutex.AssertHeld();
   1158     const int count = call_count();
   1159     Assert(count >= 1, __FILE__, __LINE__,
   1160            "call_count() is <= 0 when GetCurrentAction() is "
   1161            "called - this should never happen.");
   1162 
   1163     const int action_count = static_cast<int>(untyped_actions_.size());
   1164     if (action_count > 0 && !repeated_action_specified_ &&
   1165         count > action_count) {
   1166       // If there is at least one WillOnce() and no WillRepeatedly(),
   1167       // we warn the user when the WillOnce() clauses ran out.
   1168       ::std::stringstream ss;
   1169       DescribeLocationTo(&ss);
   1170       ss << "Actions ran out in " << source_text() << "...\n"
   1171          << "Called " << count << " times, but only "
   1172          << action_count << " WillOnce()"
   1173          << (action_count == 1 ? " is" : "s are") << " specified - ";
   1174       mocker->DescribeDefaultActionTo(args, &ss);
   1175       Log(kWarning, ss.str(), 1);
   1176     }
   1177 
   1178     return count <= action_count ?
   1179         *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
   1180         repeated_action();
   1181   }
   1182 
   1183   // Given the arguments of a mock function call, if the call will
   1184   // over-saturate this expectation, returns the default action;
   1185   // otherwise, returns the next action in this expectation.  Also
   1186   // describes *what* happened to 'what', and explains *why* Google
   1187   // Mock does it to 'why'.  This method is not const as it calls
   1188   // IncrementCallCount().  A return value of NULL means the default
   1189   // action.
   1190   const Action<F>* GetActionForArguments(
   1191       const FunctionMockerBase<F>* mocker,
   1192       const ArgumentTuple& args,
   1193       ::std::ostream* what,
   1194       ::std::ostream* why)
   1195           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1196     g_gmock_mutex.AssertHeld();
   1197     if (IsSaturated()) {
   1198       // We have an excessive call.
   1199       IncrementCallCount();
   1200       *what << "Mock function called more times than expected - ";
   1201       mocker->DescribeDefaultActionTo(args, what);
   1202       DescribeCallCountTo(why);
   1203 
   1204       // TODO(wan (at) google.com): allow the user to control whether
   1205       // unexpected calls should fail immediately or continue using a
   1206       // flag --gmock_unexpected_calls_are_fatal.
   1207       return NULL;
   1208     }
   1209 
   1210     IncrementCallCount();
   1211     RetireAllPreRequisites();
   1212 
   1213     if (retires_on_saturation_ && IsSaturated()) {
   1214       Retire();
   1215     }
   1216 
   1217     // Must be done after IncrementCount()!
   1218     *what << "Mock function call matches " << source_text() <<"...\n";
   1219     return &(GetCurrentAction(mocker, args));
   1220   }
   1221 
   1222   // All the fields below won't change once the EXPECT_CALL()
   1223   // statement finishes.
   1224   FunctionMockerBase<F>* const owner_;
   1225   ArgumentMatcherTuple matchers_;
   1226   Matcher<const ArgumentTuple&> extra_matcher_;
   1227   Action<F> repeated_action_;
   1228 
   1229   GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
   1230 };  // class TypedExpectation
   1231 
   1232 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
   1233 // specifying the default behavior of, or expectation on, a mock
   1234 // function.
   1235 
   1236 // Note: class MockSpec really belongs to the ::testing namespace.
   1237 // However if we define it in ::testing, MSVC will complain when
   1238 // classes in ::testing::internal declare it as a friend class
   1239 // template.  To workaround this compiler bug, we define MockSpec in
   1240 // ::testing::internal and import it into ::testing.
   1241 
   1242 // Logs a message including file and line number information.
   1243 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
   1244                                 const char* file, int line,
   1245                                 const std::string& message);
   1246 
   1247 template <typename F>
   1248 class MockSpec {
   1249  public:
   1250   typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
   1251   typedef typename internal::Function<F>::ArgumentMatcherTuple
   1252       ArgumentMatcherTuple;
   1253 
   1254   // Constructs a MockSpec object, given the function mocker object
   1255   // that the spec is associated with.
   1256   explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
   1257       : function_mocker_(function_mocker) {}
   1258 
   1259   // Adds a new default action spec to the function mocker and returns
   1260   // the newly created spec.
   1261   internal::OnCallSpec<F>& InternalDefaultActionSetAt(
   1262       const char* file, int line, const char* obj, const char* call) {
   1263     LogWithLocation(internal::kInfo, file, line,
   1264                     std::string("ON_CALL(") + obj + ", " + call + ") invoked");
   1265     return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
   1266   }
   1267 
   1268   // Adds a new expectation spec to the function mocker and returns
   1269   // the newly created spec.
   1270   internal::TypedExpectation<F>& InternalExpectedAt(
   1271       const char* file, int line, const char* obj, const char* call) {
   1272     const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
   1273                                   call + ")");
   1274     LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
   1275     return function_mocker_->AddNewExpectation(
   1276         file, line, source_text, matchers_);
   1277   }
   1278 
   1279  private:
   1280   template <typename Function>
   1281   friend class internal::FunctionMocker;
   1282 
   1283   void SetMatchers(const ArgumentMatcherTuple& matchers) {
   1284     matchers_ = matchers;
   1285   }
   1286 
   1287   // The function mocker that owns this spec.
   1288   internal::FunctionMockerBase<F>* const function_mocker_;
   1289   // The argument matchers specified in the spec.
   1290   ArgumentMatcherTuple matchers_;
   1291 
   1292   GTEST_DISALLOW_ASSIGN_(MockSpec);
   1293 };  // class MockSpec
   1294 
   1295 // Wrapper type for generically holding an ordinary value or lvalue reference.
   1296 // If T is not a reference type, it must be copyable or movable.
   1297 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
   1298 // T is a move-only value type (which means that it will always be copyable
   1299 // if the current platform does not support move semantics).
   1300 //
   1301 // The primary template defines handling for values, but function header
   1302 // comments describe the contract for the whole template (including
   1303 // specializations).
   1304 template <typename T>
   1305 class ReferenceOrValueWrapper {
   1306  public:
   1307   // Constructs a wrapper from the given value/reference.
   1308   explicit ReferenceOrValueWrapper(T value)
   1309       : value_(::testing::internal::move(value)) {
   1310   }
   1311 
   1312   // Unwraps and returns the underlying value/reference, exactly as
   1313   // originally passed. The behavior of calling this more than once on
   1314   // the same object is unspecified.
   1315   T Unwrap() { return ::testing::internal::move(value_); }
   1316 
   1317   // Provides nondestructive access to the underlying value/reference.
   1318   // Always returns a const reference (more precisely,
   1319   // const RemoveReference<T>&). The behavior of calling this after
   1320   // calling Unwrap on the same object is unspecified.
   1321   const T& Peek() const {
   1322     return value_;
   1323   }
   1324 
   1325  private:
   1326   T value_;
   1327 };
   1328 
   1329 // Specialization for lvalue reference types. See primary template
   1330 // for documentation.
   1331 template <typename T>
   1332 class ReferenceOrValueWrapper<T&> {
   1333  public:
   1334   // Workaround for debatable pass-by-reference lint warning (c-library-team
   1335   // policy precludes NOLINT in this context)
   1336   typedef T& reference;
   1337   explicit ReferenceOrValueWrapper(reference ref)
   1338       : value_ptr_(&ref) {}
   1339   T& Unwrap() { return *value_ptr_; }
   1340   const T& Peek() const { return *value_ptr_; }
   1341 
   1342  private:
   1343   T* value_ptr_;
   1344 };
   1345 
   1346 // MSVC warns about using 'this' in base member initializer list, so
   1347 // we need to temporarily disable the warning.  We have to do it for
   1348 // the entire class to suppress the warning, even though it's about
   1349 // the constructor only.
   1350 
   1351 #ifdef _MSC_VER
   1352 # pragma warning(push)          // Saves the current warning state.
   1353 # pragma warning(disable:4355)  // Temporarily disables warning 4355.
   1354 #endif  // _MSV_VER
   1355 
   1356 // C++ treats the void type specially.  For example, you cannot define
   1357 // a void-typed variable or pass a void value to a function.
   1358 // ActionResultHolder<T> holds a value of type T, where T must be a
   1359 // copyable type or void (T doesn't need to be default-constructable).
   1360 // It hides the syntactic difference between void and other types, and
   1361 // is used to unify the code for invoking both void-returning and
   1362 // non-void-returning mock functions.
   1363 
   1364 // Untyped base class for ActionResultHolder<T>.
   1365 class UntypedActionResultHolderBase {
   1366  public:
   1367   virtual ~UntypedActionResultHolderBase() {}
   1368 
   1369   // Prints the held value as an action's result to os.
   1370   virtual void PrintAsActionResult(::std::ostream* os) const = 0;
   1371 };
   1372 
   1373 // This generic definition is used when T is not void.
   1374 template <typename T>
   1375 class ActionResultHolder : public UntypedActionResultHolderBase {
   1376  public:
   1377   // Returns the held value. Must not be called more than once.
   1378   T Unwrap() {
   1379     return result_.Unwrap();
   1380   }
   1381 
   1382   // Prints the held value as an action's result to os.
   1383   virtual void PrintAsActionResult(::std::ostream* os) const {
   1384     *os << "\n          Returns: ";
   1385     // T may be a reference type, so we don't use UniversalPrint().
   1386     UniversalPrinter<T>::Print(result_.Peek(), os);
   1387   }
   1388 
   1389   // Performs the given mock function's default action and returns the
   1390   // result in a new-ed ActionResultHolder.
   1391   template <typename F>
   1392   static ActionResultHolder* PerformDefaultAction(
   1393       const FunctionMockerBase<F>* func_mocker,
   1394       const typename Function<F>::ArgumentTuple& args,
   1395       const std::string& call_description) {
   1396     return new ActionResultHolder(Wrapper(
   1397         func_mocker->PerformDefaultAction(args, call_description)));
   1398   }
   1399 
   1400   // Performs the given action and returns the result in a new-ed
   1401   // ActionResultHolder.
   1402   template <typename F>
   1403   static ActionResultHolder*
   1404   PerformAction(const Action<F>& action,
   1405                 const typename Function<F>::ArgumentTuple& args) {
   1406     return new ActionResultHolder(Wrapper(action.Perform(args)));
   1407   }
   1408 
   1409  private:
   1410   typedef ReferenceOrValueWrapper<T> Wrapper;
   1411 
   1412   explicit ActionResultHolder(Wrapper result)
   1413       : result_(::testing::internal::move(result)) {
   1414   }
   1415 
   1416   Wrapper result_;
   1417 
   1418   GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
   1419 };
   1420 
   1421 // Specialization for T = void.
   1422 template <>
   1423 class ActionResultHolder<void> : public UntypedActionResultHolderBase {
   1424  public:
   1425   void Unwrap() { }
   1426 
   1427   virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
   1428 
   1429   // Performs the given mock function's default action and returns ownership
   1430   // of an empty ActionResultHolder*.
   1431   template <typename F>
   1432   static ActionResultHolder* PerformDefaultAction(
   1433       const FunctionMockerBase<F>* func_mocker,
   1434       const typename Function<F>::ArgumentTuple& args,
   1435       const std::string& call_description) {
   1436     func_mocker->PerformDefaultAction(args, call_description);
   1437     return new ActionResultHolder;
   1438   }
   1439 
   1440   // Performs the given action and returns ownership of an empty
   1441   // ActionResultHolder*.
   1442   template <typename F>
   1443   static ActionResultHolder* PerformAction(
   1444       const Action<F>& action,
   1445       const typename Function<F>::ArgumentTuple& args) {
   1446     action.Perform(args);
   1447     return new ActionResultHolder;
   1448   }
   1449 
   1450  private:
   1451   ActionResultHolder() {}
   1452   GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
   1453 };
   1454 
   1455 // The base of the function mocker class for the given function type.
   1456 // We put the methods in this class instead of its child to avoid code
   1457 // bloat.
   1458 template <typename F>
   1459 class FunctionMockerBase : public UntypedFunctionMockerBase {
   1460  public:
   1461   typedef typename Function<F>::Result Result;
   1462   typedef typename Function<F>::ArgumentTuple ArgumentTuple;
   1463   typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
   1464 
   1465   FunctionMockerBase() : current_spec_(this) {}
   1466 
   1467   // The destructor verifies that all expectations on this mock
   1468   // function have been satisfied.  If not, it will report Google Test
   1469   // non-fatal failures for the violations.
   1470   virtual ~FunctionMockerBase()
   1471         GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
   1472     MutexLock l(&g_gmock_mutex);
   1473     VerifyAndClearExpectationsLocked();
   1474     Mock::UnregisterLocked(this);
   1475     ClearDefaultActionsLocked();
   1476   }
   1477 
   1478   // Returns the ON_CALL spec that matches this mock function with the
   1479   // given arguments; returns NULL if no matching ON_CALL is found.
   1480   // L = *
   1481   const OnCallSpec<F>* FindOnCallSpec(
   1482       const ArgumentTuple& args) const {
   1483     for (UntypedOnCallSpecs::const_reverse_iterator it
   1484              = untyped_on_call_specs_.rbegin();
   1485          it != untyped_on_call_specs_.rend(); ++it) {
   1486       const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
   1487       if (spec->Matches(args))
   1488         return spec;
   1489     }
   1490 
   1491     return NULL;
   1492   }
   1493 
   1494   // Performs the default action of this mock function on the given
   1495   // arguments and returns the result. Asserts (or throws if
   1496   // exceptions are enabled) with a helpful call descrption if there
   1497   // is no valid return value. This method doesn't depend on the
   1498   // mutable state of this object, and thus can be called concurrently
   1499   // without locking.
   1500   // L = *
   1501   Result PerformDefaultAction(const ArgumentTuple& args,
   1502                               const std::string& call_description) const {
   1503     const OnCallSpec<F>* const spec =
   1504         this->FindOnCallSpec(args);
   1505     if (spec != NULL) {
   1506       return spec->GetAction().Perform(args);
   1507     }
   1508     const std::string message =
   1509         call_description +
   1510         "\n    The mock function has no default action "
   1511         "set, and its return type has no default value set.";
   1512 #if GTEST_HAS_EXCEPTIONS
   1513     if (!DefaultValue<Result>::Exists()) {
   1514       throw std::runtime_error(message);
   1515     }
   1516 #else
   1517     Assert(DefaultValue<Result>::Exists(), "", -1, message);
   1518 #endif
   1519     return DefaultValue<Result>::Get();
   1520   }
   1521 
   1522   // Performs the default action with the given arguments and returns
   1523   // the action's result.  The call description string will be used in
   1524   // the error message to describe the call in the case the default
   1525   // action fails.  The caller is responsible for deleting the result.
   1526   // L = *
   1527   virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
   1528       const void* untyped_args,  // must point to an ArgumentTuple
   1529       const std::string& call_description) const {
   1530     const ArgumentTuple& args =
   1531         *static_cast<const ArgumentTuple*>(untyped_args);
   1532     return ResultHolder::PerformDefaultAction(this, args, call_description);
   1533   }
   1534 
   1535   // Performs the given action with the given arguments and returns
   1536   // the action's result.  The caller is responsible for deleting the
   1537   // result.
   1538   // L = *
   1539   virtual UntypedActionResultHolderBase* UntypedPerformAction(
   1540       const void* untyped_action, const void* untyped_args) const {
   1541     // Make a copy of the action before performing it, in case the
   1542     // action deletes the mock object (and thus deletes itself).
   1543     const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
   1544     const ArgumentTuple& args =
   1545         *static_cast<const ArgumentTuple*>(untyped_args);
   1546     return ResultHolder::PerformAction(action, args);
   1547   }
   1548 
   1549   // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
   1550   // clears the ON_CALL()s set on this mock function.
   1551   virtual void ClearDefaultActionsLocked()
   1552       GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1553     g_gmock_mutex.AssertHeld();
   1554 
   1555     // Deleting our default actions may trigger other mock objects to be
   1556     // deleted, for example if an action contains a reference counted smart
   1557     // pointer to that mock object, and that is the last reference. So if we
   1558     // delete our actions within the context of the global mutex we may deadlock
   1559     // when this method is called again. Instead, make a copy of the set of
   1560     // actions to delete, clear our set within the mutex, and then delete the
   1561     // actions outside of the mutex.
   1562     UntypedOnCallSpecs specs_to_delete;
   1563     untyped_on_call_specs_.swap(specs_to_delete);
   1564 
   1565     g_gmock_mutex.Unlock();
   1566     for (UntypedOnCallSpecs::const_iterator it =
   1567              specs_to_delete.begin();
   1568          it != specs_to_delete.end(); ++it) {
   1569       delete static_cast<const OnCallSpec<F>*>(*it);
   1570     }
   1571 
   1572     // Lock the mutex again, since the caller expects it to be locked when we
   1573     // return.
   1574     g_gmock_mutex.Lock();
   1575   }
   1576 
   1577  protected:
   1578   template <typename Function>
   1579   friend class MockSpec;
   1580 
   1581   typedef ActionResultHolder<Result> ResultHolder;
   1582 
   1583   // Returns the result of invoking this mock function with the given
   1584   // arguments.  This function can be safely called from multiple
   1585   // threads concurrently.
   1586   Result InvokeWith(const ArgumentTuple& args)
   1587         GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
   1588     scoped_ptr<ResultHolder> holder(
   1589         DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args)));
   1590     return holder->Unwrap();
   1591   }
   1592 
   1593   // Adds and returns a default action spec for this mock function.
   1594   OnCallSpec<F>& AddNewOnCallSpec(
   1595       const char* file, int line,
   1596       const ArgumentMatcherTuple& m)
   1597           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
   1598     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
   1599     OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
   1600     untyped_on_call_specs_.push_back(on_call_spec);
   1601     return *on_call_spec;
   1602   }
   1603 
   1604   // Adds and returns an expectation spec for this mock function.
   1605   TypedExpectation<F>& AddNewExpectation(const char* file, int line,
   1606                                          const std::string& source_text,
   1607                                          const ArgumentMatcherTuple& m)
   1608       GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
   1609     Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
   1610     TypedExpectation<F>* const expectation =
   1611         new TypedExpectation<F>(this, file, line, source_text, m);
   1612     const linked_ptr<ExpectationBase> untyped_expectation(expectation);
   1613     untyped_expectations_.push_back(untyped_expectation);
   1614 
   1615     // Adds this expectation into the implicit sequence if there is one.
   1616     Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
   1617     if (implicit_sequence != NULL) {
   1618       implicit_sequence->AddExpectation(Expectation(untyped_expectation));
   1619     }
   1620 
   1621     return *expectation;
   1622   }
   1623 
   1624   // The current spec (either default action spec or expectation spec)
   1625   // being described on this function mocker.
   1626   MockSpec<F>& current_spec() { return current_spec_; }
   1627 
   1628  private:
   1629   template <typename Func> friend class TypedExpectation;
   1630 
   1631   // Some utilities needed for implementing UntypedInvokeWith().
   1632 
   1633   // Describes what default action will be performed for the given
   1634   // arguments.
   1635   // L = *
   1636   void DescribeDefaultActionTo(const ArgumentTuple& args,
   1637                                ::std::ostream* os) const {
   1638     const OnCallSpec<F>* const spec = FindOnCallSpec(args);
   1639 
   1640     if (spec == NULL) {
   1641       *os << (internal::type_equals<Result, void>::value ?
   1642               "returning directly.\n" :
   1643               "returning default value.\n");
   1644     } else {
   1645       *os << "taking default action specified at:\n"
   1646           << FormatFileLocation(spec->file(), spec->line()) << "\n";
   1647     }
   1648   }
   1649 
   1650   // Writes a message that the call is uninteresting (i.e. neither
   1651   // explicitly expected nor explicitly unexpected) to the given
   1652   // ostream.
   1653   virtual void UntypedDescribeUninterestingCall(
   1654       const void* untyped_args,
   1655       ::std::ostream* os) const
   1656           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
   1657     const ArgumentTuple& args =
   1658         *static_cast<const ArgumentTuple*>(untyped_args);
   1659     *os << "Uninteresting mock function call - ";
   1660     DescribeDefaultActionTo(args, os);
   1661     *os << "    Function call: " << Name();
   1662     UniversalPrint(args, os);
   1663   }
   1664 
   1665   // Returns the expectation that matches the given function arguments
   1666   // (or NULL is there's no match); when a match is found,
   1667   // untyped_action is set to point to the action that should be
   1668   // performed (or NULL if the action is "do default"), and
   1669   // is_excessive is modified to indicate whether the call exceeds the
   1670   // expected number.
   1671   //
   1672   // Critical section: We must find the matching expectation and the
   1673   // corresponding action that needs to be taken in an ATOMIC
   1674   // transaction.  Otherwise another thread may call this mock
   1675   // method in the middle and mess up the state.
   1676   //
   1677   // However, performing the action has to be left out of the critical
   1678   // section.  The reason is that we have no control on what the
   1679   // action does (it can invoke an arbitrary user function or even a
   1680   // mock function) and excessive locking could cause a dead lock.
   1681   virtual const ExpectationBase* UntypedFindMatchingExpectation(
   1682       const void* untyped_args,
   1683       const void** untyped_action, bool* is_excessive,
   1684       ::std::ostream* what, ::std::ostream* why)
   1685           GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
   1686     const ArgumentTuple& args =
   1687         *static_cast<const ArgumentTuple*>(untyped_args);
   1688     MutexLock l(&g_gmock_mutex);
   1689     TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
   1690     if (exp == NULL) {  // A match wasn't found.
   1691       this->FormatUnexpectedCallMessageLocked(args, what, why);
   1692       return NULL;
   1693     }
   1694 
   1695     // This line must be done before calling GetActionForArguments(),
   1696     // which will increment the call count for *exp and thus affect
   1697     // its saturation status.
   1698     *is_excessive = exp->IsSaturated();
   1699     const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
   1700     if (action != NULL && action->IsDoDefault())
   1701       action = NULL;  // Normalize "do default" to NULL.
   1702     *untyped_action = action;
   1703     return exp;
   1704   }
   1705 
   1706   // Prints the given function arguments to the ostream.
   1707   virtual void UntypedPrintArgs(const void* untyped_args,
   1708                                 ::std::ostream* os) const {
   1709     const ArgumentTuple& args =
   1710         *static_cast<const ArgumentTuple*>(untyped_args);
   1711     UniversalPrint(args, os);
   1712   }
   1713 
   1714   // Returns the expectation that matches the arguments, or NULL if no
   1715   // expectation matches them.
   1716   TypedExpectation<F>* FindMatchingExpectationLocked(
   1717       const ArgumentTuple& args) const
   1718           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1719     g_gmock_mutex.AssertHeld();
   1720     for (typename UntypedExpectations::const_reverse_iterator it =
   1721              untyped_expectations_.rbegin();
   1722          it != untyped_expectations_.rend(); ++it) {
   1723       TypedExpectation<F>* const exp =
   1724           static_cast<TypedExpectation<F>*>(it->get());
   1725       if (exp->ShouldHandleArguments(args)) {
   1726         return exp;
   1727       }
   1728     }
   1729     return NULL;
   1730   }
   1731 
   1732   // Returns a message that the arguments don't match any expectation.
   1733   void FormatUnexpectedCallMessageLocked(
   1734       const ArgumentTuple& args,
   1735       ::std::ostream* os,
   1736       ::std::ostream* why) const
   1737           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1738     g_gmock_mutex.AssertHeld();
   1739     *os << "\nUnexpected mock function call - ";
   1740     DescribeDefaultActionTo(args, os);
   1741     PrintTriedExpectationsLocked(args, why);
   1742   }
   1743 
   1744   // Prints a list of expectations that have been tried against the
   1745   // current mock function call.
   1746   void PrintTriedExpectationsLocked(
   1747       const ArgumentTuple& args,
   1748       ::std::ostream* why) const
   1749           GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
   1750     g_gmock_mutex.AssertHeld();
   1751     const int count = static_cast<int>(untyped_expectations_.size());
   1752     *why << "Google Mock tried the following " << count << " "
   1753          << (count == 1 ? "expectation, but it didn't match" :
   1754              "expectations, but none matched")
   1755          << ":\n";
   1756     for (int i = 0; i < count; i++) {
   1757       TypedExpectation<F>* const expectation =
   1758           static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
   1759       *why << "\n";
   1760       expectation->DescribeLocationTo(why);
   1761       if (count > 1) {
   1762         *why << "tried expectation #" << i << ": ";
   1763       }
   1764       *why << expectation->source_text() << "...\n";
   1765       expectation->ExplainMatchResultTo(args, why);
   1766       expectation->DescribeCallCountTo(why);
   1767     }
   1768   }
   1769 
   1770   // The current spec (either default action spec or expectation spec)
   1771   // being described on this function mocker.
   1772   MockSpec<F> current_spec_;
   1773 
   1774   // There is no generally useful and implementable semantics of
   1775   // copying a mock object, so copying a mock is usually a user error.
   1776   // Thus we disallow copying function mockers.  If the user really
   1777   // wants to copy a mock object, they should implement their own copy
   1778   // operation, for example:
   1779   //
   1780   //   class MockFoo : public Foo {
   1781   //    public:
   1782   //     // Defines a copy constructor explicitly.
   1783   //     MockFoo(const MockFoo& src) {}
   1784   //     ...
   1785   //   };
   1786   GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
   1787 };  // class FunctionMockerBase
   1788 
   1789 #ifdef _MSC_VER
   1790 # pragma warning(pop)  // Restores the warning state.
   1791 #endif  // _MSV_VER
   1792 
   1793 // Implements methods of FunctionMockerBase.
   1794 
   1795 // Verifies that all expectations on this mock function have been
   1796 // satisfied.  Reports one or more Google Test non-fatal failures and
   1797 // returns false if not.
   1798 
   1799 // Reports an uninteresting call (whose description is in msg) in the
   1800 // manner specified by 'reaction'.
   1801 void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
   1802 
   1803 }  // namespace internal
   1804 
   1805 // The style guide prohibits "using" statements in a namespace scope
   1806 // inside a header file.  However, the MockSpec class template is
   1807 // meant to be defined in the ::testing namespace.  The following line
   1808 // is just a trick for working around a bug in MSVC 8.0, which cannot
   1809 // handle it if we define MockSpec in ::testing.
   1810 using internal::MockSpec;
   1811 
   1812 // Const(x) is a convenient function for obtaining a const reference
   1813 // to x.  This is useful for setting expectations on an overloaded
   1814 // const mock method, e.g.
   1815 //
   1816 //   class MockFoo : public FooInterface {
   1817 //    public:
   1818 //     MOCK_METHOD0(Bar, int());
   1819 //     MOCK_CONST_METHOD0(Bar, int&());
   1820 //   };
   1821 //
   1822 //   MockFoo foo;
   1823 //   // Expects a call to non-const MockFoo::Bar().
   1824 //   EXPECT_CALL(foo, Bar());
   1825 //   // Expects a call to const MockFoo::Bar().
   1826 //   EXPECT_CALL(Const(foo), Bar());
   1827 template <typename T>
   1828 inline const T& Const(const T& x) { return x; }
   1829 
   1830 // Constructs an Expectation object that references and co-owns exp.
   1831 inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
   1832     : expectation_base_(exp.GetHandle().expectation_base()) {}
   1833 
   1834 }  // namespace testing
   1835 
   1836 // A separate macro is required to avoid compile errors when the name
   1837 // of the method used in call is a result of macro expansion.
   1838 // See CompilesWithMethodNameExpandedFromMacro tests in
   1839 // internal/gmock-spec-builders_test.cc for more details.
   1840 #define GMOCK_ON_CALL_IMPL_(obj, call) \
   1841     ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
   1842                                                     #obj, #call)
   1843 #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
   1844 
   1845 #define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
   1846     ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
   1847 #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
   1848 
   1849 #endif  // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
   1850