blob: c1b630141d452296bbaf52b83a562f30ac329d87 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements the ON_CALL() and EXPECT_CALL() macros.
35//
36// A user can use the ON_CALL() macro to specify the default action of
37// a mock method. The syntax is:
38//
39// ON_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000040// .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +000041// .WillByDefault(action);
42//
zhanyong.wanbf550852009-06-09 06:09:53 +000043// where the .With() clause is optional.
shiqiane35fdd92008-12-10 05:08:54 +000044//
45// A user can use the EXPECT_CALL() macro to specify an expectation on
46// a mock method. The syntax is:
47//
48// EXPECT_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000049// .With(multi-argument-matchers)
shiqiane35fdd92008-12-10 05:08:54 +000050// .Times(cardinality)
51// .InSequence(sequences)
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000052// .After(expectations)
shiqiane35fdd92008-12-10 05:08:54 +000053// .WillOnce(action)
54// .WillRepeatedly(action)
55// .RetiresOnSaturation();
56//
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000057// where all clauses are optional, and .InSequence()/.After()/
58// .WillOnce() can appear any number of times.
shiqiane35fdd92008-12-10 05:08:54 +000059
60#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
61#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62
63#include <map>
64#include <set>
65#include <sstream>
66#include <string>
67#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000068#include "gmock/gmock-actions.h"
69#include "gmock/gmock-cardinalities.h"
70#include "gmock/gmock-matchers.h"
71#include "gmock/internal/gmock-internal-utils.h"
72#include "gmock/internal/gmock-port.h"
73#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000074
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050075#if GTEST_HAS_EXCEPTIONS
76# include <stdexcept> // NOLINT
77#endif
78
shiqiane35fdd92008-12-10 05:08:54 +000079namespace testing {
80
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000081// An abstract handle of an expectation.
82class Expectation;
83
84// A set of expectation handles.
85class ExpectationSet;
86
shiqiane35fdd92008-12-10 05:08:54 +000087// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
88// and MUST NOT BE USED IN USER CODE!!!
89namespace internal {
90
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000091// Implements a mock function.
92template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000093
94// Base class for expectations.
95class ExpectationBase;
96
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000097// Implements an expectation.
98template <typename F> class TypedExpectation;
99
shiqiane35fdd92008-12-10 05:08:54 +0000100// Helper class for testing the Expectation class template.
101class ExpectationTester;
102
103// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000104template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000105
shiqiane35fdd92008-12-10 05:08:54 +0000106// Protects the mock object registry (in class Mock), all function
107// mockers, and all expectations.
108//
109// The reason we don't use more fine-grained protection is: when a
110// mock function Foo() is called, it needs to consult its expectations
111// to see which one should be picked. If another thread is allowed to
112// call a mock function (either Foo() or a different one) at the same
113// time, it could affect the "retired" attributes of Foo()'s
114// expectations when InSequence() is used, and thus affect which
115// expectation gets picked. Therefore, we sequence all mock function
116// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000117GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000118
zhanyong.waned6c9272011-02-23 19:39:27 +0000119// Untyped base class for ActionResultHolder<R>.
120class UntypedActionResultHolderBase;
121
shiqiane35fdd92008-12-10 05:08:54 +0000122// Abstract base class of FunctionMockerBase. This is the
123// type-agnostic part of the function mocker interface. Its pure
124// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000125class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000126 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000127 UntypedFunctionMockerBase();
128 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000129
130 // Verifies that all expectations on this mock function have been
131 // satisfied. Reports one or more Google Test non-fatal failures
132 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000133 bool VerifyAndClearExpectationsLocked()
134 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000135
136 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000137 virtual void ClearDefaultActionsLocked()
138 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000139
140 // In all of the following Untyped* functions, it's the caller's
141 // responsibility to guarantee the correctness of the arguments'
142 // types.
143
144 // Performs the default action with the given arguments and returns
145 // the action's result. The call description string will be used in
146 // the error message to describe the call in the case the default
147 // action fails.
148 // L = *
149 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Nico Weber09fd5b32017-05-15 17:07:03 -0400150 const void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000151
152 // Performs the given action with the given arguments and returns
153 // the action's result.
154 // L = *
155 virtual UntypedActionResultHolderBase* UntypedPerformAction(
156 const void* untyped_action,
157 const void* untyped_args) const = 0;
158
159 // Writes a message that the call is uninteresting (i.e. neither
160 // explicitly expected nor explicitly unexpected) to the given
161 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +0000162 virtual void UntypedDescribeUninterestingCall(
163 const void* untyped_args,
164 ::std::ostream* os) const
165 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000166
167 // Returns the expectation that matches the given function arguments
168 // (or NULL is there's no match); when a match is found,
169 // untyped_action is set to point to the action that should be
170 // performed (or NULL if the action is "do default"), and
171 // is_excessive is modified to indicate whether the call exceeds the
172 // expected number.
zhanyong.waned6c9272011-02-23 19:39:27 +0000173 virtual const ExpectationBase* UntypedFindMatchingExpectation(
174 const void* untyped_args,
175 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000176 ::std::ostream* what, ::std::ostream* why)
177 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000178
179 // Prints the given function arguments to the ostream.
180 virtual void UntypedPrintArgs(const void* untyped_args,
181 ::std::ostream* os) const = 0;
182
183 // Sets the mock object this mock method belongs to, and registers
184 // this information in the global mock registry. Will be called
185 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
186 // method.
187 // TODO(wan@google.com): rename to SetAndRegisterOwner().
vladlosev4d60a592011-10-24 21:16:22 +0000188 void RegisterOwner(const void* mock_obj)
189 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000190
191 // Sets the mock object this mock method belongs to, and sets the
192 // name of the mock function. Will be called upon each invocation
193 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000194 void SetOwnerAndName(const void* mock_obj, const char* name)
195 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000196
197 // Returns the mock object this mock method belongs to. Must be
198 // called after RegisterOwner() or SetOwnerAndName() has been
199 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000200 const void* MockObject() const
201 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000202
203 // Returns the name of this mock method. Must be called after
204 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000205 const char* Name() const
206 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000207
208 // Returns the result of invoking this mock function with the given
209 // arguments. This function can be safely called from multiple
210 // threads concurrently. The caller is responsible for deleting the
211 // result.
kosakb5c81092014-01-29 06:41:44 +0000212 UntypedActionResultHolderBase* UntypedInvokeWith(
vladlosev4d60a592011-10-24 21:16:22 +0000213 const void* untyped_args)
214 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000215
216 protected:
217 typedef std::vector<const void*> UntypedOnCallSpecs;
218
219 typedef std::vector<internal::linked_ptr<ExpectationBase> >
220 UntypedExpectations;
221
222 // Returns an Expectation object that references and co-owns exp,
223 // which must be an expectation on this mock function.
224 Expectation GetHandleOf(ExpectationBase* exp);
225
226 // Address of the mock object this mock method belongs to. Only
227 // valid after this mock method has been called or
228 // ON_CALL/EXPECT_CALL has been invoked on it.
229 const void* mock_obj_; // Protected by g_gmock_mutex.
230
231 // Name of the function being mocked. Only valid after this mock
232 // method has been called.
233 const char* name_; // Protected by g_gmock_mutex.
234
235 // All default action specs for this function mocker.
236 UntypedOnCallSpecs untyped_on_call_specs_;
237
238 // All expectations for this function mocker.
239 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000240}; // class UntypedFunctionMockerBase
241
zhanyong.waned6c9272011-02-23 19:39:27 +0000242// Untyped base class for OnCallSpec<F>.
243class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000244 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000245 // The arguments are the location of the ON_CALL() statement.
246 UntypedOnCallSpecBase(const char* a_file, int a_line)
247 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000248
249 // Where in the source file was the default action spec defined?
250 const char* file() const { return file_; }
251 int line() const { return line_; }
252
zhanyong.waned6c9272011-02-23 19:39:27 +0000253 protected:
254 // Gives each clause in the ON_CALL() statement a name.
255 enum Clause {
256 // Do not change the order of the enum members! The run-time
257 // syntax checking relies on it.
258 kNone,
259 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000260 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000261 };
262
263 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400264 void AssertSpecProperty(bool property,
265 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000266 Assert(property, file_, line_, failure_message);
267 }
268
269 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400270 void ExpectSpecProperty(bool property,
271 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000272 Expect(property, file_, line_, failure_message);
273 }
274
275 const char* file_;
276 int line_;
277
278 // The last clause in the ON_CALL() statement as seen so far.
279 // Initially kNone and changes as the statement is parsed.
280 Clause last_clause_;
281}; // class UntypedOnCallSpecBase
282
283// This template class implements an ON_CALL spec.
284template <typename F>
285class OnCallSpec : public UntypedOnCallSpecBase {
286 public:
287 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
288 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
289
290 // Constructs an OnCallSpec object from the information inside
291 // the parenthesis of an ON_CALL() statement.
292 OnCallSpec(const char* a_file, int a_line,
293 const ArgumentMatcherTuple& matchers)
294 : UntypedOnCallSpecBase(a_file, a_line),
295 matchers_(matchers),
296 // By default, extra_matcher_ should match anything. However,
297 // we cannot initialize it with _ as that triggers a compiler
298 // bug in Symbian's C++ compiler (cannot decide between two
299 // overloaded constructors of Matcher<const ArgumentTuple&>).
300 extra_matcher_(A<const ArgumentTuple&>()) {
301 }
302
zhanyong.wanbf550852009-06-09 06:09:53 +0000303 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000304 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000305 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000306 ExpectSpecProperty(last_clause_ < kWith,
307 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000308 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000309 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000310
311 extra_matcher_ = m;
312 return *this;
313 }
314
315 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000316 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000317 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000318 ".WillByDefault() must appear "
319 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000320 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000321
322 ExpectSpecProperty(!action.IsDoDefault(),
323 "DoDefault() cannot be used in ON_CALL().");
324 action_ = action;
325 return *this;
326 }
327
328 // Returns true iff the given arguments match the matchers.
329 bool Matches(const ArgumentTuple& args) const {
330 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
331 }
332
333 // Returns the action specified by the user.
334 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000335 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000336 ".WillByDefault() must appear exactly "
337 "once in an ON_CALL().");
338 return action_;
339 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000340
shiqiane35fdd92008-12-10 05:08:54 +0000341 private:
shiqiane35fdd92008-12-10 05:08:54 +0000342 // The information in statement
343 //
344 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000345 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000346 // .WillByDefault(action);
347 //
348 // is recorded in the data members like this:
349 //
350 // source file that contains the statement => file_
351 // line number of the statement => line_
352 // matchers => matchers_
353 // multi-argument-matcher => extra_matcher_
354 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000355 ArgumentMatcherTuple matchers_;
356 Matcher<const ArgumentTuple&> extra_matcher_;
357 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000358}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000359
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000360// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000361enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000362 kAllow,
363 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000364 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000365};
366
367} // namespace internal
368
369// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000370class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000371 public:
372 // The following public methods can be called concurrently.
373
zhanyong.wandf35a762009-04-22 22:25:31 +0000374 // Tells Google Mock to ignore mock_obj when checking for leaked
375 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000376 static void AllowLeak(const void* mock_obj)
377 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000378
shiqiane35fdd92008-12-10 05:08:54 +0000379 // Verifies and clears all expectations on the given mock object.
380 // If the expectations aren't satisfied, generates one or more
381 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000382 static bool VerifyAndClearExpectations(void* mock_obj)
383 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000384
385 // Verifies all expectations on the given mock object and clears its
386 // default actions and expectations. Returns true iff the
387 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000388 static bool VerifyAndClear(void* mock_obj)
389 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000390
shiqiane35fdd92008-12-10 05:08:54 +0000391 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000392 friend class internal::UntypedFunctionMockerBase;
393
shiqiane35fdd92008-12-10 05:08:54 +0000394 // Needed for a function mocker to register itself (so that we know
395 // how to clear a mock object).
396 template <typename F>
397 friend class internal::FunctionMockerBase;
398
shiqiane35fdd92008-12-10 05:08:54 +0000399 template <typename M>
400 friend class NiceMock;
401
402 template <typename M>
zhanyong.wan844fa942013-03-01 01:54:22 +0000403 friend class NaggyMock;
404
405 template <typename M>
shiqiane35fdd92008-12-10 05:08:54 +0000406 friend class StrictMock;
407
408 // Tells Google Mock to allow uninteresting calls on the given mock
409 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000410 static void AllowUninterestingCalls(const void* mock_obj)
411 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000412
413 // Tells Google Mock to warn the user about uninteresting calls on
414 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000415 static void WarnUninterestingCalls(const void* mock_obj)
416 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000417
418 // Tells Google Mock to fail uninteresting calls on the given mock
419 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000420 static void FailUninterestingCalls(const void* mock_obj)
421 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000422
423 // Tells Google Mock the given mock object is being destroyed and
424 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000425 static void UnregisterCallReaction(const void* mock_obj)
426 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000427
428 // Returns the reaction Google Mock will have on uninteresting calls
429 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000430 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000431 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000432 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000433
434 // Verifies that all expectations on the given mock object have been
435 // satisfied. Reports one or more Google Test non-fatal failures
436 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000437 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
438 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000439
440 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000441 static void ClearDefaultActionsLocked(void* mock_obj)
442 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000443
444 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000445 static void Register(
446 const void* mock_obj,
447 internal::UntypedFunctionMockerBase* mocker)
448 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000449
zhanyong.wandf35a762009-04-22 22:25:31 +0000450 // Tells Google Mock where in the source code mock_obj is used in an
451 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
452 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000453 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000454 const void* mock_obj, const char* file, int line)
455 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000456
shiqiane35fdd92008-12-10 05:08:54 +0000457 // Unregisters a mock method; removes the owning mock object from
458 // the registry when the last mock method associated with it has
459 // been unregistered. This is called only in the destructor of
460 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000461 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
462 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000463}; // class Mock
464
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000465// An abstract handle of an expectation. Useful in the .After()
466// clause of EXPECT_CALL() for setting the (partial) order of
467// expectations. The syntax:
468//
469// Expectation e1 = EXPECT_CALL(...)...;
470// EXPECT_CALL(...).After(e1)...;
471//
472// sets two expectations where the latter can only be matched after
473// the former has been satisfied.
474//
475// Notes:
476// - This class is copyable and has value semantics.
477// - Constness is shallow: a const Expectation object itself cannot
478// be modified, but the mutable methods of the ExpectationBase
479// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000480// - The constructors and destructor are defined out-of-line because
481// the Symbian WINSCW compiler wants to otherwise instantiate them
482// when it sees this class definition, at which point it doesn't have
483// ExpectationBase available yet, leading to incorrect destruction
484// in the linked_ptr (or compilation errors if using a checking
485// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000486class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000487 public:
488 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000489 Expectation();
490
491 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000492
493 // This single-argument ctor must not be explicit, in order to support the
494 // Expectation e = EXPECT_CALL(...);
495 // syntax.
496 //
497 // A TypedExpectation object stores its pre-requisites as
498 // Expectation objects, and needs to call the non-const Retire()
499 // method on the ExpectationBase objects they reference. Therefore
500 // Expectation must receive a *non-const* reference to the
501 // ExpectationBase object.
502 Expectation(internal::ExpectationBase& exp); // NOLINT
503
504 // The compiler-generated copy ctor and operator= work exactly as
505 // intended, so we don't need to define our own.
506
507 // Returns true iff rhs references the same expectation as this object does.
508 bool operator==(const Expectation& rhs) const {
509 return expectation_base_ == rhs.expectation_base_;
510 }
511
512 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
513
514 private:
515 friend class ExpectationSet;
516 friend class Sequence;
517 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000518 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000519
520 template <typename F>
521 friend class ::testing::internal::FunctionMockerBase;
522
523 template <typename F>
524 friend class ::testing::internal::TypedExpectation;
525
526 // This comparator is needed for putting Expectation objects into a set.
527 class Less {
528 public:
529 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
530 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
531 }
532 };
533
534 typedef ::std::set<Expectation, Less> Set;
535
536 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000537 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000538
539 // Returns the expectation this object references.
540 const internal::linked_ptr<internal::ExpectationBase>&
541 expectation_base() const {
542 return expectation_base_;
543 }
544
545 // A linked_ptr that co-owns the expectation this handle references.
546 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
547};
548
549// A set of expectation handles. Useful in the .After() clause of
550// EXPECT_CALL() for setting the (partial) order of expectations. The
551// syntax:
552//
553// ExpectationSet es;
554// es += EXPECT_CALL(...)...;
555// es += EXPECT_CALL(...)...;
556// EXPECT_CALL(...).After(es)...;
557//
558// sets three expectations where the last one can only be matched
559// after the first two have both been satisfied.
560//
561// This class is copyable and has value semantics.
562class ExpectationSet {
563 public:
564 // A bidirectional iterator that can read a const element in the set.
565 typedef Expectation::Set::const_iterator const_iterator;
566
567 // An object stored in the set. This is an alias of Expectation.
568 typedef Expectation::Set::value_type value_type;
569
570 // Constructs an empty set.
571 ExpectationSet() {}
572
573 // This single-argument ctor must not be explicit, in order to support the
574 // ExpectationSet es = EXPECT_CALL(...);
575 // syntax.
576 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
577 *this += Expectation(exp);
578 }
579
580 // This single-argument ctor implements implicit conversion from
581 // Expectation and thus must not be explicit. This allows either an
582 // Expectation or an ExpectationSet to be used in .After().
583 ExpectationSet(const Expectation& e) { // NOLINT
584 *this += e;
585 }
586
587 // The compiler-generator ctor and operator= works exactly as
588 // intended, so we don't need to define our own.
589
590 // Returns true iff rhs contains the same set of Expectation objects
591 // as this does.
592 bool operator==(const ExpectationSet& rhs) const {
593 return expectations_ == rhs.expectations_;
594 }
595
596 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
597
598 // Implements the syntax
599 // expectation_set += EXPECT_CALL(...);
600 ExpectationSet& operator+=(const Expectation& e) {
601 expectations_.insert(e);
602 return *this;
603 }
604
605 int size() const { return static_cast<int>(expectations_.size()); }
606
607 const_iterator begin() const { return expectations_.begin(); }
608 const_iterator end() const { return expectations_.end(); }
609
610 private:
611 Expectation::Set expectations_;
612};
613
614
shiqiane35fdd92008-12-10 05:08:54 +0000615// Sequence objects are used by a user to specify the relative order
616// in which the expectations should match. They are copyable (we rely
617// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000618class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000619 public:
620 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000621 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000622
623 // Adds an expectation to this sequence. The caller must ensure
624 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000625 void AddExpectation(const Expectation& expectation) const;
626
shiqiane35fdd92008-12-10 05:08:54 +0000627 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000628 // The last expectation in this sequence. We use a linked_ptr here
629 // because Sequence objects are copyable and we want the copies to
630 // be aliases. The linked_ptr allows the copies to co-own and share
631 // the same Expectation object.
632 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000633}; // class Sequence
634
635// An object of this type causes all EXPECT_CALL() statements
636// encountered in its scope to be put in an anonymous sequence. The
637// work is done in the constructor and destructor. You should only
638// create an InSequence object on the stack.
639//
640// The sole purpose for this class is to support easy definition of
641// sequential expectations, e.g.
642//
643// {
644// InSequence dummy; // The name of the object doesn't matter.
645//
646// // The following expectations must match in the order they appear.
647// EXPECT_CALL(a, Bar())...;
648// EXPECT_CALL(a, Baz())...;
649// ...
650// EXPECT_CALL(b, Xyz())...;
651// }
652//
653// You can create InSequence objects in multiple threads, as long as
654// they are used to affect different mock objects. The idea is that
655// each thread can create and set up its own mocks as if it's the only
656// thread. However, for clarity of your tests we recommend you to set
657// up mocks in the main thread unless you have a good reason not to do
658// so.
vladlosev587c1b32011-05-20 00:42:22 +0000659class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000660 public:
661 InSequence();
662 ~InSequence();
663 private:
664 bool sequence_created_;
665
666 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000667} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000668
669namespace internal {
670
671// Points to the implicit sequence introduced by a living InSequence
672// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000673GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000674
675// Base class for implementing expectations.
676//
677// There are two reasons for having a type-agnostic base class for
678// Expectation:
679//
680// 1. We need to store collections of expectations of different
681// types (e.g. all pre-requisites of a particular expectation, all
682// expectations in a sequence). Therefore these expectation objects
683// must share a common base class.
684//
685// 2. We can avoid binary code bloat by moving methods not depending
686// on the template argument of Expectation to the base class.
687//
688// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000689class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000690 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000691 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400692 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000693
694 virtual ~ExpectationBase();
695
696 // Where in the source file was the expectation spec defined?
697 const char* file() const { return file_; }
698 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000699 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000700 // Returns the cardinality specified in the expectation spec.
701 const Cardinality& cardinality() const { return cardinality_; }
702
703 // Describes the source file location of this expectation.
704 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000705 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000706 }
707
708 // Describes how many times a function call matching this
709 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000710 void DescribeCallCountTo(::std::ostream* os) const
711 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000712
713 // If this mock method has an extra matcher (i.e. .With(matcher)),
714 // describes it to the ostream.
715 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000716
shiqiane35fdd92008-12-10 05:08:54 +0000717 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000718 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000719 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000720
721 enum Clause {
722 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000723 kNone,
724 kWith,
725 kTimes,
726 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000727 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000728 kWillOnce,
729 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000730 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000731 };
732
zhanyong.waned6c9272011-02-23 19:39:27 +0000733 typedef std::vector<const void*> UntypedActions;
734
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000735 // Returns an Expectation object that references and co-owns this
736 // expectation.
737 virtual Expectation GetHandle() = 0;
738
shiqiane35fdd92008-12-10 05:08:54 +0000739 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400740 void AssertSpecProperty(bool property,
741 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000742 Assert(property, file_, line_, failure_message);
743 }
744
745 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400746 void ExpectSpecProperty(bool property,
747 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000748 Expect(property, file_, line_, failure_message);
749 }
750
751 // Explicitly specifies the cardinality of this expectation. Used
752 // by the subclasses to implement the .Times() clause.
753 void SpecifyCardinality(const Cardinality& cardinality);
754
755 // Returns true iff the user specified the cardinality explicitly
756 // using a .Times().
757 bool cardinality_specified() const { return cardinality_specified_; }
758
759 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000760 void set_cardinality(const Cardinality& a_cardinality) {
761 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000762 }
763
764 // The following group of methods should only be called after the
765 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
766 // the current thread.
767
768 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000769 void RetireAllPreRequisites()
770 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000771
772 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000773 bool is_retired() const
774 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000775 g_gmock_mutex.AssertHeld();
776 return retired_;
777 }
778
779 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000780 void Retire()
781 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000782 g_gmock_mutex.AssertHeld();
783 retired_ = true;
784 }
785
786 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000787 bool IsSatisfied() const
788 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000789 g_gmock_mutex.AssertHeld();
790 return cardinality().IsSatisfiedByCallCount(call_count_);
791 }
792
793 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000794 bool IsSaturated() const
795 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000796 g_gmock_mutex.AssertHeld();
797 return cardinality().IsSaturatedByCallCount(call_count_);
798 }
799
800 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000801 bool IsOverSaturated() const
802 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000803 g_gmock_mutex.AssertHeld();
804 return cardinality().IsOverSaturatedByCallCount(call_count_);
805 }
806
807 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000808 bool AllPrerequisitesAreSatisfied() const
809 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000810
811 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000812 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
813 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000814
815 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000816 int call_count() const
817 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000818 g_gmock_mutex.AssertHeld();
819 return call_count_;
820 }
821
822 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000823 void IncrementCallCount()
824 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000825 g_gmock_mutex.AssertHeld();
826 call_count_++;
827 }
828
zhanyong.waned6c9272011-02-23 19:39:27 +0000829 // Checks the action count (i.e. the number of WillOnce() and
830 // WillRepeatedly() clauses) against the cardinality if this hasn't
831 // been done before. Prints a warning if there are too many or too
832 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000833 void CheckActionCountIfNotDone() const
834 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000835
shiqiane35fdd92008-12-10 05:08:54 +0000836 friend class ::testing::Sequence;
837 friend class ::testing::internal::ExpectationTester;
838
839 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000840 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000841
zhanyong.waned6c9272011-02-23 19:39:27 +0000842 // Implements the .Times() clause.
843 void UntypedTimes(const Cardinality& a_cardinality);
844
shiqiane35fdd92008-12-10 05:08:54 +0000845 // This group of fields are part of the spec and won't change after
846 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000847 const char* file_; // The file that contains the expectation.
848 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400849 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000850 // True iff the cardinality is specified explicitly.
851 bool cardinality_specified_;
852 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000853 // The immediate pre-requisites (i.e. expectations that must be
854 // satisfied before this expectation can be matched) of this
855 // expectation. We use linked_ptr in the set because we want an
856 // Expectation object to be co-owned by its FunctionMocker and its
857 // successors. This allows multiple mock objects to be deleted at
858 // different times.
859 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000860
861 // This group of fields are the current state of the expectation,
862 // and can change as the mock function is called.
863 int call_count_; // How many times this expectation has been invoked.
864 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000865 UntypedActions untyped_actions_;
866 bool extra_matcher_specified_;
867 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
868 bool retires_on_saturation_;
869 Clause last_clause_;
870 mutable bool action_count_checked_; // Under mutex_.
871 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000872
873 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000874}; // class ExpectationBase
875
876// Impements an expectation for the given function type.
877template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000878class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000879 public:
880 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
881 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
882 typedef typename Function<F>::Result Result;
883
Nico Weber09fd5b32017-05-15 17:07:03 -0400884 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
885 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000886 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000887 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000888 owner_(owner),
889 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000890 // By default, extra_matcher_ should match anything. However,
891 // we cannot initialize it with _ as that triggers a compiler
892 // bug in Symbian's C++ compiler (cannot decide between two
893 // overloaded constructors of Matcher<const ArgumentTuple&>).
894 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000895 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000896
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000897 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000898 // Check the validity of the action count if it hasn't been done
899 // yet (for example, if the expectation was never used).
900 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000901 for (UntypedActions::const_iterator it = untyped_actions_.begin();
902 it != untyped_actions_.end(); ++it) {
903 delete static_cast<const Action<F>*>(*it);
904 }
shiqiane35fdd92008-12-10 05:08:54 +0000905 }
906
zhanyong.wanbf550852009-06-09 06:09:53 +0000907 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000908 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000909 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000910 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000911 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000912 "more than once in an EXPECT_CALL().");
913 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000914 ExpectSpecProperty(last_clause_ < kWith,
915 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000916 "clause in an EXPECT_CALL().");
917 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000918 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000919
920 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000921 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000922 return *this;
923 }
924
925 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000926 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000927 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000928 return *this;
929 }
930
931 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000932 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000933 return Times(Exactly(n));
934 }
935
936 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000937 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000938 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000939 ".InSequence() cannot appear after .After(),"
940 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000941 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000942 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000943
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000944 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000945 return *this;
946 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000947 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000948 return InSequence(s1).InSequence(s2);
949 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000950 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
951 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000952 return InSequence(s1, s2).InSequence(s3);
953 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000954 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
955 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000956 return InSequence(s1, s2, s3).InSequence(s4);
957 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000958 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
959 const Sequence& s3, const Sequence& s4,
960 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000961 return InSequence(s1, s2, s3, s4).InSequence(s5);
962 }
963
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000964 // Implements that .After() clause.
965 TypedExpectation& After(const ExpectationSet& s) {
966 ExpectSpecProperty(last_clause_ <= kAfter,
967 ".After() cannot appear after .WillOnce(),"
968 " .WillRepeatedly(), or "
969 ".RetiresOnSaturation().");
970 last_clause_ = kAfter;
971
972 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
973 immediate_prerequisites_ += *it;
974 }
975 return *this;
976 }
977 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
978 return After(s1).After(s2);
979 }
980 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
981 const ExpectationSet& s3) {
982 return After(s1, s2).After(s3);
983 }
984 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
985 const ExpectationSet& s3, const ExpectationSet& s4) {
986 return After(s1, s2, s3).After(s4);
987 }
988 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
989 const ExpectationSet& s3, const ExpectationSet& s4,
990 const ExpectationSet& s5) {
991 return After(s1, s2, s3, s4).After(s5);
992 }
993
shiqiane35fdd92008-12-10 05:08:54 +0000994 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000995 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000996 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000997 ".WillOnce() cannot appear after "
998 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000999 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001000
zhanyong.waned6c9272011-02-23 19:39:27 +00001001 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001002 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001003 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001004 }
1005 return *this;
1006 }
1007
1008 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001009 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001010 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001011 ExpectSpecProperty(false,
1012 ".WillRepeatedly() cannot appear "
1013 "more than once in an EXPECT_CALL().");
1014 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001015 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001016 ".WillRepeatedly() cannot appear "
1017 "after .RetiresOnSaturation().");
1018 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001019 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001020 repeated_action_specified_ = true;
1021
1022 repeated_action_ = action;
1023 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001024 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001025 }
1026
1027 // Now that no more action clauses can be specified, we check
1028 // whether their count makes sense.
1029 CheckActionCountIfNotDone();
1030 return *this;
1031 }
1032
1033 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001034 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001035 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001036 ".RetiresOnSaturation() cannot appear "
1037 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001038 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001039 retires_on_saturation_ = true;
1040
1041 // Now that no more action clauses can be specified, we check
1042 // whether their count makes sense.
1043 CheckActionCountIfNotDone();
1044 return *this;
1045 }
1046
1047 // Returns the matchers for the arguments as specified inside the
1048 // EXPECT_CALL() macro.
1049 const ArgumentMatcherTuple& matchers() const {
1050 return matchers_;
1051 }
1052
zhanyong.wanbf550852009-06-09 06:09:53 +00001053 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001054 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1055 return extra_matcher_;
1056 }
1057
shiqiane35fdd92008-12-10 05:08:54 +00001058 // Returns the action specified by the .WillRepeatedly() clause.
1059 const Action<F>& repeated_action() const { return repeated_action_; }
1060
zhanyong.waned6c9272011-02-23 19:39:27 +00001061 // If this mock method has an extra matcher (i.e. .With(matcher)),
1062 // describes it to the ostream.
1063 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001064 if (extra_matcher_specified_) {
1065 *os << " Expected args: ";
1066 extra_matcher_.DescribeTo(os);
1067 *os << "\n";
1068 }
1069 }
1070
shiqiane35fdd92008-12-10 05:08:54 +00001071 private:
1072 template <typename Function>
1073 friend class FunctionMockerBase;
1074
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001075 // Returns an Expectation object that references and co-owns this
1076 // expectation.
1077 virtual Expectation GetHandle() {
1078 return owner_->GetHandleOf(this);
1079 }
1080
shiqiane35fdd92008-12-10 05:08:54 +00001081 // The following methods will be called only after the EXPECT_CALL()
1082 // statement finishes and when the current thread holds
1083 // g_gmock_mutex.
1084
1085 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001086 bool Matches(const ArgumentTuple& args) const
1087 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001088 g_gmock_mutex.AssertHeld();
1089 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1090 }
1091
1092 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001093 bool ShouldHandleArguments(const ArgumentTuple& args) const
1094 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001095 g_gmock_mutex.AssertHeld();
1096
1097 // In case the action count wasn't checked when the expectation
1098 // was defined (e.g. if this expectation has no WillRepeatedly()
1099 // or RetiresOnSaturation() clause), we check it when the
1100 // expectation is used for the first time.
1101 CheckActionCountIfNotDone();
1102 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1103 }
1104
1105 // Describes the result of matching the arguments against this
1106 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001107 void ExplainMatchResultTo(
1108 const ArgumentTuple& args,
1109 ::std::ostream* os) const
1110 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001111 g_gmock_mutex.AssertHeld();
1112
1113 if (is_retired()) {
1114 *os << " Expected: the expectation is active\n"
1115 << " Actual: it is retired\n";
1116 } else if (!Matches(args)) {
1117 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001118 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001119 }
zhanyong.wan82113312010-01-08 21:55:40 +00001120 StringMatchResultListener listener;
1121 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001122 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001123 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001124 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001125
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001126 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001127 *os << "\n";
1128 }
1129 } else if (!AllPrerequisitesAreSatisfied()) {
1130 *os << " Expected: all pre-requisites are satisfied\n"
1131 << " Actual: the following immediate pre-requisites "
1132 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001133 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001134 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1135 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001136 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001137 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001138 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001139 *os << "pre-requisite #" << i++ << "\n";
1140 }
1141 *os << " (end of pre-requisites)\n";
1142 } else {
1143 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001144 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001145 // is called only when the mock function call does NOT match the
1146 // expectation.
1147 *os << "The call matches the expectation.\n";
1148 }
1149 }
1150
1151 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001152 const Action<F>& GetCurrentAction(
1153 const FunctionMockerBase<F>* mocker,
1154 const ArgumentTuple& args) const
1155 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001156 g_gmock_mutex.AssertHeld();
1157 const int count = call_count();
1158 Assert(count >= 1, __FILE__, __LINE__,
1159 "call_count() is <= 0 when GetCurrentAction() is "
1160 "called - this should never happen.");
1161
zhanyong.waned6c9272011-02-23 19:39:27 +00001162 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001163 if (action_count > 0 && !repeated_action_specified_ &&
1164 count > action_count) {
1165 // If there is at least one WillOnce() and no WillRepeatedly(),
1166 // we warn the user when the WillOnce() clauses ran out.
1167 ::std::stringstream ss;
1168 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001169 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001170 << "Called " << count << " times, but only "
1171 << action_count << " WillOnce()"
1172 << (action_count == 1 ? " is" : "s are") << " specified - ";
1173 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001174 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001175 }
1176
zhanyong.waned6c9272011-02-23 19:39:27 +00001177 return count <= action_count ?
1178 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1179 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001180 }
1181
1182 // Given the arguments of a mock function call, if the call will
1183 // over-saturate this expectation, returns the default action;
1184 // otherwise, returns the next action in this expectation. Also
1185 // describes *what* happened to 'what', and explains *why* Google
1186 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001187 // IncrementCallCount(). A return value of NULL means the default
1188 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001189 const Action<F>* GetActionForArguments(
1190 const FunctionMockerBase<F>* mocker,
1191 const ArgumentTuple& args,
1192 ::std::ostream* what,
1193 ::std::ostream* why)
1194 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001195 g_gmock_mutex.AssertHeld();
1196 if (IsSaturated()) {
1197 // We have an excessive call.
1198 IncrementCallCount();
1199 *what << "Mock function called more times than expected - ";
1200 mocker->DescribeDefaultActionTo(args, what);
1201 DescribeCallCountTo(why);
1202
zhanyong.waned6c9272011-02-23 19:39:27 +00001203 // TODO(wan@google.com): allow the user to control whether
1204 // unexpected calls should fail immediately or continue using a
1205 // flag --gmock_unexpected_calls_are_fatal.
1206 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001207 }
1208
1209 IncrementCallCount();
1210 RetireAllPreRequisites();
1211
zhanyong.waned6c9272011-02-23 19:39:27 +00001212 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001213 Retire();
1214 }
1215
1216 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001217 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001218 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001219 }
1220
1221 // All the fields below won't change once the EXPECT_CALL()
1222 // statement finishes.
1223 FunctionMockerBase<F>* const owner_;
1224 ArgumentMatcherTuple matchers_;
1225 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001226 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001227
1228 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001229}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001230
1231// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1232// specifying the default behavior of, or expectation on, a mock
1233// function.
1234
1235// Note: class MockSpec really belongs to the ::testing namespace.
1236// However if we define it in ::testing, MSVC will complain when
1237// classes in ::testing::internal declare it as a friend class
1238// template. To workaround this compiler bug, we define MockSpec in
1239// ::testing::internal and import it into ::testing.
1240
zhanyong.waned6c9272011-02-23 19:39:27 +00001241// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001242GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1243 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001244 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001245
shiqiane35fdd92008-12-10 05:08:54 +00001246template <typename F>
1247class MockSpec {
1248 public:
1249 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1250 typedef typename internal::Function<F>::ArgumentMatcherTuple
1251 ArgumentMatcherTuple;
1252
1253 // Constructs a MockSpec object, given the function mocker object
1254 // that the spec is associated with.
1255 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1256 : function_mocker_(function_mocker) {}
1257
1258 // Adds a new default action spec to the function mocker and returns
1259 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001260 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001261 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001262 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001263 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001264 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001265 }
1266
1267 // Adds a new expectation spec to the function mocker and returns
1268 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001269 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001270 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001271 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1272 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001273 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001274 return function_mocker_->AddNewExpectation(
1275 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001276 }
1277
1278 private:
1279 template <typename Function>
1280 friend class internal::FunctionMocker;
1281
1282 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1283 matchers_ = matchers;
1284 }
1285
shiqiane35fdd92008-12-10 05:08:54 +00001286 // The function mocker that owns this spec.
1287 internal::FunctionMockerBase<F>* const function_mocker_;
1288 // The argument matchers specified in the spec.
1289 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001290
1291 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001292}; // class MockSpec
1293
kosakb5c81092014-01-29 06:41:44 +00001294// Wrapper type for generically holding an ordinary value or lvalue reference.
1295// If T is not a reference type, it must be copyable or movable.
1296// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1297// T is a move-only value type (which means that it will always be copyable
1298// if the current platform does not support move semantics).
1299//
1300// The primary template defines handling for values, but function header
1301// comments describe the contract for the whole template (including
1302// specializations).
1303template <typename T>
1304class ReferenceOrValueWrapper {
1305 public:
1306 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001307 explicit ReferenceOrValueWrapper(T value)
1308 : value_(::testing::internal::move(value)) {
1309 }
kosakb5c81092014-01-29 06:41:44 +00001310
1311 // Unwraps and returns the underlying value/reference, exactly as
1312 // originally passed. The behavior of calling this more than once on
1313 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001314 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001315
1316 // Provides nondestructive access to the underlying value/reference.
1317 // Always returns a const reference (more precisely,
1318 // const RemoveReference<T>&). The behavior of calling this after
1319 // calling Unwrap on the same object is unspecified.
1320 const T& Peek() const {
1321 return value_;
1322 }
1323
1324 private:
1325 T value_;
1326};
1327
1328// Specialization for lvalue reference types. See primary template
1329// for documentation.
1330template <typename T>
1331class ReferenceOrValueWrapper<T&> {
1332 public:
1333 // Workaround for debatable pass-by-reference lint warning (c-library-team
1334 // policy precludes NOLINT in this context)
1335 typedef T& reference;
1336 explicit ReferenceOrValueWrapper(reference ref)
1337 : value_ptr_(&ref) {}
1338 T& Unwrap() { return *value_ptr_; }
1339 const T& Peek() const { return *value_ptr_; }
1340
1341 private:
1342 T* value_ptr_;
1343};
1344
shiqiane35fdd92008-12-10 05:08:54 +00001345// MSVC warns about using 'this' in base member initializer list, so
1346// we need to temporarily disable the warning. We have to do it for
1347// the entire class to suppress the warning, even though it's about
1348// the constructor only.
1349
1350#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001351# pragma warning(push) // Saves the current warning state.
1352# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001353#endif // _MSV_VER
1354
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001355// C++ treats the void type specially. For example, you cannot define
1356// a void-typed variable or pass a void value to a function.
1357// ActionResultHolder<T> holds a value of type T, where T must be a
1358// copyable type or void (T doesn't need to be default-constructable).
1359// It hides the syntactic difference between void and other types, and
1360// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001361// non-void-returning mock functions.
1362
1363// Untyped base class for ActionResultHolder<T>.
1364class UntypedActionResultHolderBase {
1365 public:
1366 virtual ~UntypedActionResultHolderBase() {}
1367
1368 // Prints the held value as an action's result to os.
1369 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1370};
1371
1372// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001373template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001374class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001375 public:
kosakb5c81092014-01-29 06:41:44 +00001376 // Returns the held value. Must not be called more than once.
1377 T Unwrap() {
1378 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001379 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001380
1381 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001382 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001383 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001384 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001385 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001386 }
1387
1388 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001389 // result in a new-ed ActionResultHolder.
1390 template <typename F>
1391 static ActionResultHolder* PerformDefaultAction(
1392 const FunctionMockerBase<F>* func_mocker,
1393 const typename Function<F>::ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001394 const std::string& call_description) {
kosakb5c81092014-01-29 06:41:44 +00001395 return new ActionResultHolder(Wrapper(
1396 func_mocker->PerformDefaultAction(args, call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001397 }
1398
zhanyong.waned6c9272011-02-23 19:39:27 +00001399 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001400 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001401 template <typename F>
1402 static ActionResultHolder*
1403 PerformAction(const Action<F>& action,
1404 const typename Function<F>::ArgumentTuple& args) {
kosakb5c81092014-01-29 06:41:44 +00001405 return new ActionResultHolder(Wrapper(action.Perform(args)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001406 }
1407
1408 private:
kosakb5c81092014-01-29 06:41:44 +00001409 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001410
kosakd370f852014-11-17 01:14:16 +00001411 explicit ActionResultHolder(Wrapper result)
1412 : result_(::testing::internal::move(result)) {
1413 }
kosakb5c81092014-01-29 06:41:44 +00001414
1415 Wrapper result_;
1416
1417 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001418};
1419
1420// Specialization for T = void.
1421template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001422class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001423 public:
kosakb5c81092014-01-29 06:41:44 +00001424 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001425
zhanyong.waned6c9272011-02-23 19:39:27 +00001426 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1427
kosakb5c81092014-01-29 06:41:44 +00001428 // Performs the given mock function's default action and returns ownership
1429 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001430 template <typename F>
1431 static ActionResultHolder* PerformDefaultAction(
1432 const FunctionMockerBase<F>* func_mocker,
1433 const typename Function<F>::ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001434 const std::string& call_description) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001435 func_mocker->PerformDefaultAction(args, call_description);
kosakb5c81092014-01-29 06:41:44 +00001436 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001437 }
1438
kosakb5c81092014-01-29 06:41:44 +00001439 // Performs the given action and returns ownership of an empty
1440 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001441 template <typename F>
1442 static ActionResultHolder* PerformAction(
1443 const Action<F>& action,
1444 const typename Function<F>::ArgumentTuple& args) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001445 action.Perform(args);
kosakb5c81092014-01-29 06:41:44 +00001446 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001447 }
kosakb5c81092014-01-29 06:41:44 +00001448
1449 private:
1450 ActionResultHolder() {}
1451 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001452};
1453
shiqiane35fdd92008-12-10 05:08:54 +00001454// The base of the function mocker class for the given function type.
1455// We put the methods in this class instead of its child to avoid code
1456// bloat.
1457template <typename F>
1458class FunctionMockerBase : public UntypedFunctionMockerBase {
1459 public:
1460 typedef typename Function<F>::Result Result;
1461 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1462 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1463
zhanyong.waned6c9272011-02-23 19:39:27 +00001464 FunctionMockerBase() : current_spec_(this) {}
shiqiane35fdd92008-12-10 05:08:54 +00001465
1466 // The destructor verifies that all expectations on this mock
1467 // function have been satisfied. If not, it will report Google Test
1468 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001469 virtual ~FunctionMockerBase()
1470 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001471 MutexLock l(&g_gmock_mutex);
1472 VerifyAndClearExpectationsLocked();
1473 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001474 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001475 }
1476
1477 // Returns the ON_CALL spec that matches this mock function with the
1478 // given arguments; returns NULL if no matching ON_CALL is found.
1479 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001480 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001481 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001482 for (UntypedOnCallSpecs::const_reverse_iterator it
1483 = untyped_on_call_specs_.rbegin();
1484 it != untyped_on_call_specs_.rend(); ++it) {
1485 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1486 if (spec->Matches(args))
1487 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001488 }
1489
1490 return NULL;
1491 }
1492
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001493 // Performs the default action of this mock function on the given
1494 // arguments and returns the result. Asserts (or throws if
1495 // exceptions are enabled) with a helpful call descrption if there
1496 // is no valid return value. This method doesn't depend on the
1497 // mutable state of this object, and thus can be called concurrently
1498 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001499 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001500 Result PerformDefaultAction(const ArgumentTuple& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001501 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001502 const OnCallSpec<F>* const spec =
1503 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001504 if (spec != NULL) {
1505 return spec->GetAction().Perform(args);
1506 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001507 const std::string message =
1508 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001509 "\n The mock function has no default action "
1510 "set, and its return type has no default value set.";
1511#if GTEST_HAS_EXCEPTIONS
1512 if (!DefaultValue<Result>::Exists()) {
1513 throw std::runtime_error(message);
1514 }
1515#else
1516 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1517#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001518 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001519 }
1520
zhanyong.waned6c9272011-02-23 19:39:27 +00001521 // Performs the default action with the given arguments and returns
1522 // the action's result. The call description string will be used in
1523 // the error message to describe the call in the case the default
1524 // action fails. The caller is responsible for deleting the result.
1525 // L = *
1526 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1527 const void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001528 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001529 const ArgumentTuple& args =
1530 *static_cast<const ArgumentTuple*>(untyped_args);
1531 return ResultHolder::PerformDefaultAction(this, args, call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001532 }
1533
zhanyong.waned6c9272011-02-23 19:39:27 +00001534 // Performs the given action with the given arguments and returns
1535 // the action's result. The caller is responsible for deleting the
1536 // result.
1537 // L = *
1538 virtual UntypedActionResultHolderBase* UntypedPerformAction(
1539 const void* untyped_action, const void* untyped_args) const {
1540 // Make a copy of the action before performing it, in case the
1541 // action deletes the mock object (and thus deletes itself).
1542 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1543 const ArgumentTuple& args =
1544 *static_cast<const ArgumentTuple*>(untyped_args);
1545 return ResultHolder::PerformAction(action, args);
1546 }
shiqiane35fdd92008-12-10 05:08:54 +00001547
zhanyong.waned6c9272011-02-23 19:39:27 +00001548 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1549 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001550 virtual void ClearDefaultActionsLocked()
1551 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001552 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001553
1554 // Deleting our default actions may trigger other mock objects to be
1555 // deleted, for example if an action contains a reference counted smart
1556 // pointer to that mock object, and that is the last reference. So if we
1557 // delete our actions within the context of the global mutex we may deadlock
1558 // when this method is called again. Instead, make a copy of the set of
1559 // actions to delete, clear our set within the mutex, and then delete the
1560 // actions outside of the mutex.
1561 UntypedOnCallSpecs specs_to_delete;
1562 untyped_on_call_specs_.swap(specs_to_delete);
1563
1564 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001565 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001566 specs_to_delete.begin();
1567 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001568 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001569 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001570
1571 // Lock the mutex again, since the caller expects it to be locked when we
1572 // return.
1573 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001574 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001575
shiqiane35fdd92008-12-10 05:08:54 +00001576 protected:
1577 template <typename Function>
1578 friend class MockSpec;
1579
zhanyong.waned6c9272011-02-23 19:39:27 +00001580 typedef ActionResultHolder<Result> ResultHolder;
1581
shiqiane35fdd92008-12-10 05:08:54 +00001582 // Returns the result of invoking this mock function with the given
1583 // arguments. This function can be safely called from multiple
1584 // threads concurrently.
vladlosev4d60a592011-10-24 21:16:22 +00001585 Result InvokeWith(const ArgumentTuple& args)
1586 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
kosakb5c81092014-01-29 06:41:44 +00001587 scoped_ptr<ResultHolder> holder(
1588 DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args)));
1589 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001590 }
shiqiane35fdd92008-12-10 05:08:54 +00001591
1592 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001593 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001594 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001595 const ArgumentMatcherTuple& m)
1596 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001597 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001598 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1599 untyped_on_call_specs_.push_back(on_call_spec);
1600 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001601 }
1602
1603 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001604 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1605 const std::string& source_text,
1606 const ArgumentMatcherTuple& m)
1607 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001608 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001609 TypedExpectation<F>* const expectation =
1610 new TypedExpectation<F>(this, file, line, source_text, m);
1611 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1612 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001613
1614 // Adds this expectation into the implicit sequence if there is one.
1615 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1616 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001617 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001618 }
1619
1620 return *expectation;
1621 }
1622
1623 // The current spec (either default action spec or expectation spec)
1624 // being described on this function mocker.
1625 MockSpec<F>& current_spec() { return current_spec_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001626
shiqiane35fdd92008-12-10 05:08:54 +00001627 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001628 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001629
zhanyong.waned6c9272011-02-23 19:39:27 +00001630 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001631
1632 // Describes what default action will be performed for the given
1633 // arguments.
1634 // L = *
1635 void DescribeDefaultActionTo(const ArgumentTuple& args,
1636 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001637 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001638
1639 if (spec == NULL) {
1640 *os << (internal::type_equals<Result, void>::value ?
1641 "returning directly.\n" :
1642 "returning default value.\n");
1643 } else {
1644 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001645 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001646 }
1647 }
1648
1649 // Writes a message that the call is uninteresting (i.e. neither
1650 // explicitly expected nor explicitly unexpected) to the given
1651 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001652 virtual void UntypedDescribeUninterestingCall(
1653 const void* untyped_args,
1654 ::std::ostream* os) const
1655 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001656 const ArgumentTuple& args =
1657 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001658 *os << "Uninteresting mock function call - ";
1659 DescribeDefaultActionTo(args, os);
1660 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001661 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001662 }
1663
zhanyong.waned6c9272011-02-23 19:39:27 +00001664 // Returns the expectation that matches the given function arguments
1665 // (or NULL is there's no match); when a match is found,
1666 // untyped_action is set to point to the action that should be
1667 // performed (or NULL if the action is "do default"), and
1668 // is_excessive is modified to indicate whether the call exceeds the
1669 // expected number.
1670 //
shiqiane35fdd92008-12-10 05:08:54 +00001671 // Critical section: We must find the matching expectation and the
1672 // corresponding action that needs to be taken in an ATOMIC
1673 // transaction. Otherwise another thread may call this mock
1674 // method in the middle and mess up the state.
1675 //
1676 // However, performing the action has to be left out of the critical
1677 // section. The reason is that we have no control on what the
1678 // action does (it can invoke an arbitrary user function or even a
1679 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001680 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1681 const void* untyped_args,
1682 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001683 ::std::ostream* what, ::std::ostream* why)
1684 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001685 const ArgumentTuple& args =
1686 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001687 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001688 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1689 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001690 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001691 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001692 }
1693
1694 // This line must be done before calling GetActionForArguments(),
1695 // which will increment the call count for *exp and thus affect
1696 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001697 *is_excessive = exp->IsSaturated();
1698 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1699 if (action != NULL && action->IsDoDefault())
1700 action = NULL; // Normalize "do default" to NULL.
1701 *untyped_action = action;
1702 return exp;
1703 }
1704
1705 // Prints the given function arguments to the ostream.
1706 virtual void UntypedPrintArgs(const void* untyped_args,
1707 ::std::ostream* os) const {
1708 const ArgumentTuple& args =
1709 *static_cast<const ArgumentTuple*>(untyped_args);
1710 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001711 }
1712
1713 // Returns the expectation that matches the arguments, or NULL if no
1714 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001715 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001716 const ArgumentTuple& args) const
1717 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001718 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001719 for (typename UntypedExpectations::const_reverse_iterator it =
1720 untyped_expectations_.rbegin();
1721 it != untyped_expectations_.rend(); ++it) {
1722 TypedExpectation<F>* const exp =
1723 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001724 if (exp->ShouldHandleArguments(args)) {
1725 return exp;
1726 }
1727 }
1728 return NULL;
1729 }
1730
1731 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001732 void FormatUnexpectedCallMessageLocked(
1733 const ArgumentTuple& args,
1734 ::std::ostream* os,
1735 ::std::ostream* why) const
1736 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001737 g_gmock_mutex.AssertHeld();
1738 *os << "\nUnexpected mock function call - ";
1739 DescribeDefaultActionTo(args, os);
1740 PrintTriedExpectationsLocked(args, why);
1741 }
1742
1743 // Prints a list of expectations that have been tried against the
1744 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001745 void PrintTriedExpectationsLocked(
1746 const ArgumentTuple& args,
1747 ::std::ostream* why) const
1748 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001749 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001750 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001751 *why << "Google Mock tried the following " << count << " "
1752 << (count == 1 ? "expectation, but it didn't match" :
1753 "expectations, but none matched")
1754 << ":\n";
1755 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001756 TypedExpectation<F>* const expectation =
1757 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001758 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001759 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001760 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001761 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001762 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001763 *why << expectation->source_text() << "...\n";
1764 expectation->ExplainMatchResultTo(args, why);
1765 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001766 }
1767 }
1768
shiqiane35fdd92008-12-10 05:08:54 +00001769 // The current spec (either default action spec or expectation spec)
1770 // being described on this function mocker.
1771 MockSpec<F> current_spec_;
1772
zhanyong.wan16cf4732009-05-14 20:55:30 +00001773 // There is no generally useful and implementable semantics of
1774 // copying a mock object, so copying a mock is usually a user error.
1775 // Thus we disallow copying function mockers. If the user really
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +01001776 // wants to copy a mock object, they should implement their own copy
zhanyong.wan16cf4732009-05-14 20:55:30 +00001777 // operation, for example:
1778 //
1779 // class MockFoo : public Foo {
1780 // public:
1781 // // Defines a copy constructor explicitly.
1782 // MockFoo(const MockFoo& src) {}
1783 // ...
1784 // };
1785 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001786}; // class FunctionMockerBase
1787
1788#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001789# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001790#endif // _MSV_VER
1791
1792// Implements methods of FunctionMockerBase.
1793
1794// Verifies that all expectations on this mock function have been
1795// satisfied. Reports one or more Google Test non-fatal failures and
1796// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001797
1798// Reports an uninteresting call (whose description is in msg) in the
1799// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001800void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001801
shiqiane35fdd92008-12-10 05:08:54 +00001802} // namespace internal
1803
1804// The style guide prohibits "using" statements in a namespace scope
1805// inside a header file. However, the MockSpec class template is
1806// meant to be defined in the ::testing namespace. The following line
1807// is just a trick for working around a bug in MSVC 8.0, which cannot
1808// handle it if we define MockSpec in ::testing.
1809using internal::MockSpec;
1810
1811// Const(x) is a convenient function for obtaining a const reference
1812// to x. This is useful for setting expectations on an overloaded
1813// const mock method, e.g.
1814//
1815// class MockFoo : public FooInterface {
1816// public:
1817// MOCK_METHOD0(Bar, int());
1818// MOCK_CONST_METHOD0(Bar, int&());
1819// };
1820//
1821// MockFoo foo;
1822// // Expects a call to non-const MockFoo::Bar().
1823// EXPECT_CALL(foo, Bar());
1824// // Expects a call to const MockFoo::Bar().
1825// EXPECT_CALL(Const(foo), Bar());
1826template <typename T>
1827inline const T& Const(const T& x) { return x; }
1828
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001829// Constructs an Expectation object that references and co-owns exp.
1830inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1831 : expectation_base_(exp.GetHandle().expectation_base()) {}
1832
shiqiane35fdd92008-12-10 05:08:54 +00001833} // namespace testing
1834
1835// A separate macro is required to avoid compile errors when the name
1836// of the method used in call is a result of macro expansion.
1837// See CompilesWithMethodNameExpandedFromMacro tests in
1838// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001839#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001840 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1841 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001842#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001843
zhanyong.wane0d051e2009-02-19 00:33:37 +00001844#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001845 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001846#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001847
1848#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_