1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// Google Mock - a framework for writing C++ mock classes.
31//
32// This file implements the ON_CALL() and EXPECT_CALL() macros.
33//
34// A user can use the ON_CALL() macro to specify the default action of
35// a mock method. The syntax is:
36//
37// ON_CALL(mock_object, Method(argument-matchers))
38// .With(multi-argument-matcher)
39// .WillByDefault(action);
40//
41// where the .With() clause is optional.
42//
43// A user can use the EXPECT_CALL() macro to specify an expectation on
44// a mock method. The syntax is:
45//
46// EXPECT_CALL(mock_object, Method(argument-matchers))
47// .With(multi-argument-matchers)
48// .Times(cardinality)
49// .InSequence(sequences)
50// .After(expectations)
51// .WillOnce(action)
52// .WillRepeatedly(action)
53// .RetiresOnSaturation();
54//
55// where all clauses are optional, and .InSequence()/.After()/
56// .WillOnce() can appear any number of times.
57
58// IWYU pragma: private, include "gmock/gmock.h"
59// IWYU pragma: friend gmock/.*
60
61#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
63
64#include <cstdint>
65#include <functional>
66#include <map>
67#include <memory>
68#include <ostream>
69#include <set>
70#include <sstream>
71#include <string>
72#include <type_traits>
73#include <utility>
74#include <vector>
75
76#include "gmock/gmock-actions.h"
77#include "gmock/gmock-cardinalities.h"
78#include "gmock/gmock-matchers.h"
79#include "gmock/internal/gmock-internal-utils.h"
80#include "gmock/internal/gmock-port.h"
81#include "gtest/gtest.h"
82
83#if GTEST_HAS_EXCEPTIONS
84#include <stdexcept> // NOLINT
85#endif
86
87GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
88/* class A needs to have dll-interface to be used by clients of class B */)
89
90namespace testing {
91
92// An abstract handle of an expectation.
93class Expectation;
94
95// A set of expectation handles.
96class ExpectationSet;
97
98// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
99// and MUST NOT BE USED IN USER CODE!!!
100namespace internal {
101
102// Implements a mock function.
103template <typename F>
104class FunctionMocker;
105
106// Base class for expectations.
107class ExpectationBase;
108
109// Implements an expectation.
110template <typename F>
111class TypedExpectation;
112
113// Helper class for testing the Expectation class template.
114class ExpectationTester;
115
116// Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
117template <typename MockClass>
118class NiceMockImpl;
119template <typename MockClass>
120class StrictMockImpl;
121template <typename MockClass>
122class NaggyMockImpl;
123
124// Protects the mock object registry (in class Mock), all function
125// mockers, and all expectations.
126//
127// The reason we don't use more fine-grained protection is: when a
128// mock function Foo() is called, it needs to consult its expectations
129// to see which one should be picked. If another thread is allowed to
130// call a mock function (either Foo() or a different one) at the same
131// time, it could affect the "retired" attributes of Foo()'s
132// expectations when InSequence() is used, and thus affect which
133// expectation gets picked. Therefore, we sequence all mock function
134// calls to ensure the integrity of the mock objects' states.
135GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
136
137// Abstract base class of FunctionMocker. This is the
138// type-agnostic part of the function mocker interface. Its pure
139// virtual methods are implemented by FunctionMocker.
140class GTEST_API_ UntypedFunctionMockerBase {
141 public:
142 UntypedFunctionMockerBase();
143 virtual ~UntypedFunctionMockerBase();
144
145 // Verifies that all expectations on this mock function have been
146 // satisfied. Reports one or more Google Test non-fatal failures
147 // and returns false if not.
148 bool VerifyAndClearExpectationsLocked()
149 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
150
151 // Clears the ON_CALL()s set on this mock function.
152 virtual void ClearDefaultActionsLocked()
153 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
154
155 // In all of the following Untyped* functions, it's the caller's
156 // responsibility to guarantee the correctness of the arguments'
157 // types.
158
159 // Writes a message that the call is uninteresting (i.e. neither
160 // explicitly expected nor explicitly unexpected) to the given
161 // ostream.
162 virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
163 ::std::ostream* os) const
164 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
165
166 // Returns the expectation that matches the given function arguments
167 // (or NULL is there's no match); when a match is found,
168 // untyped_action is set to point to the action that should be
169 // performed (or NULL if the action is "do default"), and
170 // is_excessive is modified to indicate whether the call exceeds the
171 // expected number.
172 virtual const ExpectationBase* UntypedFindMatchingExpectation(
173 const void* untyped_args, const void** untyped_action, bool* is_excessive,
174 ::std::ostream* what, ::std::ostream* why)
175 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
176
177 // Prints the given function arguments to the ostream.
178 virtual void UntypedPrintArgs(const void* untyped_args,
179 ::std::ostream* os) const = 0;
180
181 // Sets the mock object this mock method belongs to, and registers
182 // this information in the global mock registry. Will be called
183 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
184 // method.
185 void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
186
187 // Sets the mock object this mock method belongs to, and sets the
188 // name of the mock function. Will be called upon each invocation
189 // of this mock function.
190 void SetOwnerAndName(const void* mock_obj, const char* name)
191 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
192
193 // Returns the mock object this mock method belongs to. Must be
194 // called after RegisterOwner() or SetOwnerAndName() has been
195 // called.
196 const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
197
198 // Returns the name of this mock method. Must be called after
199 // SetOwnerAndName() has been called.
200 const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
201
202 protected:
203 typedef std::vector<const void*> UntypedOnCallSpecs;
204
205 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
206
207 // Returns an Expectation object that references and co-owns exp,
208 // which must be an expectation on this mock function.
209 Expectation GetHandleOf(ExpectationBase* exp);
210
211 // Address of the mock object this mock method belongs to. Only
212 // valid after this mock method has been called or
213 // ON_CALL/EXPECT_CALL has been invoked on it.
214 const void* mock_obj_; // Protected by g_gmock_mutex.
215
216 // Name of the function being mocked. Only valid after this mock
217 // method has been called.
218 const char* name_; // Protected by g_gmock_mutex.
219
220 // All default action specs for this function mocker.
221 UntypedOnCallSpecs untyped_on_call_specs_;
222
223 // All expectations for this function mocker.
224 //
225 // It's undefined behavior to interleave expectations (EXPECT_CALLs
226 // or ON_CALLs) and mock function calls. Also, the order of
227 // expectations is important. Therefore it's a logic race condition
228 // to read/write untyped_expectations_ concurrently. In order for
229 // tools like tsan to catch concurrent read/write accesses to
230 // untyped_expectations, we deliberately leave accesses to it
231 // unprotected.
232 UntypedExpectations untyped_expectations_;
233}; // class UntypedFunctionMockerBase
234
235// Untyped base class for OnCallSpec<F>.
236class UntypedOnCallSpecBase {
237 public:
238 // The arguments are the location of the ON_CALL() statement.
239 UntypedOnCallSpecBase(const char* a_file, int a_line)
240 : file_(a_file), line_(a_line), last_clause_(kNone) {}
241
242 // Where in the source file was the default action spec defined?
243 const char* file() const { return file_; }
244 int line() const { return line_; }
245
246 protected:
247 // Gives each clause in the ON_CALL() statement a name.
248 enum Clause {
249 // Do not change the order of the enum members! The run-time
250 // syntax checking relies on it.
251 kNone,
252 kWith,
253 kWillByDefault
254 };
255
256 // Asserts that the ON_CALL() statement has a certain property.
257 void AssertSpecProperty(bool property,
258 const std::string& failure_message) const {
259 Assert(condition: property, file: file_, line: line_, msg: failure_message);
260 }
261
262 // Expects that the ON_CALL() statement has a certain property.
263 void ExpectSpecProperty(bool property,
264 const std::string& failure_message) const {
265 Expect(condition: property, file: file_, line: line_, msg: failure_message);
266 }
267
268 const char* file_;
269 int line_;
270
271 // The last clause in the ON_CALL() statement as seen so far.
272 // Initially kNone and changes as the statement is parsed.
273 Clause last_clause_;
274}; // class UntypedOnCallSpecBase
275
276// This template class implements an ON_CALL spec.
277template <typename F>
278class OnCallSpec : public UntypedOnCallSpecBase {
279 public:
280 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
281 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
282
283 // Constructs an OnCallSpec object from the information inside
284 // the parenthesis of an ON_CALL() statement.
285 OnCallSpec(const char* a_file, int a_line,
286 const ArgumentMatcherTuple& matchers)
287 : UntypedOnCallSpecBase(a_file, a_line),
288 matchers_(matchers),
289 // By default, extra_matcher_ should match anything. However,
290 // we cannot initialize it with _ as that causes ambiguity between
291 // Matcher's copy and move constructor for some argument types.
292 extra_matcher_(A<const ArgumentTuple&>()) {}
293
294 // Implements the .With() clause.
295 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
296 // Makes sure this is called at most once.
297 ExpectSpecProperty(property: last_clause_ < kWith,
298 failure_message: ".With() cannot appear "
299 "more than once in an ON_CALL().");
300 last_clause_ = kWith;
301
302 extra_matcher_ = m;
303 return *this;
304 }
305
306 // Implements the .WillByDefault() clause.
307 OnCallSpec& WillByDefault(const Action<F>& action) {
308 ExpectSpecProperty(property: last_clause_ < kWillByDefault,
309 failure_message: ".WillByDefault() must appear "
310 "exactly once in an ON_CALL().");
311 last_clause_ = kWillByDefault;
312
313 ExpectSpecProperty(property: !action.IsDoDefault(),
314 failure_message: "DoDefault() cannot be used in ON_CALL().");
315 action_ = action;
316 return *this;
317 }
318
319 // Returns true if and only if the given arguments match the matchers.
320 bool Matches(const ArgumentTuple& args) const {
321 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
322 }
323
324 // Returns the action specified by the user.
325 const Action<F>& GetAction() const {
326 AssertSpecProperty(property: last_clause_ == kWillByDefault,
327 failure_message: ".WillByDefault() must appear exactly "
328 "once in an ON_CALL().");
329 return action_;
330 }
331
332 private:
333 // The information in statement
334 //
335 // ON_CALL(mock_object, Method(matchers))
336 // .With(multi-argument-matcher)
337 // .WillByDefault(action);
338 //
339 // is recorded in the data members like this:
340 //
341 // source file that contains the statement => file_
342 // line number of the statement => line_
343 // matchers => matchers_
344 // multi-argument-matcher => extra_matcher_
345 // action => action_
346 ArgumentMatcherTuple matchers_;
347 Matcher<const ArgumentTuple&> extra_matcher_;
348 Action<F> action_;
349}; // class OnCallSpec
350
351// Possible reactions on uninteresting calls.
352enum CallReaction {
353 kAllow,
354 kWarn,
355 kFail,
356};
357
358} // namespace internal
359
360// Utilities for manipulating mock objects.
361class GTEST_API_ Mock {
362 public:
363 // The following public methods can be called concurrently.
364
365 // Tells Google Mock to ignore mock_obj when checking for leaked
366 // mock objects.
367 static void AllowLeak(const void* mock_obj)
368 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
369
370 // Verifies and clears all expectations on the given mock object.
371 // If the expectations aren't satisfied, generates one or more
372 // Google Test non-fatal failures and returns false.
373 static bool VerifyAndClearExpectations(void* mock_obj)
374 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
375
376 // Verifies all expectations on the given mock object and clears its
377 // default actions and expectations. Returns true if and only if the
378 // verification was successful.
379 static bool VerifyAndClear(void* mock_obj)
380 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
381
382 // Returns whether the mock was created as a naggy mock (default)
383 static bool IsNaggy(void* mock_obj)
384 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
385 // Returns whether the mock was created as a nice mock
386 static bool IsNice(void* mock_obj)
387 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
388 // Returns whether the mock was created as a strict mock
389 static bool IsStrict(void* mock_obj)
390 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
391
392 private:
393 friend class internal::UntypedFunctionMockerBase;
394
395 // Needed for a function mocker to register itself (so that we know
396 // how to clear a mock object).
397 template <typename F>
398 friend class internal::FunctionMocker;
399
400 template <typename MockClass>
401 friend class internal::NiceMockImpl;
402 template <typename MockClass>
403 friend class internal::NaggyMockImpl;
404 template <typename MockClass>
405 friend class internal::StrictMockImpl;
406
407 // Tells Google Mock to allow uninteresting calls on the given mock
408 // object.
409 static void AllowUninterestingCalls(uintptr_t mock_obj)
410 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
411
412 // Tells Google Mock to warn the user about uninteresting calls on
413 // the given mock object.
414 static void WarnUninterestingCalls(uintptr_t mock_obj)
415 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
416
417 // Tells Google Mock to fail uninteresting calls on the given mock
418 // object.
419 static void FailUninterestingCalls(uintptr_t mock_obj)
420 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
421
422 // Tells Google Mock the given mock object is being destroyed and
423 // its entry in the call-reaction table should be removed.
424 static void UnregisterCallReaction(uintptr_t mock_obj)
425 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
426
427 // Returns the reaction Google Mock will have on uninteresting calls
428 // made on the given mock object.
429 static internal::CallReaction GetReactionOnUninterestingCalls(
430 const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
431
432 // Verifies that all expectations on the given mock object have been
433 // satisfied. Reports one or more Google Test non-fatal failures
434 // and returns false if not.
435 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
436 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
437
438 // Clears all ON_CALL()s set on the given mock object.
439 static void ClearDefaultActionsLocked(void* mock_obj)
440 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
441
442 // Registers a mock object and a mock method it owns.
443 static void Register(const void* mock_obj,
444 internal::UntypedFunctionMockerBase* mocker)
445 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
446
447 // Tells Google Mock where in the source code mock_obj is used in an
448 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
449 // information helps the user identify which object it is.
450 static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,
451 const char* file, int line)
452 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
453
454 // Unregisters a mock method; removes the owning mock object from
455 // the registry when the last mock method associated with it has
456 // been unregistered. This is called only in the destructor of
457 // FunctionMocker.
458 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
459 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
460}; // class Mock
461
462// An abstract handle of an expectation. Useful in the .After()
463// clause of EXPECT_CALL() for setting the (partial) order of
464// expectations. The syntax:
465//
466// Expectation e1 = EXPECT_CALL(...)...;
467// EXPECT_CALL(...).After(e1)...;
468//
469// sets two expectations where the latter can only be matched after
470// the former has been satisfied.
471//
472// Notes:
473// - This class is copyable and has value semantics.
474// - Constness is shallow: a const Expectation object itself cannot
475// be modified, but the mutable methods of the ExpectationBase
476// object it references can be called via expectation_base().
477
478class GTEST_API_ Expectation {
479 public:
480 // Constructs a null object that doesn't reference any expectation.
481 Expectation();
482 Expectation(Expectation&&) = default;
483 Expectation(const Expectation&) = default;
484 Expectation& operator=(Expectation&&) = default;
485 Expectation& operator=(const Expectation&) = default;
486 ~Expectation();
487
488 // This single-argument ctor must not be explicit, in order to support the
489 // Expectation e = EXPECT_CALL(...);
490 // syntax.
491 //
492 // A TypedExpectation object stores its pre-requisites as
493 // Expectation objects, and needs to call the non-const Retire()
494 // method on the ExpectationBase objects they reference. Therefore
495 // Expectation must receive a *non-const* reference to the
496 // ExpectationBase object.
497 Expectation(internal::ExpectationBase& exp); // NOLINT
498
499 // The compiler-generated copy ctor and operator= work exactly as
500 // intended, so we don't need to define our own.
501
502 // Returns true if and only if rhs references the same expectation as this
503 // object does.
504 bool operator==(const Expectation& rhs) const {
505 return expectation_base_ == rhs.expectation_base_;
506 }
507
508 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
509
510 private:
511 friend class ExpectationSet;
512 friend class Sequence;
513 friend class ::testing::internal::ExpectationBase;
514 friend class ::testing::internal::UntypedFunctionMockerBase;
515
516 template <typename F>
517 friend class ::testing::internal::FunctionMocker;
518
519 template <typename F>
520 friend class ::testing::internal::TypedExpectation;
521
522 // This comparator is needed for putting Expectation objects into a set.
523 class Less {
524 public:
525 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
526 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
527 }
528 };
529
530 typedef ::std::set<Expectation, Less> Set;
531
532 Expectation(
533 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
534
535 // Returns the expectation this object references.
536 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
537 return expectation_base_;
538 }
539
540 // A shared_ptr that co-owns the expectation this handle references.
541 std::shared_ptr<internal::ExpectationBase> expectation_base_;
542};
543
544// A set of expectation handles. Useful in the .After() clause of
545// EXPECT_CALL() for setting the (partial) order of expectations. The
546// syntax:
547//
548// ExpectationSet es;
549// es += EXPECT_CALL(...)...;
550// es += EXPECT_CALL(...)...;
551// EXPECT_CALL(...).After(es)...;
552//
553// sets three expectations where the last one can only be matched
554// after the first two have both been satisfied.
555//
556// This class is copyable and has value semantics.
557class ExpectationSet {
558 public:
559 // A bidirectional iterator that can read a const element in the set.
560 typedef Expectation::Set::const_iterator const_iterator;
561
562 // An object stored in the set. This is an alias of Expectation.
563 typedef Expectation::Set::value_type value_type;
564
565 // Constructs an empty set.
566 ExpectationSet() {}
567
568 // This single-argument ctor must not be explicit, in order to support the
569 // ExpectationSet es = EXPECT_CALL(...);
570 // syntax.
571 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
572 *this += Expectation(exp);
573 }
574
575 // This single-argument ctor implements implicit conversion from
576 // Expectation and thus must not be explicit. This allows either an
577 // Expectation or an ExpectationSet to be used in .After().
578 ExpectationSet(const Expectation& e) { // NOLINT
579 *this += e;
580 }
581
582 // The compiler-generator ctor and operator= works exactly as
583 // intended, so we don't need to define our own.
584
585 // Returns true if and only if rhs contains the same set of Expectation
586 // objects as this does.
587 bool operator==(const ExpectationSet& rhs) const {
588 return expectations_ == rhs.expectations_;
589 }
590
591 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
592
593 // Implements the syntax
594 // expectation_set += EXPECT_CALL(...);
595 ExpectationSet& operator+=(const Expectation& e) {
596 expectations_.insert(x: e);
597 return *this;
598 }
599
600 int size() const { return static_cast<int>(expectations_.size()); }
601
602 const_iterator begin() const { return expectations_.begin(); }
603 const_iterator end() const { return expectations_.end(); }
604
605 private:
606 Expectation::Set expectations_;
607};
608
609// Sequence objects are used by a user to specify the relative order
610// in which the expectations should match. They are copyable (we rely
611// on the compiler-defined copy constructor and assignment operator).
612class GTEST_API_ Sequence {
613 public:
614 // Constructs an empty sequence.
615 Sequence() : last_expectation_(new Expectation) {}
616
617 // Adds an expectation to this sequence. The caller must ensure
618 // that no other thread is accessing this Sequence object.
619 void AddExpectation(const Expectation& expectation) const;
620
621 private:
622 // The last expectation in this sequence.
623 std::shared_ptr<Expectation> last_expectation_;
624}; // class Sequence
625
626// An object of this type causes all EXPECT_CALL() statements
627// encountered in its scope to be put in an anonymous sequence. The
628// work is done in the constructor and destructor. You should only
629// create an InSequence object on the stack.
630//
631// The sole purpose for this class is to support easy definition of
632// sequential expectations, e.g.
633//
634// {
635// InSequence dummy; // The name of the object doesn't matter.
636//
637// // The following expectations must match in the order they appear.
638// EXPECT_CALL(a, Bar())...;
639// EXPECT_CALL(a, Baz())...;
640// ...
641// EXPECT_CALL(b, Xyz())...;
642// }
643//
644// You can create InSequence objects in multiple threads, as long as
645// they are used to affect different mock objects. The idea is that
646// each thread can create and set up its own mocks as if it's the only
647// thread. However, for clarity of your tests we recommend you to set
648// up mocks in the main thread unless you have a good reason not to do
649// so.
650class GTEST_API_ InSequence {
651 public:
652 InSequence();
653 ~InSequence();
654
655 private:
656 bool sequence_created_;
657
658 InSequence(const InSequence&) = delete;
659 InSequence& operator=(const InSequence&) = delete;
660};
661
662namespace internal {
663
664// Points to the implicit sequence introduced by a living InSequence
665// object (if any) in the current thread or NULL.
666GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
667
668// Base class for implementing expectations.
669//
670// There are two reasons for having a type-agnostic base class for
671// Expectation:
672//
673// 1. We need to store collections of expectations of different
674// types (e.g. all pre-requisites of a particular expectation, all
675// expectations in a sequence). Therefore these expectation objects
676// must share a common base class.
677//
678// 2. We can avoid binary code bloat by moving methods not depending
679// on the template argument of Expectation to the base class.
680//
681// This class is internal and mustn't be used by user code directly.
682class GTEST_API_ ExpectationBase {
683 public:
684 // source_text is the EXPECT_CALL(...) source that created this Expectation.
685 ExpectationBase(const char* file, int line, const std::string& source_text);
686
687 virtual ~ExpectationBase();
688
689 // Where in the source file was the expectation spec defined?
690 const char* file() const { return file_; }
691 int line() const { return line_; }
692 const char* source_text() const { return source_text_.c_str(); }
693 // Returns the cardinality specified in the expectation spec.
694 const Cardinality& cardinality() const { return cardinality_; }
695
696 // Describes the source file location of this expectation.
697 void DescribeLocationTo(::std::ostream* os) const {
698 *os << FormatFileLocation(file: file(), line: line()) << " ";
699 }
700
701 // Describes how many times a function call matching this
702 // expectation has occurred.
703 void DescribeCallCountTo(::std::ostream* os) const
704 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
705
706 // If this mock method has an extra matcher (i.e. .With(matcher)),
707 // describes it to the ostream.
708 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
709
710 // Do not rely on this for correctness.
711 // This is only for making human-readable test output easier to understand.
712 void UntypedDescription(std::string description) {
713 description_ = std::move(description);
714 }
715
716 protected:
717 friend class ::testing::Expectation;
718 friend class UntypedFunctionMockerBase;
719
720 enum Clause {
721 // Don't change the order of the enum members!
722 kNone,
723 kWith,
724 kTimes,
725 kInSequence,
726 kAfter,
727 kWillOnce,
728 kWillRepeatedly,
729 kRetiresOnSaturation
730 };
731
732 typedef std::vector<const void*> UntypedActions;
733
734 // Returns an Expectation object that references and co-owns this
735 // expectation.
736 virtual Expectation GetHandle() = 0;
737
738 // Asserts that the EXPECT_CALL() statement has the given property.
739 void AssertSpecProperty(bool property,
740 const std::string& failure_message) const {
741 Assert(condition: property, file: file_, line: line_, msg: failure_message);
742 }
743
744 // Expects that the EXPECT_CALL() statement has the given property.
745 void ExpectSpecProperty(bool property,
746 const std::string& failure_message) const {
747 Expect(condition: property, file: file_, line: line_, msg: failure_message);
748 }
749
750 // Explicitly specifies the cardinality of this expectation. Used
751 // by the subclasses to implement the .Times() clause.
752 void SpecifyCardinality(const Cardinality& cardinality);
753
754 // Returns true if and only if the user specified the cardinality
755 // explicitly using a .Times().
756 bool cardinality_specified() const { return cardinality_specified_; }
757
758 // Sets the cardinality of this expectation spec.
759 void set_cardinality(const Cardinality& a_cardinality) {
760 cardinality_ = a_cardinality;
761 }
762
763 // The following group of methods should only be called after the
764 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
765 // the current thread.
766
767 // Retires all pre-requisites of this expectation.
768 void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
769
770 // Returns true if and only if this expectation is retired.
771 bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
772 g_gmock_mutex.AssertHeld();
773 return retired_;
774 }
775
776 // Retires this expectation.
777 void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
778 g_gmock_mutex.AssertHeld();
779 retired_ = true;
780 }
781
782 // Returns a human-readable description of this expectation.
783 // Do not rely on this for correctness. It is only for human readability.
784 const std::string& GetDescription() const { return description_; }
785
786 // Returns true if and only if this expectation is satisfied.
787 bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
788 g_gmock_mutex.AssertHeld();
789 return cardinality().IsSatisfiedByCallCount(call_count: call_count_);
790 }
791
792 // Returns true if and only if this expectation is saturated.
793 bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
794 g_gmock_mutex.AssertHeld();
795 return cardinality().IsSaturatedByCallCount(call_count: call_count_);
796 }
797
798 // Returns true if and only if this expectation is over-saturated.
799 bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
800 g_gmock_mutex.AssertHeld();
801 return cardinality().IsOverSaturatedByCallCount(call_count: call_count_);
802 }
803
804 // Returns true if and only if all pre-requisites of this expectation are
805 // satisfied.
806 bool AllPrerequisitesAreSatisfied() const
807 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
808
809 // Adds unsatisfied pre-requisites of this expectation to 'result'.
810 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
811 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
812
813 // Returns the number this expectation has been invoked.
814 int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
815 g_gmock_mutex.AssertHeld();
816 return call_count_;
817 }
818
819 // Increments the number this expectation has been invoked.
820 void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
821 g_gmock_mutex.AssertHeld();
822 call_count_++;
823 }
824
825 // Checks the action count (i.e. the number of WillOnce() and
826 // WillRepeatedly() clauses) against the cardinality if this hasn't
827 // been done before. Prints a warning if there are too many or too
828 // few actions.
829 void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);
830
831 friend class ::testing::Sequence;
832 friend class ::testing::internal::ExpectationTester;
833
834 template <typename Function>
835 friend class TypedExpectation;
836
837 // Implements the .Times() clause.
838 void UntypedTimes(const Cardinality& a_cardinality);
839
840 // This group of fields are part of the spec and won't change after
841 // an EXPECT_CALL() statement finishes.
842 const char* file_; // The file that contains the expectation.
843 int line_; // The line number of the expectation.
844 const std::string source_text_; // The EXPECT_CALL(...) source text.
845 std::string description_; // User-readable name for the expectation.
846 // True if and only if the cardinality is specified explicitly.
847 bool cardinality_specified_;
848 Cardinality cardinality_; // The cardinality of the expectation.
849 // The immediate pre-requisites (i.e. expectations that must be
850 // satisfied before this expectation can be matched) of this
851 // expectation. We use std::shared_ptr in the set because we want an
852 // Expectation object to be co-owned by its FunctionMocker and its
853 // successors. This allows multiple mock objects to be deleted at
854 // different times.
855 ExpectationSet immediate_prerequisites_;
856
857 // This group of fields are the current state of the expectation,
858 // and can change as the mock function is called.
859 int call_count_; // How many times this expectation has been invoked.
860 bool retired_; // True if and only if this expectation has retired.
861 UntypedActions untyped_actions_;
862 bool extra_matcher_specified_;
863 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
864 bool retires_on_saturation_;
865 Clause last_clause_;
866 mutable bool action_count_checked_; // Under mutex_.
867 mutable Mutex mutex_; // Protects action_count_checked_.
868}; // class ExpectationBase
869
870template <typename F>
871class TypedExpectation;
872
873// Implements an expectation for the given function type.
874template <typename R, typename... Args>
875class TypedExpectation<R(Args...)> : public ExpectationBase {
876 private:
877 using F = R(Args...);
878
879 public:
880 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
881 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
882 typedef typename Function<F>::Result Result;
883
884 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
885 const std::string& a_source_text,
886 const ArgumentMatcherTuple& m)
887 : ExpectationBase(a_file, a_line, a_source_text),
888 owner_(owner),
889 matchers_(m),
890 // By default, extra_matcher_ should match anything. However,
891 // we cannot initialize it with _ as that causes ambiguity between
892 // Matcher's copy and move constructor for some argument types.
893 extra_matcher_(A<const ArgumentTuple&>()),
894 repeated_action_(DoDefault()) {}
895
896 ~TypedExpectation() override {
897 // Check the validity of the action count if it hasn't been done
898 // yet (for example, if the expectation was never used).
899 CheckActionCountIfNotDone();
900 for (UntypedActions::const_iterator it = untyped_actions_.begin();
901 it != untyped_actions_.end(); ++it) {
902 delete static_cast<const Action<F>*>(*it);
903 }
904 }
905
906 // Implements the .With() clause.
907 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
908 if (last_clause_ == kWith) {
909 ExpectSpecProperty(property: false,
910 failure_message: ".With() cannot appear "
911 "more than once in an EXPECT_CALL().");
912 } else {
913 ExpectSpecProperty(property: last_clause_ < kWith,
914 failure_message: ".With() must be the first "
915 "clause in an EXPECT_CALL().");
916 }
917 last_clause_ = kWith;
918
919 extra_matcher_ = m;
920 extra_matcher_specified_ = true;
921 return *this;
922 }
923
924 // Do not rely on this for correctness.
925 // This is only for making human-readable test output easier to understand.
926 TypedExpectation& Description(std::string name) {
927 ExpectationBase::UntypedDescription(description: std::move(name));
928 return *this;
929 }
930
931 // Implements the .Times() clause.
932 TypedExpectation& Times(const Cardinality& a_cardinality) {
933 ExpectationBase::UntypedTimes(a_cardinality);
934 return *this;
935 }
936
937 // Implements the .Times() clause.
938 TypedExpectation& Times(int n) { return Times(Exactly(n)); }
939
940 // Implements the .InSequence() clause.
941 TypedExpectation& InSequence(const Sequence& s) {
942 ExpectSpecProperty(property: last_clause_ <= kInSequence,
943 failure_message: ".InSequence() cannot appear after .After(),"
944 " .WillOnce(), .WillRepeatedly(), or "
945 ".RetiresOnSaturation().");
946 last_clause_ = kInSequence;
947
948 s.AddExpectation(expectation: GetHandle());
949 return *this;
950 }
951 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
952 return InSequence(s1).InSequence(s2);
953 }
954 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
955 const Sequence& s3) {
956 return InSequence(s1, s2).InSequence(s3);
957 }
958 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
959 const Sequence& s3, const Sequence& s4) {
960 return InSequence(s1, s2, s3).InSequence(s4);
961 }
962 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
963 const Sequence& s3, const Sequence& s4,
964 const Sequence& s5) {
965 return InSequence(s1, s2, s3, s4).InSequence(s5);
966 }
967
968 // Implements that .After() clause.
969 TypedExpectation& After(const ExpectationSet& s) {
970 ExpectSpecProperty(property: last_clause_ <= kAfter,
971 failure_message: ".After() cannot appear after .WillOnce(),"
972 " .WillRepeatedly(), or "
973 ".RetiresOnSaturation().");
974 last_clause_ = kAfter;
975
976 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
977 immediate_prerequisites_ += *it;
978 }
979 return *this;
980 }
981 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
982 return After(s1).After(s2);
983 }
984 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
985 const ExpectationSet& s3) {
986 return After(s1, s2).After(s3);
987 }
988 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
989 const ExpectationSet& s3, const ExpectationSet& s4) {
990 return After(s1, s2, s3).After(s4);
991 }
992 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
993 const ExpectationSet& s3, const ExpectationSet& s4,
994 const ExpectationSet& s5) {
995 return After(s1, s2, s3, s4).After(s5);
996 }
997
998 // Preferred, type-safe overload: consume anything that can be directly
999 // converted to a OnceAction, except for Action<F> objects themselves.
1000 TypedExpectation& WillOnce(OnceAction<F> once_action) {
1001 // Call the overload below, smuggling the OnceAction as a copyable callable.
1002 // We know this is safe because a WillOnce action will not be called more
1003 // than once.
1004 return WillOnce(Action<F>(ActionAdaptor{
1005 std::make_shared<OnceAction<F>>(std::move(once_action)),
1006 }));
1007 }
1008
1009 // Fallback overload: accept Action<F> objects and those actions that define
1010 // `operator Action<F>` but not `operator OnceAction<F>`.
1011 //
1012 // This is templated in order to cause the overload above to be preferred
1013 // when the input is convertible to either type.
1014 template <int&... ExplicitArgumentBarrier, typename = void>
1015 TypedExpectation& WillOnce(Action<F> action) {
1016 ExpectSpecProperty(property: last_clause_ <= kWillOnce,
1017 failure_message: ".WillOnce() cannot appear after "
1018 ".WillRepeatedly() or .RetiresOnSaturation().");
1019 last_clause_ = kWillOnce;
1020
1021 untyped_actions_.push_back(new Action<F>(std::move(action)));
1022
1023 if (!cardinality_specified()) {
1024 set_cardinality(Exactly(n: static_cast<int>(untyped_actions_.size())));
1025 }
1026 return *this;
1027 }
1028
1029 // Implements the .WillRepeatedly() clause.
1030 TypedExpectation& WillRepeatedly(const Action<F>& action) {
1031 if (last_clause_ == kWillRepeatedly) {
1032 ExpectSpecProperty(property: false,
1033 failure_message: ".WillRepeatedly() cannot appear "
1034 "more than once in an EXPECT_CALL().");
1035 } else {
1036 ExpectSpecProperty(property: last_clause_ < kWillRepeatedly,
1037 failure_message: ".WillRepeatedly() cannot appear "
1038 "after .RetiresOnSaturation().");
1039 }
1040 last_clause_ = kWillRepeatedly;
1041 repeated_action_specified_ = true;
1042
1043 repeated_action_ = action;
1044 if (!cardinality_specified()) {
1045 set_cardinality(AtLeast(n: static_cast<int>(untyped_actions_.size())));
1046 }
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 // Implements the .RetiresOnSaturation() clause.
1055 TypedExpectation& RetiresOnSaturation() {
1056 ExpectSpecProperty(property: last_clause_ < kRetiresOnSaturation,
1057 failure_message: ".RetiresOnSaturation() cannot appear "
1058 "more than once.");
1059 last_clause_ = kRetiresOnSaturation;
1060 retires_on_saturation_ = true;
1061
1062 // Now that no more action clauses can be specified, we check
1063 // whether their count makes sense.
1064 CheckActionCountIfNotDone();
1065 return *this;
1066 }
1067
1068 // Returns the matchers for the arguments as specified inside the
1069 // EXPECT_CALL() macro.
1070 const ArgumentMatcherTuple& matchers() const { return matchers_; }
1071
1072 // Returns the matcher specified by the .With() clause.
1073 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1074 return extra_matcher_;
1075 }
1076
1077 // Returns the action specified by the .WillRepeatedly() clause.
1078 const Action<F>& repeated_action() const { return repeated_action_; }
1079
1080 // If this mock method has an extra matcher (i.e. .With(matcher)),
1081 // describes it to the ostream.
1082 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
1083 if (extra_matcher_specified_) {
1084 *os << " Expected args: ";
1085 extra_matcher_.DescribeTo(os);
1086 *os << "\n";
1087 }
1088 }
1089
1090 private:
1091 template <typename Function>
1092 friend class FunctionMocker;
1093
1094 // An adaptor that turns a OneAction<F> into something compatible with
1095 // Action<F>. Must be called at most once.
1096 struct ActionAdaptor {
1097 std::shared_ptr<OnceAction<R(Args...)>> once_action;
1098
1099 R operator()(Args&&... args) const {
1100 return std::move(*once_action).Call(std::forward<Args>(args)...);
1101 }
1102 };
1103
1104 // Returns an Expectation object that references and co-owns this
1105 // expectation.
1106 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
1107
1108 // The following methods will be called only after the EXPECT_CALL()
1109 // statement finishes and when the current thread holds
1110 // g_gmock_mutex.
1111
1112 // Returns true if and only if this expectation matches the given arguments.
1113 bool Matches(const ArgumentTuple& args) const
1114 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1115 g_gmock_mutex.AssertHeld();
1116 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1117 }
1118
1119 // Returns true if and only if this expectation should handle the given
1120 // arguments.
1121 bool ShouldHandleArguments(const ArgumentTuple& args) const
1122 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1123 g_gmock_mutex.AssertHeld();
1124
1125 // In case the action count wasn't checked when the expectation
1126 // was defined (e.g. if this expectation has no WillRepeatedly()
1127 // or RetiresOnSaturation() clause), we check it when the
1128 // expectation is used for the first time.
1129 CheckActionCountIfNotDone();
1130 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1131 }
1132
1133 // Describes the result of matching the arguments against this
1134 // expectation to the given ostream.
1135 void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const
1136 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1137 g_gmock_mutex.AssertHeld();
1138
1139 if (is_retired()) {
1140 *os << " Expected: the expectation is active\n"
1141 << " Actual: it is retired\n";
1142 } else if (!Matches(args)) {
1143 if (!TupleMatches(matchers_, args)) {
1144 ExplainMatchFailureTupleTo(matchers_, args, os);
1145 }
1146 StringMatchResultListener listener;
1147 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1148 *os << " Expected args: ";
1149 extra_matcher_.DescribeTo(os);
1150 *os << "\n Actual: don't match";
1151
1152 internal::PrintIfNotEmpty(explanation: listener.str(), os);
1153 *os << "\n";
1154 }
1155 } else if (!AllPrerequisitesAreSatisfied()) {
1156 *os << " Expected: all pre-requisites are satisfied\n"
1157 << " Actual: the following immediate pre-requisites "
1158 << "are not satisfied:\n";
1159 ExpectationSet unsatisfied_prereqs;
1160 FindUnsatisfiedPrerequisites(result: &unsatisfied_prereqs);
1161 int i = 0;
1162 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1163 it != unsatisfied_prereqs.end(); ++it) {
1164 it->expectation_base()->DescribeLocationTo(os);
1165 *os << "pre-requisite #" << i++ << "\n";
1166 }
1167 *os << " (end of pre-requisites)\n";
1168 } else {
1169 // This line is here just for completeness' sake. It will never
1170 // be executed as currently the ExplainMatchResultTo() function
1171 // is called only when the mock function call does NOT match the
1172 // expectation.
1173 *os << "The call matches the expectation.\n";
1174 }
1175 }
1176
1177 // Returns the action that should be taken for the current invocation.
1178 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
1179 const ArgumentTuple& args) const
1180 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1181 g_gmock_mutex.AssertHeld();
1182 const int count = call_count();
1183 Assert(condition: count >= 1, __FILE__, __LINE__,
1184 msg: "call_count() is <= 0 when GetCurrentAction() is "
1185 "called - this should never happen.");
1186
1187 const int action_count = static_cast<int>(untyped_actions_.size());
1188 if (action_count > 0 && !repeated_action_specified_ &&
1189 count > action_count) {
1190 // If there is at least one WillOnce() and no WillRepeatedly(),
1191 // we warn the user when the WillOnce() clauses ran out.
1192 ::std::stringstream ss;
1193 DescribeLocationTo(os: &ss);
1194 ss << "Actions ran out in " << source_text() << "...\n"
1195 << "Called " << count << " times, but only " << action_count
1196 << " WillOnce()" << (action_count == 1 ? " is" : "s are")
1197 << " specified - ";
1198 mocker->DescribeDefaultActionTo(args, &ss);
1199 Log(severity: kWarning, message: ss.str(), stack_frames_to_skip: 1);
1200 }
1201
1202 return count <= action_count
1203 ? *static_cast<const Action<F>*>(
1204 untyped_actions_[static_cast<size_t>(count - 1)])
1205 : repeated_action();
1206 }
1207
1208 // Given the arguments of a mock function call, if the call will
1209 // over-saturate this expectation, returns the default action;
1210 // otherwise, returns the next action in this expectation. Also
1211 // describes *what* happened to 'what', and explains *why* Google
1212 // Mock does it to 'why'. This method is not const as it calls
1213 // IncrementCallCount(). A return value of NULL means the default
1214 // action.
1215 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
1216 const ArgumentTuple& args,
1217 ::std::ostream* what,
1218 ::std::ostream* why)
1219 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1220 g_gmock_mutex.AssertHeld();
1221 const ::std::string& expectation_description = GetDescription();
1222 if (IsSaturated()) {
1223 // We have an excessive call.
1224 IncrementCallCount();
1225 *what << "Mock function ";
1226 if (!expectation_description.empty()) {
1227 *what << "\"" << expectation_description << "\" ";
1228 }
1229 *what << "called more times than expected - ";
1230 mocker->DescribeDefaultActionTo(args, what);
1231 DescribeCallCountTo(os: why);
1232
1233 return nullptr;
1234 }
1235
1236 IncrementCallCount();
1237 RetireAllPreRequisites();
1238
1239 if (retires_on_saturation_ && IsSaturated()) {
1240 Retire();
1241 }
1242
1243 // Must be done after IncrementCount()!
1244 *what << "Mock function ";
1245 if (!expectation_description.empty()) {
1246 *what << "\"" << expectation_description << "\" ";
1247 }
1248 *what << "call matches " << source_text() << "...\n";
1249 return &(GetCurrentAction(mocker, args));
1250 }
1251
1252 // All the fields below won't change once the EXPECT_CALL()
1253 // statement finishes.
1254 FunctionMocker<F>* const owner_;
1255 ArgumentMatcherTuple matchers_;
1256 Matcher<const ArgumentTuple&> extra_matcher_;
1257 Action<F> repeated_action_;
1258
1259 TypedExpectation(const TypedExpectation&) = delete;
1260 TypedExpectation& operator=(const TypedExpectation&) = delete;
1261}; // class TypedExpectation
1262
1263// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1264// specifying the default behavior of, or expectation on, a mock
1265// function.
1266
1267// Note: class MockSpec really belongs to the ::testing namespace.
1268// However if we define it in ::testing, MSVC will complain when
1269// classes in ::testing::internal declare it as a friend class
1270// template. To workaround this compiler bug, we define MockSpec in
1271// ::testing::internal and import it into ::testing.
1272
1273// Logs a message including file and line number information.
1274GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1275 const char* file, int line,
1276 const std::string& message);
1277
1278template <typename F>
1279class MockSpec {
1280 public:
1281 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1282 typedef
1283 typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1284
1285 // Constructs a MockSpec object, given the function mocker object
1286 // that the spec is associated with.
1287 MockSpec(internal::FunctionMocker<F>* function_mocker,
1288 const ArgumentMatcherTuple& matchers)
1289 : function_mocker_(function_mocker), matchers_(matchers) {}
1290
1291 // Adds a new default action spec to the function mocker and returns
1292 // the newly created spec.
1293 internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,
1294 int line, const char* obj,
1295 const char* call) {
1296 LogWithLocation(severity: internal::kInfo, file, line,
1297 message: std::string("ON_CALL(") + obj + ", " + call + ") invoked");
1298 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1299 }
1300
1301 // Adds a new expectation spec to the function mocker and returns
1302 // the newly created spec.
1303 internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,
1304 const char* obj,
1305 const char* call) {
1306 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1307 call + ")");
1308 LogWithLocation(severity: internal::kInfo, file, line, message: source_text + " invoked");
1309 return function_mocker_->AddNewExpectation(file, line, source_text,
1310 matchers_);
1311 }
1312
1313 // This operator overload is used to swallow the superfluous parameter list
1314 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1315 // explanation.
1316 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1317 return *this;
1318 }
1319
1320 private:
1321 template <typename Function>
1322 friend class internal::FunctionMocker;
1323
1324 // The function mocker that owns this spec.
1325 internal::FunctionMocker<F>* const function_mocker_;
1326 // The argument matchers specified in the spec.
1327 ArgumentMatcherTuple matchers_;
1328}; // class MockSpec
1329
1330// Wrapper type for generically holding an ordinary value or lvalue reference.
1331// If T is not a reference type, it must be copyable or movable.
1332// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1333// T is a move-only value type (which means that it will always be copyable
1334// if the current platform does not support move semantics).
1335//
1336// The primary template defines handling for values, but function header
1337// comments describe the contract for the whole template (including
1338// specializations).
1339template <typename T>
1340class ReferenceOrValueWrapper {
1341 public:
1342 // Constructs a wrapper from the given value/reference.
1343 explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
1344
1345 // Unwraps and returns the underlying value/reference, exactly as
1346 // originally passed. The behavior of calling this more than once on
1347 // the same object is unspecified.
1348 T Unwrap() { return std::move(value_); }
1349
1350 // Provides nondestructive access to the underlying value/reference.
1351 // Always returns a const reference (more precisely,
1352 // const std::add_lvalue_reference<T>::type). The behavior of calling this
1353 // after calling Unwrap on the same object is unspecified.
1354 const T& Peek() const { return value_; }
1355
1356 private:
1357 T value_;
1358};
1359
1360// Specialization for lvalue reference types. See primary template
1361// for documentation.
1362template <typename T>
1363class ReferenceOrValueWrapper<T&> {
1364 public:
1365 // Workaround for debatable pass-by-reference lint warning (c-library-team
1366 // policy precludes NOLINT in this context)
1367 typedef T& reference;
1368 explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
1369 T& Unwrap() { return *value_ptr_; }
1370 const T& Peek() const { return *value_ptr_; }
1371
1372 private:
1373 T* value_ptr_;
1374};
1375
1376// Prints the held value as an action's result to os.
1377template <typename T>
1378void PrintAsActionResult(const T& result, std::ostream& os) {
1379 os << "\n Returns: ";
1380 // T may be a reference type, so we don't use UniversalPrint().
1381 UniversalPrinter<T>::Print(result, &os);
1382}
1383
1384// Reports an uninteresting call (whose description is in msg) in the
1385// manner specified by 'reaction'.
1386GTEST_API_ void ReportUninterestingCall(CallReaction reaction,
1387 const std::string& msg);
1388
1389// A generic RAII type that runs a user-provided function in its destructor.
1390class Cleanup final {
1391 public:
1392 explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}
1393 ~Cleanup() { f_(); }
1394
1395 private:
1396 std::function<void()> f_;
1397};
1398
1399template <typename F>
1400class FunctionMocker;
1401
1402template <typename R, typename... Args>
1403class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
1404 using F = R(Args...);
1405
1406 public:
1407 using Result = R;
1408 using ArgumentTuple = std::tuple<Args...>;
1409 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1410
1411 FunctionMocker() {}
1412
1413 // There is no generally useful and implementable semantics of
1414 // copying a mock object, so copying a mock is usually a user error.
1415 // Thus we disallow copying function mockers. If the user really
1416 // wants to copy a mock object, they should implement their own copy
1417 // operation, for example:
1418 //
1419 // class MockFoo : public Foo {
1420 // public:
1421 // // Defines a copy constructor explicitly.
1422 // MockFoo(const MockFoo& src) {}
1423 // ...
1424 // };
1425 FunctionMocker(const FunctionMocker&) = delete;
1426 FunctionMocker& operator=(const FunctionMocker&) = delete;
1427
1428 // The destructor verifies that all expectations on this mock
1429 // function have been satisfied. If not, it will report Google Test
1430 // non-fatal failures for the violations.
1431 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1432 MutexLock l(&g_gmock_mutex);
1433 VerifyAndClearExpectationsLocked();
1434 Mock::UnregisterLocked(mocker: this);
1435 ClearDefaultActionsLocked();
1436 }
1437
1438 // Returns the ON_CALL spec that matches this mock function with the
1439 // given arguments; returns NULL if no matching ON_CALL is found.
1440 // L = *
1441 const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {
1442 for (UntypedOnCallSpecs::const_reverse_iterator it =
1443 untyped_on_call_specs_.rbegin();
1444 it != untyped_on_call_specs_.rend(); ++it) {
1445 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1446 if (spec->Matches(args)) return spec;
1447 }
1448
1449 return nullptr;
1450 }
1451
1452 // Performs the default action of this mock function on the given
1453 // arguments and returns the result. Asserts (or throws if
1454 // exceptions are enabled) with a helpful call description if there
1455 // is no valid return value. This method doesn't depend on the
1456 // mutable state of this object, and thus can be called concurrently
1457 // without locking.
1458 // L = *
1459 Result PerformDefaultAction(ArgumentTuple&& args,
1460 const std::string& call_description) const {
1461 const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);
1462 if (spec != nullptr) {
1463 return spec->GetAction().Perform(std::move(args));
1464 }
1465 const std::string message =
1466 call_description +
1467 "\n The mock function has no default action "
1468 "set, and its return type has no default value set.";
1469#if GTEST_HAS_EXCEPTIONS
1470 if (!DefaultValue<Result>::Exists()) {
1471 throw std::runtime_error(message);
1472 }
1473#else
1474 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1475#endif
1476 return DefaultValue<Result>::Get();
1477 }
1478
1479 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1480 // clears the ON_CALL()s set on this mock function.
1481 void ClearDefaultActionsLocked() override
1482 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1483 g_gmock_mutex.AssertHeld();
1484
1485 // Deleting our default actions may trigger other mock objects to be
1486 // deleted, for example if an action contains a reference counted smart
1487 // pointer to that mock object, and that is the last reference. So if we
1488 // delete our actions within the context of the global mutex we may deadlock
1489 // when this method is called again. Instead, make a copy of the set of
1490 // actions to delete, clear our set within the mutex, and then delete the
1491 // actions outside of the mutex.
1492 UntypedOnCallSpecs specs_to_delete;
1493 untyped_on_call_specs_.swap(x&: specs_to_delete);
1494
1495 g_gmock_mutex.Unlock();
1496 for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
1497 it != specs_to_delete.end(); ++it) {
1498 delete static_cast<const OnCallSpec<F>*>(*it);
1499 }
1500
1501 // Lock the mutex again, since the caller expects it to be locked when we
1502 // return.
1503 g_gmock_mutex.Lock();
1504 }
1505
1506 // Returns the result of invoking this mock function with the given
1507 // arguments. This function can be safely called from multiple
1508 // threads concurrently.
1509 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1510 return InvokeWith(args: ArgumentTuple(std::forward<Args>(args)...));
1511 }
1512
1513 MockSpec<F> With(Matcher<Args>... m) {
1514 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
1515 }
1516
1517 protected:
1518 template <typename Function>
1519 friend class MockSpec;
1520
1521 // Adds and returns a default action spec for this mock function.
1522 OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
1523 const ArgumentMatcherTuple& m)
1524 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1525 Mock::RegisterUseByOnCallOrExpectCall(mock_obj: MockObject(), file, line);
1526 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1527 untyped_on_call_specs_.push_back(on_call_spec);
1528 return *on_call_spec;
1529 }
1530
1531 // Adds and returns an expectation spec for this mock function.
1532 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1533 const std::string& source_text,
1534 const ArgumentMatcherTuple& m)
1535 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1536 Mock::RegisterUseByOnCallOrExpectCall(mock_obj: MockObject(), file, line);
1537 TypedExpectation<F>* const expectation =
1538 new TypedExpectation<F>(this, file, line, source_text, m);
1539 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1540 // See the definition of untyped_expectations_ for why access to
1541 // it is unprotected here.
1542 untyped_expectations_.push_back(untyped_expectation);
1543
1544 // Adds this expectation into the implicit sequence if there is one.
1545 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1546 if (implicit_sequence != nullptr) {
1547 implicit_sequence->AddExpectation(expectation: Expectation(untyped_expectation));
1548 }
1549
1550 return *expectation;
1551 }
1552
1553 private:
1554 template <typename Func>
1555 friend class TypedExpectation;
1556
1557 // Some utilities needed for implementing UntypedInvokeWith().
1558
1559 // Describes what default action will be performed for the given
1560 // arguments.
1561 // L = *
1562 void DescribeDefaultActionTo(const ArgumentTuple& args,
1563 ::std::ostream* os) const {
1564 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1565
1566 if (spec == nullptr) {
1567 *os << (std::is_void<Result>::value ? "returning directly.\n"
1568 : "returning default value.\n");
1569 } else {
1570 *os << "taking default action specified at:\n"
1571 << FormatFileLocation(spec->file(), spec->line()) << "\n";
1572 }
1573 }
1574
1575 // Writes a message that the call is uninteresting (i.e. neither
1576 // explicitly expected nor explicitly unexpected) to the given
1577 // ostream.
1578 void UntypedDescribeUninterestingCall(const void* untyped_args,
1579 ::std::ostream* os) const override
1580 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1581 const ArgumentTuple& args =
1582 *static_cast<const ArgumentTuple*>(untyped_args);
1583 *os << "Uninteresting mock function call - ";
1584 DescribeDefaultActionTo(args, os);
1585 *os << " Function call: " << Name();
1586 UniversalPrint(args, os);
1587 }
1588
1589 // Returns the expectation that matches the given function arguments
1590 // (or NULL is there's no match); when a match is found,
1591 // untyped_action is set to point to the action that should be
1592 // performed (or NULL if the action is "do default"), and
1593 // is_excessive is modified to indicate whether the call exceeds the
1594 // expected number.
1595 //
1596 // Critical section: We must find the matching expectation and the
1597 // corresponding action that needs to be taken in an ATOMIC
1598 // transaction. Otherwise another thread may call this mock
1599 // method in the middle and mess up the state.
1600 //
1601 // However, performing the action has to be left out of the critical
1602 // section. The reason is that we have no control on what the
1603 // action does (it can invoke an arbitrary user function or even a
1604 // mock function) and excessive locking could cause a dead lock.
1605 const ExpectationBase* UntypedFindMatchingExpectation(
1606 const void* untyped_args, const void** untyped_action, bool* is_excessive,
1607 ::std::ostream* what, ::std::ostream* why) override
1608 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1609 const ArgumentTuple& args =
1610 *static_cast<const ArgumentTuple*>(untyped_args);
1611 MutexLock l(&g_gmock_mutex);
1612 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1613 if (exp == nullptr) { // A match wasn't found.
1614 this->FormatUnexpectedCallMessageLocked(args, what, why);
1615 return nullptr;
1616 }
1617
1618 // This line must be done before calling GetActionForArguments(),
1619 // which will increment the call count for *exp and thus affect
1620 // its saturation status.
1621 *is_excessive = exp->IsSaturated();
1622 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1623 if (action != nullptr && action->IsDoDefault())
1624 action = nullptr; // Normalize "do default" to NULL.
1625 *untyped_action = action;
1626 return exp;
1627 }
1628
1629 // Prints the given function arguments to the ostream.
1630 void UntypedPrintArgs(const void* untyped_args,
1631 ::std::ostream* os) const override {
1632 const ArgumentTuple& args =
1633 *static_cast<const ArgumentTuple*>(untyped_args);
1634 UniversalPrint(args, os);
1635 }
1636
1637 // Returns the expectation that matches the arguments, or NULL if no
1638 // expectation matches them.
1639 TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)
1640 const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1641 g_gmock_mutex.AssertHeld();
1642 // See the definition of untyped_expectations_ for why access to
1643 // it is unprotected here.
1644 for (typename UntypedExpectations::const_reverse_iterator it =
1645 untyped_expectations_.rbegin();
1646 it != untyped_expectations_.rend(); ++it) {
1647 TypedExpectation<F>* const exp =
1648 static_cast<TypedExpectation<F>*>(it->get());
1649 if (exp->ShouldHandleArguments(args)) {
1650 return exp;
1651 }
1652 }
1653 return nullptr;
1654 }
1655
1656 // Returns a message that the arguments don't match any expectation.
1657 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1658 ::std::ostream* os,
1659 ::std::ostream* why) const
1660 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1661 g_gmock_mutex.AssertHeld();
1662 *os << "\nUnexpected mock function call - ";
1663 DescribeDefaultActionTo(args, os);
1664 PrintTriedExpectationsLocked(args, why);
1665 }
1666
1667 // Prints a list of expectations that have been tried against the
1668 // current mock function call.
1669 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1670 ::std::ostream* why) const
1671 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1672 g_gmock_mutex.AssertHeld();
1673 const size_t count = untyped_expectations_.size();
1674 *why << "Google Mock tried the following " << count << " "
1675 << (count == 1 ? "expectation, but it didn't match"
1676 : "expectations, but none matched")
1677 << ":\n";
1678 for (size_t i = 0; i < count; i++) {
1679 TypedExpectation<F>* const expectation =
1680 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1681 *why << "\n";
1682 expectation->DescribeLocationTo(why);
1683 if (count > 1) {
1684 *why << "tried expectation #" << i << ": ";
1685 }
1686 *why << expectation->source_text() << "...\n";
1687 expectation->ExplainMatchResultTo(args, why);
1688 expectation->DescribeCallCountTo(why);
1689 }
1690 }
1691
1692 // Performs the given action (or the default if it's null) with the given
1693 // arguments and returns the action's result.
1694 // L = *
1695 R PerformAction(const void* untyped_action, ArgumentTuple&& args,
1696 const std::string& call_description) const {
1697 if (untyped_action == nullptr) {
1698 return PerformDefaultAction(args: std::move(args), call_description);
1699 }
1700
1701 // Make a copy of the action before performing it, in case the
1702 // action deletes the mock object (and thus deletes itself).
1703 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1704 return action.Perform(std::move(args));
1705 }
1706
1707 // Is it possible to store an object of the supplied type in a local variable
1708 // for the sake of printing it, then return it on to the caller?
1709 template <typename T>
1710 using can_print_result = internal::conjunction<
1711 // void can't be stored as an object (and we also don't need to print it).
1712 internal::negation<std::is_void<T>>,
1713 // Non-moveable types can't be returned on to the user, so there's no way
1714 // for us to intercept and print them.
1715 std::is_move_constructible<T>>;
1716
1717 // Perform the supplied action, printing the result to os.
1718 template <typename T = R,
1719 typename std::enable_if<can_print_result<T>::value, int>::type = 0>
1720 R PerformActionAndPrintResult(const void* const untyped_action,
1721 ArgumentTuple&& args,
1722 const std::string& call_description,
1723 std::ostream& os) {
1724 R result = PerformAction(untyped_action, args: std::move(args), call_description);
1725
1726 PrintAsActionResult(result, os);
1727 return std::forward<R>(result);
1728 }
1729
1730 // An overload for when it's not possible to print the result. In this case we
1731 // simply perform the action.
1732 template <typename T = R,
1733 typename std::enable_if<
1734 internal::negation<can_print_result<T>>::value, int>::type = 0>
1735 R PerformActionAndPrintResult(const void* const untyped_action,
1736 ArgumentTuple&& args,
1737 const std::string& call_description,
1738 std::ostream&) {
1739 return PerformAction(untyped_action, args: std::move(args), call_description);
1740 }
1741
1742 // Returns the result of invoking this mock function with the given
1743 // arguments. This function can be safely called from multiple
1744 // threads concurrently.
1745 R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
1746}; // class FunctionMocker
1747
1748// Calculates the result of invoking this mock function with the given
1749// arguments, prints it, and returns it.
1750template <typename R, typename... Args>
1751R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
1752 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1753 // See the definition of untyped_expectations_ for why access to it
1754 // is unprotected here.
1755 if (untyped_expectations_.size() == 0) {
1756 // No expectation is set on this mock method - we have an
1757 // uninteresting call.
1758
1759 // We must get Google Mock's reaction on uninteresting calls
1760 // made on this mock object BEFORE performing the action,
1761 // because the action may DELETE the mock object and make the
1762 // following expression meaningless.
1763 const CallReaction reaction =
1764 Mock::GetReactionOnUninterestingCalls(mock_obj: MockObject());
1765
1766 // True if and only if we need to print this call's arguments and return
1767 // value. This definition must be kept in sync with
1768 // the behavior of ReportUninterestingCall().
1769 const bool need_to_report_uninteresting_call =
1770 // If the user allows this uninteresting call, we print it
1771 // only when they want informational messages.
1772 reaction == kAllow ? LogIsVisible(severity: kInfo) :
1773 // If the user wants this to be a warning, we print
1774 // it only when they want to see warnings.
1775 reaction == kWarn
1776 ? LogIsVisible(severity: kWarning)
1777 :
1778 // Otherwise, the user wants this to be an error, and we
1779 // should always print detailed information in the error.
1780 true;
1781
1782 if (!need_to_report_uninteresting_call) {
1783 // Perform the action without printing the call information.
1784 return this->PerformDefaultAction(
1785 std::move(args), "Function call: " + std::string(Name()));
1786 }
1787
1788 // Warns about the uninteresting call.
1789 ::std::stringstream ss;
1790 this->UntypedDescribeUninterestingCall(&args, &ss);
1791
1792 // Perform the action, print the result, and then report the uninteresting
1793 // call.
1794 //
1795 // We use RAII to do the latter in case R is void or a non-moveable type. In
1796 // either case we can't assign it to a local variable.
1797 const Cleanup report_uninteresting_call(
1798 [&] { ReportUninterestingCall(reaction, msg: ss.str()); });
1799
1800 return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
1801 }
1802
1803 bool is_excessive = false;
1804 ::std::stringstream ss;
1805 ::std::stringstream why;
1806 ::std::stringstream loc;
1807 const void* untyped_action = nullptr;
1808
1809 // The UntypedFindMatchingExpectation() function acquires and
1810 // releases g_gmock_mutex.
1811
1812 const ExpectationBase* const untyped_expectation =
1813 this->UntypedFindMatchingExpectation(&args, &untyped_action,
1814 &is_excessive, &ss, &why);
1815 const bool found = untyped_expectation != nullptr;
1816
1817 // True if and only if we need to print the call's arguments
1818 // and return value.
1819 // This definition must be kept in sync with the uses of Expect()
1820 // and Log() in this function.
1821 const bool need_to_report_call =
1822 !found || is_excessive || LogIsVisible(severity: kInfo);
1823 if (!need_to_report_call) {
1824 // Perform the action without printing the call information.
1825 return PerformAction(untyped_action, args: std::move(args), call_description: "");
1826 }
1827
1828 ss << " Function call: " << Name();
1829 this->UntypedPrintArgs(&args, &ss);
1830
1831 // In case the action deletes a piece of the expectation, we
1832 // generate the message beforehand.
1833 if (found && !is_excessive) {
1834 untyped_expectation->DescribeLocationTo(os: &loc);
1835 }
1836
1837 // Perform the action, print the result, and then fail or log in whatever way
1838 // is appropriate.
1839 //
1840 // We use RAII to do the latter in case R is void or a non-moveable type. In
1841 // either case we can't assign it to a local variable.
1842 const Cleanup handle_failures([&] {
1843 ss << "\n" << why.str();
1844
1845 if (!found) {
1846 // No expectation matches this call - reports a failure.
1847 Expect(condition: false, file: nullptr, line: -1, msg: ss.str());
1848 } else if (is_excessive) {
1849 // We had an upper-bound violation and the failure message is in ss.
1850 Expect(condition: false, file: untyped_expectation->file(), line: untyped_expectation->line(),
1851 msg: ss.str());
1852 } else {
1853 // We had an expected call and the matching expectation is
1854 // described in ss.
1855 Log(severity: kInfo, message: loc.str() + ss.str(), stack_frames_to_skip: 2);
1856 }
1857 });
1858
1859 return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
1860 ss);
1861}
1862
1863} // namespace internal
1864
1865namespace internal {
1866
1867template <typename F>
1868class MockFunction;
1869
1870template <typename R, typename... Args>
1871class MockFunction<R(Args...)> {
1872 public:
1873 MockFunction(const MockFunction&) = delete;
1874 MockFunction& operator=(const MockFunction&) = delete;
1875
1876 std::function<R(Args...)> AsStdFunction() {
1877 return [this](Args... args) -> R {
1878 return this->Call(std::forward<Args>(args)...);
1879 };
1880 }
1881
1882 // Implementation detail: the expansion of the MOCK_METHOD macro.
1883 R Call(Args... args) {
1884 mock_.SetOwnerAndName(this, "Call");
1885 return mock_.Invoke(std::forward<Args>(args)...);
1886 }
1887
1888 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1889 mock_.RegisterOwner(this);
1890 return mock_.With(std::move(m)...);
1891 }
1892
1893 MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
1894 return this->gmock_Call(::testing::A<Args>()...);
1895 }
1896
1897 protected:
1898 MockFunction() = default;
1899 ~MockFunction() = default;
1900
1901 private:
1902 FunctionMocker<R(Args...)> mock_;
1903};
1904
1905/*
1906The SignatureOf<F> struct is a meta-function returning function signature
1907corresponding to the provided F argument.
1908
1909It makes use of MockFunction easier by allowing it to accept more F arguments
1910than just function signatures.
1911
1912Specializations provided here cover a signature type itself and any template
1913that can be parameterized with a signature, including std::function and
1914boost::function.
1915*/
1916
1917template <typename F, typename = void>
1918struct SignatureOf;
1919
1920template <typename R, typename... Args>
1921struct SignatureOf<R(Args...)> {
1922 using type = R(Args...);
1923};
1924
1925template <template <typename> class C, typename F>
1926struct SignatureOf<C<F>,
1927 typename std::enable_if<std::is_function<F>::value>::type>
1928 : SignatureOf<F> {};
1929
1930template <typename F>
1931using SignatureOfT = typename SignatureOf<F>::type;
1932
1933} // namespace internal
1934
1935// A MockFunction<F> type has one mock method whose type is
1936// internal::SignatureOfT<F>. It is useful when you just want your
1937// test code to emit some messages and have Google Mock verify the
1938// right messages are sent (and perhaps at the right times). For
1939// example, if you are exercising code:
1940//
1941// Foo(1);
1942// Foo(2);
1943// Foo(3);
1944//
1945// and want to verify that Foo(1) and Foo(3) both invoke
1946// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1947//
1948// TEST(FooTest, InvokesBarCorrectly) {
1949// MyMock mock;
1950// MockFunction<void(string check_point_name)> check;
1951// {
1952// InSequence s;
1953//
1954// EXPECT_CALL(mock, Bar("a"));
1955// EXPECT_CALL(check, Call("1"));
1956// EXPECT_CALL(check, Call("2"));
1957// EXPECT_CALL(mock, Bar("a"));
1958// }
1959// Foo(1);
1960// check.Call("1");
1961// Foo(2);
1962// check.Call("2");
1963// Foo(3);
1964// }
1965//
1966// The expectation spec says that the first Bar("a") must happen
1967// before check point "1", the second Bar("a") must happen after check
1968// point "2", and nothing should happen between the two check
1969// points. The explicit check points make it easy to tell which
1970// Bar("a") is called by which call to Foo().
1971//
1972// MockFunction<F> can also be used to exercise code that accepts
1973// std::function<internal::SignatureOfT<F>> callbacks. To do so, use
1974// AsStdFunction() method to create std::function proxy forwarding to
1975// original object's Call. Example:
1976//
1977// TEST(FooTest, RunsCallbackWithBarArgument) {
1978// MockFunction<int(string)> callback;
1979// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1980// Foo(callback.AsStdFunction());
1981// }
1982//
1983// The internal::SignatureOfT<F> indirection allows to use other types
1984// than just function signature type. This is typically useful when
1985// providing a mock for a predefined std::function type. Example:
1986//
1987// using FilterPredicate = std::function<bool(string)>;
1988// void MyFilterAlgorithm(FilterPredicate predicate);
1989//
1990// TEST(FooTest, FilterPredicateAlwaysAccepts) {
1991// MockFunction<FilterPredicate> predicateMock;
1992// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
1993// MyFilterAlgorithm(predicateMock.AsStdFunction());
1994// }
1995template <typename F>
1996class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
1997 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
1998
1999 public:
2000 using Base::Base;
2001};
2002
2003// The style guide prohibits "using" statements in a namespace scope
2004// inside a header file. However, the MockSpec class template is
2005// meant to be defined in the ::testing namespace. The following line
2006// is just a trick for working around a bug in MSVC 8.0, which cannot
2007// handle it if we define MockSpec in ::testing.
2008using internal::MockSpec;
2009
2010// Const(x) is a convenient function for obtaining a const reference
2011// to x. This is useful for setting expectations on an overloaded
2012// const mock method, e.g.
2013//
2014// class MockFoo : public FooInterface {
2015// public:
2016// MOCK_METHOD0(Bar, int());
2017// MOCK_CONST_METHOD0(Bar, int&());
2018// };
2019//
2020// MockFoo foo;
2021// // Expects a call to non-const MockFoo::Bar().
2022// EXPECT_CALL(foo, Bar());
2023// // Expects a call to const MockFoo::Bar().
2024// EXPECT_CALL(Const(foo), Bar());
2025template <typename T>
2026inline const T& Const(const T& x) {
2027 return x;
2028}
2029
2030// Constructs an Expectation object that references and co-owns exp.
2031inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
2032 : expectation_base_(exp.GetHandle().expectation_base()) {}
2033
2034} // namespace testing
2035
2036GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2037
2038// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
2039// required to avoid compile errors when the name of the method used in call is
2040// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
2041// tests in internal/gmock-spec-builders_test.cc for more details.
2042//
2043// This macro supports statements both with and without parameter matchers. If
2044// the parameter list is omitted, gMock will accept any parameters, which allows
2045// tests to be written that don't need to encode the number of method
2046// parameter. This technique may only be used for non-overloaded methods.
2047//
2048// // These are the same:
2049// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
2050// ON_CALL(mock, NoArgsMethod).WillByDefault(...);
2051//
2052// // As are these:
2053// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
2054// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
2055//
2056// // Can also specify args if you want, of course:
2057// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
2058//
2059// // Overloads work as long as you specify parameters:
2060// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
2061// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
2062//
2063// // Oops! Which overload did you want?
2064// ON_CALL(mock, OverloadedMethod).WillByDefault(...);
2065// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
2066//
2067// How this works: The mock class uses two overloads of the gmock_Method
2068// expectation setter method plus an operator() overload on the MockSpec object.
2069// In the matcher list form, the macro expands to:
2070//
2071// // This statement:
2072// ON_CALL(mock, TwoArgsMethod(_, 45))...
2073//
2074// // ...expands to:
2075// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
2076// |-------------v---------------||------------v-------------|
2077// invokes first overload swallowed by operator()
2078//
2079// // ...which is essentially:
2080// mock.gmock_TwoArgsMethod(_, 45)...
2081//
2082// Whereas the form without a matcher list:
2083//
2084// // This statement:
2085// ON_CALL(mock, TwoArgsMethod)...
2086//
2087// // ...expands to:
2088// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
2089// |-----------------------v--------------------------|
2090// invokes second overload
2091//
2092// // ...which is essentially:
2093// mock.gmock_TwoArgsMethod(_, _)...
2094//
2095// The WithoutMatchers() argument is used to disambiguate overloads and to
2096// block the caller from accidentally invoking the second overload directly. The
2097// second argument is an internal type derived from the method signature. The
2098// failure to disambiguate two overloads of this method in the ON_CALL statement
2099// is how we block callers from setting expectations on overloaded methods.
2100#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
2101 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
2102 nullptr) \
2103 .Setter(__FILE__, __LINE__, #mock_expr, #call)
2104
2105#define ON_CALL(obj, call) \
2106 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
2107
2108#define EXPECT_CALL(obj, call) \
2109 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
2110
2111#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
2112