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