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