blob: a8347bd86df67f80da882082022f7d4bb0a9b6cf [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements the ON_CALL() and EXPECT_CALL() macros.
35//
36// A user can use the ON_CALL() macro to specify the default action of
37// a mock method. The syntax is:
38//
39// ON_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000040// .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +000041// .WillByDefault(action);
42//
zhanyong.wanbf550852009-06-09 06:09:53 +000043// where the .With() clause is optional.
shiqiane35fdd92008-12-10 05:08:54 +000044//
45// A user can use the EXPECT_CALL() macro to specify an expectation on
46// a mock method. The syntax is:
47//
48// EXPECT_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000049// .With(multi-argument-matchers)
shiqiane35fdd92008-12-10 05:08:54 +000050// .Times(cardinality)
51// .InSequence(sequences)
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000052// .After(expectations)
shiqiane35fdd92008-12-10 05:08:54 +000053// .WillOnce(action)
54// .WillRepeatedly(action)
55// .RetiresOnSaturation();
56//
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000057// where all clauses are optional, and .InSequence()/.After()/
58// .WillOnce() can appear any number of times.
shiqiane35fdd92008-12-10 05:08:54 +000059
60#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
61#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62
63#include <map>
64#include <set>
65#include <sstream>
66#include <string>
67#include <vector>
68
zhanyong.wanedd4ab42013-02-28 22:58:51 +000069#if GTEST_HAS_EXCEPTIONS
70# include <stdexcept> // NOLINT
71#endif
72
zhanyong.wan53e08c42010-09-14 05:38:21 +000073#include "gmock/gmock-actions.h"
74#include "gmock/gmock-cardinalities.h"
75#include "gmock/gmock-matchers.h"
76#include "gmock/internal/gmock-internal-utils.h"
77#include "gmock/internal/gmock-port.h"
78#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000079
80namespace testing {
81
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000082// An abstract handle of an expectation.
83class Expectation;
84
85// A set of expectation handles.
86class ExpectationSet;
87
shiqiane35fdd92008-12-10 05:08:54 +000088// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
89// and MUST NOT BE USED IN USER CODE!!!
90namespace internal {
91
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000092// Implements a mock function.
93template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000094
95// Base class for expectations.
96class ExpectationBase;
97
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000098// Implements an expectation.
99template <typename F> class TypedExpectation;
100
shiqiane35fdd92008-12-10 05:08:54 +0000101// Helper class for testing the Expectation class template.
102class ExpectationTester;
103
104// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000105template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000106
shiqiane35fdd92008-12-10 05:08:54 +0000107// Protects the mock object registry (in class Mock), all function
108// mockers, and all expectations.
109//
110// The reason we don't use more fine-grained protection is: when a
111// mock function Foo() is called, it needs to consult its expectations
112// to see which one should be picked. If another thread is allowed to
113// call a mock function (either Foo() or a different one) at the same
114// time, it could affect the "retired" attributes of Foo()'s
115// expectations when InSequence() is used, and thus affect which
116// expectation gets picked. Therefore, we sequence all mock function
117// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000118GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000119
zhanyong.waned6c9272011-02-23 19:39:27 +0000120// Untyped base class for ActionResultHolder<R>.
121class UntypedActionResultHolderBase;
122
shiqiane35fdd92008-12-10 05:08:54 +0000123// Abstract base class of FunctionMockerBase. This is the
124// type-agnostic part of the function mocker interface. Its pure
125// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000126class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000127 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000128 UntypedFunctionMockerBase();
129 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000130
131 // Verifies that all expectations on this mock function have been
132 // satisfied. Reports one or more Google Test non-fatal failures
133 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000134 bool VerifyAndClearExpectationsLocked()
135 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000136
137 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000138 virtual void ClearDefaultActionsLocked()
139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000140
141 // In all of the following Untyped* functions, it's the caller's
142 // responsibility to guarantee the correctness of the arguments'
143 // types.
144
145 // Performs the default action with the given arguments and returns
146 // the action's result. The call description string will be used in
147 // the error message to describe the call in the case the default
148 // action fails.
149 // L = *
150 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Nico Weber09fd5b32017-05-15 17:07:03 -0400151 const void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000152
153 // Performs the given action with the given arguments and returns
154 // the action's result.
155 // L = *
156 virtual UntypedActionResultHolderBase* UntypedPerformAction(
157 const void* untyped_action,
158 const void* untyped_args) const = 0;
159
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.
kosakb5c81092014-01-29 06:41:44 +0000213 UntypedActionResultHolderBase* UntypedInvokeWith(
vladlosev4d60a592011-10-24 21:16:22 +0000214 const void* untyped_args)
215 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000216
217 protected:
218 typedef std::vector<const void*> UntypedOnCallSpecs;
219
220 typedef std::vector<internal::linked_ptr<ExpectationBase> >
221 UntypedExpectations;
222
223 // Returns an Expectation object that references and co-owns exp,
224 // which must be an expectation on this mock function.
225 Expectation GetHandleOf(ExpectationBase* exp);
226
227 // Address of the mock object this mock method belongs to. Only
228 // valid after this mock method has been called or
229 // ON_CALL/EXPECT_CALL has been invoked on it.
230 const void* mock_obj_; // Protected by g_gmock_mutex.
231
232 // Name of the function being mocked. Only valid after this mock
233 // method has been called.
234 const char* name_; // Protected by g_gmock_mutex.
235
236 // All default action specs for this function mocker.
237 UntypedOnCallSpecs untyped_on_call_specs_;
238
239 // All expectations for this function mocker.
240 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000241}; // class UntypedFunctionMockerBase
242
zhanyong.waned6c9272011-02-23 19:39:27 +0000243// Untyped base class for OnCallSpec<F>.
244class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000245 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000246 // The arguments are the location of the ON_CALL() statement.
247 UntypedOnCallSpecBase(const char* a_file, int a_line)
248 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000249
250 // Where in the source file was the default action spec defined?
251 const char* file() const { return file_; }
252 int line() const { return line_; }
253
zhanyong.waned6c9272011-02-23 19:39:27 +0000254 protected:
255 // Gives each clause in the ON_CALL() statement a name.
256 enum Clause {
257 // Do not change the order of the enum members! The run-time
258 // syntax checking relies on it.
259 kNone,
260 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000261 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000262 };
263
264 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400265 void AssertSpecProperty(bool property,
266 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000267 Assert(property, file_, line_, failure_message);
268 }
269
270 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400271 void ExpectSpecProperty(bool property,
272 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000273 Expect(property, file_, line_, failure_message);
274 }
275
276 const char* file_;
277 int line_;
278
279 // The last clause in the ON_CALL() statement as seen so far.
280 // Initially kNone and changes as the statement is parsed.
281 Clause last_clause_;
282}; // class UntypedOnCallSpecBase
283
284// This template class implements an ON_CALL spec.
285template <typename F>
286class OnCallSpec : public UntypedOnCallSpecBase {
287 public:
288 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
289 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
290
291 // Constructs an OnCallSpec object from the information inside
292 // the parenthesis of an ON_CALL() statement.
293 OnCallSpec(const char* a_file, int a_line,
294 const ArgumentMatcherTuple& matchers)
295 : UntypedOnCallSpecBase(a_file, a_line),
296 matchers_(matchers),
297 // By default, extra_matcher_ should match anything. However,
298 // we cannot initialize it with _ as that triggers a compiler
299 // bug in Symbian's C++ compiler (cannot decide between two
300 // overloaded constructors of Matcher<const ArgumentTuple&>).
301 extra_matcher_(A<const ArgumentTuple&>()) {
302 }
303
zhanyong.wanbf550852009-06-09 06:09:53 +0000304 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000305 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000306 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000307 ExpectSpecProperty(last_clause_ < kWith,
308 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000309 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000310 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000311
312 extra_matcher_ = m;
313 return *this;
314 }
315
316 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000317 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000318 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000319 ".WillByDefault() must appear "
320 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000321 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000322
323 ExpectSpecProperty(!action.IsDoDefault(),
324 "DoDefault() cannot be used in ON_CALL().");
325 action_ = action;
326 return *this;
327 }
328
329 // Returns true iff the given arguments match the matchers.
330 bool Matches(const ArgumentTuple& args) const {
331 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
332 }
333
334 // Returns the action specified by the user.
335 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000336 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000337 ".WillByDefault() must appear exactly "
338 "once in an ON_CALL().");
339 return action_;
340 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000341
shiqiane35fdd92008-12-10 05:08:54 +0000342 private:
shiqiane35fdd92008-12-10 05:08:54 +0000343 // The information in statement
344 //
345 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000346 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000347 // .WillByDefault(action);
348 //
349 // is recorded in the data members like this:
350 //
351 // source file that contains the statement => file_
352 // line number of the statement => line_
353 // matchers => matchers_
354 // multi-argument-matcher => extra_matcher_
355 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000356 ArgumentMatcherTuple matchers_;
357 Matcher<const ArgumentTuple&> extra_matcher_;
358 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000359}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000360
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000361// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000362enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000363 kAllow,
364 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000365 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000366};
367
368} // namespace internal
369
370// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000371class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000372 public:
373 // The following public methods can be called concurrently.
374
zhanyong.wandf35a762009-04-22 22:25:31 +0000375 // Tells Google Mock to ignore mock_obj when checking for leaked
376 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000377 static void AllowLeak(const void* mock_obj)
378 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000379
shiqiane35fdd92008-12-10 05:08:54 +0000380 // Verifies and clears all expectations on the given mock object.
381 // If the expectations aren't satisfied, generates one or more
382 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000383 static bool VerifyAndClearExpectations(void* mock_obj)
384 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000385
386 // Verifies all expectations on the given mock object and clears its
387 // default actions and expectations. Returns true iff the
388 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000389 static bool VerifyAndClear(void* mock_obj)
390 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000391
shiqiane35fdd92008-12-10 05:08:54 +0000392 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000393 friend class internal::UntypedFunctionMockerBase;
394
shiqiane35fdd92008-12-10 05:08:54 +0000395 // Needed for a function mocker to register itself (so that we know
396 // how to clear a mock object).
397 template <typename F>
398 friend class internal::FunctionMockerBase;
399
shiqiane35fdd92008-12-10 05:08:54 +0000400 template <typename M>
401 friend class NiceMock;
402
403 template <typename M>
zhanyong.wan844fa942013-03-01 01:54:22 +0000404 friend class NaggyMock;
405
406 template <typename M>
shiqiane35fdd92008-12-10 05:08:54 +0000407 friend class StrictMock;
408
409 // Tells Google Mock to allow uninteresting calls on the given mock
410 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000411 static void AllowUninterestingCalls(const void* mock_obj)
412 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000413
414 // Tells Google Mock to warn the user about uninteresting calls on
415 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000416 static void WarnUninterestingCalls(const void* mock_obj)
417 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000418
419 // Tells Google Mock to fail uninteresting calls on the given mock
420 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000421 static void FailUninterestingCalls(const void* mock_obj)
422 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000423
424 // Tells Google Mock the given mock object is being destroyed and
425 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000426 static void UnregisterCallReaction(const void* mock_obj)
427 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000428
429 // Returns the reaction Google Mock will have on uninteresting calls
430 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000431 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000432 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000433 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000434
435 // Verifies that all expectations on the given mock object have been
436 // satisfied. Reports one or more Google Test non-fatal failures
437 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000438 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
439 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000440
441 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000442 static void ClearDefaultActionsLocked(void* mock_obj)
443 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000444
445 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000446 static void Register(
447 const void* mock_obj,
448 internal::UntypedFunctionMockerBase* mocker)
449 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000450
zhanyong.wandf35a762009-04-22 22:25:31 +0000451 // Tells Google Mock where in the source code mock_obj is used in an
452 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
453 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000454 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000455 const void* mock_obj, const char* file, int line)
456 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000457
shiqiane35fdd92008-12-10 05:08:54 +0000458 // Unregisters a mock method; removes the owning mock object from
459 // the registry when the last mock method associated with it has
460 // been unregistered. This is called only in the destructor of
461 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000462 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
463 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000464}; // class Mock
465
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000466// An abstract handle of an expectation. Useful in the .After()
467// clause of EXPECT_CALL() for setting the (partial) order of
468// expectations. The syntax:
469//
470// Expectation e1 = EXPECT_CALL(...)...;
471// EXPECT_CALL(...).After(e1)...;
472//
473// sets two expectations where the latter can only be matched after
474// the former has been satisfied.
475//
476// Notes:
477// - This class is copyable and has value semantics.
478// - Constness is shallow: a const Expectation object itself cannot
479// be modified, but the mutable methods of the ExpectationBase
480// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000481// - The constructors and destructor are defined out-of-line because
482// the Symbian WINSCW compiler wants to otherwise instantiate them
483// when it sees this class definition, at which point it doesn't have
484// ExpectationBase available yet, leading to incorrect destruction
485// in the linked_ptr (or compilation errors if using a checking
486// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000487class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000488 public:
489 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000490 Expectation();
491
492 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000493
494 // This single-argument ctor must not be explicit, in order to support the
495 // Expectation e = EXPECT_CALL(...);
496 // syntax.
497 //
498 // A TypedExpectation object stores its pre-requisites as
499 // Expectation objects, and needs to call the non-const Retire()
500 // method on the ExpectationBase objects they reference. Therefore
501 // Expectation must receive a *non-const* reference to the
502 // ExpectationBase object.
503 Expectation(internal::ExpectationBase& exp); // NOLINT
504
505 // The compiler-generated copy ctor and operator= work exactly as
506 // intended, so we don't need to define our own.
507
508 // Returns true iff rhs references the same expectation as this object does.
509 bool operator==(const Expectation& rhs) const {
510 return expectation_base_ == rhs.expectation_base_;
511 }
512
513 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
514
515 private:
516 friend class ExpectationSet;
517 friend class Sequence;
518 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000519 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000520
521 template <typename F>
522 friend class ::testing::internal::FunctionMockerBase;
523
524 template <typename F>
525 friend class ::testing::internal::TypedExpectation;
526
527 // This comparator is needed for putting Expectation objects into a set.
528 class Less {
529 public:
530 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
531 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
532 }
533 };
534
535 typedef ::std::set<Expectation, Less> Set;
536
537 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000538 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000539
540 // Returns the expectation this object references.
541 const internal::linked_ptr<internal::ExpectationBase>&
542 expectation_base() const {
543 return expectation_base_;
544 }
545
546 // A linked_ptr that co-owns the expectation this handle references.
547 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
548};
549
550// A set of expectation handles. Useful in the .After() clause of
551// EXPECT_CALL() for setting the (partial) order of expectations. The
552// syntax:
553//
554// ExpectationSet es;
555// es += EXPECT_CALL(...)...;
556// es += EXPECT_CALL(...)...;
557// EXPECT_CALL(...).After(es)...;
558//
559// sets three expectations where the last one can only be matched
560// after the first two have both been satisfied.
561//
562// This class is copyable and has value semantics.
563class ExpectationSet {
564 public:
565 // A bidirectional iterator that can read a const element in the set.
566 typedef Expectation::Set::const_iterator const_iterator;
567
568 // An object stored in the set. This is an alias of Expectation.
569 typedef Expectation::Set::value_type value_type;
570
571 // Constructs an empty set.
572 ExpectationSet() {}
573
574 // This single-argument ctor must not be explicit, in order to support the
575 // ExpectationSet es = EXPECT_CALL(...);
576 // syntax.
577 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
578 *this += Expectation(exp);
579 }
580
581 // This single-argument ctor implements implicit conversion from
582 // Expectation and thus must not be explicit. This allows either an
583 // Expectation or an ExpectationSet to be used in .After().
584 ExpectationSet(const Expectation& e) { // NOLINT
585 *this += e;
586 }
587
588 // The compiler-generator ctor and operator= works exactly as
589 // intended, so we don't need to define our own.
590
591 // Returns true iff rhs contains the same set of Expectation objects
592 // as this does.
593 bool operator==(const ExpectationSet& rhs) const {
594 return expectations_ == rhs.expectations_;
595 }
596
597 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
598
599 // Implements the syntax
600 // expectation_set += EXPECT_CALL(...);
601 ExpectationSet& operator+=(const Expectation& e) {
602 expectations_.insert(e);
603 return *this;
604 }
605
606 int size() const { return static_cast<int>(expectations_.size()); }
607
608 const_iterator begin() const { return expectations_.begin(); }
609 const_iterator end() const { return expectations_.end(); }
610
611 private:
612 Expectation::Set expectations_;
613};
614
615
shiqiane35fdd92008-12-10 05:08:54 +0000616// Sequence objects are used by a user to specify the relative order
617// in which the expectations should match. They are copyable (we rely
618// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000619class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000620 public:
621 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000622 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000623
624 // Adds an expectation to this sequence. The caller must ensure
625 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000626 void AddExpectation(const Expectation& expectation) const;
627
shiqiane35fdd92008-12-10 05:08:54 +0000628 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000629 // The last expectation in this sequence. We use a linked_ptr here
630 // because Sequence objects are copyable and we want the copies to
631 // be aliases. The linked_ptr allows the copies to co-own and share
632 // the same Expectation object.
633 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000634}; // class Sequence
635
636// An object of this type causes all EXPECT_CALL() statements
637// encountered in its scope to be put in an anonymous sequence. The
638// work is done in the constructor and destructor. You should only
639// create an InSequence object on the stack.
640//
641// The sole purpose for this class is to support easy definition of
642// sequential expectations, e.g.
643//
644// {
645// InSequence dummy; // The name of the object doesn't matter.
646//
647// // The following expectations must match in the order they appear.
648// EXPECT_CALL(a, Bar())...;
649// EXPECT_CALL(a, Baz())...;
650// ...
651// EXPECT_CALL(b, Xyz())...;
652// }
653//
654// You can create InSequence objects in multiple threads, as long as
655// they are used to affect different mock objects. The idea is that
656// each thread can create and set up its own mocks as if it's the only
657// thread. However, for clarity of your tests we recommend you to set
658// up mocks in the main thread unless you have a good reason not to do
659// so.
vladlosev587c1b32011-05-20 00:42:22 +0000660class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000661 public:
662 InSequence();
663 ~InSequence();
664 private:
665 bool sequence_created_;
666
667 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000668} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000669
670namespace internal {
671
672// Points to the implicit sequence introduced by a living InSequence
673// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000674GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000675
676// Base class for implementing expectations.
677//
678// There are two reasons for having a type-agnostic base class for
679// Expectation:
680//
681// 1. We need to store collections of expectations of different
682// types (e.g. all pre-requisites of a particular expectation, all
683// expectations in a sequence). Therefore these expectation objects
684// must share a common base class.
685//
686// 2. We can avoid binary code bloat by moving methods not depending
687// on the template argument of Expectation to the base class.
688//
689// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000690class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000691 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000692 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400693 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000694
695 virtual ~ExpectationBase();
696
697 // Where in the source file was the expectation spec defined?
698 const char* file() const { return file_; }
699 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000700 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000701 // Returns the cardinality specified in the expectation spec.
702 const Cardinality& cardinality() const { return cardinality_; }
703
704 // Describes the source file location of this expectation.
705 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000706 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000707 }
708
709 // Describes how many times a function call matching this
710 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000711 void DescribeCallCountTo(::std::ostream* os) const
712 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000713
714 // If this mock method has an extra matcher (i.e. .With(matcher)),
715 // describes it to the ostream.
716 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000717
shiqiane35fdd92008-12-10 05:08:54 +0000718 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000719 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000720 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000721
722 enum Clause {
723 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000724 kNone,
725 kWith,
726 kTimes,
727 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000728 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000729 kWillOnce,
730 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000731 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000732 };
733
zhanyong.waned6c9272011-02-23 19:39:27 +0000734 typedef std::vector<const void*> UntypedActions;
735
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000736 // Returns an Expectation object that references and co-owns this
737 // expectation.
738 virtual Expectation GetHandle() = 0;
739
shiqiane35fdd92008-12-10 05:08:54 +0000740 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400741 void AssertSpecProperty(bool property,
742 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000743 Assert(property, file_, line_, failure_message);
744 }
745
746 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400747 void ExpectSpecProperty(bool property,
748 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000749 Expect(property, file_, line_, failure_message);
750 }
751
752 // Explicitly specifies the cardinality of this expectation. Used
753 // by the subclasses to implement the .Times() clause.
754 void SpecifyCardinality(const Cardinality& cardinality);
755
756 // Returns true iff the user specified the cardinality explicitly
757 // using a .Times().
758 bool cardinality_specified() const { return cardinality_specified_; }
759
760 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000761 void set_cardinality(const Cardinality& a_cardinality) {
762 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000763 }
764
765 // The following group of methods should only be called after the
766 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
767 // the current thread.
768
769 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000770 void RetireAllPreRequisites()
771 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000772
773 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000774 bool is_retired() const
775 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000776 g_gmock_mutex.AssertHeld();
777 return retired_;
778 }
779
780 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000781 void Retire()
782 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000783 g_gmock_mutex.AssertHeld();
784 retired_ = true;
785 }
786
787 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000788 bool IsSatisfied() const
789 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000790 g_gmock_mutex.AssertHeld();
791 return cardinality().IsSatisfiedByCallCount(call_count_);
792 }
793
794 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000795 bool IsSaturated() const
796 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000797 g_gmock_mutex.AssertHeld();
798 return cardinality().IsSaturatedByCallCount(call_count_);
799 }
800
801 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000802 bool IsOverSaturated() const
803 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000804 g_gmock_mutex.AssertHeld();
805 return cardinality().IsOverSaturatedByCallCount(call_count_);
806 }
807
808 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000809 bool AllPrerequisitesAreSatisfied() const
810 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000811
812 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000813 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
814 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000815
816 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000817 int call_count() const
818 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000819 g_gmock_mutex.AssertHeld();
820 return call_count_;
821 }
822
823 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000824 void IncrementCallCount()
825 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000826 g_gmock_mutex.AssertHeld();
827 call_count_++;
828 }
829
zhanyong.waned6c9272011-02-23 19:39:27 +0000830 // Checks the action count (i.e. the number of WillOnce() and
831 // WillRepeatedly() clauses) against the cardinality if this hasn't
832 // been done before. Prints a warning if there are too many or too
833 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000834 void CheckActionCountIfNotDone() const
835 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000836
shiqiane35fdd92008-12-10 05:08:54 +0000837 friend class ::testing::Sequence;
838 friend class ::testing::internal::ExpectationTester;
839
840 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000841 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000842
zhanyong.waned6c9272011-02-23 19:39:27 +0000843 // Implements the .Times() clause.
844 void UntypedTimes(const Cardinality& a_cardinality);
845
shiqiane35fdd92008-12-10 05:08:54 +0000846 // This group of fields are part of the spec and won't change after
847 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000848 const char* file_; // The file that contains the expectation.
849 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400850 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000851 // True iff the cardinality is specified explicitly.
852 bool cardinality_specified_;
853 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000854 // The immediate pre-requisites (i.e. expectations that must be
855 // satisfied before this expectation can be matched) of this
856 // expectation. We use linked_ptr in the set because we want an
857 // Expectation object to be co-owned by its FunctionMocker and its
858 // successors. This allows multiple mock objects to be deleted at
859 // different times.
860 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000861
862 // This group of fields are the current state of the expectation,
863 // and can change as the mock function is called.
864 int call_count_; // How many times this expectation has been invoked.
865 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000866 UntypedActions untyped_actions_;
867 bool extra_matcher_specified_;
868 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
869 bool retires_on_saturation_;
870 Clause last_clause_;
871 mutable bool action_count_checked_; // Under mutex_.
872 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000873
874 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000875}; // class ExpectationBase
876
877// Impements an expectation for the given function type.
878template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000879class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000880 public:
881 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
882 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
883 typedef typename Function<F>::Result Result;
884
Nico Weber09fd5b32017-05-15 17:07:03 -0400885 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
886 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000887 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000888 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000889 owner_(owner),
890 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000891 // By default, extra_matcher_ should match anything. However,
892 // we cannot initialize it with _ as that triggers a compiler
893 // bug in Symbian's C++ compiler (cannot decide between two
894 // overloaded constructors of Matcher<const ArgumentTuple&>).
895 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000896 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000897
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000898 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000899 // Check the validity of the action count if it hasn't been done
900 // yet (for example, if the expectation was never used).
901 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000902 for (UntypedActions::const_iterator it = untyped_actions_.begin();
903 it != untyped_actions_.end(); ++it) {
904 delete static_cast<const Action<F>*>(*it);
905 }
shiqiane35fdd92008-12-10 05:08:54 +0000906 }
907
zhanyong.wanbf550852009-06-09 06:09:53 +0000908 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000909 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000910 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000911 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000912 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000913 "more than once in an EXPECT_CALL().");
914 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000915 ExpectSpecProperty(last_clause_ < kWith,
916 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000917 "clause in an EXPECT_CALL().");
918 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000919 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000920
921 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000922 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000923 return *this;
924 }
925
926 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000927 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000928 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000929 return *this;
930 }
931
932 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000933 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000934 return Times(Exactly(n));
935 }
936
937 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000938 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000939 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000940 ".InSequence() cannot appear after .After(),"
941 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000942 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000943 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000944
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000945 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000946 return *this;
947 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000948 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000949 return InSequence(s1).InSequence(s2);
950 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000951 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
952 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000953 return InSequence(s1, s2).InSequence(s3);
954 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000955 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
956 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000957 return InSequence(s1, s2, s3).InSequence(s4);
958 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000959 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
960 const Sequence& s3, const Sequence& s4,
961 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000962 return InSequence(s1, s2, s3, s4).InSequence(s5);
963 }
964
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000965 // Implements that .After() clause.
966 TypedExpectation& After(const ExpectationSet& s) {
967 ExpectSpecProperty(last_clause_ <= kAfter,
968 ".After() cannot appear after .WillOnce(),"
969 " .WillRepeatedly(), or "
970 ".RetiresOnSaturation().");
971 last_clause_ = kAfter;
972
973 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
974 immediate_prerequisites_ += *it;
975 }
976 return *this;
977 }
978 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
979 return After(s1).After(s2);
980 }
981 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
982 const ExpectationSet& s3) {
983 return After(s1, s2).After(s3);
984 }
985 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
986 const ExpectationSet& s3, const ExpectationSet& s4) {
987 return After(s1, s2, s3).After(s4);
988 }
989 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
990 const ExpectationSet& s3, const ExpectationSet& s4,
991 const ExpectationSet& s5) {
992 return After(s1, s2, s3, s4).After(s5);
993 }
994
shiqiane35fdd92008-12-10 05:08:54 +0000995 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000996 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000997 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000998 ".WillOnce() cannot appear after "
999 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001000 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001001
zhanyong.waned6c9272011-02-23 19:39:27 +00001002 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001003 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001004 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001005 }
1006 return *this;
1007 }
1008
1009 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001010 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001011 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001012 ExpectSpecProperty(false,
1013 ".WillRepeatedly() cannot appear "
1014 "more than once in an EXPECT_CALL().");
1015 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001016 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001017 ".WillRepeatedly() cannot appear "
1018 "after .RetiresOnSaturation().");
1019 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001020 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001021 repeated_action_specified_ = true;
1022
1023 repeated_action_ = action;
1024 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001025 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001026 }
1027
1028 // Now that no more action clauses can be specified, we check
1029 // whether their count makes sense.
1030 CheckActionCountIfNotDone();
1031 return *this;
1032 }
1033
1034 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001035 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001036 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001037 ".RetiresOnSaturation() cannot appear "
1038 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001039 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001040 retires_on_saturation_ = true;
1041
1042 // Now that no more action clauses can be specified, we check
1043 // whether their count makes sense.
1044 CheckActionCountIfNotDone();
1045 return *this;
1046 }
1047
1048 // Returns the matchers for the arguments as specified inside the
1049 // EXPECT_CALL() macro.
1050 const ArgumentMatcherTuple& matchers() const {
1051 return matchers_;
1052 }
1053
zhanyong.wanbf550852009-06-09 06:09:53 +00001054 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001055 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1056 return extra_matcher_;
1057 }
1058
shiqiane35fdd92008-12-10 05:08:54 +00001059 // Returns the action specified by the .WillRepeatedly() clause.
1060 const Action<F>& repeated_action() const { return repeated_action_; }
1061
zhanyong.waned6c9272011-02-23 19:39:27 +00001062 // If this mock method has an extra matcher (i.e. .With(matcher)),
1063 // describes it to the ostream.
1064 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001065 if (extra_matcher_specified_) {
1066 *os << " Expected args: ";
1067 extra_matcher_.DescribeTo(os);
1068 *os << "\n";
1069 }
1070 }
1071
shiqiane35fdd92008-12-10 05:08:54 +00001072 private:
1073 template <typename Function>
1074 friend class FunctionMockerBase;
1075
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001076 // Returns an Expectation object that references and co-owns this
1077 // expectation.
1078 virtual Expectation GetHandle() {
1079 return owner_->GetHandleOf(this);
1080 }
1081
shiqiane35fdd92008-12-10 05:08:54 +00001082 // The following methods will be called only after the EXPECT_CALL()
1083 // statement finishes and when the current thread holds
1084 // g_gmock_mutex.
1085
1086 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001087 bool Matches(const ArgumentTuple& args) const
1088 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001089 g_gmock_mutex.AssertHeld();
1090 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1091 }
1092
1093 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001094 bool ShouldHandleArguments(const ArgumentTuple& args) const
1095 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001096 g_gmock_mutex.AssertHeld();
1097
1098 // In case the action count wasn't checked when the expectation
1099 // was defined (e.g. if this expectation has no WillRepeatedly()
1100 // or RetiresOnSaturation() clause), we check it when the
1101 // expectation is used for the first time.
1102 CheckActionCountIfNotDone();
1103 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1104 }
1105
1106 // Describes the result of matching the arguments against this
1107 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001108 void ExplainMatchResultTo(
1109 const ArgumentTuple& args,
1110 ::std::ostream* os) const
1111 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001112 g_gmock_mutex.AssertHeld();
1113
1114 if (is_retired()) {
1115 *os << " Expected: the expectation is active\n"
1116 << " Actual: it is retired\n";
1117 } else if (!Matches(args)) {
1118 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001119 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001120 }
zhanyong.wan82113312010-01-08 21:55:40 +00001121 StringMatchResultListener listener;
1122 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001123 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001124 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001125 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001126
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001127 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001128 *os << "\n";
1129 }
1130 } else if (!AllPrerequisitesAreSatisfied()) {
1131 *os << " Expected: all pre-requisites are satisfied\n"
1132 << " Actual: the following immediate pre-requisites "
1133 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001134 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001135 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1136 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001137 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001138 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001139 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001140 *os << "pre-requisite #" << i++ << "\n";
1141 }
1142 *os << " (end of pre-requisites)\n";
1143 } else {
1144 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001145 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001146 // is called only when the mock function call does NOT match the
1147 // expectation.
1148 *os << "The call matches the expectation.\n";
1149 }
1150 }
1151
1152 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001153 const Action<F>& GetCurrentAction(
1154 const FunctionMockerBase<F>* mocker,
1155 const ArgumentTuple& args) const
1156 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001157 g_gmock_mutex.AssertHeld();
1158 const int count = call_count();
1159 Assert(count >= 1, __FILE__, __LINE__,
1160 "call_count() is <= 0 when GetCurrentAction() is "
1161 "called - this should never happen.");
1162
zhanyong.waned6c9272011-02-23 19:39:27 +00001163 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001164 if (action_count > 0 && !repeated_action_specified_ &&
1165 count > action_count) {
1166 // If there is at least one WillOnce() and no WillRepeatedly(),
1167 // we warn the user when the WillOnce() clauses ran out.
1168 ::std::stringstream ss;
1169 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001170 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001171 << "Called " << count << " times, but only "
1172 << action_count << " WillOnce()"
1173 << (action_count == 1 ? " is" : "s are") << " specified - ";
1174 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001175 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001176 }
1177
zhanyong.waned6c9272011-02-23 19:39:27 +00001178 return count <= action_count ?
1179 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1180 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001181 }
1182
1183 // Given the arguments of a mock function call, if the call will
1184 // over-saturate this expectation, returns the default action;
1185 // otherwise, returns the next action in this expectation. Also
1186 // describes *what* happened to 'what', and explains *why* Google
1187 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001188 // IncrementCallCount(). A return value of NULL means the default
1189 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001190 const Action<F>* GetActionForArguments(
1191 const FunctionMockerBase<F>* mocker,
1192 const ArgumentTuple& args,
1193 ::std::ostream* what,
1194 ::std::ostream* why)
1195 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001196 g_gmock_mutex.AssertHeld();
1197 if (IsSaturated()) {
1198 // We have an excessive call.
1199 IncrementCallCount();
1200 *what << "Mock function called more times than expected - ";
1201 mocker->DescribeDefaultActionTo(args, what);
1202 DescribeCallCountTo(why);
1203
zhanyong.waned6c9272011-02-23 19:39:27 +00001204 // TODO(wan@google.com): allow the user to control whether
1205 // unexpected calls should fail immediately or continue using a
1206 // flag --gmock_unexpected_calls_are_fatal.
1207 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001208 }
1209
1210 IncrementCallCount();
1211 RetireAllPreRequisites();
1212
zhanyong.waned6c9272011-02-23 19:39:27 +00001213 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001214 Retire();
1215 }
1216
1217 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001218 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001219 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001220 }
1221
1222 // All the fields below won't change once the EXPECT_CALL()
1223 // statement finishes.
1224 FunctionMockerBase<F>* const owner_;
1225 ArgumentMatcherTuple matchers_;
1226 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001227 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001228
1229 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001230}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001231
1232// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1233// specifying the default behavior of, or expectation on, a mock
1234// function.
1235
1236// Note: class MockSpec really belongs to the ::testing namespace.
1237// However if we define it in ::testing, MSVC will complain when
1238// classes in ::testing::internal declare it as a friend class
1239// template. To workaround this compiler bug, we define MockSpec in
1240// ::testing::internal and import it into ::testing.
1241
zhanyong.waned6c9272011-02-23 19:39:27 +00001242// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001243GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1244 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001245 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001246
shiqiane35fdd92008-12-10 05:08:54 +00001247template <typename F>
1248class MockSpec {
1249 public:
1250 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1251 typedef typename internal::Function<F>::ArgumentMatcherTuple
1252 ArgumentMatcherTuple;
1253
1254 // Constructs a MockSpec object, given the function mocker object
1255 // that the spec is associated with.
1256 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1257 : function_mocker_(function_mocker) {}
1258
1259 // Adds a new default action spec to the function mocker and returns
1260 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001261 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001262 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001263 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001264 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001265 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001266 }
1267
1268 // Adds a new expectation spec to the function mocker and returns
1269 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001270 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001271 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001272 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1273 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001274 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001275 return function_mocker_->AddNewExpectation(
1276 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001277 }
1278
1279 private:
1280 template <typename Function>
1281 friend class internal::FunctionMocker;
1282
1283 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1284 matchers_ = matchers;
1285 }
1286
shiqiane35fdd92008-12-10 05:08:54 +00001287 // The function mocker that owns this spec.
1288 internal::FunctionMockerBase<F>* const function_mocker_;
1289 // The argument matchers specified in the spec.
1290 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001291
1292 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001293}; // class MockSpec
1294
kosakb5c81092014-01-29 06:41:44 +00001295// Wrapper type for generically holding an ordinary value or lvalue reference.
1296// If T is not a reference type, it must be copyable or movable.
1297// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1298// T is a move-only value type (which means that it will always be copyable
1299// if the current platform does not support move semantics).
1300//
1301// The primary template defines handling for values, but function header
1302// comments describe the contract for the whole template (including
1303// specializations).
1304template <typename T>
1305class ReferenceOrValueWrapper {
1306 public:
1307 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001308 explicit ReferenceOrValueWrapper(T value)
1309 : value_(::testing::internal::move(value)) {
1310 }
kosakb5c81092014-01-29 06:41:44 +00001311
1312 // Unwraps and returns the underlying value/reference, exactly as
1313 // originally passed. The behavior of calling this more than once on
1314 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001315 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001316
1317 // Provides nondestructive access to the underlying value/reference.
1318 // Always returns a const reference (more precisely,
1319 // const RemoveReference<T>&). The behavior of calling this after
1320 // calling Unwrap on the same object is unspecified.
1321 const T& Peek() const {
1322 return value_;
1323 }
1324
1325 private:
1326 T value_;
1327};
1328
1329// Specialization for lvalue reference types. See primary template
1330// for documentation.
1331template <typename T>
1332class ReferenceOrValueWrapper<T&> {
1333 public:
1334 // Workaround for debatable pass-by-reference lint warning (c-library-team
1335 // policy precludes NOLINT in this context)
1336 typedef T& reference;
1337 explicit ReferenceOrValueWrapper(reference ref)
1338 : value_ptr_(&ref) {}
1339 T& Unwrap() { return *value_ptr_; }
1340 const T& Peek() const { return *value_ptr_; }
1341
1342 private:
1343 T* value_ptr_;
1344};
1345
shiqiane35fdd92008-12-10 05:08:54 +00001346// MSVC warns about using 'this' in base member initializer list, so
1347// we need to temporarily disable the warning. We have to do it for
1348// the entire class to suppress the warning, even though it's about
1349// the constructor only.
1350
1351#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001352# pragma warning(push) // Saves the current warning state.
1353# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001354#endif // _MSV_VER
1355
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001356// C++ treats the void type specially. For example, you cannot define
1357// a void-typed variable or pass a void value to a function.
1358// ActionResultHolder<T> holds a value of type T, where T must be a
1359// copyable type or void (T doesn't need to be default-constructable).
1360// It hides the syntactic difference between void and other types, and
1361// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001362// non-void-returning mock functions.
1363
1364// Untyped base class for ActionResultHolder<T>.
1365class UntypedActionResultHolderBase {
1366 public:
1367 virtual ~UntypedActionResultHolderBase() {}
1368
1369 // Prints the held value as an action's result to os.
1370 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1371};
1372
1373// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001374template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001375class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001376 public:
kosakb5c81092014-01-29 06:41:44 +00001377 // Returns the held value. Must not be called more than once.
1378 T Unwrap() {
1379 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001380 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001381
1382 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001383 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001384 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001385 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001386 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001387 }
1388
1389 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001390 // result in a new-ed ActionResultHolder.
1391 template <typename F>
1392 static ActionResultHolder* PerformDefaultAction(
1393 const FunctionMockerBase<F>* func_mocker,
1394 const typename Function<F>::ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001395 const std::string& call_description) {
kosakb5c81092014-01-29 06:41:44 +00001396 return new ActionResultHolder(Wrapper(
1397 func_mocker->PerformDefaultAction(args, call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001398 }
1399
zhanyong.waned6c9272011-02-23 19:39:27 +00001400 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001401 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001402 template <typename F>
1403 static ActionResultHolder*
1404 PerformAction(const Action<F>& action,
1405 const typename Function<F>::ArgumentTuple& args) {
kosakb5c81092014-01-29 06:41:44 +00001406 return new ActionResultHolder(Wrapper(action.Perform(args)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001407 }
1408
1409 private:
kosakb5c81092014-01-29 06:41:44 +00001410 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001411
kosakd370f852014-11-17 01:14:16 +00001412 explicit ActionResultHolder(Wrapper result)
1413 : result_(::testing::internal::move(result)) {
1414 }
kosakb5c81092014-01-29 06:41:44 +00001415
1416 Wrapper result_;
1417
1418 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001419};
1420
1421// Specialization for T = void.
1422template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001423class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001424 public:
kosakb5c81092014-01-29 06:41:44 +00001425 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001426
zhanyong.waned6c9272011-02-23 19:39:27 +00001427 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1428
kosakb5c81092014-01-29 06:41:44 +00001429 // Performs the given mock function's default action and returns ownership
1430 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001431 template <typename F>
1432 static ActionResultHolder* PerformDefaultAction(
1433 const FunctionMockerBase<F>* func_mocker,
1434 const typename Function<F>::ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001435 const std::string& call_description) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001436 func_mocker->PerformDefaultAction(args, call_description);
kosakb5c81092014-01-29 06:41:44 +00001437 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001438 }
1439
kosakb5c81092014-01-29 06:41:44 +00001440 // Performs the given action and returns ownership of an empty
1441 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001442 template <typename F>
1443 static ActionResultHolder* PerformAction(
1444 const Action<F>& action,
1445 const typename Function<F>::ArgumentTuple& args) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001446 action.Perform(args);
kosakb5c81092014-01-29 06:41:44 +00001447 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001448 }
kosakb5c81092014-01-29 06:41:44 +00001449
1450 private:
1451 ActionResultHolder() {}
1452 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001453};
1454
shiqiane35fdd92008-12-10 05:08:54 +00001455// The base of the function mocker class for the given function type.
1456// We put the methods in this class instead of its child to avoid code
1457// bloat.
1458template <typename F>
1459class FunctionMockerBase : public UntypedFunctionMockerBase {
1460 public:
1461 typedef typename Function<F>::Result Result;
1462 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1463 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1464
zhanyong.waned6c9272011-02-23 19:39:27 +00001465 FunctionMockerBase() : current_spec_(this) {}
shiqiane35fdd92008-12-10 05:08:54 +00001466
1467 // The destructor verifies that all expectations on this mock
1468 // function have been satisfied. If not, it will report Google Test
1469 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001470 virtual ~FunctionMockerBase()
1471 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001472 MutexLock l(&g_gmock_mutex);
1473 VerifyAndClearExpectationsLocked();
1474 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001475 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001476 }
1477
1478 // Returns the ON_CALL spec that matches this mock function with the
1479 // given arguments; returns NULL if no matching ON_CALL is found.
1480 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001481 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001482 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001483 for (UntypedOnCallSpecs::const_reverse_iterator it
1484 = untyped_on_call_specs_.rbegin();
1485 it != untyped_on_call_specs_.rend(); ++it) {
1486 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1487 if (spec->Matches(args))
1488 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001489 }
1490
1491 return NULL;
1492 }
1493
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001494 // Performs the default action of this mock function on the given
1495 // arguments and returns the result. Asserts (or throws if
1496 // exceptions are enabled) with a helpful call descrption if there
1497 // is no valid return value. This method doesn't depend on the
1498 // mutable state of this object, and thus can be called concurrently
1499 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001500 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001501 Result PerformDefaultAction(const ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001502 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001503 const OnCallSpec<F>* const spec =
1504 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001505 if (spec != NULL) {
1506 return spec->GetAction().Perform(args);
1507 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001508 const std::string message =
1509 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001510 "\n The mock function has no default action "
1511 "set, and its return type has no default value set.";
1512#if GTEST_HAS_EXCEPTIONS
1513 if (!DefaultValue<Result>::Exists()) {
1514 throw std::runtime_error(message);
1515 }
1516#else
1517 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1518#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001519 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001520 }
1521
zhanyong.waned6c9272011-02-23 19:39:27 +00001522 // Performs the default action with the given arguments and returns
1523 // the action's result. The call description string will be used in
1524 // the error message to describe the call in the case the default
1525 // action fails. The caller is responsible for deleting the result.
1526 // L = *
1527 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1528 const void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001529 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001530 const ArgumentTuple& args =
1531 *static_cast<const ArgumentTuple*>(untyped_args);
1532 return ResultHolder::PerformDefaultAction(this, args, call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001533 }
1534
zhanyong.waned6c9272011-02-23 19:39:27 +00001535 // Performs the given action with the given arguments and returns
1536 // the action's result. The caller is responsible for deleting the
1537 // result.
1538 // L = *
1539 virtual UntypedActionResultHolderBase* UntypedPerformAction(
1540 const void* untyped_action, const void* untyped_args) const {
1541 // Make a copy of the action before performing it, in case the
1542 // action deletes the mock object (and thus deletes itself).
1543 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1544 const ArgumentTuple& args =
1545 *static_cast<const ArgumentTuple*>(untyped_args);
1546 return ResultHolder::PerformAction(action, args);
1547 }
shiqiane35fdd92008-12-10 05:08:54 +00001548
zhanyong.waned6c9272011-02-23 19:39:27 +00001549 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1550 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001551 virtual void ClearDefaultActionsLocked()
1552 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001553 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001554
1555 // Deleting our default actions may trigger other mock objects to be
1556 // deleted, for example if an action contains a reference counted smart
1557 // pointer to that mock object, and that is the last reference. So if we
1558 // delete our actions within the context of the global mutex we may deadlock
1559 // when this method is called again. Instead, make a copy of the set of
1560 // actions to delete, clear our set within the mutex, and then delete the
1561 // actions outside of the mutex.
1562 UntypedOnCallSpecs specs_to_delete;
1563 untyped_on_call_specs_.swap(specs_to_delete);
1564
1565 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001566 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001567 specs_to_delete.begin();
1568 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001569 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001570 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001571
1572 // Lock the mutex again, since the caller expects it to be locked when we
1573 // return.
1574 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001575 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001576
shiqiane35fdd92008-12-10 05:08:54 +00001577 protected:
1578 template <typename Function>
1579 friend class MockSpec;
1580
zhanyong.waned6c9272011-02-23 19:39:27 +00001581 typedef ActionResultHolder<Result> ResultHolder;
1582
shiqiane35fdd92008-12-10 05:08:54 +00001583 // Returns the result of invoking this mock function with the given
1584 // arguments. This function can be safely called from multiple
1585 // threads concurrently.
vladlosev4d60a592011-10-24 21:16:22 +00001586 Result InvokeWith(const ArgumentTuple& args)
1587 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
kosakb5c81092014-01-29 06:41:44 +00001588 scoped_ptr<ResultHolder> holder(
1589 DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args)));
1590 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001591 }
shiqiane35fdd92008-12-10 05:08:54 +00001592
1593 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001594 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001595 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001596 const ArgumentMatcherTuple& m)
1597 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001598 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001599 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1600 untyped_on_call_specs_.push_back(on_call_spec);
1601 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001602 }
1603
1604 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001605 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1606 const std::string& source_text,
1607 const ArgumentMatcherTuple& m)
1608 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001609 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001610 TypedExpectation<F>* const expectation =
1611 new TypedExpectation<F>(this, file, line, source_text, m);
1612 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1613 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001614
1615 // Adds this expectation into the implicit sequence if there is one.
1616 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1617 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001618 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001619 }
1620
1621 return *expectation;
1622 }
1623
1624 // The current spec (either default action spec or expectation spec)
1625 // being described on this function mocker.
1626 MockSpec<F>& current_spec() { return current_spec_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001627
shiqiane35fdd92008-12-10 05:08:54 +00001628 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001629 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001630
zhanyong.waned6c9272011-02-23 19:39:27 +00001631 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001632
1633 // Describes what default action will be performed for the given
1634 // arguments.
1635 // L = *
1636 void DescribeDefaultActionTo(const ArgumentTuple& args,
1637 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001638 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001639
1640 if (spec == NULL) {
1641 *os << (internal::type_equals<Result, void>::value ?
1642 "returning directly.\n" :
1643 "returning default value.\n");
1644 } else {
1645 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001646 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001647 }
1648 }
1649
1650 // Writes a message that the call is uninteresting (i.e. neither
1651 // explicitly expected nor explicitly unexpected) to the given
1652 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001653 virtual void UntypedDescribeUninterestingCall(
1654 const void* untyped_args,
1655 ::std::ostream* os) const
1656 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001657 const ArgumentTuple& args =
1658 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001659 *os << "Uninteresting mock function call - ";
1660 DescribeDefaultActionTo(args, os);
1661 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001662 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001663 }
1664
zhanyong.waned6c9272011-02-23 19:39:27 +00001665 // Returns the expectation that matches the given function arguments
1666 // (or NULL is there's no match); when a match is found,
1667 // untyped_action is set to point to the action that should be
1668 // performed (or NULL if the action is "do default"), and
1669 // is_excessive is modified to indicate whether the call exceeds the
1670 // expected number.
1671 //
shiqiane35fdd92008-12-10 05:08:54 +00001672 // Critical section: We must find the matching expectation and the
1673 // corresponding action that needs to be taken in an ATOMIC
1674 // transaction. Otherwise another thread may call this mock
1675 // method in the middle and mess up the state.
1676 //
1677 // However, performing the action has to be left out of the critical
1678 // section. The reason is that we have no control on what the
1679 // action does (it can invoke an arbitrary user function or even a
1680 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001681 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1682 const void* untyped_args,
1683 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001684 ::std::ostream* what, ::std::ostream* why)
1685 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001686 const ArgumentTuple& args =
1687 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001688 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001689 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1690 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001691 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001692 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001693 }
1694
1695 // This line must be done before calling GetActionForArguments(),
1696 // which will increment the call count for *exp and thus affect
1697 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001698 *is_excessive = exp->IsSaturated();
1699 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1700 if (action != NULL && action->IsDoDefault())
1701 action = NULL; // Normalize "do default" to NULL.
1702 *untyped_action = action;
1703 return exp;
1704 }
1705
1706 // Prints the given function arguments to the ostream.
1707 virtual void UntypedPrintArgs(const void* untyped_args,
1708 ::std::ostream* os) const {
1709 const ArgumentTuple& args =
1710 *static_cast<const ArgumentTuple*>(untyped_args);
1711 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001712 }
1713
1714 // Returns the expectation that matches the arguments, or NULL if no
1715 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001716 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001717 const ArgumentTuple& args) const
1718 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001719 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001720 for (typename UntypedExpectations::const_reverse_iterator it =
1721 untyped_expectations_.rbegin();
1722 it != untyped_expectations_.rend(); ++it) {
1723 TypedExpectation<F>* const exp =
1724 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001725 if (exp->ShouldHandleArguments(args)) {
1726 return exp;
1727 }
1728 }
1729 return NULL;
1730 }
1731
1732 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001733 void FormatUnexpectedCallMessageLocked(
1734 const ArgumentTuple& args,
1735 ::std::ostream* os,
1736 ::std::ostream* why) const
1737 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001738 g_gmock_mutex.AssertHeld();
1739 *os << "\nUnexpected mock function call - ";
1740 DescribeDefaultActionTo(args, os);
1741 PrintTriedExpectationsLocked(args, why);
1742 }
1743
1744 // Prints a list of expectations that have been tried against the
1745 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001746 void PrintTriedExpectationsLocked(
1747 const ArgumentTuple& args,
1748 ::std::ostream* why) const
1749 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001750 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001751 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001752 *why << "Google Mock tried the following " << count << " "
1753 << (count == 1 ? "expectation, but it didn't match" :
1754 "expectations, but none matched")
1755 << ":\n";
1756 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001757 TypedExpectation<F>* const expectation =
1758 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001759 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001760 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001761 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001762 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001763 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001764 *why << expectation->source_text() << "...\n";
1765 expectation->ExplainMatchResultTo(args, why);
1766 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001767 }
1768 }
1769
shiqiane35fdd92008-12-10 05:08:54 +00001770 // The current spec (either default action spec or expectation spec)
1771 // being described on this function mocker.
1772 MockSpec<F> current_spec_;
1773
zhanyong.wan16cf4732009-05-14 20:55:30 +00001774 // There is no generally useful and implementable semantics of
1775 // copying a mock object, so copying a mock is usually a user error.
1776 // Thus we disallow copying function mockers. If the user really
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +01001777 // wants to copy a mock object, they should implement their own copy
zhanyong.wan16cf4732009-05-14 20:55:30 +00001778 // operation, for example:
1779 //
1780 // class MockFoo : public Foo {
1781 // public:
1782 // // Defines a copy constructor explicitly.
1783 // MockFoo(const MockFoo& src) {}
1784 // ...
1785 // };
1786 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001787}; // class FunctionMockerBase
1788
1789#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001790# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001791#endif // _MSV_VER
1792
1793// Implements methods of FunctionMockerBase.
1794
1795// Verifies that all expectations on this mock function have been
1796// satisfied. Reports one or more Google Test non-fatal failures and
1797// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001798
1799// Reports an uninteresting call (whose description is in msg) in the
1800// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001801void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001802
shiqiane35fdd92008-12-10 05:08:54 +00001803} // namespace internal
1804
1805// The style guide prohibits "using" statements in a namespace scope
1806// inside a header file. However, the MockSpec class template is
1807// meant to be defined in the ::testing namespace. The following line
1808// is just a trick for working around a bug in MSVC 8.0, which cannot
1809// handle it if we define MockSpec in ::testing.
1810using internal::MockSpec;
1811
1812// Const(x) is a convenient function for obtaining a const reference
1813// to x. This is useful for setting expectations on an overloaded
1814// const mock method, e.g.
1815//
1816// class MockFoo : public FooInterface {
1817// public:
1818// MOCK_METHOD0(Bar, int());
1819// MOCK_CONST_METHOD0(Bar, int&());
1820// };
1821//
1822// MockFoo foo;
1823// // Expects a call to non-const MockFoo::Bar().
1824// EXPECT_CALL(foo, Bar());
1825// // Expects a call to const MockFoo::Bar().
1826// EXPECT_CALL(Const(foo), Bar());
1827template <typename T>
1828inline const T& Const(const T& x) { return x; }
1829
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001830// Constructs an Expectation object that references and co-owns exp.
1831inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1832 : expectation_base_(exp.GetHandle().expectation_base()) {}
1833
shiqiane35fdd92008-12-10 05:08:54 +00001834} // namespace testing
1835
1836// A separate macro is required to avoid compile errors when the name
1837// of the method used in call is a result of macro expansion.
1838// See CompilesWithMethodNameExpandedFromMacro tests in
1839// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001840#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001841 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1842 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001843#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001844
zhanyong.wane0d051e2009-02-19 00:33:37 +00001845#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001846 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001847#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001848
1849#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_