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