blob: 9670b59c7ad1b136fb5d7488257b5962549b8129 [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
Gennadiy Civil984cba32018-07-27 11:15:08 -040060// GOOGLETEST_CM0002 DO NOT DELETE
61
shiqiane35fdd92008-12-10 05:08:54 +000062#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
63#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
64
65#include <map>
66#include <set>
67#include <sstream>
68#include <string>
69#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000070#include "gmock/gmock-actions.h"
71#include "gmock/gmock-cardinalities.h"
72#include "gmock/gmock-matchers.h"
73#include "gmock/internal/gmock-internal-utils.h"
74#include "gmock/internal/gmock-port.h"
75#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000076
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050077#if GTEST_HAS_EXCEPTIONS
78# include <stdexcept> // NOLINT
79#endif
80
shiqiane35fdd92008-12-10 05:08:54 +000081namespace testing {
82
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000083// An abstract handle of an expectation.
84class Expectation;
85
86// A set of expectation handles.
87class ExpectationSet;
88
shiqiane35fdd92008-12-10 05:08:54 +000089// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
90// and MUST NOT BE USED IN USER CODE!!!
91namespace internal {
92
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000093// Implements a mock function.
94template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000095
96// Base class for expectations.
97class ExpectationBase;
98
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000099// Implements an expectation.
100template <typename F> class TypedExpectation;
101
shiqiane35fdd92008-12-10 05:08:54 +0000102// Helper class for testing the Expectation class template.
103class ExpectationTester;
104
105// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000106template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000107
shiqiane35fdd92008-12-10 05:08:54 +0000108// Protects the mock object registry (in class Mock), all function
109// mockers, and all expectations.
110//
111// The reason we don't use more fine-grained protection is: when a
112// mock function Foo() is called, it needs to consult its expectations
113// to see which one should be picked. If another thread is allowed to
114// call a mock function (either Foo() or a different one) at the same
115// time, it could affect the "retired" attributes of Foo()'s
116// expectations when InSequence() is used, and thus affect which
117// expectation gets picked. Therefore, we sequence all mock function
118// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000119GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000120
zhanyong.waned6c9272011-02-23 19:39:27 +0000121// Untyped base class for ActionResultHolder<R>.
122class UntypedActionResultHolderBase;
123
shiqiane35fdd92008-12-10 05:08:54 +0000124// Abstract base class of FunctionMockerBase. This is the
125// type-agnostic part of the function mocker interface. Its pure
126// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000127class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000128 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000129 UntypedFunctionMockerBase();
130 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000131
132 // Verifies that all expectations on this mock function have been
133 // satisfied. Reports one or more Google Test non-fatal failures
134 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000135 bool VerifyAndClearExpectationsLocked()
136 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000137
138 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000139 virtual void ClearDefaultActionsLocked()
140 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000141
142 // In all of the following Untyped* functions, it's the caller's
143 // responsibility to guarantee the correctness of the arguments'
144 // types.
145
146 // Performs the default action with the given arguments and returns
147 // the action's result. The call description string will be used in
148 // the error message to describe the call in the case the default
149 // action fails.
150 // L = *
151 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400152 void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000153
154 // Performs the given action with the given arguments and returns
155 // the action's result.
156 // L = *
157 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400158 const void* untyped_action, void* untyped_args) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000159
160 // Writes a message that the call is uninteresting (i.e. neither
161 // explicitly expected nor explicitly unexpected) to the given
162 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +0000163 virtual void UntypedDescribeUninterestingCall(
164 const void* untyped_args,
165 ::std::ostream* os) const
166 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000167
168 // Returns the expectation that matches the given function arguments
169 // (or NULL is there's no match); when a match is found,
170 // untyped_action is set to point to the action that should be
171 // performed (or NULL if the action is "do default"), and
172 // is_excessive is modified to indicate whether the call exceeds the
173 // expected number.
zhanyong.waned6c9272011-02-23 19:39:27 +0000174 virtual const ExpectationBase* UntypedFindMatchingExpectation(
175 const void* untyped_args,
176 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000177 ::std::ostream* what, ::std::ostream* why)
178 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000179
180 // Prints the given function arguments to the ostream.
181 virtual void UntypedPrintArgs(const void* untyped_args,
182 ::std::ostream* os) const = 0;
183
184 // Sets the mock object this mock method belongs to, and registers
185 // this information in the global mock registry. Will be called
186 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
187 // method.
188 // TODO(wan@google.com): rename to SetAndRegisterOwner().
vladlosev4d60a592011-10-24 21:16:22 +0000189 void RegisterOwner(const void* mock_obj)
190 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000191
192 // Sets the mock object this mock method belongs to, and sets the
193 // name of the mock function. Will be called upon each invocation
194 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000195 void SetOwnerAndName(const void* mock_obj, const char* name)
196 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000197
198 // Returns the mock object this mock method belongs to. Must be
199 // called after RegisterOwner() or SetOwnerAndName() has been
200 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000201 const void* MockObject() const
202 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000203
204 // Returns the name of this mock method. Must be called after
205 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000206 const char* Name() const
207 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000208
209 // Returns the result of invoking this mock function with the given
210 // arguments. This function can be safely called from multiple
211 // threads concurrently. The caller is responsible for deleting the
212 // result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400213 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
214 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000215
216 protected:
217 typedef std::vector<const void*> UntypedOnCallSpecs;
218
219 typedef std::vector<internal::linked_ptr<ExpectationBase> >
220 UntypedExpectations;
221
222 // Returns an Expectation object that references and co-owns exp,
223 // which must be an expectation on this mock function.
224 Expectation GetHandleOf(ExpectationBase* exp);
225
226 // Address of the mock object this mock method belongs to. Only
227 // valid after this mock method has been called or
228 // ON_CALL/EXPECT_CALL has been invoked on it.
229 const void* mock_obj_; // Protected by g_gmock_mutex.
230
231 // Name of the function being mocked. Only valid after this mock
232 // method has been called.
233 const char* name_; // Protected by g_gmock_mutex.
234
235 // All default action specs for this function mocker.
236 UntypedOnCallSpecs untyped_on_call_specs_;
237
238 // All expectations for this function mocker.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400239 //
240 // It's undefined behavior to interleave expectations (EXPECT_CALLs
241 // or ON_CALLs) and mock function calls. Also, the order of
242 // expectations is important. Therefore it's a logic race condition
243 // to read/write untyped_expectations_ concurrently. In order for
244 // tools like tsan to catch concurrent read/write accesses to
245 // untyped_expectations, we deliberately leave accesses to it
246 // unprotected.
zhanyong.waned6c9272011-02-23 19:39:27 +0000247 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000248}; // class UntypedFunctionMockerBase
249
zhanyong.waned6c9272011-02-23 19:39:27 +0000250// Untyped base class for OnCallSpec<F>.
251class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000252 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000253 // The arguments are the location of the ON_CALL() statement.
254 UntypedOnCallSpecBase(const char* a_file, int a_line)
255 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000256
257 // Where in the source file was the default action spec defined?
258 const char* file() const { return file_; }
259 int line() const { return line_; }
260
zhanyong.waned6c9272011-02-23 19:39:27 +0000261 protected:
262 // Gives each clause in the ON_CALL() statement a name.
263 enum Clause {
264 // Do not change the order of the enum members! The run-time
265 // syntax checking relies on it.
266 kNone,
267 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000268 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000269 };
270
271 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400272 void AssertSpecProperty(bool property,
273 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000274 Assert(property, file_, line_, failure_message);
275 }
276
277 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400278 void ExpectSpecProperty(bool property,
279 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000280 Expect(property, file_, line_, failure_message);
281 }
282
283 const char* file_;
284 int line_;
285
286 // The last clause in the ON_CALL() statement as seen so far.
287 // Initially kNone and changes as the statement is parsed.
288 Clause last_clause_;
289}; // class UntypedOnCallSpecBase
290
291// This template class implements an ON_CALL spec.
292template <typename F>
293class OnCallSpec : public UntypedOnCallSpecBase {
294 public:
295 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
296 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
297
298 // Constructs an OnCallSpec object from the information inside
299 // the parenthesis of an ON_CALL() statement.
300 OnCallSpec(const char* a_file, int a_line,
301 const ArgumentMatcherTuple& matchers)
302 : UntypedOnCallSpecBase(a_file, a_line),
303 matchers_(matchers),
304 // By default, extra_matcher_ should match anything. However,
305 // we cannot initialize it with _ as that triggers a compiler
306 // bug in Symbian's C++ compiler (cannot decide between two
307 // overloaded constructors of Matcher<const ArgumentTuple&>).
308 extra_matcher_(A<const ArgumentTuple&>()) {
309 }
310
zhanyong.wanbf550852009-06-09 06:09:53 +0000311 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000312 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000313 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000314 ExpectSpecProperty(last_clause_ < kWith,
315 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000316 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000317 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000318
319 extra_matcher_ = m;
320 return *this;
321 }
322
323 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000324 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000325 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000326 ".WillByDefault() must appear "
327 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000328 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000329
330 ExpectSpecProperty(!action.IsDoDefault(),
331 "DoDefault() cannot be used in ON_CALL().");
332 action_ = action;
333 return *this;
334 }
335
336 // Returns true iff the given arguments match the matchers.
337 bool Matches(const ArgumentTuple& args) const {
338 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
339 }
340
341 // Returns the action specified by the user.
342 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000343 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000344 ".WillByDefault() must appear exactly "
345 "once in an ON_CALL().");
346 return action_;
347 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000348
shiqiane35fdd92008-12-10 05:08:54 +0000349 private:
shiqiane35fdd92008-12-10 05:08:54 +0000350 // The information in statement
351 //
352 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000353 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000354 // .WillByDefault(action);
355 //
356 // is recorded in the data members like this:
357 //
358 // source file that contains the statement => file_
359 // line number of the statement => line_
360 // matchers => matchers_
361 // multi-argument-matcher => extra_matcher_
362 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000363 ArgumentMatcherTuple matchers_;
364 Matcher<const ArgumentTuple&> extra_matcher_;
365 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000366}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000367
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000368// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000369enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000370 kAllow,
371 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000372 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000373};
374
375} // namespace internal
376
377// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000378class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000379 public:
380 // The following public methods can be called concurrently.
381
zhanyong.wandf35a762009-04-22 22:25:31 +0000382 // Tells Google Mock to ignore mock_obj when checking for leaked
383 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000384 static void AllowLeak(const void* mock_obj)
385 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000386
shiqiane35fdd92008-12-10 05:08:54 +0000387 // Verifies and clears all expectations on the given mock object.
388 // If the expectations aren't satisfied, generates one or more
389 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000390 static bool VerifyAndClearExpectations(void* mock_obj)
391 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000392
393 // Verifies all expectations on the given mock object and clears its
394 // default actions and expectations. Returns true iff the
395 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000396 static bool VerifyAndClear(void* mock_obj)
397 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000398
shiqiane35fdd92008-12-10 05:08:54 +0000399 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000400 friend class internal::UntypedFunctionMockerBase;
401
shiqiane35fdd92008-12-10 05:08:54 +0000402 // Needed for a function mocker to register itself (so that we know
403 // how to clear a mock object).
404 template <typename F>
405 friend class internal::FunctionMockerBase;
406
shiqiane35fdd92008-12-10 05:08:54 +0000407 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700408 friend class NiceMock;
shiqiane35fdd92008-12-10 05:08:54 +0000409
410 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700411 friend class NaggyMock;
zhanyong.wan844fa942013-03-01 01:54:22 +0000412
413 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700414 friend class StrictMock;
shiqiane35fdd92008-12-10 05:08:54 +0000415
416 // Tells Google Mock to allow uninteresting calls on the given mock
417 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000418 static void AllowUninterestingCalls(const void* mock_obj)
419 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000420
421 // Tells Google Mock to warn the user about uninteresting calls on
422 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000423 static void WarnUninterestingCalls(const void* mock_obj)
424 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000425
426 // Tells Google Mock to fail uninteresting calls on the given mock
427 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000428 static void FailUninterestingCalls(const void* mock_obj)
429 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000430
431 // Tells Google Mock the given mock object is being destroyed and
432 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000433 static void UnregisterCallReaction(const void* mock_obj)
434 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000435
436 // Returns the reaction Google Mock will have on uninteresting calls
437 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000438 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000439 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000440 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000441
442 // Verifies that all expectations on the given mock object have been
443 // satisfied. Reports one or more Google Test non-fatal failures
444 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000445 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
446 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000447
448 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000449 static void ClearDefaultActionsLocked(void* mock_obj)
450 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000451
452 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000453 static void Register(
454 const void* mock_obj,
455 internal::UntypedFunctionMockerBase* mocker)
456 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000457
zhanyong.wandf35a762009-04-22 22:25:31 +0000458 // Tells Google Mock where in the source code mock_obj is used in an
459 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
460 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000461 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000462 const void* mock_obj, const char* file, int line)
463 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000464
shiqiane35fdd92008-12-10 05:08:54 +0000465 // Unregisters a mock method; removes the owning mock object from
466 // the registry when the last mock method associated with it has
467 // been unregistered. This is called only in the destructor of
468 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000469 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
470 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000471}; // class Mock
472
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000473// An abstract handle of an expectation. Useful in the .After()
474// clause of EXPECT_CALL() for setting the (partial) order of
475// expectations. The syntax:
476//
477// Expectation e1 = EXPECT_CALL(...)...;
478// EXPECT_CALL(...).After(e1)...;
479//
480// sets two expectations where the latter can only be matched after
481// the former has been satisfied.
482//
483// Notes:
484// - This class is copyable and has value semantics.
485// - Constness is shallow: a const Expectation object itself cannot
486// be modified, but the mutable methods of the ExpectationBase
487// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000488// - The constructors and destructor are defined out-of-line because
489// the Symbian WINSCW compiler wants to otherwise instantiate them
490// when it sees this class definition, at which point it doesn't have
491// ExpectationBase available yet, leading to incorrect destruction
492// in the linked_ptr (or compilation errors if using a checking
493// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000494class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000495 public:
496 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000497 Expectation();
498
499 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000500
501 // This single-argument ctor must not be explicit, in order to support the
502 // Expectation e = EXPECT_CALL(...);
503 // syntax.
504 //
505 // A TypedExpectation object stores its pre-requisites as
506 // Expectation objects, and needs to call the non-const Retire()
507 // method on the ExpectationBase objects they reference. Therefore
508 // Expectation must receive a *non-const* reference to the
509 // ExpectationBase object.
510 Expectation(internal::ExpectationBase& exp); // NOLINT
511
512 // The compiler-generated copy ctor and operator= work exactly as
513 // intended, so we don't need to define our own.
514
515 // Returns true iff rhs references the same expectation as this object does.
516 bool operator==(const Expectation& rhs) const {
517 return expectation_base_ == rhs.expectation_base_;
518 }
519
520 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
521
522 private:
523 friend class ExpectationSet;
524 friend class Sequence;
525 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000526 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000527
528 template <typename F>
529 friend class ::testing::internal::FunctionMockerBase;
530
531 template <typename F>
532 friend class ::testing::internal::TypedExpectation;
533
534 // This comparator is needed for putting Expectation objects into a set.
535 class Less {
536 public:
537 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
538 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
539 }
540 };
541
542 typedef ::std::set<Expectation, Less> Set;
543
544 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000545 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000546
547 // Returns the expectation this object references.
548 const internal::linked_ptr<internal::ExpectationBase>&
549 expectation_base() const {
550 return expectation_base_;
551 }
552
553 // A linked_ptr that co-owns the expectation this handle references.
554 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
555};
556
557// A set of expectation handles. Useful in the .After() clause of
558// EXPECT_CALL() for setting the (partial) order of expectations. The
559// syntax:
560//
561// ExpectationSet es;
562// es += EXPECT_CALL(...)...;
563// es += EXPECT_CALL(...)...;
564// EXPECT_CALL(...).After(es)...;
565//
566// sets three expectations where the last one can only be matched
567// after the first two have both been satisfied.
568//
569// This class is copyable and has value semantics.
570class ExpectationSet {
571 public:
572 // A bidirectional iterator that can read a const element in the set.
573 typedef Expectation::Set::const_iterator const_iterator;
574
575 // An object stored in the set. This is an alias of Expectation.
576 typedef Expectation::Set::value_type value_type;
577
578 // Constructs an empty set.
579 ExpectationSet() {}
580
581 // This single-argument ctor must not be explicit, in order to support the
582 // ExpectationSet es = EXPECT_CALL(...);
583 // syntax.
584 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
585 *this += Expectation(exp);
586 }
587
588 // This single-argument ctor implements implicit conversion from
589 // Expectation and thus must not be explicit. This allows either an
590 // Expectation or an ExpectationSet to be used in .After().
591 ExpectationSet(const Expectation& e) { // NOLINT
592 *this += e;
593 }
594
595 // The compiler-generator ctor and operator= works exactly as
596 // intended, so we don't need to define our own.
597
598 // Returns true iff rhs contains the same set of Expectation objects
599 // as this does.
600 bool operator==(const ExpectationSet& rhs) const {
601 return expectations_ == rhs.expectations_;
602 }
603
604 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
605
606 // Implements the syntax
607 // expectation_set += EXPECT_CALL(...);
608 ExpectationSet& operator+=(const Expectation& e) {
609 expectations_.insert(e);
610 return *this;
611 }
612
613 int size() const { return static_cast<int>(expectations_.size()); }
614
615 const_iterator begin() const { return expectations_.begin(); }
616 const_iterator end() const { return expectations_.end(); }
617
618 private:
619 Expectation::Set expectations_;
620};
621
622
shiqiane35fdd92008-12-10 05:08:54 +0000623// Sequence objects are used by a user to specify the relative order
624// in which the expectations should match. They are copyable (we rely
625// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000626class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000627 public:
628 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000629 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000630
631 // Adds an expectation to this sequence. The caller must ensure
632 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000633 void AddExpectation(const Expectation& expectation) const;
634
shiqiane35fdd92008-12-10 05:08:54 +0000635 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000636 // The last expectation in this sequence. We use a linked_ptr here
637 // because Sequence objects are copyable and we want the copies to
638 // be aliases. The linked_ptr allows the copies to co-own and share
639 // the same Expectation object.
640 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000641}; // class Sequence
642
643// An object of this type causes all EXPECT_CALL() statements
644// encountered in its scope to be put in an anonymous sequence. The
645// work is done in the constructor and destructor. You should only
646// create an InSequence object on the stack.
647//
648// The sole purpose for this class is to support easy definition of
649// sequential expectations, e.g.
650//
651// {
652// InSequence dummy; // The name of the object doesn't matter.
653//
654// // The following expectations must match in the order they appear.
655// EXPECT_CALL(a, Bar())...;
656// EXPECT_CALL(a, Baz())...;
657// ...
658// EXPECT_CALL(b, Xyz())...;
659// }
660//
661// You can create InSequence objects in multiple threads, as long as
662// they are used to affect different mock objects. The idea is that
663// each thread can create and set up its own mocks as if it's the only
664// thread. However, for clarity of your tests we recommend you to set
665// up mocks in the main thread unless you have a good reason not to do
666// so.
vladlosev587c1b32011-05-20 00:42:22 +0000667class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000668 public:
669 InSequence();
670 ~InSequence();
671 private:
672 bool sequence_created_;
673
674 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000675} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000676
677namespace internal {
678
679// Points to the implicit sequence introduced by a living InSequence
680// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000681GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000682
683// Base class for implementing expectations.
684//
685// There are two reasons for having a type-agnostic base class for
686// Expectation:
687//
688// 1. We need to store collections of expectations of different
689// types (e.g. all pre-requisites of a particular expectation, all
690// expectations in a sequence). Therefore these expectation objects
691// must share a common base class.
692//
693// 2. We can avoid binary code bloat by moving methods not depending
694// on the template argument of Expectation to the base class.
695//
696// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000697class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000698 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000699 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400700 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000701
702 virtual ~ExpectationBase();
703
704 // Where in the source file was the expectation spec defined?
705 const char* file() const { return file_; }
706 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000707 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000708 // Returns the cardinality specified in the expectation spec.
709 const Cardinality& cardinality() const { return cardinality_; }
710
711 // Describes the source file location of this expectation.
712 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000713 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000714 }
715
716 // Describes how many times a function call matching this
717 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000718 void DescribeCallCountTo(::std::ostream* os) const
719 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000720
721 // If this mock method has an extra matcher (i.e. .With(matcher)),
722 // describes it to the ostream.
723 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000724
shiqiane35fdd92008-12-10 05:08:54 +0000725 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000726 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000727 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000728
729 enum Clause {
730 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000731 kNone,
732 kWith,
733 kTimes,
734 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000735 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000736 kWillOnce,
737 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000738 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000739 };
740
zhanyong.waned6c9272011-02-23 19:39:27 +0000741 typedef std::vector<const void*> UntypedActions;
742
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000743 // Returns an Expectation object that references and co-owns this
744 // expectation.
745 virtual Expectation GetHandle() = 0;
746
shiqiane35fdd92008-12-10 05:08:54 +0000747 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400748 void AssertSpecProperty(bool property,
749 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000750 Assert(property, file_, line_, failure_message);
751 }
752
753 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400754 void ExpectSpecProperty(bool property,
755 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000756 Expect(property, file_, line_, failure_message);
757 }
758
759 // Explicitly specifies the cardinality of this expectation. Used
760 // by the subclasses to implement the .Times() clause.
761 void SpecifyCardinality(const Cardinality& cardinality);
762
763 // Returns true iff the user specified the cardinality explicitly
764 // using a .Times().
765 bool cardinality_specified() const { return cardinality_specified_; }
766
767 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000768 void set_cardinality(const Cardinality& a_cardinality) {
769 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000770 }
771
772 // The following group of methods should only be called after the
773 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
774 // the current thread.
775
776 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000777 void RetireAllPreRequisites()
778 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000779
780 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000781 bool is_retired() const
782 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000783 g_gmock_mutex.AssertHeld();
784 return retired_;
785 }
786
787 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000788 void Retire()
789 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000790 g_gmock_mutex.AssertHeld();
791 retired_ = true;
792 }
793
794 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000795 bool IsSatisfied() const
796 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000797 g_gmock_mutex.AssertHeld();
798 return cardinality().IsSatisfiedByCallCount(call_count_);
799 }
800
801 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000802 bool IsSaturated() const
803 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000804 g_gmock_mutex.AssertHeld();
805 return cardinality().IsSaturatedByCallCount(call_count_);
806 }
807
808 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000809 bool IsOverSaturated() const
810 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000811 g_gmock_mutex.AssertHeld();
812 return cardinality().IsOverSaturatedByCallCount(call_count_);
813 }
814
815 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000816 bool AllPrerequisitesAreSatisfied() const
817 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000818
819 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000820 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
821 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000822
823 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000824 int call_count() const
825 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000826 g_gmock_mutex.AssertHeld();
827 return call_count_;
828 }
829
830 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000831 void IncrementCallCount()
832 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000833 g_gmock_mutex.AssertHeld();
834 call_count_++;
835 }
836
zhanyong.waned6c9272011-02-23 19:39:27 +0000837 // Checks the action count (i.e. the number of WillOnce() and
838 // WillRepeatedly() clauses) against the cardinality if this hasn't
839 // been done before. Prints a warning if there are too many or too
840 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000841 void CheckActionCountIfNotDone() const
842 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000843
shiqiane35fdd92008-12-10 05:08:54 +0000844 friend class ::testing::Sequence;
845 friend class ::testing::internal::ExpectationTester;
846
847 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000848 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000849
zhanyong.waned6c9272011-02-23 19:39:27 +0000850 // Implements the .Times() clause.
851 void UntypedTimes(const Cardinality& a_cardinality);
852
shiqiane35fdd92008-12-10 05:08:54 +0000853 // This group of fields are part of the spec and won't change after
854 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000855 const char* file_; // The file that contains the expectation.
856 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400857 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000858 // True iff the cardinality is specified explicitly.
859 bool cardinality_specified_;
860 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000861 // The immediate pre-requisites (i.e. expectations that must be
862 // satisfied before this expectation can be matched) of this
863 // expectation. We use linked_ptr in the set because we want an
864 // Expectation object to be co-owned by its FunctionMocker and its
865 // successors. This allows multiple mock objects to be deleted at
866 // different times.
867 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000868
869 // This group of fields are the current state of the expectation,
870 // and can change as the mock function is called.
871 int call_count_; // How many times this expectation has been invoked.
872 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000873 UntypedActions untyped_actions_;
874 bool extra_matcher_specified_;
875 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
876 bool retires_on_saturation_;
877 Clause last_clause_;
878 mutable bool action_count_checked_; // Under mutex_.
879 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000880
881 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000882}; // class ExpectationBase
883
884// Impements an expectation for the given function type.
885template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000886class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000887 public:
888 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
889 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
890 typedef typename Function<F>::Result Result;
891
Nico Weber09fd5b32017-05-15 17:07:03 -0400892 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
893 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000894 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000895 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000896 owner_(owner),
897 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000898 // By default, extra_matcher_ should match anything. However,
899 // we cannot initialize it with _ as that triggers a compiler
900 // bug in Symbian's C++ compiler (cannot decide between two
901 // overloaded constructors of Matcher<const ArgumentTuple&>).
902 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000903 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000904
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000905 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000906 // Check the validity of the action count if it hasn't been done
907 // yet (for example, if the expectation was never used).
908 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000909 for (UntypedActions::const_iterator it = untyped_actions_.begin();
910 it != untyped_actions_.end(); ++it) {
911 delete static_cast<const Action<F>*>(*it);
912 }
shiqiane35fdd92008-12-10 05:08:54 +0000913 }
914
zhanyong.wanbf550852009-06-09 06:09:53 +0000915 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000916 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000917 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000918 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000919 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000920 "more than once in an EXPECT_CALL().");
921 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000922 ExpectSpecProperty(last_clause_ < kWith,
923 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000924 "clause in an EXPECT_CALL().");
925 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000926 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000927
928 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000929 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000930 return *this;
931 }
932
933 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000934 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000935 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000936 return *this;
937 }
938
939 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000940 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000941 return Times(Exactly(n));
942 }
943
944 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000945 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000946 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000947 ".InSequence() cannot appear after .After(),"
948 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000949 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000950 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000951
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000952 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000953 return *this;
954 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000955 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000956 return InSequence(s1).InSequence(s2);
957 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000958 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
959 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000960 return InSequence(s1, s2).InSequence(s3);
961 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000962 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
963 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000964 return InSequence(s1, s2, s3).InSequence(s4);
965 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000966 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
967 const Sequence& s3, const Sequence& s4,
968 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000969 return InSequence(s1, s2, s3, s4).InSequence(s5);
970 }
971
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000972 // Implements that .After() clause.
973 TypedExpectation& After(const ExpectationSet& s) {
974 ExpectSpecProperty(last_clause_ <= kAfter,
975 ".After() cannot appear after .WillOnce(),"
976 " .WillRepeatedly(), or "
977 ".RetiresOnSaturation().");
978 last_clause_ = kAfter;
979
980 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
981 immediate_prerequisites_ += *it;
982 }
983 return *this;
984 }
985 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
986 return After(s1).After(s2);
987 }
988 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
989 const ExpectationSet& s3) {
990 return After(s1, s2).After(s3);
991 }
992 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
993 const ExpectationSet& s3, const ExpectationSet& s4) {
994 return After(s1, s2, s3).After(s4);
995 }
996 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
997 const ExpectationSet& s3, const ExpectationSet& s4,
998 const ExpectationSet& s5) {
999 return After(s1, s2, s3, s4).After(s5);
1000 }
1001
shiqiane35fdd92008-12-10 05:08:54 +00001002 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001003 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001004 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +00001005 ".WillOnce() cannot appear after "
1006 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001007 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001008
zhanyong.waned6c9272011-02-23 19:39:27 +00001009 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001010 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001011 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001012 }
1013 return *this;
1014 }
1015
1016 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001017 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001018 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001019 ExpectSpecProperty(false,
1020 ".WillRepeatedly() cannot appear "
1021 "more than once in an EXPECT_CALL().");
1022 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001023 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001024 ".WillRepeatedly() cannot appear "
1025 "after .RetiresOnSaturation().");
1026 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001027 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001028 repeated_action_specified_ = true;
1029
1030 repeated_action_ = action;
1031 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001032 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001033 }
1034
1035 // Now that no more action clauses can be specified, we check
1036 // whether their count makes sense.
1037 CheckActionCountIfNotDone();
1038 return *this;
1039 }
1040
1041 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001042 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001043 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001044 ".RetiresOnSaturation() cannot appear "
1045 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001046 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001047 retires_on_saturation_ = true;
1048
1049 // Now that no more action clauses can be specified, we check
1050 // whether their count makes sense.
1051 CheckActionCountIfNotDone();
1052 return *this;
1053 }
1054
1055 // Returns the matchers for the arguments as specified inside the
1056 // EXPECT_CALL() macro.
1057 const ArgumentMatcherTuple& matchers() const {
1058 return matchers_;
1059 }
1060
zhanyong.wanbf550852009-06-09 06:09:53 +00001061 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001062 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1063 return extra_matcher_;
1064 }
1065
shiqiane35fdd92008-12-10 05:08:54 +00001066 // Returns the action specified by the .WillRepeatedly() clause.
1067 const Action<F>& repeated_action() const { return repeated_action_; }
1068
zhanyong.waned6c9272011-02-23 19:39:27 +00001069 // If this mock method has an extra matcher (i.e. .With(matcher)),
1070 // describes it to the ostream.
1071 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001072 if (extra_matcher_specified_) {
1073 *os << " Expected args: ";
1074 extra_matcher_.DescribeTo(os);
1075 *os << "\n";
1076 }
1077 }
1078
shiqiane35fdd92008-12-10 05:08:54 +00001079 private:
1080 template <typename Function>
1081 friend class FunctionMockerBase;
1082
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001083 // Returns an Expectation object that references and co-owns this
1084 // expectation.
1085 virtual Expectation GetHandle() {
1086 return owner_->GetHandleOf(this);
1087 }
1088
shiqiane35fdd92008-12-10 05:08:54 +00001089 // The following methods will be called only after the EXPECT_CALL()
1090 // statement finishes and when the current thread holds
1091 // g_gmock_mutex.
1092
1093 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001094 bool Matches(const ArgumentTuple& args) const
1095 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001096 g_gmock_mutex.AssertHeld();
1097 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1098 }
1099
1100 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001101 bool ShouldHandleArguments(const ArgumentTuple& args) const
1102 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001103 g_gmock_mutex.AssertHeld();
1104
1105 // In case the action count wasn't checked when the expectation
1106 // was defined (e.g. if this expectation has no WillRepeatedly()
1107 // or RetiresOnSaturation() clause), we check it when the
1108 // expectation is used for the first time.
1109 CheckActionCountIfNotDone();
1110 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1111 }
1112
1113 // Describes the result of matching the arguments against this
1114 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001115 void ExplainMatchResultTo(
1116 const ArgumentTuple& args,
1117 ::std::ostream* os) const
1118 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001119 g_gmock_mutex.AssertHeld();
1120
1121 if (is_retired()) {
1122 *os << " Expected: the expectation is active\n"
1123 << " Actual: it is retired\n";
1124 } else if (!Matches(args)) {
1125 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001126 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001127 }
zhanyong.wan82113312010-01-08 21:55:40 +00001128 StringMatchResultListener listener;
1129 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001130 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001131 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001132 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001133
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001134 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001135 *os << "\n";
1136 }
1137 } else if (!AllPrerequisitesAreSatisfied()) {
1138 *os << " Expected: all pre-requisites are satisfied\n"
1139 << " Actual: the following immediate pre-requisites "
1140 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001141 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001142 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1143 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001144 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001145 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001146 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001147 *os << "pre-requisite #" << i++ << "\n";
1148 }
1149 *os << " (end of pre-requisites)\n";
1150 } else {
1151 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001152 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001153 // is called only when the mock function call does NOT match the
1154 // expectation.
1155 *os << "The call matches the expectation.\n";
1156 }
1157 }
1158
1159 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001160 const Action<F>& GetCurrentAction(
1161 const FunctionMockerBase<F>* mocker,
1162 const ArgumentTuple& args) const
1163 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001164 g_gmock_mutex.AssertHeld();
1165 const int count = call_count();
1166 Assert(count >= 1, __FILE__, __LINE__,
1167 "call_count() is <= 0 when GetCurrentAction() is "
1168 "called - this should never happen.");
1169
zhanyong.waned6c9272011-02-23 19:39:27 +00001170 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001171 if (action_count > 0 && !repeated_action_specified_ &&
1172 count > action_count) {
1173 // If there is at least one WillOnce() and no WillRepeatedly(),
1174 // we warn the user when the WillOnce() clauses ran out.
1175 ::std::stringstream ss;
1176 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001177 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001178 << "Called " << count << " times, but only "
1179 << action_count << " WillOnce()"
1180 << (action_count == 1 ? " is" : "s are") << " specified - ";
1181 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001182 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001183 }
1184
zhanyong.waned6c9272011-02-23 19:39:27 +00001185 return count <= action_count ?
1186 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1187 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001188 }
1189
1190 // Given the arguments of a mock function call, if the call will
1191 // over-saturate this expectation, returns the default action;
1192 // otherwise, returns the next action in this expectation. Also
1193 // describes *what* happened to 'what', and explains *why* Google
1194 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001195 // IncrementCallCount(). A return value of NULL means the default
1196 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001197 const Action<F>* GetActionForArguments(
1198 const FunctionMockerBase<F>* mocker,
1199 const ArgumentTuple& args,
1200 ::std::ostream* what,
1201 ::std::ostream* why)
1202 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001203 g_gmock_mutex.AssertHeld();
1204 if (IsSaturated()) {
1205 // We have an excessive call.
1206 IncrementCallCount();
1207 *what << "Mock function called more times than expected - ";
1208 mocker->DescribeDefaultActionTo(args, what);
1209 DescribeCallCountTo(why);
1210
zhanyong.waned6c9272011-02-23 19:39:27 +00001211 // TODO(wan@google.com): allow the user to control whether
1212 // unexpected calls should fail immediately or continue using a
1213 // flag --gmock_unexpected_calls_are_fatal.
1214 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001215 }
1216
1217 IncrementCallCount();
1218 RetireAllPreRequisites();
1219
zhanyong.waned6c9272011-02-23 19:39:27 +00001220 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001221 Retire();
1222 }
1223
1224 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001225 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001226 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001227 }
1228
1229 // All the fields below won't change once the EXPECT_CALL()
1230 // statement finishes.
1231 FunctionMockerBase<F>* const owner_;
1232 ArgumentMatcherTuple matchers_;
1233 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001234 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001235
1236 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001237}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001238
1239// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1240// specifying the default behavior of, or expectation on, a mock
1241// function.
1242
1243// Note: class MockSpec really belongs to the ::testing namespace.
1244// However if we define it in ::testing, MSVC will complain when
1245// classes in ::testing::internal declare it as a friend class
1246// template. To workaround this compiler bug, we define MockSpec in
1247// ::testing::internal and import it into ::testing.
1248
zhanyong.waned6c9272011-02-23 19:39:27 +00001249// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001250GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1251 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001252 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001253
shiqiane35fdd92008-12-10 05:08:54 +00001254template <typename F>
1255class MockSpec {
1256 public:
1257 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1258 typedef typename internal::Function<F>::ArgumentMatcherTuple
1259 ArgumentMatcherTuple;
1260
1261 // Constructs a MockSpec object, given the function mocker object
1262 // that the spec is associated with.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001263 MockSpec(internal::FunctionMockerBase<F>* function_mocker,
1264 const ArgumentMatcherTuple& matchers)
1265 : function_mocker_(function_mocker), matchers_(matchers) {}
shiqiane35fdd92008-12-10 05:08:54 +00001266
1267 // Adds a new default action spec to the function mocker and returns
1268 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001269 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001270 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001271 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001272 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001273 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001274 }
1275
1276 // Adds a new expectation spec to the function mocker and returns
1277 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001278 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001279 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001280 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1281 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001282 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001283 return function_mocker_->AddNewExpectation(
1284 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001285 }
1286
David Sunderlandf437f8c2018-04-18 19:28:56 -04001287 // This operator overload is used to swallow the superfluous parameter list
1288 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1289 // explanation.
1290 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1291 return *this;
1292 }
1293
shiqiane35fdd92008-12-10 05:08:54 +00001294 private:
1295 template <typename Function>
1296 friend class internal::FunctionMocker;
1297
shiqiane35fdd92008-12-10 05:08:54 +00001298 // The function mocker that owns this spec.
1299 internal::FunctionMockerBase<F>* const function_mocker_;
1300 // The argument matchers specified in the spec.
1301 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001302
1303 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001304}; // class MockSpec
1305
kosakb5c81092014-01-29 06:41:44 +00001306// Wrapper type for generically holding an ordinary value or lvalue reference.
1307// If T is not a reference type, it must be copyable or movable.
1308// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1309// T is a move-only value type (which means that it will always be copyable
1310// if the current platform does not support move semantics).
1311//
1312// The primary template defines handling for values, but function header
1313// comments describe the contract for the whole template (including
1314// specializations).
1315template <typename T>
1316class ReferenceOrValueWrapper {
1317 public:
1318 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001319 explicit ReferenceOrValueWrapper(T value)
1320 : value_(::testing::internal::move(value)) {
1321 }
kosakb5c81092014-01-29 06:41:44 +00001322
1323 // Unwraps and returns the underlying value/reference, exactly as
1324 // originally passed. The behavior of calling this more than once on
1325 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001326 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001327
1328 // Provides nondestructive access to the underlying value/reference.
1329 // Always returns a const reference (more precisely,
1330 // const RemoveReference<T>&). The behavior of calling this after
1331 // calling Unwrap on the same object is unspecified.
1332 const T& Peek() const {
1333 return value_;
1334 }
1335
1336 private:
1337 T value_;
1338};
1339
1340// Specialization for lvalue reference types. See primary template
1341// for documentation.
1342template <typename T>
1343class ReferenceOrValueWrapper<T&> {
1344 public:
1345 // Workaround for debatable pass-by-reference lint warning (c-library-team
1346 // policy precludes NOLINT in this context)
1347 typedef T& reference;
1348 explicit ReferenceOrValueWrapper(reference ref)
1349 : value_ptr_(&ref) {}
1350 T& Unwrap() { return *value_ptr_; }
1351 const T& Peek() const { return *value_ptr_; }
1352
1353 private:
1354 T* value_ptr_;
1355};
1356
shiqiane35fdd92008-12-10 05:08:54 +00001357// MSVC warns about using 'this' in base member initializer list, so
1358// we need to temporarily disable the warning. We have to do it for
1359// the entire class to suppress the warning, even though it's about
1360// the constructor only.
1361
1362#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001363# pragma warning(push) // Saves the current warning state.
1364# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001365#endif // _MSV_VER
1366
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001367// C++ treats the void type specially. For example, you cannot define
1368// a void-typed variable or pass a void value to a function.
1369// ActionResultHolder<T> holds a value of type T, where T must be a
1370// copyable type or void (T doesn't need to be default-constructable).
1371// It hides the syntactic difference between void and other types, and
1372// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001373// non-void-returning mock functions.
1374
1375// Untyped base class for ActionResultHolder<T>.
1376class UntypedActionResultHolderBase {
1377 public:
1378 virtual ~UntypedActionResultHolderBase() {}
1379
1380 // Prints the held value as an action's result to os.
1381 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1382};
1383
1384// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001385template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001386class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001387 public:
kosakb5c81092014-01-29 06:41:44 +00001388 // Returns the held value. Must not be called more than once.
1389 T Unwrap() {
1390 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001391 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001392
1393 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001394 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001395 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001396 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001397 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001398 }
1399
1400 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001401 // result in a new-ed ActionResultHolder.
1402 template <typename F>
1403 static ActionResultHolder* PerformDefaultAction(
1404 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001405 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001406 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001407 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1408 internal::move(args), call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001409 }
1410
zhanyong.waned6c9272011-02-23 19:39:27 +00001411 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001412 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001413 template <typename F>
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001414 static ActionResultHolder* PerformAction(
1415 const Action<F>& action,
1416 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1417 return new ActionResultHolder(
1418 Wrapper(action.Perform(internal::move(args))));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001419 }
1420
1421 private:
kosakb5c81092014-01-29 06:41:44 +00001422 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001423
kosakd370f852014-11-17 01:14:16 +00001424 explicit ActionResultHolder(Wrapper result)
1425 : result_(::testing::internal::move(result)) {
1426 }
kosakb5c81092014-01-29 06:41:44 +00001427
1428 Wrapper result_;
1429
1430 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001431};
1432
1433// Specialization for T = void.
1434template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001435class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001436 public:
kosakb5c81092014-01-29 06:41:44 +00001437 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001438
zhanyong.waned6c9272011-02-23 19:39:27 +00001439 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1440
kosakb5c81092014-01-29 06:41:44 +00001441 // Performs the given mock function's default action and returns ownership
1442 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001443 template <typename F>
1444 static ActionResultHolder* PerformDefaultAction(
1445 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001446 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001447 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001448 func_mocker->PerformDefaultAction(internal::move(args), call_description);
kosakb5c81092014-01-29 06:41:44 +00001449 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001450 }
1451
kosakb5c81092014-01-29 06:41:44 +00001452 // Performs the given action and returns ownership of an empty
1453 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001454 template <typename F>
1455 static ActionResultHolder* PerformAction(
1456 const Action<F>& action,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001457 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1458 action.Perform(internal::move(args));
kosakb5c81092014-01-29 06:41:44 +00001459 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001460 }
kosakb5c81092014-01-29 06:41:44 +00001461
1462 private:
1463 ActionResultHolder() {}
1464 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001465};
1466
shiqiane35fdd92008-12-10 05:08:54 +00001467// The base of the function mocker class for the given function type.
1468// We put the methods in this class instead of its child to avoid code
1469// bloat.
1470template <typename F>
1471class FunctionMockerBase : public UntypedFunctionMockerBase {
1472 public:
1473 typedef typename Function<F>::Result Result;
1474 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1475 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1476
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001477 FunctionMockerBase() {}
shiqiane35fdd92008-12-10 05:08:54 +00001478
1479 // The destructor verifies that all expectations on this mock
1480 // function have been satisfied. If not, it will report Google Test
1481 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001482 virtual ~FunctionMockerBase()
1483 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001484 MutexLock l(&g_gmock_mutex);
1485 VerifyAndClearExpectationsLocked();
1486 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001487 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001488 }
1489
1490 // Returns the ON_CALL spec that matches this mock function with the
1491 // given arguments; returns NULL if no matching ON_CALL is found.
1492 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001493 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001494 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001495 for (UntypedOnCallSpecs::const_reverse_iterator it
1496 = untyped_on_call_specs_.rbegin();
1497 it != untyped_on_call_specs_.rend(); ++it) {
1498 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1499 if (spec->Matches(args))
1500 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001501 }
1502
1503 return NULL;
1504 }
1505
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001506 // Performs the default action of this mock function on the given
1507 // arguments and returns the result. Asserts (or throws if
1508 // exceptions are enabled) with a helpful call descrption if there
1509 // is no valid return value. This method doesn't depend on the
1510 // mutable state of this object, and thus can be called concurrently
1511 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001512 // L = *
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001513 Result PerformDefaultAction(
1514 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1515 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001516 const OnCallSpec<F>* const spec =
1517 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001518 if (spec != NULL) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001519 return spec->GetAction().Perform(internal::move(args));
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001520 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001521 const std::string message =
1522 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001523 "\n The mock function has no default action "
1524 "set, and its return type has no default value set.";
1525#if GTEST_HAS_EXCEPTIONS
1526 if (!DefaultValue<Result>::Exists()) {
1527 throw std::runtime_error(message);
1528 }
1529#else
1530 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1531#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001532 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001533 }
1534
zhanyong.waned6c9272011-02-23 19:39:27 +00001535 // Performs the default action with the given arguments and returns
1536 // the action's result. The call description string will be used in
1537 // the error message to describe the call in the case the default
1538 // action fails. The caller is responsible for deleting the result.
1539 // L = *
1540 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001541 void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001542 const std::string& call_description) const {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001543 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1544 return ResultHolder::PerformDefaultAction(this, internal::move(*args),
1545 call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001546 }
1547
zhanyong.waned6c9272011-02-23 19:39:27 +00001548 // Performs the given action with the given arguments and returns
1549 // the action's result. The caller is responsible for deleting the
1550 // result.
1551 // L = *
1552 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001553 const void* untyped_action, void* untyped_args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001554 // Make a copy of the action before performing it, in case the
1555 // action deletes the mock object (and thus deletes itself).
1556 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001557 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1558 return ResultHolder::PerformAction(action, internal::move(*args));
zhanyong.waned6c9272011-02-23 19:39:27 +00001559 }
shiqiane35fdd92008-12-10 05:08:54 +00001560
zhanyong.waned6c9272011-02-23 19:39:27 +00001561 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1562 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001563 virtual void ClearDefaultActionsLocked()
1564 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001565 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001566
1567 // Deleting our default actions may trigger other mock objects to be
1568 // deleted, for example if an action contains a reference counted smart
1569 // pointer to that mock object, and that is the last reference. So if we
1570 // delete our actions within the context of the global mutex we may deadlock
1571 // when this method is called again. Instead, make a copy of the set of
1572 // actions to delete, clear our set within the mutex, and then delete the
1573 // actions outside of the mutex.
1574 UntypedOnCallSpecs specs_to_delete;
1575 untyped_on_call_specs_.swap(specs_to_delete);
1576
1577 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001578 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001579 specs_to_delete.begin();
1580 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001581 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001582 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001583
1584 // Lock the mutex again, since the caller expects it to be locked when we
1585 // return.
1586 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001587 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001588
shiqiane35fdd92008-12-10 05:08:54 +00001589 protected:
1590 template <typename Function>
1591 friend class MockSpec;
1592
zhanyong.waned6c9272011-02-23 19:39:27 +00001593 typedef ActionResultHolder<Result> ResultHolder;
1594
shiqiane35fdd92008-12-10 05:08:54 +00001595 // Returns the result of invoking this mock function with the given
1596 // arguments. This function can be safely called from multiple
1597 // threads concurrently.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001598 Result InvokeWith(
1599 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args)
1600 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1601 // const_cast is required since in C++98 we still pass ArgumentTuple around
1602 // by const& instead of rvalue reference.
1603 void* untyped_args = const_cast<void*>(static_cast<const void*>(&args));
kosakb5c81092014-01-29 06:41:44 +00001604 scoped_ptr<ResultHolder> holder(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001605 DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args)));
kosakb5c81092014-01-29 06:41:44 +00001606 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001607 }
shiqiane35fdd92008-12-10 05:08:54 +00001608
1609 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001610 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001611 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001612 const ArgumentMatcherTuple& m)
1613 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001614 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001615 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1616 untyped_on_call_specs_.push_back(on_call_spec);
1617 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001618 }
1619
1620 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001621 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1622 const std::string& source_text,
1623 const ArgumentMatcherTuple& m)
1624 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001625 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001626 TypedExpectation<F>* const expectation =
1627 new TypedExpectation<F>(this, file, line, source_text, m);
1628 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001629 // See the definition of untyped_expectations_ for why access to
1630 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001631 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001632
1633 // Adds this expectation into the implicit sequence if there is one.
1634 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1635 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001636 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001637 }
1638
1639 return *expectation;
1640 }
1641
shiqiane35fdd92008-12-10 05:08:54 +00001642 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001643 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001644
zhanyong.waned6c9272011-02-23 19:39:27 +00001645 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001646
1647 // Describes what default action will be performed for the given
1648 // arguments.
1649 // L = *
1650 void DescribeDefaultActionTo(const ArgumentTuple& args,
1651 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001652 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001653
1654 if (spec == NULL) {
1655 *os << (internal::type_equals<Result, void>::value ?
1656 "returning directly.\n" :
1657 "returning default value.\n");
1658 } else {
1659 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001660 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001661 }
1662 }
1663
1664 // Writes a message that the call is uninteresting (i.e. neither
1665 // explicitly expected nor explicitly unexpected) to the given
1666 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001667 virtual void UntypedDescribeUninterestingCall(
1668 const void* untyped_args,
1669 ::std::ostream* os) const
1670 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001671 const ArgumentTuple& args =
1672 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001673 *os << "Uninteresting mock function call - ";
1674 DescribeDefaultActionTo(args, os);
1675 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001676 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001677 }
1678
zhanyong.waned6c9272011-02-23 19:39:27 +00001679 // Returns the expectation that matches the given function arguments
1680 // (or NULL is there's no match); when a match is found,
1681 // untyped_action is set to point to the action that should be
1682 // performed (or NULL if the action is "do default"), and
1683 // is_excessive is modified to indicate whether the call exceeds the
1684 // expected number.
1685 //
shiqiane35fdd92008-12-10 05:08:54 +00001686 // Critical section: We must find the matching expectation and the
1687 // corresponding action that needs to be taken in an ATOMIC
1688 // transaction. Otherwise another thread may call this mock
1689 // method in the middle and mess up the state.
1690 //
1691 // However, performing the action has to be left out of the critical
1692 // section. The reason is that we have no control on what the
1693 // action does (it can invoke an arbitrary user function or even a
1694 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001695 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1696 const void* untyped_args,
1697 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001698 ::std::ostream* what, ::std::ostream* why)
1699 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001700 const ArgumentTuple& args =
1701 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001702 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001703 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1704 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001705 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001706 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001707 }
1708
1709 // This line must be done before calling GetActionForArguments(),
1710 // which will increment the call count for *exp and thus affect
1711 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001712 *is_excessive = exp->IsSaturated();
1713 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1714 if (action != NULL && action->IsDoDefault())
1715 action = NULL; // Normalize "do default" to NULL.
1716 *untyped_action = action;
1717 return exp;
1718 }
1719
1720 // Prints the given function arguments to the ostream.
1721 virtual void UntypedPrintArgs(const void* untyped_args,
1722 ::std::ostream* os) const {
1723 const ArgumentTuple& args =
1724 *static_cast<const ArgumentTuple*>(untyped_args);
1725 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001726 }
1727
1728 // Returns the expectation that matches the arguments, or NULL if no
1729 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001730 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001731 const ArgumentTuple& args) const
1732 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001733 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001734 // See the definition of untyped_expectations_ for why access to
1735 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001736 for (typename UntypedExpectations::const_reverse_iterator it =
1737 untyped_expectations_.rbegin();
1738 it != untyped_expectations_.rend(); ++it) {
1739 TypedExpectation<F>* const exp =
1740 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001741 if (exp->ShouldHandleArguments(args)) {
1742 return exp;
1743 }
1744 }
1745 return NULL;
1746 }
1747
1748 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001749 void FormatUnexpectedCallMessageLocked(
1750 const ArgumentTuple& args,
1751 ::std::ostream* os,
1752 ::std::ostream* why) const
1753 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001754 g_gmock_mutex.AssertHeld();
1755 *os << "\nUnexpected mock function call - ";
1756 DescribeDefaultActionTo(args, os);
1757 PrintTriedExpectationsLocked(args, why);
1758 }
1759
1760 // Prints a list of expectations that have been tried against the
1761 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001762 void PrintTriedExpectationsLocked(
1763 const ArgumentTuple& args,
1764 ::std::ostream* why) const
1765 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001766 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001767 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001768 *why << "Google Mock tried the following " << count << " "
1769 << (count == 1 ? "expectation, but it didn't match" :
1770 "expectations, but none matched")
1771 << ":\n";
1772 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001773 TypedExpectation<F>* const expectation =
1774 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001775 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001776 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001777 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001778 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001779 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001780 *why << expectation->source_text() << "...\n";
1781 expectation->ExplainMatchResultTo(args, why);
1782 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001783 }
1784 }
1785
zhanyong.wan16cf4732009-05-14 20:55:30 +00001786 // There is no generally useful and implementable semantics of
1787 // copying a mock object, so copying a mock is usually a user error.
1788 // Thus we disallow copying function mockers. If the user really
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +01001789 // wants to copy a mock object, they should implement their own copy
zhanyong.wan16cf4732009-05-14 20:55:30 +00001790 // operation, for example:
1791 //
1792 // class MockFoo : public Foo {
1793 // public:
1794 // // Defines a copy constructor explicitly.
1795 // MockFoo(const MockFoo& src) {}
1796 // ...
1797 // };
1798 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001799}; // class FunctionMockerBase
1800
1801#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001802# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001803#endif // _MSV_VER
1804
1805// Implements methods of FunctionMockerBase.
1806
1807// Verifies that all expectations on this mock function have been
1808// satisfied. Reports one or more Google Test non-fatal failures and
1809// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001810
1811// Reports an uninteresting call (whose description is in msg) in the
1812// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001813void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001814
shiqiane35fdd92008-12-10 05:08:54 +00001815} // namespace internal
1816
1817// The style guide prohibits "using" statements in a namespace scope
1818// inside a header file. However, the MockSpec class template is
1819// meant to be defined in the ::testing namespace. The following line
1820// is just a trick for working around a bug in MSVC 8.0, which cannot
1821// handle it if we define MockSpec in ::testing.
1822using internal::MockSpec;
1823
1824// Const(x) is a convenient function for obtaining a const reference
1825// to x. This is useful for setting expectations on an overloaded
1826// const mock method, e.g.
1827//
1828// class MockFoo : public FooInterface {
1829// public:
1830// MOCK_METHOD0(Bar, int());
1831// MOCK_CONST_METHOD0(Bar, int&());
1832// };
1833//
1834// MockFoo foo;
1835// // Expects a call to non-const MockFoo::Bar().
1836// EXPECT_CALL(foo, Bar());
1837// // Expects a call to const MockFoo::Bar().
1838// EXPECT_CALL(Const(foo), Bar());
1839template <typename T>
1840inline const T& Const(const T& x) { return x; }
1841
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001842// Constructs an Expectation object that references and co-owns exp.
1843inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1844 : expectation_base_(exp.GetHandle().expectation_base()) {}
1845
shiqiane35fdd92008-12-10 05:08:54 +00001846} // namespace testing
1847
David Sunderlandf437f8c2018-04-18 19:28:56 -04001848// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1849// required to avoid compile errors when the name of the method used in call is
1850// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1851// tests in internal/gmock-spec-builders_test.cc for more details.
1852//
1853// This macro supports statements both with and without parameter matchers. If
1854// the parameter list is omitted, gMock will accept any parameters, which allows
1855// tests to be written that don't need to encode the number of method
1856// parameter. This technique may only be used for non-overloaded methods.
1857//
1858// // These are the same:
duxiuxing65a49a72018-07-17 15:46:47 +08001859// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1860// ON_CALL(mock, NoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001861//
1862// // As are these:
duxiuxing65a49a72018-07-17 15:46:47 +08001863// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1864// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001865//
1866// // Can also specify args if you want, of course:
duxiuxing65a49a72018-07-17 15:46:47 +08001867// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001868//
1869// // Overloads work as long as you specify parameters:
duxiuxing65a49a72018-07-17 15:46:47 +08001870// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1871// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001872//
1873// // Oops! Which overload did you want?
duxiuxing65a49a72018-07-17 15:46:47 +08001874// ON_CALL(mock, OverloadedMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001875// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1876//
1877// How this works: The mock class uses two overloads of the gmock_Method
1878// expectation setter method plus an operator() overload on the MockSpec object.
1879// In the matcher list form, the macro expands to:
1880//
1881// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001882// ON_CALL(mock, TwoArgsMethod(_, 45))...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001883//
duxiuxing65a49a72018-07-17 15:46:47 +08001884// // ...expands to:
1885// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001886// |-------------v---------------||------------v-------------|
1887// invokes first overload swallowed by operator()
1888//
duxiuxing65a49a72018-07-17 15:46:47 +08001889// // ...which is essentially:
1890// mock.gmock_TwoArgsMethod(_, 45)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001891//
1892// Whereas the form without a matcher list:
1893//
1894// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001895// ON_CALL(mock, TwoArgsMethod)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001896//
duxiuxing65a49a72018-07-17 15:46:47 +08001897// // ...expands to:
1898// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001899// |-----------------------v--------------------------|
1900// invokes second overload
1901//
duxiuxing65a49a72018-07-17 15:46:47 +08001902// // ...which is essentially:
1903// mock.gmock_TwoArgsMethod(_, _)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001904//
1905// The WithoutMatchers() argument is used to disambiguate overloads and to
1906// block the caller from accidentally invoking the second overload directly. The
1907// second argument is an internal type derived from the method signature. The
1908// failure to disambiguate two overloads of this method in the ON_CALL statement
1909// is how we block callers from setting expectations on overloaded methods.
1910#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1911 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \
1912 .Setter(__FILE__, __LINE__, #mock_expr, #call)
shiqiane35fdd92008-12-10 05:08:54 +00001913
David Sunderlandf437f8c2018-04-18 19:28:56 -04001914#define ON_CALL(obj, call) \
1915 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1916
1917#define EXPECT_CALL(obj, call) \
1918 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
shiqiane35fdd92008-12-10 05:08:54 +00001919
1920#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_