blob: 436e2d8b7747b29d27a083feee921165adf0a766 [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
mistergdf428ec2018-08-20 14:48:45 -040080GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
81/* class A needs to have dll-interface to be used by clients of class B */)
82
shiqiane35fdd92008-12-10 05:08:54 +000083namespace testing {
84
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000085// An abstract handle of an expectation.
86class Expectation;
87
88// A set of expectation handles.
89class ExpectationSet;
90
shiqiane35fdd92008-12-10 05:08:54 +000091// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
92// and MUST NOT BE USED IN USER CODE!!!
93namespace internal {
94
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000095// Implements a mock function.
96template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000097
98// Base class for expectations.
99class ExpectationBase;
100
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000101// Implements an expectation.
102template <typename F> class TypedExpectation;
103
shiqiane35fdd92008-12-10 05:08:54 +0000104// Helper class for testing the Expectation class template.
105class ExpectationTester;
106
107// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000108template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000109
shiqiane35fdd92008-12-10 05:08:54 +0000110// Protects the mock object registry (in class Mock), all function
111// mockers, and all expectations.
112//
113// The reason we don't use more fine-grained protection is: when a
114// mock function Foo() is called, it needs to consult its expectations
115// to see which one should be picked. If another thread is allowed to
116// call a mock function (either Foo() or a different one) at the same
117// time, it could affect the "retired" attributes of Foo()'s
118// expectations when InSequence() is used, and thus affect which
119// expectation gets picked. Therefore, we sequence all mock function
120// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000121GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000122
zhanyong.waned6c9272011-02-23 19:39:27 +0000123// Untyped base class for ActionResultHolder<R>.
124class UntypedActionResultHolderBase;
125
shiqiane35fdd92008-12-10 05:08:54 +0000126// Abstract base class of FunctionMockerBase. This is the
127// type-agnostic part of the function mocker interface. Its pure
128// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000129class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000130 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000131 UntypedFunctionMockerBase();
132 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000133
134 // Verifies that all expectations on this mock function have been
135 // satisfied. Reports one or more Google Test non-fatal failures
136 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000137 bool VerifyAndClearExpectationsLocked()
138 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000139
140 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000141 virtual void ClearDefaultActionsLocked()
142 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000143
144 // In all of the following Untyped* functions, it's the caller's
145 // responsibility to guarantee the correctness of the arguments'
146 // types.
147
148 // Performs the default action with the given arguments and returns
149 // the action's result. The call description string will be used in
150 // the error message to describe the call in the case the default
151 // action fails.
152 // L = *
153 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400154 void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000155
156 // Performs the given action with the given arguments and returns
157 // the action's result.
158 // L = *
159 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400160 const void* untyped_action, void* untyped_args) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000161
162 // Writes a message that the call is uninteresting (i.e. neither
163 // explicitly expected nor explicitly unexpected) to the given
164 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +0000165 virtual void UntypedDescribeUninterestingCall(
166 const void* untyped_args,
167 ::std::ostream* os) const
168 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000169
170 // Returns the expectation that matches the given function arguments
171 // (or NULL is there's no match); when a match is found,
172 // untyped_action is set to point to the action that should be
173 // performed (or NULL if the action is "do default"), and
174 // is_excessive is modified to indicate whether the call exceeds the
175 // expected number.
zhanyong.waned6c9272011-02-23 19:39:27 +0000176 virtual const ExpectationBase* UntypedFindMatchingExpectation(
177 const void* untyped_args,
178 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000179 ::std::ostream* what, ::std::ostream* why)
180 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000181
182 // Prints the given function arguments to the ostream.
183 virtual void UntypedPrintArgs(const void* untyped_args,
184 ::std::ostream* os) const = 0;
185
186 // Sets the mock object this mock method belongs to, and registers
187 // this information in the global mock registry. Will be called
188 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
189 // method.
Gennadiy Civil265efde2018-08-14 15:04:11 -0400190 // FIXME: rename to SetAndRegisterOwner().
vladlosev4d60a592011-10-24 21:16:22 +0000191 void RegisterOwner(const void* mock_obj)
192 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000193
194 // Sets the mock object this mock method belongs to, and sets the
195 // name of the mock function. Will be called upon each invocation
196 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000197 void SetOwnerAndName(const void* mock_obj, const char* name)
198 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000199
200 // Returns the mock object this mock method belongs to. Must be
201 // called after RegisterOwner() or SetOwnerAndName() has been
202 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000203 const void* MockObject() const
204 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000205
206 // Returns the name of this mock method. Must be called after
207 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000208 const char* Name() const
209 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000210
211 // Returns the result of invoking this mock function with the given
212 // arguments. This function can be safely called from multiple
213 // threads concurrently. The caller is responsible for deleting the
214 // result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400215 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
216 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000217
218 protected:
219 typedef std::vector<const void*> UntypedOnCallSpecs;
220
221 typedef std::vector<internal::linked_ptr<ExpectationBase> >
222 UntypedExpectations;
223
224 // Returns an Expectation object that references and co-owns exp,
225 // which must be an expectation on this mock function.
226 Expectation GetHandleOf(ExpectationBase* exp);
227
228 // Address of the mock object this mock method belongs to. Only
229 // valid after this mock method has been called or
230 // ON_CALL/EXPECT_CALL has been invoked on it.
231 const void* mock_obj_; // Protected by g_gmock_mutex.
232
233 // Name of the function being mocked. Only valid after this mock
234 // method has been called.
235 const char* name_; // Protected by g_gmock_mutex.
236
237 // All default action specs for this function mocker.
238 UntypedOnCallSpecs untyped_on_call_specs_;
239
240 // All expectations for this function mocker.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400241 //
242 // It's undefined behavior to interleave expectations (EXPECT_CALLs
243 // or ON_CALLs) and mock function calls. Also, the order of
244 // expectations is important. Therefore it's a logic race condition
245 // to read/write untyped_expectations_ concurrently. In order for
246 // tools like tsan to catch concurrent read/write accesses to
247 // untyped_expectations, we deliberately leave accesses to it
248 // unprotected.
zhanyong.waned6c9272011-02-23 19:39:27 +0000249 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000250}; // class UntypedFunctionMockerBase
251
zhanyong.waned6c9272011-02-23 19:39:27 +0000252// Untyped base class for OnCallSpec<F>.
253class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000254 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000255 // The arguments are the location of the ON_CALL() statement.
256 UntypedOnCallSpecBase(const char* a_file, int a_line)
257 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000258
259 // Where in the source file was the default action spec defined?
260 const char* file() const { return file_; }
261 int line() const { return line_; }
262
zhanyong.waned6c9272011-02-23 19:39:27 +0000263 protected:
264 // Gives each clause in the ON_CALL() statement a name.
265 enum Clause {
266 // Do not change the order of the enum members! The run-time
267 // syntax checking relies on it.
268 kNone,
269 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000270 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000271 };
272
273 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400274 void AssertSpecProperty(bool property,
275 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000276 Assert(property, file_, line_, failure_message);
277 }
278
279 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400280 void ExpectSpecProperty(bool property,
281 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000282 Expect(property, file_, line_, failure_message);
283 }
284
285 const char* file_;
286 int line_;
287
288 // The last clause in the ON_CALL() statement as seen so far.
289 // Initially kNone and changes as the statement is parsed.
290 Clause last_clause_;
291}; // class UntypedOnCallSpecBase
292
293// This template class implements an ON_CALL spec.
294template <typename F>
295class OnCallSpec : public UntypedOnCallSpecBase {
296 public:
297 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
298 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
299
300 // Constructs an OnCallSpec object from the information inside
301 // the parenthesis of an ON_CALL() statement.
302 OnCallSpec(const char* a_file, int a_line,
303 const ArgumentMatcherTuple& matchers)
304 : UntypedOnCallSpecBase(a_file, a_line),
305 matchers_(matchers),
306 // By default, extra_matcher_ should match anything. However,
307 // we cannot initialize it with _ as that triggers a compiler
308 // bug in Symbian's C++ compiler (cannot decide between two
309 // overloaded constructors of Matcher<const ArgumentTuple&>).
310 extra_matcher_(A<const ArgumentTuple&>()) {
311 }
312
zhanyong.wanbf550852009-06-09 06:09:53 +0000313 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000314 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000315 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000316 ExpectSpecProperty(last_clause_ < kWith,
317 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000318 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000319 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000320
321 extra_matcher_ = m;
322 return *this;
323 }
324
325 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000326 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000327 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000328 ".WillByDefault() must appear "
329 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000330 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000331
332 ExpectSpecProperty(!action.IsDoDefault(),
333 "DoDefault() cannot be used in ON_CALL().");
334 action_ = action;
335 return *this;
336 }
337
338 // Returns true iff the given arguments match the matchers.
339 bool Matches(const ArgumentTuple& args) const {
340 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
341 }
342
343 // Returns the action specified by the user.
344 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000345 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000346 ".WillByDefault() must appear exactly "
347 "once in an ON_CALL().");
348 return action_;
349 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000350
shiqiane35fdd92008-12-10 05:08:54 +0000351 private:
shiqiane35fdd92008-12-10 05:08:54 +0000352 // The information in statement
353 //
354 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000355 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000356 // .WillByDefault(action);
357 //
358 // is recorded in the data members like this:
359 //
360 // source file that contains the statement => file_
361 // line number of the statement => line_
362 // matchers => matchers_
363 // multi-argument-matcher => extra_matcher_
364 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000365 ArgumentMatcherTuple matchers_;
366 Matcher<const ArgumentTuple&> extra_matcher_;
367 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000368}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000369
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000370// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000371enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000372 kAllow,
373 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000374 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000375};
376
377} // namespace internal
378
379// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000380class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000381 public:
382 // The following public methods can be called concurrently.
383
zhanyong.wandf35a762009-04-22 22:25:31 +0000384 // Tells Google Mock to ignore mock_obj when checking for leaked
385 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000386 static void AllowLeak(const void* mock_obj)
387 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000388
shiqiane35fdd92008-12-10 05:08:54 +0000389 // Verifies and clears all expectations on the given mock object.
390 // If the expectations aren't satisfied, generates one or more
391 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000392 static bool VerifyAndClearExpectations(void* mock_obj)
393 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000394
395 // Verifies all expectations on the given mock object and clears its
396 // default actions and expectations. Returns true iff the
397 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000398 static bool VerifyAndClear(void* mock_obj)
399 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000400
shiqiane35fdd92008-12-10 05:08:54 +0000401 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000402 friend class internal::UntypedFunctionMockerBase;
403
shiqiane35fdd92008-12-10 05:08:54 +0000404 // Needed for a function mocker to register itself (so that we know
405 // how to clear a mock object).
406 template <typename F>
407 friend class internal::FunctionMockerBase;
408
shiqiane35fdd92008-12-10 05:08:54 +0000409 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700410 friend class NiceMock;
shiqiane35fdd92008-12-10 05:08:54 +0000411
412 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700413 friend class NaggyMock;
zhanyong.wan844fa942013-03-01 01:54:22 +0000414
415 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700416 friend class StrictMock;
shiqiane35fdd92008-12-10 05:08:54 +0000417
418 // Tells Google Mock to allow uninteresting calls on the given mock
419 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000420 static void AllowUninterestingCalls(const void* mock_obj)
421 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000422
423 // Tells Google Mock to warn the user about uninteresting calls on
424 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000425 static void WarnUninterestingCalls(const void* mock_obj)
426 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000427
428 // Tells Google Mock to fail uninteresting calls on the given mock
429 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000430 static void FailUninterestingCalls(const void* mock_obj)
431 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000432
433 // Tells Google Mock the given mock object is being destroyed and
434 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000435 static void UnregisterCallReaction(const void* mock_obj)
436 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000437
438 // Returns the reaction Google Mock will have on uninteresting calls
439 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000440 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000441 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000442 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000443
444 // Verifies that all expectations on the given mock object have been
445 // satisfied. Reports one or more Google Test non-fatal failures
446 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000447 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
448 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000449
450 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000451 static void ClearDefaultActionsLocked(void* mock_obj)
452 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000453
454 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000455 static void Register(
456 const void* mock_obj,
457 internal::UntypedFunctionMockerBase* mocker)
458 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000459
zhanyong.wandf35a762009-04-22 22:25:31 +0000460 // Tells Google Mock where in the source code mock_obj is used in an
461 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
462 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000463 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000464 const void* mock_obj, const char* file, int line)
465 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000466
shiqiane35fdd92008-12-10 05:08:54 +0000467 // Unregisters a mock method; removes the owning mock object from
468 // the registry when the last mock method associated with it has
469 // been unregistered. This is called only in the destructor of
470 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000471 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
472 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000473}; // class Mock
474
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000475// An abstract handle of an expectation. Useful in the .After()
476// clause of EXPECT_CALL() for setting the (partial) order of
477// expectations. The syntax:
478//
479// Expectation e1 = EXPECT_CALL(...)...;
480// EXPECT_CALL(...).After(e1)...;
481//
482// sets two expectations where the latter can only be matched after
483// the former has been satisfied.
484//
485// Notes:
486// - This class is copyable and has value semantics.
487// - Constness is shallow: a const Expectation object itself cannot
488// be modified, but the mutable methods of the ExpectationBase
489// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000490// - The constructors and destructor are defined out-of-line because
491// the Symbian WINSCW compiler wants to otherwise instantiate them
492// when it sees this class definition, at which point it doesn't have
493// ExpectationBase available yet, leading to incorrect destruction
494// in the linked_ptr (or compilation errors if using a checking
495// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000496class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000497 public:
498 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000499 Expectation();
500
501 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000502
503 // This single-argument ctor must not be explicit, in order to support the
504 // Expectation e = EXPECT_CALL(...);
505 // syntax.
506 //
507 // A TypedExpectation object stores its pre-requisites as
508 // Expectation objects, and needs to call the non-const Retire()
509 // method on the ExpectationBase objects they reference. Therefore
510 // Expectation must receive a *non-const* reference to the
511 // ExpectationBase object.
512 Expectation(internal::ExpectationBase& exp); // NOLINT
513
514 // The compiler-generated copy ctor and operator= work exactly as
515 // intended, so we don't need to define our own.
516
517 // Returns true iff rhs references the same expectation as this object does.
518 bool operator==(const Expectation& rhs) const {
519 return expectation_base_ == rhs.expectation_base_;
520 }
521
522 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
523
524 private:
525 friend class ExpectationSet;
526 friend class Sequence;
527 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000528 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000529
530 template <typename F>
531 friend class ::testing::internal::FunctionMockerBase;
532
533 template <typename F>
534 friend class ::testing::internal::TypedExpectation;
535
536 // This comparator is needed for putting Expectation objects into a set.
537 class Less {
538 public:
539 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
540 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
541 }
542 };
543
544 typedef ::std::set<Expectation, Less> Set;
545
546 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000547 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000548
549 // Returns the expectation this object references.
550 const internal::linked_ptr<internal::ExpectationBase>&
551 expectation_base() const {
552 return expectation_base_;
553 }
554
555 // A linked_ptr that co-owns the expectation this handle references.
556 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
557};
558
559// A set of expectation handles. Useful in the .After() clause of
560// EXPECT_CALL() for setting the (partial) order of expectations. The
561// syntax:
562//
563// ExpectationSet es;
564// es += EXPECT_CALL(...)...;
565// es += EXPECT_CALL(...)...;
566// EXPECT_CALL(...).After(es)...;
567//
568// sets three expectations where the last one can only be matched
569// after the first two have both been satisfied.
570//
571// This class is copyable and has value semantics.
572class ExpectationSet {
573 public:
574 // A bidirectional iterator that can read a const element in the set.
575 typedef Expectation::Set::const_iterator const_iterator;
576
577 // An object stored in the set. This is an alias of Expectation.
578 typedef Expectation::Set::value_type value_type;
579
580 // Constructs an empty set.
581 ExpectationSet() {}
582
583 // This single-argument ctor must not be explicit, in order to support the
584 // ExpectationSet es = EXPECT_CALL(...);
585 // syntax.
586 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
587 *this += Expectation(exp);
588 }
589
590 // This single-argument ctor implements implicit conversion from
591 // Expectation and thus must not be explicit. This allows either an
592 // Expectation or an ExpectationSet to be used in .After().
593 ExpectationSet(const Expectation& e) { // NOLINT
594 *this += e;
595 }
596
597 // The compiler-generator ctor and operator= works exactly as
598 // intended, so we don't need to define our own.
599
600 // Returns true iff rhs contains the same set of Expectation objects
601 // as this does.
602 bool operator==(const ExpectationSet& rhs) const {
603 return expectations_ == rhs.expectations_;
604 }
605
606 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
607
608 // Implements the syntax
609 // expectation_set += EXPECT_CALL(...);
610 ExpectationSet& operator+=(const Expectation& e) {
611 expectations_.insert(e);
612 return *this;
613 }
614
615 int size() const { return static_cast<int>(expectations_.size()); }
616
617 const_iterator begin() const { return expectations_.begin(); }
618 const_iterator end() const { return expectations_.end(); }
619
620 private:
621 Expectation::Set expectations_;
622};
623
624
shiqiane35fdd92008-12-10 05:08:54 +0000625// Sequence objects are used by a user to specify the relative order
626// in which the expectations should match. They are copyable (we rely
627// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000628class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000629 public:
630 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000631 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000632
633 // Adds an expectation to this sequence. The caller must ensure
634 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000635 void AddExpectation(const Expectation& expectation) const;
636
shiqiane35fdd92008-12-10 05:08:54 +0000637 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000638 // The last expectation in this sequence. We use a linked_ptr here
639 // because Sequence objects are copyable and we want the copies to
640 // be aliases. The linked_ptr allows the copies to co-own and share
641 // the same Expectation object.
642 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000643}; // class Sequence
644
645// An object of this type causes all EXPECT_CALL() statements
646// encountered in its scope to be put in an anonymous sequence. The
647// work is done in the constructor and destructor. You should only
648// create an InSequence object on the stack.
649//
650// The sole purpose for this class is to support easy definition of
651// sequential expectations, e.g.
652//
653// {
654// InSequence dummy; // The name of the object doesn't matter.
655//
656// // The following expectations must match in the order they appear.
657// EXPECT_CALL(a, Bar())...;
658// EXPECT_CALL(a, Baz())...;
659// ...
660// EXPECT_CALL(b, Xyz())...;
661// }
662//
663// You can create InSequence objects in multiple threads, as long as
664// they are used to affect different mock objects. The idea is that
665// each thread can create and set up its own mocks as if it's the only
666// thread. However, for clarity of your tests we recommend you to set
667// up mocks in the main thread unless you have a good reason not to do
668// so.
vladlosev587c1b32011-05-20 00:42:22 +0000669class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000670 public:
671 InSequence();
672 ~InSequence();
673 private:
674 bool sequence_created_;
675
676 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000677} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000678
679namespace internal {
680
681// Points to the implicit sequence introduced by a living InSequence
682// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000683GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000684
685// Base class for implementing expectations.
686//
687// There are two reasons for having a type-agnostic base class for
688// Expectation:
689//
690// 1. We need to store collections of expectations of different
691// types (e.g. all pre-requisites of a particular expectation, all
692// expectations in a sequence). Therefore these expectation objects
693// must share a common base class.
694//
695// 2. We can avoid binary code bloat by moving methods not depending
696// on the template argument of Expectation to the base class.
697//
698// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000699class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000700 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000701 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400702 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000703
704 virtual ~ExpectationBase();
705
706 // Where in the source file was the expectation spec defined?
707 const char* file() const { return file_; }
708 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000709 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000710 // Returns the cardinality specified in the expectation spec.
711 const Cardinality& cardinality() const { return cardinality_; }
712
713 // Describes the source file location of this expectation.
714 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000715 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000716 }
717
718 // Describes how many times a function call matching this
719 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000720 void DescribeCallCountTo(::std::ostream* os) const
721 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000722
723 // If this mock method has an extra matcher (i.e. .With(matcher)),
724 // describes it to the ostream.
725 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000726
shiqiane35fdd92008-12-10 05:08:54 +0000727 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000728 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000729 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000730
731 enum Clause {
732 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000733 kNone,
734 kWith,
735 kTimes,
736 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000737 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000738 kWillOnce,
739 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000740 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000741 };
742
zhanyong.waned6c9272011-02-23 19:39:27 +0000743 typedef std::vector<const void*> UntypedActions;
744
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000745 // Returns an Expectation object that references and co-owns this
746 // expectation.
747 virtual Expectation GetHandle() = 0;
748
shiqiane35fdd92008-12-10 05:08:54 +0000749 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400750 void AssertSpecProperty(bool property,
751 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000752 Assert(property, file_, line_, failure_message);
753 }
754
755 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400756 void ExpectSpecProperty(bool property,
757 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000758 Expect(property, file_, line_, failure_message);
759 }
760
761 // Explicitly specifies the cardinality of this expectation. Used
762 // by the subclasses to implement the .Times() clause.
763 void SpecifyCardinality(const Cardinality& cardinality);
764
765 // Returns true iff the user specified the cardinality explicitly
766 // using a .Times().
767 bool cardinality_specified() const { return cardinality_specified_; }
768
769 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000770 void set_cardinality(const Cardinality& a_cardinality) {
771 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000772 }
773
774 // The following group of methods should only be called after the
775 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
776 // the current thread.
777
778 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000779 void RetireAllPreRequisites()
780 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000781
782 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000783 bool is_retired() const
784 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000785 g_gmock_mutex.AssertHeld();
786 return retired_;
787 }
788
789 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000790 void Retire()
791 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000792 g_gmock_mutex.AssertHeld();
793 retired_ = true;
794 }
795
796 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000797 bool IsSatisfied() const
798 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000799 g_gmock_mutex.AssertHeld();
800 return cardinality().IsSatisfiedByCallCount(call_count_);
801 }
802
803 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000804 bool IsSaturated() const
805 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000806 g_gmock_mutex.AssertHeld();
807 return cardinality().IsSaturatedByCallCount(call_count_);
808 }
809
810 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000811 bool IsOverSaturated() const
812 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000813 g_gmock_mutex.AssertHeld();
814 return cardinality().IsOverSaturatedByCallCount(call_count_);
815 }
816
817 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000818 bool AllPrerequisitesAreSatisfied() const
819 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000820
821 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000822 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
823 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000824
825 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000826 int call_count() const
827 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000828 g_gmock_mutex.AssertHeld();
829 return call_count_;
830 }
831
832 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000833 void IncrementCallCount()
834 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000835 g_gmock_mutex.AssertHeld();
836 call_count_++;
837 }
838
zhanyong.waned6c9272011-02-23 19:39:27 +0000839 // Checks the action count (i.e. the number of WillOnce() and
840 // WillRepeatedly() clauses) against the cardinality if this hasn't
841 // been done before. Prints a warning if there are too many or too
842 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000843 void CheckActionCountIfNotDone() const
844 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000845
shiqiane35fdd92008-12-10 05:08:54 +0000846 friend class ::testing::Sequence;
847 friend class ::testing::internal::ExpectationTester;
848
849 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000850 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000851
zhanyong.waned6c9272011-02-23 19:39:27 +0000852 // Implements the .Times() clause.
853 void UntypedTimes(const Cardinality& a_cardinality);
854
shiqiane35fdd92008-12-10 05:08:54 +0000855 // This group of fields are part of the spec and won't change after
856 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000857 const char* file_; // The file that contains the expectation.
858 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400859 const std::string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000860 // True iff the cardinality is specified explicitly.
861 bool cardinality_specified_;
862 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000863 // The immediate pre-requisites (i.e. expectations that must be
864 // satisfied before this expectation can be matched) of this
865 // expectation. We use linked_ptr in the set because we want an
866 // Expectation object to be co-owned by its FunctionMocker and its
867 // successors. This allows multiple mock objects to be deleted at
868 // different times.
869 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000870
871 // This group of fields are the current state of the expectation,
872 // and can change as the mock function is called.
873 int call_count_; // How many times this expectation has been invoked.
874 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000875 UntypedActions untyped_actions_;
876 bool extra_matcher_specified_;
877 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
878 bool retires_on_saturation_;
879 Clause last_clause_;
880 mutable bool action_count_checked_; // Under mutex_.
881 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000882
883 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000884}; // class ExpectationBase
885
886// Impements an expectation for the given function type.
887template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000888class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000889 public:
890 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
891 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
892 typedef typename Function<F>::Result Result;
893
Nico Weber09fd5b32017-05-15 17:07:03 -0400894 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
895 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000896 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000897 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000898 owner_(owner),
899 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000900 // By default, extra_matcher_ should match anything. However,
901 // we cannot initialize it with _ as that triggers a compiler
902 // bug in Symbian's C++ compiler (cannot decide between two
903 // overloaded constructors of Matcher<const ArgumentTuple&>).
904 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000905 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000906
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000907 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000908 // Check the validity of the action count if it hasn't been done
909 // yet (for example, if the expectation was never used).
910 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000911 for (UntypedActions::const_iterator it = untyped_actions_.begin();
912 it != untyped_actions_.end(); ++it) {
913 delete static_cast<const Action<F>*>(*it);
914 }
shiqiane35fdd92008-12-10 05:08:54 +0000915 }
916
zhanyong.wanbf550852009-06-09 06:09:53 +0000917 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000918 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000919 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000920 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000921 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000922 "more than once in an EXPECT_CALL().");
923 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000924 ExpectSpecProperty(last_clause_ < kWith,
925 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000926 "clause in an EXPECT_CALL().");
927 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000928 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000929
930 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000931 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000932 return *this;
933 }
934
935 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000936 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000937 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000938 return *this;
939 }
940
941 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000942 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000943 return Times(Exactly(n));
944 }
945
946 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000947 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000948 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000949 ".InSequence() cannot appear after .After(),"
950 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000951 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000952 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000953
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000954 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000955 return *this;
956 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000957 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000958 return InSequence(s1).InSequence(s2);
959 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000960 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
961 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000962 return InSequence(s1, s2).InSequence(s3);
963 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000964 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
965 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000966 return InSequence(s1, s2, s3).InSequence(s4);
967 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000968 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
969 const Sequence& s3, const Sequence& s4,
970 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000971 return InSequence(s1, s2, s3, s4).InSequence(s5);
972 }
973
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000974 // Implements that .After() clause.
975 TypedExpectation& After(const ExpectationSet& s) {
976 ExpectSpecProperty(last_clause_ <= kAfter,
977 ".After() cannot appear after .WillOnce(),"
978 " .WillRepeatedly(), or "
979 ".RetiresOnSaturation().");
980 last_clause_ = kAfter;
981
982 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
983 immediate_prerequisites_ += *it;
984 }
985 return *this;
986 }
987 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
988 return After(s1).After(s2);
989 }
990 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
991 const ExpectationSet& s3) {
992 return After(s1, s2).After(s3);
993 }
994 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
995 const ExpectationSet& s3, const ExpectationSet& s4) {
996 return After(s1, s2, s3).After(s4);
997 }
998 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
999 const ExpectationSet& s3, const ExpectationSet& s4,
1000 const ExpectationSet& s5) {
1001 return After(s1, s2, s3, s4).After(s5);
1002 }
1003
shiqiane35fdd92008-12-10 05:08:54 +00001004 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001005 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001006 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +00001007 ".WillOnce() cannot appear after "
1008 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001009 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001010
zhanyong.waned6c9272011-02-23 19:39:27 +00001011 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001012 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001013 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001014 }
1015 return *this;
1016 }
1017
1018 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001019 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001020 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001021 ExpectSpecProperty(false,
1022 ".WillRepeatedly() cannot appear "
1023 "more than once in an EXPECT_CALL().");
1024 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001025 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001026 ".WillRepeatedly() cannot appear "
1027 "after .RetiresOnSaturation().");
1028 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001029 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001030 repeated_action_specified_ = true;
1031
1032 repeated_action_ = action;
1033 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001034 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001035 }
1036
1037 // Now that no more action clauses can be specified, we check
1038 // whether their count makes sense.
1039 CheckActionCountIfNotDone();
1040 return *this;
1041 }
1042
1043 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001044 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001045 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001046 ".RetiresOnSaturation() cannot appear "
1047 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001048 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001049 retires_on_saturation_ = true;
1050
1051 // Now that no more action clauses can be specified, we check
1052 // whether their count makes sense.
1053 CheckActionCountIfNotDone();
1054 return *this;
1055 }
1056
1057 // Returns the matchers for the arguments as specified inside the
1058 // EXPECT_CALL() macro.
1059 const ArgumentMatcherTuple& matchers() const {
1060 return matchers_;
1061 }
1062
zhanyong.wanbf550852009-06-09 06:09:53 +00001063 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001064 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1065 return extra_matcher_;
1066 }
1067
shiqiane35fdd92008-12-10 05:08:54 +00001068 // Returns the action specified by the .WillRepeatedly() clause.
1069 const Action<F>& repeated_action() const { return repeated_action_; }
1070
zhanyong.waned6c9272011-02-23 19:39:27 +00001071 // If this mock method has an extra matcher (i.e. .With(matcher)),
1072 // describes it to the ostream.
1073 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001074 if (extra_matcher_specified_) {
1075 *os << " Expected args: ";
1076 extra_matcher_.DescribeTo(os);
1077 *os << "\n";
1078 }
1079 }
1080
shiqiane35fdd92008-12-10 05:08:54 +00001081 private:
1082 template <typename Function>
1083 friend class FunctionMockerBase;
1084
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001085 // Returns an Expectation object that references and co-owns this
1086 // expectation.
1087 virtual Expectation GetHandle() {
1088 return owner_->GetHandleOf(this);
1089 }
1090
shiqiane35fdd92008-12-10 05:08:54 +00001091 // The following methods will be called only after the EXPECT_CALL()
1092 // statement finishes and when the current thread holds
1093 // g_gmock_mutex.
1094
1095 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001096 bool Matches(const ArgumentTuple& args) const
1097 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001098 g_gmock_mutex.AssertHeld();
1099 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1100 }
1101
1102 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001103 bool ShouldHandleArguments(const ArgumentTuple& args) const
1104 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001105 g_gmock_mutex.AssertHeld();
1106
1107 // In case the action count wasn't checked when the expectation
1108 // was defined (e.g. if this expectation has no WillRepeatedly()
1109 // or RetiresOnSaturation() clause), we check it when the
1110 // expectation is used for the first time.
1111 CheckActionCountIfNotDone();
1112 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1113 }
1114
1115 // Describes the result of matching the arguments against this
1116 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001117 void ExplainMatchResultTo(
1118 const ArgumentTuple& args,
1119 ::std::ostream* os) const
1120 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001121 g_gmock_mutex.AssertHeld();
1122
1123 if (is_retired()) {
1124 *os << " Expected: the expectation is active\n"
1125 << " Actual: it is retired\n";
1126 } else if (!Matches(args)) {
1127 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001128 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001129 }
zhanyong.wan82113312010-01-08 21:55:40 +00001130 StringMatchResultListener listener;
1131 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001132 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001133 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001134 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001135
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001136 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001137 *os << "\n";
1138 }
1139 } else if (!AllPrerequisitesAreSatisfied()) {
1140 *os << " Expected: all pre-requisites are satisfied\n"
1141 << " Actual: the following immediate pre-requisites "
1142 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001143 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001144 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1145 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001146 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001147 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001148 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001149 *os << "pre-requisite #" << i++ << "\n";
1150 }
1151 *os << " (end of pre-requisites)\n";
1152 } else {
1153 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001154 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001155 // is called only when the mock function call does NOT match the
1156 // expectation.
1157 *os << "The call matches the expectation.\n";
1158 }
1159 }
1160
1161 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001162 const Action<F>& GetCurrentAction(
1163 const FunctionMockerBase<F>* mocker,
1164 const ArgumentTuple& args) const
1165 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001166 g_gmock_mutex.AssertHeld();
1167 const int count = call_count();
1168 Assert(count >= 1, __FILE__, __LINE__,
1169 "call_count() is <= 0 when GetCurrentAction() is "
1170 "called - this should never happen.");
1171
zhanyong.waned6c9272011-02-23 19:39:27 +00001172 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001173 if (action_count > 0 && !repeated_action_specified_ &&
1174 count > action_count) {
1175 // If there is at least one WillOnce() and no WillRepeatedly(),
1176 // we warn the user when the WillOnce() clauses ran out.
1177 ::std::stringstream ss;
1178 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001179 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001180 << "Called " << count << " times, but only "
1181 << action_count << " WillOnce()"
1182 << (action_count == 1 ? " is" : "s are") << " specified - ";
1183 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001184 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001185 }
1186
zhanyong.waned6c9272011-02-23 19:39:27 +00001187 return count <= action_count ?
1188 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1189 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001190 }
1191
1192 // Given the arguments of a mock function call, if the call will
1193 // over-saturate this expectation, returns the default action;
1194 // otherwise, returns the next action in this expectation. Also
1195 // describes *what* happened to 'what', and explains *why* Google
1196 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001197 // IncrementCallCount(). A return value of NULL means the default
1198 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001199 const Action<F>* GetActionForArguments(
1200 const FunctionMockerBase<F>* mocker,
1201 const ArgumentTuple& args,
1202 ::std::ostream* what,
1203 ::std::ostream* why)
1204 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001205 g_gmock_mutex.AssertHeld();
1206 if (IsSaturated()) {
1207 // We have an excessive call.
1208 IncrementCallCount();
1209 *what << "Mock function called more times than expected - ";
1210 mocker->DescribeDefaultActionTo(args, what);
1211 DescribeCallCountTo(why);
1212
Gennadiy Civil265efde2018-08-14 15:04:11 -04001213 // FIXME: allow the user to control whether
zhanyong.waned6c9272011-02-23 19:39:27 +00001214 // unexpected calls should fail immediately or continue using a
1215 // flag --gmock_unexpected_calls_are_fatal.
1216 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001217 }
1218
1219 IncrementCallCount();
1220 RetireAllPreRequisites();
1221
zhanyong.waned6c9272011-02-23 19:39:27 +00001222 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001223 Retire();
1224 }
1225
1226 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001227 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001228 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001229 }
1230
1231 // All the fields below won't change once the EXPECT_CALL()
1232 // statement finishes.
1233 FunctionMockerBase<F>* const owner_;
1234 ArgumentMatcherTuple matchers_;
1235 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001236 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001237
1238 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001239}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001240
1241// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1242// specifying the default behavior of, or expectation on, a mock
1243// function.
1244
1245// Note: class MockSpec really belongs to the ::testing namespace.
1246// However if we define it in ::testing, MSVC will complain when
1247// classes in ::testing::internal declare it as a friend class
1248// template. To workaround this compiler bug, we define MockSpec in
1249// ::testing::internal and import it into ::testing.
1250
zhanyong.waned6c9272011-02-23 19:39:27 +00001251// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001252GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1253 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001254 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001255
shiqiane35fdd92008-12-10 05:08:54 +00001256template <typename F>
1257class MockSpec {
1258 public:
1259 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1260 typedef typename internal::Function<F>::ArgumentMatcherTuple
1261 ArgumentMatcherTuple;
1262
1263 // Constructs a MockSpec object, given the function mocker object
1264 // that the spec is associated with.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001265 MockSpec(internal::FunctionMockerBase<F>* function_mocker,
1266 const ArgumentMatcherTuple& matchers)
1267 : function_mocker_(function_mocker), matchers_(matchers) {}
shiqiane35fdd92008-12-10 05:08:54 +00001268
1269 // Adds a new default action spec to the function mocker and returns
1270 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001271 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001272 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001273 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001274 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001275 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001276 }
1277
1278 // Adds a new expectation spec to the function mocker and returns
1279 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001280 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001281 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001282 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1283 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001284 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001285 return function_mocker_->AddNewExpectation(
1286 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001287 }
1288
David Sunderlandf437f8c2018-04-18 19:28:56 -04001289 // This operator overload is used to swallow the superfluous parameter list
1290 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1291 // explanation.
1292 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1293 return *this;
1294 }
1295
shiqiane35fdd92008-12-10 05:08:54 +00001296 private:
1297 template <typename Function>
1298 friend class internal::FunctionMocker;
1299
shiqiane35fdd92008-12-10 05:08:54 +00001300 // The function mocker that owns this spec.
1301 internal::FunctionMockerBase<F>* const function_mocker_;
1302 // The argument matchers specified in the spec.
1303 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001304
1305 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001306}; // class MockSpec
1307
kosakb5c81092014-01-29 06:41:44 +00001308// Wrapper type for generically holding an ordinary value or lvalue reference.
1309// If T is not a reference type, it must be copyable or movable.
1310// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1311// T is a move-only value type (which means that it will always be copyable
1312// if the current platform does not support move semantics).
1313//
1314// The primary template defines handling for values, but function header
1315// comments describe the contract for the whole template (including
1316// specializations).
1317template <typename T>
1318class ReferenceOrValueWrapper {
1319 public:
1320 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001321 explicit ReferenceOrValueWrapper(T value)
1322 : value_(::testing::internal::move(value)) {
1323 }
kosakb5c81092014-01-29 06:41:44 +00001324
1325 // Unwraps and returns the underlying value/reference, exactly as
1326 // originally passed. The behavior of calling this more than once on
1327 // the same object is unspecified.
kosakd370f852014-11-17 01:14:16 +00001328 T Unwrap() { return ::testing::internal::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001329
1330 // Provides nondestructive access to the underlying value/reference.
1331 // Always returns a const reference (more precisely,
1332 // const RemoveReference<T>&). The behavior of calling this after
1333 // calling Unwrap on the same object is unspecified.
1334 const T& Peek() const {
1335 return value_;
1336 }
1337
1338 private:
1339 T value_;
1340};
1341
1342// Specialization for lvalue reference types. See primary template
1343// for documentation.
1344template <typename T>
1345class ReferenceOrValueWrapper<T&> {
1346 public:
1347 // Workaround for debatable pass-by-reference lint warning (c-library-team
1348 // policy precludes NOLINT in this context)
1349 typedef T& reference;
1350 explicit ReferenceOrValueWrapper(reference ref)
1351 : value_ptr_(&ref) {}
1352 T& Unwrap() { return *value_ptr_; }
1353 const T& Peek() const { return *value_ptr_; }
1354
1355 private:
1356 T* value_ptr_;
1357};
1358
shiqiane35fdd92008-12-10 05:08:54 +00001359// MSVC warns about using 'this' in base member initializer list, so
1360// we need to temporarily disable the warning. We have to do it for
1361// the entire class to suppress the warning, even though it's about
1362// the constructor only.
mistergdf428ec2018-08-20 14:48:45 -04001363GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
shiqiane35fdd92008-12-10 05:08:54 +00001364
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001365// C++ treats the void type specially. For example, you cannot define
1366// a void-typed variable or pass a void value to a function.
1367// ActionResultHolder<T> holds a value of type T, where T must be a
1368// copyable type or void (T doesn't need to be default-constructable).
1369// It hides the syntactic difference between void and other types, and
1370// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001371// non-void-returning mock functions.
1372
1373// Untyped base class for ActionResultHolder<T>.
1374class UntypedActionResultHolderBase {
1375 public:
1376 virtual ~UntypedActionResultHolderBase() {}
1377
1378 // Prints the held value as an action's result to os.
1379 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1380};
1381
1382// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001383template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001384class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001385 public:
kosakb5c81092014-01-29 06:41:44 +00001386 // Returns the held value. Must not be called more than once.
1387 T Unwrap() {
1388 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001389 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001390
1391 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001392 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001393 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001394 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001395 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001396 }
1397
1398 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001399 // result in a new-ed ActionResultHolder.
1400 template <typename F>
1401 static ActionResultHolder* PerformDefaultAction(
1402 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001403 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001404 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001405 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1406 internal::move(args), call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001407 }
1408
zhanyong.waned6c9272011-02-23 19:39:27 +00001409 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001410 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001411 template <typename F>
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001412 static ActionResultHolder* PerformAction(
1413 const Action<F>& action,
1414 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1415 return new ActionResultHolder(
1416 Wrapper(action.Perform(internal::move(args))));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001417 }
1418
1419 private:
kosakb5c81092014-01-29 06:41:44 +00001420 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001421
kosakd370f852014-11-17 01:14:16 +00001422 explicit ActionResultHolder(Wrapper result)
1423 : result_(::testing::internal::move(result)) {
1424 }
kosakb5c81092014-01-29 06:41:44 +00001425
1426 Wrapper result_;
1427
1428 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001429};
1430
1431// Specialization for T = void.
1432template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001433class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001434 public:
kosakb5c81092014-01-29 06:41:44 +00001435 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001436
zhanyong.waned6c9272011-02-23 19:39:27 +00001437 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1438
kosakb5c81092014-01-29 06:41:44 +00001439 // Performs the given mock function's default action and returns ownership
1440 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001441 template <typename F>
1442 static ActionResultHolder* PerformDefaultAction(
1443 const FunctionMockerBase<F>* func_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001444 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001445 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001446 func_mocker->PerformDefaultAction(internal::move(args), call_description);
kosakb5c81092014-01-29 06:41:44 +00001447 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001448 }
1449
kosakb5c81092014-01-29 06:41:44 +00001450 // Performs the given action and returns ownership of an empty
1451 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001452 template <typename F>
1453 static ActionResultHolder* PerformAction(
1454 const Action<F>& action,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001455 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args) {
1456 action.Perform(internal::move(args));
kosakb5c81092014-01-29 06:41:44 +00001457 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001458 }
kosakb5c81092014-01-29 06:41:44 +00001459
1460 private:
1461 ActionResultHolder() {}
1462 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001463};
1464
shiqiane35fdd92008-12-10 05:08:54 +00001465// The base of the function mocker class for the given function type.
1466// We put the methods in this class instead of its child to avoid code
1467// bloat.
1468template <typename F>
1469class FunctionMockerBase : public UntypedFunctionMockerBase {
1470 public:
1471 typedef typename Function<F>::Result Result;
1472 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1473 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1474
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001475 FunctionMockerBase() {}
shiqiane35fdd92008-12-10 05:08:54 +00001476
1477 // The destructor verifies that all expectations on this mock
1478 // function have been satisfied. If not, it will report Google Test
1479 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001480 virtual ~FunctionMockerBase()
1481 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001482 MutexLock l(&g_gmock_mutex);
1483 VerifyAndClearExpectationsLocked();
1484 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001485 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001486 }
1487
1488 // Returns the ON_CALL spec that matches this mock function with the
1489 // given arguments; returns NULL if no matching ON_CALL is found.
1490 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001491 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001492 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001493 for (UntypedOnCallSpecs::const_reverse_iterator it
1494 = untyped_on_call_specs_.rbegin();
1495 it != untyped_on_call_specs_.rend(); ++it) {
1496 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1497 if (spec->Matches(args))
1498 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001499 }
1500
1501 return NULL;
1502 }
1503
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001504 // Performs the default action of this mock function on the given
1505 // arguments and returns the result. Asserts (or throws if
1506 // exceptions are enabled) with a helpful call descrption if there
1507 // is no valid return value. This method doesn't depend on the
1508 // mutable state of this object, and thus can be called concurrently
1509 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001510 // L = *
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001511 Result PerformDefaultAction(
1512 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args,
1513 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001514 const OnCallSpec<F>* const spec =
1515 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001516 if (spec != NULL) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001517 return spec->GetAction().Perform(internal::move(args));
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001518 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001519 const std::string message =
1520 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001521 "\n The mock function has no default action "
1522 "set, and its return type has no default value set.";
1523#if GTEST_HAS_EXCEPTIONS
1524 if (!DefaultValue<Result>::Exists()) {
1525 throw std::runtime_error(message);
1526 }
1527#else
1528 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1529#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001530 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001531 }
1532
zhanyong.waned6c9272011-02-23 19:39:27 +00001533 // Performs the default action with the given arguments and returns
1534 // the action's result. The call description string will be used in
1535 // the error message to describe the call in the case the default
1536 // action fails. The caller is responsible for deleting the result.
1537 // L = *
1538 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001539 void* untyped_args, // must point to an ArgumentTuple
Nico Weber09fd5b32017-05-15 17:07:03 -04001540 const std::string& call_description) const {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001541 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1542 return ResultHolder::PerformDefaultAction(this, internal::move(*args),
1543 call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001544 }
1545
zhanyong.waned6c9272011-02-23 19:39:27 +00001546 // Performs the given action with the given arguments and returns
1547 // the action's result. The caller is responsible for deleting the
1548 // result.
1549 // L = *
1550 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001551 const void* untyped_action, void* untyped_args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001552 // Make a copy of the action before performing it, in case the
1553 // action deletes the mock object (and thus deletes itself).
1554 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001555 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1556 return ResultHolder::PerformAction(action, internal::move(*args));
zhanyong.waned6c9272011-02-23 19:39:27 +00001557 }
shiqiane35fdd92008-12-10 05:08:54 +00001558
zhanyong.waned6c9272011-02-23 19:39:27 +00001559 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1560 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001561 virtual void ClearDefaultActionsLocked()
1562 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001563 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001564
1565 // Deleting our default actions may trigger other mock objects to be
1566 // deleted, for example if an action contains a reference counted smart
1567 // pointer to that mock object, and that is the last reference. So if we
1568 // delete our actions within the context of the global mutex we may deadlock
1569 // when this method is called again. Instead, make a copy of the set of
1570 // actions to delete, clear our set within the mutex, and then delete the
1571 // actions outside of the mutex.
1572 UntypedOnCallSpecs specs_to_delete;
1573 untyped_on_call_specs_.swap(specs_to_delete);
1574
1575 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001576 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001577 specs_to_delete.begin();
1578 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001579 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001580 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001581
1582 // Lock the mutex again, since the caller expects it to be locked when we
1583 // return.
1584 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001585 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001586
shiqiane35fdd92008-12-10 05:08:54 +00001587 protected:
1588 template <typename Function>
1589 friend class MockSpec;
1590
zhanyong.waned6c9272011-02-23 19:39:27 +00001591 typedef ActionResultHolder<Result> ResultHolder;
1592
shiqiane35fdd92008-12-10 05:08:54 +00001593 // Returns the result of invoking this mock function with the given
1594 // arguments. This function can be safely called from multiple
1595 // threads concurrently.
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001596 Result InvokeWith(
1597 typename RvalueRef<typename Function<F>::ArgumentTuple>::type args)
1598 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1599 // const_cast is required since in C++98 we still pass ArgumentTuple around
1600 // by const& instead of rvalue reference.
1601 void* untyped_args = const_cast<void*>(static_cast<const void*>(&args));
kosakb5c81092014-01-29 06:41:44 +00001602 scoped_ptr<ResultHolder> holder(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001603 DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args)));
kosakb5c81092014-01-29 06:41:44 +00001604 return holder->Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001605 }
shiqiane35fdd92008-12-10 05:08:54 +00001606
1607 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001608 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001609 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001610 const ArgumentMatcherTuple& m)
1611 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001612 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001613 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1614 untyped_on_call_specs_.push_back(on_call_spec);
1615 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001616 }
1617
1618 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001619 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1620 const std::string& source_text,
1621 const ArgumentMatcherTuple& m)
1622 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001623 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001624 TypedExpectation<F>* const expectation =
1625 new TypedExpectation<F>(this, file, line, source_text, m);
1626 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001627 // See the definition of untyped_expectations_ for why access to
1628 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001629 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001630
1631 // Adds this expectation into the implicit sequence if there is one.
1632 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1633 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001634 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001635 }
1636
1637 return *expectation;
1638 }
1639
shiqiane35fdd92008-12-10 05:08:54 +00001640 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001641 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001642
zhanyong.waned6c9272011-02-23 19:39:27 +00001643 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001644
1645 // Describes what default action will be performed for the given
1646 // arguments.
1647 // L = *
1648 void DescribeDefaultActionTo(const ArgumentTuple& args,
1649 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001650 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001651
1652 if (spec == NULL) {
1653 *os << (internal::type_equals<Result, void>::value ?
1654 "returning directly.\n" :
1655 "returning default value.\n");
1656 } else {
1657 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001658 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001659 }
1660 }
1661
1662 // Writes a message that the call is uninteresting (i.e. neither
1663 // explicitly expected nor explicitly unexpected) to the given
1664 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001665 virtual void UntypedDescribeUninterestingCall(
1666 const void* untyped_args,
1667 ::std::ostream* os) const
1668 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001669 const ArgumentTuple& args =
1670 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001671 *os << "Uninteresting mock function call - ";
1672 DescribeDefaultActionTo(args, os);
1673 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001674 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001675 }
1676
zhanyong.waned6c9272011-02-23 19:39:27 +00001677 // Returns the expectation that matches the given function arguments
1678 // (or NULL is there's no match); when a match is found,
1679 // untyped_action is set to point to the action that should be
1680 // performed (or NULL if the action is "do default"), and
1681 // is_excessive is modified to indicate whether the call exceeds the
1682 // expected number.
1683 //
shiqiane35fdd92008-12-10 05:08:54 +00001684 // Critical section: We must find the matching expectation and the
1685 // corresponding action that needs to be taken in an ATOMIC
1686 // transaction. Otherwise another thread may call this mock
1687 // method in the middle and mess up the state.
1688 //
1689 // However, performing the action has to be left out of the critical
1690 // section. The reason is that we have no control on what the
1691 // action does (it can invoke an arbitrary user function or even a
1692 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001693 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1694 const void* untyped_args,
1695 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001696 ::std::ostream* what, ::std::ostream* why)
1697 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001698 const ArgumentTuple& args =
1699 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001700 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001701 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1702 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001703 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001704 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001705 }
1706
1707 // This line must be done before calling GetActionForArguments(),
1708 // which will increment the call count for *exp and thus affect
1709 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001710 *is_excessive = exp->IsSaturated();
1711 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1712 if (action != NULL && action->IsDoDefault())
1713 action = NULL; // Normalize "do default" to NULL.
1714 *untyped_action = action;
1715 return exp;
1716 }
1717
1718 // Prints the given function arguments to the ostream.
1719 virtual void UntypedPrintArgs(const void* untyped_args,
1720 ::std::ostream* os) const {
1721 const ArgumentTuple& args =
1722 *static_cast<const ArgumentTuple*>(untyped_args);
1723 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001724 }
1725
1726 // Returns the expectation that matches the arguments, or NULL if no
1727 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001728 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001729 const ArgumentTuple& args) const
1730 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001731 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001732 // See the definition of untyped_expectations_ for why access to
1733 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001734 for (typename UntypedExpectations::const_reverse_iterator it =
1735 untyped_expectations_.rbegin();
1736 it != untyped_expectations_.rend(); ++it) {
1737 TypedExpectation<F>* const exp =
1738 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001739 if (exp->ShouldHandleArguments(args)) {
1740 return exp;
1741 }
1742 }
1743 return NULL;
1744 }
1745
1746 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001747 void FormatUnexpectedCallMessageLocked(
1748 const ArgumentTuple& args,
1749 ::std::ostream* os,
1750 ::std::ostream* why) const
1751 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001752 g_gmock_mutex.AssertHeld();
1753 *os << "\nUnexpected mock function call - ";
1754 DescribeDefaultActionTo(args, os);
1755 PrintTriedExpectationsLocked(args, why);
1756 }
1757
1758 // Prints a list of expectations that have been tried against the
1759 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001760 void PrintTriedExpectationsLocked(
1761 const ArgumentTuple& args,
1762 ::std::ostream* why) const
1763 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001764 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001765 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001766 *why << "Google Mock tried the following " << count << " "
1767 << (count == 1 ? "expectation, but it didn't match" :
1768 "expectations, but none matched")
1769 << ":\n";
1770 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001771 TypedExpectation<F>* const expectation =
1772 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001773 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001774 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001775 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001776 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001777 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001778 *why << expectation->source_text() << "...\n";
1779 expectation->ExplainMatchResultTo(args, why);
1780 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001781 }
1782 }
1783
zhanyong.wan16cf4732009-05-14 20:55:30 +00001784 // There is no generally useful and implementable semantics of
1785 // copying a mock object, so copying a mock is usually a user error.
1786 // Thus we disallow copying function mockers. If the user really
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +01001787 // wants to copy a mock object, they should implement their own copy
zhanyong.wan16cf4732009-05-14 20:55:30 +00001788 // operation, for example:
1789 //
1790 // class MockFoo : public Foo {
1791 // public:
1792 // // Defines a copy constructor explicitly.
1793 // MockFoo(const MockFoo& src) {}
1794 // ...
1795 // };
1796 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001797}; // class FunctionMockerBase
1798
mistergdf428ec2018-08-20 14:48:45 -04001799GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
shiqiane35fdd92008-12-10 05:08:54 +00001800
1801// Implements methods of FunctionMockerBase.
1802
1803// Verifies that all expectations on this mock function have been
1804// satisfied. Reports one or more Google Test non-fatal failures and
1805// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001806
1807// Reports an uninteresting call (whose description is in msg) in the
1808// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001809void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001810
shiqiane35fdd92008-12-10 05:08:54 +00001811} // namespace internal
1812
1813// The style guide prohibits "using" statements in a namespace scope
1814// inside a header file. However, the MockSpec class template is
1815// meant to be defined in the ::testing namespace. The following line
1816// is just a trick for working around a bug in MSVC 8.0, which cannot
1817// handle it if we define MockSpec in ::testing.
1818using internal::MockSpec;
1819
1820// Const(x) is a convenient function for obtaining a const reference
1821// to x. This is useful for setting expectations on an overloaded
1822// const mock method, e.g.
1823//
1824// class MockFoo : public FooInterface {
1825// public:
1826// MOCK_METHOD0(Bar, int());
1827// MOCK_CONST_METHOD0(Bar, int&());
1828// };
1829//
1830// MockFoo foo;
1831// // Expects a call to non-const MockFoo::Bar().
1832// EXPECT_CALL(foo, Bar());
1833// // Expects a call to const MockFoo::Bar().
1834// EXPECT_CALL(Const(foo), Bar());
1835template <typename T>
1836inline const T& Const(const T& x) { return x; }
1837
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001838// Constructs an Expectation object that references and co-owns exp.
1839inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1840 : expectation_base_(exp.GetHandle().expectation_base()) {}
1841
shiqiane35fdd92008-12-10 05:08:54 +00001842} // namespace testing
1843
mistergdf428ec2018-08-20 14:48:45 -04001844GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1845
David Sunderlandf437f8c2018-04-18 19:28:56 -04001846// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1847// required to avoid compile errors when the name of the method used in call is
1848// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1849// tests in internal/gmock-spec-builders_test.cc for more details.
1850//
1851// This macro supports statements both with and without parameter matchers. If
1852// the parameter list is omitted, gMock will accept any parameters, which allows
1853// tests to be written that don't need to encode the number of method
1854// parameter. This technique may only be used for non-overloaded methods.
1855//
1856// // These are the same:
duxiuxing65a49a72018-07-17 15:46:47 +08001857// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1858// ON_CALL(mock, NoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001859//
1860// // As are these:
duxiuxing65a49a72018-07-17 15:46:47 +08001861// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1862// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001863//
1864// // Can also specify args if you want, of course:
duxiuxing65a49a72018-07-17 15:46:47 +08001865// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001866//
1867// // Overloads work as long as you specify parameters:
duxiuxing65a49a72018-07-17 15:46:47 +08001868// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1869// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001870//
1871// // Oops! Which overload did you want?
duxiuxing65a49a72018-07-17 15:46:47 +08001872// ON_CALL(mock, OverloadedMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001873// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1874//
1875// How this works: The mock class uses two overloads of the gmock_Method
1876// expectation setter method plus an operator() overload on the MockSpec object.
1877// In the matcher list form, the macro expands to:
1878//
1879// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001880// ON_CALL(mock, TwoArgsMethod(_, 45))...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001881//
duxiuxing65a49a72018-07-17 15:46:47 +08001882// // ...expands to:
1883// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001884// |-------------v---------------||------------v-------------|
1885// invokes first overload swallowed by operator()
1886//
duxiuxing65a49a72018-07-17 15:46:47 +08001887// // ...which is essentially:
1888// mock.gmock_TwoArgsMethod(_, 45)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001889//
1890// Whereas the form without a matcher list:
1891//
1892// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001893// ON_CALL(mock, TwoArgsMethod)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001894//
duxiuxing65a49a72018-07-17 15:46:47 +08001895// // ...expands to:
1896// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001897// |-----------------------v--------------------------|
1898// invokes second overload
1899//
duxiuxing65a49a72018-07-17 15:46:47 +08001900// // ...which is essentially:
1901// mock.gmock_TwoArgsMethod(_, _)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001902//
1903// The WithoutMatchers() argument is used to disambiguate overloads and to
1904// block the caller from accidentally invoking the second overload directly. The
1905// second argument is an internal type derived from the method signature. The
1906// failure to disambiguate two overloads of this method in the ON_CALL statement
1907// is how we block callers from setting expectations on overloaded methods.
1908#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1909 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \
1910 .Setter(__FILE__, __LINE__, #mock_expr, #call)
shiqiane35fdd92008-12-10 05:08:54 +00001911
David Sunderlandf437f8c2018-04-18 19:28:56 -04001912#define ON_CALL(obj, call) \
1913 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1914
1915#define EXPECT_CALL(obj, call) \
1916 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
shiqiane35fdd92008-12-10 05:08:54 +00001917
1918#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_