blob: 0fc43d6d23d8e5764f6fcd338cf1596d9de8ae7a [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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// .WithArguments(multi-argument-matcher)
41// .WillByDefault(action);
42//
43// where the .WithArguments() 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// .WithArguments(multi-argument-matchers)
50// .Times(cardinality)
51// .InSequence(sequences)
52// .WillOnce(action)
53// .WillRepeatedly(action)
54// .RetiresOnSaturation();
55//
56// where all clauses are optional, .InSequence() and .WillOnce() can
57// appear any number of times, and .Times() can be omitted only if
58// .WillOnce() or .WillRepeatedly() is present.
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
69#include <gmock/gmock-actions.h>
70#include <gmock/gmock-cardinalities.h>
71#include <gmock/gmock-matchers.h>
72#include <gmock/gmock-printers.h>
73#include <gmock/internal/gmock-internal-utils.h>
74#include <gmock/internal/gmock-port.h>
75#include <gtest/gtest.h>
76
77namespace testing {
78
79// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
80// and MUST NOT BE USED IN USER CODE!!!
81namespace internal {
82
83template <typename F>
84class FunctionMocker;
85
86// Base class for expectations.
87class ExpectationBase;
88
89// Helper class for testing the Expectation class template.
90class ExpectationTester;
91
92// Base class for function mockers.
93template <typename F>
94class FunctionMockerBase;
95
96// Helper class for implementing FunctionMockerBase<F>::InvokeWith().
97template <typename Result, typename F>
98class InvokeWithHelper;
99
100// Protects the mock object registry (in class Mock), all function
101// mockers, and all expectations.
102//
103// The reason we don't use more fine-grained protection is: when a
104// mock function Foo() is called, it needs to consult its expectations
105// to see which one should be picked. If another thread is allowed to
106// call a mock function (either Foo() or a different one) at the same
107// time, it could affect the "retired" attributes of Foo()'s
108// expectations when InSequence() is used, and thus affect which
109// expectation gets picked. Therefore, we sequence all mock function
110// calls to ensure the integrity of the mock objects' states.
111extern Mutex g_gmock_mutex;
112
113// Abstract base class of FunctionMockerBase. This is the
114// type-agnostic part of the function mocker interface. Its pure
115// virtual methods are implemented by FunctionMockerBase.
116class UntypedFunctionMockerBase {
117 public:
118 virtual ~UntypedFunctionMockerBase() {}
119
120 // Verifies that all expectations on this mock function have been
121 // satisfied. Reports one or more Google Test non-fatal failures
122 // and returns false if not.
123 // L >= g_gmock_mutex
124 virtual bool VerifyAndClearExpectationsLocked() = 0;
125
126 // Clears the ON_CALL()s set on this mock function.
127 // L >= g_gmock_mutex
128 virtual void ClearDefaultActionsLocked() = 0;
129}; // class UntypedFunctionMockerBase
130
131// This template class implements a default action spec (i.e. an
132// ON_CALL() statement).
133template <typename F>
134class DefaultActionSpec {
135 public:
136 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
137 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
138
139 // Constructs a DefaultActionSpec object from the information inside
140 // the parenthesis of an ON_CALL() statement.
141 DefaultActionSpec(const char* file, int line,
142 const ArgumentMatcherTuple& matchers)
143 : file_(file),
144 line_(line),
145 matchers_(matchers),
146 extra_matcher_(_),
147 last_clause_(NONE) {
148 }
149
150 // Where in the source file was the default action spec defined?
151 const char* file() const { return file_; }
152 int line() const { return line_; }
153
154 // Implements the .WithArguments() clause.
155 DefaultActionSpec& WithArguments(const Matcher<const ArgumentTuple&>& m) {
156 // Makes sure this is called at most once.
157 ExpectSpecProperty(last_clause_ < WITH_ARGUMENTS,
158 ".WithArguments() cannot appear "
159 "more than once in an ON_CALL().");
160 last_clause_ = WITH_ARGUMENTS;
161
162 extra_matcher_ = m;
163 return *this;
164 }
165
166 // Implements the .WillByDefault() clause.
167 DefaultActionSpec& WillByDefault(const Action<F>& action) {
168 ExpectSpecProperty(last_clause_ < WILL_BY_DEFAULT,
169 ".WillByDefault() must appear "
170 "exactly once in an ON_CALL().");
171 last_clause_ = WILL_BY_DEFAULT;
172
173 ExpectSpecProperty(!action.IsDoDefault(),
174 "DoDefault() cannot be used in ON_CALL().");
175 action_ = action;
176 return *this;
177 }
178
179 // Returns true iff the given arguments match the matchers.
180 bool Matches(const ArgumentTuple& args) const {
181 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
182 }
183
184 // Returns the action specified by the user.
185 const Action<F>& GetAction() const {
186 AssertSpecProperty(last_clause_ == WILL_BY_DEFAULT,
187 ".WillByDefault() must appear exactly "
188 "once in an ON_CALL().");
189 return action_;
190 }
191 private:
192 // Gives each clause in the ON_CALL() statement a name.
193 enum Clause {
194 // Do not change the order of the enum members! The run-time
195 // syntax checking relies on it.
196 NONE,
197 WITH_ARGUMENTS,
198 WILL_BY_DEFAULT,
199 };
200
201 // Asserts that the ON_CALL() statement has a certain property.
202 void AssertSpecProperty(bool property, const string& failure_message) const {
203 Assert(property, file_, line_, failure_message);
204 }
205
206 // Expects that the ON_CALL() statement has a certain property.
207 void ExpectSpecProperty(bool property, const string& failure_message) const {
208 Expect(property, file_, line_, failure_message);
209 }
210
211 // The information in statement
212 //
213 // ON_CALL(mock_object, Method(matchers))
214 // .WithArguments(multi-argument-matcher)
215 // .WillByDefault(action);
216 //
217 // is recorded in the data members like this:
218 //
219 // source file that contains the statement => file_
220 // line number of the statement => line_
221 // matchers => matchers_
222 // multi-argument-matcher => extra_matcher_
223 // action => action_
224 const char* file_;
225 int line_;
226 ArgumentMatcherTuple matchers_;
227 Matcher<const ArgumentTuple&> extra_matcher_;
228 Action<F> action_;
229
230 // The last clause in the ON_CALL() statement as seen so far.
231 // Initially NONE and changes as the statement is parsed.
232 Clause last_clause_;
233}; // class DefaultActionSpec
234
235// Possible reactions on uninteresting calls.
236enum CallReaction {
237 ALLOW,
238 WARN,
239 FAIL,
240};
241
242} // namespace internal
243
244// Utilities for manipulating mock objects.
245class Mock {
246 public:
247 // The following public methods can be called concurrently.
248
zhanyong.wandf35a762009-04-22 22:25:31 +0000249 // Tells Google Mock to ignore mock_obj when checking for leaked
250 // mock objects.
251 static void AllowLeak(const void* mock_obj);
252
shiqiane35fdd92008-12-10 05:08:54 +0000253 // Verifies and clears all expectations on the given mock object.
254 // If the expectations aren't satisfied, generates one or more
255 // Google Test non-fatal failures and returns false.
256 static bool VerifyAndClearExpectations(void* mock_obj);
257
258 // Verifies all expectations on the given mock object and clears its
259 // default actions and expectations. Returns true iff the
260 // verification was successful.
261 static bool VerifyAndClear(void* mock_obj);
262 private:
263 // Needed for a function mocker to register itself (so that we know
264 // how to clear a mock object).
265 template <typename F>
266 friend class internal::FunctionMockerBase;
267
268 template <typename R, typename Args>
269 friend class internal::InvokeWithHelper;
270
271 template <typename M>
272 friend class NiceMock;
273
274 template <typename M>
275 friend class StrictMock;
276
277 // Tells Google Mock to allow uninteresting calls on the given mock
278 // object.
279 // L < g_gmock_mutex
280 static void AllowUninterestingCalls(const void* mock_obj);
281
282 // Tells Google Mock to warn the user about uninteresting calls on
283 // the given mock object.
284 // L < g_gmock_mutex
285 static void WarnUninterestingCalls(const void* mock_obj);
286
287 // Tells Google Mock to fail uninteresting calls on the given mock
288 // object.
289 // L < g_gmock_mutex
290 static void FailUninterestingCalls(const void* mock_obj);
291
292 // Tells Google Mock the given mock object is being destroyed and
293 // its entry in the call-reaction table should be removed.
294 // L < g_gmock_mutex
295 static void UnregisterCallReaction(const void* mock_obj);
296
297 // Returns the reaction Google Mock will have on uninteresting calls
298 // made on the given mock object.
299 // L < g_gmock_mutex
300 static internal::CallReaction GetReactionOnUninterestingCalls(
301 const void* mock_obj);
302
303 // Verifies that all expectations on the given mock object have been
304 // satisfied. Reports one or more Google Test non-fatal failures
305 // and returns false if not.
306 // L >= g_gmock_mutex
307 static bool VerifyAndClearExpectationsLocked(void* mock_obj);
308
309 // Clears all ON_CALL()s set on the given mock object.
310 // L >= g_gmock_mutex
311 static void ClearDefaultActionsLocked(void* mock_obj);
312
313 // Registers a mock object and a mock method it owns.
314 // L < g_gmock_mutex
315 static void Register(const void* mock_obj,
316 internal::UntypedFunctionMockerBase* mocker);
317
zhanyong.wandf35a762009-04-22 22:25:31 +0000318 // Tells Google Mock where in the source code mock_obj is used in an
319 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
320 // information helps the user identify which object it is.
321 // L < g_gmock_mutex
322 static void RegisterUseByOnCallOrExpectCall(
323 const void* mock_obj, const char* file, int line);
324
shiqiane35fdd92008-12-10 05:08:54 +0000325 // Unregisters a mock method; removes the owning mock object from
326 // the registry when the last mock method associated with it has
327 // been unregistered. This is called only in the destructor of
328 // FunctionMockerBase.
329 // L >= g_gmock_mutex
330 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
331}; // class Mock
332
333// Sequence objects are used by a user to specify the relative order
334// in which the expectations should match. They are copyable (we rely
335// on the compiler-defined copy constructor and assignment operator).
336class Sequence {
337 public:
338 // Constructs an empty sequence.
339 Sequence()
340 : last_expectation_(
341 new internal::linked_ptr<internal::ExpectationBase>(NULL)) {}
342
343 // Adds an expectation to this sequence. The caller must ensure
344 // that no other thread is accessing this Sequence object.
345 void AddExpectation(
346 const internal::linked_ptr<internal::ExpectationBase>& expectation) const;
347 private:
348 // The last expectation in this sequence. We use a nested
349 // linked_ptr here because:
350 // - Sequence objects are copyable, and we want the copies to act
351 // as aliases. The outer linked_ptr allows the copies to co-own
352 // and share the same state.
353 // - An Expectation object is co-owned (via linked_ptr) by its
354 // FunctionMocker and its successors (other Expectation objects).
355 // Hence the inner linked_ptr.
356 internal::linked_ptr<internal::linked_ptr<internal::ExpectationBase> >
357 last_expectation_;
358}; // class Sequence
359
360// An object of this type causes all EXPECT_CALL() statements
361// encountered in its scope to be put in an anonymous sequence. The
362// work is done in the constructor and destructor. You should only
363// create an InSequence object on the stack.
364//
365// The sole purpose for this class is to support easy definition of
366// sequential expectations, e.g.
367//
368// {
369// InSequence dummy; // The name of the object doesn't matter.
370//
371// // The following expectations must match in the order they appear.
372// EXPECT_CALL(a, Bar())...;
373// EXPECT_CALL(a, Baz())...;
374// ...
375// EXPECT_CALL(b, Xyz())...;
376// }
377//
378// You can create InSequence objects in multiple threads, as long as
379// they are used to affect different mock objects. The idea is that
380// each thread can create and set up its own mocks as if it's the only
381// thread. However, for clarity of your tests we recommend you to set
382// up mocks in the main thread unless you have a good reason not to do
383// so.
384class InSequence {
385 public:
386 InSequence();
387 ~InSequence();
388 private:
389 bool sequence_created_;
390
391 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wane0d051e2009-02-19 00:33:37 +0000392} GMOCK_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000393
394namespace internal {
395
396// Points to the implicit sequence introduced by a living InSequence
397// object (if any) in the current thread or NULL.
398extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
399
400// Base class for implementing expectations.
401//
402// There are two reasons for having a type-agnostic base class for
403// Expectation:
404//
405// 1. We need to store collections of expectations of different
406// types (e.g. all pre-requisites of a particular expectation, all
407// expectations in a sequence). Therefore these expectation objects
408// must share a common base class.
409//
410// 2. We can avoid binary code bloat by moving methods not depending
411// on the template argument of Expectation to the base class.
412//
413// This class is internal and mustn't be used by user code directly.
414class ExpectationBase {
415 public:
416 ExpectationBase(const char* file, int line);
417
418 virtual ~ExpectationBase();
419
420 // Where in the source file was the expectation spec defined?
421 const char* file() const { return file_; }
422 int line() const { return line_; }
423
424 // Returns the cardinality specified in the expectation spec.
425 const Cardinality& cardinality() const { return cardinality_; }
426
427 // Describes the source file location of this expectation.
428 void DescribeLocationTo(::std::ostream* os) const {
429 *os << file() << ":" << line() << ": ";
430 }
431
432 // Describes how many times a function call matching this
433 // expectation has occurred.
434 // L >= g_gmock_mutex
435 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
436 protected:
437 typedef std::set<linked_ptr<ExpectationBase>,
438 LinkedPtrLessThan<ExpectationBase> >
439 ExpectationBaseSet;
440
441 enum Clause {
442 // Don't change the order of the enum members!
443 NONE,
444 WITH_ARGUMENTS,
445 TIMES,
446 IN_SEQUENCE,
447 WILL_ONCE,
448 WILL_REPEATEDLY,
449 RETIRES_ON_SATURATION,
450 };
451
452 // Asserts that the EXPECT_CALL() statement has the given property.
453 void AssertSpecProperty(bool property, const string& failure_message) const {
454 Assert(property, file_, line_, failure_message);
455 }
456
457 // Expects that the EXPECT_CALL() statement has the given property.
458 void ExpectSpecProperty(bool property, const string& failure_message) const {
459 Expect(property, file_, line_, failure_message);
460 }
461
462 // Explicitly specifies the cardinality of this expectation. Used
463 // by the subclasses to implement the .Times() clause.
464 void SpecifyCardinality(const Cardinality& cardinality);
465
466 // Returns true iff the user specified the cardinality explicitly
467 // using a .Times().
468 bool cardinality_specified() const { return cardinality_specified_; }
469
470 // Sets the cardinality of this expectation spec.
471 void set_cardinality(const Cardinality& cardinality) {
472 cardinality_ = cardinality;
473 }
474
475 // The following group of methods should only be called after the
476 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
477 // the current thread.
478
479 // Retires all pre-requisites of this expectation.
480 // L >= g_gmock_mutex
481 void RetireAllPreRequisites();
482
483 // Returns true iff this expectation is retired.
484 // L >= g_gmock_mutex
485 bool is_retired() const {
486 g_gmock_mutex.AssertHeld();
487 return retired_;
488 }
489
490 // Retires this expectation.
491 // L >= g_gmock_mutex
492 void Retire() {
493 g_gmock_mutex.AssertHeld();
494 retired_ = true;
495 }
496
497 // Returns true iff this expectation is satisfied.
498 // L >= g_gmock_mutex
499 bool IsSatisfied() const {
500 g_gmock_mutex.AssertHeld();
501 return cardinality().IsSatisfiedByCallCount(call_count_);
502 }
503
504 // Returns true iff this expectation is saturated.
505 // L >= g_gmock_mutex
506 bool IsSaturated() const {
507 g_gmock_mutex.AssertHeld();
508 return cardinality().IsSaturatedByCallCount(call_count_);
509 }
510
511 // Returns true iff this expectation is over-saturated.
512 // L >= g_gmock_mutex
513 bool IsOverSaturated() const {
514 g_gmock_mutex.AssertHeld();
515 return cardinality().IsOverSaturatedByCallCount(call_count_);
516 }
517
518 // Returns true iff all pre-requisites of this expectation are satisfied.
519 // L >= g_gmock_mutex
520 bool AllPrerequisitesAreSatisfied() const;
521
522 // Adds unsatisfied pre-requisites of this expectation to 'result'.
523 // L >= g_gmock_mutex
524 void FindUnsatisfiedPrerequisites(ExpectationBaseSet* result) const;
525
526 // Returns the number this expectation has been invoked.
527 // L >= g_gmock_mutex
528 int call_count() const {
529 g_gmock_mutex.AssertHeld();
530 return call_count_;
531 }
532
533 // Increments the number this expectation has been invoked.
534 // L >= g_gmock_mutex
535 void IncrementCallCount() {
536 g_gmock_mutex.AssertHeld();
537 call_count_++;
538 }
539
540 private:
541 friend class ::testing::Sequence;
542 friend class ::testing::internal::ExpectationTester;
543
544 template <typename Function>
545 friend class Expectation;
546
547 // This group of fields are part of the spec and won't change after
548 // an EXPECT_CALL() statement finishes.
549 const char* file_; // The file that contains the expectation.
550 int line_; // The line number of the expectation.
551 // True iff the cardinality is specified explicitly.
552 bool cardinality_specified_;
553 Cardinality cardinality_; // The cardinality of the expectation.
554 // The immediate pre-requisites of this expectation. We use
555 // linked_ptr in the set because we want an Expectation object to be
556 // co-owned by its FunctionMocker and its successors. This allows
557 // multiple mock objects to be deleted at different times.
558 ExpectationBaseSet immediate_prerequisites_;
559
560 // This group of fields are the current state of the expectation,
561 // and can change as the mock function is called.
562 int call_count_; // How many times this expectation has been invoked.
563 bool retired_; // True iff this expectation has retired.
564}; // class ExpectationBase
565
566// Impements an expectation for the given function type.
567template <typename F>
568class Expectation : public ExpectationBase {
569 public:
570 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
571 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
572 typedef typename Function<F>::Result Result;
573
574 Expectation(FunctionMockerBase<F>* owner, const char* file, int line,
575 const ArgumentMatcherTuple& m)
576 : ExpectationBase(file, line),
577 owner_(owner),
578 matchers_(m),
579 extra_matcher_(_),
580 repeated_action_specified_(false),
581 repeated_action_(DoDefault()),
582 retires_on_saturation_(false),
583 last_clause_(NONE),
584 action_count_checked_(false) {}
585
586 virtual ~Expectation() {
587 // Check the validity of the action count if it hasn't been done
588 // yet (for example, if the expectation was never used).
589 CheckActionCountIfNotDone();
590 }
591
592 // Implements the .WithArguments() clause.
593 Expectation& WithArguments(const Matcher<const ArgumentTuple&>& m) {
594 if (last_clause_ == WITH_ARGUMENTS) {
595 ExpectSpecProperty(false,
596 ".WithArguments() cannot appear "
597 "more than once in an EXPECT_CALL().");
598 } else {
599 ExpectSpecProperty(last_clause_ < WITH_ARGUMENTS,
600 ".WithArguments() must be the first "
601 "clause in an EXPECT_CALL().");
602 }
603 last_clause_ = WITH_ARGUMENTS;
604
605 extra_matcher_ = m;
606 return *this;
607 }
608
609 // Implements the .Times() clause.
610 Expectation& Times(const Cardinality& cardinality) {
611 if (last_clause_ ==TIMES) {
612 ExpectSpecProperty(false,
613 ".Times() cannot appear "
614 "more than once in an EXPECT_CALL().");
615 } else {
616 ExpectSpecProperty(last_clause_ < TIMES,
617 ".Times() cannot appear after "
618 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
619 "or .RetiresOnSaturation().");
620 }
621 last_clause_ = TIMES;
622
623 ExpectationBase::SpecifyCardinality(cardinality);
624 return *this;
625 }
626
627 // Implements the .Times() clause.
628 Expectation& Times(int n) {
629 return Times(Exactly(n));
630 }
631
632 // Implements the .InSequence() clause.
633 Expectation& InSequence(const Sequence& s) {
634 ExpectSpecProperty(last_clause_ <= IN_SEQUENCE,
635 ".InSequence() cannot appear after .WillOnce(),"
636 " .WillRepeatedly(), or "
637 ".RetiresOnSaturation().");
638 last_clause_ = IN_SEQUENCE;
639
640 s.AddExpectation(owner_->GetLinkedExpectationBase(this));
641 return *this;
642 }
643 Expectation& InSequence(const Sequence& s1, const Sequence& s2) {
644 return InSequence(s1).InSequence(s2);
645 }
646 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
647 const Sequence& s3) {
648 return InSequence(s1, s2).InSequence(s3);
649 }
650 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
651 const Sequence& s3, const Sequence& s4) {
652 return InSequence(s1, s2, s3).InSequence(s4);
653 }
654 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
655 const Sequence& s3, const Sequence& s4,
656 const Sequence& s5) {
657 return InSequence(s1, s2, s3, s4).InSequence(s5);
658 }
659
660 // Implements the .WillOnce() clause.
661 Expectation& WillOnce(const Action<F>& action) {
662 ExpectSpecProperty(last_clause_ <= WILL_ONCE,
663 ".WillOnce() cannot appear after "
664 ".WillRepeatedly() or .RetiresOnSaturation().");
665 last_clause_ = WILL_ONCE;
666
667 actions_.push_back(action);
668 if (!cardinality_specified()) {
669 set_cardinality(Exactly(static_cast<int>(actions_.size())));
670 }
671 return *this;
672 }
673
674 // Implements the .WillRepeatedly() clause.
675 Expectation& WillRepeatedly(const Action<F>& action) {
676 if (last_clause_ == WILL_REPEATEDLY) {
677 ExpectSpecProperty(false,
678 ".WillRepeatedly() cannot appear "
679 "more than once in an EXPECT_CALL().");
680 } else {
681 ExpectSpecProperty(last_clause_ < WILL_REPEATEDLY,
682 ".WillRepeatedly() cannot appear "
683 "after .RetiresOnSaturation().");
684 }
685 last_clause_ = WILL_REPEATEDLY;
686 repeated_action_specified_ = true;
687
688 repeated_action_ = action;
689 if (!cardinality_specified()) {
690 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
691 }
692
693 // Now that no more action clauses can be specified, we check
694 // whether their count makes sense.
695 CheckActionCountIfNotDone();
696 return *this;
697 }
698
699 // Implements the .RetiresOnSaturation() clause.
700 Expectation& RetiresOnSaturation() {
701 ExpectSpecProperty(last_clause_ < RETIRES_ON_SATURATION,
702 ".RetiresOnSaturation() cannot appear "
703 "more than once.");
704 last_clause_ = RETIRES_ON_SATURATION;
705 retires_on_saturation_ = true;
706
707 // Now that no more action clauses can be specified, we check
708 // whether their count makes sense.
709 CheckActionCountIfNotDone();
710 return *this;
711 }
712
713 // Returns the matchers for the arguments as specified inside the
714 // EXPECT_CALL() macro.
715 const ArgumentMatcherTuple& matchers() const {
716 return matchers_;
717 }
718
719 // Returns the matcher specified by the .WithArguments() clause.
720 const Matcher<const ArgumentTuple&>& extra_matcher() const {
721 return extra_matcher_;
722 }
723
724 // Returns the sequence of actions specified by the .WillOnce() clause.
725 const std::vector<Action<F> >& actions() const { return actions_; }
726
727 // Returns the action specified by the .WillRepeatedly() clause.
728 const Action<F>& repeated_action() const { return repeated_action_; }
729
730 // Returns true iff the .RetiresOnSaturation() clause was specified.
731 bool retires_on_saturation() const { return retires_on_saturation_; }
732
733 // Describes how many times a function call matching this
734 // expectation has occurred (implements
735 // ExpectationBase::DescribeCallCountTo()).
736 // L >= g_gmock_mutex
737 virtual void DescribeCallCountTo(::std::ostream* os) const {
738 g_gmock_mutex.AssertHeld();
739
740 // Describes how many times the function is expected to be called.
741 *os << " Expected: to be ";
742 cardinality().DescribeTo(os);
743 *os << "\n Actual: ";
744 Cardinality::DescribeActualCallCountTo(call_count(), os);
745
746 // Describes the state of the expectation (e.g. is it satisfied?
747 // is it active?).
748 *os << " - " << (IsOverSaturated() ? "over-saturated" :
749 IsSaturated() ? "saturated" :
750 IsSatisfied() ? "satisfied" : "unsatisfied")
751 << " and "
752 << (is_retired() ? "retired" : "active");
753 }
754 private:
755 template <typename Function>
756 friend class FunctionMockerBase;
757
758 template <typename R, typename Function>
759 friend class InvokeWithHelper;
760
761 // The following methods will be called only after the EXPECT_CALL()
762 // statement finishes and when the current thread holds
763 // g_gmock_mutex.
764
765 // Returns true iff this expectation matches the given arguments.
766 // L >= g_gmock_mutex
767 bool Matches(const ArgumentTuple& args) const {
768 g_gmock_mutex.AssertHeld();
769 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
770 }
771
772 // Returns true iff this expectation should handle the given arguments.
773 // L >= g_gmock_mutex
774 bool ShouldHandleArguments(const ArgumentTuple& args) const {
775 g_gmock_mutex.AssertHeld();
776
777 // In case the action count wasn't checked when the expectation
778 // was defined (e.g. if this expectation has no WillRepeatedly()
779 // or RetiresOnSaturation() clause), we check it when the
780 // expectation is used for the first time.
781 CheckActionCountIfNotDone();
782 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
783 }
784
785 // Describes the result of matching the arguments against this
786 // expectation to the given ostream.
787 // L >= g_gmock_mutex
788 void DescribeMatchResultTo(const ArgumentTuple& args,
789 ::std::ostream* os) const {
790 g_gmock_mutex.AssertHeld();
791
792 if (is_retired()) {
793 *os << " Expected: the expectation is active\n"
794 << " Actual: it is retired\n";
795 } else if (!Matches(args)) {
796 if (!TupleMatches(matchers_, args)) {
797 DescribeMatchFailureTupleTo(matchers_, args, os);
798 }
799 if (!extra_matcher_.Matches(args)) {
800 *os << " Expected: ";
801 extra_matcher_.DescribeTo(os);
802 *os << "\n Actual: false";
803
804 internal::ExplainMatchResultAsNeededTo<const ArgumentTuple&>(
805 extra_matcher_, args, os);
806 *os << "\n";
807 }
808 } else if (!AllPrerequisitesAreSatisfied()) {
809 *os << " Expected: all pre-requisites are satisfied\n"
810 << " Actual: the following immediate pre-requisites "
811 << "are not satisfied:\n";
812 ExpectationBaseSet unsatisfied_prereqs;
813 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
814 int i = 0;
815 for (ExpectationBaseSet::const_iterator it = unsatisfied_prereqs.begin();
816 it != unsatisfied_prereqs.end(); ++it) {
817 (*it)->DescribeLocationTo(os);
818 *os << "pre-requisite #" << i++ << "\n";
819 }
820 *os << " (end of pre-requisites)\n";
821 } else {
822 // This line is here just for completeness' sake. It will never
823 // be executed as currently the DescribeMatchResultTo() function
824 // is called only when the mock function call does NOT match the
825 // expectation.
826 *os << "The call matches the expectation.\n";
827 }
828 }
829
830 // Returns the action that should be taken for the current invocation.
831 // L >= g_gmock_mutex
832 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
833 const ArgumentTuple& args) const {
834 g_gmock_mutex.AssertHeld();
835 const int count = call_count();
836 Assert(count >= 1, __FILE__, __LINE__,
837 "call_count() is <= 0 when GetCurrentAction() is "
838 "called - this should never happen.");
839
840 const int action_count = static_cast<int>(actions().size());
841 if (action_count > 0 && !repeated_action_specified_ &&
842 count > action_count) {
843 // If there is at least one WillOnce() and no WillRepeatedly(),
844 // we warn the user when the WillOnce() clauses ran out.
845 ::std::stringstream ss;
846 DescribeLocationTo(&ss);
847 ss << "Actions ran out.\n"
848 << "Called " << count << " times, but only "
849 << action_count << " WillOnce()"
850 << (action_count == 1 ? " is" : "s are") << " specified - ";
851 mocker->DescribeDefaultActionTo(args, &ss);
852 Log(WARNING, ss.str(), 1);
853 }
854
855 return count <= action_count ? actions()[count - 1] : repeated_action();
856 }
857
858 // Given the arguments of a mock function call, if the call will
859 // over-saturate this expectation, returns the default action;
860 // otherwise, returns the next action in this expectation. Also
861 // describes *what* happened to 'what', and explains *why* Google
862 // Mock does it to 'why'. This method is not const as it calls
863 // IncrementCallCount().
864 // L >= g_gmock_mutex
865 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
866 const ArgumentTuple& args,
867 ::std::ostream* what,
868 ::std::ostream* why) {
869 g_gmock_mutex.AssertHeld();
870 if (IsSaturated()) {
871 // We have an excessive call.
872 IncrementCallCount();
873 *what << "Mock function called more times than expected - ";
874 mocker->DescribeDefaultActionTo(args, what);
875 DescribeCallCountTo(why);
876
877 // TODO(wan): allow the user to control whether unexpected calls
878 // should fail immediately or continue using a flag
879 // --gmock_unexpected_calls_are_fatal.
880 return DoDefault();
881 }
882
883 IncrementCallCount();
884 RetireAllPreRequisites();
885
886 if (retires_on_saturation() && IsSaturated()) {
887 Retire();
888 }
889
890 // Must be done after IncrementCount()!
891 *what << "Expected mock function call.\n";
892 return GetCurrentAction(mocker, args);
893 }
894
895 // Checks the action count (i.e. the number of WillOnce() and
896 // WillRepeatedly() clauses) against the cardinality if this hasn't
897 // been done before. Prints a warning if there are too many or too
898 // few actions.
899 // L < mutex_
900 void CheckActionCountIfNotDone() const {
901 bool should_check = false;
902 {
903 MutexLock l(&mutex_);
904 if (!action_count_checked_) {
905 action_count_checked_ = true;
906 should_check = true;
907 }
908 }
909
910 if (should_check) {
911 if (!cardinality_specified_) {
912 // The cardinality was inferred - no need to check the action
913 // count against it.
914 return;
915 }
916
917 // The cardinality was explicitly specified.
918 const int action_count = static_cast<int>(actions_.size());
919 const int upper_bound = cardinality().ConservativeUpperBound();
920 const int lower_bound = cardinality().ConservativeLowerBound();
921 bool too_many; // True if there are too many actions, or false
922 // if there are too few.
923 if (action_count > upper_bound ||
924 (action_count == upper_bound && repeated_action_specified_)) {
925 too_many = true;
926 } else if (0 < action_count && action_count < lower_bound &&
927 !repeated_action_specified_) {
928 too_many = false;
929 } else {
930 return;
931 }
932
933 ::std::stringstream ss;
934 DescribeLocationTo(&ss);
935 ss << "Too " << (too_many ? "many" : "few")
936 << " actions specified.\n"
937 << "Expected to be ";
938 cardinality().DescribeTo(&ss);
939 ss << ", but has " << (too_many ? "" : "only ")
940 << action_count << " WillOnce()"
941 << (action_count == 1 ? "" : "s");
942 if (repeated_action_specified_) {
943 ss << " and a WillRepeatedly()";
944 }
945 ss << ".";
946 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
947 }
948 }
949
950 // All the fields below won't change once the EXPECT_CALL()
951 // statement finishes.
952 FunctionMockerBase<F>* const owner_;
953 ArgumentMatcherTuple matchers_;
954 Matcher<const ArgumentTuple&> extra_matcher_;
955 std::vector<Action<F> > actions_;
956 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
957 Action<F> repeated_action_;
958 bool retires_on_saturation_;
959 Clause last_clause_;
960 mutable bool action_count_checked_; // Under mutex_.
961 mutable Mutex mutex_; // Protects action_count_checked_.
962}; // class Expectation
963
964// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
965// specifying the default behavior of, or expectation on, a mock
966// function.
967
968// Note: class MockSpec really belongs to the ::testing namespace.
969// However if we define it in ::testing, MSVC will complain when
970// classes in ::testing::internal declare it as a friend class
971// template. To workaround this compiler bug, we define MockSpec in
972// ::testing::internal and import it into ::testing.
973
974template <typename F>
975class MockSpec {
976 public:
977 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
978 typedef typename internal::Function<F>::ArgumentMatcherTuple
979 ArgumentMatcherTuple;
980
981 // Constructs a MockSpec object, given the function mocker object
982 // that the spec is associated with.
983 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
984 : function_mocker_(function_mocker) {}
985
986 // Adds a new default action spec to the function mocker and returns
987 // the newly created spec.
988 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
989 const char* file, int line, const char* obj, const char* call) {
990 LogWithLocation(internal::INFO, file, line,
991 string("ON_CALL(") + obj + ", " + call + ") invoked");
992 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
993 }
994
995 // Adds a new expectation spec to the function mocker and returns
996 // the newly created spec.
997 internal::Expectation<F>& InternalExpectedAt(
998 const char* file, int line, const char* obj, const char* call) {
999 LogWithLocation(internal::INFO, file, line,
1000 string("EXPECT_CALL(") + obj + ", " + call + ") invoked");
1001 return function_mocker_->AddNewExpectation(file, line, matchers_);
1002 }
1003
1004 private:
1005 template <typename Function>
1006 friend class internal::FunctionMocker;
1007
1008 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1009 matchers_ = matchers;
1010 }
1011
1012 // Logs a message including file and line number information.
1013 void LogWithLocation(testing::internal::LogSeverity severity,
1014 const char* file, int line,
1015 const string& message) {
1016 ::std::ostringstream s;
1017 s << file << ":" << line << ": " << message << ::std::endl;
1018 Log(severity, s.str(), 0);
1019 }
1020
1021 // The function mocker that owns this spec.
1022 internal::FunctionMockerBase<F>* const function_mocker_;
1023 // The argument matchers specified in the spec.
1024 ArgumentMatcherTuple matchers_;
1025}; // class MockSpec
1026
1027// MSVC warns about using 'this' in base member initializer list, so
1028// we need to temporarily disable the warning. We have to do it for
1029// the entire class to suppress the warning, even though it's about
1030// the constructor only.
1031
1032#ifdef _MSC_VER
1033#pragma warning(push) // Saves the current warning state.
1034#pragma warning(disable:4355) // Temporarily disables warning 4355.
1035#endif // _MSV_VER
1036
1037// The base of the function mocker class for the given function type.
1038// We put the methods in this class instead of its child to avoid code
1039// bloat.
1040template <typename F>
1041class FunctionMockerBase : public UntypedFunctionMockerBase {
1042 public:
1043 typedef typename Function<F>::Result Result;
1044 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1045 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1046
1047 FunctionMockerBase() : mock_obj_(NULL), name_(""), current_spec_(this) {}
1048
1049 // The destructor verifies that all expectations on this mock
1050 // function have been satisfied. If not, it will report Google Test
1051 // non-fatal failures for the violations.
1052 // L < g_gmock_mutex
1053 virtual ~FunctionMockerBase() {
1054 MutexLock l(&g_gmock_mutex);
1055 VerifyAndClearExpectationsLocked();
1056 Mock::UnregisterLocked(this);
1057 }
1058
1059 // Returns the ON_CALL spec that matches this mock function with the
1060 // given arguments; returns NULL if no matching ON_CALL is found.
1061 // L = *
1062 const DefaultActionSpec<F>* FindDefaultActionSpec(
1063 const ArgumentTuple& args) const {
1064 for (typename std::vector<DefaultActionSpec<F> >::const_reverse_iterator it
1065 = default_actions_.rbegin();
1066 it != default_actions_.rend(); ++it) {
1067 const DefaultActionSpec<F>& spec = *it;
1068 if (spec.Matches(args))
1069 return &spec;
1070 }
1071
1072 return NULL;
1073 }
1074
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001075 // Performs the default action of this mock function on the given arguments
1076 // and returns the result. Asserts with a helpful call descrption if there is
1077 // no valid return value. This method doesn't depend on the mutable state of
1078 // this object, and thus can be called concurrently without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001079 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001080 Result PerformDefaultAction(const ArgumentTuple& args,
1081 const string& call_description) const {
shiqiane35fdd92008-12-10 05:08:54 +00001082 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001083 if (spec != NULL) {
1084 return spec->GetAction().Perform(args);
1085 }
1086 Assert(DefaultValue<Result>::Exists(), "", -1,
1087 call_description + "\n The mock function has no default action "
1088 "set, and its return type has no default value set.");
1089 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001090 }
1091
1092 // Registers this function mocker and the mock object owning it;
1093 // returns a reference to the function mocker object. This is only
1094 // called by the ON_CALL() and EXPECT_CALL() macros.
zhanyong.wandf35a762009-04-22 22:25:31 +00001095 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001096 FunctionMocker<F>& RegisterOwner(const void* mock_obj) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001097 {
1098 MutexLock l(&g_gmock_mutex);
1099 mock_obj_ = mock_obj;
1100 }
shiqiane35fdd92008-12-10 05:08:54 +00001101 Mock::Register(mock_obj, this);
zhanyong.wan946bc642009-03-31 00:05:30 +00001102 return *::testing::internal::down_cast<FunctionMocker<F>*>(this);
shiqiane35fdd92008-12-10 05:08:54 +00001103 }
1104
1105 // The following two functions are from UntypedFunctionMockerBase.
1106
1107 // Verifies that all expectations on this mock function have been
1108 // satisfied. Reports one or more Google Test non-fatal failures
1109 // and returns false if not.
1110 // L >= g_gmock_mutex
1111 virtual bool VerifyAndClearExpectationsLocked();
1112
1113 // Clears the ON_CALL()s set on this mock function.
1114 // L >= g_gmock_mutex
1115 virtual void ClearDefaultActionsLocked() {
1116 g_gmock_mutex.AssertHeld();
1117 default_actions_.clear();
1118 }
1119
1120 // Sets the name of the function being mocked. Will be called upon
1121 // each invocation of this mock function.
1122 // L < g_gmock_mutex
1123 void SetOwnerAndName(const void* mock_obj, const char* name) {
1124 // We protect name_ under g_gmock_mutex in case this mock function
1125 // is called from two threads concurrently.
1126 MutexLock l(&g_gmock_mutex);
1127 mock_obj_ = mock_obj;
1128 name_ = name;
1129 }
1130
1131 // Returns the address of the mock object this method belongs to.
1132 // Must be called after SetOwnerAndName() has been called.
1133 // L < g_gmock_mutex
1134 const void* MockObject() const {
1135 const void* mock_obj;
1136 {
1137 // We protect mock_obj_ under g_gmock_mutex in case this mock
1138 // function is called from two threads concurrently.
1139 MutexLock l(&g_gmock_mutex);
1140 mock_obj = mock_obj_;
1141 }
1142 return mock_obj;
1143 }
1144
1145 // Returns the name of the function being mocked. Must be called
1146 // after SetOwnerAndName() has been called.
1147 // L < g_gmock_mutex
1148 const char* Name() const {
1149 const char* name;
1150 {
1151 // We protect name_ under g_gmock_mutex in case this mock
1152 // function is called from two threads concurrently.
1153 MutexLock l(&g_gmock_mutex);
1154 name = name_;
1155 }
1156 return name;
1157 }
1158 protected:
1159 template <typename Function>
1160 friend class MockSpec;
1161
1162 template <typename R, typename Function>
1163 friend class InvokeWithHelper;
1164
1165 // Returns the result of invoking this mock function with the given
1166 // arguments. This function can be safely called from multiple
1167 // threads concurrently.
1168 // L < g_gmock_mutex
1169 Result InvokeWith(const ArgumentTuple& args) {
1170 return InvokeWithHelper<Result, F>::InvokeAndPrintResult(this, args);
1171 }
1172
1173 // Adds and returns a default action spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001174 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001175 DefaultActionSpec<F>& AddNewDefaultActionSpec(
1176 const char* file, int line,
1177 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001178 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
shiqiane35fdd92008-12-10 05:08:54 +00001179 default_actions_.push_back(DefaultActionSpec<F>(file, line, m));
1180 return default_actions_.back();
1181 }
1182
1183 // Adds and returns an expectation spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001184 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001185 Expectation<F>& AddNewExpectation(
1186 const char* file, int line,
1187 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001188 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
shiqiane35fdd92008-12-10 05:08:54 +00001189 const linked_ptr<Expectation<F> > expectation(
1190 new Expectation<F>(this, file, line, m));
1191 expectations_.push_back(expectation);
1192
1193 // Adds this expectation into the implicit sequence if there is one.
1194 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1195 if (implicit_sequence != NULL) {
1196 implicit_sequence->AddExpectation(expectation);
1197 }
1198
1199 return *expectation;
1200 }
1201
1202 // The current spec (either default action spec or expectation spec)
1203 // being described on this function mocker.
1204 MockSpec<F>& current_spec() { return current_spec_; }
1205 private:
1206 template <typename Func> friend class Expectation;
1207
1208 typedef std::vector<internal::linked_ptr<Expectation<F> > > Expectations;
1209
1210 // Gets the internal::linked_ptr<ExpectationBase> object that co-owns 'exp'.
1211 internal::linked_ptr<ExpectationBase> GetLinkedExpectationBase(
1212 Expectation<F>* exp) {
1213 for (typename Expectations::const_iterator it = expectations_.begin();
1214 it != expectations_.end(); ++it) {
1215 if (it->get() == exp) {
1216 return *it;
1217 }
1218 }
1219
1220 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
1221 return internal::linked_ptr<ExpectationBase>(NULL);
1222 // The above statement is just to make the code compile, and will
1223 // never be executed.
1224 }
1225
1226 // Some utilities needed for implementing InvokeWith().
1227
1228 // Describes what default action will be performed for the given
1229 // arguments.
1230 // L = *
1231 void DescribeDefaultActionTo(const ArgumentTuple& args,
1232 ::std::ostream* os) const {
1233 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1234
1235 if (spec == NULL) {
1236 *os << (internal::type_equals<Result, void>::value ?
1237 "returning directly.\n" :
1238 "returning default value.\n");
1239 } else {
1240 *os << "taking default action specified at:\n"
1241 << spec->file() << ":" << spec->line() << ":\n";
1242 }
1243 }
1244
1245 // Writes a message that the call is uninteresting (i.e. neither
1246 // explicitly expected nor explicitly unexpected) to the given
1247 // ostream.
1248 // L < g_gmock_mutex
1249 void DescribeUninterestingCall(const ArgumentTuple& args,
1250 ::std::ostream* os) const {
1251 *os << "Uninteresting mock function call - ";
1252 DescribeDefaultActionTo(args, os);
1253 *os << " Function call: " << Name();
1254 UniversalPrinter<ArgumentTuple>::Print(args, os);
1255 }
1256
1257 // Critical section: We must find the matching expectation and the
1258 // corresponding action that needs to be taken in an ATOMIC
1259 // transaction. Otherwise another thread may call this mock
1260 // method in the middle and mess up the state.
1261 //
1262 // However, performing the action has to be left out of the critical
1263 // section. The reason is that we have no control on what the
1264 // action does (it can invoke an arbitrary user function or even a
1265 // mock function) and excessive locking could cause a dead lock.
1266 // L < g_gmock_mutex
1267 bool FindMatchingExpectationAndAction(
1268 const ArgumentTuple& args, Expectation<F>** exp, Action<F>* action,
1269 bool* is_excessive, ::std::ostream* what, ::std::ostream* why) {
1270 MutexLock l(&g_gmock_mutex);
1271 *exp = this->FindMatchingExpectationLocked(args);
1272 if (*exp == NULL) { // A match wasn't found.
1273 *action = DoDefault();
1274 this->FormatUnexpectedCallMessageLocked(args, what, why);
1275 return false;
1276 }
1277
1278 // This line must be done before calling GetActionForArguments(),
1279 // which will increment the call count for *exp and thus affect
1280 // its saturation status.
1281 *is_excessive = (*exp)->IsSaturated();
1282 *action = (*exp)->GetActionForArguments(this, args, what, why);
1283 return true;
1284 }
1285
1286 // Returns the expectation that matches the arguments, or NULL if no
1287 // expectation matches them.
1288 // L >= g_gmock_mutex
1289 Expectation<F>* FindMatchingExpectationLocked(
1290 const ArgumentTuple& args) const {
1291 g_gmock_mutex.AssertHeld();
1292 for (typename Expectations::const_reverse_iterator it =
1293 expectations_.rbegin();
1294 it != expectations_.rend(); ++it) {
1295 Expectation<F>* const exp = it->get();
1296 if (exp->ShouldHandleArguments(args)) {
1297 return exp;
1298 }
1299 }
1300 return NULL;
1301 }
1302
1303 // Returns a message that the arguments don't match any expectation.
1304 // L >= g_gmock_mutex
1305 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1306 ::std::ostream* os,
1307 ::std::ostream* why) const {
1308 g_gmock_mutex.AssertHeld();
1309 *os << "\nUnexpected mock function call - ";
1310 DescribeDefaultActionTo(args, os);
1311 PrintTriedExpectationsLocked(args, why);
1312 }
1313
1314 // Prints a list of expectations that have been tried against the
1315 // current mock function call.
1316 // L >= g_gmock_mutex
1317 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1318 ::std::ostream* why) const {
1319 g_gmock_mutex.AssertHeld();
1320 const int count = static_cast<int>(expectations_.size());
1321 *why << "Google Mock tried the following " << count << " "
1322 << (count == 1 ? "expectation, but it didn't match" :
1323 "expectations, but none matched")
1324 << ":\n";
1325 for (int i = 0; i < count; i++) {
1326 *why << "\n";
1327 expectations_[i]->DescribeLocationTo(why);
1328 if (count > 1) {
1329 *why << "tried expectation #" << i;
1330 }
1331 *why << "\n";
1332 expectations_[i]->DescribeMatchResultTo(args, why);
1333 expectations_[i]->DescribeCallCountTo(why);
1334 }
1335 }
1336
zhanyong.wandf35a762009-04-22 22:25:31 +00001337 // Address of the mock object this mock method belongs to. Only
1338 // valid after this mock method has been called or
1339 // ON_CALL/EXPECT_CALL has been invoked on it.
shiqiane35fdd92008-12-10 05:08:54 +00001340 const void* mock_obj_; // Protected by g_gmock_mutex.
1341
zhanyong.wandf35a762009-04-22 22:25:31 +00001342 // Name of the function being mocked. Only valid after this mock
1343 // method has been called.
shiqiane35fdd92008-12-10 05:08:54 +00001344 const char* name_; // Protected by g_gmock_mutex.
1345
1346 // The current spec (either default action spec or expectation spec)
1347 // being described on this function mocker.
1348 MockSpec<F> current_spec_;
1349
1350 // All default action specs for this function mocker.
1351 std::vector<DefaultActionSpec<F> > default_actions_;
1352 // All expectations for this function mocker.
1353 Expectations expectations_;
1354}; // class FunctionMockerBase
1355
1356#ifdef _MSC_VER
1357#pragma warning(pop) // Restores the warning state.
1358#endif // _MSV_VER
1359
1360// Implements methods of FunctionMockerBase.
1361
1362// Verifies that all expectations on this mock function have been
1363// satisfied. Reports one or more Google Test non-fatal failures and
1364// returns false if not.
1365// L >= g_gmock_mutex
1366template <typename F>
1367bool FunctionMockerBase<F>::VerifyAndClearExpectationsLocked() {
1368 g_gmock_mutex.AssertHeld();
1369 bool expectations_met = true;
1370 for (typename Expectations::const_iterator it = expectations_.begin();
1371 it != expectations_.end(); ++it) {
1372 Expectation<F>* const exp = it->get();
1373
1374 if (exp->IsOverSaturated()) {
1375 // There was an upper-bound violation. Since the error was
1376 // already reported when it occurred, there is no need to do
1377 // anything here.
1378 expectations_met = false;
1379 } else if (!exp->IsSatisfied()) {
1380 expectations_met = false;
1381 ::std::stringstream ss;
1382 ss << "Actual function call count doesn't match this expectation.\n";
1383 // No need to show the source file location of the expectation
1384 // in the description, as the Expect() call that follows already
1385 // takes care of it.
1386 exp->DescribeCallCountTo(&ss);
1387 Expect(false, exp->file(), exp->line(), ss.str());
1388 }
1389 }
1390 expectations_.clear();
1391 return expectations_met;
1392}
1393
1394// Reports an uninteresting call (whose description is in msg) in the
1395// manner specified by 'reaction'.
1396void ReportUninterestingCall(CallReaction reaction, const string& msg);
1397
1398// When an uninteresting or unexpected mock function is called, we
1399// want to print its return value to assist the user debugging. Since
1400// there's nothing to print when the function returns void, we need to
1401// specialize the logic of FunctionMockerBase<F>::InvokeWith() for
1402// void return values.
1403//
1404// C++ doesn't allow us to specialize a member function template
1405// unless we also specialize its enclosing class, so we had to let
1406// InvokeWith() delegate its work to a helper class InvokeWithHelper,
1407// which can then be specialized.
1408//
1409// Note that InvokeWithHelper must be a class template (as opposed to
1410// a function template), as only class templates can be partially
1411// specialized.
1412template <typename Result, typename F>
1413class InvokeWithHelper {
1414 public:
1415 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1416
1417 // Calculates the result of invoking the function mocked by mocker
1418 // with the given arguments, prints it, and returns it.
1419 // L < g_gmock_mutex
1420 static Result InvokeAndPrintResult(
1421 FunctionMockerBase<F>* mocker,
1422 const ArgumentTuple& args) {
1423 if (mocker->expectations_.size() == 0) {
1424 // No expectation is set on this mock method - we have an
1425 // uninteresting call.
1426
1427 // Warns about the uninteresting call.
1428 ::std::stringstream ss;
1429 mocker->DescribeUninterestingCall(args, &ss);
1430
1431 // We must get Google Mock's reaction on uninteresting calls
1432 // made on this mock object BEFORE performing the action,
1433 // because the action may DELETE the mock object and make the
1434 // following expression meaningless.
1435 const CallReaction reaction =
1436 Mock::GetReactionOnUninterestingCalls(mocker->MockObject());
1437
1438 // Calculates the function result.
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001439 Result result = mocker->PerformDefaultAction(args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001440
1441 // Prints the function result.
1442 ss << "\n Returns: ";
1443 UniversalPrinter<Result>::Print(result, &ss);
1444 ReportUninterestingCall(reaction, ss.str());
1445
1446 return result;
1447 }
1448
1449 bool is_excessive = false;
1450 ::std::stringstream ss;
1451 ::std::stringstream why;
zhanyong.wan6f147692009-03-03 06:44:08 +00001452 ::std::stringstream loc;
shiqiane35fdd92008-12-10 05:08:54 +00001453 Action<F> action;
1454 Expectation<F>* exp;
1455
1456 // The FindMatchingExpectationAndAction() function acquires and
1457 // releases g_gmock_mutex.
1458 const bool found = mocker->FindMatchingExpectationAndAction(
1459 args, &exp, &action, &is_excessive, &ss, &why);
1460 ss << " Function call: " << mocker->Name();
1461 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
zhanyong.wan6f147692009-03-03 06:44:08 +00001462 // In case the action deletes a piece of the expectation, we
1463 // generate the message beforehand.
1464 if (found && !is_excessive) {
1465 exp->DescribeLocationTo(&loc);
1466 }
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001467 Result result = action.IsDoDefault() ?
1468 mocker->PerformDefaultAction(args, ss.str())
shiqiane35fdd92008-12-10 05:08:54 +00001469 : action.Perform(args);
1470 ss << "\n Returns: ";
1471 UniversalPrinter<Result>::Print(result, &ss);
1472 ss << "\n" << why.str();
1473
1474 if (found) {
1475 if (is_excessive) {
1476 // We had an upper-bound violation and the failure message is in ss.
1477 Expect(false, exp->file(), exp->line(), ss.str());
1478 } else {
1479 // We had an expected call and the matching expectation is
1480 // described in ss.
shiqiane35fdd92008-12-10 05:08:54 +00001481 Log(INFO, loc.str() + ss.str(), 3);
1482 }
1483 } else {
1484 // No expectation matches this call - reports a failure.
1485 Expect(false, NULL, -1, ss.str());
1486 }
1487 return result;
1488 }
1489}; // class InvokeWithHelper
1490
1491// This specialization helps to implement
1492// FunctionMockerBase<F>::InvokeWith() for void-returning functions.
1493template <typename F>
1494class InvokeWithHelper<void, F> {
1495 public:
1496 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1497
1498 // Invokes the function mocked by mocker with the given arguments.
1499 // L < g_gmock_mutex
1500 static void InvokeAndPrintResult(FunctionMockerBase<F>* mocker,
1501 const ArgumentTuple& args) {
1502 const int count = static_cast<int>(mocker->expectations_.size());
1503 if (count == 0) {
1504 // No expectation is set on this mock method - we have an
1505 // uninteresting call.
1506 ::std::stringstream ss;
1507 mocker->DescribeUninterestingCall(args, &ss);
1508
1509 // We must get Google Mock's reaction on uninteresting calls
1510 // made on this mock object BEFORE performing the action,
1511 // because the action may DELETE the mock object and make the
1512 // following expression meaningless.
1513 const CallReaction reaction =
1514 Mock::GetReactionOnUninterestingCalls(mocker->MockObject());
1515
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001516 mocker->PerformDefaultAction(args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001517 ReportUninterestingCall(reaction, ss.str());
1518 return;
1519 }
1520
1521 bool is_excessive = false;
1522 ::std::stringstream ss;
1523 ::std::stringstream why;
zhanyong.wan6f147692009-03-03 06:44:08 +00001524 ::std::stringstream loc;
shiqiane35fdd92008-12-10 05:08:54 +00001525 Action<F> action;
1526 Expectation<F>* exp;
1527
1528 // The FindMatchingExpectationAndAction() function acquires and
1529 // releases g_gmock_mutex.
1530 const bool found = mocker->FindMatchingExpectationAndAction(
1531 args, &exp, &action, &is_excessive, &ss, &why);
1532 ss << " Function call: " << mocker->Name();
1533 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1534 ss << "\n" << why.str();
zhanyong.wan6f147692009-03-03 06:44:08 +00001535 // In case the action deletes a piece of the expectation, we
1536 // generate the message beforehand.
1537 if (found && !is_excessive) {
1538 exp->DescribeLocationTo(&loc);
1539 }
shiqiane35fdd92008-12-10 05:08:54 +00001540 if (action.IsDoDefault()) {
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001541 mocker->PerformDefaultAction(args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001542 } else {
1543 action.Perform(args);
1544 }
1545
1546 if (found) {
1547 // A matching expectation and corresponding action were found.
1548 if (is_excessive) {
1549 // We had an upper-bound violation and the failure message is in ss.
1550 Expect(false, exp->file(), exp->line(), ss.str());
1551 } else {
1552 // We had an expected call and the matching expectation is
1553 // described in ss.
shiqiane35fdd92008-12-10 05:08:54 +00001554 Log(INFO, loc.str() + ss.str(), 3);
1555 }
1556 } else {
1557 // No matching expectation was found - reports an error.
1558 Expect(false, NULL, -1, ss.str());
1559 }
1560 }
1561}; // class InvokeWithHelper<void, F>
1562
1563} // namespace internal
1564
1565// The style guide prohibits "using" statements in a namespace scope
1566// inside a header file. However, the MockSpec class template is
1567// meant to be defined in the ::testing namespace. The following line
1568// is just a trick for working around a bug in MSVC 8.0, which cannot
1569// handle it if we define MockSpec in ::testing.
1570using internal::MockSpec;
1571
1572// Const(x) is a convenient function for obtaining a const reference
1573// to x. This is useful for setting expectations on an overloaded
1574// const mock method, e.g.
1575//
1576// class MockFoo : public FooInterface {
1577// public:
1578// MOCK_METHOD0(Bar, int());
1579// MOCK_CONST_METHOD0(Bar, int&());
1580// };
1581//
1582// MockFoo foo;
1583// // Expects a call to non-const MockFoo::Bar().
1584// EXPECT_CALL(foo, Bar());
1585// // Expects a call to const MockFoo::Bar().
1586// EXPECT_CALL(Const(foo), Bar());
1587template <typename T>
1588inline const T& Const(const T& x) { return x; }
1589
1590} // namespace testing
1591
1592// A separate macro is required to avoid compile errors when the name
1593// of the method used in call is a result of macro expansion.
1594// See CompilesWithMethodNameExpandedFromMacro tests in
1595// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001596#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001597 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1598 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001599#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001600
zhanyong.wane0d051e2009-02-19 00:33:37 +00001601#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001602 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001603#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001604
1605#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_