blob: cf1e7e23a7d5deb2ccccf271e05a7392104582c3 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements the ON_CALL() and EXPECT_CALL() macros.
35//
36// A user can use the ON_CALL() macro to specify the default action of
37// a mock method. The syntax is:
38//
39// ON_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000040// .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +000041// .WillByDefault(action);
42//
zhanyong.wanbf550852009-06-09 06:09:53 +000043// where the .With() clause is optional.
shiqiane35fdd92008-12-10 05:08:54 +000044//
45// A user can use the EXPECT_CALL() macro to specify an expectation on
46// a mock method. The syntax is:
47//
48// EXPECT_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000049// .With(multi-argument-matchers)
shiqiane35fdd92008-12-10 05:08:54 +000050// .Times(cardinality)
51// .InSequence(sequences)
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000052// .After(expectations)
shiqiane35fdd92008-12-10 05:08:54 +000053// .WillOnce(action)
54// .WillRepeatedly(action)
55// .RetiresOnSaturation();
56//
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000057// where all clauses are optional, and .InSequence()/.After()/
58// .WillOnce() can appear any number of times.
shiqiane35fdd92008-12-10 05:08:54 +000059
60#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
61#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62
63#include <map>
64#include <set>
65#include <sstream>
66#include <string>
67#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000068#include "gmock/gmock-actions.h"
69#include "gmock/gmock-cardinalities.h"
70#include "gmock/gmock-matchers.h"
71#include "gmock/internal/gmock-internal-utils.h"
72#include "gmock/internal/gmock-port.h"
73#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000074
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050075#if GTEST_HAS_EXCEPTIONS
76# include <stdexcept> // NOLINT
77#endif
78
shiqiane35fdd92008-12-10 05:08:54 +000079namespace testing {
80
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000081// An abstract handle of an expectation.
82class Expectation;
83
84// A set of expectation handles.
85class ExpectationSet;
86
shiqiane35fdd92008-12-10 05:08:54 +000087// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
88// and MUST NOT BE USED IN USER CODE!!!
89namespace internal {
90
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000091// Implements a mock function.
92template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000093
94// Base class for expectations.
95class ExpectationBase;
96
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000097// Implements an expectation.
98template <typename F> class TypedExpectation;
99
shiqiane35fdd92008-12-10 05:08:54 +0000100// Helper class for testing the Expectation class template.
101class ExpectationTester;
102
103// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000104template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000105
shiqiane35fdd92008-12-10 05:08:54 +0000106// Protects the mock object registry (in class Mock), all function
107// mockers, and all expectations.
108//
109// The reason we don't use more fine-grained protection is: when a
110// mock function Foo() is called, it needs to consult its expectations
111// to see which one should be picked. If another thread is allowed to
112// call a mock function (either Foo() or a different one) at the same
113// time, it could affect the "retired" attributes of Foo()'s
114// expectations when InSequence() is used, and thus affect which
115// expectation gets picked. Therefore, we sequence all mock function
116// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000117GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000118
zhanyong.waned6c9272011-02-23 19:39:27 +0000119// Untyped base class for ActionResultHolder<R>.
120class UntypedActionResultHolderBase;
121
shiqiane35fdd92008-12-10 05:08:54 +0000122// Abstract base class of FunctionMockerBase. This is the
123// type-agnostic part of the function mocker interface. Its pure
124// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000125class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000126 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000127 UntypedFunctionMockerBase();
128 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000129
130 // Verifies that all expectations on this mock function have been
131 // satisfied. Reports one or more Google Test non-fatal failures
132 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000133 bool VerifyAndClearExpectationsLocked()
134 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000135
136 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000137 virtual void ClearDefaultActionsLocked()
138 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000139
140 // In all of the following Untyped* functions, it's the caller's
141 // responsibility to guarantee the correctness of the arguments'
142 // types.
143
144 // Performs the default action with the given arguments and returns
145 // the action's result. The call description string will be used in
146 // the error message to describe the call in the case the default
147 // action fails.
148 // L = *
149 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400150 void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000151
152 // Performs the given action with the given arguments and returns
153 // the action's result.
154 // L = *
155 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400156 const void* untyped_action, void* untyped_args) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000157
158 // Writes a message that the call is uninteresting (i.e. neither
159 // explicitly expected nor explicitly unexpected) to the given
160 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +0000161 virtual void UntypedDescribeUninterestingCall(
162 const void* untyped_args,
163 ::std::ostream* os) const
164 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000165
166 // Returns the expectation that matches the given function arguments
167 // (or NULL is there's no match); when a match is found,
168 // untyped_action is set to point to the action that should be
169 // performed (or NULL if the action is "do default"), and
170 // is_excessive is modified to indicate whether the call exceeds the
171 // expected number.
zhanyong.waned6c9272011-02-23 19:39:27 +0000172 virtual const ExpectationBase* UntypedFindMatchingExpectation(
173 const void* untyped_args,
174 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000175 ::std::ostream* what, ::std::ostream* why)
176 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000177
178 // Prints the given function arguments to the ostream.
179 virtual void UntypedPrintArgs(const void* untyped_args,
180 ::std::ostream* os) const = 0;
181
182 // Sets the mock object this mock method belongs to, and registers
183 // this information in the global mock registry. Will be called
184 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
185 // method.
186 // TODO(wan@google.com): rename to SetAndRegisterOwner().
vladlosev4d60a592011-10-24 21:16:22 +0000187 void RegisterOwner(const void* mock_obj)
188 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000189
190 // Sets the mock object this mock method belongs to, and sets the
191 // name of the mock function. Will be called upon each invocation
192 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000193 void SetOwnerAndName(const void* mock_obj, const char* name)
194 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000195
196 // Returns the mock object this mock method belongs to. Must be
197 // called after RegisterOwner() or SetOwnerAndName() has been
198 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000199 const void* MockObject() const
200 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000201
202 // Returns the name of this mock method. Must be called after
203 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000204 const char* Name() const
205 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000206
207 // Returns the result of invoking this mock function with the given
208 // arguments. This function can be safely called from multiple
209 // threads concurrently. The caller is responsible for deleting the
210 // result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400211 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
212 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000213
214 protected:
215 typedef std::vector<const void*> UntypedOnCallSpecs;
216
217 typedef std::vector<internal::linked_ptr<ExpectationBase> >
218 UntypedExpectations;
219
220 // Returns an Expectation object that references and co-owns exp,
221 // which must be an expectation on this mock function.
222 Expectation GetHandleOf(ExpectationBase* exp);
223
224 // Address of the mock object this mock method belongs to. Only
225 // valid after this mock method has been called or
226 // ON_CALL/EXPECT_CALL has been invoked on it.
227 const void* mock_obj_; // Protected by g_gmock_mutex.
228
229 // Name of the function being mocked. Only valid after this mock
230 // method has been called.
231 const char* name_; // Protected by g_gmock_mutex.
232
233 // All default action specs for this function mocker.
234 UntypedOnCallSpecs untyped_on_call_specs_;
235
236 // All expectations for this function mocker.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400237 //
238 // It's undefined behavior to interleave expectations (EXPECT_CALLs
239 // or ON_CALLs) and mock function calls. Also, the order of
240 // expectations is important. Therefore it's a logic race condition
241 // to read/write untyped_expectations_ concurrently. In order for
242 // tools like tsan to catch concurrent read/write accesses to
243 // untyped_expectations, we deliberately leave accesses to it
244 // unprotected.
zhanyong.waned6c9272011-02-23 19:39:27 +0000245 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000246}; // class UntypedFunctionMockerBase
247
zhanyong.waned6c9272011-02-23 19:39:27 +0000248// Untyped base class for OnCallSpec<F>.
249class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000250 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000251 // The arguments are the location of the ON_CALL() statement.
252 UntypedOnCallSpecBase(const char* a_file, int a_line)
253 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000254
255 // Where in the source file was the default action spec defined?
256 const char* file() const { return file_; }
257 int line() const { return line_; }
258
zhanyong.waned6c9272011-02-23 19:39:27 +0000259 protected:
260 // Gives each clause in the ON_CALL() statement a name.
261 enum Clause {
262 // Do not change the order of the enum members! The run-time
263 // syntax checking relies on it.
264 kNone,
265 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000266 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000267 };
268
269 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400270 void AssertSpecProperty(bool property,
271 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000272 Assert(property, file_, line_, failure_message);
273 }
274
275 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400276 void ExpectSpecProperty(bool property,
277 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000278 Expect(property, file_, line_, failure_message);
279 }
280
281 const char* file_;
282 int line_;
283
284 // The last clause in the ON_CALL() statement as seen so far.
285 // Initially kNone and changes as the statement is parsed.
286 Clause last_clause_;
287}; // class UntypedOnCallSpecBase
288
289// This template class implements an ON_CALL spec.
290template <typename F>
291class OnCallSpec : public UntypedOnCallSpecBase {
292 public:
293 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
294 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
295
296 // Constructs an OnCallSpec object from the information inside
297 // the parenthesis of an ON_CALL() statement.
298 OnCallSpec(const char* a_file, int a_line,
299 const ArgumentMatcherTuple& matchers)
300 : UntypedOnCallSpecBase(a_file, a_line),
301 matchers_(matchers),
302 // By default, extra_matcher_ should match anything. However,
303 // we cannot initialize it with _ as that triggers a compiler
304 // bug in Symbian's C++ compiler (cannot decide between two
305 // overloaded constructors of Matcher<const ArgumentTuple&>).
306 extra_matcher_(A<const ArgumentTuple&>()) {
307 }
308
zhanyong.wanbf550852009-06-09 06:09:53 +0000309 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000310 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000311 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000312 ExpectSpecProperty(last_clause_ < kWith,
313 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000314 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000315 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000316
317 extra_matcher_ = m;
318 return *this;
319 }
320
321 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000322 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000323 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000324 ".WillByDefault() must appear "
325 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000326 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000327
328 ExpectSpecProperty(!action.IsDoDefault(),
329 "DoDefault() cannot be used in ON_CALL().");
330 action_ = action;
331 return *this;
332 }
333
334 // Returns true iff the given arguments match the matchers.
335 bool Matches(const ArgumentTuple& args) const {
336 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
337 }
338
339 // Returns the action specified by the user.
340 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000341 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000342 ".WillByDefault() must appear exactly "
343 "once in an ON_CALL().");
344 return action_;
345 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000346
shiqiane35fdd92008-12-10 05:08:54 +0000347 private:
shiqiane35fdd92008-12-10 05:08:54 +0000348 // The information in statement
349 //
350 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000351 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000352 // .WillByDefault(action);
353 //
354 // is recorded in the data members like this:
355 //
356 // source file that contains the statement => file_
357 // line number of the statement => line_
358 // matchers => matchers_
359 // multi-argument-matcher => extra_matcher_
360 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000361 ArgumentMatcherTuple matchers_;
362 Matcher<const ArgumentTuple&> extra_matcher_;
363 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000364}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000365
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000366// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000367enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000368 kAllow,
369 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000370 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000371};
372
373} // namespace internal
374
375// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000376class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000377 public:
378 // The following public methods can be called concurrently.
379
zhanyong.wandf35a762009-04-22 22:25:31 +0000380 // Tells Google Mock to ignore mock_obj when checking for leaked
381 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000382 static void AllowLeak(const void* mock_obj)
383 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000384
shiqiane35fdd92008-12-10 05:08:54 +0000385 // Verifies and clears all expectations on the given mock object.
386 // If the expectations aren't satisfied, generates one or more
387 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000388 static bool VerifyAndClearExpectations(void* mock_obj)
389 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000390
391 // Verifies all expectations on the given mock object and clears its
392 // default actions and expectations. Returns true iff the
393 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000394 static bool VerifyAndClear(void* mock_obj)
395 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000396
shiqiane35fdd92008-12-10 05:08:54 +0000397 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000398 friend class internal::UntypedFunctionMockerBase;
399
shiqiane35fdd92008-12-10 05:08:54 +0000400 // Needed for a function mocker to register itself (so that we know
401 // how to clear a mock object).
402 template <typename F>
403 friend class internal::FunctionMockerBase;
404
shiqiane35fdd92008-12-10 05:08:54 +0000405 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700406 friend class NiceMock;
shiqiane35fdd92008-12-10 05:08:54 +0000407
408 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700409 friend class NaggyMock;
zhanyong.wan844fa942013-03-01 01:54:22 +0000410
411 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700412 friend class StrictMock;
shiqiane35fdd92008-12-10 05:08:54 +0000413
414 // Tells Google Mock to allow uninteresting calls on the given mock
415 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000416 static void AllowUninterestingCalls(const void* mock_obj)
417 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000418
419 // Tells Google Mock to warn the user about uninteresting calls on
420 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000421 static void WarnUninterestingCalls(const void* mock_obj)
422 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000423
424 // Tells Google Mock to fail uninteresting calls on the given mock
425 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000426 static void FailUninterestingCalls(const void* mock_obj)
427 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000428
429 // Tells Google Mock the given mock object is being destroyed and
430 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000431 static void UnregisterCallReaction(const void* mock_obj)
432 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000433
434 // Returns the reaction Google Mock will have on uninteresting calls
435 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000436 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000437 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000438 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000439
440 // Verifies that all expectations on the given mock object have been
441 // satisfied. Reports one or more Google Test non-fatal failures
442 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000443 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
444 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000445
446 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000447 static void ClearDefaultActionsLocked(void* mock_obj)
448 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000449
450 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000451 static void Register(
452 const void* mock_obj,
453 internal::UntypedFunctionMockerBase* mocker)
454 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000455
zhanyong.wandf35a762009-04-22 22:25:31 +0000456 // Tells Google Mock where in the source code mock_obj is used in an
457 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
458 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000459 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000460 const void* mock_obj, const char* file, int line)
461 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000462
shiqiane35fdd92008-12-10 05:08:54 +0000463 // Unregisters a mock method; removes the owning mock object from
464 // the registry when the last mock method associated with it has
465 // been unregistered. This is called only in the destructor of
466 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000467 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
468 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000469}; // class Mock
470
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000471// An abstract handle of an expectation. Useful in the .After()
472// clause of EXPECT_CALL() for setting the (partial) order of
473// expectations. The syntax:
474//
475// Expectation e1 = EXPECT_CALL(...)...;
476// EXPECT_CALL(...).After(e1)...;
477//
478// sets two expectations where the latter can only be matched after
479// the former has been satisfied.
480//
481// Notes:
482// - This class is copyable and has value semantics.
483// - Constness is shallow: a const Expectation object itself cannot
484// be modified, but the mutable methods of the ExpectationBase
485// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000486// - The constructors and destructor are defined out-of-line because
487// the Symbian WINSCW compiler wants to otherwise instantiate them
488// when it sees this class definition, at which point it doesn't have
489// ExpectationBase available yet, leading to incorrect destruction
490// in the linked_ptr (or compilation errors if using a checking
491// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000492class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000493 public:
494 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000495 Expectation();
496
497 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000498
499 // This single-argument ctor must not be explicit, in order to support the
500 // Expectation e = EXPECT_CALL(...);
501 // syntax.
502 //
503 // A TypedExpectation object stores its pre-requisites as
504 // Expectation objects, and needs to call the non-const Retire()
505 // method on the ExpectationBase objects they reference. Therefore
506 // Expectation must receive a *non-const* reference to the
507 // ExpectationBase object.
508 Expectation(internal::ExpectationBase& exp); // NOLINT
509
510 // The compiler-generated copy ctor and operator= work exactly as
511 // intended, so we don't need to define our own.
512
513 // Returns true iff rhs references the same expectation as this object does.
514 bool operator==(const Expectation& rhs) const {
515 return expectation_base_ == rhs.expectation_base_;
516 }
517
518 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
519
520 private:
521 friend class ExpectationSet;
522 friend class Sequence;
523 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000524 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000525
526 template <typename F>
527 friend class ::testing::internal::FunctionMockerBase;
528
529 template <typename F>
530 friend class ::testing::internal::TypedExpectation;
531
532 // This comparator is needed for putting Expectation objects into a set.
533 class Less {
534 public:
535 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
536 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
537 }
538 };
539
540 typedef ::std::set<Expectation, Less> Set;
541
542 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000543 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000544
545 // Returns the expectation this object references.
546 const internal::linked_ptr<internal::ExpectationBase>&
547 expectation_base() const {
548 return expectation_base_;
549 }
550
551 // A linked_ptr that co-owns the expectation this handle references.
552 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
553};
554
555// A set of expectation handles. Useful in the .After() clause of
556// EXPECT_CALL() for setting the (partial) order of expectations. The
557// syntax:
558//
559// ExpectationSet es;
560// es += EXPECT_CALL(...)...;
561// es += EXPECT_CALL(...)...;
562// EXPECT_CALL(...).After(es)...;
563//
564// sets three expectations where the last one can only be matched
565// after the first two have both been satisfied.
566//
567// This class is copyable and has value semantics.
568class ExpectationSet {
569 public:
570 // A bidirectional iterator that can read a const element in the set.
571 typedef Expectation::Set::const_iterator const_iterator;
572
573 // An object stored in the set. This is an alias of Expectation.
574 typedef Expectation::Set::value_type value_type;
575
576 // Constructs an empty set.
577 ExpectationSet() {}
578
579 // This single-argument ctor must not be explicit, in order to support the
580 // ExpectationSet es = EXPECT_CALL(...);
581 // syntax.
582 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
583 *this += Expectation(exp);
584 }
585
586 // This single-argument ctor implements implicit conversion from
587 // Expectation and thus must not be explicit. This allows either an
588 // Expectation or an ExpectationSet to be used in .After().
589 ExpectationSet(const Expectation& e) { // NOLINT
590 *this += e;
591 }
592
593 // The compiler-generator ctor and operator= works exactly as
594 // intended, so we don't need to define our own.
595
596 // Returns true iff rhs contains the same set of Expectation objects
597 // as this does.
598 bool operator==(const ExpectationSet& rhs) const {
599 return expectations_ == rhs.expectations_;
600 }
601
602 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
603
604 // Implements the syntax
605 // expectation_set += EXPECT_CALL(...);
606 ExpectationSet& operator+=(const Expectation& e) {
607 expectations_.insert(e);
608 return *this;
609 }
610
611 int size() const { return static_cast<int>(expectations_.size()); }
612
613 const_iterator begin() const { return expectations_.begin(); }
614 const_iterator end() const { return expectations_.end(); }
615
616 private:
617 Expectation::Set expectations_;
618};
619
620
shiqiane35fdd92008-12-10 05:08:54 +0000621// Sequence objects are used by a user to specify the relative order
622// in which the expectations should match. They are copyable (we rely
623// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000624class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000625 public:
626 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000627 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000628
629 // Adds an expectation to this sequence. The caller must ensure
630 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000631 void AddExpectation(const Expectation& expectation) const;
632
shiqiane35fdd92008-12-10 05:08:54 +0000633 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000634 // The last expectation in this sequence. We use a linked_ptr here
635 // because Sequence objects are copyable and we want the copies to
636 // be aliases. The linked_ptr allows the copies to co-own and share
637 // the same Expectation object.
638 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000639}; // class Sequence
640
641// An object of this type causes all EXPECT_CALL() statements
642// encountered in its scope to be put in an anonymous sequence. The
643// work is done in the constructor and destructor. You should only
644// create an InSequence object on the stack.
645//
646// The sole purpose for this class is to support easy definition of
647// sequential expectations, e.g.
648//
649// {
650// InSequence dummy; // The name of the object doesn't matter.
651//
652// // The following expectations must match in the order they appear.
653// EXPECT_CALL(a, Bar())...;
654// EXPECT_CALL(a, Baz())...;
655// ...
656// EXPECT_CALL(b, Xyz())...;
657// }
658//
659// You can create InSequence objects in multiple threads, as long as
660// they are used to affect different mock objects. The idea is that
661// each thread can create and set up its own mocks as if it's the only
662// thread. However, for clarity of your tests we recommend you to set
663// up mocks in the main thread unless you have a good reason not to do
664// so.
vladlosev587c1b32011-05-20 00:42:22 +0000665class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000666 public:
667 InSequence();
668 ~InSequence();
669 private:
670 bool sequence_created_;
671
672 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000673} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000674
675namespace internal {
676
677// Points to the implicit sequence introduced by a living InSequence
678// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000679GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000680
681// Base class for implementing expectations.
682//
683// There are two reasons for having a type-agnostic base class for
684// Expectation:
685//
686// 1. We need to store collections of expectations of different
687// types (e.g. all pre-requisites of a particular expectation, all
688// expectations in a sequence). Therefore these expectation objects
689// must share a common base class.
690//
691// 2. We can avoid binary code bloat by moving methods not depending
692// on the template argument of Expectation to the base class.
693//
694// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000695class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000696 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000697 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400698 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000699
700 virtual ~ExpectationBase();
701
702 // Where in the source file was the expectation spec defined?
703 const char* file() const { return file_; }
704 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000705 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000706 // Returns the cardinality specified in the expectation spec.
707 const Cardinality& cardinality() const { return cardinality_; }
708
709 // Describes the source file location of this expectation.
710 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000711 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000712 }
713
714 // Describes how many times a function call matching this
715 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000716 void DescribeCallCountTo(::std::ostream* os) const
717 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000718
719 // If this mock method has an extra matcher (i.e. .With(matcher)),
720 // describes it to the ostream.
721 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000722
shiqiane35fdd92008-12-10 05:08:54 +0000723 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000724 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000725 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000726
727 enum Clause {
728 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000729 kNone,
730 kWith,
731 kTimes,
732 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000733 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000734 kWillOnce,
735 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000736 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000737 };
738
zhanyong.waned6c9272011-02-23 19:39:27 +0000739 typedef std::vector<const void*> UntypedActions;
740
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000741 // Returns an Expectation object that references and co-owns this
742 // expectation.
743 virtual Expectation GetHandle() = 0;
744
shiqiane35fdd92008-12-10 05:08:54 +0000745 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400746 void AssertSpecProperty(bool property,
747 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000748 Assert(property, file_, line_, failure_message);
749 }
750
751 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400752 void ExpectSpecProperty(bool property,
753 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000754 Expect(property, file_, line_, failure_message);
755 }
756
757 // Explicitly specifies the cardinality of this expectation. Used
758 // by the subclasses to implement the .Times() clause.
759 void SpecifyCardinality(const Cardinality& cardinality);
760
761 // Returns true iff the user specified the cardinality explicitly
762 // using a .Times().
763 bool cardinality_specified() const { return cardinality_specified_; }
764
765 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000766 void set_cardinality(const Cardinality& a_cardinality) {
767 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000768 }
769
770 // The following group of methods should only be called after the
771 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
772 // the current thread.
773
774 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000775 void RetireAllPreRequisites()
776 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000777
778 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000779 bool is_retired() const
780 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000781 g_gmock_mutex.AssertHeld();
782 return retired_;
783 }
784
785 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000786 void Retire()
787 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000788 g_gmock_mutex.AssertHeld();
789 retired_ = true;
790 }
791
792 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000793 bool IsSatisfied() const
794 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000795 g_gmock_mutex.AssertHeld();
796 return cardinality().IsSatisfiedByCallCount(call_count_);
797 }
798
799 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000800 bool IsSaturated() const
801 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000802 g_gmock_mutex.AssertHeld();
803 return cardinality().IsSaturatedByCallCount(call_count_);
804 }
805
806 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000807 bool IsOverSaturated() const
808 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000809 g_gmock_mutex.AssertHeld();
810 return cardinality().IsOverSaturatedByCallCount(call_count_);
811 }
812
813 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000814 bool AllPrerequisitesAreSatisfied() const
815 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000816
817 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000818 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
819 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000820
821 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000822 int call_count() const
823 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000824 g_gmock_mutex.AssertHeld();
825 return call_count_;
826 }
827
828 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000829 void IncrementCallCount()
830 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000831 g_gmock_mutex.AssertHeld();
832 call_count_++;
833 }
834
zhanyong.waned6c9272011-02-23 19:39:27 +0000835 // Checks the action count (i.e. the number of WillOnce() and
836 // WillRepeatedly() clauses) against the cardinality if this hasn't
837 // been done before. Prints a warning if there are too many or too
838 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000839 void CheckActionCountIfNotDone() const
840 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000841
shiqiane35fdd92008-12-10 05:08:54 +0000842 friend class ::testing::Sequence;
843 friend class ::testing::internal::ExpectationTester;
844
845 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000846 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000847
zhanyong.waned6c9272011-02-23 19:39:27 +0000848 // Implements the .Times() clause.
849 void UntypedTimes(const Cardinality& a_cardinality);
850
shiqiane35fdd92008-12-10 05:08:54 +0000851 // This group of fields are part of the spec and won't change after
852 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000853 const char* file_; // The file that contains the expectation.
854 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400855 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000856 // True iff the cardinality is specified explicitly.
857 bool cardinality_specified_;
858 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000859 // The immediate pre-requisites (i.e. expectations that must be
860 // satisfied before this expectation can be matched) of this
861 // expectation. We use linked_ptr in the set because we want an
862 // Expectation object to be co-owned by its FunctionMocker and its
863 // successors. This allows multiple mock objects to be deleted at
864 // different times.
865 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000866
867 // This group of fields are the current state of the expectation,
868 // and can change as the mock function is called.
869 int call_count_; // How many times this expectation has been invoked.
870 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000871 UntypedActions untyped_actions_;
872 bool extra_matcher_specified_;
873 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
874 bool retires_on_saturation_;
875 Clause last_clause_;
876 mutable bool action_count_checked_; // Under mutex_.
877 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000878
879 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000880}; // class ExpectationBase
881
882// Impements an expectation for the given function type.
883template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000884class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000885 public:
886 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
887 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
888 typedef typename Function<F>::Result Result;
889
Nico Weber09fd5b32017-05-15 17:07:03 -0400890 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
891 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000892 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000893 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000894 owner_(owner),
895 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000896 // By default, extra_matcher_ should match anything. However,
897 // we cannot initialize it with _ as that triggers a compiler
898 // bug in Symbian's C++ compiler (cannot decide between two
899 // overloaded constructors of Matcher<const ArgumentTuple&>).
900 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000901 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000902
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000903 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000904 // Check the validity of the action count if it hasn't been done
905 // yet (for example, if the expectation was never used).
906 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000907 for (UntypedActions::const_iterator it = untyped_actions_.begin();
908 it != untyped_actions_.end(); ++it) {
909 delete static_cast<const Action<F>*>(*it);
910 }
shiqiane35fdd92008-12-10 05:08:54 +0000911 }
912
zhanyong.wanbf550852009-06-09 06:09:53 +0000913 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000914 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000915 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000916 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000917 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000918 "more than once in an EXPECT_CALL().");
919 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000920 ExpectSpecProperty(last_clause_ < kWith,
921 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000922 "clause in an EXPECT_CALL().");
923 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000924 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000925
926 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000927 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000928 return *this;
929 }
930
931 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000932 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000933 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000934 return *this;
935 }
936
937 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000938 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000939 return Times(Exactly(n));
940 }
941
942 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000943 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000944 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000945 ".InSequence() cannot appear after .After(),"
946 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000947 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000948 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000949
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000950 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000951 return *this;
952 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000953 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000954 return InSequence(s1).InSequence(s2);
955 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000956 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
957 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000958 return InSequence(s1, s2).InSequence(s3);
959 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000960 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
961 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000962 return InSequence(s1, s2, s3).InSequence(s4);
963 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000964 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
965 const Sequence& s3, const Sequence& s4,
966 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000967 return InSequence(s1, s2, s3, s4).InSequence(s5);
968 }
969
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000970 // Implements that .After() clause.
971 TypedExpectation& After(const ExpectationSet& s) {
972 ExpectSpecProperty(last_clause_ <= kAfter,
973 ".After() cannot appear after .WillOnce(),"
974 " .WillRepeatedly(), or "
975 ".RetiresOnSaturation().");
976 last_clause_ = kAfter;
977
978 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
979 immediate_prerequisites_ += *it;
980 }
981 return *this;
982 }
983 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
984 return After(s1).After(s2);
985 }
986 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
987 const ExpectationSet& s3) {
988 return After(s1, s2).After(s3);
989 }
990 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
991 const ExpectationSet& s3, const ExpectationSet& s4) {
992 return After(s1, s2, s3).After(s4);
993 }
994 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
995 const ExpectationSet& s3, const ExpectationSet& s4,
996 const ExpectationSet& s5) {
997 return After(s1, s2, s3, s4).After(s5);
998 }
999
shiqiane35fdd92008-12-10 05:08:54 +00001000 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001001 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001002 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +00001003 ".WillOnce() cannot appear after "
1004 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001005 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001006
zhanyong.waned6c9272011-02-23 19:39:27 +00001007 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001008 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001009 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001010 }
1011 return *this;
1012 }
1013
1014 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001015 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001016 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001017 ExpectSpecProperty(false,
1018 ".WillRepeatedly() cannot appear "
1019 "more than once in an EXPECT_CALL().");
1020 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001021 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001022 ".WillRepeatedly() cannot appear "
1023 "after .RetiresOnSaturation().");
1024 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001025 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001026 repeated_action_specified_ = true;
1027
1028 repeated_action_ = action;
1029 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001030 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001031 }
1032
1033 // Now that no more action clauses can be specified, we check
1034 // whether their count makes sense.
1035 CheckActionCountIfNotDone();
1036 return *this;
1037 }
1038
1039 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001040 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001041 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001042 ".RetiresOnSaturation() cannot appear "
1043 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001044 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001045 retires_on_saturation_ = true;
1046
1047 // Now that no more action clauses can be specified, we check
1048 // whether their count makes sense.
1049 CheckActionCountIfNotDone();
1050 return *this;
1051 }
1052
1053 // Returns the matchers for the arguments as specified inside the
1054 // EXPECT_CALL() macro.
1055 const ArgumentMatcherTuple& matchers() const {
1056 return matchers_;
1057 }
1058
zhanyong.wanbf550852009-06-09 06:09:53 +00001059 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001060 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1061 return extra_matcher_;
1062 }
1063
shiqiane35fdd92008-12-10 05:08:54 +00001064 // Returns the action specified by the .WillRepeatedly() clause.
1065 const Action<F>& repeated_action() const { return repeated_action_; }
1066
zhanyong.waned6c9272011-02-23 19:39:27 +00001067 // If this mock method has an extra matcher (i.e. .With(matcher)),
1068 // describes it to the ostream.
1069 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001070 if (extra_matcher_specified_) {
1071 *os << " Expected args: ";
1072 extra_matcher_.DescribeTo(os);
1073 *os << "\n";
1074 }
1075 }
1076
shiqiane35fdd92008-12-10 05:08:54 +00001077 private:
1078 template <typename Function>
1079 friend class FunctionMockerBase;
1080
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001081 // Returns an Expectation object that references and co-owns this
1082 // expectation.
1083 virtual Expectation GetHandle() {
1084 return owner_->GetHandleOf(this);
1085 }
1086
shiqiane35fdd92008-12-10 05:08:54 +00001087 // The following methods will be called only after the EXPECT_CALL()
1088 // statement finishes and when the current thread holds
1089 // g_gmock_mutex.
1090
1091 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001092 bool Matches(const ArgumentTuple& args) const
1093 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001094 g_gmock_mutex.AssertHeld();
1095 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1096 }
1097
1098 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001099 bool ShouldHandleArguments(const ArgumentTuple& args) const
1100 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001101 g_gmock_mutex.AssertHeld();
1102
1103 // In case the action count wasn't checked when the expectation
1104 // was defined (e.g. if this expectation has no WillRepeatedly()
1105 // or RetiresOnSaturation() clause), we check it when the
1106 // expectation is used for the first time.
1107 CheckActionCountIfNotDone();
1108 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1109 }
1110
1111 // Describes the result of matching the arguments against this
1112 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001113 void ExplainMatchResultTo(
1114 const ArgumentTuple& args,
1115 ::std::ostream* os) const
1116 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001117 g_gmock_mutex.AssertHeld();
1118
1119 if (is_retired()) {
1120 *os << " Expected: the expectation is active\n"
1121 << " Actual: it is retired\n";
1122 } else if (!Matches(args)) {
1123 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001124 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001125 }
zhanyong.wan82113312010-01-08 21:55:40 +00001126 StringMatchResultListener listener;
1127 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001128 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001129 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001130 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001131
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001132 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001133 *os << "\n";
1134 }
1135 } else if (!AllPrerequisitesAreSatisfied()) {
1136 *os << " Expected: all pre-requisites are satisfied\n"
1137 << " Actual: the following immediate pre-requisites "
1138 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001139 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001140 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1141 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001142 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001143 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001144 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001145 *os << "pre-requisite #" << i++ << "\n";
1146 }
1147 *os << " (end of pre-requisites)\n";
1148 } else {
1149 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001150 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001151 // is called only when the mock function call does NOT match the
1152 // expectation.
1153 *os << "The call matches the expectation.\n";
1154 }
1155 }
1156
1157 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001158 const Action<F>& GetCurrentAction(
1159 const FunctionMockerBase<F>* mocker,
1160 const ArgumentTuple& args) const
1161 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001162 g_gmock_mutex.AssertHeld();
1163 const int count = call_count();
1164 Assert(count >= 1, __FILE__, __LINE__,
1165 "call_count() is <= 0 when GetCurrentAction() is "
1166 "called - this should never happen.");
1167
zhanyong.waned6c9272011-02-23 19:39:27 +00001168 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001169 if (action_count > 0 && !repeated_action_specified_ &&
1170 count > action_count) {
1171 // If there is at least one WillOnce() and no WillRepeatedly(),
1172 // we warn the user when the WillOnce() clauses ran out.
1173 ::std::stringstream ss;
1174 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001175 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001176 << "Called " << count << " times, but only "
1177 << action_count << " WillOnce()"
1178 << (action_count == 1 ? " is" : "s are") << " specified - ";
1179 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001180 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001181 }
1182
zhanyong.waned6c9272011-02-23 19:39:27 +00001183 return count <= action_count ?
1184 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1185 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001186 }
1187
1188 // Given the arguments of a mock function call, if the call will
1189 // over-saturate this expectation, returns the default action;
1190 // otherwise, returns the next action in this expectation. Also
1191 // describes *what* happened to 'what', and explains *why* Google
1192 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001193 // IncrementCallCount(). A return value of NULL means the default
1194 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001195 const Action<F>* GetActionForArguments(
1196 const FunctionMockerBase<F>* mocker,
1197 const ArgumentTuple& args,
1198 ::std::ostream* what,
1199 ::std::ostream* why)
1200 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001201 g_gmock_mutex.AssertHeld();
1202 if (IsSaturated()) {
1203 // We have an excessive call.
1204 IncrementCallCount();
1205 *what << "Mock function called more times than expected - ";
1206 mocker->DescribeDefaultActionTo(args, what);
1207 DescribeCallCountTo(why);
1208
zhanyong.waned6c9272011-02-23 19:39:27 +00001209 // TODO(wan@google.com): allow the user to control whether
1210 // unexpected calls should fail immediately or continue using a
1211 // flag --gmock_unexpected_calls_are_fatal.
1212 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001213 }
1214
1215 IncrementCallCount();
1216 RetireAllPreRequisites();
1217
zhanyong.waned6c9272011-02-23 19:39:27 +00001218 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001219 Retire();
1220 }
1221
1222 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001223 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001224 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001225 }
1226
1227 // All the fields below won't change once the EXPECT_CALL()
1228 // statement finishes.
1229 FunctionMockerBase<F>* const owner_;
1230 ArgumentMatcherTuple matchers_;
1231 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001232 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001233
1234 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001235}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001236
1237// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1238// specifying the default behavior of, or expectation on, a mock
1239// function.
1240
1241// Note: class MockSpec really belongs to the ::testing namespace.
1242// However if we define it in ::testing, MSVC will complain when
1243// classes in ::testing::internal declare it as a friend class
1244// template. To workaround this compiler bug, we define MockSpec in
1245// ::testing::internal and import it into ::testing.
1246
zhanyong.waned6c9272011-02-23 19:39:27 +00001247// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001248GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1249 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001250 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001251
shiqiane35fdd92008-12-10 05:08:54 +00001252template <typename F>
1253class MockSpec {
1254 public:
1255 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1256 typedef typename internal::Function<F>::ArgumentMatcherTuple
1257 ArgumentMatcherTuple;
1258
1259 // Constructs a MockSpec object, given the function mocker object
1260 // that the spec is associated with.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001261 MockSpec(internal::FunctionMockerBase<F>* function_mocker,
1262 const ArgumentMatcherTuple& matchers)
1263 : function_mocker_(function_mocker), matchers_(matchers) {}
shiqiane35fdd92008-12-10 05:08:54 +00001264
1265 // Adds a new default action spec to the function mocker and returns
1266 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001267 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001268 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001269 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001270 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001271 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001272 }
1273
1274 // Adds a new expectation spec to the function mocker and returns
1275 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001276 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001277 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001278 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1279 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001280 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001281 return function_mocker_->AddNewExpectation(
1282 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001283 }
1284
David Sunderlandf437f8c2018-04-18 19:28:56 -04001285 // This operator overload is used to swallow the superfluous parameter list
1286 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1287 // explanation.
1288 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1289 return *this;
1290 }
1291
shiqiane35fdd92008-12-10 05:08:54 +00001292 private:
1293 template <typename Function>
1294 friend class internal::FunctionMocker;
1295
shiqiane35fdd92008-12-10 05:08:54 +00001296 // The function mocker that owns this spec.
1297 internal::FunctionMockerBase<F>* const function_mocker_;
1298 // The argument matchers specified in the spec.
1299 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001300
1301 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001302}; // class MockSpec
1303
kosakb5c81092014-01-29 06:41:44 +00001304// Wrapper type for generically holding an ordinary value or lvalue reference.
1305// If T is not a reference type, it must be copyable or movable.
1306// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1307// T is a move-only value type (which means that it will always be copyable
1308// if the current platform does not support move semantics).
1309//
1310// The primary template defines handling for values, but function header
1311// comments describe the contract for the whole template (including
1312// specializations).
1313template <typename T>
1314class ReferenceOrValueWrapper {
1315 public:
1316 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001317 explicit ReferenceOrValueWrapper(T value)
1318 : value_(::testing::internal::move(value)) {
1319 }
kosakb5c81092014-01-29 06:41:44 +00001320
1321 // Unwraps and returns the underlying value/reference, exactly as
1322 // originally passed. The behavior of calling this more than once on
1323 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001324 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001325
1326 // Provides nondestructive access to the underlying value/reference.
1327 // Always returns a const reference (more precisely,
1328 // const RemoveReference<T>&). The behavior of calling this after
1329 // calling Unwrap on the same object is unspecified.
1330 const T& Peek() const {
1331 return value_;
1332 }
1333
1334 private:
1335 T value_;
1336};
1337
1338// Specialization for lvalue reference types. See primary template
1339// for documentation.
1340template <typename T>
1341class ReferenceOrValueWrapper<T&> {
1342 public:
1343 // Workaround for debatable pass-by-reference lint warning (c-library-team
1344 // policy precludes NOLINT in this context)
1345 typedef T& reference;
1346 explicit ReferenceOrValueWrapper(reference ref)
1347 : value_ptr_(&ref) {}
1348 T& Unwrap() { return *value_ptr_; }
1349 const T& Peek() const { return *value_ptr_; }
1350
1351 private:
1352 T* value_ptr_;
1353};
1354
shiqiane35fdd92008-12-10 05:08:54 +00001355// MSVC warns about using 'this' in base member initializer list, so
1356// we need to temporarily disable the warning. We have to do it for
1357// the entire class to suppress the warning, even though it's about
1358// the constructor only.
1359
1360#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001361# pragma warning(push) // Saves the current warning state.
1362# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001363#endif // _MSV_VER
1364
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001365// C++ treats the void type specially. For example, you cannot define
1366// a void-typed variable or pass a void value to a function.
1367// ActionResultHolder<T> holds a value of type T, where T must be a
1368// copyable type or void (T doesn't need to be default-constructable).
1369// It hides the syntactic difference between void and other types, and
1370// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001371// non-void-returning mock functions.
1372
1373// Untyped base class for ActionResultHolder<T>.
1374class UntypedActionResultHolderBase {
1375 public:
1376 virtual ~UntypedActionResultHolderBase() {}
1377
1378 // Prints the held value as an action's result to os.
1379 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1380};
1381
1382// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001383template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001384class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001385 public:
kosakb5c81092014-01-29 06:41:44 +00001386 // Returns the held value. Must not be called more than once.
1387 T Unwrap() {
1388 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001389 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001390
1391 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001392 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001393 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001394 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001395 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001396 }
1397
1398 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001399 // result in a new-ed ActionResultHolder.
1400 template <typename F>
1401 static ActionResultHolder* PerformDefaultAction(
1402 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001403 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001404 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001405 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1406 internal::move(args), call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001407 }
1408
zhanyong.waned6c9272011-02-23 19:39:27 +00001409 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001410 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001411 template <typename F>
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001412 static ActionResultHolder* PerformAction(
1413 const Action<F>& action,
1414 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1415 return new ActionResultHolder(
1416 Wrapper(action.Perform(internal::move(args))));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001417 }
1418
1419 private:
kosakb5c81092014-01-29 06:41:44 +00001420 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001421
kosakd370f852014-11-17 01:14:16 +00001422 explicit ActionResultHolder(Wrapper result)
1423 : result_(::testing::internal::move(result)) {
1424 }
kosakb5c81092014-01-29 06:41:44 +00001425
1426 Wrapper result_;
1427
1428 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001429};
1430
1431// Specialization for T = void.
1432template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001433class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001434 public:
kosakb5c81092014-01-29 06:41:44 +00001435 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001436
zhanyong.waned6c9272011-02-23 19:39:27 +00001437 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1438
kosakb5c81092014-01-29 06:41:44 +00001439 // Performs the given mock function's default action and returns ownership
1440 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001441 template <typename F>
1442 static ActionResultHolder* PerformDefaultAction(
1443 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001444 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001445 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001446 func_mocker->PerformDefaultAction(internal::move(args), call_description);
kosakb5c81092014-01-29 06:41:44 +00001447 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001448 }
1449
kosakb5c81092014-01-29 06:41:44 +00001450 // Performs the given action and returns ownership of an empty
1451 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001452 template <typename F>
1453 static ActionResultHolder* PerformAction(
1454 const Action<F>& action,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001455 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1456 action.Perform(internal::move(args));
kosakb5c81092014-01-29 06:41:44 +00001457 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001458 }
kosakb5c81092014-01-29 06:41:44 +00001459
1460 private:
1461 ActionResultHolder() {}
1462 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001463};
1464
shiqiane35fdd92008-12-10 05:08:54 +00001465// The base of the function mocker class for the given function type.
1466// We put the methods in this class instead of its child to avoid code
1467// bloat.
1468template <typename F>
1469class FunctionMockerBase : public UntypedFunctionMockerBase {
1470 public:
1471 typedef typename Function<F>::Result Result;
1472 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1473 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1474
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001475 FunctionMockerBase() {}
shiqiane35fdd92008-12-10 05:08:54 +00001476
1477 // The destructor verifies that all expectations on this mock
1478 // function have been satisfied. If not, it will report Google Test
1479 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001480 virtual ~FunctionMockerBase()
1481 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001482 MutexLock l(&g_gmock_mutex);
1483 VerifyAndClearExpectationsLocked();
1484 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001485 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001486 }
1487
1488 // Returns the ON_CALL spec that matches this mock function with the
1489 // given arguments; returns NULL if no matching ON_CALL is found.
1490 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001491 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001492 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001493 for (UntypedOnCallSpecs::const_reverse_iterator it
1494 = untyped_on_call_specs_.rbegin();
1495 it != untyped_on_call_specs_.rend(); ++it) {
1496 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1497 if (spec->Matches(args))
1498 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001499 }
1500
1501 return NULL;
1502 }
1503
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001504 // Performs the default action of this mock function on the given
1505 // arguments and returns the result. Asserts (or throws if
1506 // exceptions are enabled) with a helpful call descrption if there
1507 // is no valid return value. This method doesn't depend on the
1508 // mutable state of this object, and thus can be called concurrently
1509 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001510 // L = *
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001511 Result PerformDefaultAction(
1512 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1513 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001514 const OnCallSpec<F>* const spec =
1515 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001516 if (spec != NULL) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001517 return spec->GetAction().Perform(internal::move(args));
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001518 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001519 const std::string message =
1520 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001521 "\n The mock function has no default action "
1522 "set, and its return type has no default value set.";
1523#if GTEST_HAS_EXCEPTIONS
1524 if (!DefaultValue<Result>::Exists()) {
1525 throw std::runtime_error(message);
1526 }
1527#else
1528 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1529#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001530 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001531 }
1532
zhanyong.waned6c9272011-02-23 19:39:27 +00001533 // Performs the default action with the given arguments and returns
1534 // the action's result. The call description string will be used in
1535 // the error message to describe the call in the case the default
1536 // action fails. The caller is responsible for deleting the result.
1537 // L = *
1538 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001539 void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001540 const std::string& call_description) const {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001541 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1542 return ResultHolder::PerformDefaultAction(this, internal::move(*args),
1543 call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001544 }
1545
zhanyong.waned6c9272011-02-23 19:39:27 +00001546 // Performs the given action with the given arguments and returns
1547 // the action's result. The caller is responsible for deleting the
1548 // result.
1549 // L = *
1550 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001551 const void* untyped_action, void* untyped_args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001552 // Make a copy of the action before performing it, in case the
1553 // action deletes the mock object (and thus deletes itself).
1554 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001555 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1556 return ResultHolder::PerformAction(action, internal::move(*args));
zhanyong.waned6c9272011-02-23 19:39:27 +00001557 }
shiqiane35fdd92008-12-10 05:08:54 +00001558
zhanyong.waned6c9272011-02-23 19:39:27 +00001559 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1560 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001561 virtual void ClearDefaultActionsLocked()
1562 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001563 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001564
1565 // Deleting our default actions may trigger other mock objects to be
1566 // deleted, for example if an action contains a reference counted smart
1567 // pointer to that mock object, and that is the last reference. So if we
1568 // delete our actions within the context of the global mutex we may deadlock
1569 // when this method is called again. Instead, make a copy of the set of
1570 // actions to delete, clear our set within the mutex, and then delete the
1571 // actions outside of the mutex.
1572 UntypedOnCallSpecs specs_to_delete;
1573 untyped_on_call_specs_.swap(specs_to_delete);
1574
1575 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001576 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001577 specs_to_delete.begin();
1578 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001579 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001580 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001581
1582 // Lock the mutex again, since the caller expects it to be locked when we
1583 // return.
1584 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001585 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001586
shiqiane35fdd92008-12-10 05:08:54 +00001587 protected:
1588 template <typename Function>
1589 friend class MockSpec;
1590
zhanyong.waned6c9272011-02-23 19:39:27 +00001591 typedef ActionResultHolder<Result> ResultHolder;
1592
shiqiane35fdd92008-12-10 05:08:54 +00001593 // Returns the result of invoking this mock function with the given
1594 // arguments. This function can be safely called from multiple
1595 // threads concurrently.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001596 Result InvokeWith(
1597 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args)
1598 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1599 // const_cast is required since in C++98 we still pass ArgumentTuple around
1600 // by const& instead of rvalue reference.
1601 void* untyped_args = const_cast<void*>(static_cast<const void*>(&args));
kosakb5c81092014-01-29 06:41:44 +00001602 scoped_ptr<ResultHolder> holder(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001603 DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args)));
kosakb5c81092014-01-29 06:41:44 +00001604 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001605 }
shiqiane35fdd92008-12-10 05:08:54 +00001606
1607 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001608 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001609 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001610 const ArgumentMatcherTuple& m)
1611 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001612 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001613 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1614 untyped_on_call_specs_.push_back(on_call_spec);
1615 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001616 }
1617
1618 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001619 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1620 const std::string& source_text,
1621 const ArgumentMatcherTuple& m)
1622 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001623 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001624 TypedExpectation<F>* const expectation =
1625 new TypedExpectation<F>(this, file, line, source_text, m);
1626 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001627 // See the definition of untyped_expectations_ for why access to
1628 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001629 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001630
1631 // Adds this expectation into the implicit sequence if there is one.
1632 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1633 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001634 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001635 }
1636
1637 return *expectation;
1638 }
1639
shiqiane35fdd92008-12-10 05:08:54 +00001640 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001641 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001642
zhanyong.waned6c9272011-02-23 19:39:27 +00001643 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001644
1645 // Describes what default action will be performed for the given
1646 // arguments.
1647 // L = *
1648 void DescribeDefaultActionTo(const ArgumentTuple& args,
1649 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001650 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001651
1652 if (spec == NULL) {
1653 *os << (internal::type_equals<Result, void>::value ?
1654 "returning directly.\n" :
1655 "returning default value.\n");
1656 } else {
1657 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001658 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001659 }
1660 }
1661
1662 // Writes a message that the call is uninteresting (i.e. neither
1663 // explicitly expected nor explicitly unexpected) to the given
1664 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001665 virtual void UntypedDescribeUninterestingCall(
1666 const void* untyped_args,
1667 ::std::ostream* os) const
1668 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001669 const ArgumentTuple& args =
1670 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001671 *os << "Uninteresting mock function call - ";
1672 DescribeDefaultActionTo(args, os);
1673 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001674 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001675 }
1676
zhanyong.waned6c9272011-02-23 19:39:27 +00001677 // Returns the expectation that matches the given function arguments
1678 // (or NULL is there's no match); when a match is found,
1679 // untyped_action is set to point to the action that should be
1680 // performed (or NULL if the action is "do default"), and
1681 // is_excessive is modified to indicate whether the call exceeds the
1682 // expected number.
1683 //
shiqiane35fdd92008-12-10 05:08:54 +00001684 // Critical section: We must find the matching expectation and the
1685 // corresponding action that needs to be taken in an ATOMIC
1686 // transaction. Otherwise another thread may call this mock
1687 // method in the middle and mess up the state.
1688 //
1689 // However, performing the action has to be left out of the critical
1690 // section. The reason is that we have no control on what the
1691 // action does (it can invoke an arbitrary user function or even a
1692 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001693 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1694 const void* untyped_args,
1695 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001696 ::std::ostream* what, ::std::ostream* why)
1697 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001698 const ArgumentTuple& args =
1699 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001700 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001701 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1702 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001703 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001704 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001705 }
1706
1707 // This line must be done before calling GetActionForArguments(),
1708 // which will increment the call count for *exp and thus affect
1709 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001710 *is_excessive = exp->IsSaturated();
1711 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1712 if (action != NULL && action->IsDoDefault())
1713 action = NULL; // Normalize "do default" to NULL.
1714 *untyped_action = action;
1715 return exp;
1716 }
1717
1718 // Prints the given function arguments to the ostream.
1719 virtual void UntypedPrintArgs(const void* untyped_args,
1720 ::std::ostream* os) const {
1721 const ArgumentTuple& args =
1722 *static_cast<const ArgumentTuple*>(untyped_args);
1723 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001724 }
1725
1726 // Returns the expectation that matches the arguments, or NULL if no
1727 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001728 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001729 const ArgumentTuple& args) const
1730 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001731 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001732 // See the definition of untyped_expectations_ for why access to
1733 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001734 for (typename UntypedExpectations::const_reverse_iterator it =
1735 untyped_expectations_.rbegin();
1736 it != untyped_expectations_.rend(); ++it) {
1737 TypedExpectation<F>* const exp =
1738 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001739 if (exp->ShouldHandleArguments(args)) {
1740 return exp;
1741 }
1742 }
1743 return NULL;
1744 }
1745
1746 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001747 void FormatUnexpectedCallMessageLocked(
1748 const ArgumentTuple& args,
1749 ::std::ostream* os,
1750 ::std::ostream* why) const
1751 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001752 g_gmock_mutex.AssertHeld();
1753 *os << "\nUnexpected mock function call - ";
1754 DescribeDefaultActionTo(args, os);
1755 PrintTriedExpectationsLocked(args, why);
1756 }
1757
1758 // Prints a list of expectations that have been tried against the
1759 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001760 void PrintTriedExpectationsLocked(
1761 const ArgumentTuple& args,
1762 ::std::ostream* why) const
1763 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001764 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001765 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001766 *why << "Google Mock tried the following " << count << " "
1767 << (count == 1 ? "expectation, but it didn't match" :
1768 "expectations, but none matched")
1769 << ":\n";
1770 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001771 TypedExpectation<F>* const expectation =
1772 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001773 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001774 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001775 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001776 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001777 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001778 *why << expectation->source_text() << "...\n";
1779 expectation->ExplainMatchResultTo(args, why);
1780 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001781 }
1782 }
1783
zhanyong.wan16cf4732009-05-14 20:55:30 +00001784 // There is no generally useful and implementable semantics of
1785 // copying a mock object, so copying a mock is usually a user error.
1786 // Thus we disallow copying function mockers. If the user really
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +01001787 // wants to copy a mock object, they should implement their own copy
zhanyong.wan16cf4732009-05-14 20:55:30 +00001788 // operation, for example:
1789 //
1790 // class MockFoo : public Foo {
1791 // public:
1792 // // Defines a copy constructor explicitly.
1793 // MockFoo(const MockFoo& src) {}
1794 // ...
1795 // };
1796 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001797}; // class FunctionMockerBase
1798
1799#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001800# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001801#endif // _MSV_VER
1802
1803// Implements methods of FunctionMockerBase.
1804
1805// Verifies that all expectations on this mock function have been
1806// satisfied. Reports one or more Google Test non-fatal failures and
1807// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001808
1809// Reports an uninteresting call (whose description is in msg) in the
1810// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001811void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001812
shiqiane35fdd92008-12-10 05:08:54 +00001813} // namespace internal
1814
1815// The style guide prohibits "using" statements in a namespace scope
1816// inside a header file. However, the MockSpec class template is
1817// meant to be defined in the ::testing namespace. The following line
1818// is just a trick for working around a bug in MSVC 8.0, which cannot
1819// handle it if we define MockSpec in ::testing.
1820using internal::MockSpec;
1821
1822// Const(x) is a convenient function for obtaining a const reference
1823// to x. This is useful for setting expectations on an overloaded
1824// const mock method, e.g.
1825//
1826// class MockFoo : public FooInterface {
1827// public:
1828// MOCK_METHOD0(Bar, int());
1829// MOCK_CONST_METHOD0(Bar, int&());
1830// };
1831//
1832// MockFoo foo;
1833// // Expects a call to non-const MockFoo::Bar().
1834// EXPECT_CALL(foo, Bar());
1835// // Expects a call to const MockFoo::Bar().
1836// EXPECT_CALL(Const(foo), Bar());
1837template <typename T>
1838inline const T& Const(const T& x) { return x; }
1839
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001840// Constructs an Expectation object that references and co-owns exp.
1841inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1842 : expectation_base_(exp.GetHandle().expectation_base()) {}
1843
shiqiane35fdd92008-12-10 05:08:54 +00001844} // namespace testing
1845
David Sunderlandf437f8c2018-04-18 19:28:56 -04001846// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1847// required to avoid compile errors when the name of the method used in call is
1848// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1849// tests in internal/gmock-spec-builders_test.cc for more details.
1850//
1851// This macro supports statements both with and without parameter matchers. If
1852// the parameter list is omitted, gMock will accept any parameters, which allows
1853// tests to be written that don't need to encode the number of method
1854// parameter. This technique may only be used for non-overloaded methods.
1855//
1856// // These are the same:
1857// ON_CALL(mock, NoArgsMethod()).WillByDefault(…);
1858// ON_CALL(mock, NoArgsMethod).WillByDefault(…);
1859//
1860// // As are these:
1861// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(…);
1862// ON_CALL(mock, TwoArgsMethod).WillByDefault(…);
1863//
1864// // Can also specify args if you want, of course:
1865// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(…);
1866//
1867// // Overloads work as long as you specify parameters:
1868// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(…);
1869// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(…);
1870//
1871// // Oops! Which overload did you want?
1872// ON_CALL(mock, OverloadedMethod).WillByDefault(…);
1873// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1874//
1875// How this works: The mock class uses two overloads of the gmock_Method
1876// expectation setter method plus an operator() overload on the MockSpec object.
1877// In the matcher list form, the macro expands to:
1878//
1879// // This statement:
1880// ON_CALL(mock, TwoArgsMethod(_, 45))…
1881//
1882// // …expands to:
1883// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)…
1884// |-------------v---------------||------------v-------------|
1885// invokes first overload swallowed by operator()
1886//
1887// // …which is essentially:
1888// mock.gmock_TwoArgsMethod(_, 45)…
1889//
1890// Whereas the form without a matcher list:
1891//
1892// // This statement:
1893// ON_CALL(mock, TwoArgsMethod)…
1894//
1895// // …expands to:
1896// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)…
1897// |-----------------------v--------------------------|
1898// invokes second overload
1899//
1900// // …which is essentially:
1901// mock.gmock_TwoArgsMethod(_, _)…
1902//
1903// The WithoutMatchers() argument is used to disambiguate overloads and to
1904// block the caller from accidentally invoking the second overload directly. The
1905// second argument is an internal type derived from the method signature. The
1906// failure to disambiguate two overloads of this method in the ON_CALL statement
1907// is how we block callers from setting expectations on overloaded methods.
1908#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1909 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \
1910 .Setter(__FILE__, __LINE__, #mock_expr, #call)
shiqiane35fdd92008-12-10 05:08:54 +00001911
David Sunderlandf437f8c2018-04-18 19:28:56 -04001912#define ON_CALL(obj, call) \
1913 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1914
1915#define EXPECT_CALL(obj, call) \
1916 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
shiqiane35fdd92008-12-10 05:08:54 +00001917
1918#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_