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