blob: 735a3bcbb4a6db54f3c0a7e20bcffb27cff3e81d [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
Adam Badura1f809602019-07-11 09:49:59 +020064#include <functional>
shiqiane35fdd92008-12-10 05:08:54 +000065#include <map>
misterg80b43d92018-10-29 11:09:33 -040066#include <memory>
shiqiane35fdd92008-12-10 05:08:54 +000067#include <set>
68#include <sstream>
69#include <string>
Abseil Team29b47e42018-10-16 15:29:37 -040070#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000071#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000072#include "gmock/gmock-actions.h"
73#include "gmock/gmock-cardinalities.h"
74#include "gmock/gmock-matchers.h"
75#include "gmock/internal/gmock-internal-utils.h"
76#include "gmock/internal/gmock-port.h"
77#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000078
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050079#if GTEST_HAS_EXCEPTIONS
80# include <stdexcept> // NOLINT
81#endif
82
mistergdf428ec2018-08-20 14:48:45 -040083GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
84/* class A needs to have dll-interface to be used by clients of class B */)
85
shiqiane35fdd92008-12-10 05:08:54 +000086namespace testing {
87
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000088// An abstract handle of an expectation.
89class Expectation;
90
91// A set of expectation handles.
92class ExpectationSet;
93
shiqiane35fdd92008-12-10 05:08:54 +000094// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
95// and MUST NOT BE USED IN USER CODE!!!
96namespace internal {
97
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000098// Implements a mock function.
99template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +0000100
101// Base class for expectations.
102class ExpectationBase;
103
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000104// Implements an expectation.
105template <typename F> class TypedExpectation;
106
shiqiane35fdd92008-12-10 05:08:54 +0000107// Helper class for testing the Expectation class template.
108class ExpectationTester;
109
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
Abseil Teamde5be0e2018-11-08 11:14:50 -0500126// Abstract base class of FunctionMocker. This is the
shiqiane35fdd92008-12-10 05:08:54 +0000127// type-agnostic part of the function mocker interface. Its pure
Abseil Teamde5be0e2018-11-08 11:14:50 -0500128// virtual methods are implemented by FunctionMocker.
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.
vladlosev4d60a592011-10-24 21:16:22 +0000190 void RegisterOwner(const void* mock_obj)
191 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000192
193 // Sets the mock object this mock method belongs to, and sets the
194 // name of the mock function. Will be called upon each invocation
195 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000196 void SetOwnerAndName(const void* mock_obj, const char* name)
197 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000198
199 // Returns the mock object this mock method belongs to. Must be
200 // called after RegisterOwner() or SetOwnerAndName() has been
201 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000202 const void* MockObject() const
203 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000204
205 // Returns the name of this mock method. Must be called after
206 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000207 const char* Name() const
208 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000209
210 // Returns the result of invoking this mock function with the given
211 // arguments. This function can be safely called from multiple
212 // threads concurrently. The caller is responsible for deleting the
213 // result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400214 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
215 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000216
217 protected:
218 typedef std::vector<const void*> UntypedOnCallSpecs;
219
misterg80b43d92018-10-29 11:09:33 -0400220 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
zhanyong.waned6c9272011-02-23 19:39:27 +0000221
222 // Returns an Expectation object that references and co-owns exp,
223 // which must be an expectation on this mock function.
224 Expectation GetHandleOf(ExpectationBase* exp);
225
226 // Address of the mock object this mock method belongs to. Only
227 // valid after this mock method has been called or
228 // ON_CALL/EXPECT_CALL has been invoked on it.
229 const void* mock_obj_; // Protected by g_gmock_mutex.
230
231 // Name of the function being mocked. Only valid after this mock
232 // method has been called.
233 const char* name_; // Protected by g_gmock_mutex.
234
235 // All default action specs for this function mocker.
236 UntypedOnCallSpecs untyped_on_call_specs_;
237
238 // All expectations for this function mocker.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400239 //
240 // It's undefined behavior to interleave expectations (EXPECT_CALLs
241 // or ON_CALLs) and mock function calls. Also, the order of
242 // expectations is important. Therefore it's a logic race condition
243 // to read/write untyped_expectations_ concurrently. In order for
244 // tools like tsan to catch concurrent read/write accesses to
245 // untyped_expectations, we deliberately leave accesses to it
246 // unprotected.
zhanyong.waned6c9272011-02-23 19:39:27 +0000247 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000248}; // class UntypedFunctionMockerBase
249
zhanyong.waned6c9272011-02-23 19:39:27 +0000250// Untyped base class for OnCallSpec<F>.
251class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000252 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000253 // The arguments are the location of the ON_CALL() statement.
254 UntypedOnCallSpecBase(const char* a_file, int a_line)
255 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000256
257 // Where in the source file was the default action spec defined?
258 const char* file() const { return file_; }
259 int line() const { return line_; }
260
zhanyong.waned6c9272011-02-23 19:39:27 +0000261 protected:
262 // Gives each clause in the ON_CALL() statement a name.
263 enum Clause {
264 // Do not change the order of the enum members! The run-time
265 // syntax checking relies on it.
266 kNone,
267 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000268 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000269 };
270
271 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400272 void AssertSpecProperty(bool property,
273 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000274 Assert(property, file_, line_, failure_message);
275 }
276
277 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400278 void ExpectSpecProperty(bool property,
279 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000280 Expect(property, file_, line_, failure_message);
281 }
282
283 const char* file_;
284 int line_;
285
286 // The last clause in the ON_CALL() statement as seen so far.
287 // Initially kNone and changes as the statement is parsed.
288 Clause last_clause_;
289}; // class UntypedOnCallSpecBase
290
291// This template class implements an ON_CALL spec.
292template <typename F>
293class OnCallSpec : public UntypedOnCallSpecBase {
294 public:
295 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
296 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
297
298 // Constructs an OnCallSpec object from the information inside
299 // the parenthesis of an ON_CALL() statement.
300 OnCallSpec(const char* a_file, int a_line,
301 const ArgumentMatcherTuple& matchers)
302 : UntypedOnCallSpecBase(a_file, a_line),
303 matchers_(matchers),
Abseil Team9518a572019-01-17 15:56:41 -0500304 // By default, extra_matcher_ should match anything. However,
305 // we cannot initialize it with _ as that causes ambiguity between
306 // Matcher's copy and move constructor for some argument types.
307 extra_matcher_(A<const ArgumentTuple&>()) {}
zhanyong.waned6c9272011-02-23 19:39:27 +0000308
zhanyong.wanbf550852009-06-09 06:09:53 +0000309 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000310 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000311 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000312 ExpectSpecProperty(last_clause_ < kWith,
313 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000314 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000315 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000316
317 extra_matcher_ = m;
318 return *this;
319 }
320
321 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000322 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000323 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000324 ".WillByDefault() must appear "
325 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000326 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000327
328 ExpectSpecProperty(!action.IsDoDefault(),
329 "DoDefault() cannot be used in ON_CALL().");
330 action_ = action;
331 return *this;
332 }
333
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200334 // Returns true if the given arguments match the matchers.
shiqiane35fdd92008-12-10 05:08:54 +0000335 bool Matches(const ArgumentTuple& args) const {
336 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
337 }
338
339 // Returns the action specified by the user.
340 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000341 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000342 ".WillByDefault() must appear exactly "
343 "once in an ON_CALL().");
344 return action_;
345 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000346
shiqiane35fdd92008-12-10 05:08:54 +0000347 private:
shiqiane35fdd92008-12-10 05:08:54 +0000348 // The information in statement
349 //
350 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000351 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000352 // .WillByDefault(action);
353 //
354 // is recorded in the data members like this:
355 //
356 // source file that contains the statement => file_
357 // line number of the statement => line_
358 // matchers => matchers_
359 // multi-argument-matcher => extra_matcher_
360 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000361 ArgumentMatcherTuple matchers_;
362 Matcher<const ArgumentTuple&> extra_matcher_;
363 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000364}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000365
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000366// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000367enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000368 kAllow,
369 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000370 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000371};
372
373} // namespace internal
374
375// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000376class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000377 public:
378 // The following public methods can be called concurrently.
379
zhanyong.wandf35a762009-04-22 22:25:31 +0000380 // Tells Google Mock to ignore mock_obj when checking for leaked
381 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000382 static void AllowLeak(const void* mock_obj)
383 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000384
shiqiane35fdd92008-12-10 05:08:54 +0000385 // Verifies and clears all expectations on the given mock object.
386 // If the expectations aren't satisfied, generates one or more
387 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000388 static bool VerifyAndClearExpectations(void* mock_obj)
389 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000390
391 // Verifies all expectations on the given mock object and clears its
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200392 // default actions and expectations. Returns true if the
shiqiane35fdd92008-12-10 05:08:54 +0000393 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000394 static bool VerifyAndClear(void* mock_obj)
395 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000396
Gennadiy Civil20eaf6e2018-10-23 15:13:41 -0400397 // Returns whether the mock was created as a naggy mock (default)
Jonathan Wendeborn67a240a2018-10-16 08:07:15 +0200398 static bool IsNaggy(void* mock_obj)
399 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
Gennadiy Civil20eaf6e2018-10-23 15:13:41 -0400400 // Returns whether the mock was created as a nice mock
Jonathan Wendeborn67a240a2018-10-16 08:07:15 +0200401 static bool IsNice(void* mock_obj)
402 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
Gennadiy Civil20eaf6e2018-10-23 15:13:41 -0400403 // Returns whether the mock was created as a strict mock
Jonathan Wendeborn67a240a2018-10-16 08:07:15 +0200404 static bool IsStrict(void* mock_obj)
405 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
406
shiqiane35fdd92008-12-10 05:08:54 +0000407 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000408 friend class internal::UntypedFunctionMockerBase;
409
shiqiane35fdd92008-12-10 05:08:54 +0000410 // Needed for a function mocker to register itself (so that we know
411 // how to clear a mock object).
412 template <typename F>
Abseil Teamde5be0e2018-11-08 11:14:50 -0500413 friend class internal::FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +0000414
shiqiane35fdd92008-12-10 05:08:54 +0000415 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700416 friend class NiceMock;
shiqiane35fdd92008-12-10 05:08:54 +0000417
418 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700419 friend class NaggyMock;
zhanyong.wan844fa942013-03-01 01:54:22 +0000420
421 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700422 friend class StrictMock;
shiqiane35fdd92008-12-10 05:08:54 +0000423
424 // Tells Google Mock to allow uninteresting calls on the given mock
425 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000426 static void AllowUninterestingCalls(const void* mock_obj)
427 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000428
429 // Tells Google Mock to warn the user about uninteresting calls on
430 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000431 static void WarnUninterestingCalls(const void* mock_obj)
432 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000433
434 // Tells Google Mock to fail uninteresting calls on the given mock
435 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000436 static void FailUninterestingCalls(const void* mock_obj)
437 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000438
439 // Tells Google Mock the given mock object is being destroyed and
440 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000441 static void UnregisterCallReaction(const void* mock_obj)
442 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000443
444 // Returns the reaction Google Mock will have on uninteresting calls
445 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000446 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000447 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000448 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000449
450 // Verifies that all expectations on the given mock object have been
451 // satisfied. Reports one or more Google Test non-fatal failures
452 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000453 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
454 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000455
456 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000457 static void ClearDefaultActionsLocked(void* mock_obj)
458 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000459
460 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000461 static void Register(
462 const void* mock_obj,
463 internal::UntypedFunctionMockerBase* mocker)
464 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000465
zhanyong.wandf35a762009-04-22 22:25:31 +0000466 // Tells Google Mock where in the source code mock_obj is used in an
467 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
468 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000469 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000470 const void* mock_obj, const char* file, int line)
471 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000472
shiqiane35fdd92008-12-10 05:08:54 +0000473 // Unregisters a mock method; removes the owning mock object from
474 // the registry when the last mock method associated with it has
475 // been unregistered. This is called only in the destructor of
Abseil Teamde5be0e2018-11-08 11:14:50 -0500476 // FunctionMocker.
vladlosev4d60a592011-10-24 21:16:22 +0000477 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
478 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000479}; // class Mock
480
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000481// An abstract handle of an expectation. Useful in the .After()
482// clause of EXPECT_CALL() for setting the (partial) order of
483// expectations. The syntax:
484//
485// Expectation e1 = EXPECT_CALL(...)...;
486// EXPECT_CALL(...).After(e1)...;
487//
488// sets two expectations where the latter can only be matched after
489// the former has been satisfied.
490//
491// Notes:
492// - This class is copyable and has value semantics.
493// - Constness is shallow: a const Expectation object itself cannot
494// be modified, but the mutable methods of the ExpectationBase
495// object it references can be called via expectation_base().
misterg80b43d92018-10-29 11:09:33 -0400496
vladlosev587c1b32011-05-20 00:42:22 +0000497class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000498 public:
499 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000500 Expectation();
501
502 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000503
504 // This single-argument ctor must not be explicit, in order to support the
505 // Expectation e = EXPECT_CALL(...);
506 // syntax.
507 //
508 // A TypedExpectation object stores its pre-requisites as
509 // Expectation objects, and needs to call the non-const Retire()
510 // method on the ExpectationBase objects they reference. Therefore
511 // Expectation must receive a *non-const* reference to the
512 // ExpectationBase object.
513 Expectation(internal::ExpectationBase& exp); // NOLINT
514
515 // The compiler-generated copy ctor and operator= work exactly as
516 // intended, so we don't need to define our own.
517
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200518 // Returns true if rhs references the same expectation as this object does.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000519 bool operator==(const Expectation& rhs) const {
520 return expectation_base_ == rhs.expectation_base_;
521 }
522
523 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
524
525 private:
526 friend class ExpectationSet;
527 friend class Sequence;
528 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000529 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000530
531 template <typename F>
Abseil Teamde5be0e2018-11-08 11:14:50 -0500532 friend class ::testing::internal::FunctionMocker;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000533
534 template <typename F>
535 friend class ::testing::internal::TypedExpectation;
536
537 // This comparator is needed for putting Expectation objects into a set.
538 class Less {
539 public:
540 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
541 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
542 }
543 };
544
545 typedef ::std::set<Expectation, Less> Set;
546
547 Expectation(
misterg80b43d92018-10-29 11:09:33 -0400548 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000549
550 // Returns the expectation this object references.
misterg80b43d92018-10-29 11:09:33 -0400551 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000552 return expectation_base_;
553 }
554
misterg80b43d92018-10-29 11:09:33 -0400555 // A shared_ptr that co-owns the expectation this handle references.
556 std::shared_ptr<internal::ExpectationBase> expectation_base_;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000557};
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
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200600 // Returns true if rhs contains the same set of Expectation objects
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000601 // 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:
misterg80b43d92018-10-29 11:09:33 -0400638 // The last expectation in this sequence.
639 std::shared_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000640}; // class Sequence
641
642// An object of this type causes all EXPECT_CALL() statements
643// encountered in its scope to be put in an anonymous sequence. The
644// work is done in the constructor and destructor. You should only
645// create an InSequence object on the stack.
646//
647// The sole purpose for this class is to support easy definition of
648// sequential expectations, e.g.
649//
650// {
651// InSequence dummy; // The name of the object doesn't matter.
652//
653// // The following expectations must match in the order they appear.
654// EXPECT_CALL(a, Bar())...;
655// EXPECT_CALL(a, Baz())...;
656// ...
657// EXPECT_CALL(b, Xyz())...;
658// }
659//
660// You can create InSequence objects in multiple threads, as long as
661// they are used to affect different mock objects. The idea is that
662// each thread can create and set up its own mocks as if it's the only
663// thread. However, for clarity of your tests we recommend you to set
664// up mocks in the main thread unless you have a good reason not to do
665// so.
vladlosev587c1b32011-05-20 00:42:22 +0000666class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000667 public:
668 InSequence();
669 ~InSequence();
670 private:
671 bool sequence_created_;
672
673 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000674} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000675
676namespace internal {
677
678// Points to the implicit sequence introduced by a living InSequence
679// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000680GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000681
682// Base class for implementing expectations.
683//
684// There are two reasons for having a type-agnostic base class for
685// Expectation:
686//
687// 1. We need to store collections of expectations of different
688// types (e.g. all pre-requisites of a particular expectation, all
689// expectations in a sequence). Therefore these expectation objects
690// must share a common base class.
691//
692// 2. We can avoid binary code bloat by moving methods not depending
693// on the template argument of Expectation to the base class.
694//
695// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000696class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000697 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000698 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400699 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000700
701 virtual ~ExpectationBase();
702
703 // Where in the source file was the expectation spec defined?
704 const char* file() const { return file_; }
705 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000706 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000707 // Returns the cardinality specified in the expectation spec.
708 const Cardinality& cardinality() const { return cardinality_; }
709
710 // Describes the source file location of this expectation.
711 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000712 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000713 }
714
715 // Describes how many times a function call matching this
716 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000717 void DescribeCallCountTo(::std::ostream* os) const
718 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000719
720 // If this mock method has an extra matcher (i.e. .With(matcher)),
721 // describes it to the ostream.
722 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000723
shiqiane35fdd92008-12-10 05:08:54 +0000724 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000725 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000726 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000727
728 enum Clause {
729 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000730 kNone,
731 kWith,
732 kTimes,
733 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000734 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000735 kWillOnce,
736 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000737 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000738 };
739
zhanyong.waned6c9272011-02-23 19:39:27 +0000740 typedef std::vector<const void*> UntypedActions;
741
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000742 // Returns an Expectation object that references and co-owns this
743 // expectation.
744 virtual Expectation GetHandle() = 0;
745
shiqiane35fdd92008-12-10 05:08:54 +0000746 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400747 void AssertSpecProperty(bool property,
748 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000749 Assert(property, file_, line_, failure_message);
750 }
751
752 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400753 void ExpectSpecProperty(bool property,
754 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000755 Expect(property, file_, line_, failure_message);
756 }
757
758 // Explicitly specifies the cardinality of this expectation. Used
759 // by the subclasses to implement the .Times() clause.
760 void SpecifyCardinality(const Cardinality& cardinality);
761
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200762 // Returns true if the user specified the cardinality explicitly
shiqiane35fdd92008-12-10 05:08:54 +0000763 // using a .Times().
764 bool cardinality_specified() const { return cardinality_specified_; }
765
766 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000767 void set_cardinality(const Cardinality& a_cardinality) {
768 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000769 }
770
771 // The following group of methods should only be called after the
772 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
773 // the current thread.
774
775 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000776 void RetireAllPreRequisites()
777 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000778
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200779 // Returns true if this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000780 bool is_retired() const
781 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000782 g_gmock_mutex.AssertHeld();
783 return retired_;
784 }
785
786 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000787 void Retire()
788 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000789 g_gmock_mutex.AssertHeld();
790 retired_ = true;
791 }
792
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200793 // Returns true if this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000794 bool IsSatisfied() const
795 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000796 g_gmock_mutex.AssertHeld();
797 return cardinality().IsSatisfiedByCallCount(call_count_);
798 }
799
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200800 // Returns true if this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000801 bool IsSaturated() const
802 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000803 g_gmock_mutex.AssertHeld();
804 return cardinality().IsSaturatedByCallCount(call_count_);
805 }
806
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200807 // Returns true if this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000808 bool IsOverSaturated() const
809 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000810 g_gmock_mutex.AssertHeld();
811 return cardinality().IsOverSaturatedByCallCount(call_count_);
812 }
813
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200814 // Returns true if all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000815 bool AllPrerequisitesAreSatisfied() const
816 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000817
818 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000819 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
820 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000821
822 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000823 int call_count() const
824 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000825 g_gmock_mutex.AssertHeld();
826 return call_count_;
827 }
828
829 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000830 void IncrementCallCount()
831 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000832 g_gmock_mutex.AssertHeld();
833 call_count_++;
834 }
835
zhanyong.waned6c9272011-02-23 19:39:27 +0000836 // Checks the action count (i.e. the number of WillOnce() and
837 // WillRepeatedly() clauses) against the cardinality if this hasn't
838 // been done before. Prints a warning if there are too many or too
839 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000840 void CheckActionCountIfNotDone() const
841 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000842
shiqiane35fdd92008-12-10 05:08:54 +0000843 friend class ::testing::Sequence;
844 friend class ::testing::internal::ExpectationTester;
845
846 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000847 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000848
zhanyong.waned6c9272011-02-23 19:39:27 +0000849 // Implements the .Times() clause.
850 void UntypedTimes(const Cardinality& a_cardinality);
851
shiqiane35fdd92008-12-10 05:08:54 +0000852 // This group of fields are part of the spec and won't change after
853 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000854 const char* file_; // The file that contains the expectation.
855 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400856 const std::string source_text_; // The EXPECT_CALL(...) source text.
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200857 // True if the cardinality is specified explicitly.
shiqiane35fdd92008-12-10 05:08:54 +0000858 bool cardinality_specified_;
859 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000860 // The immediate pre-requisites (i.e. expectations that must be
861 // satisfied before this expectation can be matched) of this
misterg80b43d92018-10-29 11:09:33 -0400862 // expectation. We use std::shared_ptr in the set because we want an
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000863 // Expectation object to be co-owned by its FunctionMocker and its
864 // successors. This allows multiple mock objects to be deleted at
865 // different times.
866 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000867
868 // This group of fields are the current state of the expectation,
869 // and can change as the mock function is called.
870 int call_count_; // How many times this expectation has been invoked.
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200871 bool retired_; // True if this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000872 UntypedActions untyped_actions_;
873 bool extra_matcher_specified_;
874 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
875 bool retires_on_saturation_;
876 Clause last_clause_;
877 mutable bool action_count_checked_; // Under mutex_.
878 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000879
880 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000881}; // class ExpectationBase
882
883// Impements an expectation for the given function type.
884template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000885class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000886 public:
887 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
888 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
889 typedef typename Function<F>::Result Result;
890
Abseil Teamde5be0e2018-11-08 11:14:50 -0500891 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
Nico Weber09fd5b32017-05-15 17:07:03 -0400892 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000893 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000894 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000895 owner_(owner),
896 matchers_(m),
Abseil Team9518a572019-01-17 15:56:41 -0500897 // By default, extra_matcher_ should match anything. However,
898 // we cannot initialize it with _ as that causes ambiguity between
899 // Matcher's copy and move constructor for some argument types.
900 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000901 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000902
Abseil Team26743362018-12-03 11:30:02 -0500903 ~TypedExpectation() override {
shiqiane35fdd92008-12-10 05:08:54 +0000904 // Check the validity of the action count if it hasn't been done
905 // yet (for example, if the expectation was never used).
906 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000907 for (UntypedActions::const_iterator it = untyped_actions_.begin();
908 it != untyped_actions_.end(); ++it) {
909 delete static_cast<const Action<F>*>(*it);
910 }
shiqiane35fdd92008-12-10 05:08:54 +0000911 }
912
zhanyong.wanbf550852009-06-09 06:09:53 +0000913 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000914 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000915 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000916 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000917 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000918 "more than once in an EXPECT_CALL().");
919 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000920 ExpectSpecProperty(last_clause_ < kWith,
921 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000922 "clause in an EXPECT_CALL().");
923 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000924 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000925
926 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000927 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000928 return *this;
929 }
930
931 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000932 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000933 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000934 return *this;
935 }
936
937 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000938 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000939 return Times(Exactly(n));
940 }
941
942 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000943 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000944 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000945 ".InSequence() cannot appear after .After(),"
946 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000947 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000948 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000949
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000950 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000951 return *this;
952 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000953 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000954 return InSequence(s1).InSequence(s2);
955 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000956 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
957 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000958 return InSequence(s1, s2).InSequence(s3);
959 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000960 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
961 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000962 return InSequence(s1, s2, s3).InSequence(s4);
963 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000964 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
965 const Sequence& s3, const Sequence& s4,
966 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000967 return InSequence(s1, s2, s3, s4).InSequence(s5);
968 }
969
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000970 // Implements that .After() clause.
971 TypedExpectation& After(const ExpectationSet& s) {
972 ExpectSpecProperty(last_clause_ <= kAfter,
973 ".After() cannot appear after .WillOnce(),"
974 " .WillRepeatedly(), or "
975 ".RetiresOnSaturation().");
976 last_clause_ = kAfter;
977
978 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
979 immediate_prerequisites_ += *it;
980 }
981 return *this;
982 }
983 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
984 return After(s1).After(s2);
985 }
986 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
987 const ExpectationSet& s3) {
988 return After(s1, s2).After(s3);
989 }
990 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
991 const ExpectationSet& s3, const ExpectationSet& s4) {
992 return After(s1, s2, s3).After(s4);
993 }
994 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
995 const ExpectationSet& s3, const ExpectationSet& s4,
996 const ExpectationSet& s5) {
997 return After(s1, s2, s3, s4).After(s5);
998 }
999
shiqiane35fdd92008-12-10 05:08:54 +00001000 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001001 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001002 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +00001003 ".WillOnce() cannot appear after "
1004 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001005 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001006
zhanyong.waned6c9272011-02-23 19:39:27 +00001007 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001008 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001009 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001010 }
1011 return *this;
1012 }
1013
1014 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001015 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001016 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001017 ExpectSpecProperty(false,
1018 ".WillRepeatedly() cannot appear "
1019 "more than once in an EXPECT_CALL().");
1020 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001021 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001022 ".WillRepeatedly() cannot appear "
1023 "after .RetiresOnSaturation().");
1024 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001025 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001026 repeated_action_specified_ = true;
1027
1028 repeated_action_ = action;
1029 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001030 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001031 }
1032
1033 // Now that no more action clauses can be specified, we check
1034 // whether their count makes sense.
1035 CheckActionCountIfNotDone();
1036 return *this;
1037 }
1038
1039 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001040 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001041 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001042 ".RetiresOnSaturation() cannot appear "
1043 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001044 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001045 retires_on_saturation_ = true;
1046
1047 // Now that no more action clauses can be specified, we check
1048 // whether their count makes sense.
1049 CheckActionCountIfNotDone();
1050 return *this;
1051 }
1052
1053 // Returns the matchers for the arguments as specified inside the
1054 // EXPECT_CALL() macro.
1055 const ArgumentMatcherTuple& matchers() const {
1056 return matchers_;
1057 }
1058
zhanyong.wanbf550852009-06-09 06:09:53 +00001059 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001060 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1061 return extra_matcher_;
1062 }
1063
shiqiane35fdd92008-12-10 05:08:54 +00001064 // Returns the action specified by the .WillRepeatedly() clause.
1065 const Action<F>& repeated_action() const { return repeated_action_; }
1066
zhanyong.waned6c9272011-02-23 19:39:27 +00001067 // If this mock method has an extra matcher (i.e. .With(matcher)),
1068 // describes it to the ostream.
Abseil Team26743362018-12-03 11:30:02 -05001069 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
vladlosev6c54a5e2009-10-21 06:15:34 +00001070 if (extra_matcher_specified_) {
1071 *os << " Expected args: ";
1072 extra_matcher_.DescribeTo(os);
1073 *os << "\n";
1074 }
1075 }
1076
shiqiane35fdd92008-12-10 05:08:54 +00001077 private:
1078 template <typename Function>
Abseil Teamde5be0e2018-11-08 11:14:50 -05001079 friend class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +00001080
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001081 // Returns an Expectation object that references and co-owns this
1082 // expectation.
Abseil Team26743362018-12-03 11:30:02 -05001083 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001084
shiqiane35fdd92008-12-10 05:08:54 +00001085 // The following methods will be called only after the EXPECT_CALL()
1086 // statement finishes and when the current thread holds
1087 // g_gmock_mutex.
1088
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +02001089 // Returns true if this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001090 bool Matches(const ArgumentTuple& args) const
1091 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001092 g_gmock_mutex.AssertHeld();
1093 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1094 }
1095
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +02001096 // Returns true if this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001097 bool ShouldHandleArguments(const ArgumentTuple& args) const
1098 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001099 g_gmock_mutex.AssertHeld();
1100
1101 // In case the action count wasn't checked when the expectation
1102 // was defined (e.g. if this expectation has no WillRepeatedly()
1103 // or RetiresOnSaturation() clause), we check it when the
1104 // expectation is used for the first time.
1105 CheckActionCountIfNotDone();
1106 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1107 }
1108
1109 // Describes the result of matching the arguments against this
1110 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001111 void ExplainMatchResultTo(
1112 const ArgumentTuple& args,
1113 ::std::ostream* os) const
1114 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001115 g_gmock_mutex.AssertHeld();
1116
1117 if (is_retired()) {
1118 *os << " Expected: the expectation is active\n"
1119 << " Actual: it is retired\n";
1120 } else if (!Matches(args)) {
1121 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001122 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001123 }
zhanyong.wan82113312010-01-08 21:55:40 +00001124 StringMatchResultListener listener;
1125 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001126 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001127 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001128 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001129
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001130 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001131 *os << "\n";
1132 }
1133 } else if (!AllPrerequisitesAreSatisfied()) {
1134 *os << " Expected: all pre-requisites are satisfied\n"
1135 << " Actual: the following immediate pre-requisites "
1136 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001137 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001138 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1139 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001140 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001141 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001142 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001143 *os << "pre-requisite #" << i++ << "\n";
1144 }
1145 *os << " (end of pre-requisites)\n";
1146 } else {
1147 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001148 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001149 // is called only when the mock function call does NOT match the
1150 // expectation.
1151 *os << "The call matches the expectation.\n";
1152 }
1153 }
1154
1155 // Returns the action that should be taken for the current invocation.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001156 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
1157 const ArgumentTuple& args) const
1158 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001159 g_gmock_mutex.AssertHeld();
1160 const int count = call_count();
1161 Assert(count >= 1, __FILE__, __LINE__,
1162 "call_count() is <= 0 when GetCurrentAction() is "
1163 "called - this should never happen.");
1164
zhanyong.waned6c9272011-02-23 19:39:27 +00001165 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001166 if (action_count > 0 && !repeated_action_specified_ &&
1167 count > action_count) {
1168 // If there is at least one WillOnce() and no WillRepeatedly(),
1169 // we warn the user when the WillOnce() clauses ran out.
1170 ::std::stringstream ss;
1171 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001172 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001173 << "Called " << count << " times, but only "
1174 << action_count << " WillOnce()"
1175 << (action_count == 1 ? " is" : "s are") << " specified - ";
1176 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001177 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001178 }
1179
Gennadiy Civila651a4d2018-10-12 16:12:32 -04001180 return count <= action_count
1181 ? *static_cast<const Action<F>*>(
1182 untyped_actions_[static_cast<size_t>(count - 1)])
1183 : repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001184 }
1185
1186 // Given the arguments of a mock function call, if the call will
1187 // over-saturate this expectation, returns the default action;
1188 // otherwise, returns the next action in this expectation. Also
1189 // describes *what* happened to 'what', and explains *why* Google
1190 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001191 // IncrementCallCount(). A return value of NULL means the default
1192 // action.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001193 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
1194 const ArgumentTuple& args,
1195 ::std::ostream* what,
1196 ::std::ostream* why)
1197 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001198 g_gmock_mutex.AssertHeld();
1199 if (IsSaturated()) {
1200 // We have an excessive call.
1201 IncrementCallCount();
1202 *what << "Mock function called more times than expected - ";
1203 mocker->DescribeDefaultActionTo(args, what);
1204 DescribeCallCountTo(why);
1205
Abseil Team4bb49ed2018-10-04 18:28:05 -04001206 return nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001207 }
1208
1209 IncrementCallCount();
1210 RetireAllPreRequisites();
1211
zhanyong.waned6c9272011-02-23 19:39:27 +00001212 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001213 Retire();
1214 }
1215
1216 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001217 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001218 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001219 }
1220
1221 // All the fields below won't change once the EXPECT_CALL()
1222 // statement finishes.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001223 FunctionMocker<F>* const owner_;
shiqiane35fdd92008-12-10 05:08:54 +00001224 ArgumentMatcherTuple matchers_;
1225 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001226 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001227
1228 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001229}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001230
1231// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1232// specifying the default behavior of, or expectation on, a mock
1233// function.
1234
1235// Note: class MockSpec really belongs to the ::testing namespace.
1236// However if we define it in ::testing, MSVC will complain when
1237// classes in ::testing::internal declare it as a friend class
1238// template. To workaround this compiler bug, we define MockSpec in
1239// ::testing::internal and import it into ::testing.
1240
zhanyong.waned6c9272011-02-23 19:39:27 +00001241// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001242GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1243 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001244 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001245
shiqiane35fdd92008-12-10 05:08:54 +00001246template <typename F>
1247class MockSpec {
1248 public:
1249 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1250 typedef typename internal::Function<F>::ArgumentMatcherTuple
1251 ArgumentMatcherTuple;
1252
1253 // Constructs a MockSpec object, given the function mocker object
1254 // that the spec is associated with.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001255 MockSpec(internal::FunctionMocker<F>* function_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001256 const ArgumentMatcherTuple& matchers)
1257 : function_mocker_(function_mocker), matchers_(matchers) {}
shiqiane35fdd92008-12-10 05:08:54 +00001258
1259 // Adds a new default action spec to the function mocker and returns
1260 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001261 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001262 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001263 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001264 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001265 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001266 }
1267
1268 // Adds a new expectation spec to the function mocker and returns
1269 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001270 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001271 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001272 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1273 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001274 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001275 return function_mocker_->AddNewExpectation(
1276 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001277 }
1278
David Sunderlandf437f8c2018-04-18 19:28:56 -04001279 // This operator overload is used to swallow the superfluous parameter list
1280 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1281 // explanation.
1282 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1283 return *this;
1284 }
1285
shiqiane35fdd92008-12-10 05:08:54 +00001286 private:
1287 template <typename Function>
1288 friend class internal::FunctionMocker;
1289
shiqiane35fdd92008-12-10 05:08:54 +00001290 // The function mocker that owns this spec.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001291 internal::FunctionMocker<F>* const function_mocker_;
shiqiane35fdd92008-12-10 05:08:54 +00001292 // The argument matchers specified in the spec.
1293 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001294
1295 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001296}; // class MockSpec
1297
kosakb5c81092014-01-29 06:41:44 +00001298// Wrapper type for generically holding an ordinary value or lvalue reference.
1299// If T is not a reference type, it must be copyable or movable.
1300// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1301// T is a move-only value type (which means that it will always be copyable
1302// if the current platform does not support move semantics).
1303//
1304// The primary template defines handling for values, but function header
1305// comments describe the contract for the whole template (including
1306// specializations).
1307template <typename T>
1308class ReferenceOrValueWrapper {
1309 public:
1310 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001311 explicit ReferenceOrValueWrapper(T value)
Abseil Team29b47e42018-10-16 15:29:37 -04001312 : value_(std::move(value)) {
kosakd370f852014-11-17 01:14:16 +00001313 }
kosakb5c81092014-01-29 06:41:44 +00001314
1315 // Unwraps and returns the underlying value/reference, exactly as
1316 // originally passed. The behavior of calling this more than once on
1317 // the same object is unspecified.
Abseil Team29b47e42018-10-16 15:29:37 -04001318 T Unwrap() { return std::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001319
1320 // Provides nondestructive access to the underlying value/reference.
1321 // Always returns a const reference (more precisely,
1322 // const RemoveReference<T>&). The behavior of calling this after
1323 // calling Unwrap on the same object is unspecified.
1324 const T& Peek() const {
1325 return value_;
1326 }
1327
1328 private:
1329 T value_;
1330};
1331
1332// Specialization for lvalue reference types. See primary template
1333// for documentation.
1334template <typename T>
1335class ReferenceOrValueWrapper<T&> {
1336 public:
1337 // Workaround for debatable pass-by-reference lint warning (c-library-team
1338 // policy precludes NOLINT in this context)
1339 typedef T& reference;
1340 explicit ReferenceOrValueWrapper(reference ref)
1341 : value_ptr_(&ref) {}
1342 T& Unwrap() { return *value_ptr_; }
1343 const T& Peek() const { return *value_ptr_; }
1344
1345 private:
1346 T* value_ptr_;
1347};
1348
shiqiane35fdd92008-12-10 05:08:54 +00001349// MSVC warns about using 'this' in base member initializer list, so
1350// we need to temporarily disable the warning. We have to do it for
1351// the entire class to suppress the warning, even though it's about
1352// the constructor only.
mistergdf428ec2018-08-20 14:48:45 -04001353GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
shiqiane35fdd92008-12-10 05:08:54 +00001354
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001355// C++ treats the void type specially. For example, you cannot define
1356// a void-typed variable or pass a void value to a function.
1357// ActionResultHolder<T> holds a value of type T, where T must be a
1358// copyable type or void (T doesn't need to be default-constructable).
1359// It hides the syntactic difference between void and other types, and
1360// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001361// non-void-returning mock functions.
1362
1363// Untyped base class for ActionResultHolder<T>.
1364class UntypedActionResultHolderBase {
1365 public:
1366 virtual ~UntypedActionResultHolderBase() {}
1367
1368 // Prints the held value as an action's result to os.
1369 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1370};
1371
1372// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001373template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001374class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001375 public:
kosakb5c81092014-01-29 06:41:44 +00001376 // Returns the held value. Must not be called more than once.
1377 T Unwrap() {
1378 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001379 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001380
1381 // Prints the held value as an action's result to os.
Abseil Team26743362018-12-03 11:30:02 -05001382 void PrintAsActionResult(::std::ostream* os) const override {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001383 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001384 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001385 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001386 }
1387
1388 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001389 // result in a new-ed ActionResultHolder.
1390 template <typename F>
1391 static ActionResultHolder* PerformDefaultAction(
Abseil Teamde5be0e2018-11-08 11:14:50 -05001392 const FunctionMocker<F>* func_mocker,
Abseil Team29b47e42018-10-16 15:29:37 -04001393 typename Function<F>::ArgumentTuple&& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001394 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001395 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
Abseil Team29b47e42018-10-16 15:29:37 -04001396 std::move(args), call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001397 }
1398
zhanyong.waned6c9272011-02-23 19:39:27 +00001399 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001400 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001401 template <typename F>
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001402 static ActionResultHolder* PerformAction(
Abseil Team29b47e42018-10-16 15:29:37 -04001403 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001404 return new ActionResultHolder(
Abseil Team29b47e42018-10-16 15:29:37 -04001405 Wrapper(action.Perform(std::move(args))));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001406 }
1407
1408 private:
kosakb5c81092014-01-29 06:41:44 +00001409 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001410
kosakd370f852014-11-17 01:14:16 +00001411 explicit ActionResultHolder(Wrapper result)
Abseil Team29b47e42018-10-16 15:29:37 -04001412 : result_(std::move(result)) {
kosakd370f852014-11-17 01:14:16 +00001413 }
kosakb5c81092014-01-29 06:41:44 +00001414
1415 Wrapper result_;
1416
1417 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001418};
1419
1420// Specialization for T = void.
1421template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001422class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001423 public:
kosakb5c81092014-01-29 06:41:44 +00001424 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001425
Abseil Team26743362018-12-03 11:30:02 -05001426 void PrintAsActionResult(::std::ostream* /* os */) const override {}
zhanyong.waned6c9272011-02-23 19:39:27 +00001427
kosakb5c81092014-01-29 06:41:44 +00001428 // Performs the given mock function's default action and returns ownership
1429 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001430 template <typename F>
1431 static ActionResultHolder* PerformDefaultAction(
Abseil Teamde5be0e2018-11-08 11:14:50 -05001432 const FunctionMocker<F>* func_mocker,
Abseil Team29b47e42018-10-16 15:29:37 -04001433 typename Function<F>::ArgumentTuple&& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001434 const std::string& call_description) {
Abseil Team29b47e42018-10-16 15:29:37 -04001435 func_mocker->PerformDefaultAction(std::move(args), call_description);
kosakb5c81092014-01-29 06:41:44 +00001436 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001437 }
1438
kosakb5c81092014-01-29 06:41:44 +00001439 // Performs the given action and returns ownership of an empty
1440 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001441 template <typename F>
1442 static ActionResultHolder* PerformAction(
Abseil Team29b47e42018-10-16 15:29:37 -04001443 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
1444 action.Perform(std::move(args));
kosakb5c81092014-01-29 06:41:44 +00001445 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001446 }
kosakb5c81092014-01-29 06:41:44 +00001447
1448 private:
1449 ActionResultHolder() {}
1450 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001451};
1452
shiqiane35fdd92008-12-10 05:08:54 +00001453template <typename F>
Abseil Teamde5be0e2018-11-08 11:14:50 -05001454class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +00001455
Abseil Teamde5be0e2018-11-08 11:14:50 -05001456template <typename R, typename... Args>
Abseil Team569fba42019-01-22 09:58:06 -05001457class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
Abseil Teamde5be0e2018-11-08 11:14:50 -05001458 using F = R(Args...);
1459
1460 public:
1461 using Result = R;
1462 using ArgumentTuple = std::tuple<Args...>;
1463 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1464
1465 FunctionMocker() {}
1466
1467 // There is no generally useful and implementable semantics of
1468 // copying a mock object, so copying a mock is usually a user error.
1469 // Thus we disallow copying function mockers. If the user really
1470 // wants to copy a mock object, they should implement their own copy
1471 // operation, for example:
1472 //
1473 // class MockFoo : public Foo {
1474 // public:
1475 // // Defines a copy constructor explicitly.
1476 // MockFoo(const MockFoo& src) {}
1477 // ...
1478 // };
1479 FunctionMocker(const FunctionMocker&) = delete;
1480 FunctionMocker& operator=(const FunctionMocker&) = delete;
shiqiane35fdd92008-12-10 05:08:54 +00001481
1482 // The destructor verifies that all expectations on this mock
1483 // function have been satisfied. If not, it will report Google Test
1484 // non-fatal failures for the violations.
Abseil Team26743362018-12-03 11:30:02 -05001485 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001486 MutexLock l(&g_gmock_mutex);
1487 VerifyAndClearExpectationsLocked();
1488 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001489 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001490 }
1491
1492 // Returns the ON_CALL spec that matches this mock function with the
1493 // given arguments; returns NULL if no matching ON_CALL is found.
1494 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001495 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001496 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001497 for (UntypedOnCallSpecs::const_reverse_iterator it
1498 = untyped_on_call_specs_.rbegin();
1499 it != untyped_on_call_specs_.rend(); ++it) {
1500 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1501 if (spec->Matches(args))
1502 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001503 }
1504
Abseil Team4bb49ed2018-10-04 18:28:05 -04001505 return nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001506 }
1507
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001508 // Performs the default action of this mock function on the given
1509 // arguments and returns the result. Asserts (or throws if
1510 // exceptions are enabled) with a helpful call descrption if there
1511 // is no valid return value. This method doesn't depend on the
1512 // mutable state of this object, and thus can be called concurrently
1513 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001514 // L = *
Abseil Teamde5be0e2018-11-08 11:14:50 -05001515 Result PerformDefaultAction(ArgumentTuple&& args,
Abseil Team29b47e42018-10-16 15:29:37 -04001516 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001517 const OnCallSpec<F>* const spec =
1518 this->FindOnCallSpec(args);
Abseil Team4bb49ed2018-10-04 18:28:05 -04001519 if (spec != nullptr) {
Abseil Team29b47e42018-10-16 15:29:37 -04001520 return spec->GetAction().Perform(std::move(args));
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001521 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001522 const std::string message =
1523 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001524 "\n The mock function has no default action "
1525 "set, and its return type has no default value set.";
1526#if GTEST_HAS_EXCEPTIONS
1527 if (!DefaultValue<Result>::Exists()) {
1528 throw std::runtime_error(message);
1529 }
1530#else
1531 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1532#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001533 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001534 }
1535
zhanyong.waned6c9272011-02-23 19:39:27 +00001536 // Performs the default action with the given arguments and returns
1537 // the action's result. The call description string will be used in
1538 // the error message to describe the call in the case the default
1539 // action fails. The caller is responsible for deleting the result.
1540 // L = *
Abseil Team26743362018-12-03 11:30:02 -05001541 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001542 void* untyped_args, // must point to an ArgumentTuple
Abseil Team26743362018-12-03 11:30:02 -05001543 const std::string& call_description) const override {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001544 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team29b47e42018-10-16 15:29:37 -04001545 return ResultHolder::PerformDefaultAction(this, std::move(*args),
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001546 call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001547 }
1548
zhanyong.waned6c9272011-02-23 19:39:27 +00001549 // Performs the given action with the given arguments and returns
1550 // the action's result. The caller is responsible for deleting the
1551 // result.
1552 // L = *
Abseil Team26743362018-12-03 11:30:02 -05001553 UntypedActionResultHolderBase* UntypedPerformAction(
1554 const void* untyped_action, void* untyped_args) const override {
zhanyong.waned6c9272011-02-23 19:39:27 +00001555 // Make a copy of the action before performing it, in case the
1556 // action deletes the mock object (and thus deletes itself).
1557 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001558 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team29b47e42018-10-16 15:29:37 -04001559 return ResultHolder::PerformAction(action, std::move(*args));
zhanyong.waned6c9272011-02-23 19:39:27 +00001560 }
shiqiane35fdd92008-12-10 05:08:54 +00001561
zhanyong.waned6c9272011-02-23 19:39:27 +00001562 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1563 // clears the ON_CALL()s set on this mock function.
Abseil Team26743362018-12-03 11:30:02 -05001564 void ClearDefaultActionsLocked() override
vladlosev4d60a592011-10-24 21:16:22 +00001565 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001566 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001567
1568 // Deleting our default actions may trigger other mock objects to be
1569 // deleted, for example if an action contains a reference counted smart
1570 // pointer to that mock object, and that is the last reference. So if we
1571 // delete our actions within the context of the global mutex we may deadlock
1572 // when this method is called again. Instead, make a copy of the set of
1573 // actions to delete, clear our set within the mutex, and then delete the
1574 // actions outside of the mutex.
1575 UntypedOnCallSpecs specs_to_delete;
1576 untyped_on_call_specs_.swap(specs_to_delete);
1577
1578 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001579 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001580 specs_to_delete.begin();
1581 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001582 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001583 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001584
1585 // Lock the mutex again, since the caller expects it to be locked when we
1586 // return.
1587 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001588 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001589
Abseil Teamde5be0e2018-11-08 11:14:50 -05001590 // Returns the result of invoking this mock function with the given
1591 // arguments. This function can be safely called from multiple
1592 // threads concurrently.
1593 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1594 ArgumentTuple tuple(std::forward<Args>(args)...);
1595 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
1596 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
1597 return holder->Unwrap();
1598 }
1599
1600 MockSpec<F> With(Matcher<Args>... m) {
1601 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
1602 }
1603
shiqiane35fdd92008-12-10 05:08:54 +00001604 protected:
1605 template <typename Function>
1606 friend class MockSpec;
1607
zhanyong.waned6c9272011-02-23 19:39:27 +00001608 typedef ActionResultHolder<Result> ResultHolder;
1609
shiqiane35fdd92008-12-10 05:08:54 +00001610 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001611 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001612 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001613 const ArgumentMatcherTuple& m)
1614 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001615 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001616 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1617 untyped_on_call_specs_.push_back(on_call_spec);
1618 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001619 }
1620
1621 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001622 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1623 const std::string& source_text,
1624 const ArgumentMatcherTuple& m)
1625 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001626 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001627 TypedExpectation<F>* const expectation =
1628 new TypedExpectation<F>(this, file, line, source_text, m);
misterg80b43d92018-10-29 11:09:33 -04001629 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001630 // See the definition of untyped_expectations_ for why access to
1631 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001632 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001633
1634 // Adds this expectation into the implicit sequence if there is one.
1635 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
Abseil Team4bb49ed2018-10-04 18:28:05 -04001636 if (implicit_sequence != nullptr) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001637 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001638 }
1639
1640 return *expectation;
1641 }
1642
shiqiane35fdd92008-12-10 05:08:54 +00001643 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001644 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001645
zhanyong.waned6c9272011-02-23 19:39:27 +00001646 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001647
1648 // Describes what default action will be performed for the given
1649 // arguments.
1650 // L = *
1651 void DescribeDefaultActionTo(const ArgumentTuple& args,
1652 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001653 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001654
Abseil Team4bb49ed2018-10-04 18:28:05 -04001655 if (spec == nullptr) {
shiqiane35fdd92008-12-10 05:08:54 +00001656 *os << (internal::type_equals<Result, void>::value ?
1657 "returning directly.\n" :
1658 "returning default value.\n");
1659 } else {
1660 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001661 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001662 }
1663 }
1664
1665 // Writes a message that the call is uninteresting (i.e. neither
1666 // explicitly expected nor explicitly unexpected) to the given
1667 // ostream.
Abseil Team26743362018-12-03 11:30:02 -05001668 void UntypedDescribeUninterestingCall(const void* untyped_args,
1669 ::std::ostream* os) const override
1670 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001671 const ArgumentTuple& args =
1672 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001673 *os << "Uninteresting mock function call - ";
1674 DescribeDefaultActionTo(args, os);
1675 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001676 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001677 }
1678
zhanyong.waned6c9272011-02-23 19:39:27 +00001679 // Returns the expectation that matches the given function arguments
1680 // (or NULL is there's no match); when a match is found,
1681 // untyped_action is set to point to the action that should be
1682 // performed (or NULL if the action is "do default"), and
1683 // is_excessive is modified to indicate whether the call exceeds the
1684 // expected number.
1685 //
shiqiane35fdd92008-12-10 05:08:54 +00001686 // Critical section: We must find the matching expectation and the
1687 // corresponding action that needs to be taken in an ATOMIC
1688 // transaction. Otherwise another thread may call this mock
1689 // method in the middle and mess up the state.
1690 //
1691 // However, performing the action has to be left out of the critical
1692 // section. The reason is that we have no control on what the
1693 // action does (it can invoke an arbitrary user function or even a
1694 // mock function) and excessive locking could cause a dead lock.
Abseil Team26743362018-12-03 11:30:02 -05001695 const ExpectationBase* UntypedFindMatchingExpectation(
1696 const void* untyped_args, const void** untyped_action, bool* is_excessive,
1697 ::std::ostream* what, ::std::ostream* why) override
1698 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001699 const ArgumentTuple& args =
1700 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001701 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001702 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
Abseil Team4bb49ed2018-10-04 18:28:05 -04001703 if (exp == nullptr) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001704 this->FormatUnexpectedCallMessageLocked(args, what, why);
Abseil Team4bb49ed2018-10-04 18:28:05 -04001705 return nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001706 }
1707
1708 // This line must be done before calling GetActionForArguments(),
1709 // which will increment the call count for *exp and thus affect
1710 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001711 *is_excessive = exp->IsSaturated();
1712 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
Abseil Team4bb49ed2018-10-04 18:28:05 -04001713 if (action != nullptr && action->IsDoDefault())
1714 action = nullptr; // Normalize "do default" to NULL.
zhanyong.waned6c9272011-02-23 19:39:27 +00001715 *untyped_action = action;
1716 return exp;
1717 }
1718
1719 // Prints the given function arguments to the ostream.
Abseil Team26743362018-12-03 11:30:02 -05001720 void UntypedPrintArgs(const void* untyped_args,
1721 ::std::ostream* os) const override {
zhanyong.waned6c9272011-02-23 19:39:27 +00001722 const ArgumentTuple& args =
1723 *static_cast<const ArgumentTuple*>(untyped_args);
1724 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001725 }
1726
1727 // Returns the expectation that matches the arguments, or NULL if no
1728 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001729 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001730 const ArgumentTuple& args) const
1731 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001732 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001733 // See the definition of untyped_expectations_ for why access to
1734 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001735 for (typename UntypedExpectations::const_reverse_iterator it =
1736 untyped_expectations_.rbegin();
1737 it != untyped_expectations_.rend(); ++it) {
1738 TypedExpectation<F>* const exp =
1739 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001740 if (exp->ShouldHandleArguments(args)) {
1741 return exp;
1742 }
1743 }
Abseil Team4bb49ed2018-10-04 18:28:05 -04001744 return nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001745 }
1746
1747 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001748 void FormatUnexpectedCallMessageLocked(
1749 const ArgumentTuple& args,
1750 ::std::ostream* os,
1751 ::std::ostream* why) const
1752 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001753 g_gmock_mutex.AssertHeld();
1754 *os << "\nUnexpected mock function call - ";
1755 DescribeDefaultActionTo(args, os);
1756 PrintTriedExpectationsLocked(args, why);
1757 }
1758
1759 // Prints a list of expectations that have been tried against the
1760 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001761 void PrintTriedExpectationsLocked(
1762 const ArgumentTuple& args,
1763 ::std::ostream* why) const
1764 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001765 g_gmock_mutex.AssertHeld();
Robert Woldbergdec3b812018-10-12 11:12:55 -06001766 const size_t count = untyped_expectations_.size();
shiqiane35fdd92008-12-10 05:08:54 +00001767 *why << "Google Mock tried the following " << count << " "
1768 << (count == 1 ? "expectation, but it didn't match" :
1769 "expectations, but none matched")
1770 << ":\n";
Robert Woldbergdec3b812018-10-12 11:12:55 -06001771 for (size_t i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001772 TypedExpectation<F>* const expectation =
1773 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001774 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001775 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001776 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001777 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001778 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001779 *why << expectation->source_text() << "...\n";
1780 expectation->ExplainMatchResultTo(args, why);
1781 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001782 }
1783 }
Abseil Teamde5be0e2018-11-08 11:14:50 -05001784}; // class FunctionMocker
shiqiane35fdd92008-12-10 05:08:54 +00001785
mistergdf428ec2018-08-20 14:48:45 -04001786GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
shiqiane35fdd92008-12-10 05:08:54 +00001787
shiqiane35fdd92008-12-10 05:08:54 +00001788// Reports an uninteresting call (whose description is in msg) in the
1789// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -04001790void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
shiqiane35fdd92008-12-10 05:08:54 +00001791
shiqiane35fdd92008-12-10 05:08:54 +00001792} // namespace internal
1793
Abseil Teamde5be0e2018-11-08 11:14:50 -05001794// A MockFunction<F> class has one mock method whose type is F. It is
1795// useful when you just want your test code to emit some messages and
1796// have Google Mock verify the right messages are sent (and perhaps at
1797// the right times). For example, if you are exercising code:
1798//
1799// Foo(1);
1800// Foo(2);
1801// Foo(3);
1802//
1803// and want to verify that Foo(1) and Foo(3) both invoke
1804// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1805//
1806// TEST(FooTest, InvokesBarCorrectly) {
1807// MyMock mock;
1808// MockFunction<void(string check_point_name)> check;
1809// {
1810// InSequence s;
1811//
1812// EXPECT_CALL(mock, Bar("a"));
1813// EXPECT_CALL(check, Call("1"));
1814// EXPECT_CALL(check, Call("2"));
1815// EXPECT_CALL(mock, Bar("a"));
1816// }
1817// Foo(1);
1818// check.Call("1");
1819// Foo(2);
1820// check.Call("2");
1821// Foo(3);
1822// }
1823//
1824// The expectation spec says that the first Bar("a") must happen
1825// before check point "1", the second Bar("a") must happen after check
1826// point "2", and nothing should happen between the two check
1827// points. The explicit check points make it easy to tell which
1828// Bar("a") is called by which call to Foo().
1829//
1830// MockFunction<F> can also be used to exercise code that accepts
1831// std::function<F> callbacks. To do so, use AsStdFunction() method
1832// to create std::function proxy forwarding to original object's Call.
1833// Example:
1834//
1835// TEST(FooTest, RunsCallbackWithBarArgument) {
1836// MockFunction<int(string)> callback;
1837// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1838// Foo(callback.AsStdFunction());
1839// }
1840template <typename F>
1841class MockFunction;
1842
1843template <typename R, typename... Args>
1844class MockFunction<R(Args...)> {
1845 public:
1846 MockFunction() {}
1847 MockFunction(const MockFunction&) = delete;
1848 MockFunction& operator=(const MockFunction&) = delete;
1849
1850 std::function<R(Args...)> AsStdFunction() {
1851 return [this](Args... args) -> R {
1852 return this->Call(std::forward<Args>(args)...);
1853 };
1854 }
1855
1856 // Implementation detail: the expansion of the MOCK_METHOD macro.
1857 R Call(Args... args) {
1858 mock_.SetOwnerAndName(this, "Call");
1859 return mock_.Invoke(std::forward<Args>(args)...);
1860 }
1861
1862 internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1863 mock_.RegisterOwner(this);
1864 return mock_.With(std::move(m)...);
1865 }
1866
1867 internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
1868 R (*)(Args...)) {
1869 return this->gmock_Call(::testing::A<Args>()...);
1870 }
1871
1872 private:
Krystian Kuzniarek637b0412019-08-01 11:33:36 +02001873 internal::FunctionMocker<R(Args...)> mock_;
Abseil Teamde5be0e2018-11-08 11:14:50 -05001874};
1875
shiqiane35fdd92008-12-10 05:08:54 +00001876// The style guide prohibits "using" statements in a namespace scope
1877// inside a header file. However, the MockSpec class template is
1878// meant to be defined in the ::testing namespace. The following line
1879// is just a trick for working around a bug in MSVC 8.0, which cannot
1880// handle it if we define MockSpec in ::testing.
1881using internal::MockSpec;
1882
1883// Const(x) is a convenient function for obtaining a const reference
1884// to x. This is useful for setting expectations on an overloaded
1885// const mock method, e.g.
1886//
1887// class MockFoo : public FooInterface {
1888// public:
1889// MOCK_METHOD0(Bar, int());
1890// MOCK_CONST_METHOD0(Bar, int&());
1891// };
1892//
1893// MockFoo foo;
1894// // Expects a call to non-const MockFoo::Bar().
1895// EXPECT_CALL(foo, Bar());
1896// // Expects a call to const MockFoo::Bar().
1897// EXPECT_CALL(Const(foo), Bar());
1898template <typename T>
1899inline const T& Const(const T& x) { return x; }
1900
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001901// Constructs an Expectation object that references and co-owns exp.
1902inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1903 : expectation_base_(exp.GetHandle().expectation_base()) {}
1904
shiqiane35fdd92008-12-10 05:08:54 +00001905} // namespace testing
1906
mistergdf428ec2018-08-20 14:48:45 -04001907GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1908
David Sunderlandf437f8c2018-04-18 19:28:56 -04001909// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1910// required to avoid compile errors when the name of the method used in call is
1911// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1912// tests in internal/gmock-spec-builders_test.cc for more details.
1913//
1914// This macro supports statements both with and without parameter matchers. If
1915// the parameter list is omitted, gMock will accept any parameters, which allows
1916// tests to be written that don't need to encode the number of method
1917// parameter. This technique may only be used for non-overloaded methods.
1918//
1919// // These are the same:
duxiuxing65a49a72018-07-17 15:46:47 +08001920// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1921// ON_CALL(mock, NoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001922//
1923// // As are these:
duxiuxing65a49a72018-07-17 15:46:47 +08001924// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1925// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001926//
1927// // Can also specify args if you want, of course:
duxiuxing65a49a72018-07-17 15:46:47 +08001928// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001929//
1930// // Overloads work as long as you specify parameters:
duxiuxing65a49a72018-07-17 15:46:47 +08001931// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1932// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001933//
1934// // Oops! Which overload did you want?
duxiuxing65a49a72018-07-17 15:46:47 +08001935// ON_CALL(mock, OverloadedMethod).WillByDefault(...);
David Sunderlandf437f8c2018-04-18 19:28:56 -04001936// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1937//
1938// How this works: The mock class uses two overloads of the gmock_Method
1939// expectation setter method plus an operator() overload on the MockSpec object.
1940// In the matcher list form, the macro expands to:
1941//
1942// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001943// ON_CALL(mock, TwoArgsMethod(_, 45))...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001944//
duxiuxing65a49a72018-07-17 15:46:47 +08001945// // ...expands to:
1946// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001947// |-------------v---------------||------------v-------------|
1948// invokes first overload swallowed by operator()
1949//
duxiuxing65a49a72018-07-17 15:46:47 +08001950// // ...which is essentially:
1951// mock.gmock_TwoArgsMethod(_, 45)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001952//
1953// Whereas the form without a matcher list:
1954//
1955// // This statement:
duxiuxing65a49a72018-07-17 15:46:47 +08001956// ON_CALL(mock, TwoArgsMethod)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001957//
duxiuxing65a49a72018-07-17 15:46:47 +08001958// // ...expands to:
1959// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001960// |-----------------------v--------------------------|
1961// invokes second overload
1962//
duxiuxing65a49a72018-07-17 15:46:47 +08001963// // ...which is essentially:
1964// mock.gmock_TwoArgsMethod(_, _)...
David Sunderlandf437f8c2018-04-18 19:28:56 -04001965//
1966// The WithoutMatchers() argument is used to disambiguate overloads and to
1967// block the caller from accidentally invoking the second overload directly. The
1968// second argument is an internal type derived from the method signature. The
1969// failure to disambiguate two overloads of this method in the ON_CALL statement
1970// is how we block callers from setting expectations on overloaded methods.
Gennadiy Civile9085762018-10-29 13:46:24 -04001971#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1972 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
1973 nullptr) \
David Sunderlandf437f8c2018-04-18 19:28:56 -04001974 .Setter(__FILE__, __LINE__, #mock_expr, #call)
shiqiane35fdd92008-12-10 05:08:54 +00001975
David Sunderlandf437f8c2018-04-18 19:28:56 -04001976#define ON_CALL(obj, call) \
1977 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1978
1979#define EXPECT_CALL(obj, call) \
1980 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
shiqiane35fdd92008-12-10 05:08:54 +00001981
1982#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_