blob: 6d7f92002968a007038b576afda331e03450f885 [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
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400106// Uninteresting call behavior mixins.
107template <typename M> class NiceMockBase;
108template <typename M> class NaggyMockBase;
109template <typename M> class StrictMockBase;
110
shiqiane35fdd92008-12-10 05:08:54 +0000111// Protects the mock object registry (in class Mock), all function
112// mockers, and all expectations.
113//
114// The reason we don't use more fine-grained protection is: when a
115// mock function Foo() is called, it needs to consult its expectations
116// to see which one should be picked. If another thread is allowed to
117// call a mock function (either Foo() or a different one) at the same
118// time, it could affect the "retired" attributes of Foo()'s
119// expectations when InSequence() is used, and thus affect which
120// expectation gets picked. Therefore, we sequence all mock function
121// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000122GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000123
zhanyong.waned6c9272011-02-23 19:39:27 +0000124// Untyped base class for ActionResultHolder<R>.
125class UntypedActionResultHolderBase;
126
shiqiane35fdd92008-12-10 05:08:54 +0000127// Abstract base class of FunctionMockerBase. This is the
128// type-agnostic part of the function mocker interface. Its pure
129// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000130class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000131 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000132 UntypedFunctionMockerBase();
133 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000134
135 // Verifies that all expectations on this mock function have been
136 // satisfied. Reports one or more Google Test non-fatal failures
137 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000138 bool VerifyAndClearExpectationsLocked()
139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000140
141 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000142 virtual void ClearDefaultActionsLocked()
143 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000144
145 // In all of the following Untyped* functions, it's the caller's
146 // responsibility to guarantee the correctness of the arguments'
147 // types.
148
149 // Performs the default action with the given arguments and returns
150 // the action's result. The call description string will be used in
151 // the error message to describe the call in the case the default
152 // action fails.
153 // L = *
154 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400155 void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000156
157 // Performs the given action with the given arguments and returns
158 // the action's result.
159 // L = *
160 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400161 const void* untyped_action, void* untyped_args) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000162
163 // Writes a message that the call is uninteresting (i.e. neither
164 // explicitly expected nor explicitly unexpected) to the given
165 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +0000166 virtual void UntypedDescribeUninterestingCall(
167 const void* untyped_args,
168 ::std::ostream* os) const
169 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000170
171 // Returns the expectation that matches the given function arguments
172 // (or NULL is there's no match); when a match is found,
173 // untyped_action is set to point to the action that should be
174 // performed (or NULL if the action is "do default"), and
175 // is_excessive is modified to indicate whether the call exceeds the
176 // expected number.
zhanyong.waned6c9272011-02-23 19:39:27 +0000177 virtual const ExpectationBase* UntypedFindMatchingExpectation(
178 const void* untyped_args,
179 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000180 ::std::ostream* what, ::std::ostream* why)
181 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000182
183 // Prints the given function arguments to the ostream.
184 virtual void UntypedPrintArgs(const void* untyped_args,
185 ::std::ostream* os) const = 0;
186
187 // Sets the mock object this mock method belongs to, and registers
188 // this information in the global mock registry. Will be called
189 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
190 // method.
191 // TODO(wan@google.com): rename to SetAndRegisterOwner().
vladlosev4d60a592011-10-24 21:16:22 +0000192 void RegisterOwner(const void* mock_obj)
193 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000194
195 // Sets the mock object this mock method belongs to, and sets the
196 // name of the mock function. Will be called upon each invocation
197 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000198 void SetOwnerAndName(const void* mock_obj, const char* name)
199 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000200
201 // Returns the mock object this mock method belongs to. Must be
202 // called after RegisterOwner() or SetOwnerAndName() has been
203 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000204 const void* MockObject() const
205 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000206
207 // Returns the name of this mock method. Must be called after
208 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000209 const char* Name() const
210 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000211
212 // Returns the result of invoking this mock function with the given
213 // arguments. This function can be safely called from multiple
214 // threads concurrently. The caller is responsible for deleting the
215 // result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400216 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
217 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000218
219 protected:
220 typedef std::vector<const void*> UntypedOnCallSpecs;
221
222 typedef std::vector<internal::linked_ptr<ExpectationBase> >
223 UntypedExpectations;
224
225 // Returns an Expectation object that references and co-owns exp,
226 // which must be an expectation on this mock function.
227 Expectation GetHandleOf(ExpectationBase* exp);
228
229 // Address of the mock object this mock method belongs to. Only
230 // valid after this mock method has been called or
231 // ON_CALL/EXPECT_CALL has been invoked on it.
232 const void* mock_obj_; // Protected by g_gmock_mutex.
233
234 // Name of the function being mocked. Only valid after this mock
235 // method has been called.
236 const char* name_; // Protected by g_gmock_mutex.
237
238 // All default action specs for this function mocker.
239 UntypedOnCallSpecs untyped_on_call_specs_;
240
241 // All expectations for this function mocker.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400242 //
243 // It's undefined behavior to interleave expectations (EXPECT_CALLs
244 // or ON_CALLs) and mock function calls. Also, the order of
245 // expectations is important. Therefore it's a logic race condition
246 // to read/write untyped_expectations_ concurrently. In order for
247 // tools like tsan to catch concurrent read/write accesses to
248 // untyped_expectations, we deliberately leave accesses to it
249 // unprotected.
zhanyong.waned6c9272011-02-23 19:39:27 +0000250 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000251}; // class UntypedFunctionMockerBase
252
zhanyong.waned6c9272011-02-23 19:39:27 +0000253// Untyped base class for OnCallSpec<F>.
254class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000255 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000256 // The arguments are the location of the ON_CALL() statement.
257 UntypedOnCallSpecBase(const char* a_file, int a_line)
258 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000259
260 // Where in the source file was the default action spec defined?
261 const char* file() const { return file_; }
262 int line() const { return line_; }
263
zhanyong.waned6c9272011-02-23 19:39:27 +0000264 protected:
265 // Gives each clause in the ON_CALL() statement a name.
266 enum Clause {
267 // Do not change the order of the enum members! The run-time
268 // syntax checking relies on it.
269 kNone,
270 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000271 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000272 };
273
274 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400275 void AssertSpecProperty(bool property,
276 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000277 Assert(property, file_, line_, failure_message);
278 }
279
280 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400281 void ExpectSpecProperty(bool property,
282 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000283 Expect(property, file_, line_, failure_message);
284 }
285
286 const char* file_;
287 int line_;
288
289 // The last clause in the ON_CALL() statement as seen so far.
290 // Initially kNone and changes as the statement is parsed.
291 Clause last_clause_;
292}; // class UntypedOnCallSpecBase
293
294// This template class implements an ON_CALL spec.
295template <typename F>
296class OnCallSpec : public UntypedOnCallSpecBase {
297 public:
298 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
299 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
300
301 // Constructs an OnCallSpec object from the information inside
302 // the parenthesis of an ON_CALL() statement.
303 OnCallSpec(const char* a_file, int a_line,
304 const ArgumentMatcherTuple& matchers)
305 : UntypedOnCallSpecBase(a_file, a_line),
306 matchers_(matchers),
307 // By default, extra_matcher_ should match anything. However,
308 // we cannot initialize it with _ as that triggers a compiler
309 // bug in Symbian's C++ compiler (cannot decide between two
310 // overloaded constructors of Matcher<const ArgumentTuple&>).
311 extra_matcher_(A<const ArgumentTuple&>()) {
312 }
313
zhanyong.wanbf550852009-06-09 06:09:53 +0000314 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000315 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000316 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000317 ExpectSpecProperty(last_clause_ < kWith,
318 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000319 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000320 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000321
322 extra_matcher_ = m;
323 return *this;
324 }
325
326 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000327 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000328 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000329 ".WillByDefault() must appear "
330 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000331 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000332
333 ExpectSpecProperty(!action.IsDoDefault(),
334 "DoDefault() cannot be used in ON_CALL().");
335 action_ = action;
336 return *this;
337 }
338
339 // Returns true iff the given arguments match the matchers.
340 bool Matches(const ArgumentTuple& args) const {
341 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
342 }
343
344 // Returns the action specified by the user.
345 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000346 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000347 ".WillByDefault() must appear exactly "
348 "once in an ON_CALL().");
349 return action_;
350 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000351
shiqiane35fdd92008-12-10 05:08:54 +0000352 private:
shiqiane35fdd92008-12-10 05:08:54 +0000353 // The information in statement
354 //
355 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000356 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000357 // .WillByDefault(action);
358 //
359 // is recorded in the data members like this:
360 //
361 // source file that contains the statement => file_
362 // line number of the statement => line_
363 // matchers => matchers_
364 // multi-argument-matcher => extra_matcher_
365 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000366 ArgumentMatcherTuple matchers_;
367 Matcher<const ArgumentTuple&> extra_matcher_;
368 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000369}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000370
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000371// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000372enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000373 kAllow,
374 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000375 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000376};
377
378} // namespace internal
379
380// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000381class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000382 public:
383 // The following public methods can be called concurrently.
384
zhanyong.wandf35a762009-04-22 22:25:31 +0000385 // Tells Google Mock to ignore mock_obj when checking for leaked
386 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000387 static void AllowLeak(const void* mock_obj)
388 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000389
shiqiane35fdd92008-12-10 05:08:54 +0000390 // Verifies and clears all expectations on the given mock object.
391 // If the expectations aren't satisfied, generates one or more
392 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000393 static bool VerifyAndClearExpectations(void* mock_obj)
394 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000395
396 // Verifies all expectations on the given mock object and clears its
397 // default actions and expectations. Returns true iff the
398 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000399 static bool VerifyAndClear(void* mock_obj)
400 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000401
shiqiane35fdd92008-12-10 05:08:54 +0000402 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000403 friend class internal::UntypedFunctionMockerBase;
404
shiqiane35fdd92008-12-10 05:08:54 +0000405 // Needed for a function mocker to register itself (so that we know
406 // how to clear a mock object).
407 template <typename F>
408 friend class internal::FunctionMockerBase;
409
shiqiane35fdd92008-12-10 05:08:54 +0000410 template <typename M>
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400411 friend class internal::NiceMockBase;
shiqiane35fdd92008-12-10 05:08:54 +0000412
413 template <typename M>
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400414 friend class internal::NaggyMockBase;
zhanyong.wan844fa942013-03-01 01:54:22 +0000415
416 template <typename M>
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400417 friend class internal::StrictMockBase;
shiqiane35fdd92008-12-10 05:08:54 +0000418
419 // Tells Google Mock to allow uninteresting calls on the given mock
420 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000421 static void AllowUninterestingCalls(const void* mock_obj)
422 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000423
424 // Tells Google Mock to warn the user about uninteresting calls on
425 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000426 static void WarnUninterestingCalls(const void* mock_obj)
427 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000428
429 // Tells Google Mock to fail uninteresting calls on the given mock
430 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000431 static void FailUninterestingCalls(const void* mock_obj)
432 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000433
434 // Tells Google Mock the given mock object is being destroyed and
435 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000436 static void UnregisterCallReaction(const void* mock_obj)
437 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000438
439 // Returns the reaction Google Mock will have on uninteresting calls
440 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000441 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000442 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000443 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000444
445 // Verifies that all expectations on the given mock object have been
446 // satisfied. Reports one or more Google Test non-fatal failures
447 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000448 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
449 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000450
451 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000452 static void ClearDefaultActionsLocked(void* mock_obj)
453 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000454
455 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000456 static void Register(
457 const void* mock_obj,
458 internal::UntypedFunctionMockerBase* mocker)
459 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000460
zhanyong.wandf35a762009-04-22 22:25:31 +0000461 // Tells Google Mock where in the source code mock_obj is used in an
462 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
463 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000464 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000465 const void* mock_obj, const char* file, int line)
466 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000467
shiqiane35fdd92008-12-10 05:08:54 +0000468 // Unregisters a mock method; removes the owning mock object from
469 // the registry when the last mock method associated with it has
470 // been unregistered. This is called only in the destructor of
471 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000472 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
473 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000474}; // class Mock
475
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000476// An abstract handle of an expectation. Useful in the .After()
477// clause of EXPECT_CALL() for setting the (partial) order of
478// expectations. The syntax:
479//
480// Expectation e1 = EXPECT_CALL(...)...;
481// EXPECT_CALL(...).After(e1)...;
482//
483// sets two expectations where the latter can only be matched after
484// the former has been satisfied.
485//
486// Notes:
487// - This class is copyable and has value semantics.
488// - Constness is shallow: a const Expectation object itself cannot
489// be modified, but the mutable methods of the ExpectationBase
490// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000491// - The constructors and destructor are defined out-of-line because
492// the Symbian WINSCW compiler wants to otherwise instantiate them
493// when it sees this class definition, at which point it doesn't have
494// ExpectationBase available yet, leading to incorrect destruction
495// in the linked_ptr (or compilation errors if using a checking
496// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000497class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000498 public:
499 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000500 Expectation();
501
502 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000503
504 // This single-argument ctor must not be explicit, in order to support the
505 // Expectation e = EXPECT_CALL(...);
506 // syntax.
507 //
508 // A TypedExpectation object stores its pre-requisites as
509 // Expectation objects, and needs to call the non-const Retire()
510 // method on the ExpectationBase objects they reference. Therefore
511 // Expectation must receive a *non-const* reference to the
512 // ExpectationBase object.
513 Expectation(internal::ExpectationBase& exp); // NOLINT
514
515 // The compiler-generated copy ctor and operator= work exactly as
516 // intended, so we don't need to define our own.
517
518 // Returns true iff rhs references the same expectation as this object does.
519 bool operator==(const Expectation& rhs) const {
520 return expectation_base_ == rhs.expectation_base_;
521 }
522
523 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
524
525 private:
526 friend class ExpectationSet;
527 friend class Sequence;
528 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000529 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000530
531 template <typename F>
532 friend class ::testing::internal::FunctionMockerBase;
533
534 template <typename F>
535 friend class ::testing::internal::TypedExpectation;
536
537 // This comparator is needed for putting Expectation objects into a set.
538 class Less {
539 public:
540 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
541 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
542 }
543 };
544
545 typedef ::std::set<Expectation, Less> Set;
546
547 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000548 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000549
550 // Returns the expectation this object references.
551 const internal::linked_ptr<internal::ExpectationBase>&
552 expectation_base() const {
553 return expectation_base_;
554 }
555
556 // A linked_ptr that co-owns the expectation this handle references.
557 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
558};
559
560// A set of expectation handles. Useful in the .After() clause of
561// EXPECT_CALL() for setting the (partial) order of expectations. The
562// syntax:
563//
564// ExpectationSet es;
565// es += EXPECT_CALL(...)...;
566// es += EXPECT_CALL(...)...;
567// EXPECT_CALL(...).After(es)...;
568//
569// sets three expectations where the last one can only be matched
570// after the first two have both been satisfied.
571//
572// This class is copyable and has value semantics.
573class ExpectationSet {
574 public:
575 // A bidirectional iterator that can read a const element in the set.
576 typedef Expectation::Set::const_iterator const_iterator;
577
578 // An object stored in the set. This is an alias of Expectation.
579 typedef Expectation::Set::value_type value_type;
580
581 // Constructs an empty set.
582 ExpectationSet() {}
583
584 // This single-argument ctor must not be explicit, in order to support the
585 // ExpectationSet es = EXPECT_CALL(...);
586 // syntax.
587 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
588 *this += Expectation(exp);
589 }
590
591 // This single-argument ctor implements implicit conversion from
592 // Expectation and thus must not be explicit. This allows either an
593 // Expectation or an ExpectationSet to be used in .After().
594 ExpectationSet(const Expectation& e) { // NOLINT
595 *this += e;
596 }
597
598 // The compiler-generator ctor and operator= works exactly as
599 // intended, so we don't need to define our own.
600
601 // Returns true iff rhs contains the same set of Expectation objects
602 // as this does.
603 bool operator==(const ExpectationSet& rhs) const {
604 return expectations_ == rhs.expectations_;
605 }
606
607 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
608
609 // Implements the syntax
610 // expectation_set += EXPECT_CALL(...);
611 ExpectationSet& operator+=(const Expectation& e) {
612 expectations_.insert(e);
613 return *this;
614 }
615
616 int size() const { return static_cast<int>(expectations_.size()); }
617
618 const_iterator begin() const { return expectations_.begin(); }
619 const_iterator end() const { return expectations_.end(); }
620
621 private:
622 Expectation::Set expectations_;
623};
624
625
shiqiane35fdd92008-12-10 05:08:54 +0000626// Sequence objects are used by a user to specify the relative order
627// in which the expectations should match. They are copyable (we rely
628// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000629class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000630 public:
631 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000632 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000633
634 // Adds an expectation to this sequence. The caller must ensure
635 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000636 void AddExpectation(const Expectation& expectation) const;
637
shiqiane35fdd92008-12-10 05:08:54 +0000638 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000639 // The last expectation in this sequence. We use a linked_ptr here
640 // because Sequence objects are copyable and we want the copies to
641 // be aliases. The linked_ptr allows the copies to co-own and share
642 // the same Expectation object.
643 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000644}; // class Sequence
645
646// An object of this type causes all EXPECT_CALL() statements
647// encountered in its scope to be put in an anonymous sequence. The
648// work is done in the constructor and destructor. You should only
649// create an InSequence object on the stack.
650//
651// The sole purpose for this class is to support easy definition of
652// sequential expectations, e.g.
653//
654// {
655// InSequence dummy; // The name of the object doesn't matter.
656//
657// // The following expectations must match in the order they appear.
658// EXPECT_CALL(a, Bar())...;
659// EXPECT_CALL(a, Baz())...;
660// ...
661// EXPECT_CALL(b, Xyz())...;
662// }
663//
664// You can create InSequence objects in multiple threads, as long as
665// they are used to affect different mock objects. The idea is that
666// each thread can create and set up its own mocks as if it's the only
667// thread. However, for clarity of your tests we recommend you to set
668// up mocks in the main thread unless you have a good reason not to do
669// so.
vladlosev587c1b32011-05-20 00:42:22 +0000670class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000671 public:
672 InSequence();
673 ~InSequence();
674 private:
675 bool sequence_created_;
676
677 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000678} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000679
680namespace internal {
681
682// Points to the implicit sequence introduced by a living InSequence
683// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000684GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000685
686// Base class for implementing expectations.
687//
688// There are two reasons for having a type-agnostic base class for
689// Expectation:
690//
691// 1. We need to store collections of expectations of different
692// types (e.g. all pre-requisites of a particular expectation, all
693// expectations in a sequence). Therefore these expectation objects
694// must share a common base class.
695//
696// 2. We can avoid binary code bloat by moving methods not depending
697// on the template argument of Expectation to the base class.
698//
699// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000700class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000701 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000702 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400703 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000704
705 virtual ~ExpectationBase();
706
707 // Where in the source file was the expectation spec defined?
708 const char* file() const { return file_; }
709 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000710 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000711 // Returns the cardinality specified in the expectation spec.
712 const Cardinality& cardinality() const { return cardinality_; }
713
714 // Describes the source file location of this expectation.
715 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000716 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000717 }
718
719 // Describes how many times a function call matching this
720 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000721 void DescribeCallCountTo(::std::ostream* os) const
722 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000723
724 // If this mock method has an extra matcher (i.e. .With(matcher)),
725 // describes it to the ostream.
726 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000727
shiqiane35fdd92008-12-10 05:08:54 +0000728 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000729 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000730 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000731
732 enum Clause {
733 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000734 kNone,
735 kWith,
736 kTimes,
737 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000738 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000739 kWillOnce,
740 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000741 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000742 };
743
zhanyong.waned6c9272011-02-23 19:39:27 +0000744 typedef std::vector<const void*> UntypedActions;
745
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000746 // Returns an Expectation object that references and co-owns this
747 // expectation.
748 virtual Expectation GetHandle() = 0;
749
shiqiane35fdd92008-12-10 05:08:54 +0000750 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400751 void AssertSpecProperty(bool property,
752 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000753 Assert(property, file_, line_, failure_message);
754 }
755
756 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400757 void ExpectSpecProperty(bool property,
758 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000759 Expect(property, file_, line_, failure_message);
760 }
761
762 // Explicitly specifies the cardinality of this expectation. Used
763 // by the subclasses to implement the .Times() clause.
764 void SpecifyCardinality(const Cardinality& cardinality);
765
766 // Returns true iff the user specified the cardinality explicitly
767 // using a .Times().
768 bool cardinality_specified() const { return cardinality_specified_; }
769
770 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000771 void set_cardinality(const Cardinality& a_cardinality) {
772 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000773 }
774
775 // The following group of methods should only be called after the
776 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
777 // the current thread.
778
779 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000780 void RetireAllPreRequisites()
781 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000782
783 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000784 bool is_retired() const
785 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000786 g_gmock_mutex.AssertHeld();
787 return retired_;
788 }
789
790 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000791 void Retire()
792 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000793 g_gmock_mutex.AssertHeld();
794 retired_ = true;
795 }
796
797 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000798 bool IsSatisfied() const
799 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000800 g_gmock_mutex.AssertHeld();
801 return cardinality().IsSatisfiedByCallCount(call_count_);
802 }
803
804 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000805 bool IsSaturated() const
806 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000807 g_gmock_mutex.AssertHeld();
808 return cardinality().IsSaturatedByCallCount(call_count_);
809 }
810
811 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000812 bool IsOverSaturated() const
813 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000814 g_gmock_mutex.AssertHeld();
815 return cardinality().IsOverSaturatedByCallCount(call_count_);
816 }
817
818 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000819 bool AllPrerequisitesAreSatisfied() const
820 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000821
822 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000823 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
824 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000825
826 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000827 int call_count() const
828 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000829 g_gmock_mutex.AssertHeld();
830 return call_count_;
831 }
832
833 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000834 void IncrementCallCount()
835 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000836 g_gmock_mutex.AssertHeld();
837 call_count_++;
838 }
839
zhanyong.waned6c9272011-02-23 19:39:27 +0000840 // Checks the action count (i.e. the number of WillOnce() and
841 // WillRepeatedly() clauses) against the cardinality if this hasn't
842 // been done before. Prints a warning if there are too many or too
843 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000844 void CheckActionCountIfNotDone() const
845 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000846
shiqiane35fdd92008-12-10 05:08:54 +0000847 friend class ::testing::Sequence;
848 friend class ::testing::internal::ExpectationTester;
849
850 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000851 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000852
zhanyong.waned6c9272011-02-23 19:39:27 +0000853 // Implements the .Times() clause.
854 void UntypedTimes(const Cardinality& a_cardinality);
855
shiqiane35fdd92008-12-10 05:08:54 +0000856 // This group of fields are part of the spec and won't change after
857 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000858 const char* file_; // The file that contains the expectation.
859 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400860 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000861 // True iff the cardinality is specified explicitly.
862 bool cardinality_specified_;
863 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000864 // The immediate pre-requisites (i.e. expectations that must be
865 // satisfied before this expectation can be matched) of this
866 // expectation. We use linked_ptr in the set because we want an
867 // Expectation object to be co-owned by its FunctionMocker and its
868 // successors. This allows multiple mock objects to be deleted at
869 // different times.
870 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000871
872 // This group of fields are the current state of the expectation,
873 // and can change as the mock function is called.
874 int call_count_; // How many times this expectation has been invoked.
875 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000876 UntypedActions untyped_actions_;
877 bool extra_matcher_specified_;
878 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
879 bool retires_on_saturation_;
880 Clause last_clause_;
881 mutable bool action_count_checked_; // Under mutex_.
882 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000883
884 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000885}; // class ExpectationBase
886
887// Impements an expectation for the given function type.
888template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000889class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000890 public:
891 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
892 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
893 typedef typename Function<F>::Result Result;
894
Nico Weber09fd5b32017-05-15 17:07:03 -0400895 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
896 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000897 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000898 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000899 owner_(owner),
900 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000901 // By default, extra_matcher_ should match anything. However,
902 // we cannot initialize it with _ as that triggers a compiler
903 // bug in Symbian's C++ compiler (cannot decide between two
904 // overloaded constructors of Matcher<const ArgumentTuple&>).
905 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000906 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000907
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000908 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000909 // Check the validity of the action count if it hasn't been done
910 // yet (for example, if the expectation was never used).
911 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000912 for (UntypedActions::const_iterator it = untyped_actions_.begin();
913 it != untyped_actions_.end(); ++it) {
914 delete static_cast<const Action<F>*>(*it);
915 }
shiqiane35fdd92008-12-10 05:08:54 +0000916 }
917
zhanyong.wanbf550852009-06-09 06:09:53 +0000918 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000919 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000920 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000921 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000922 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000923 "more than once in an EXPECT_CALL().");
924 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000925 ExpectSpecProperty(last_clause_ < kWith,
926 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000927 "clause in an EXPECT_CALL().");
928 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000929 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000930
931 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000932 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000933 return *this;
934 }
935
936 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000937 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000938 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000939 return *this;
940 }
941
942 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000943 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000944 return Times(Exactly(n));
945 }
946
947 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000948 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000949 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000950 ".InSequence() cannot appear after .After(),"
951 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000952 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000953 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000954
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000955 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000956 return *this;
957 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000958 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000959 return InSequence(s1).InSequence(s2);
960 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000961 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
962 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000963 return InSequence(s1, s2).InSequence(s3);
964 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000965 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
966 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000967 return InSequence(s1, s2, s3).InSequence(s4);
968 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000969 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
970 const Sequence& s3, const Sequence& s4,
971 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000972 return InSequence(s1, s2, s3, s4).InSequence(s5);
973 }
974
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000975 // Implements that .After() clause.
976 TypedExpectation& After(const ExpectationSet& s) {
977 ExpectSpecProperty(last_clause_ <= kAfter,
978 ".After() cannot appear after .WillOnce(),"
979 " .WillRepeatedly(), or "
980 ".RetiresOnSaturation().");
981 last_clause_ = kAfter;
982
983 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
984 immediate_prerequisites_ += *it;
985 }
986 return *this;
987 }
988 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
989 return After(s1).After(s2);
990 }
991 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
992 const ExpectationSet& s3) {
993 return After(s1, s2).After(s3);
994 }
995 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
996 const ExpectationSet& s3, const ExpectationSet& s4) {
997 return After(s1, s2, s3).After(s4);
998 }
999 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
1000 const ExpectationSet& s3, const ExpectationSet& s4,
1001 const ExpectationSet& s5) {
1002 return After(s1, s2, s3, s4).After(s5);
1003 }
1004
shiqiane35fdd92008-12-10 05:08:54 +00001005 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001006 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001007 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +00001008 ".WillOnce() cannot appear after "
1009 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001010 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001011
zhanyong.waned6c9272011-02-23 19:39:27 +00001012 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001013 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001014 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001015 }
1016 return *this;
1017 }
1018
1019 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001020 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001021 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001022 ExpectSpecProperty(false,
1023 ".WillRepeatedly() cannot appear "
1024 "more than once in an EXPECT_CALL().");
1025 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001026 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001027 ".WillRepeatedly() cannot appear "
1028 "after .RetiresOnSaturation().");
1029 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001030 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001031 repeated_action_specified_ = true;
1032
1033 repeated_action_ = action;
1034 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001035 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001036 }
1037
1038 // Now that no more action clauses can be specified, we check
1039 // whether their count makes sense.
1040 CheckActionCountIfNotDone();
1041 return *this;
1042 }
1043
1044 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001045 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001046 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001047 ".RetiresOnSaturation() cannot appear "
1048 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001049 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001050 retires_on_saturation_ = true;
1051
1052 // Now that no more action clauses can be specified, we check
1053 // whether their count makes sense.
1054 CheckActionCountIfNotDone();
1055 return *this;
1056 }
1057
1058 // Returns the matchers for the arguments as specified inside the
1059 // EXPECT_CALL() macro.
1060 const ArgumentMatcherTuple& matchers() const {
1061 return matchers_;
1062 }
1063
zhanyong.wanbf550852009-06-09 06:09:53 +00001064 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001065 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1066 return extra_matcher_;
1067 }
1068
shiqiane35fdd92008-12-10 05:08:54 +00001069 // Returns the action specified by the .WillRepeatedly() clause.
1070 const Action<F>& repeated_action() const { return repeated_action_; }
1071
zhanyong.waned6c9272011-02-23 19:39:27 +00001072 // If this mock method has an extra matcher (i.e. .With(matcher)),
1073 // describes it to the ostream.
1074 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001075 if (extra_matcher_specified_) {
1076 *os << " Expected args: ";
1077 extra_matcher_.DescribeTo(os);
1078 *os << "\n";
1079 }
1080 }
1081
shiqiane35fdd92008-12-10 05:08:54 +00001082 private:
1083 template <typename Function>
1084 friend class FunctionMockerBase;
1085
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001086 // Returns an Expectation object that references and co-owns this
1087 // expectation.
1088 virtual Expectation GetHandle() {
1089 return owner_->GetHandleOf(this);
1090 }
1091
shiqiane35fdd92008-12-10 05:08:54 +00001092 // The following methods will be called only after the EXPECT_CALL()
1093 // statement finishes and when the current thread holds
1094 // g_gmock_mutex.
1095
1096 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001097 bool Matches(const ArgumentTuple& args) const
1098 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001099 g_gmock_mutex.AssertHeld();
1100 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1101 }
1102
1103 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001104 bool ShouldHandleArguments(const ArgumentTuple& args) const
1105 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001106 g_gmock_mutex.AssertHeld();
1107
1108 // In case the action count wasn't checked when the expectation
1109 // was defined (e.g. if this expectation has no WillRepeatedly()
1110 // or RetiresOnSaturation() clause), we check it when the
1111 // expectation is used for the first time.
1112 CheckActionCountIfNotDone();
1113 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1114 }
1115
1116 // Describes the result of matching the arguments against this
1117 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001118 void ExplainMatchResultTo(
1119 const ArgumentTuple& args,
1120 ::std::ostream* os) const
1121 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001122 g_gmock_mutex.AssertHeld();
1123
1124 if (is_retired()) {
1125 *os << " Expected: the expectation is active\n"
1126 << " Actual: it is retired\n";
1127 } else if (!Matches(args)) {
1128 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001129 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001130 }
zhanyong.wan82113312010-01-08 21:55:40 +00001131 StringMatchResultListener listener;
1132 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001133 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001134 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001135 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001136
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001137 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001138 *os << "\n";
1139 }
1140 } else if (!AllPrerequisitesAreSatisfied()) {
1141 *os << " Expected: all pre-requisites are satisfied\n"
1142 << " Actual: the following immediate pre-requisites "
1143 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001144 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001145 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1146 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001147 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001148 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001149 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001150 *os << "pre-requisite #" << i++ << "\n";
1151 }
1152 *os << " (end of pre-requisites)\n";
1153 } else {
1154 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001155 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001156 // is called only when the mock function call does NOT match the
1157 // expectation.
1158 *os << "The call matches the expectation.\n";
1159 }
1160 }
1161
1162 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001163 const Action<F>& GetCurrentAction(
1164 const FunctionMockerBase<F>* mocker,
1165 const ArgumentTuple& args) const
1166 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001167 g_gmock_mutex.AssertHeld();
1168 const int count = call_count();
1169 Assert(count >= 1, __FILE__, __LINE__,
1170 "call_count() is <= 0 when GetCurrentAction() is "
1171 "called - this should never happen.");
1172
zhanyong.waned6c9272011-02-23 19:39:27 +00001173 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001174 if (action_count > 0 && !repeated_action_specified_ &&
1175 count > action_count) {
1176 // If there is at least one WillOnce() and no WillRepeatedly(),
1177 // we warn the user when the WillOnce() clauses ran out.
1178 ::std::stringstream ss;
1179 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001180 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001181 << "Called " << count << " times, but only "
1182 << action_count << " WillOnce()"
1183 << (action_count == 1 ? " is" : "s are") << " specified - ";
1184 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001185 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001186 }
1187
zhanyong.waned6c9272011-02-23 19:39:27 +00001188 return count <= action_count ?
1189 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1190 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001191 }
1192
1193 // Given the arguments of a mock function call, if the call will
1194 // over-saturate this expectation, returns the default action;
1195 // otherwise, returns the next action in this expectation. Also
1196 // describes *what* happened to 'what', and explains *why* Google
1197 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001198 // IncrementCallCount(). A return value of NULL means the default
1199 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001200 const Action<F>* GetActionForArguments(
1201 const FunctionMockerBase<F>* mocker,
1202 const ArgumentTuple& args,
1203 ::std::ostream* what,
1204 ::std::ostream* why)
1205 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001206 g_gmock_mutex.AssertHeld();
1207 if (IsSaturated()) {
1208 // We have an excessive call.
1209 IncrementCallCount();
1210 *what << "Mock function called more times than expected - ";
1211 mocker->DescribeDefaultActionTo(args, what);
1212 DescribeCallCountTo(why);
1213
zhanyong.waned6c9272011-02-23 19:39:27 +00001214 // TODO(wan@google.com): allow the user to control whether
1215 // unexpected calls should fail immediately or continue using a
1216 // flag --gmock_unexpected_calls_are_fatal.
1217 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001218 }
1219
1220 IncrementCallCount();
1221 RetireAllPreRequisites();
1222
zhanyong.waned6c9272011-02-23 19:39:27 +00001223 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001224 Retire();
1225 }
1226
1227 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001228 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001229 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001230 }
1231
1232 // All the fields below won't change once the EXPECT_CALL()
1233 // statement finishes.
1234 FunctionMockerBase<F>* const owner_;
1235 ArgumentMatcherTuple matchers_;
1236 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001237 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001238
1239 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001240}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001241
1242// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1243// specifying the default behavior of, or expectation on, a mock
1244// function.
1245
1246// Note: class MockSpec really belongs to the ::testing namespace.
1247// However if we define it in ::testing, MSVC will complain when
1248// classes in ::testing::internal declare it as a friend class
1249// template. To workaround this compiler bug, we define MockSpec in
1250// ::testing::internal and import it into ::testing.
1251
zhanyong.waned6c9272011-02-23 19:39:27 +00001252// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001253GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1254 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001255 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001256
shiqiane35fdd92008-12-10 05:08:54 +00001257template <typename F>
1258class MockSpec {
1259 public:
1260 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1261 typedef typename internal::Function<F>::ArgumentMatcherTuple
1262 ArgumentMatcherTuple;
1263
1264 // Constructs a MockSpec object, given the function mocker object
1265 // that the spec is associated with.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001266 MockSpec(internal::FunctionMockerBase<F>* function_mocker,
1267 const ArgumentMatcherTuple& matchers)
1268 : function_mocker_(function_mocker), matchers_(matchers) {}
shiqiane35fdd92008-12-10 05:08:54 +00001269
1270 // Adds a new default action spec to the function mocker and returns
1271 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001272 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001273 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001274 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001275 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001276 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001277 }
1278
1279 // Adds a new expectation spec to the function mocker and returns
1280 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001281 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001282 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001283 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1284 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001285 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001286 return function_mocker_->AddNewExpectation(
1287 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001288 }
1289
1290 private:
1291 template <typename Function>
1292 friend class internal::FunctionMocker;
1293
shiqiane35fdd92008-12-10 05:08:54 +00001294 // The function mocker that owns this spec.
1295 internal::FunctionMockerBase<F>* const function_mocker_;
1296 // The argument matchers specified in the spec.
1297 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001298
1299 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001300}; // class MockSpec
1301
kosakb5c81092014-01-29 06:41:44 +00001302// Wrapper type for generically holding an ordinary value or lvalue reference.
1303// If T is not a reference type, it must be copyable or movable.
1304// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1305// T is a move-only value type (which means that it will always be copyable
1306// if the current platform does not support move semantics).
1307//
1308// The primary template defines handling for values, but function header
1309// comments describe the contract for the whole template (including
1310// specializations).
1311template <typename T>
1312class ReferenceOrValueWrapper {
1313 public:
1314 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001315 explicit ReferenceOrValueWrapper(T value)
1316 : value_(::testing::internal::move(value)) {
1317 }
kosakb5c81092014-01-29 06:41:44 +00001318
1319 // Unwraps and returns the underlying value/reference, exactly as
1320 // originally passed. The behavior of calling this more than once on
1321 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001322 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001323
1324 // Provides nondestructive access to the underlying value/reference.
1325 // Always returns a const reference (more precisely,
1326 // const RemoveReference<T>&). The behavior of calling this after
1327 // calling Unwrap on the same object is unspecified.
1328 const T& Peek() const {
1329 return value_;
1330 }
1331
1332 private:
1333 T value_;
1334};
1335
1336// Specialization for lvalue reference types. See primary template
1337// for documentation.
1338template <typename T>
1339class ReferenceOrValueWrapper<T&> {
1340 public:
1341 // Workaround for debatable pass-by-reference lint warning (c-library-team
1342 // policy precludes NOLINT in this context)
1343 typedef T& reference;
1344 explicit ReferenceOrValueWrapper(reference ref)
1345 : value_ptr_(&ref) {}
1346 T& Unwrap() { return *value_ptr_; }
1347 const T& Peek() const { return *value_ptr_; }
1348
1349 private:
1350 T* value_ptr_;
1351};
1352
shiqiane35fdd92008-12-10 05:08:54 +00001353// MSVC warns about using 'this' in base member initializer list, so
1354// we need to temporarily disable the warning. We have to do it for
1355// the entire class to suppress the warning, even though it's about
1356// the constructor only.
1357
1358#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001359# pragma warning(push) // Saves the current warning state.
1360# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001361#endif // _MSV_VER
1362
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001363// C++ treats the void type specially. For example, you cannot define
1364// a void-typed variable or pass a void value to a function.
1365// ActionResultHolder<T> holds a value of type T, where T must be a
1366// copyable type or void (T doesn't need to be default-constructable).
1367// It hides the syntactic difference between void and other types, and
1368// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001369// non-void-returning mock functions.
1370
1371// Untyped base class for ActionResultHolder<T>.
1372class UntypedActionResultHolderBase {
1373 public:
1374 virtual ~UntypedActionResultHolderBase() {}
1375
1376 // Prints the held value as an action's result to os.
1377 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1378};
1379
1380// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001381template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001382class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001383 public:
kosakb5c81092014-01-29 06:41:44 +00001384 // Returns the held value. Must not be called more than once.
1385 T Unwrap() {
1386 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001387 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001388
1389 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001390 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001391 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001392 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001393 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001394 }
1395
1396 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001397 // result in a new-ed ActionResultHolder.
1398 template <typename F>
1399 static ActionResultHolder* PerformDefaultAction(
1400 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001401 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001402 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001403 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1404 internal::move(args), call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001405 }
1406
zhanyong.waned6c9272011-02-23 19:39:27 +00001407 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001408 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001409 template <typename F>
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001410 static ActionResultHolder* PerformAction(
1411 const Action<F>& action,
1412 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1413 return new ActionResultHolder(
1414 Wrapper(action.Perform(internal::move(args))));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001415 }
1416
1417 private:
kosakb5c81092014-01-29 06:41:44 +00001418 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001419
kosakd370f852014-11-17 01:14:16 +00001420 explicit ActionResultHolder(Wrapper result)
1421 : result_(::testing::internal::move(result)) {
1422 }
kosakb5c81092014-01-29 06:41:44 +00001423
1424 Wrapper result_;
1425
1426 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001427};
1428
1429// Specialization for T = void.
1430template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001431class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001432 public:
kosakb5c81092014-01-29 06:41:44 +00001433 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001434
zhanyong.waned6c9272011-02-23 19:39:27 +00001435 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1436
kosakb5c81092014-01-29 06:41:44 +00001437 // Performs the given mock function's default action and returns ownership
1438 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001439 template <typename F>
1440 static ActionResultHolder* PerformDefaultAction(
1441 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001442 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001443 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001444 func_mocker->PerformDefaultAction(internal::move(args), call_description);
kosakb5c81092014-01-29 06:41:44 +00001445 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001446 }
1447
kosakb5c81092014-01-29 06:41:44 +00001448 // Performs the given action and returns ownership of an empty
1449 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001450 template <typename F>
1451 static ActionResultHolder* PerformAction(
1452 const Action<F>& action,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001453 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1454 action.Perform(internal::move(args));
kosakb5c81092014-01-29 06:41:44 +00001455 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001456 }
kosakb5c81092014-01-29 06:41:44 +00001457
1458 private:
1459 ActionResultHolder() {}
1460 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001461};
1462
shiqiane35fdd92008-12-10 05:08:54 +00001463// The base of the function mocker class for the given function type.
1464// We put the methods in this class instead of its child to avoid code
1465// bloat.
1466template <typename F>
1467class FunctionMockerBase : public UntypedFunctionMockerBase {
1468 public:
1469 typedef typename Function<F>::Result Result;
1470 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1471 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1472
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001473 FunctionMockerBase() {}
shiqiane35fdd92008-12-10 05:08:54 +00001474
1475 // The destructor verifies that all expectations on this mock
1476 // function have been satisfied. If not, it will report Google Test
1477 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001478 virtual ~FunctionMockerBase()
1479 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001480 MutexLock l(&g_gmock_mutex);
1481 VerifyAndClearExpectationsLocked();
1482 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001483 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001484 }
1485
1486 // Returns the ON_CALL spec that matches this mock function with the
1487 // given arguments; returns NULL if no matching ON_CALL is found.
1488 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001489 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001490 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001491 for (UntypedOnCallSpecs::const_reverse_iterator it
1492 = untyped_on_call_specs_.rbegin();
1493 it != untyped_on_call_specs_.rend(); ++it) {
1494 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1495 if (spec->Matches(args))
1496 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001497 }
1498
1499 return NULL;
1500 }
1501
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001502 // Performs the default action of this mock function on the given
1503 // arguments and returns the result. Asserts (or throws if
1504 // exceptions are enabled) with a helpful call descrption if there
1505 // is no valid return value. This method doesn't depend on the
1506 // mutable state of this object, and thus can be called concurrently
1507 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001508 // L = *
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001509 Result PerformDefaultAction(
1510 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1511 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001512 const OnCallSpec<F>* const spec =
1513 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001514 if (spec != NULL) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001515 return spec->GetAction().Perform(internal::move(args));
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001516 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001517 const std::string message =
1518 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001519 "\n The mock function has no default action "
1520 "set, and its return type has no default value set.";
1521#if GTEST_HAS_EXCEPTIONS
1522 if (!DefaultValue<Result>::Exists()) {
1523 throw std::runtime_error(message);
1524 }
1525#else
1526 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1527#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001528 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001529 }
1530
zhanyong.waned6c9272011-02-23 19:39:27 +00001531 // Performs the default action with the given arguments and returns
1532 // the action's result. The call description string will be used in
1533 // the error message to describe the call in the case the default
1534 // action fails. The caller is responsible for deleting the result.
1535 // L = *
1536 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001537 void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001538 const std::string& call_description) const {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001539 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1540 return ResultHolder::PerformDefaultAction(this, internal::move(*args),
1541 call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001542 }
1543
zhanyong.waned6c9272011-02-23 19:39:27 +00001544 // Performs the given action with the given arguments and returns
1545 // the action's result. The caller is responsible for deleting the
1546 // result.
1547 // L = *
1548 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001549 const void* untyped_action, void* untyped_args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001550 // Make a copy of the action before performing it, in case the
1551 // action deletes the mock object (and thus deletes itself).
1552 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001553 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1554 return ResultHolder::PerformAction(action, internal::move(*args));
zhanyong.waned6c9272011-02-23 19:39:27 +00001555 }
shiqiane35fdd92008-12-10 05:08:54 +00001556
zhanyong.waned6c9272011-02-23 19:39:27 +00001557 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1558 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001559 virtual void ClearDefaultActionsLocked()
1560 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001561 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001562
1563 // Deleting our default actions may trigger other mock objects to be
1564 // deleted, for example if an action contains a reference counted smart
1565 // pointer to that mock object, and that is the last reference. So if we
1566 // delete our actions within the context of the global mutex we may deadlock
1567 // when this method is called again. Instead, make a copy of the set of
1568 // actions to delete, clear our set within the mutex, and then delete the
1569 // actions outside of the mutex.
1570 UntypedOnCallSpecs specs_to_delete;
1571 untyped_on_call_specs_.swap(specs_to_delete);
1572
1573 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001574 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001575 specs_to_delete.begin();
1576 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001577 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001578 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001579
1580 // Lock the mutex again, since the caller expects it to be locked when we
1581 // return.
1582 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001583 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001584
shiqiane35fdd92008-12-10 05:08:54 +00001585 protected:
1586 template <typename Function>
1587 friend class MockSpec;
1588
zhanyong.waned6c9272011-02-23 19:39:27 +00001589 typedef ActionResultHolder<Result> ResultHolder;
1590
shiqiane35fdd92008-12-10 05:08:54 +00001591 // Returns the result of invoking this mock function with the given
1592 // arguments. This function can be safely called from multiple
1593 // threads concurrently.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001594 Result InvokeWith(
1595 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args)
1596 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1597 // const_cast is required since in C++98 we still pass ArgumentTuple around
1598 // by const& instead of rvalue reference.
1599 void* untyped_args = const_cast<void*>(static_cast<const void*>(&args));
kosakb5c81092014-01-29 06:41:44 +00001600 scoped_ptr<ResultHolder> holder(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001601 DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args)));
kosakb5c81092014-01-29 06:41:44 +00001602 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001603 }
shiqiane35fdd92008-12-10 05:08:54 +00001604
1605 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001606 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001607 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001608 const ArgumentMatcherTuple& m)
1609 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001610 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001611 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1612 untyped_on_call_specs_.push_back(on_call_spec);
1613 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001614 }
1615
1616 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001617 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1618 const std::string& source_text,
1619 const ArgumentMatcherTuple& m)
1620 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001621 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001622 TypedExpectation<F>* const expectation =
1623 new TypedExpectation<F>(this, file, line, source_text, m);
1624 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001625 // See the definition of untyped_expectations_ for why access to
1626 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001627 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001628
1629 // Adds this expectation into the implicit sequence if there is one.
1630 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1631 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001632 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001633 }
1634
1635 return *expectation;
1636 }
1637
shiqiane35fdd92008-12-10 05:08:54 +00001638 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001639 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001640
zhanyong.waned6c9272011-02-23 19:39:27 +00001641 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001642
1643 // Describes what default action will be performed for the given
1644 // arguments.
1645 // L = *
1646 void DescribeDefaultActionTo(const ArgumentTuple& args,
1647 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001648 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001649
1650 if (spec == NULL) {
1651 *os << (internal::type_equals<Result, void>::value ?
1652 "returning directly.\n" :
1653 "returning default value.\n");
1654 } else {
1655 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001656 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001657 }
1658 }
1659
1660 // Writes a message that the call is uninteresting (i.e. neither
1661 // explicitly expected nor explicitly unexpected) to the given
1662 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001663 virtual void UntypedDescribeUninterestingCall(
1664 const void* untyped_args,
1665 ::std::ostream* os) const
1666 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001667 const ArgumentTuple& args =
1668 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001669 *os << "Uninteresting mock function call - ";
1670 DescribeDefaultActionTo(args, os);
1671 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001672 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001673 }
1674
zhanyong.waned6c9272011-02-23 19:39:27 +00001675 // Returns the expectation that matches the given function arguments
1676 // (or NULL is there's no match); when a match is found,
1677 // untyped_action is set to point to the action that should be
1678 // performed (or NULL if the action is "do default"), and
1679 // is_excessive is modified to indicate whether the call exceeds the
1680 // expected number.
1681 //
shiqiane35fdd92008-12-10 05:08:54 +00001682 // Critical section: We must find the matching expectation and the
1683 // corresponding action that needs to be taken in an ATOMIC
1684 // transaction. Otherwise another thread may call this mock
1685 // method in the middle and mess up the state.
1686 //
1687 // However, performing the action has to be left out of the critical
1688 // section. The reason is that we have no control on what the
1689 // action does (it can invoke an arbitrary user function or even a
1690 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001691 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1692 const void* untyped_args,
1693 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001694 ::std::ostream* what, ::std::ostream* why)
1695 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001696 const ArgumentTuple& args =
1697 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001698 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001699 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1700 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001701 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001702 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001703 }
1704
1705 // This line must be done before calling GetActionForArguments(),
1706 // which will increment the call count for *exp and thus affect
1707 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001708 *is_excessive = exp->IsSaturated();
1709 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1710 if (action != NULL && action->IsDoDefault())
1711 action = NULL; // Normalize "do default" to NULL.
1712 *untyped_action = action;
1713 return exp;
1714 }
1715
1716 // Prints the given function arguments to the ostream.
1717 virtual void UntypedPrintArgs(const void* untyped_args,
1718 ::std::ostream* os) const {
1719 const ArgumentTuple& args =
1720 *static_cast<const ArgumentTuple*>(untyped_args);
1721 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001722 }
1723
1724 // Returns the expectation that matches the arguments, or NULL if no
1725 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001726 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001727 const ArgumentTuple& args) const
1728 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001729 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001730 // See the definition of untyped_expectations_ for why access to
1731 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001732 for (typename UntypedExpectations::const_reverse_iterator it =
1733 untyped_expectations_.rbegin();
1734 it != untyped_expectations_.rend(); ++it) {
1735 TypedExpectation<F>* const exp =
1736 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001737 if (exp->ShouldHandleArguments(args)) {
1738 return exp;
1739 }
1740 }
1741 return NULL;
1742 }
1743
1744 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001745 void FormatUnexpectedCallMessageLocked(
1746 const ArgumentTuple& args,
1747 ::std::ostream* os,
1748 ::std::ostream* why) const
1749 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001750 g_gmock_mutex.AssertHeld();
1751 *os << "\nUnexpected mock function call - ";
1752 DescribeDefaultActionTo(args, os);
1753 PrintTriedExpectationsLocked(args, why);
1754 }
1755
1756 // Prints a list of expectations that have been tried against the
1757 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001758 void PrintTriedExpectationsLocked(
1759 const ArgumentTuple& args,
1760 ::std::ostream* why) const
1761 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001762 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001763 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001764 *why << "Google Mock tried the following " << count << " "
1765 << (count == 1 ? "expectation, but it didn't match" :
1766 "expectations, but none matched")
1767 << ":\n";
1768 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001769 TypedExpectation<F>* const expectation =
1770 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001771 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001772 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001773 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001774 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001775 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001776 *why << expectation->source_text() << "...\n";
1777 expectation->ExplainMatchResultTo(args, why);
1778 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001779 }
1780 }
1781
zhanyong.wan16cf4732009-05-14 20:55:30 +00001782 // There is no generally useful and implementable semantics of
1783 // copying a mock object, so copying a mock is usually a user error.
1784 // Thus we disallow copying function mockers. If the user really
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +01001785 // wants to copy a mock object, they should implement their own copy
zhanyong.wan16cf4732009-05-14 20:55:30 +00001786 // operation, for example:
1787 //
1788 // class MockFoo : public Foo {
1789 // public:
1790 // // Defines a copy constructor explicitly.
1791 // MockFoo(const MockFoo& src) {}
1792 // ...
1793 // };
1794 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001795}; // class FunctionMockerBase
1796
1797#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001798# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001799#endif // _MSV_VER
1800
1801// Implements methods of FunctionMockerBase.
1802
1803// Verifies that all expectations on this mock function have been
1804// satisfied. Reports one or more Google Test non-fatal failures and
1805// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001806
1807// Reports an uninteresting call (whose description is in msg) in the
1808// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001809void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001810
shiqiane35fdd92008-12-10 05:08:54 +00001811} // namespace internal
1812
1813// The style guide prohibits "using" statements in a namespace scope
1814// inside a header file. However, the MockSpec class template is
1815// meant to be defined in the ::testing namespace. The following line
1816// is just a trick for working around a bug in MSVC 8.0, which cannot
1817// handle it if we define MockSpec in ::testing.
1818using internal::MockSpec;
1819
1820// Const(x) is a convenient function for obtaining a const reference
1821// to x. This is useful for setting expectations on an overloaded
1822// const mock method, e.g.
1823//
1824// class MockFoo : public FooInterface {
1825// public:
1826// MOCK_METHOD0(Bar, int());
1827// MOCK_CONST_METHOD0(Bar, int&());
1828// };
1829//
1830// MockFoo foo;
1831// // Expects a call to non-const MockFoo::Bar().
1832// EXPECT_CALL(foo, Bar());
1833// // Expects a call to const MockFoo::Bar().
1834// EXPECT_CALL(Const(foo), Bar());
1835template <typename T>
1836inline const T& Const(const T& x) { return x; }
1837
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001838// Constructs an Expectation object that references and co-owns exp.
1839inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1840 : expectation_base_(exp.GetHandle().expectation_base()) {}
1841
shiqiane35fdd92008-12-10 05:08:54 +00001842} // namespace testing
1843
1844// A separate macro is required to avoid compile errors when the name
1845// of the method used in call is a result of macro expansion.
1846// See CompilesWithMethodNameExpandedFromMacro tests in
1847// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001848#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001849 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1850 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001851#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001852
zhanyong.wane0d051e2009-02-19 00:33:37 +00001853#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001854 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001855#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001856
1857#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_