blob: 0d83cd6f76f78cb543275fdfdbb903e817480a37 [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.
Gennadiy Civila3c0dd02018-08-14 14:04:07 -040029
shiqiane35fdd92008-12-10 05:08:54 +000030
31// Google Mock - a framework for writing C++ mock classes.
32//
33// This file implements the ON_CALL() and EXPECT_CALL() macros.
34//
35// A user can use the ON_CALL() macro to specify the default action of
36// a mock method. The syntax is:
37//
38// ON_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000039// .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +000040// .WillByDefault(action);
41//
zhanyong.wanbf550852009-06-09 06:09:53 +000042// where the .With() clause is optional.
shiqiane35fdd92008-12-10 05:08:54 +000043//
44// A user can use the EXPECT_CALL() macro to specify an expectation on
45// a mock method. The syntax is:
46//
47// EXPECT_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000048// .With(multi-argument-matchers)
shiqiane35fdd92008-12-10 05:08:54 +000049// .Times(cardinality)
50// .InSequence(sequences)
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000051// .After(expectations)
shiqiane35fdd92008-12-10 05:08:54 +000052// .WillOnce(action)
53// .WillRepeatedly(action)
54// .RetiresOnSaturation();
55//
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000056// where all clauses are optional, and .InSequence()/.After()/
57// .WillOnce() can appear any number of times.
shiqiane35fdd92008-12-10 05:08:54 +000058
Gennadiy Civil984cba32018-07-27 11:15:08 -040059// GOOGLETEST_CM0002 DO NOT DELETE
60
shiqiane35fdd92008-12-10 05:08:54 +000061#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
63
64#include <map>
65#include <set>
66#include <sstream>
67#include <string>
68#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000069#include "gmock/gmock-actions.h"
70#include "gmock/gmock-cardinalities.h"
71#include "gmock/gmock-matchers.h"
72#include "gmock/internal/gmock-internal-utils.h"
73#include "gmock/internal/gmock-port.h"
74#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000075
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050076#if GTEST_HAS_EXCEPTIONS
77# include <stdexcept> // NOLINT
78#endif
79
shiqiane35fdd92008-12-10 05:08:54 +000080namespace testing {
81
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000082// An abstract handle of an expectation.
83class Expectation;
84
85// A set of expectation handles.
86class ExpectationSet;
87
shiqiane35fdd92008-12-10 05:08:54 +000088// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
89// and MUST NOT BE USED IN USER CODE!!!
90namespace internal {
91
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000092// Implements a mock function.
93template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000094
95// Base class for expectations.
96class ExpectationBase;
97
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000098// Implements an expectation.
99template <typename F> class TypedExpectation;
100
shiqiane35fdd92008-12-10 05:08:54 +0000101// Helper class for testing the Expectation class template.
102class ExpectationTester;
103
104// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000105template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000106
shiqiane35fdd92008-12-10 05:08:54 +0000107// Protects the mock object registry (in class Mock), all function
108// mockers, and all expectations.
109//
110// The reason we don't use more fine-grained protection is: when a
111// mock function Foo() is called, it needs to consult its expectations
112// to see which one should be picked. If another thread is allowed to
113// call a mock function (either Foo() or a different one) at the same
114// time, it could affect the "retired" attributes of Foo()'s
115// expectations when InSequence() is used, and thus affect which
116// expectation gets picked. Therefore, we sequence all mock function
117// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000118GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000119
zhanyong.waned6c9272011-02-23 19:39:27 +0000120// Untyped base class for ActionResultHolder<R>.
121class UntypedActionResultHolderBase;
122
shiqiane35fdd92008-12-10 05:08:54 +0000123// Abstract base class of FunctionMockerBase. This is the
124// type-agnostic part of the function mocker interface. Its pure
125// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000126class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000127 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000128 UntypedFunctionMockerBase();
129 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000130
131 // Verifies that all expectations on this mock function have been
132 // satisfied. Reports one or more Google Test non-fatal failures
133 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000134 bool VerifyAndClearExpectationsLocked()
135 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000136
137 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000138 virtual void ClearDefaultActionsLocked()
139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000140
141 // In all of the following Untyped* functions, it's the caller's
142 // responsibility to guarantee the correctness of the arguments'
143 // types.
144
145 // Performs the default action with the given arguments and returns
146 // the action's result. The call description string will be used in
147 // the error message to describe the call in the case the default
148 // action fails.
149 // L = *
150 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400151 void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000152
153 // Performs the given action with the given arguments and returns
154 // the action's result.
155 // L = *
156 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400157 const void* untyped_action, void* untyped_args) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000158
159 // Writes a message that the call is uninteresting (i.e. neither
160 // explicitly expected nor explicitly unexpected) to the given
161 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +0000162 virtual void UntypedDescribeUninterestingCall(
163 const void* untyped_args,
164 ::std::ostream* os) const
165 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000166
167 // Returns the expectation that matches the given function arguments
168 // (or NULL is there's no match); when a match is found,
169 // untyped_action is set to point to the action that should be
170 // performed (or NULL if the action is "do default"), and
171 // is_excessive is modified to indicate whether the call exceeds the
172 // expected number.
zhanyong.waned6c9272011-02-23 19:39:27 +0000173 virtual const ExpectationBase* UntypedFindMatchingExpectation(
174 const void* untyped_args,
175 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000176 ::std::ostream* what, ::std::ostream* why)
177 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000178
179 // Prints the given function arguments to the ostream.
180 virtual void UntypedPrintArgs(const void* untyped_args,
181 ::std::ostream* os) const = 0;
182
183 // Sets the mock object this mock method belongs to, and registers
184 // this information in the global mock registry. Will be called
185 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
186 // method.
Gennadiy Civil265efde2018-08-14 15:04:11 -0400187 // FIXME: rename to SetAndRegisterOwner().
vladlosev4d60a592011-10-24 21:16:22 +0000188 void RegisterOwner(const void* mock_obj)
189 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000190
191 // Sets the mock object this mock method belongs to, and sets the
192 // name of the mock function. Will be called upon each invocation
193 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000194 void SetOwnerAndName(const void* mock_obj, const char* name)
195 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000196
197 // Returns the mock object this mock method belongs to. Must be
198 // called after RegisterOwner() or SetOwnerAndName() has been
199 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000200 const void* MockObject() const
201 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000202
203 // Returns the name of this mock method. Must be called after
204 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000205 const char* Name() const
206 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000207
208 // Returns the result of invoking this mock function with the given
209 // arguments. This function can be safely called from multiple
210 // threads concurrently. The caller is responsible for deleting the
211 // result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400212 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
213 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000214
215 protected:
216 typedef std::vector<const void*> UntypedOnCallSpecs;
217
218 typedef std::vector<internal::linked_ptr<ExpectationBase> >
219 UntypedExpectations;
220
221 // Returns an Expectation object that references and co-owns exp,
222 // which must be an expectation on this mock function.
223 Expectation GetHandleOf(ExpectationBase* exp);
224
225 // Address of the mock object this mock method belongs to. Only
226 // valid after this mock method has been called or
227 // ON_CALL/EXPECT_CALL has been invoked on it.
228 const void* mock_obj_; // Protected by g_gmock_mutex.
229
230 // Name of the function being mocked. Only valid after this mock
231 // method has been called.
232 const char* name_; // Protected by g_gmock_mutex.
233
234 // All default action specs for this function mocker.
235 UntypedOnCallSpecs untyped_on_call_specs_;
236
237 // All expectations for this function mocker.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400238 //
239 // It's undefined behavior to interleave expectations (EXPECT_CALLs
240 // or ON_CALLs) and mock function calls. Also, the order of
241 // expectations is important. Therefore it's a logic race condition
242 // to read/write untyped_expectations_ concurrently. In order for
243 // tools like tsan to catch concurrent read/write accesses to
244 // untyped_expectations, we deliberately leave accesses to it
245 // unprotected.
zhanyong.waned6c9272011-02-23 19:39:27 +0000246 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000247}; // class UntypedFunctionMockerBase
248
zhanyong.waned6c9272011-02-23 19:39:27 +0000249// Untyped base class for OnCallSpec<F>.
250class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000251 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000252 // The arguments are the location of the ON_CALL() statement.
253 UntypedOnCallSpecBase(const char* a_file, int a_line)
254 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000255
256 // Where in the source file was the default action spec defined?
257 const char* file() const { return file_; }
258 int line() const { return line_; }
259
zhanyong.waned6c9272011-02-23 19:39:27 +0000260 protected:
261 // Gives each clause in the ON_CALL() statement a name.
262 enum Clause {
263 // Do not change the order of the enum members! The run-time
264 // syntax checking relies on it.
265 kNone,
266 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000267 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000268 };
269
270 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400271 void AssertSpecProperty(bool property,
272 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000273 Assert(property, file_, line_, failure_message);
274 }
275
276 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400277 void ExpectSpecProperty(bool property,
278 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000279 Expect(property, file_, line_, failure_message);
280 }
281
282 const char* file_;
283 int line_;
284
285 // The last clause in the ON_CALL() statement as seen so far.
286 // Initially kNone and changes as the statement is parsed.
287 Clause last_clause_;
288}; // class UntypedOnCallSpecBase
289
290// This template class implements an ON_CALL spec.
291template <typename F>
292class OnCallSpec : public UntypedOnCallSpecBase {
293 public:
294 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
295 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
296
297 // Constructs an OnCallSpec object from the information inside
298 // the parenthesis of an ON_CALL() statement.
299 OnCallSpec(const char* a_file, int a_line,
300 const ArgumentMatcherTuple& matchers)
301 : UntypedOnCallSpecBase(a_file, a_line),
302 matchers_(matchers),
303 // By default, extra_matcher_ should match anything. However,
304 // we cannot initialize it with _ as that triggers a compiler
305 // bug in Symbian's C++ compiler (cannot decide between two
306 // overloaded constructors of Matcher<const ArgumentTuple&>).
307 extra_matcher_(A<const ArgumentTuple&>()) {
308 }
309
zhanyong.wanbf550852009-06-09 06:09:53 +0000310 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000311 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000312 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000313 ExpectSpecProperty(last_clause_ < kWith,
314 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000315 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000316 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000317
318 extra_matcher_ = m;
319 return *this;
320 }
321
322 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000323 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000324 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000325 ".WillByDefault() must appear "
326 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000327 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000328
329 ExpectSpecProperty(!action.IsDoDefault(),
330 "DoDefault() cannot be used in ON_CALL().");
331 action_ = action;
332 return *this;
333 }
334
335 // Returns true iff the given arguments match the matchers.
336 bool Matches(const ArgumentTuple& args) const {
337 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
338 }
339
340 // Returns the action specified by the user.
341 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000342 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000343 ".WillByDefault() must appear exactly "
344 "once in an ON_CALL().");
345 return action_;
346 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000347
shiqiane35fdd92008-12-10 05:08:54 +0000348 private:
shiqiane35fdd92008-12-10 05:08:54 +0000349 // The information in statement
350 //
351 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000352 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000353 // .WillByDefault(action);
354 //
355 // is recorded in the data members like this:
356 //
357 // source file that contains the statement => file_
358 // line number of the statement => line_
359 // matchers => matchers_
360 // multi-argument-matcher => extra_matcher_
361 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000362 ArgumentMatcherTuple matchers_;
363 Matcher<const ArgumentTuple&> extra_matcher_;
364 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000365}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000366
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000367// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000368enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000369 kAllow,
370 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000371 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000372};
373
374} // namespace internal
375
376// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000377class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000378 public:
379 // The following public methods can be called concurrently.
380
zhanyong.wandf35a762009-04-22 22:25:31 +0000381 // Tells Google Mock to ignore mock_obj when checking for leaked
382 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000383 static void AllowLeak(const void* mock_obj)
384 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000385
shiqiane35fdd92008-12-10 05:08:54 +0000386 // Verifies and clears all expectations on the given mock object.
387 // If the expectations aren't satisfied, generates one or more
388 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000389 static bool VerifyAndClearExpectations(void* mock_obj)
390 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000391
392 // Verifies all expectations on the given mock object and clears its
393 // default actions and expectations. Returns true iff the
394 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000395 static bool VerifyAndClear(void* mock_obj)
396 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000397
shiqiane35fdd92008-12-10 05:08:54 +0000398 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000399 friend class internal::UntypedFunctionMockerBase;
400
shiqiane35fdd92008-12-10 05:08:54 +0000401 // Needed for a function mocker to register itself (so that we know
402 // how to clear a mock object).
403 template <typename F>
404 friend class internal::FunctionMockerBase;
405
shiqiane35fdd92008-12-10 05:08:54 +0000406 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700407 friend class NiceMock;
shiqiane35fdd92008-12-10 05:08:54 +0000408
409 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700410 friend class NaggyMock;
zhanyong.wan844fa942013-03-01 01:54:22 +0000411
412 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700413 friend class StrictMock;
shiqiane35fdd92008-12-10 05:08:54 +0000414
415 // Tells Google Mock to allow uninteresting calls on the given mock
416 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000417 static void AllowUninterestingCalls(const void* mock_obj)
418 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000419
420 // Tells Google Mock to warn the user about uninteresting calls on
421 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000422 static void WarnUninterestingCalls(const void* mock_obj)
423 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000424
425 // Tells Google Mock to fail uninteresting calls on the given mock
426 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000427 static void FailUninterestingCalls(const void* mock_obj)
428 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000429
430 // Tells Google Mock the given mock object is being destroyed and
431 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000432 static void UnregisterCallReaction(const void* mock_obj)
433 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000434
435 // Returns the reaction Google Mock will have on uninteresting calls
436 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000437 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000438 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000439 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000440
441 // Verifies that all expectations on the given mock object have been
442 // satisfied. Reports one or more Google Test non-fatal failures
443 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000444 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
445 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000446
447 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000448 static void ClearDefaultActionsLocked(void* mock_obj)
449 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000450
451 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000452 static void Register(
453 const void* mock_obj,
454 internal::UntypedFunctionMockerBase* mocker)
455 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000456
zhanyong.wandf35a762009-04-22 22:25:31 +0000457 // Tells Google Mock where in the source code mock_obj is used in an
458 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
459 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000460 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000461 const void* mock_obj, const char* file, int line)
462 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000463
shiqiane35fdd92008-12-10 05:08:54 +0000464 // Unregisters a mock method; removes the owning mock object from
465 // the registry when the last mock method associated with it has
466 // been unregistered. This is called only in the destructor of
467 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000468 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
469 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000470}; // class Mock
471
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000472// An abstract handle of an expectation. Useful in the .After()
473// clause of EXPECT_CALL() for setting the (partial) order of
474// expectations. The syntax:
475//
476// Expectation e1 = EXPECT_CALL(...)...;
477// EXPECT_CALL(...).After(e1)...;
478//
479// sets two expectations where the latter can only be matched after
480// the former has been satisfied.
481//
482// Notes:
483// - This class is copyable and has value semantics.
484// - Constness is shallow: a const Expectation object itself cannot
485// be modified, but the mutable methods of the ExpectationBase
486// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000487// - The constructors and destructor are defined out-of-line because
488// the Symbian WINSCW compiler wants to otherwise instantiate them
489// when it sees this class definition, at which point it doesn't have
490// ExpectationBase available yet, leading to incorrect destruction
491// in the linked_ptr (or compilation errors if using a checking
492// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000493class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000494 public:
495 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000496 Expectation();
497
498 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000499
500 // This single-argument ctor must not be explicit, in order to support the
501 // Expectation e = EXPECT_CALL(...);
502 // syntax.
503 //
504 // A TypedExpectation object stores its pre-requisites as
505 // Expectation objects, and needs to call the non-const Retire()
506 // method on the ExpectationBase objects they reference. Therefore
507 // Expectation must receive a *non-const* reference to the
508 // ExpectationBase object.
509 Expectation(internal::ExpectationBase& exp); // NOLINT
510
511 // The compiler-generated copy ctor and operator= work exactly as
512 // intended, so we don't need to define our own.
513
514 // Returns true iff rhs references the same expectation as this object does.
515 bool operator==(const Expectation& rhs) const {
516 return expectation_base_ == rhs.expectation_base_;
517 }
518
519 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
520
521 private:
522 friend class ExpectationSet;
523 friend class Sequence;
524 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000525 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000526
527 template <typename F>
528 friend class ::testing::internal::FunctionMockerBase;
529
530 template <typename F>
531 friend class ::testing::internal::TypedExpectation;
532
533 // This comparator is needed for putting Expectation objects into a set.
534 class Less {
535 public:
536 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
537 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
538 }
539 };
540
541 typedef ::std::set<Expectation, Less> Set;
542
543 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000544 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000545
546 // Returns the expectation this object references.
547 const internal::linked_ptr<internal::ExpectationBase>&
548 expectation_base() const {
549 return expectation_base_;
550 }
551
552 // A linked_ptr that co-owns the expectation this handle references.
553 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
554};
555
556// A set of expectation handles. Useful in the .After() clause of
557// EXPECT_CALL() for setting the (partial) order of expectations. The
558// syntax:
559//
560// ExpectationSet es;
561// es += EXPECT_CALL(...)...;
562// es += EXPECT_CALL(...)...;
563// EXPECT_CALL(...).After(es)...;
564//
565// sets three expectations where the last one can only be matched
566// after the first two have both been satisfied.
567//
568// This class is copyable and has value semantics.
569class ExpectationSet {
570 public:
571 // A bidirectional iterator that can read a const element in the set.
572 typedef Expectation::Set::const_iterator const_iterator;
573
574 // An object stored in the set. This is an alias of Expectation.
575 typedef Expectation::Set::value_type value_type;
576
577 // Constructs an empty set.
578 ExpectationSet() {}
579
580 // This single-argument ctor must not be explicit, in order to support the
581 // ExpectationSet es = EXPECT_CALL(...);
582 // syntax.
583 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
584 *this += Expectation(exp);
585 }
586
587 // This single-argument ctor implements implicit conversion from
588 // Expectation and thus must not be explicit. This allows either an
589 // Expectation or an ExpectationSet to be used in .After().
590 ExpectationSet(const Expectation& e) { // NOLINT
591 *this += e;
592 }
593
594 // The compiler-generator ctor and operator= works exactly as
595 // intended, so we don't need to define our own.
596
597 // Returns true iff rhs contains the same set of Expectation objects
598 // as this does.
599 bool operator==(const ExpectationSet& rhs) const {
600 return expectations_ == rhs.expectations_;
601 }
602
603 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
604
605 // Implements the syntax
606 // expectation_set += EXPECT_CALL(...);
607 ExpectationSet& operator+=(const Expectation& e) {
608 expectations_.insert(e);
609 return *this;
610 }
611
612 int size() const { return static_cast<int>(expectations_.size()); }
613
614 const_iterator begin() const { return expectations_.begin(); }
615 const_iterator end() const { return expectations_.end(); }
616
617 private:
618 Expectation::Set expectations_;
619};
620
621
shiqiane35fdd92008-12-10 05:08:54 +0000622// Sequence objects are used by a user to specify the relative order
623// in which the expectations should match. They are copyable (we rely
624// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000625class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000626 public:
627 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000628 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000629
630 // Adds an expectation to this sequence. The caller must ensure
631 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000632 void AddExpectation(const Expectation& expectation) const;
633
shiqiane35fdd92008-12-10 05:08:54 +0000634 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000635 // The last expectation in this sequence. We use a linked_ptr here
636 // because Sequence objects are copyable and we want the copies to
637 // be aliases. The linked_ptr allows the copies to co-own and share
638 // the same Expectation object.
639 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000640}; // class Sequence
641
642// An object of this type causes all EXPECT_CALL() statements
643// encountered in its scope to be put in an anonymous sequence. The
644// work is done in the constructor and destructor. You should only
645// create an InSequence object on the stack.
646//
647// The sole purpose for this class is to support easy definition of
648// sequential expectations, e.g.
649//
650// {
651// InSequence dummy; // The name of the object doesn't matter.
652//
653// // The following expectations must match in the order they appear.
654// EXPECT_CALL(a, Bar())...;
655// EXPECT_CALL(a, Baz())...;
656// ...
657// EXPECT_CALL(b, Xyz())...;
658// }
659//
660// You can create InSequence objects in multiple threads, as long as
661// they are used to affect different mock objects. The idea is that
662// each thread can create and set up its own mocks as if it's the only
663// thread. However, for clarity of your tests we recommend you to set
664// up mocks in the main thread unless you have a good reason not to do
665// so.
vladlosev587c1b32011-05-20 00:42:22 +0000666class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000667 public:
668 InSequence();
669 ~InSequence();
670 private:
671 bool sequence_created_;
672
673 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000674} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000675
676namespace internal {
677
678// Points to the implicit sequence introduced by a living InSequence
679// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000680GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000681
682// Base class for implementing expectations.
683//
684// There are two reasons for having a type-agnostic base class for
685// Expectation:
686//
687// 1. We need to store collections of expectations of different
688// types (e.g. all pre-requisites of a particular expectation, all
689// expectations in a sequence). Therefore these expectation objects
690// must share a common base class.
691//
692// 2. We can avoid binary code bloat by moving methods not depending
693// on the template argument of Expectation to the base class.
694//
695// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000696class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000697 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000698 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400699 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000700
701 virtual ~ExpectationBase();
702
703 // Where in the source file was the expectation spec defined?
704 const char* file() const { return file_; }
705 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000706 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000707 // Returns the cardinality specified in the expectation spec.
708 const Cardinality& cardinality() const { return cardinality_; }
709
710 // Describes the source file location of this expectation.
711 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000712 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000713 }
714
715 // Describes how many times a function call matching this
716 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000717 void DescribeCallCountTo(::std::ostream* os) const
718 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000719
720 // If this mock method has an extra matcher (i.e. .With(matcher)),
721 // describes it to the ostream.
722 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000723
shiqiane35fdd92008-12-10 05:08:54 +0000724 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000725 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000726 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000727
728 enum Clause {
729 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000730 kNone,
731 kWith,
732 kTimes,
733 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000734 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000735 kWillOnce,
736 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000737 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000738 };
739
zhanyong.waned6c9272011-02-23 19:39:27 +0000740 typedef std::vector<const void*> UntypedActions;
741
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000742 // Returns an Expectation object that references and co-owns this
743 // expectation.
744 virtual Expectation GetHandle() = 0;
745
shiqiane35fdd92008-12-10 05:08:54 +0000746 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400747 void AssertSpecProperty(bool property,
748 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000749 Assert(property, file_, line_, failure_message);
750 }
751
752 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400753 void ExpectSpecProperty(bool property,
754 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000755 Expect(property, file_, line_, failure_message);
756 }
757
758 // Explicitly specifies the cardinality of this expectation. Used
759 // by the subclasses to implement the .Times() clause.
760 void SpecifyCardinality(const Cardinality& cardinality);
761
762 // Returns true iff the user specified the cardinality explicitly
763 // using a .Times().
764 bool cardinality_specified() const { return cardinality_specified_; }
765
766 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000767 void set_cardinality(const Cardinality& a_cardinality) {
768 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000769 }
770
771 // The following group of methods should only be called after the
772 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
773 // the current thread.
774
775 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000776 void RetireAllPreRequisites()
777 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000778
779 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000780 bool is_retired() const
781 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000782 g_gmock_mutex.AssertHeld();
783 return retired_;
784 }
785
786 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000787 void Retire()
788 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000789 g_gmock_mutex.AssertHeld();
790 retired_ = true;
791 }
792
793 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000794 bool IsSatisfied() const
795 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000796 g_gmock_mutex.AssertHeld();
797 return cardinality().IsSatisfiedByCallCount(call_count_);
798 }
799
800 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000801 bool IsSaturated() const
802 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000803 g_gmock_mutex.AssertHeld();
804 return cardinality().IsSaturatedByCallCount(call_count_);
805 }
806
807 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000808 bool IsOverSaturated() const
809 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000810 g_gmock_mutex.AssertHeld();
811 return cardinality().IsOverSaturatedByCallCount(call_count_);
812 }
813
814 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000815 bool AllPrerequisitesAreSatisfied() const
816 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000817
818 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000819 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
820 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000821
822 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000823 int call_count() const
824 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000825 g_gmock_mutex.AssertHeld();
826 return call_count_;
827 }
828
829 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000830 void IncrementCallCount()
831 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000832 g_gmock_mutex.AssertHeld();
833 call_count_++;
834 }
835
zhanyong.waned6c9272011-02-23 19:39:27 +0000836 // Checks the action count (i.e. the number of WillOnce() and
837 // WillRepeatedly() clauses) against the cardinality if this hasn't
838 // been done before. Prints a warning if there are too many or too
839 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000840 void CheckActionCountIfNotDone() const
841 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000842
shiqiane35fdd92008-12-10 05:08:54 +0000843 friend class ::testing::Sequence;
844 friend class ::testing::internal::ExpectationTester;
845
846 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000847 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000848
zhanyong.waned6c9272011-02-23 19:39:27 +0000849 // Implements the .Times() clause.
850 void UntypedTimes(const Cardinality& a_cardinality);
851
shiqiane35fdd92008-12-10 05:08:54 +0000852 // This group of fields are part of the spec and won't change after
853 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000854 const char* file_; // The file that contains the expectation.
855 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400856 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000857 // True iff the cardinality is specified explicitly.
858 bool cardinality_specified_;
859 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000860 // The immediate pre-requisites (i.e. expectations that must be
861 // satisfied before this expectation can be matched) of this
862 // expectation. We use linked_ptr in the set because we want an
863 // Expectation object to be co-owned by its FunctionMocker and its
864 // successors. This allows multiple mock objects to be deleted at
865 // different times.
866 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000867
868 // This group of fields are the current state of the expectation,
869 // and can change as the mock function is called.
870 int call_count_; // How many times this expectation has been invoked.
871 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000872 UntypedActions untyped_actions_;
873 bool extra_matcher_specified_;
874 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
875 bool retires_on_saturation_;
876 Clause last_clause_;
877 mutable bool action_count_checked_; // Under mutex_.
878 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000879
880 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000881}; // class ExpectationBase
882
883// Impements an expectation for the given function type.
884template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000885class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000886 public:
887 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
888 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
889 typedef typename Function<F>::Result Result;
890
Nico Weber09fd5b32017-05-15 17:07:03 -0400891 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
892 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000893 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000894 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000895 owner_(owner),
896 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000897 // By default, extra_matcher_ should match anything. However,
898 // we cannot initialize it with _ as that triggers a compiler
899 // bug in Symbian's C++ compiler (cannot decide between two
900 // overloaded constructors of Matcher<const ArgumentTuple&>).
901 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000902 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000903
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000904 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000905 // Check the validity of the action count if it hasn't been done
906 // yet (for example, if the expectation was never used).
907 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000908 for (UntypedActions::const_iterator it = untyped_actions_.begin();
909 it != untyped_actions_.end(); ++it) {
910 delete static_cast<const Action<F>*>(*it);
911 }
shiqiane35fdd92008-12-10 05:08:54 +0000912 }
913
zhanyong.wanbf550852009-06-09 06:09:53 +0000914 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000915 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000916 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000917 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000918 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000919 "more than once in an EXPECT_CALL().");
920 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000921 ExpectSpecProperty(last_clause_ < kWith,
922 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000923 "clause in an EXPECT_CALL().");
924 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000925 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000926
927 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000928 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000929 return *this;
930 }
931
932 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000933 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000934 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000935 return *this;
936 }
937
938 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000939 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000940 return Times(Exactly(n));
941 }
942
943 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000944 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000945 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000946 ".InSequence() cannot appear after .After(),"
947 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000948 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000949 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000950
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000951 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000952 return *this;
953 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000954 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000955 return InSequence(s1).InSequence(s2);
956 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000957 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
958 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000959 return InSequence(s1, s2).InSequence(s3);
960 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000961 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
962 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000963 return InSequence(s1, s2, s3).InSequence(s4);
964 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000965 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
966 const Sequence& s3, const Sequence& s4,
967 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000968 return InSequence(s1, s2, s3, s4).InSequence(s5);
969 }
970
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000971 // Implements that .After() clause.
972 TypedExpectation& After(const ExpectationSet& s) {
973 ExpectSpecProperty(last_clause_ <= kAfter,
974 ".After() cannot appear after .WillOnce(),"
975 " .WillRepeatedly(), or "
976 ".RetiresOnSaturation().");
977 last_clause_ = kAfter;
978
979 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
980 immediate_prerequisites_ += *it;
981 }
982 return *this;
983 }
984 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
985 return After(s1).After(s2);
986 }
987 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
988 const ExpectationSet& s3) {
989 return After(s1, s2).After(s3);
990 }
991 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
992 const ExpectationSet& s3, const ExpectationSet& s4) {
993 return After(s1, s2, s3).After(s4);
994 }
995 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
996 const ExpectationSet& s3, const ExpectationSet& s4,
997 const ExpectationSet& s5) {
998 return After(s1, s2, s3, s4).After(s5);
999 }
1000
shiqiane35fdd92008-12-10 05:08:54 +00001001 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001002 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001003 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +00001004 ".WillOnce() cannot appear after "
1005 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001006 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001007
zhanyong.waned6c9272011-02-23 19:39:27 +00001008 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001009 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001010 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001011 }
1012 return *this;
1013 }
1014
1015 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001016 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001017 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001018 ExpectSpecProperty(false,
1019 ".WillRepeatedly() cannot appear "
1020 "more than once in an EXPECT_CALL().");
1021 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001022 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001023 ".WillRepeatedly() cannot appear "
1024 "after .RetiresOnSaturation().");
1025 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001026 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001027 repeated_action_specified_ = true;
1028
1029 repeated_action_ = action;
1030 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001031 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001032 }
1033
1034 // Now that no more action clauses can be specified, we check
1035 // whether their count makes sense.
1036 CheckActionCountIfNotDone();
1037 return *this;
1038 }
1039
1040 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001041 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001042 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001043 ".RetiresOnSaturation() cannot appear "
1044 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001045 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001046 retires_on_saturation_ = true;
1047
1048 // Now that no more action clauses can be specified, we check
1049 // whether their count makes sense.
1050 CheckActionCountIfNotDone();
1051 return *this;
1052 }
1053
1054 // Returns the matchers for the arguments as specified inside the
1055 // EXPECT_CALL() macro.
1056 const ArgumentMatcherTuple& matchers() const {
1057 return matchers_;
1058 }
1059
zhanyong.wanbf550852009-06-09 06:09:53 +00001060 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001061 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1062 return extra_matcher_;
1063 }
1064
shiqiane35fdd92008-12-10 05:08:54 +00001065 // Returns the action specified by the .WillRepeatedly() clause.
1066 const Action<F>& repeated_action() const { return repeated_action_; }
1067
zhanyong.waned6c9272011-02-23 19:39:27 +00001068 // If this mock method has an extra matcher (i.e. .With(matcher)),
1069 // describes it to the ostream.
1070 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001071 if (extra_matcher_specified_) {
1072 *os << " Expected args: ";
1073 extra_matcher_.DescribeTo(os);
1074 *os << "\n";
1075 }
1076 }
1077
shiqiane35fdd92008-12-10 05:08:54 +00001078 private:
1079 template <typename Function>
1080 friend class FunctionMockerBase;
1081
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001082 // Returns an Expectation object that references and co-owns this
1083 // expectation.
1084 virtual Expectation GetHandle() {
1085 return owner_->GetHandleOf(this);
1086 }
1087
shiqiane35fdd92008-12-10 05:08:54 +00001088 // The following methods will be called only after the EXPECT_CALL()
1089 // statement finishes and when the current thread holds
1090 // g_gmock_mutex.
1091
1092 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001093 bool Matches(const ArgumentTuple& args) const
1094 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001095 g_gmock_mutex.AssertHeld();
1096 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1097 }
1098
1099 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001100 bool ShouldHandleArguments(const ArgumentTuple& args) const
1101 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001102 g_gmock_mutex.AssertHeld();
1103
1104 // In case the action count wasn't checked when the expectation
1105 // was defined (e.g. if this expectation has no WillRepeatedly()
1106 // or RetiresOnSaturation() clause), we check it when the
1107 // expectation is used for the first time.
1108 CheckActionCountIfNotDone();
1109 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1110 }
1111
1112 // Describes the result of matching the arguments against this
1113 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001114 void ExplainMatchResultTo(
1115 const ArgumentTuple& args,
1116 ::std::ostream* os) const
1117 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001118 g_gmock_mutex.AssertHeld();
1119
1120 if (is_retired()) {
1121 *os << " Expected: the expectation is active\n"
1122 << " Actual: it is retired\n";
1123 } else if (!Matches(args)) {
1124 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001125 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001126 }
zhanyong.wan82113312010-01-08 21:55:40 +00001127 StringMatchResultListener listener;
1128 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001129 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001130 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001131 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001132
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001133 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001134 *os << "\n";
1135 }
1136 } else if (!AllPrerequisitesAreSatisfied()) {
1137 *os << " Expected: all pre-requisites are satisfied\n"
1138 << " Actual: the following immediate pre-requisites "
1139 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001140 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001141 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1142 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001143 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001144 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001145 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001146 *os << "pre-requisite #" << i++ << "\n";
1147 }
1148 *os << " (end of pre-requisites)\n";
1149 } else {
1150 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001151 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001152 // is called only when the mock function call does NOT match the
1153 // expectation.
1154 *os << "The call matches the expectation.\n";
1155 }
1156 }
1157
1158 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001159 const Action<F>& GetCurrentAction(
1160 const FunctionMockerBase<F>* mocker,
1161 const ArgumentTuple& args) const
1162 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001163 g_gmock_mutex.AssertHeld();
1164 const int count = call_count();
1165 Assert(count >= 1, __FILE__, __LINE__,
1166 "call_count() is <= 0 when GetCurrentAction() is "
1167 "called - this should never happen.");
1168
zhanyong.waned6c9272011-02-23 19:39:27 +00001169 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001170 if (action_count > 0 && !repeated_action_specified_ &&
1171 count > action_count) {
1172 // If there is at least one WillOnce() and no WillRepeatedly(),
1173 // we warn the user when the WillOnce() clauses ran out.
1174 ::std::stringstream ss;
1175 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001176 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001177 << "Called " << count << " times, but only "
1178 << action_count << " WillOnce()"
1179 << (action_count == 1 ? " is" : "s are") << " specified - ";
1180 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001181 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001182 }
1183
zhanyong.waned6c9272011-02-23 19:39:27 +00001184 return count <= action_count ?
1185 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1186 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001187 }
1188
1189 // Given the arguments of a mock function call, if the call will
1190 // over-saturate this expectation, returns the default action;
1191 // otherwise, returns the next action in this expectation. Also
1192 // describes *what* happened to 'what', and explains *why* Google
1193 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001194 // IncrementCallCount(). A return value of NULL means the default
1195 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001196 const Action<F>* GetActionForArguments(
1197 const FunctionMockerBase<F>* mocker,
1198 const ArgumentTuple& args,
1199 ::std::ostream* what,
1200 ::std::ostream* why)
1201 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001202 g_gmock_mutex.AssertHeld();
1203 if (IsSaturated()) {
1204 // We have an excessive call.
1205 IncrementCallCount();
1206 *what << "Mock function called more times than expected - ";
1207 mocker->DescribeDefaultActionTo(args, what);
1208 DescribeCallCountTo(why);
1209
Gennadiy Civil265efde2018-08-14 15:04:11 -04001210 // FIXME: allow the user to control whether
zhanyong.waned6c9272011-02-23 19:39:27 +00001211 // unexpected calls should fail immediately or continue using a
1212 // flag --gmock_unexpected_calls_are_fatal.
1213 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001214 }
1215
1216 IncrementCallCount();
1217 RetireAllPreRequisites();
1218
zhanyong.waned6c9272011-02-23 19:39:27 +00001219 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001220 Retire();
1221 }
1222
1223 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001224 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001225 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001226 }
1227
1228 // All the fields below won't change once the EXPECT_CALL()
1229 // statement finishes.
1230 FunctionMockerBase<F>* const owner_;
1231 ArgumentMatcherTuple matchers_;
1232 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001233 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001234
1235 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001236}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001237
1238// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1239// specifying the default behavior of, or expectation on, a mock
1240// function.
1241
1242// Note: class MockSpec really belongs to the ::testing namespace.
1243// However if we define it in ::testing, MSVC will complain when
1244// classes in ::testing::internal declare it as a friend class
1245// template. To workaround this compiler bug, we define MockSpec in
1246// ::testing::internal and import it into ::testing.
1247
zhanyong.waned6c9272011-02-23 19:39:27 +00001248// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001249GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1250 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001251 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001252
shiqiane35fdd92008-12-10 05:08:54 +00001253template <typename F>
1254class MockSpec {
1255 public:
1256 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1257 typedef typename internal::Function<F>::ArgumentMatcherTuple
1258 ArgumentMatcherTuple;
1259
1260 // Constructs a MockSpec object, given the function mocker object
1261 // that the spec is associated with.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001262 MockSpec(internal::FunctionMockerBase<F>* function_mocker,
1263 const ArgumentMatcherTuple& matchers)
1264 : function_mocker_(function_mocker), matchers_(matchers) {}
shiqiane35fdd92008-12-10 05:08:54 +00001265
1266 // Adds a new default action spec to the function mocker and returns
1267 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001268 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001269 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001270 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001271 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001272 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001273 }
1274
1275 // Adds a new expectation spec to the function mocker and returns
1276 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001277 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001278 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001279 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1280 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001281 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001282 return function_mocker_->AddNewExpectation(
1283 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001284 }
1285
David Sunderlandf437f8c2018-04-18 19:28:56 -04001286 // This operator overload is used to swallow the superfluous parameter list
1287 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1288 // explanation.
1289 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1290 return *this;
1291 }
1292
shiqiane35fdd92008-12-10 05:08:54 +00001293 private:
1294 template <typename Function>
1295 friend class internal::FunctionMocker;
1296
shiqiane35fdd92008-12-10 05:08:54 +00001297 // The function mocker that owns this spec.
1298 internal::FunctionMockerBase<F>* const function_mocker_;
1299 // The argument matchers specified in the spec.
1300 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001301
1302 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001303}; // class MockSpec
1304
kosakb5c81092014-01-29 06:41:44 +00001305// Wrapper type for generically holding an ordinary value or lvalue reference.
1306// If T is not a reference type, it must be copyable or movable.
1307// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1308// T is a move-only value type (which means that it will always be copyable
1309// if the current platform does not support move semantics).
1310//
1311// The primary template defines handling for values, but function header
1312// comments describe the contract for the whole template (including
1313// specializations).
1314template <typename T>
1315class ReferenceOrValueWrapper {
1316 public:
1317 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001318 explicit ReferenceOrValueWrapper(T value)
1319 : value_(::testing::internal::move(value)) {
1320 }
kosakb5c81092014-01-29 06:41:44 +00001321
1322 // Unwraps and returns the underlying value/reference, exactly as
1323 // originally passed. The behavior of calling this more than once on
1324 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001325 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001326
1327 // Provides nondestructive access to the underlying value/reference.
1328 // Always returns a const reference (more precisely,
1329 // const RemoveReference<T>&). The behavior of calling this after
1330 // calling Unwrap on the same object is unspecified.
1331 const T& Peek() const {
1332 return value_;
1333 }
1334
1335 private:
1336 T value_;
1337};
1338
1339// Specialization for lvalue reference types. See primary template
1340// for documentation.
1341template <typename T>
1342class ReferenceOrValueWrapper<T&> {
1343 public:
1344 // Workaround for debatable pass-by-reference lint warning (c-library-team
1345 // policy precludes NOLINT in this context)
1346 typedef T& reference;
1347 explicit ReferenceOrValueWrapper(reference ref)
1348 : value_ptr_(&ref) {}
1349 T& Unwrap() { return *value_ptr_; }
1350 const T& Peek() const { return *value_ptr_; }
1351
1352 private:
1353 T* value_ptr_;
1354};
1355
shiqiane35fdd92008-12-10 05:08:54 +00001356// MSVC warns about using 'this' in base member initializer list, so
1357// we need to temporarily disable the warning. We have to do it for
1358// the entire class to suppress the warning, even though it's about
1359// the constructor only.
1360
1361#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001362# pragma warning(push) // Saves the current warning state.
1363# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001364#endif // _MSV_VER
1365
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001366// C++ treats the void type specially. For example, you cannot define
1367// a void-typed variable or pass a void value to a function.
1368// ActionResultHolder<T> holds a value of type T, where T must be a
1369// copyable type or void (T doesn't need to be default-constructable).
1370// It hides the syntactic difference between void and other types, and
1371// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001372// non-void-returning mock functions.
1373
1374// Untyped base class for ActionResultHolder<T>.
1375class UntypedActionResultHolderBase {
1376 public:
1377 virtual ~UntypedActionResultHolderBase() {}
1378
1379 // Prints the held value as an action's result to os.
1380 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1381};
1382
1383// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001384template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001385class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001386 public:
kosakb5c81092014-01-29 06:41:44 +00001387 // Returns the held value. Must not be called more than once.
1388 T Unwrap() {
1389 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001390 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001391
1392 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001393 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001394 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001395 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001396 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001397 }
1398
1399 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001400 // result in a new-ed ActionResultHolder.
1401 template <typename F>
1402 static ActionResultHolder* PerformDefaultAction(
1403 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001404 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001405 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001406 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1407 internal::move(args), call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001408 }
1409
zhanyong.waned6c9272011-02-23 19:39:27 +00001410 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001411 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001412 template <typename F>
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001413 static ActionResultHolder* PerformAction(
1414 const Action<F>& action,
1415 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1416 return new ActionResultHolder(
1417 Wrapper(action.Perform(internal::move(args))));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001418 }
1419
1420 private:
kosakb5c81092014-01-29 06:41:44 +00001421 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001422
kosakd370f852014-11-17 01:14:16 +00001423 explicit ActionResultHolder(Wrapper result)
1424 : result_(::testing::internal::move(result)) {
1425 }
kosakb5c81092014-01-29 06:41:44 +00001426
1427 Wrapper result_;
1428
1429 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001430};
1431
1432// Specialization for T = void.
1433template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001434class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001435 public:
kosakb5c81092014-01-29 06:41:44 +00001436 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001437
zhanyong.waned6c9272011-02-23 19:39:27 +00001438 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1439
kosakb5c81092014-01-29 06:41:44 +00001440 // Performs the given mock function's default action and returns ownership
1441 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001442 template <typename F>
1443 static ActionResultHolder* PerformDefaultAction(
1444 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001445 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001446 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001447 func_mocker->PerformDefaultAction(internal::move(args), call_description);
kosakb5c81092014-01-29 06:41:44 +00001448 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001449 }
1450
kosakb5c81092014-01-29 06:41:44 +00001451 // Performs the given action and returns ownership of an empty
1452 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001453 template <typename F>
1454 static ActionResultHolder* PerformAction(
1455 const Action<F>& action,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001456 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1457 action.Perform(internal::move(args));
kosakb5c81092014-01-29 06:41:44 +00001458 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001459 }
kosakb5c81092014-01-29 06:41:44 +00001460
1461 private:
1462 ActionResultHolder() {}
1463 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001464};
1465
shiqiane35fdd92008-12-10 05:08:54 +00001466// The base of the function mocker class for the given function type.
1467// We put the methods in this class instead of its child to avoid code
1468// bloat.
1469template <typename F>
1470class FunctionMockerBase : public UntypedFunctionMockerBase {
1471 public:
1472 typedef typename Function<F>::Result Result;
1473 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1474 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1475
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001476 FunctionMockerBase() {}
shiqiane35fdd92008-12-10 05:08:54 +00001477
1478 // The destructor verifies that all expectations on this mock
1479 // function have been satisfied. If not, it will report Google Test
1480 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001481 virtual ~FunctionMockerBase()
1482 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001483 MutexLock l(&g_gmock_mutex);
1484 VerifyAndClearExpectationsLocked();
1485 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001486 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001487 }
1488
1489 // Returns the ON_CALL spec that matches this mock function with the
1490 // given arguments; returns NULL if no matching ON_CALL is found.
1491 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001492 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001493 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001494 for (UntypedOnCallSpecs::const_reverse_iterator it
1495 = untyped_on_call_specs_.rbegin();
1496 it != untyped_on_call_specs_.rend(); ++it) {
1497 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1498 if (spec->Matches(args))
1499 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001500 }
1501
1502 return NULL;
1503 }
1504
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001505 // Performs the default action of this mock function on the given
1506 // arguments and returns the result. Asserts (or throws if
1507 // exceptions are enabled) with a helpful call descrption if there
1508 // is no valid return value. This method doesn't depend on the
1509 // mutable state of this object, and thus can be called concurrently
1510 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001511 // L = *
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001512 Result PerformDefaultAction(
1513 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1514 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001515 const OnCallSpec<F>* const spec =
1516 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001517 if (spec != NULL) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001518 return spec->GetAction().Perform(internal::move(args));
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001519 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001520 const std::string message =
1521 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001522 "\n The mock function has no default action "
1523 "set, and its return type has no default value set.";
1524#if GTEST_HAS_EXCEPTIONS
1525 if (!DefaultValue<Result>::Exists()) {
1526 throw std::runtime_error(message);
1527 }
1528#else
1529 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1530#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001531 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001532 }
1533
zhanyong.waned6c9272011-02-23 19:39:27 +00001534 // Performs the default action with the given arguments and returns
1535 // the action's result. The call description string will be used in
1536 // the error message to describe the call in the case the default
1537 // action fails. The caller is responsible for deleting the result.
1538 // L = *
1539 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001540 void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001541 const std::string& call_description) const {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001542 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1543 return ResultHolder::PerformDefaultAction(this, internal::move(*args),
1544 call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001545 }
1546
zhanyong.waned6c9272011-02-23 19:39:27 +00001547 // Performs the given action with the given arguments and returns
1548 // the action's result. The caller is responsible for deleting the
1549 // result.
1550 // L = *
1551 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001552 const void* untyped_action, void* untyped_args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001553 // Make a copy of the action before performing it, in case the
1554 // action deletes the mock object (and thus deletes itself).
1555 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001556 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1557 return ResultHolder::PerformAction(action, internal::move(*args));
zhanyong.waned6c9272011-02-23 19:39:27 +00001558 }
shiqiane35fdd92008-12-10 05:08:54 +00001559
zhanyong.waned6c9272011-02-23 19:39:27 +00001560 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1561 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001562 virtual void ClearDefaultActionsLocked()
1563 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001564 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001565
1566 // Deleting our default actions may trigger other mock objects to be
1567 // deleted, for example if an action contains a reference counted smart
1568 // pointer to that mock object, and that is the last reference. So if we
1569 // delete our actions within the context of the global mutex we may deadlock
1570 // when this method is called again. Instead, make a copy of the set of
1571 // actions to delete, clear our set within the mutex, and then delete the
1572 // actions outside of the mutex.
1573 UntypedOnCallSpecs specs_to_delete;
1574 untyped_on_call_specs_.swap(specs_to_delete);
1575
1576 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001577 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001578 specs_to_delete.begin();
1579 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001580 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001581 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001582
1583 // Lock the mutex again, since the caller expects it to be locked when we
1584 // return.
1585 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001586 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001587
shiqiane35fdd92008-12-10 05:08:54 +00001588 protected:
1589 template <typename Function>
1590 friend class MockSpec;
1591
zhanyong.waned6c9272011-02-23 19:39:27 +00001592 typedef ActionResultHolder<Result> ResultHolder;
1593
shiqiane35fdd92008-12-10 05:08:54 +00001594 // Returns the result of invoking this mock function with the given
1595 // arguments. This function can be safely called from multiple
1596 // threads concurrently.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001597 Result InvokeWith(
1598 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args)
1599 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1600 // const_cast is required since in C++98 we still pass ArgumentTuple around
1601 // by const& instead of rvalue reference.
1602 void* untyped_args = const_cast<void*>(static_cast<const void*>(&args));
kosakb5c81092014-01-29 06:41:44 +00001603 scoped_ptr<ResultHolder> holder(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001604 DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args)));
kosakb5c81092014-01-29 06:41:44 +00001605 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001606 }
shiqiane35fdd92008-12-10 05:08:54 +00001607
1608 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001609 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001610 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001611 const ArgumentMatcherTuple& m)
1612 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001613 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001614 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1615 untyped_on_call_specs_.push_back(on_call_spec);
1616 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001617 }
1618
1619 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001620 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1621 const std::string& source_text,
1622 const ArgumentMatcherTuple& m)
1623 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001624 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001625 TypedExpectation<F>* const expectation =
1626 new TypedExpectation<F>(this, file, line, source_text, m);
1627 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001628 // See the definition of untyped_expectations_ for why access to
1629 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001630 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001631
1632 // Adds this expectation into the implicit sequence if there is one.
1633 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1634 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001635 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001636 }
1637
1638 return *expectation;
1639 }
1640
shiqiane35fdd92008-12-10 05:08:54 +00001641 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001642 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001643
zhanyong.waned6c9272011-02-23 19:39:27 +00001644 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001645
1646 // Describes what default action will be performed for the given
1647 // arguments.
1648 // L = *
1649 void DescribeDefaultActionTo(const ArgumentTuple& args,
1650 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001651 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001652
1653 if (spec == NULL) {
1654 *os << (internal::type_equals<Result, void>::value ?
1655 "returning directly.\n" :
1656 "returning default value.\n");
1657 } else {
1658 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001659 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001660 }
1661 }
1662
1663 // Writes a message that the call is uninteresting (i.e. neither
1664 // explicitly expected nor explicitly unexpected) to the given
1665 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001666 virtual void UntypedDescribeUninterestingCall(
1667 const void* untyped_args,
1668 ::std::ostream* os) const
1669 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001670 const ArgumentTuple& args =
1671 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001672 *os << "Uninteresting mock function call - ";
1673 DescribeDefaultActionTo(args, os);
1674 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001675 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001676 }
1677
zhanyong.waned6c9272011-02-23 19:39:27 +00001678 // Returns the expectation that matches the given function arguments
1679 // (or NULL is there's no match); when a match is found,
1680 // untyped_action is set to point to the action that should be
1681 // performed (or NULL if the action is "do default"), and
1682 // is_excessive is modified to indicate whether the call exceeds the
1683 // expected number.
1684 //
shiqiane35fdd92008-12-10 05:08:54 +00001685 // Critical section: We must find the matching expectation and the
1686 // corresponding action that needs to be taken in an ATOMIC
1687 // transaction. Otherwise another thread may call this mock
1688 // method in the middle and mess up the state.
1689 //
1690 // However, performing the action has to be left out of the critical
1691 // section. The reason is that we have no control on what the
1692 // action does (it can invoke an arbitrary user function or even a
1693 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001694 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1695 const void* untyped_args,
1696 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001697 ::std::ostream* what, ::std::ostream* why)
1698 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001699 const ArgumentTuple& args =
1700 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001701 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001702 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1703 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001704 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001705 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001706 }
1707
1708 // This line must be done before calling GetActionForArguments(),
1709 // which will increment the call count for *exp and thus affect
1710 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001711 *is_excessive = exp->IsSaturated();
1712 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1713 if (action != NULL && action->IsDoDefault())
1714 action = NULL; // Normalize "do default" to NULL.
1715 *untyped_action = action;
1716 return exp;
1717 }
1718
1719 // Prints the given function arguments to the ostream.
1720 virtual void UntypedPrintArgs(const void* untyped_args,
1721 ::std::ostream* os) const {
1722 const ArgumentTuple& args =
1723 *static_cast<const ArgumentTuple*>(untyped_args);
1724 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001725 }
1726
1727 // Returns the expectation that matches the arguments, or NULL if no
1728 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001729 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001730 const ArgumentTuple& args) const
1731 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001732 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001733 // See the definition of untyped_expectations_ for why access to
1734 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001735 for (typename UntypedExpectations::const_reverse_iterator it =
1736 untyped_expectations_.rbegin();
1737 it != untyped_expectations_.rend(); ++it) {
1738 TypedExpectation<F>* const exp =
1739 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001740 if (exp->ShouldHandleArguments(args)) {
1741 return exp;
1742 }
1743 }
1744 return NULL;
1745 }
1746
1747 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001748 void FormatUnexpectedCallMessageLocked(
1749 const ArgumentTuple& args,
1750 ::std::ostream* os,
1751 ::std::ostream* why) const
1752 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001753 g_gmock_mutex.AssertHeld();
1754 *os << "\nUnexpected mock function call - ";
1755 DescribeDefaultActionTo(args, os);
1756 PrintTriedExpectationsLocked(args, why);
1757 }
1758
1759 // Prints a list of expectations that have been tried against the
1760 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001761 void PrintTriedExpectationsLocked(
1762 const ArgumentTuple& args,
1763 ::std::ostream* why) const
1764 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001765 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001766 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001767 *why << "Google Mock tried the following " << count << " "
1768 << (count == 1 ? "expectation, but it didn't match" :
1769 "expectations, but none matched")
1770 << ":\n";
1771 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001772 TypedExpectation<F>* const expectation =
1773 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001774 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001775 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001776 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001777 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001778 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001779 *why << expectation->source_text() << "...\n";
1780 expectation->ExplainMatchResultTo(args, why);
1781 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001782 }
1783 }
1784
zhanyong.wan16cf4732009-05-14 20:55:30 +00001785 // There is no generally useful and implementable semantics of
1786 // copying a mock object, so copying a mock is usually a user error.
1787 // Thus we disallow copying function mockers. If the user really
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +01001788 // wants to copy a mock object, they should implement their own copy
zhanyong.wan16cf4732009-05-14 20:55:30 +00001789 // operation, for example:
1790 //
1791 // class MockFoo : public Foo {
1792 // public:
1793 // // Defines a copy constructor explicitly.
1794 // MockFoo(const MockFoo& src) {}
1795 // ...
1796 // };
1797 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001798}; // class FunctionMockerBase
1799
1800#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001801# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001802#endif // _MSV_VER
1803
1804// Implements methods of FunctionMockerBase.
1805
1806// Verifies that all expectations on this mock function have been
1807// satisfied. Reports one or more Google Test non-fatal failures and
1808// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001809
1810// Reports an uninteresting call (whose description is in msg) in the
1811// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001812void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001813
shiqiane35fdd92008-12-10 05:08:54 +00001814} // namespace internal
1815
1816// The style guide prohibits "using" statements in a namespace scope
1817// inside a header file. However, the MockSpec class template is
1818// meant to be defined in the ::testing namespace. The following line
1819// is just a trick for working around a bug in MSVC 8.0, which cannot
1820// handle it if we define MockSpec in ::testing.
1821using internal::MockSpec;
1822
1823// Const(x) is a convenient function for obtaining a const reference
1824// to x. This is useful for setting expectations on an overloaded
1825// const mock method, e.g.
1826//
1827// class MockFoo : public FooInterface {
1828// public:
1829// MOCK_METHOD0(Bar, int());
1830// MOCK_CONST_METHOD0(Bar, int&());
1831// };
1832//
1833// MockFoo foo;
1834// // Expects a call to non-const MockFoo::Bar().
1835// EXPECT_CALL(foo, Bar());
1836// // Expects a call to const MockFoo::Bar().
1837// EXPECT_CALL(Const(foo), Bar());
1838template <typename T>
1839inline const T& Const(const T& x) { return x; }
1840
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001841// Constructs an Expectation object that references and co-owns exp.
1842inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1843 : expectation_base_(exp.GetHandle().expectation_base()) {}
1844
shiqiane35fdd92008-12-10 05:08:54 +00001845} // namespace testing
1846
David Sunderlandf437f8c2018-04-18 19:28:56 -04001847// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1848// required to avoid compile errors when the name of the method used in call is
1849// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1850// tests in internal/gmock-spec-builders_test.cc for more details.
1851//
1852// This macro supports statements both with and without parameter matchers. If
1853// the parameter list is omitted, gMock will accept any parameters, which allows
1854// tests to be written that don't need to encode the number of method
1855// parameter. This technique may only be used for non-overloaded methods.
1856//
1857// // These are the same:
duxiuxing65a49a72018-07-17 15:46:47 +08001858// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1859// ON_CALL(mock, NoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001860//
1861// // As are these:
duxiuxing65a49a72018-07-17 15:46:47 +08001862// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1863// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001864//
1865// // Can also specify args if you want, of course:
duxiuxing65a49a72018-07-17 15:46:47 +08001866// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001867//
1868// // Overloads work as long as you specify parameters:
duxiuxing65a49a72018-07-17 15:46:47 +08001869// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1870// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001871//
1872// // Oops! Which overload did you want?
duxiuxing65a49a72018-07-17 15:46:47 +08001873// ON_CALL(mock, OverloadedMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001874// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1875//
1876// How this works: The mock class uses two overloads of the gmock_Method
1877// expectation setter method plus an operator() overload on the MockSpec object.
1878// In the matcher list form, the macro expands to:
1879//
1880// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001881// ON_CALL(mock, TwoArgsMethod(_, 45))...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001882//
duxiuxing65a49a72018-07-17 15:46:47 +08001883// // ...expands to:
1884// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001885// |-------------v---------------||------------v-------------|
1886// invokes first overload swallowed by operator()
1887//
duxiuxing65a49a72018-07-17 15:46:47 +08001888// // ...which is essentially:
1889// mock.gmock_TwoArgsMethod(_, 45)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001890//
1891// Whereas the form without a matcher list:
1892//
1893// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001894// ON_CALL(mock, TwoArgsMethod)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001895//
duxiuxing65a49a72018-07-17 15:46:47 +08001896// // ...expands to:
1897// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001898// |-----------------------v--------------------------|
1899// invokes second overload
1900//
duxiuxing65a49a72018-07-17 15:46:47 +08001901// // ...which is essentially:
1902// mock.gmock_TwoArgsMethod(_, _)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001903//
1904// The WithoutMatchers() argument is used to disambiguate overloads and to
1905// block the caller from accidentally invoking the second overload directly. The
1906// second argument is an internal type derived from the method signature. The
1907// failure to disambiguate two overloads of this method in the ON_CALL statement
1908// is how we block callers from setting expectations on overloaded methods.
1909#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1910 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \
1911 .Setter(__FILE__, __LINE__, #mock_expr, #call)
shiqiane35fdd92008-12-10 05:08:54 +00001912
David Sunderlandf437f8c2018-04-18 19:28:56 -04001913#define ON_CALL(obj, call) \
1914 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1915
1916#define EXPECT_CALL(obj, call) \
1917 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
shiqiane35fdd92008-12-10 05:08:54 +00001918
1919#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_