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