blob: 39f72129d65f0d7ce277bb779c94189edbce3965 [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,
366 kDefault = kWarn // By default, warn about uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000367};
368
369} // namespace internal
370
371// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000372class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000373 public:
374 // The following public methods can be called concurrently.
375
zhanyong.wandf35a762009-04-22 22:25:31 +0000376 // Tells Google Mock to ignore mock_obj when checking for leaked
377 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000378 static void AllowLeak(const void* mock_obj)
379 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000380
shiqiane35fdd92008-12-10 05:08:54 +0000381 // Verifies and clears all expectations on the given mock object.
382 // If the expectations aren't satisfied, generates one or more
383 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000384 static bool VerifyAndClearExpectations(void* mock_obj)
385 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000386
387 // Verifies all expectations on the given mock object and clears its
388 // default actions and expectations. Returns true iff the
389 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000390 static bool VerifyAndClear(void* mock_obj)
391 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000392
shiqiane35fdd92008-12-10 05:08:54 +0000393 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000394 friend class internal::UntypedFunctionMockerBase;
395
shiqiane35fdd92008-12-10 05:08:54 +0000396 // Needed for a function mocker to register itself (so that we know
397 // how to clear a mock object).
398 template <typename F>
399 friend class internal::FunctionMockerBase;
400
shiqiane35fdd92008-12-10 05:08:54 +0000401 template <typename M>
402 friend class NiceMock;
403
404 template <typename M>
zhanyong.wan844fa942013-03-01 01:54:22 +0000405 friend class NaggyMock;
406
407 template <typename M>
shiqiane35fdd92008-12-10 05:08:54 +0000408 friend class StrictMock;
409
410 // Tells Google Mock to allow uninteresting calls on the given mock
411 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000412 static void AllowUninterestingCalls(const void* mock_obj)
413 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000414
415 // Tells Google Mock to warn the user about uninteresting calls on
416 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000417 static void WarnUninterestingCalls(const void* mock_obj)
418 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000419
420 // Tells Google Mock to fail uninteresting calls on the given mock
421 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000422 static void FailUninterestingCalls(const void* mock_obj)
423 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000424
425 // Tells Google Mock the given mock object is being destroyed and
426 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000427 static void UnregisterCallReaction(const void* mock_obj)
428 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000429
430 // Returns the reaction Google Mock will have on uninteresting calls
431 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000432 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000433 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000434 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000435
436 // Verifies that all expectations on the given mock object have been
437 // satisfied. Reports one or more Google Test non-fatal failures
438 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000439 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
440 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000441
442 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000443 static void ClearDefaultActionsLocked(void* mock_obj)
444 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000445
446 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000447 static void Register(
448 const void* mock_obj,
449 internal::UntypedFunctionMockerBase* mocker)
450 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000451
zhanyong.wandf35a762009-04-22 22:25:31 +0000452 // Tells Google Mock where in the source code mock_obj is used in an
453 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
454 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000455 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000456 const void* mock_obj, const char* file, int line)
457 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000458
shiqiane35fdd92008-12-10 05:08:54 +0000459 // Unregisters a mock method; removes the owning mock object from
460 // the registry when the last mock method associated with it has
461 // been unregistered. This is called only in the destructor of
462 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000463 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
464 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000465}; // class Mock
466
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000467// An abstract handle of an expectation. Useful in the .After()
468// clause of EXPECT_CALL() for setting the (partial) order of
469// expectations. The syntax:
470//
471// Expectation e1 = EXPECT_CALL(...)...;
472// EXPECT_CALL(...).After(e1)...;
473//
474// sets two expectations where the latter can only be matched after
475// the former has been satisfied.
476//
477// Notes:
478// - This class is copyable and has value semantics.
479// - Constness is shallow: a const Expectation object itself cannot
480// be modified, but the mutable methods of the ExpectationBase
481// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000482// - The constructors and destructor are defined out-of-line because
483// the Symbian WINSCW compiler wants to otherwise instantiate them
484// when it sees this class definition, at which point it doesn't have
485// ExpectationBase available yet, leading to incorrect destruction
486// in the linked_ptr (or compilation errors if using a checking
487// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000488class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000489 public:
490 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000491 Expectation();
492
493 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000494
495 // This single-argument ctor must not be explicit, in order to support the
496 // Expectation e = EXPECT_CALL(...);
497 // syntax.
498 //
499 // A TypedExpectation object stores its pre-requisites as
500 // Expectation objects, and needs to call the non-const Retire()
501 // method on the ExpectationBase objects they reference. Therefore
502 // Expectation must receive a *non-const* reference to the
503 // ExpectationBase object.
504 Expectation(internal::ExpectationBase& exp); // NOLINT
505
506 // The compiler-generated copy ctor and operator= work exactly as
507 // intended, so we don't need to define our own.
508
509 // Returns true iff rhs references the same expectation as this object does.
510 bool operator==(const Expectation& rhs) const {
511 return expectation_base_ == rhs.expectation_base_;
512 }
513
514 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
515
516 private:
517 friend class ExpectationSet;
518 friend class Sequence;
519 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000520 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000521
522 template <typename F>
523 friend class ::testing::internal::FunctionMockerBase;
524
525 template <typename F>
526 friend class ::testing::internal::TypedExpectation;
527
528 // This comparator is needed for putting Expectation objects into a set.
529 class Less {
530 public:
531 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
532 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
533 }
534 };
535
536 typedef ::std::set<Expectation, Less> Set;
537
538 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000539 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000540
541 // Returns the expectation this object references.
542 const internal::linked_ptr<internal::ExpectationBase>&
543 expectation_base() const {
544 return expectation_base_;
545 }
546
547 // A linked_ptr that co-owns the expectation this handle references.
548 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
549};
550
551// A set of expectation handles. Useful in the .After() clause of
552// EXPECT_CALL() for setting the (partial) order of expectations. The
553// syntax:
554//
555// ExpectationSet es;
556// es += EXPECT_CALL(...)...;
557// es += EXPECT_CALL(...)...;
558// EXPECT_CALL(...).After(es)...;
559//
560// sets three expectations where the last one can only be matched
561// after the first two have both been satisfied.
562//
563// This class is copyable and has value semantics.
564class ExpectationSet {
565 public:
566 // A bidirectional iterator that can read a const element in the set.
567 typedef Expectation::Set::const_iterator const_iterator;
568
569 // An object stored in the set. This is an alias of Expectation.
570 typedef Expectation::Set::value_type value_type;
571
572 // Constructs an empty set.
573 ExpectationSet() {}
574
575 // This single-argument ctor must not be explicit, in order to support the
576 // ExpectationSet es = EXPECT_CALL(...);
577 // syntax.
578 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
579 *this += Expectation(exp);
580 }
581
582 // This single-argument ctor implements implicit conversion from
583 // Expectation and thus must not be explicit. This allows either an
584 // Expectation or an ExpectationSet to be used in .After().
585 ExpectationSet(const Expectation& e) { // NOLINT
586 *this += e;
587 }
588
589 // The compiler-generator ctor and operator= works exactly as
590 // intended, so we don't need to define our own.
591
592 // Returns true iff rhs contains the same set of Expectation objects
593 // as this does.
594 bool operator==(const ExpectationSet& rhs) const {
595 return expectations_ == rhs.expectations_;
596 }
597
598 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
599
600 // Implements the syntax
601 // expectation_set += EXPECT_CALL(...);
602 ExpectationSet& operator+=(const Expectation& e) {
603 expectations_.insert(e);
604 return *this;
605 }
606
607 int size() const { return static_cast<int>(expectations_.size()); }
608
609 const_iterator begin() const { return expectations_.begin(); }
610 const_iterator end() const { return expectations_.end(); }
611
612 private:
613 Expectation::Set expectations_;
614};
615
616
shiqiane35fdd92008-12-10 05:08:54 +0000617// Sequence objects are used by a user to specify the relative order
618// in which the expectations should match. They are copyable (we rely
619// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000620class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000621 public:
622 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000623 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000624
625 // Adds an expectation to this sequence. The caller must ensure
626 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000627 void AddExpectation(const Expectation& expectation) const;
628
shiqiane35fdd92008-12-10 05:08:54 +0000629 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000630 // The last expectation in this sequence. We use a linked_ptr here
631 // because Sequence objects are copyable and we want the copies to
632 // be aliases. The linked_ptr allows the copies to co-own and share
633 // the same Expectation object.
634 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000635}; // class Sequence
636
637// An object of this type causes all EXPECT_CALL() statements
638// encountered in its scope to be put in an anonymous sequence. The
639// work is done in the constructor and destructor. You should only
640// create an InSequence object on the stack.
641//
642// The sole purpose for this class is to support easy definition of
643// sequential expectations, e.g.
644//
645// {
646// InSequence dummy; // The name of the object doesn't matter.
647//
648// // The following expectations must match in the order they appear.
649// EXPECT_CALL(a, Bar())...;
650// EXPECT_CALL(a, Baz())...;
651// ...
652// EXPECT_CALL(b, Xyz())...;
653// }
654//
655// You can create InSequence objects in multiple threads, as long as
656// they are used to affect different mock objects. The idea is that
657// each thread can create and set up its own mocks as if it's the only
658// thread. However, for clarity of your tests we recommend you to set
659// up mocks in the main thread unless you have a good reason not to do
660// so.
vladlosev587c1b32011-05-20 00:42:22 +0000661class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000662 public:
663 InSequence();
664 ~InSequence();
665 private:
666 bool sequence_created_;
667
668 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000669} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000670
671namespace internal {
672
673// Points to the implicit sequence introduced by a living InSequence
674// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000675GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000676
677// Base class for implementing expectations.
678//
679// There are two reasons for having a type-agnostic base class for
680// Expectation:
681//
682// 1. We need to store collections of expectations of different
683// types (e.g. all pre-requisites of a particular expectation, all
684// expectations in a sequence). Therefore these expectation objects
685// must share a common base class.
686//
687// 2. We can avoid binary code bloat by moving methods not depending
688// on the template argument of Expectation to the base class.
689//
690// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000691class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000692 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000693 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400694 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000695
696 virtual ~ExpectationBase();
697
698 // Where in the source file was the expectation spec defined?
699 const char* file() const { return file_; }
700 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000701 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000702 // Returns the cardinality specified in the expectation spec.
703 const Cardinality& cardinality() const { return cardinality_; }
704
705 // Describes the source file location of this expectation.
706 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000707 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000708 }
709
710 // Describes how many times a function call matching this
711 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000712 void DescribeCallCountTo(::std::ostream* os) const
713 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000714
715 // If this mock method has an extra matcher (i.e. .With(matcher)),
716 // describes it to the ostream.
717 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000718
shiqiane35fdd92008-12-10 05:08:54 +0000719 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000720 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000721 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000722
723 enum Clause {
724 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000725 kNone,
726 kWith,
727 kTimes,
728 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000729 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000730 kWillOnce,
731 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000732 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000733 };
734
zhanyong.waned6c9272011-02-23 19:39:27 +0000735 typedef std::vector<const void*> UntypedActions;
736
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000737 // Returns an Expectation object that references and co-owns this
738 // expectation.
739 virtual Expectation GetHandle() = 0;
740
shiqiane35fdd92008-12-10 05:08:54 +0000741 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400742 void AssertSpecProperty(bool property,
743 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000744 Assert(property, file_, line_, failure_message);
745 }
746
747 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400748 void ExpectSpecProperty(bool property,
749 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000750 Expect(property, file_, line_, failure_message);
751 }
752
753 // Explicitly specifies the cardinality of this expectation. Used
754 // by the subclasses to implement the .Times() clause.
755 void SpecifyCardinality(const Cardinality& cardinality);
756
757 // Returns true iff the user specified the cardinality explicitly
758 // using a .Times().
759 bool cardinality_specified() const { return cardinality_specified_; }
760
761 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000762 void set_cardinality(const Cardinality& a_cardinality) {
763 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000764 }
765
766 // The following group of methods should only be called after the
767 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
768 // the current thread.
769
770 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000771 void RetireAllPreRequisites()
772 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000773
774 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000775 bool is_retired() const
776 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000777 g_gmock_mutex.AssertHeld();
778 return retired_;
779 }
780
781 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000782 void Retire()
783 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000784 g_gmock_mutex.AssertHeld();
785 retired_ = true;
786 }
787
788 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000789 bool IsSatisfied() const
790 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000791 g_gmock_mutex.AssertHeld();
792 return cardinality().IsSatisfiedByCallCount(call_count_);
793 }
794
795 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000796 bool IsSaturated() const
797 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000798 g_gmock_mutex.AssertHeld();
799 return cardinality().IsSaturatedByCallCount(call_count_);
800 }
801
802 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000803 bool IsOverSaturated() const
804 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000805 g_gmock_mutex.AssertHeld();
806 return cardinality().IsOverSaturatedByCallCount(call_count_);
807 }
808
809 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000810 bool AllPrerequisitesAreSatisfied() const
811 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000812
813 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000814 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
815 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000816
817 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000818 int call_count() const
819 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000820 g_gmock_mutex.AssertHeld();
821 return call_count_;
822 }
823
824 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000825 void IncrementCallCount()
826 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000827 g_gmock_mutex.AssertHeld();
828 call_count_++;
829 }
830
zhanyong.waned6c9272011-02-23 19:39:27 +0000831 // Checks the action count (i.e. the number of WillOnce() and
832 // WillRepeatedly() clauses) against the cardinality if this hasn't
833 // been done before. Prints a warning if there are too many or too
834 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000835 void CheckActionCountIfNotDone() const
836 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000837
shiqiane35fdd92008-12-10 05:08:54 +0000838 friend class ::testing::Sequence;
839 friend class ::testing::internal::ExpectationTester;
840
841 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000842 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000843
zhanyong.waned6c9272011-02-23 19:39:27 +0000844 // Implements the .Times() clause.
845 void UntypedTimes(const Cardinality& a_cardinality);
846
shiqiane35fdd92008-12-10 05:08:54 +0000847 // This group of fields are part of the spec and won't change after
848 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000849 const char* file_; // The file that contains the expectation.
850 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400851 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000852 // True iff the cardinality is specified explicitly.
853 bool cardinality_specified_;
854 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000855 // The immediate pre-requisites (i.e. expectations that must be
856 // satisfied before this expectation can be matched) of this
857 // expectation. We use linked_ptr in the set because we want an
858 // Expectation object to be co-owned by its FunctionMocker and its
859 // successors. This allows multiple mock objects to be deleted at
860 // different times.
861 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000862
863 // This group of fields are the current state of the expectation,
864 // and can change as the mock function is called.
865 int call_count_; // How many times this expectation has been invoked.
866 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000867 UntypedActions untyped_actions_;
868 bool extra_matcher_specified_;
869 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
870 bool retires_on_saturation_;
871 Clause last_clause_;
872 mutable bool action_count_checked_; // Under mutex_.
873 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000874
875 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000876}; // class ExpectationBase
877
878// Impements an expectation for the given function type.
879template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000880class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000881 public:
882 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
883 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
884 typedef typename Function<F>::Result Result;
885
Nico Weber09fd5b32017-05-15 17:07:03 -0400886 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
887 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000888 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000889 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000890 owner_(owner),
891 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000892 // By default, extra_matcher_ should match anything. However,
893 // we cannot initialize it with _ as that triggers a compiler
894 // bug in Symbian's C++ compiler (cannot decide between two
895 // overloaded constructors of Matcher<const ArgumentTuple&>).
896 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000897 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000898
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000899 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000900 // Check the validity of the action count if it hasn't been done
901 // yet (for example, if the expectation was never used).
902 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000903 for (UntypedActions::const_iterator it = untyped_actions_.begin();
904 it != untyped_actions_.end(); ++it) {
905 delete static_cast<const Action<F>*>(*it);
906 }
shiqiane35fdd92008-12-10 05:08:54 +0000907 }
908
zhanyong.wanbf550852009-06-09 06:09:53 +0000909 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000910 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000911 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000912 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000913 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000914 "more than once in an EXPECT_CALL().");
915 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000916 ExpectSpecProperty(last_clause_ < kWith,
917 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000918 "clause in an EXPECT_CALL().");
919 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000920 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000921
922 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000923 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000924 return *this;
925 }
926
927 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000928 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000929 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000930 return *this;
931 }
932
933 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000934 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000935 return Times(Exactly(n));
936 }
937
938 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000939 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000940 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000941 ".InSequence() cannot appear after .After(),"
942 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000943 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000944 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000945
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000946 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000947 return *this;
948 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000949 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000950 return InSequence(s1).InSequence(s2);
951 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000952 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
953 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000954 return InSequence(s1, s2).InSequence(s3);
955 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000956 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
957 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000958 return InSequence(s1, s2, s3).InSequence(s4);
959 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000960 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
961 const Sequence& s3, const Sequence& s4,
962 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000963 return InSequence(s1, s2, s3, s4).InSequence(s5);
964 }
965
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000966 // Implements that .After() clause.
967 TypedExpectation& After(const ExpectationSet& s) {
968 ExpectSpecProperty(last_clause_ <= kAfter,
969 ".After() cannot appear after .WillOnce(),"
970 " .WillRepeatedly(), or "
971 ".RetiresOnSaturation().");
972 last_clause_ = kAfter;
973
974 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
975 immediate_prerequisites_ += *it;
976 }
977 return *this;
978 }
979 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
980 return After(s1).After(s2);
981 }
982 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
983 const ExpectationSet& s3) {
984 return After(s1, s2).After(s3);
985 }
986 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
987 const ExpectationSet& s3, const ExpectationSet& s4) {
988 return After(s1, s2, s3).After(s4);
989 }
990 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
991 const ExpectationSet& s3, const ExpectationSet& s4,
992 const ExpectationSet& s5) {
993 return After(s1, s2, s3, s4).After(s5);
994 }
995
shiqiane35fdd92008-12-10 05:08:54 +0000996 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000997 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000998 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000999 ".WillOnce() cannot appear after "
1000 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001001 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001002
zhanyong.waned6c9272011-02-23 19:39:27 +00001003 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001004 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001005 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001006 }
1007 return *this;
1008 }
1009
1010 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001011 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001012 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001013 ExpectSpecProperty(false,
1014 ".WillRepeatedly() cannot appear "
1015 "more than once in an EXPECT_CALL().");
1016 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001017 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001018 ".WillRepeatedly() cannot appear "
1019 "after .RetiresOnSaturation().");
1020 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001021 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001022 repeated_action_specified_ = true;
1023
1024 repeated_action_ = action;
1025 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001026 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001027 }
1028
1029 // Now that no more action clauses can be specified, we check
1030 // whether their count makes sense.
1031 CheckActionCountIfNotDone();
1032 return *this;
1033 }
1034
1035 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001036 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001037 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001038 ".RetiresOnSaturation() cannot appear "
1039 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001040 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001041 retires_on_saturation_ = true;
1042
1043 // Now that no more action clauses can be specified, we check
1044 // whether their count makes sense.
1045 CheckActionCountIfNotDone();
1046 return *this;
1047 }
1048
1049 // Returns the matchers for the arguments as specified inside the
1050 // EXPECT_CALL() macro.
1051 const ArgumentMatcherTuple& matchers() const {
1052 return matchers_;
1053 }
1054
zhanyong.wanbf550852009-06-09 06:09:53 +00001055 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001056 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1057 return extra_matcher_;
1058 }
1059
shiqiane35fdd92008-12-10 05:08:54 +00001060 // Returns the action specified by the .WillRepeatedly() clause.
1061 const Action<F>& repeated_action() const { return repeated_action_; }
1062
zhanyong.waned6c9272011-02-23 19:39:27 +00001063 // If this mock method has an extra matcher (i.e. .With(matcher)),
1064 // describes it to the ostream.
1065 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001066 if (extra_matcher_specified_) {
1067 *os << " Expected args: ";
1068 extra_matcher_.DescribeTo(os);
1069 *os << "\n";
1070 }
1071 }
1072
shiqiane35fdd92008-12-10 05:08:54 +00001073 private:
1074 template <typename Function>
1075 friend class FunctionMockerBase;
1076
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001077 // Returns an Expectation object that references and co-owns this
1078 // expectation.
1079 virtual Expectation GetHandle() {
1080 return owner_->GetHandleOf(this);
1081 }
1082
shiqiane35fdd92008-12-10 05:08:54 +00001083 // The following methods will be called only after the EXPECT_CALL()
1084 // statement finishes and when the current thread holds
1085 // g_gmock_mutex.
1086
1087 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001088 bool Matches(const ArgumentTuple& args) const
1089 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001090 g_gmock_mutex.AssertHeld();
1091 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1092 }
1093
1094 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001095 bool ShouldHandleArguments(const ArgumentTuple& args) const
1096 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001097 g_gmock_mutex.AssertHeld();
1098
1099 // In case the action count wasn't checked when the expectation
1100 // was defined (e.g. if this expectation has no WillRepeatedly()
1101 // or RetiresOnSaturation() clause), we check it when the
1102 // expectation is used for the first time.
1103 CheckActionCountIfNotDone();
1104 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1105 }
1106
1107 // Describes the result of matching the arguments against this
1108 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001109 void ExplainMatchResultTo(
1110 const ArgumentTuple& args,
1111 ::std::ostream* os) const
1112 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001113 g_gmock_mutex.AssertHeld();
1114
1115 if (is_retired()) {
1116 *os << " Expected: the expectation is active\n"
1117 << " Actual: it is retired\n";
1118 } else if (!Matches(args)) {
1119 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001120 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001121 }
zhanyong.wan82113312010-01-08 21:55:40 +00001122 StringMatchResultListener listener;
1123 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001124 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001125 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001126 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001127
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001128 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001129 *os << "\n";
1130 }
1131 } else if (!AllPrerequisitesAreSatisfied()) {
1132 *os << " Expected: all pre-requisites are satisfied\n"
1133 << " Actual: the following immediate pre-requisites "
1134 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001135 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001136 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1137 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001138 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001139 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001140 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001141 *os << "pre-requisite #" << i++ << "\n";
1142 }
1143 *os << " (end of pre-requisites)\n";
1144 } else {
1145 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001146 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001147 // is called only when the mock function call does NOT match the
1148 // expectation.
1149 *os << "The call matches the expectation.\n";
1150 }
1151 }
1152
1153 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001154 const Action<F>& GetCurrentAction(
1155 const FunctionMockerBase<F>* mocker,
1156 const ArgumentTuple& args) const
1157 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001158 g_gmock_mutex.AssertHeld();
1159 const int count = call_count();
1160 Assert(count >= 1, __FILE__, __LINE__,
1161 "call_count() is <= 0 when GetCurrentAction() is "
1162 "called - this should never happen.");
1163
zhanyong.waned6c9272011-02-23 19:39:27 +00001164 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001165 if (action_count > 0 && !repeated_action_specified_ &&
1166 count > action_count) {
1167 // If there is at least one WillOnce() and no WillRepeatedly(),
1168 // we warn the user when the WillOnce() clauses ran out.
1169 ::std::stringstream ss;
1170 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001171 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001172 << "Called " << count << " times, but only "
1173 << action_count << " WillOnce()"
1174 << (action_count == 1 ? " is" : "s are") << " specified - ";
1175 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001176 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001177 }
1178
zhanyong.waned6c9272011-02-23 19:39:27 +00001179 return count <= action_count ?
1180 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1181 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001182 }
1183
1184 // Given the arguments of a mock function call, if the call will
1185 // over-saturate this expectation, returns the default action;
1186 // otherwise, returns the next action in this expectation. Also
1187 // describes *what* happened to 'what', and explains *why* Google
1188 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001189 // IncrementCallCount(). A return value of NULL means the default
1190 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001191 const Action<F>* GetActionForArguments(
1192 const FunctionMockerBase<F>* mocker,
1193 const ArgumentTuple& args,
1194 ::std::ostream* what,
1195 ::std::ostream* why)
1196 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001197 g_gmock_mutex.AssertHeld();
1198 if (IsSaturated()) {
1199 // We have an excessive call.
1200 IncrementCallCount();
1201 *what << "Mock function called more times than expected - ";
1202 mocker->DescribeDefaultActionTo(args, what);
1203 DescribeCallCountTo(why);
1204
zhanyong.waned6c9272011-02-23 19:39:27 +00001205 // TODO(wan@google.com): allow the user to control whether
1206 // unexpected calls should fail immediately or continue using a
1207 // flag --gmock_unexpected_calls_are_fatal.
1208 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001209 }
1210
1211 IncrementCallCount();
1212 RetireAllPreRequisites();
1213
zhanyong.waned6c9272011-02-23 19:39:27 +00001214 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001215 Retire();
1216 }
1217
1218 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001219 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001220 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001221 }
1222
1223 // All the fields below won't change once the EXPECT_CALL()
1224 // statement finishes.
1225 FunctionMockerBase<F>* const owner_;
1226 ArgumentMatcherTuple matchers_;
1227 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001228 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001229
1230 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001231}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001232
1233// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1234// specifying the default behavior of, or expectation on, a mock
1235// function.
1236
1237// Note: class MockSpec really belongs to the ::testing namespace.
1238// However if we define it in ::testing, MSVC will complain when
1239// classes in ::testing::internal declare it as a friend class
1240// template. To workaround this compiler bug, we define MockSpec in
1241// ::testing::internal and import it into ::testing.
1242
zhanyong.waned6c9272011-02-23 19:39:27 +00001243// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001244GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1245 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001246 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001247
shiqiane35fdd92008-12-10 05:08:54 +00001248template <typename F>
1249class MockSpec {
1250 public:
1251 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1252 typedef typename internal::Function<F>::ArgumentMatcherTuple
1253 ArgumentMatcherTuple;
1254
1255 // Constructs a MockSpec object, given the function mocker object
1256 // that the spec is associated with.
1257 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1258 : function_mocker_(function_mocker) {}
1259
1260 // Adds a new default action spec to the function mocker and returns
1261 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001262 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001263 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001264 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001265 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001266 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001267 }
1268
1269 // Adds a new expectation spec to the function mocker and returns
1270 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001271 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001272 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001273 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1274 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001275 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001276 return function_mocker_->AddNewExpectation(
1277 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001278 }
1279
1280 private:
1281 template <typename Function>
1282 friend class internal::FunctionMocker;
1283
1284 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1285 matchers_ = matchers;
1286 }
1287
shiqiane35fdd92008-12-10 05:08:54 +00001288 // The function mocker that owns this spec.
1289 internal::FunctionMockerBase<F>* const function_mocker_;
1290 // The argument matchers specified in the spec.
1291 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001292
1293 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001294}; // class MockSpec
1295
kosakb5c81092014-01-29 06:41:44 +00001296// Wrapper type for generically holding an ordinary value or lvalue reference.
1297// If T is not a reference type, it must be copyable or movable.
1298// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1299// T is a move-only value type (which means that it will always be copyable
1300// if the current platform does not support move semantics).
1301//
1302// The primary template defines handling for values, but function header
1303// comments describe the contract for the whole template (including
1304// specializations).
1305template <typename T>
1306class ReferenceOrValueWrapper {
1307 public:
1308 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001309 explicit ReferenceOrValueWrapper(T value)
1310 : value_(::testing::internal::move(value)) {
1311 }
kosakb5c81092014-01-29 06:41:44 +00001312
1313 // Unwraps and returns the underlying value/reference, exactly as
1314 // originally passed. The behavior of calling this more than once on
1315 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001316 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001317
1318 // Provides nondestructive access to the underlying value/reference.
1319 // Always returns a const reference (more precisely,
1320 // const RemoveReference<T>&). The behavior of calling this after
1321 // calling Unwrap on the same object is unspecified.
1322 const T& Peek() const {
1323 return value_;
1324 }
1325
1326 private:
1327 T value_;
1328};
1329
1330// Specialization for lvalue reference types. See primary template
1331// for documentation.
1332template <typename T>
1333class ReferenceOrValueWrapper<T&> {
1334 public:
1335 // Workaround for debatable pass-by-reference lint warning (c-library-team
1336 // policy precludes NOLINT in this context)
1337 typedef T& reference;
1338 explicit ReferenceOrValueWrapper(reference ref)
1339 : value_ptr_(&ref) {}
1340 T& Unwrap() { return *value_ptr_; }
1341 const T& Peek() const { return *value_ptr_; }
1342
1343 private:
1344 T* value_ptr_;
1345};
1346
shiqiane35fdd92008-12-10 05:08:54 +00001347// MSVC warns about using 'this' in base member initializer list, so
1348// we need to temporarily disable the warning. We have to do it for
1349// the entire class to suppress the warning, even though it's about
1350// the constructor only.
1351
1352#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001353# pragma warning(push) // Saves the current warning state.
1354# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001355#endif // _MSV_VER
1356
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001357// C++ treats the void type specially. For example, you cannot define
1358// a void-typed variable or pass a void value to a function.
1359// ActionResultHolder<T> holds a value of type T, where T must be a
1360// copyable type or void (T doesn't need to be default-constructable).
1361// It hides the syntactic difference between void and other types, and
1362// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001363// non-void-returning mock functions.
1364
1365// Untyped base class for ActionResultHolder<T>.
1366class UntypedActionResultHolderBase {
1367 public:
1368 virtual ~UntypedActionResultHolderBase() {}
1369
1370 // Prints the held value as an action's result to os.
1371 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1372};
1373
1374// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001375template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001376class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001377 public:
kosakb5c81092014-01-29 06:41:44 +00001378 // Returns the held value. Must not be called more than once.
1379 T Unwrap() {
1380 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001381 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001382
1383 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001384 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001385 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001386 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001387 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001388 }
1389
1390 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001391 // result in a new-ed ActionResultHolder.
1392 template <typename F>
1393 static ActionResultHolder* PerformDefaultAction(
1394 const FunctionMockerBase<F>* func_mocker,
1395 const typename Function<F>::ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001396 const std::string& call_description) {
kosakb5c81092014-01-29 06:41:44 +00001397 return new ActionResultHolder(Wrapper(
1398 func_mocker->PerformDefaultAction(args, call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001399 }
1400
zhanyong.waned6c9272011-02-23 19:39:27 +00001401 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001402 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001403 template <typename F>
1404 static ActionResultHolder*
1405 PerformAction(const Action<F>& action,
1406 const typename Function<F>::ArgumentTuple& args) {
kosakb5c81092014-01-29 06:41:44 +00001407 return new ActionResultHolder(Wrapper(action.Perform(args)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001408 }
1409
1410 private:
kosakb5c81092014-01-29 06:41:44 +00001411 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001412
kosakd370f852014-11-17 01:14:16 +00001413 explicit ActionResultHolder(Wrapper result)
1414 : result_(::testing::internal::move(result)) {
1415 }
kosakb5c81092014-01-29 06:41:44 +00001416
1417 Wrapper result_;
1418
1419 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001420};
1421
1422// Specialization for T = void.
1423template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001424class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001425 public:
kosakb5c81092014-01-29 06:41:44 +00001426 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001427
zhanyong.waned6c9272011-02-23 19:39:27 +00001428 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1429
kosakb5c81092014-01-29 06:41:44 +00001430 // Performs the given mock function's default action and returns ownership
1431 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001432 template <typename F>
1433 static ActionResultHolder* PerformDefaultAction(
1434 const FunctionMockerBase<F>* func_mocker,
1435 const typename Function<F>::ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001436 const std::string& call_description) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001437 func_mocker->PerformDefaultAction(args, call_description);
kosakb5c81092014-01-29 06:41:44 +00001438 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001439 }
1440
kosakb5c81092014-01-29 06:41:44 +00001441 // Performs the given action and returns ownership of an empty
1442 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001443 template <typename F>
1444 static ActionResultHolder* PerformAction(
1445 const Action<F>& action,
1446 const typename Function<F>::ArgumentTuple& args) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001447 action.Perform(args);
kosakb5c81092014-01-29 06:41:44 +00001448 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001449 }
kosakb5c81092014-01-29 06:41:44 +00001450
1451 private:
1452 ActionResultHolder() {}
1453 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001454};
1455
shiqiane35fdd92008-12-10 05:08:54 +00001456// The base of the function mocker class for the given function type.
1457// We put the methods in this class instead of its child to avoid code
1458// bloat.
1459template <typename F>
1460class FunctionMockerBase : public UntypedFunctionMockerBase {
1461 public:
1462 typedef typename Function<F>::Result Result;
1463 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1464 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1465
zhanyong.waned6c9272011-02-23 19:39:27 +00001466 FunctionMockerBase() : current_spec_(this) {}
shiqiane35fdd92008-12-10 05:08:54 +00001467
1468 // The destructor verifies that all expectations on this mock
1469 // function have been satisfied. If not, it will report Google Test
1470 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001471 virtual ~FunctionMockerBase()
1472 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001473 MutexLock l(&g_gmock_mutex);
1474 VerifyAndClearExpectationsLocked();
1475 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001476 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001477 }
1478
1479 // Returns the ON_CALL spec that matches this mock function with the
1480 // given arguments; returns NULL if no matching ON_CALL is found.
1481 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001482 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001483 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001484 for (UntypedOnCallSpecs::const_reverse_iterator it
1485 = untyped_on_call_specs_.rbegin();
1486 it != untyped_on_call_specs_.rend(); ++it) {
1487 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1488 if (spec->Matches(args))
1489 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001490 }
1491
1492 return NULL;
1493 }
1494
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001495 // Performs the default action of this mock function on the given
1496 // arguments and returns the result. Asserts (or throws if
1497 // exceptions are enabled) with a helpful call descrption if there
1498 // is no valid return value. This method doesn't depend on the
1499 // mutable state of this object, and thus can be called concurrently
1500 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001501 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001502 Result PerformDefaultAction(const ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001503 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001504 const OnCallSpec<F>* const spec =
1505 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001506 if (spec != NULL) {
1507 return spec->GetAction().Perform(args);
1508 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001509 const std::string message =
1510 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001511 "\n The mock function has no default action "
1512 "set, and its return type has no default value set.";
1513#if GTEST_HAS_EXCEPTIONS
1514 if (!DefaultValue<Result>::Exists()) {
1515 throw std::runtime_error(message);
1516 }
1517#else
1518 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1519#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001520 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001521 }
1522
zhanyong.waned6c9272011-02-23 19:39:27 +00001523 // Performs the default action with the given arguments and returns
1524 // the action's result. The call description string will be used in
1525 // the error message to describe the call in the case the default
1526 // action fails. The caller is responsible for deleting the result.
1527 // L = *
1528 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1529 const void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001530 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001531 const ArgumentTuple& args =
1532 *static_cast<const ArgumentTuple*>(untyped_args);
1533 return ResultHolder::PerformDefaultAction(this, args, call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001534 }
1535
zhanyong.waned6c9272011-02-23 19:39:27 +00001536 // Performs the given action with the given arguments and returns
1537 // the action's result. The caller is responsible for deleting the
1538 // result.
1539 // L = *
1540 virtual UntypedActionResultHolderBase* UntypedPerformAction(
1541 const void* untyped_action, const void* untyped_args) const {
1542 // Make a copy of the action before performing it, in case the
1543 // action deletes the mock object (and thus deletes itself).
1544 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1545 const ArgumentTuple& args =
1546 *static_cast<const ArgumentTuple*>(untyped_args);
1547 return ResultHolder::PerformAction(action, args);
1548 }
shiqiane35fdd92008-12-10 05:08:54 +00001549
zhanyong.waned6c9272011-02-23 19:39:27 +00001550 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1551 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001552 virtual void ClearDefaultActionsLocked()
1553 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001554 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001555
1556 // Deleting our default actions may trigger other mock objects to be
1557 // deleted, for example if an action contains a reference counted smart
1558 // pointer to that mock object, and that is the last reference. So if we
1559 // delete our actions within the context of the global mutex we may deadlock
1560 // when this method is called again. Instead, make a copy of the set of
1561 // actions to delete, clear our set within the mutex, and then delete the
1562 // actions outside of the mutex.
1563 UntypedOnCallSpecs specs_to_delete;
1564 untyped_on_call_specs_.swap(specs_to_delete);
1565
1566 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001567 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001568 specs_to_delete.begin();
1569 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001570 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001571 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001572
1573 // Lock the mutex again, since the caller expects it to be locked when we
1574 // return.
1575 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001576 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001577
shiqiane35fdd92008-12-10 05:08:54 +00001578 protected:
1579 template <typename Function>
1580 friend class MockSpec;
1581
zhanyong.waned6c9272011-02-23 19:39:27 +00001582 typedef ActionResultHolder<Result> ResultHolder;
1583
shiqiane35fdd92008-12-10 05:08:54 +00001584 // Returns the result of invoking this mock function with the given
1585 // arguments. This function can be safely called from multiple
1586 // threads concurrently.
vladlosev4d60a592011-10-24 21:16:22 +00001587 Result InvokeWith(const ArgumentTuple& args)
1588 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
kosakb5c81092014-01-29 06:41:44 +00001589 scoped_ptr<ResultHolder> holder(
1590 DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args)));
1591 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001592 }
shiqiane35fdd92008-12-10 05:08:54 +00001593
1594 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001595 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001596 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001597 const ArgumentMatcherTuple& m)
1598 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001599 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001600 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1601 untyped_on_call_specs_.push_back(on_call_spec);
1602 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001603 }
1604
1605 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001606 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1607 const std::string& source_text,
1608 const ArgumentMatcherTuple& m)
1609 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001610 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001611 TypedExpectation<F>* const expectation =
1612 new TypedExpectation<F>(this, file, line, source_text, m);
1613 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1614 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001615
1616 // Adds this expectation into the implicit sequence if there is one.
1617 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1618 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001619 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001620 }
1621
1622 return *expectation;
1623 }
1624
1625 // The current spec (either default action spec or expectation spec)
1626 // being described on this function mocker.
1627 MockSpec<F>& current_spec() { return current_spec_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001628
shiqiane35fdd92008-12-10 05:08:54 +00001629 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001630 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001631
zhanyong.waned6c9272011-02-23 19:39:27 +00001632 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001633
1634 // Describes what default action will be performed for the given
1635 // arguments.
1636 // L = *
1637 void DescribeDefaultActionTo(const ArgumentTuple& args,
1638 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001639 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001640
1641 if (spec == NULL) {
1642 *os << (internal::type_equals<Result, void>::value ?
1643 "returning directly.\n" :
1644 "returning default value.\n");
1645 } else {
1646 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001647 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001648 }
1649 }
1650
1651 // Writes a message that the call is uninteresting (i.e. neither
1652 // explicitly expected nor explicitly unexpected) to the given
1653 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001654 virtual void UntypedDescribeUninterestingCall(
1655 const void* untyped_args,
1656 ::std::ostream* os) const
1657 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001658 const ArgumentTuple& args =
1659 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001660 *os << "Uninteresting mock function call - ";
1661 DescribeDefaultActionTo(args, os);
1662 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001663 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001664 }
1665
zhanyong.waned6c9272011-02-23 19:39:27 +00001666 // Returns the expectation that matches the given function arguments
1667 // (or NULL is there's no match); when a match is found,
1668 // untyped_action is set to point to the action that should be
1669 // performed (or NULL if the action is "do default"), and
1670 // is_excessive is modified to indicate whether the call exceeds the
1671 // expected number.
1672 //
shiqiane35fdd92008-12-10 05:08:54 +00001673 // Critical section: We must find the matching expectation and the
1674 // corresponding action that needs to be taken in an ATOMIC
1675 // transaction. Otherwise another thread may call this mock
1676 // method in the middle and mess up the state.
1677 //
1678 // However, performing the action has to be left out of the critical
1679 // section. The reason is that we have no control on what the
1680 // action does (it can invoke an arbitrary user function or even a
1681 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001682 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1683 const void* untyped_args,
1684 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001685 ::std::ostream* what, ::std::ostream* why)
1686 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001687 const ArgumentTuple& args =
1688 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001689 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001690 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1691 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001692 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001693 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001694 }
1695
1696 // This line must be done before calling GetActionForArguments(),
1697 // which will increment the call count for *exp and thus affect
1698 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001699 *is_excessive = exp->IsSaturated();
1700 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1701 if (action != NULL && action->IsDoDefault())
1702 action = NULL; // Normalize "do default" to NULL.
1703 *untyped_action = action;
1704 return exp;
1705 }
1706
1707 // Prints the given function arguments to the ostream.
1708 virtual void UntypedPrintArgs(const void* untyped_args,
1709 ::std::ostream* os) const {
1710 const ArgumentTuple& args =
1711 *static_cast<const ArgumentTuple*>(untyped_args);
1712 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001713 }
1714
1715 // Returns the expectation that matches the arguments, or NULL if no
1716 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001717 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001718 const ArgumentTuple& args) const
1719 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001720 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001721 for (typename UntypedExpectations::const_reverse_iterator it =
1722 untyped_expectations_.rbegin();
1723 it != untyped_expectations_.rend(); ++it) {
1724 TypedExpectation<F>* const exp =
1725 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001726 if (exp->ShouldHandleArguments(args)) {
1727 return exp;
1728 }
1729 }
1730 return NULL;
1731 }
1732
1733 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001734 void FormatUnexpectedCallMessageLocked(
1735 const ArgumentTuple& args,
1736 ::std::ostream* os,
1737 ::std::ostream* why) const
1738 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001739 g_gmock_mutex.AssertHeld();
1740 *os << "\nUnexpected mock function call - ";
1741 DescribeDefaultActionTo(args, os);
1742 PrintTriedExpectationsLocked(args, why);
1743 }
1744
1745 // Prints a list of expectations that have been tried against the
1746 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001747 void PrintTriedExpectationsLocked(
1748 const ArgumentTuple& args,
1749 ::std::ostream* why) const
1750 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001751 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001752 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001753 *why << "Google Mock tried the following " << count << " "
1754 << (count == 1 ? "expectation, but it didn't match" :
1755 "expectations, but none matched")
1756 << ":\n";
1757 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001758 TypedExpectation<F>* const expectation =
1759 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001760 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001761 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001762 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001763 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001764 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001765 *why << expectation->source_text() << "...\n";
1766 expectation->ExplainMatchResultTo(args, why);
1767 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001768 }
1769 }
1770
shiqiane35fdd92008-12-10 05:08:54 +00001771 // The current spec (either default action spec or expectation spec)
1772 // being described on this function mocker.
1773 MockSpec<F> current_spec_;
1774
zhanyong.wan16cf4732009-05-14 20:55:30 +00001775 // There is no generally useful and implementable semantics of
1776 // copying a mock object, so copying a mock is usually a user error.
1777 // Thus we disallow copying function mockers. If the user really
1778 // wants to copy a mock object, he should implement his own copy
1779 // operation, for example:
1780 //
1781 // class MockFoo : public Foo {
1782 // public:
1783 // // Defines a copy constructor explicitly.
1784 // MockFoo(const MockFoo& src) {}
1785 // ...
1786 // };
1787 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001788}; // class FunctionMockerBase
1789
1790#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001791# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001792#endif // _MSV_VER
1793
1794// Implements methods of FunctionMockerBase.
1795
1796// Verifies that all expectations on this mock function have been
1797// satisfied. Reports one or more Google Test non-fatal failures and
1798// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001799
1800// Reports an uninteresting call (whose description is in msg) in the
1801// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001802void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001803
shiqiane35fdd92008-12-10 05:08:54 +00001804} // namespace internal
1805
1806// The style guide prohibits "using" statements in a namespace scope
1807// inside a header file. However, the MockSpec class template is
1808// meant to be defined in the ::testing namespace. The following line
1809// is just a trick for working around a bug in MSVC 8.0, which cannot
1810// handle it if we define MockSpec in ::testing.
1811using internal::MockSpec;
1812
1813// Const(x) is a convenient function for obtaining a const reference
1814// to x. This is useful for setting expectations on an overloaded
1815// const mock method, e.g.
1816//
1817// class MockFoo : public FooInterface {
1818// public:
1819// MOCK_METHOD0(Bar, int());
1820// MOCK_CONST_METHOD0(Bar, int&());
1821// };
1822//
1823// MockFoo foo;
1824// // Expects a call to non-const MockFoo::Bar().
1825// EXPECT_CALL(foo, Bar());
1826// // Expects a call to const MockFoo::Bar().
1827// EXPECT_CALL(Const(foo), Bar());
1828template <typename T>
1829inline const T& Const(const T& x) { return x; }
1830
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001831// Constructs an Expectation object that references and co-owns exp.
1832inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1833 : expectation_base_(exp.GetHandle().expectation_base()) {}
1834
shiqiane35fdd92008-12-10 05:08:54 +00001835} // namespace testing
1836
1837// A separate macro is required to avoid compile errors when the name
1838// of the method used in call is a result of macro expansion.
1839// See CompilesWithMethodNameExpandedFromMacro tests in
1840// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001841#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001842 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1843 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001844#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001845
zhanyong.wane0d051e2009-02-19 00:33:37 +00001846#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001847 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001848#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001849
1850#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_