blob: 0d1adda5c68bbb05b6aa06559c3049c028585f6e [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>
Krystian Kuzniarekec49fbc2019-08-13 22:30:12 +020070#include <type_traits>
Abseil Team29b47e42018-10-16 15:29:37 -040071#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000072#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000073#include "gmock/gmock-actions.h"
74#include "gmock/gmock-cardinalities.h"
75#include "gmock/gmock-matchers.h"
76#include "gmock/internal/gmock-internal-utils.h"
77#include "gmock/internal/gmock-port.h"
78#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000079
Gennadiy Civilfbb48a72018-01-26 11:57:58 -050080#if GTEST_HAS_EXCEPTIONS
81# include <stdexcept> // NOLINT
82#endif
83
mistergdf428ec2018-08-20 14:48:45 -040084GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
85/* class A needs to have dll-interface to be used by clients of class B */)
86
shiqiane35fdd92008-12-10 05:08:54 +000087namespace testing {
88
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000089// An abstract handle of an expectation.
90class Expectation;
91
92// A set of expectation handles.
93class ExpectationSet;
94
shiqiane35fdd92008-12-10 05:08:54 +000095// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
96// and MUST NOT BE USED IN USER CODE!!!
97namespace internal {
98
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000099// Implements a mock function.
100template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +0000101
102// Base class for expectations.
103class ExpectationBase;
104
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000105// Implements an expectation.
106template <typename F> class TypedExpectation;
107
shiqiane35fdd92008-12-10 05:08:54 +0000108// Helper class for testing the Expectation class template.
109class ExpectationTester;
110
shiqiane35fdd92008-12-10 05:08:54 +0000111// Protects the mock object registry (in class Mock), all function
112// mockers, and all expectations.
113//
114// The reason we don't use more fine-grained protection is: when a
115// mock function Foo() is called, it needs to consult its expectations
116// to see which one should be picked. If another thread is allowed to
117// call a mock function (either Foo() or a different one) at the same
118// time, it could affect the "retired" attributes of Foo()'s
119// expectations when InSequence() is used, and thus affect which
120// expectation gets picked. Therefore, we sequence all mock function
121// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000122GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000123
zhanyong.waned6c9272011-02-23 19:39:27 +0000124// Untyped base class for ActionResultHolder<R>.
125class UntypedActionResultHolderBase;
126
Abseil Teamde5be0e2018-11-08 11:14:50 -0500127// Abstract base class of FunctionMocker. This is the
shiqiane35fdd92008-12-10 05:08:54 +0000128// type-agnostic part of the function mocker interface. Its pure
Abseil Teamde5be0e2018-11-08 11:14:50 -0500129// virtual methods are implemented by FunctionMocker.
vladlosev587c1b32011-05-20 00:42:22 +0000130class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000131 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000132 UntypedFunctionMockerBase();
133 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000134
135 // Verifies that all expectations on this mock function have been
136 // satisfied. Reports one or more Google Test non-fatal failures
137 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000138 bool VerifyAndClearExpectationsLocked()
139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000140
141 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000142 virtual void ClearDefaultActionsLocked()
143 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000144
145 // In all of the following Untyped* functions, it's the caller's
146 // responsibility to guarantee the correctness of the arguments'
147 // types.
148
149 // Performs the default action with the given arguments and returns
150 // the action's result. The call description string will be used in
151 // the error message to describe the call in the case the default
152 // action fails.
153 // L = *
154 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400155 void* untyped_args, const std::string& call_description) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000156
157 // Performs the given action with the given arguments and returns
158 // the action's result.
159 // L = *
160 virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400161 const void* untyped_action, void* untyped_args) const = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000162
163 // Writes a message that the call is uninteresting (i.e. neither
164 // explicitly expected nor explicitly unexpected) to the given
165 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +0000166 virtual void UntypedDescribeUninterestingCall(
167 const void* untyped_args,
168 ::std::ostream* os) const
169 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000170
171 // Returns the expectation that matches the given function arguments
172 // (or NULL is there's no match); when a match is found,
173 // untyped_action is set to point to the action that should be
174 // performed (or NULL if the action is "do default"), and
175 // is_excessive is modified to indicate whether the call exceeds the
176 // expected number.
zhanyong.waned6c9272011-02-23 19:39:27 +0000177 virtual const ExpectationBase* UntypedFindMatchingExpectation(
178 const void* untyped_args,
179 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000180 ::std::ostream* what, ::std::ostream* why)
181 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000182
183 // Prints the given function arguments to the ostream.
184 virtual void UntypedPrintArgs(const void* untyped_args,
185 ::std::ostream* os) const = 0;
186
187 // Sets the mock object this mock method belongs to, and registers
188 // this information in the global mock registry. Will be called
189 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
190 // method.
vladlosev4d60a592011-10-24 21:16:22 +0000191 void RegisterOwner(const void* mock_obj)
192 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000193
194 // Sets the mock object this mock method belongs to, and sets the
195 // name of the mock function. Will be called upon each invocation
196 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000197 void SetOwnerAndName(const void* mock_obj, const char* name)
198 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000199
200 // Returns the mock object this mock method belongs to. Must be
201 // called after RegisterOwner() or SetOwnerAndName() has been
202 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000203 const void* MockObject() const
204 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000205
206 // Returns the name of this mock method. Must be called after
207 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000208 const char* Name() const
209 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000210
211 // Returns the result of invoking this mock function with the given
212 // arguments. This function can be safely called from multiple
213 // threads concurrently. The caller is responsible for deleting the
214 // result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400215 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
216 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000217
218 protected:
219 typedef std::vector<const void*> UntypedOnCallSpecs;
220
misterg80b43d92018-10-29 11:09:33 -0400221 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
zhanyong.waned6c9272011-02-23 19:39:27 +0000222
223 // Returns an Expectation object that references and co-owns exp,
224 // which must be an expectation on this mock function.
225 Expectation GetHandleOf(ExpectationBase* exp);
226
227 // Address of the mock object this mock method belongs to. Only
228 // valid after this mock method has been called or
229 // ON_CALL/EXPECT_CALL has been invoked on it.
230 const void* mock_obj_; // Protected by g_gmock_mutex.
231
232 // Name of the function being mocked. Only valid after this mock
233 // method has been called.
234 const char* name_; // Protected by g_gmock_mutex.
235
236 // All default action specs for this function mocker.
237 UntypedOnCallSpecs untyped_on_call_specs_;
238
239 // All expectations for this function mocker.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400240 //
241 // It's undefined behavior to interleave expectations (EXPECT_CALLs
242 // or ON_CALLs) and mock function calls. Also, the order of
243 // expectations is important. Therefore it's a logic race condition
244 // to read/write untyped_expectations_ concurrently. In order for
245 // tools like tsan to catch concurrent read/write accesses to
246 // untyped_expectations, we deliberately leave accesses to it
247 // unprotected.
zhanyong.waned6c9272011-02-23 19:39:27 +0000248 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000249}; // class UntypedFunctionMockerBase
250
zhanyong.waned6c9272011-02-23 19:39:27 +0000251// Untyped base class for OnCallSpec<F>.
252class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000253 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000254 // The arguments are the location of the ON_CALL() statement.
255 UntypedOnCallSpecBase(const char* a_file, int a_line)
256 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000257
258 // Where in the source file was the default action spec defined?
259 const char* file() const { return file_; }
260 int line() const { return line_; }
261
zhanyong.waned6c9272011-02-23 19:39:27 +0000262 protected:
263 // Gives each clause in the ON_CALL() statement a name.
264 enum Clause {
265 // Do not change the order of the enum members! The run-time
266 // syntax checking relies on it.
267 kNone,
268 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000269 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000270 };
271
272 // Asserts that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400273 void AssertSpecProperty(bool property,
274 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000275 Assert(property, file_, line_, failure_message);
276 }
277
278 // Expects that the ON_CALL() statement has a certain property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400279 void ExpectSpecProperty(bool property,
280 const std::string& failure_message) const {
zhanyong.waned6c9272011-02-23 19:39:27 +0000281 Expect(property, file_, line_, failure_message);
282 }
283
284 const char* file_;
285 int line_;
286
287 // The last clause in the ON_CALL() statement as seen so far.
288 // Initially kNone and changes as the statement is parsed.
289 Clause last_clause_;
290}; // class UntypedOnCallSpecBase
291
292// This template class implements an ON_CALL spec.
293template <typename F>
294class OnCallSpec : public UntypedOnCallSpecBase {
295 public:
296 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
297 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
298
299 // Constructs an OnCallSpec object from the information inside
300 // the parenthesis of an ON_CALL() statement.
301 OnCallSpec(const char* a_file, int a_line,
302 const ArgumentMatcherTuple& matchers)
303 : UntypedOnCallSpecBase(a_file, a_line),
304 matchers_(matchers),
Abseil Team9518a572019-01-17 15:56:41 -0500305 // By default, extra_matcher_ should match anything. However,
306 // we cannot initialize it with _ as that causes ambiguity between
307 // Matcher's copy and move constructor for some argument types.
308 extra_matcher_(A<const ArgumentTuple&>()) {}
zhanyong.waned6c9272011-02-23 19:39:27 +0000309
zhanyong.wanbf550852009-06-09 06:09:53 +0000310 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000311 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000312 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000313 ExpectSpecProperty(last_clause_ < kWith,
314 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000315 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000316 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000317
318 extra_matcher_ = m;
319 return *this;
320 }
321
322 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000323 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000324 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000325 ".WillByDefault() must appear "
326 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000327 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000328
329 ExpectSpecProperty(!action.IsDoDefault(),
330 "DoDefault() cannot be used in ON_CALL().");
331 action_ = action;
332 return *this;
333 }
334
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200335 // Returns true if the given arguments match the matchers.
shiqiane35fdd92008-12-10 05:08:54 +0000336 bool Matches(const ArgumentTuple& args) const {
337 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
338 }
339
340 // Returns the action specified by the user.
341 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000342 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000343 ".WillByDefault() must appear exactly "
344 "once in an ON_CALL().");
345 return action_;
346 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000347
shiqiane35fdd92008-12-10 05:08:54 +0000348 private:
shiqiane35fdd92008-12-10 05:08:54 +0000349 // The information in statement
350 //
351 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000352 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000353 // .WillByDefault(action);
354 //
355 // is recorded in the data members like this:
356 //
357 // source file that contains the statement => file_
358 // line number of the statement => line_
359 // matchers => matchers_
360 // multi-argument-matcher => extra_matcher_
361 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000362 ArgumentMatcherTuple matchers_;
363 Matcher<const ArgumentTuple&> extra_matcher_;
364 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000365}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000366
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000367// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000368enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000369 kAllow,
370 kWarn,
zhanyong.wanc8965042013-03-01 07:10:07 +0000371 kFail,
shiqiane35fdd92008-12-10 05:08:54 +0000372};
373
374} // namespace internal
375
376// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000377class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000378 public:
379 // The following public methods can be called concurrently.
380
zhanyong.wandf35a762009-04-22 22:25:31 +0000381 // Tells Google Mock to ignore mock_obj when checking for leaked
382 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000383 static void AllowLeak(const void* mock_obj)
384 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000385
shiqiane35fdd92008-12-10 05:08:54 +0000386 // Verifies and clears all expectations on the given mock object.
387 // If the expectations aren't satisfied, generates one or more
388 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000389 static bool VerifyAndClearExpectations(void* mock_obj)
390 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000391
392 // Verifies all expectations on the given mock object and clears its
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200393 // default actions and expectations. Returns true if the
shiqiane35fdd92008-12-10 05:08:54 +0000394 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000395 static bool VerifyAndClear(void* mock_obj)
396 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000397
Gennadiy Civil20eaf6e2018-10-23 15:13:41 -0400398 // Returns whether the mock was created as a naggy mock (default)
Jonathan Wendeborn67a240a2018-10-16 08:07:15 +0200399 static bool IsNaggy(void* mock_obj)
400 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
Gennadiy Civil20eaf6e2018-10-23 15:13:41 -0400401 // Returns whether the mock was created as a nice mock
Jonathan Wendeborn67a240a2018-10-16 08:07:15 +0200402 static bool IsNice(void* mock_obj)
403 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
Gennadiy Civil20eaf6e2018-10-23 15:13:41 -0400404 // Returns whether the mock was created as a strict mock
Jonathan Wendeborn67a240a2018-10-16 08:07:15 +0200405 static bool IsStrict(void* mock_obj)
406 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
407
shiqiane35fdd92008-12-10 05:08:54 +0000408 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000409 friend class internal::UntypedFunctionMockerBase;
410
shiqiane35fdd92008-12-10 05:08:54 +0000411 // Needed for a function mocker to register itself (so that we know
412 // how to clear a mock object).
413 template <typename F>
Abseil Teamde5be0e2018-11-08 11:14:50 -0500414 friend class internal::FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +0000415
shiqiane35fdd92008-12-10 05:08:54 +0000416 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700417 friend class NiceMock;
shiqiane35fdd92008-12-10 05:08:54 +0000418
419 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700420 friend class NaggyMock;
zhanyong.wan844fa942013-03-01 01:54:22 +0000421
422 template <typename M>
Victor Costan1324e2d2018-04-09 21:57:54 -0700423 friend class StrictMock;
shiqiane35fdd92008-12-10 05:08:54 +0000424
425 // Tells Google Mock to allow uninteresting calls on the given mock
426 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000427 static void AllowUninterestingCalls(const void* mock_obj)
428 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000429
430 // Tells Google Mock to warn the user about uninteresting calls on
431 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000432 static void WarnUninterestingCalls(const void* mock_obj)
433 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000434
435 // Tells Google Mock to fail uninteresting calls on the given mock
436 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000437 static void FailUninterestingCalls(const void* mock_obj)
438 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000439
440 // Tells Google Mock the given mock object is being destroyed and
441 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000442 static void UnregisterCallReaction(const void* mock_obj)
443 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000444
445 // Returns the reaction Google Mock will have on uninteresting calls
446 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000447 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000448 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000449 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000450
451 // Verifies that all expectations on the given mock object have been
452 // satisfied. Reports one or more Google Test non-fatal failures
453 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000454 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
455 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000456
457 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000458 static void ClearDefaultActionsLocked(void* mock_obj)
459 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000460
461 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000462 static void Register(
463 const void* mock_obj,
464 internal::UntypedFunctionMockerBase* mocker)
465 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000466
zhanyong.wandf35a762009-04-22 22:25:31 +0000467 // Tells Google Mock where in the source code mock_obj is used in an
468 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
469 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000470 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000471 const void* mock_obj, const char* file, int line)
472 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000473
shiqiane35fdd92008-12-10 05:08:54 +0000474 // Unregisters a mock method; removes the owning mock object from
475 // the registry when the last mock method associated with it has
476 // been unregistered. This is called only in the destructor of
Abseil Teamde5be0e2018-11-08 11:14:50 -0500477 // FunctionMocker.
vladlosev4d60a592011-10-24 21:16:22 +0000478 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
479 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000480}; // class Mock
481
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000482// An abstract handle of an expectation. Useful in the .After()
483// clause of EXPECT_CALL() for setting the (partial) order of
484// expectations. The syntax:
485//
486// Expectation e1 = EXPECT_CALL(...)...;
487// EXPECT_CALL(...).After(e1)...;
488//
489// sets two expectations where the latter can only be matched after
490// the former has been satisfied.
491//
492// Notes:
493// - This class is copyable and has value semantics.
494// - Constness is shallow: a const Expectation object itself cannot
495// be modified, but the mutable methods of the ExpectationBase
496// object it references can be called via expectation_base().
misterg80b43d92018-10-29 11:09:33 -0400497
vladlosev587c1b32011-05-20 00:42:22 +0000498class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000499 public:
500 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000501 Expectation();
502
503 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000504
505 // This single-argument ctor must not be explicit, in order to support the
506 // Expectation e = EXPECT_CALL(...);
507 // syntax.
508 //
509 // A TypedExpectation object stores its pre-requisites as
510 // Expectation objects, and needs to call the non-const Retire()
511 // method on the ExpectationBase objects they reference. Therefore
512 // Expectation must receive a *non-const* reference to the
513 // ExpectationBase object.
514 Expectation(internal::ExpectationBase& exp); // NOLINT
515
516 // The compiler-generated copy ctor and operator= work exactly as
517 // intended, so we don't need to define our own.
518
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200519 // Returns true if rhs references the same expectation as this object does.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000520 bool operator==(const Expectation& rhs) const {
521 return expectation_base_ == rhs.expectation_base_;
522 }
523
524 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
525
526 private:
527 friend class ExpectationSet;
528 friend class Sequence;
529 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000530 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000531
532 template <typename F>
Abseil Teamde5be0e2018-11-08 11:14:50 -0500533 friend class ::testing::internal::FunctionMocker;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000534
535 template <typename F>
536 friend class ::testing::internal::TypedExpectation;
537
538 // This comparator is needed for putting Expectation objects into a set.
539 class Less {
540 public:
541 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
542 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
543 }
544 };
545
546 typedef ::std::set<Expectation, Less> Set;
547
548 Expectation(
misterg80b43d92018-10-29 11:09:33 -0400549 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000550
551 // Returns the expectation this object references.
misterg80b43d92018-10-29 11:09:33 -0400552 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000553 return expectation_base_;
554 }
555
misterg80b43d92018-10-29 11:09:33 -0400556 // A shared_ptr that co-owns the expectation this handle references.
557 std::shared_ptr<internal::ExpectationBase> expectation_base_;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000558};
559
560// A set of expectation handles. Useful in the .After() clause of
561// EXPECT_CALL() for setting the (partial) order of expectations. The
562// syntax:
563//
564// ExpectationSet es;
565// es += EXPECT_CALL(...)...;
566// es += EXPECT_CALL(...)...;
567// EXPECT_CALL(...).After(es)...;
568//
569// sets three expectations where the last one can only be matched
570// after the first two have both been satisfied.
571//
572// This class is copyable and has value semantics.
573class ExpectationSet {
574 public:
575 // A bidirectional iterator that can read a const element in the set.
576 typedef Expectation::Set::const_iterator const_iterator;
577
578 // An object stored in the set. This is an alias of Expectation.
579 typedef Expectation::Set::value_type value_type;
580
581 // Constructs an empty set.
582 ExpectationSet() {}
583
584 // This single-argument ctor must not be explicit, in order to support the
585 // ExpectationSet es = EXPECT_CALL(...);
586 // syntax.
587 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
588 *this += Expectation(exp);
589 }
590
591 // This single-argument ctor implements implicit conversion from
592 // Expectation and thus must not be explicit. This allows either an
593 // Expectation or an ExpectationSet to be used in .After().
594 ExpectationSet(const Expectation& e) { // NOLINT
595 *this += e;
596 }
597
598 // The compiler-generator ctor and operator= works exactly as
599 // intended, so we don't need to define our own.
600
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200601 // Returns true if rhs contains the same set of Expectation objects
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000602 // as this does.
603 bool operator==(const ExpectationSet& rhs) const {
604 return expectations_ == rhs.expectations_;
605 }
606
607 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
608
609 // Implements the syntax
610 // expectation_set += EXPECT_CALL(...);
611 ExpectationSet& operator+=(const Expectation& e) {
612 expectations_.insert(e);
613 return *this;
614 }
615
616 int size() const { return static_cast<int>(expectations_.size()); }
617
618 const_iterator begin() const { return expectations_.begin(); }
619 const_iterator end() const { return expectations_.end(); }
620
621 private:
622 Expectation::Set expectations_;
623};
624
625
shiqiane35fdd92008-12-10 05:08:54 +0000626// Sequence objects are used by a user to specify the relative order
627// in which the expectations should match. They are copyable (we rely
628// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000629class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000630 public:
631 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000632 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000633
634 // Adds an expectation to this sequence. The caller must ensure
635 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000636 void AddExpectation(const Expectation& expectation) const;
637
shiqiane35fdd92008-12-10 05:08:54 +0000638 private:
misterg80b43d92018-10-29 11:09:33 -0400639 // The last expectation in this sequence.
640 std::shared_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000641}; // class Sequence
642
643// An object of this type causes all EXPECT_CALL() statements
644// encountered in its scope to be put in an anonymous sequence. The
645// work is done in the constructor and destructor. You should only
646// create an InSequence object on the stack.
647//
648// The sole purpose for this class is to support easy definition of
649// sequential expectations, e.g.
650//
651// {
652// InSequence dummy; // The name of the object doesn't matter.
653//
654// // The following expectations must match in the order they appear.
655// EXPECT_CALL(a, Bar())...;
656// EXPECT_CALL(a, Baz())...;
657// ...
658// EXPECT_CALL(b, Xyz())...;
659// }
660//
661// You can create InSequence objects in multiple threads, as long as
662// they are used to affect different mock objects. The idea is that
663// each thread can create and set up its own mocks as if it's the only
664// thread. However, for clarity of your tests we recommend you to set
665// up mocks in the main thread unless you have a good reason not to do
666// so.
vladlosev587c1b32011-05-20 00:42:22 +0000667class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000668 public:
669 InSequence();
670 ~InSequence();
671 private:
672 bool sequence_created_;
673
674 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000675} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000676
677namespace internal {
678
679// Points to the implicit sequence introduced by a living InSequence
680// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000681GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000682
683// Base class for implementing expectations.
684//
685// There are two reasons for having a type-agnostic base class for
686// Expectation:
687//
688// 1. We need to store collections of expectations of different
689// types (e.g. all pre-requisites of a particular expectation, all
690// expectations in a sequence). Therefore these expectation objects
691// must share a common base class.
692//
693// 2. We can avoid binary code bloat by moving methods not depending
694// on the template argument of Expectation to the base class.
695//
696// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000697class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000698 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000699 // source_text is the EXPECT_CALL(...) source that created this Expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400700 ExpectationBase(const char* file, int line, const std::string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000701
702 virtual ~ExpectationBase();
703
704 // Where in the source file was the expectation spec defined?
705 const char* file() const { return file_; }
706 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000707 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000708 // Returns the cardinality specified in the expectation spec.
709 const Cardinality& cardinality() const { return cardinality_; }
710
711 // Describes the source file location of this expectation.
712 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000713 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000714 }
715
716 // Describes how many times a function call matching this
717 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000718 void DescribeCallCountTo(::std::ostream* os) const
719 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000720
721 // If this mock method has an extra matcher (i.e. .With(matcher)),
722 // describes it to the ostream.
723 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000724
shiqiane35fdd92008-12-10 05:08:54 +0000725 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000726 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000727 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000728
729 enum Clause {
730 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000731 kNone,
732 kWith,
733 kTimes,
734 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000735 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000736 kWillOnce,
737 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000738 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000739 };
740
zhanyong.waned6c9272011-02-23 19:39:27 +0000741 typedef std::vector<const void*> UntypedActions;
742
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000743 // Returns an Expectation object that references and co-owns this
744 // expectation.
745 virtual Expectation GetHandle() = 0;
746
shiqiane35fdd92008-12-10 05:08:54 +0000747 // Asserts that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400748 void AssertSpecProperty(bool property,
749 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000750 Assert(property, file_, line_, failure_message);
751 }
752
753 // Expects that the EXPECT_CALL() statement has the given property.
Nico Weber09fd5b32017-05-15 17:07:03 -0400754 void ExpectSpecProperty(bool property,
755 const std::string& failure_message) const {
shiqiane35fdd92008-12-10 05:08:54 +0000756 Expect(property, file_, line_, failure_message);
757 }
758
759 // Explicitly specifies the cardinality of this expectation. Used
760 // by the subclasses to implement the .Times() clause.
761 void SpecifyCardinality(const Cardinality& cardinality);
762
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200763 // Returns true if the user specified the cardinality explicitly
shiqiane35fdd92008-12-10 05:08:54 +0000764 // using a .Times().
765 bool cardinality_specified() const { return cardinality_specified_; }
766
767 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000768 void set_cardinality(const Cardinality& a_cardinality) {
769 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000770 }
771
772 // The following group of methods should only be called after the
773 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
774 // the current thread.
775
776 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000777 void RetireAllPreRequisites()
778 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000779
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200780 // Returns true if this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000781 bool is_retired() const
782 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000783 g_gmock_mutex.AssertHeld();
784 return retired_;
785 }
786
787 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000788 void Retire()
789 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000790 g_gmock_mutex.AssertHeld();
791 retired_ = true;
792 }
793
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200794 // Returns true if this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000795 bool IsSatisfied() const
796 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000797 g_gmock_mutex.AssertHeld();
798 return cardinality().IsSatisfiedByCallCount(call_count_);
799 }
800
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200801 // Returns true if this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000802 bool IsSaturated() const
803 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000804 g_gmock_mutex.AssertHeld();
805 return cardinality().IsSaturatedByCallCount(call_count_);
806 }
807
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200808 // Returns true if this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000809 bool IsOverSaturated() const
810 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000811 g_gmock_mutex.AssertHeld();
812 return cardinality().IsOverSaturatedByCallCount(call_count_);
813 }
814
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200815 // Returns true if all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000816 bool AllPrerequisitesAreSatisfied() const
817 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000818
819 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000820 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
821 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000822
823 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000824 int call_count() const
825 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000826 g_gmock_mutex.AssertHeld();
827 return call_count_;
828 }
829
830 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000831 void IncrementCallCount()
832 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000833 g_gmock_mutex.AssertHeld();
834 call_count_++;
835 }
836
zhanyong.waned6c9272011-02-23 19:39:27 +0000837 // Checks the action count (i.e. the number of WillOnce() and
838 // WillRepeatedly() clauses) against the cardinality if this hasn't
839 // been done before. Prints a warning if there are too many or too
840 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000841 void CheckActionCountIfNotDone() const
842 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000843
shiqiane35fdd92008-12-10 05:08:54 +0000844 friend class ::testing::Sequence;
845 friend class ::testing::internal::ExpectationTester;
846
847 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000848 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000849
zhanyong.waned6c9272011-02-23 19:39:27 +0000850 // Implements the .Times() clause.
851 void UntypedTimes(const Cardinality& a_cardinality);
852
shiqiane35fdd92008-12-10 05:08:54 +0000853 // This group of fields are part of the spec and won't change after
854 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000855 const char* file_; // The file that contains the expectation.
856 int line_; // The line number of the expectation.
Nico Weber09fd5b32017-05-15 17:07:03 -0400857 const std::string source_text_; // The EXPECT_CALL(...) source text.
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200858 // True if the cardinality is specified explicitly.
shiqiane35fdd92008-12-10 05:08:54 +0000859 bool cardinality_specified_;
860 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000861 // The immediate pre-requisites (i.e. expectations that must be
862 // satisfied before this expectation can be matched) of this
misterg80b43d92018-10-29 11:09:33 -0400863 // expectation. We use std::shared_ptr in the set because we want an
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000864 // Expectation object to be co-owned by its FunctionMocker and its
865 // successors. This allows multiple mock objects to be deleted at
866 // different times.
867 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000868
869 // This group of fields are the current state of the expectation,
870 // and can change as the mock function is called.
871 int call_count_; // How many times this expectation has been invoked.
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200872 bool retired_; // True if this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000873 UntypedActions untyped_actions_;
874 bool extra_matcher_specified_;
875 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
876 bool retires_on_saturation_;
877 Clause last_clause_;
878 mutable bool action_count_checked_; // Under mutex_.
879 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000880
881 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000882}; // class ExpectationBase
883
884// Impements an expectation for the given function type.
885template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000886class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000887 public:
888 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
889 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
890 typedef typename Function<F>::Result Result;
891
Abseil Teamde5be0e2018-11-08 11:14:50 -0500892 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
Nico Weber09fd5b32017-05-15 17:07:03 -0400893 const std::string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000894 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000895 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000896 owner_(owner),
897 matchers_(m),
Abseil Team9518a572019-01-17 15:56:41 -0500898 // By default, extra_matcher_ should match anything. However,
899 // we cannot initialize it with _ as that causes ambiguity between
900 // Matcher's copy and move constructor for some argument types.
901 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000902 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000903
Abseil Team26743362018-12-03 11:30:02 -0500904 ~TypedExpectation() override {
shiqiane35fdd92008-12-10 05:08:54 +0000905 // Check the validity of the action count if it hasn't been done
906 // yet (for example, if the expectation was never used).
907 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000908 for (UntypedActions::const_iterator it = untyped_actions_.begin();
909 it != untyped_actions_.end(); ++it) {
910 delete static_cast<const Action<F>*>(*it);
911 }
shiqiane35fdd92008-12-10 05:08:54 +0000912 }
913
zhanyong.wanbf550852009-06-09 06:09:53 +0000914 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000915 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000916 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000917 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000918 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000919 "more than once in an EXPECT_CALL().");
920 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000921 ExpectSpecProperty(last_clause_ < kWith,
922 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000923 "clause in an EXPECT_CALL().");
924 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000925 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000926
927 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000928 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000929 return *this;
930 }
931
932 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000933 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000934 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000935 return *this;
936 }
937
938 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000939 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000940 return Times(Exactly(n));
941 }
942
943 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000944 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000945 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000946 ".InSequence() cannot appear after .After(),"
947 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000948 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000949 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000950
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000951 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000952 return *this;
953 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000954 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000955 return InSequence(s1).InSequence(s2);
956 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000957 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
958 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000959 return InSequence(s1, s2).InSequence(s3);
960 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000961 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
962 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000963 return InSequence(s1, s2, s3).InSequence(s4);
964 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000965 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
966 const Sequence& s3, const Sequence& s4,
967 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000968 return InSequence(s1, s2, s3, s4).InSequence(s5);
969 }
970
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000971 // Implements that .After() clause.
972 TypedExpectation& After(const ExpectationSet& s) {
973 ExpectSpecProperty(last_clause_ <= kAfter,
974 ".After() cannot appear after .WillOnce(),"
975 " .WillRepeatedly(), or "
976 ".RetiresOnSaturation().");
977 last_clause_ = kAfter;
978
979 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
980 immediate_prerequisites_ += *it;
981 }
982 return *this;
983 }
984 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
985 return After(s1).After(s2);
986 }
987 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
988 const ExpectationSet& s3) {
989 return After(s1, s2).After(s3);
990 }
991 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
992 const ExpectationSet& s3, const ExpectationSet& s4) {
993 return After(s1, s2, s3).After(s4);
994 }
995 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
996 const ExpectationSet& s3, const ExpectationSet& s4,
997 const ExpectationSet& s5) {
998 return After(s1, s2, s3, s4).After(s5);
999 }
1000
shiqiane35fdd92008-12-10 05:08:54 +00001001 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001002 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001003 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +00001004 ".WillOnce() cannot appear after "
1005 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +00001006 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +00001007
zhanyong.waned6c9272011-02-23 19:39:27 +00001008 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001009 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001010 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001011 }
1012 return *this;
1013 }
1014
1015 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001016 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001017 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001018 ExpectSpecProperty(false,
1019 ".WillRepeatedly() cannot appear "
1020 "more than once in an EXPECT_CALL().");
1021 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001022 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001023 ".WillRepeatedly() cannot appear "
1024 "after .RetiresOnSaturation().");
1025 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001026 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001027 repeated_action_specified_ = true;
1028
1029 repeated_action_ = action;
1030 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001031 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001032 }
1033
1034 // Now that no more action clauses can be specified, we check
1035 // whether their count makes sense.
1036 CheckActionCountIfNotDone();
1037 return *this;
1038 }
1039
1040 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001041 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001042 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001043 ".RetiresOnSaturation() cannot appear "
1044 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001045 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001046 retires_on_saturation_ = true;
1047
1048 // Now that no more action clauses can be specified, we check
1049 // whether their count makes sense.
1050 CheckActionCountIfNotDone();
1051 return *this;
1052 }
1053
1054 // Returns the matchers for the arguments as specified inside the
1055 // EXPECT_CALL() macro.
1056 const ArgumentMatcherTuple& matchers() const {
1057 return matchers_;
1058 }
1059
zhanyong.wanbf550852009-06-09 06:09:53 +00001060 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001061 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1062 return extra_matcher_;
1063 }
1064
shiqiane35fdd92008-12-10 05:08:54 +00001065 // Returns the action specified by the .WillRepeatedly() clause.
1066 const Action<F>& repeated_action() const { return repeated_action_; }
1067
zhanyong.waned6c9272011-02-23 19:39:27 +00001068 // If this mock method has an extra matcher (i.e. .With(matcher)),
1069 // describes it to the ostream.
Abseil Team26743362018-12-03 11:30:02 -05001070 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
vladlosev6c54a5e2009-10-21 06:15:34 +00001071 if (extra_matcher_specified_) {
1072 *os << " Expected args: ";
1073 extra_matcher_.DescribeTo(os);
1074 *os << "\n";
1075 }
1076 }
1077
shiqiane35fdd92008-12-10 05:08:54 +00001078 private:
1079 template <typename Function>
Abseil Teamde5be0e2018-11-08 11:14:50 -05001080 friend class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +00001081
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001082 // Returns an Expectation object that references and co-owns this
1083 // expectation.
Abseil Team26743362018-12-03 11:30:02 -05001084 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001085
shiqiane35fdd92008-12-10 05:08:54 +00001086 // The following methods will be called only after the EXPECT_CALL()
1087 // statement finishes and when the current thread holds
1088 // g_gmock_mutex.
1089
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +02001090 // Returns true if this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001091 bool Matches(const ArgumentTuple& args) const
1092 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001093 g_gmock_mutex.AssertHeld();
1094 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1095 }
1096
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +02001097 // Returns true if this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001098 bool ShouldHandleArguments(const ArgumentTuple& args) const
1099 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001100 g_gmock_mutex.AssertHeld();
1101
1102 // In case the action count wasn't checked when the expectation
1103 // was defined (e.g. if this expectation has no WillRepeatedly()
1104 // or RetiresOnSaturation() clause), we check it when the
1105 // expectation is used for the first time.
1106 CheckActionCountIfNotDone();
1107 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1108 }
1109
1110 // Describes the result of matching the arguments against this
1111 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001112 void ExplainMatchResultTo(
1113 const ArgumentTuple& args,
1114 ::std::ostream* os) const
1115 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001116 g_gmock_mutex.AssertHeld();
1117
1118 if (is_retired()) {
1119 *os << " Expected: the expectation is active\n"
1120 << " Actual: it is retired\n";
1121 } else if (!Matches(args)) {
1122 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001123 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001124 }
zhanyong.wan82113312010-01-08 21:55:40 +00001125 StringMatchResultListener listener;
1126 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001127 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001128 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001129 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001130
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001131 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001132 *os << "\n";
1133 }
1134 } else if (!AllPrerequisitesAreSatisfied()) {
1135 *os << " Expected: all pre-requisites are satisfied\n"
1136 << " Actual: the following immediate pre-requisites "
1137 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001138 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001139 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1140 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001141 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001142 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001143 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001144 *os << "pre-requisite #" << i++ << "\n";
1145 }
1146 *os << " (end of pre-requisites)\n";
1147 } else {
1148 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001149 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001150 // is called only when the mock function call does NOT match the
1151 // expectation.
1152 *os << "The call matches the expectation.\n";
1153 }
1154 }
1155
1156 // Returns the action that should be taken for the current invocation.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001157 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
1158 const ArgumentTuple& args) const
1159 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001160 g_gmock_mutex.AssertHeld();
1161 const int count = call_count();
1162 Assert(count >= 1, __FILE__, __LINE__,
1163 "call_count() is <= 0 when GetCurrentAction() is "
1164 "called - this should never happen.");
1165
zhanyong.waned6c9272011-02-23 19:39:27 +00001166 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001167 if (action_count > 0 && !repeated_action_specified_ &&
1168 count > action_count) {
1169 // If there is at least one WillOnce() and no WillRepeatedly(),
1170 // we warn the user when the WillOnce() clauses ran out.
1171 ::std::stringstream ss;
1172 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001173 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001174 << "Called " << count << " times, but only "
1175 << action_count << " WillOnce()"
1176 << (action_count == 1 ? " is" : "s are") << " specified - ";
1177 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001178 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001179 }
1180
Gennadiy Civila651a4d2018-10-12 16:12:32 -04001181 return count <= action_count
1182 ? *static_cast<const Action<F>*>(
1183 untyped_actions_[static_cast<size_t>(count - 1)])
1184 : repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001185 }
1186
1187 // Given the arguments of a mock function call, if the call will
1188 // over-saturate this expectation, returns the default action;
1189 // otherwise, returns the next action in this expectation. Also
1190 // describes *what* happened to 'what', and explains *why* Google
1191 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001192 // IncrementCallCount(). A return value of NULL means the default
1193 // action.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001194 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
1195 const ArgumentTuple& args,
1196 ::std::ostream* what,
1197 ::std::ostream* why)
1198 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001199 g_gmock_mutex.AssertHeld();
1200 if (IsSaturated()) {
1201 // We have an excessive call.
1202 IncrementCallCount();
1203 *what << "Mock function called more times than expected - ";
1204 mocker->DescribeDefaultActionTo(args, what);
1205 DescribeCallCountTo(why);
1206
Abseil Team4bb49ed2018-10-04 18:28:05 -04001207 return nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001208 }
1209
1210 IncrementCallCount();
1211 RetireAllPreRequisites();
1212
zhanyong.waned6c9272011-02-23 19:39:27 +00001213 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001214 Retire();
1215 }
1216
1217 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001218 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001219 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001220 }
1221
1222 // All the fields below won't change once the EXPECT_CALL()
1223 // statement finishes.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001224 FunctionMocker<F>* const owner_;
shiqiane35fdd92008-12-10 05:08:54 +00001225 ArgumentMatcherTuple matchers_;
1226 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001227 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001228
1229 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001230}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001231
1232// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1233// specifying the default behavior of, or expectation on, a mock
1234// function.
1235
1236// Note: class MockSpec really belongs to the ::testing namespace.
1237// However if we define it in ::testing, MSVC will complain when
1238// classes in ::testing::internal declare it as a friend class
1239// template. To workaround this compiler bug, we define MockSpec in
1240// ::testing::internal and import it into ::testing.
1241
zhanyong.waned6c9272011-02-23 19:39:27 +00001242// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001243GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1244 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001245 const std::string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001246
shiqiane35fdd92008-12-10 05:08:54 +00001247template <typename F>
1248class MockSpec {
1249 public:
1250 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1251 typedef typename internal::Function<F>::ArgumentMatcherTuple
1252 ArgumentMatcherTuple;
1253
1254 // Constructs a MockSpec object, given the function mocker object
1255 // that the spec is associated with.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001256 MockSpec(internal::FunctionMocker<F>* function_mocker,
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001257 const ArgumentMatcherTuple& matchers)
1258 : function_mocker_(function_mocker), matchers_(matchers) {}
shiqiane35fdd92008-12-10 05:08:54 +00001259
1260 // Adds a new default action spec to the function mocker and returns
1261 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001262 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001263 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001264 LogWithLocation(internal::kInfo, file, line,
Nico Weber09fd5b32017-05-15 17:07:03 -04001265 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001266 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001267 }
1268
1269 // Adds a new expectation spec to the function mocker and returns
1270 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001271 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001272 const char* file, int line, const char* obj, const char* call) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001273 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1274 call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001275 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001276 return function_mocker_->AddNewExpectation(
1277 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001278 }
1279
David Sunderlandf437f8c2018-04-18 19:28:56 -04001280 // This operator overload is used to swallow the superfluous parameter list
1281 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1282 // explanation.
1283 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1284 return *this;
1285 }
1286
shiqiane35fdd92008-12-10 05:08:54 +00001287 private:
1288 template <typename Function>
1289 friend class internal::FunctionMocker;
1290
shiqiane35fdd92008-12-10 05:08:54 +00001291 // The function mocker that owns this spec.
Abseil Teamde5be0e2018-11-08 11:14:50 -05001292 internal::FunctionMocker<F>* const function_mocker_;
shiqiane35fdd92008-12-10 05:08:54 +00001293 // The argument matchers specified in the spec.
1294 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001295
1296 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001297}; // class MockSpec
1298
kosakb5c81092014-01-29 06:41:44 +00001299// Wrapper type for generically holding an ordinary value or lvalue reference.
1300// If T is not a reference type, it must be copyable or movable.
1301// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1302// T is a move-only value type (which means that it will always be copyable
1303// if the current platform does not support move semantics).
1304//
1305// The primary template defines handling for values, but function header
1306// comments describe the contract for the whole template (including
1307// specializations).
1308template <typename T>
1309class ReferenceOrValueWrapper {
1310 public:
1311 // Constructs a wrapper from the given value/reference.
kosakd370f852014-11-17 01:14:16 +00001312 explicit ReferenceOrValueWrapper(T value)
Abseil Team29b47e42018-10-16 15:29:37 -04001313 : value_(std::move(value)) {
kosakd370f852014-11-17 01:14:16 +00001314 }
kosakb5c81092014-01-29 06:41:44 +00001315
1316 // Unwraps and returns the underlying value/reference, exactly as
1317 // originally passed. The behavior of calling this more than once on
1318 // the same object is unspecified.
Abseil Team29b47e42018-10-16 15:29:37 -04001319 T Unwrap() { return std::move(value_); }
kosakb5c81092014-01-29 06:41:44 +00001320
1321 // Provides nondestructive access to the underlying value/reference.
1322 // Always returns a const reference (more precisely,
1323 // const RemoveReference<T>&). The behavior of calling this after
1324 // calling Unwrap on the same object is unspecified.
1325 const T& Peek() const {
1326 return value_;
1327 }
1328
1329 private:
1330 T value_;
1331};
1332
1333// Specialization for lvalue reference types. See primary template
1334// for documentation.
1335template <typename T>
1336class ReferenceOrValueWrapper<T&> {
1337 public:
1338 // Workaround for debatable pass-by-reference lint warning (c-library-team
1339 // policy precludes NOLINT in this context)
1340 typedef T& reference;
1341 explicit ReferenceOrValueWrapper(reference ref)
1342 : value_ptr_(&ref) {}
1343 T& Unwrap() { return *value_ptr_; }
1344 const T& Peek() const { return *value_ptr_; }
1345
1346 private:
1347 T* value_ptr_;
1348};
1349
shiqiane35fdd92008-12-10 05:08:54 +00001350// MSVC warns about using 'this' in base member initializer list, so
1351// we need to temporarily disable the warning. We have to do it for
1352// the entire class to suppress the warning, even though it's about
1353// the constructor only.
mistergdf428ec2018-08-20 14:48:45 -04001354GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
shiqiane35fdd92008-12-10 05:08:54 +00001355
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001356// C++ treats the void type specially. For example, you cannot define
1357// a void-typed variable or pass a void value to a function.
1358// ActionResultHolder<T> holds a value of type T, where T must be a
1359// copyable type or void (T doesn't need to be default-constructable).
1360// It hides the syntactic difference between void and other types, and
1361// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001362// non-void-returning mock functions.
1363
1364// Untyped base class for ActionResultHolder<T>.
1365class UntypedActionResultHolderBase {
1366 public:
1367 virtual ~UntypedActionResultHolderBase() {}
1368
1369 // Prints the held value as an action's result to os.
1370 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1371};
1372
1373// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001374template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001375class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001376 public:
kosakb5c81092014-01-29 06:41:44 +00001377 // Returns the held value. Must not be called more than once.
1378 T Unwrap() {
1379 return result_.Unwrap();
zhanyong.waned6c9272011-02-23 19:39:27 +00001380 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001381
1382 // Prints the held value as an action's result to os.
Abseil Team26743362018-12-03 11:30:02 -05001383 void PrintAsActionResult(::std::ostream* os) const override {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001384 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001385 // T may be a reference type, so we don't use UniversalPrint().
kosakb5c81092014-01-29 06:41:44 +00001386 UniversalPrinter<T>::Print(result_.Peek(), os);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001387 }
1388
1389 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001390 // result in a new-ed ActionResultHolder.
1391 template <typename F>
1392 static ActionResultHolder* PerformDefaultAction(
Abseil Teamde5be0e2018-11-08 11:14:50 -05001393 const FunctionMocker<F>* func_mocker,
Abseil Team29b47e42018-10-16 15:29:37 -04001394 typename Function<F>::ArgumentTuple&& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001395 const std::string& call_description) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001396 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
Abseil Team29b47e42018-10-16 15:29:37 -04001397 std::move(args), call_description)));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001398 }
1399
zhanyong.waned6c9272011-02-23 19:39:27 +00001400 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001401 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001402 template <typename F>
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001403 static ActionResultHolder* PerformAction(
Abseil Team29b47e42018-10-16 15:29:37 -04001404 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001405 return new ActionResultHolder(
Abseil Team29b47e42018-10-16 15:29:37 -04001406 Wrapper(action.Perform(std::move(args))));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001407 }
1408
1409 private:
kosakb5c81092014-01-29 06:41:44 +00001410 typedef ReferenceOrValueWrapper<T> Wrapper;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001411
kosakd370f852014-11-17 01:14:16 +00001412 explicit ActionResultHolder(Wrapper result)
Abseil Team29b47e42018-10-16 15:29:37 -04001413 : result_(std::move(result)) {
kosakd370f852014-11-17 01:14:16 +00001414 }
kosakb5c81092014-01-29 06:41:44 +00001415
1416 Wrapper result_;
1417
1418 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001419};
1420
1421// Specialization for T = void.
1422template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001423class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001424 public:
kosakb5c81092014-01-29 06:41:44 +00001425 void Unwrap() { }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001426
Abseil Team26743362018-12-03 11:30:02 -05001427 void PrintAsActionResult(::std::ostream* /* os */) const override {}
zhanyong.waned6c9272011-02-23 19:39:27 +00001428
kosakb5c81092014-01-29 06:41:44 +00001429 // Performs the given mock function's default action and returns ownership
1430 // of an empty ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001431 template <typename F>
1432 static ActionResultHolder* PerformDefaultAction(
Abseil Teamde5be0e2018-11-08 11:14:50 -05001433 const FunctionMocker<F>* func_mocker,
Abseil Team29b47e42018-10-16 15:29:37 -04001434 typename Function<F>::ArgumentTuple&& args,
Nico Weber09fd5b32017-05-15 17:07:03 -04001435 const std::string& call_description) {
Abseil Team29b47e42018-10-16 15:29:37 -04001436 func_mocker->PerformDefaultAction(std::move(args), call_description);
kosakb5c81092014-01-29 06:41:44 +00001437 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001438 }
1439
kosakb5c81092014-01-29 06:41:44 +00001440 // Performs the given action and returns ownership of an empty
1441 // ActionResultHolder*.
zhanyong.waned6c9272011-02-23 19:39:27 +00001442 template <typename F>
1443 static ActionResultHolder* PerformAction(
Abseil Team29b47e42018-10-16 15:29:37 -04001444 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
1445 action.Perform(std::move(args));
kosakb5c81092014-01-29 06:41:44 +00001446 return new ActionResultHolder;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001447 }
kosakb5c81092014-01-29 06:41:44 +00001448
1449 private:
1450 ActionResultHolder() {}
1451 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001452};
1453
shiqiane35fdd92008-12-10 05:08:54 +00001454template <typename F>
Abseil Teamde5be0e2018-11-08 11:14:50 -05001455class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +00001456
Abseil Teamde5be0e2018-11-08 11:14:50 -05001457template <typename R, typename... Args>
Abseil Team569fba42019-01-22 09:58:06 -05001458class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
Abseil Teamde5be0e2018-11-08 11:14:50 -05001459 using F = R(Args...);
1460
1461 public:
1462 using Result = R;
1463 using ArgumentTuple = std::tuple<Args...>;
1464 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1465
1466 FunctionMocker() {}
1467
1468 // There is no generally useful and implementable semantics of
1469 // copying a mock object, so copying a mock is usually a user error.
1470 // Thus we disallow copying function mockers. If the user really
1471 // wants to copy a mock object, they should implement their own copy
1472 // operation, for example:
1473 //
1474 // class MockFoo : public Foo {
1475 // public:
1476 // // Defines a copy constructor explicitly.
1477 // MockFoo(const MockFoo& src) {}
1478 // ...
1479 // };
1480 FunctionMocker(const FunctionMocker&) = delete;
1481 FunctionMocker& operator=(const FunctionMocker&) = delete;
shiqiane35fdd92008-12-10 05:08:54 +00001482
1483 // The destructor verifies that all expectations on this mock
1484 // function have been satisfied. If not, it will report Google Test
1485 // non-fatal failures for the violations.
Abseil Team26743362018-12-03 11:30:02 -05001486 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001487 MutexLock l(&g_gmock_mutex);
1488 VerifyAndClearExpectationsLocked();
1489 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001490 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001491 }
1492
1493 // Returns the ON_CALL spec that matches this mock function with the
1494 // given arguments; returns NULL if no matching ON_CALL is found.
1495 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001496 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001497 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001498 for (UntypedOnCallSpecs::const_reverse_iterator it
1499 = untyped_on_call_specs_.rbegin();
1500 it != untyped_on_call_specs_.rend(); ++it) {
1501 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1502 if (spec->Matches(args))
1503 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001504 }
1505
Abseil Team4bb49ed2018-10-04 18:28:05 -04001506 return nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001507 }
1508
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001509 // Performs the default action of this mock function on the given
1510 // arguments and returns the result. Asserts (or throws if
1511 // exceptions are enabled) with a helpful call descrption if there
1512 // is no valid return value. This method doesn't depend on the
1513 // mutable state of this object, and thus can be called concurrently
1514 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001515 // L = *
Abseil Teamde5be0e2018-11-08 11:14:50 -05001516 Result PerformDefaultAction(ArgumentTuple&& args,
Abseil Team29b47e42018-10-16 15:29:37 -04001517 const std::string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001518 const OnCallSpec<F>* const spec =
1519 this->FindOnCallSpec(args);
Abseil Team4bb49ed2018-10-04 18:28:05 -04001520 if (spec != nullptr) {
Abseil Team29b47e42018-10-16 15:29:37 -04001521 return spec->GetAction().Perform(std::move(args));
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001522 }
Nico Weber09fd5b32017-05-15 17:07:03 -04001523 const std::string message =
1524 call_description +
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001525 "\n The mock function has no default action "
1526 "set, and its return type has no default value set.";
1527#if GTEST_HAS_EXCEPTIONS
1528 if (!DefaultValue<Result>::Exists()) {
1529 throw std::runtime_error(message);
1530 }
1531#else
1532 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1533#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001534 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001535 }
1536
zhanyong.waned6c9272011-02-23 19:39:27 +00001537 // Performs the default action with the given arguments and returns
1538 // the action's result. The call description string will be used in
1539 // the error message to describe the call in the case the default
1540 // action fails. The caller is responsible for deleting the result.
1541 // L = *
Abseil Team26743362018-12-03 11:30:02 -05001542 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001543 void* untyped_args, // must point to an ArgumentTuple
Abseil Team26743362018-12-03 11:30:02 -05001544 const std::string& call_description) const override {
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001545 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team29b47e42018-10-16 15:29:37 -04001546 return ResultHolder::PerformDefaultAction(this, std::move(*args),
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001547 call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001548 }
1549
zhanyong.waned6c9272011-02-23 19:39:27 +00001550 // Performs the given action with the given arguments and returns
1551 // the action's result. The caller is responsible for deleting the
1552 // result.
1553 // L = *
Abseil Team26743362018-12-03 11:30:02 -05001554 UntypedActionResultHolderBase* UntypedPerformAction(
1555 const void* untyped_action, void* untyped_args) const override {
zhanyong.waned6c9272011-02-23 19:39:27 +00001556 // Make a copy of the action before performing it, in case the
1557 // action deletes the mock object (and thus deletes itself).
1558 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001559 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team29b47e42018-10-16 15:29:37 -04001560 return ResultHolder::PerformAction(action, std::move(*args));
zhanyong.waned6c9272011-02-23 19:39:27 +00001561 }
shiqiane35fdd92008-12-10 05:08:54 +00001562
zhanyong.waned6c9272011-02-23 19:39:27 +00001563 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1564 // clears the ON_CALL()s set on this mock function.
Abseil Team26743362018-12-03 11:30:02 -05001565 void ClearDefaultActionsLocked() override
vladlosev4d60a592011-10-24 21:16:22 +00001566 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001567 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001568
1569 // Deleting our default actions may trigger other mock objects to be
1570 // deleted, for example if an action contains a reference counted smart
1571 // pointer to that mock object, and that is the last reference. So if we
1572 // delete our actions within the context of the global mutex we may deadlock
1573 // when this method is called again. Instead, make a copy of the set of
1574 // actions to delete, clear our set within the mutex, and then delete the
1575 // actions outside of the mutex.
1576 UntypedOnCallSpecs specs_to_delete;
1577 untyped_on_call_specs_.swap(specs_to_delete);
1578
1579 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001580 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001581 specs_to_delete.begin();
1582 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001583 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001584 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001585
1586 // Lock the mutex again, since the caller expects it to be locked when we
1587 // return.
1588 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001589 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001590
Abseil Teamde5be0e2018-11-08 11:14:50 -05001591 // Returns the result of invoking this mock function with the given
1592 // arguments. This function can be safely called from multiple
1593 // threads concurrently.
1594 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1595 ArgumentTuple tuple(std::forward<Args>(args)...);
1596 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
1597 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
1598 return holder->Unwrap();
1599 }
1600
1601 MockSpec<F> With(Matcher<Args>... m) {
1602 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
1603 }
1604
shiqiane35fdd92008-12-10 05:08:54 +00001605 protected:
1606 template <typename Function>
1607 friend class MockSpec;
1608
zhanyong.waned6c9272011-02-23 19:39:27 +00001609 typedef ActionResultHolder<Result> ResultHolder;
1610
shiqiane35fdd92008-12-10 05:08:54 +00001611 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001612 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001613 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001614 const ArgumentMatcherTuple& m)
1615 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001616 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001617 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1618 untyped_on_call_specs_.push_back(on_call_spec);
1619 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001620 }
1621
1622 // Adds and returns an expectation spec for this mock function.
Nico Weber09fd5b32017-05-15 17:07:03 -04001623 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1624 const std::string& source_text,
1625 const ArgumentMatcherTuple& m)
1626 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001627 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001628 TypedExpectation<F>* const expectation =
1629 new TypedExpectation<F>(this, file, line, source_text, m);
misterg80b43d92018-10-29 11:09:33 -04001630 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civilfe402c22018-04-05 16:09:17 -04001631 // See the definition of untyped_expectations_ for why access to
1632 // it is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +00001633 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001634
1635 // Adds this expectation into the implicit sequence if there is one.
1636 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
Abseil Team4bb49ed2018-10-04 18:28:05 -04001637 if (implicit_sequence != nullptr) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001638 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001639 }
1640
1641 return *expectation;
1642 }
1643
shiqiane35fdd92008-12-10 05:08:54 +00001644 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001645 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001646
zhanyong.waned6c9272011-02-23 19:39:27 +00001647 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001648
1649 // Describes what default action will be performed for the given
1650 // arguments.
1651 // L = *
1652 void DescribeDefaultActionTo(const ArgumentTuple& args,
1653 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001654 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001655
Abseil Team4bb49ed2018-10-04 18:28:05 -04001656 if (spec == nullptr) {
Krystian Kuzniarekec49fbc2019-08-13 22:30:12 +02001657 *os << (std::is_void<Result>::value ? "returning directly.\n"
1658 : "returning default value.\n");
shiqiane35fdd92008-12-10 05:08:54 +00001659 } 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_