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