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