blob: 3b4c08534610f6634d8c3445a3aad4f5807b9a79 [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
249 // Verifies and clears all expectations on the given mock object.
250 // If the expectations aren't satisfied, generates one or more
251 // Google Test non-fatal failures and returns false.
252 static bool VerifyAndClearExpectations(void* mock_obj);
253
254 // Verifies all expectations on the given mock object and clears its
255 // default actions and expectations. Returns true iff the
256 // verification was successful.
257 static bool VerifyAndClear(void* mock_obj);
258 private:
259 // Needed for a function mocker to register itself (so that we know
260 // how to clear a mock object).
261 template <typename F>
262 friend class internal::FunctionMockerBase;
263
264 template <typename R, typename Args>
265 friend class internal::InvokeWithHelper;
266
267 template <typename M>
268 friend class NiceMock;
269
270 template <typename M>
271 friend class StrictMock;
272
273 // Tells Google Mock to allow uninteresting calls on the given mock
274 // object.
275 // L < g_gmock_mutex
276 static void AllowUninterestingCalls(const void* mock_obj);
277
278 // Tells Google Mock to warn the user about uninteresting calls on
279 // the given mock object.
280 // L < g_gmock_mutex
281 static void WarnUninterestingCalls(const void* mock_obj);
282
283 // Tells Google Mock to fail uninteresting calls on the given mock
284 // object.
285 // L < g_gmock_mutex
286 static void FailUninterestingCalls(const void* mock_obj);
287
288 // Tells Google Mock the given mock object is being destroyed and
289 // its entry in the call-reaction table should be removed.
290 // L < g_gmock_mutex
291 static void UnregisterCallReaction(const void* mock_obj);
292
293 // Returns the reaction Google Mock will have on uninteresting calls
294 // made on the given mock object.
295 // L < g_gmock_mutex
296 static internal::CallReaction GetReactionOnUninterestingCalls(
297 const void* mock_obj);
298
299 // Verifies that all expectations on the given mock object have been
300 // satisfied. Reports one or more Google Test non-fatal failures
301 // and returns false if not.
302 // L >= g_gmock_mutex
303 static bool VerifyAndClearExpectationsLocked(void* mock_obj);
304
305 // Clears all ON_CALL()s set on the given mock object.
306 // L >= g_gmock_mutex
307 static void ClearDefaultActionsLocked(void* mock_obj);
308
309 // Registers a mock object and a mock method it owns.
310 // L < g_gmock_mutex
311 static void Register(const void* mock_obj,
312 internal::UntypedFunctionMockerBase* mocker);
313
314 // Unregisters a mock method; removes the owning mock object from
315 // the registry when the last mock method associated with it has
316 // been unregistered. This is called only in the destructor of
317 // FunctionMockerBase.
318 // L >= g_gmock_mutex
319 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
320}; // class Mock
321
322// Sequence objects are used by a user to specify the relative order
323// in which the expectations should match. They are copyable (we rely
324// on the compiler-defined copy constructor and assignment operator).
325class Sequence {
326 public:
327 // Constructs an empty sequence.
328 Sequence()
329 : last_expectation_(
330 new internal::linked_ptr<internal::ExpectationBase>(NULL)) {}
331
332 // Adds an expectation to this sequence. The caller must ensure
333 // that no other thread is accessing this Sequence object.
334 void AddExpectation(
335 const internal::linked_ptr<internal::ExpectationBase>& expectation) const;
336 private:
337 // The last expectation in this sequence. We use a nested
338 // linked_ptr here because:
339 // - Sequence objects are copyable, and we want the copies to act
340 // as aliases. The outer linked_ptr allows the copies to co-own
341 // and share the same state.
342 // - An Expectation object is co-owned (via linked_ptr) by its
343 // FunctionMocker and its successors (other Expectation objects).
344 // Hence the inner linked_ptr.
345 internal::linked_ptr<internal::linked_ptr<internal::ExpectationBase> >
346 last_expectation_;
347}; // class Sequence
348
349// An object of this type causes all EXPECT_CALL() statements
350// encountered in its scope to be put in an anonymous sequence. The
351// work is done in the constructor and destructor. You should only
352// create an InSequence object on the stack.
353//
354// The sole purpose for this class is to support easy definition of
355// sequential expectations, e.g.
356//
357// {
358// InSequence dummy; // The name of the object doesn't matter.
359//
360// // The following expectations must match in the order they appear.
361// EXPECT_CALL(a, Bar())...;
362// EXPECT_CALL(a, Baz())...;
363// ...
364// EXPECT_CALL(b, Xyz())...;
365// }
366//
367// You can create InSequence objects in multiple threads, as long as
368// they are used to affect different mock objects. The idea is that
369// each thread can create and set up its own mocks as if it's the only
370// thread. However, for clarity of your tests we recommend you to set
371// up mocks in the main thread unless you have a good reason not to do
372// so.
373class InSequence {
374 public:
375 InSequence();
376 ~InSequence();
377 private:
378 bool sequence_created_;
379
380 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wane0d051e2009-02-19 00:33:37 +0000381} GMOCK_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000382
383namespace internal {
384
385// Points to the implicit sequence introduced by a living InSequence
386// object (if any) in the current thread or NULL.
387extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
388
389// Base class for implementing expectations.
390//
391// There are two reasons for having a type-agnostic base class for
392// Expectation:
393//
394// 1. We need to store collections of expectations of different
395// types (e.g. all pre-requisites of a particular expectation, all
396// expectations in a sequence). Therefore these expectation objects
397// must share a common base class.
398//
399// 2. We can avoid binary code bloat by moving methods not depending
400// on the template argument of Expectation to the base class.
401//
402// This class is internal and mustn't be used by user code directly.
403class ExpectationBase {
404 public:
405 ExpectationBase(const char* file, int line);
406
407 virtual ~ExpectationBase();
408
409 // Where in the source file was the expectation spec defined?
410 const char* file() const { return file_; }
411 int line() const { return line_; }
412
413 // Returns the cardinality specified in the expectation spec.
414 const Cardinality& cardinality() const { return cardinality_; }
415
416 // Describes the source file location of this expectation.
417 void DescribeLocationTo(::std::ostream* os) const {
418 *os << file() << ":" << line() << ": ";
419 }
420
421 // Describes how many times a function call matching this
422 // expectation has occurred.
423 // L >= g_gmock_mutex
424 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
425 protected:
426 typedef std::set<linked_ptr<ExpectationBase>,
427 LinkedPtrLessThan<ExpectationBase> >
428 ExpectationBaseSet;
429
430 enum Clause {
431 // Don't change the order of the enum members!
432 NONE,
433 WITH_ARGUMENTS,
434 TIMES,
435 IN_SEQUENCE,
436 WILL_ONCE,
437 WILL_REPEATEDLY,
438 RETIRES_ON_SATURATION,
439 };
440
441 // Asserts that the EXPECT_CALL() statement has the given property.
442 void AssertSpecProperty(bool property, const string& failure_message) const {
443 Assert(property, file_, line_, failure_message);
444 }
445
446 // Expects that the EXPECT_CALL() statement has the given property.
447 void ExpectSpecProperty(bool property, const string& failure_message) const {
448 Expect(property, file_, line_, failure_message);
449 }
450
451 // Explicitly specifies the cardinality of this expectation. Used
452 // by the subclasses to implement the .Times() clause.
453 void SpecifyCardinality(const Cardinality& cardinality);
454
455 // Returns true iff the user specified the cardinality explicitly
456 // using a .Times().
457 bool cardinality_specified() const { return cardinality_specified_; }
458
459 // Sets the cardinality of this expectation spec.
460 void set_cardinality(const Cardinality& cardinality) {
461 cardinality_ = cardinality;
462 }
463
464 // The following group of methods should only be called after the
465 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
466 // the current thread.
467
468 // Retires all pre-requisites of this expectation.
469 // L >= g_gmock_mutex
470 void RetireAllPreRequisites();
471
472 // Returns true iff this expectation is retired.
473 // L >= g_gmock_mutex
474 bool is_retired() const {
475 g_gmock_mutex.AssertHeld();
476 return retired_;
477 }
478
479 // Retires this expectation.
480 // L >= g_gmock_mutex
481 void Retire() {
482 g_gmock_mutex.AssertHeld();
483 retired_ = true;
484 }
485
486 // Returns true iff this expectation is satisfied.
487 // L >= g_gmock_mutex
488 bool IsSatisfied() const {
489 g_gmock_mutex.AssertHeld();
490 return cardinality().IsSatisfiedByCallCount(call_count_);
491 }
492
493 // Returns true iff this expectation is saturated.
494 // L >= g_gmock_mutex
495 bool IsSaturated() const {
496 g_gmock_mutex.AssertHeld();
497 return cardinality().IsSaturatedByCallCount(call_count_);
498 }
499
500 // Returns true iff this expectation is over-saturated.
501 // L >= g_gmock_mutex
502 bool IsOverSaturated() const {
503 g_gmock_mutex.AssertHeld();
504 return cardinality().IsOverSaturatedByCallCount(call_count_);
505 }
506
507 // Returns true iff all pre-requisites of this expectation are satisfied.
508 // L >= g_gmock_mutex
509 bool AllPrerequisitesAreSatisfied() const;
510
511 // Adds unsatisfied pre-requisites of this expectation to 'result'.
512 // L >= g_gmock_mutex
513 void FindUnsatisfiedPrerequisites(ExpectationBaseSet* result) const;
514
515 // Returns the number this expectation has been invoked.
516 // L >= g_gmock_mutex
517 int call_count() const {
518 g_gmock_mutex.AssertHeld();
519 return call_count_;
520 }
521
522 // Increments the number this expectation has been invoked.
523 // L >= g_gmock_mutex
524 void IncrementCallCount() {
525 g_gmock_mutex.AssertHeld();
526 call_count_++;
527 }
528
529 private:
530 friend class ::testing::Sequence;
531 friend class ::testing::internal::ExpectationTester;
532
533 template <typename Function>
534 friend class Expectation;
535
536 // This group of fields are part of the spec and won't change after
537 // an EXPECT_CALL() statement finishes.
538 const char* file_; // The file that contains the expectation.
539 int line_; // The line number of the expectation.
540 // True iff the cardinality is specified explicitly.
541 bool cardinality_specified_;
542 Cardinality cardinality_; // The cardinality of the expectation.
543 // The immediate pre-requisites of this expectation. We use
544 // linked_ptr in the set because we want an Expectation object to be
545 // co-owned by its FunctionMocker and its successors. This allows
546 // multiple mock objects to be deleted at different times.
547 ExpectationBaseSet immediate_prerequisites_;
548
549 // This group of fields are the current state of the expectation,
550 // and can change as the mock function is called.
551 int call_count_; // How many times this expectation has been invoked.
552 bool retired_; // True iff this expectation has retired.
553}; // class ExpectationBase
554
555// Impements an expectation for the given function type.
556template <typename F>
557class Expectation : public ExpectationBase {
558 public:
559 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
560 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
561 typedef typename Function<F>::Result Result;
562
563 Expectation(FunctionMockerBase<F>* owner, const char* file, int line,
564 const ArgumentMatcherTuple& m)
565 : ExpectationBase(file, line),
566 owner_(owner),
567 matchers_(m),
568 extra_matcher_(_),
569 repeated_action_specified_(false),
570 repeated_action_(DoDefault()),
571 retires_on_saturation_(false),
572 last_clause_(NONE),
573 action_count_checked_(false) {}
574
575 virtual ~Expectation() {
576 // Check the validity of the action count if it hasn't been done
577 // yet (for example, if the expectation was never used).
578 CheckActionCountIfNotDone();
579 }
580
581 // Implements the .WithArguments() clause.
582 Expectation& WithArguments(const Matcher<const ArgumentTuple&>& m) {
583 if (last_clause_ == WITH_ARGUMENTS) {
584 ExpectSpecProperty(false,
585 ".WithArguments() cannot appear "
586 "more than once in an EXPECT_CALL().");
587 } else {
588 ExpectSpecProperty(last_clause_ < WITH_ARGUMENTS,
589 ".WithArguments() must be the first "
590 "clause in an EXPECT_CALL().");
591 }
592 last_clause_ = WITH_ARGUMENTS;
593
594 extra_matcher_ = m;
595 return *this;
596 }
597
598 // Implements the .Times() clause.
599 Expectation& Times(const Cardinality& cardinality) {
600 if (last_clause_ ==TIMES) {
601 ExpectSpecProperty(false,
602 ".Times() cannot appear "
603 "more than once in an EXPECT_CALL().");
604 } else {
605 ExpectSpecProperty(last_clause_ < TIMES,
606 ".Times() cannot appear after "
607 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
608 "or .RetiresOnSaturation().");
609 }
610 last_clause_ = TIMES;
611
612 ExpectationBase::SpecifyCardinality(cardinality);
613 return *this;
614 }
615
616 // Implements the .Times() clause.
617 Expectation& Times(int n) {
618 return Times(Exactly(n));
619 }
620
621 // Implements the .InSequence() clause.
622 Expectation& InSequence(const Sequence& s) {
623 ExpectSpecProperty(last_clause_ <= IN_SEQUENCE,
624 ".InSequence() cannot appear after .WillOnce(),"
625 " .WillRepeatedly(), or "
626 ".RetiresOnSaturation().");
627 last_clause_ = IN_SEQUENCE;
628
629 s.AddExpectation(owner_->GetLinkedExpectationBase(this));
630 return *this;
631 }
632 Expectation& InSequence(const Sequence& s1, const Sequence& s2) {
633 return InSequence(s1).InSequence(s2);
634 }
635 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
636 const Sequence& s3) {
637 return InSequence(s1, s2).InSequence(s3);
638 }
639 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
640 const Sequence& s3, const Sequence& s4) {
641 return InSequence(s1, s2, s3).InSequence(s4);
642 }
643 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
644 const Sequence& s3, const Sequence& s4,
645 const Sequence& s5) {
646 return InSequence(s1, s2, s3, s4).InSequence(s5);
647 }
648
649 // Implements the .WillOnce() clause.
650 Expectation& WillOnce(const Action<F>& action) {
651 ExpectSpecProperty(last_clause_ <= WILL_ONCE,
652 ".WillOnce() cannot appear after "
653 ".WillRepeatedly() or .RetiresOnSaturation().");
654 last_clause_ = WILL_ONCE;
655
656 actions_.push_back(action);
657 if (!cardinality_specified()) {
658 set_cardinality(Exactly(static_cast<int>(actions_.size())));
659 }
660 return *this;
661 }
662
663 // Implements the .WillRepeatedly() clause.
664 Expectation& WillRepeatedly(const Action<F>& action) {
665 if (last_clause_ == WILL_REPEATEDLY) {
666 ExpectSpecProperty(false,
667 ".WillRepeatedly() cannot appear "
668 "more than once in an EXPECT_CALL().");
669 } else {
670 ExpectSpecProperty(last_clause_ < WILL_REPEATEDLY,
671 ".WillRepeatedly() cannot appear "
672 "after .RetiresOnSaturation().");
673 }
674 last_clause_ = WILL_REPEATEDLY;
675 repeated_action_specified_ = true;
676
677 repeated_action_ = action;
678 if (!cardinality_specified()) {
679 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
680 }
681
682 // Now that no more action clauses can be specified, we check
683 // whether their count makes sense.
684 CheckActionCountIfNotDone();
685 return *this;
686 }
687
688 // Implements the .RetiresOnSaturation() clause.
689 Expectation& RetiresOnSaturation() {
690 ExpectSpecProperty(last_clause_ < RETIRES_ON_SATURATION,
691 ".RetiresOnSaturation() cannot appear "
692 "more than once.");
693 last_clause_ = RETIRES_ON_SATURATION;
694 retires_on_saturation_ = true;
695
696 // Now that no more action clauses can be specified, we check
697 // whether their count makes sense.
698 CheckActionCountIfNotDone();
699 return *this;
700 }
701
702 // Returns the matchers for the arguments as specified inside the
703 // EXPECT_CALL() macro.
704 const ArgumentMatcherTuple& matchers() const {
705 return matchers_;
706 }
707
708 // Returns the matcher specified by the .WithArguments() clause.
709 const Matcher<const ArgumentTuple&>& extra_matcher() const {
710 return extra_matcher_;
711 }
712
713 // Returns the sequence of actions specified by the .WillOnce() clause.
714 const std::vector<Action<F> >& actions() const { return actions_; }
715
716 // Returns the action specified by the .WillRepeatedly() clause.
717 const Action<F>& repeated_action() const { return repeated_action_; }
718
719 // Returns true iff the .RetiresOnSaturation() clause was specified.
720 bool retires_on_saturation() const { return retires_on_saturation_; }
721
722 // Describes how many times a function call matching this
723 // expectation has occurred (implements
724 // ExpectationBase::DescribeCallCountTo()).
725 // L >= g_gmock_mutex
726 virtual void DescribeCallCountTo(::std::ostream* os) const {
727 g_gmock_mutex.AssertHeld();
728
729 // Describes how many times the function is expected to be called.
730 *os << " Expected: to be ";
731 cardinality().DescribeTo(os);
732 *os << "\n Actual: ";
733 Cardinality::DescribeActualCallCountTo(call_count(), os);
734
735 // Describes the state of the expectation (e.g. is it satisfied?
736 // is it active?).
737 *os << " - " << (IsOverSaturated() ? "over-saturated" :
738 IsSaturated() ? "saturated" :
739 IsSatisfied() ? "satisfied" : "unsatisfied")
740 << " and "
741 << (is_retired() ? "retired" : "active");
742 }
743 private:
744 template <typename Function>
745 friend class FunctionMockerBase;
746
747 template <typename R, typename Function>
748 friend class InvokeWithHelper;
749
750 // The following methods will be called only after the EXPECT_CALL()
751 // statement finishes and when the current thread holds
752 // g_gmock_mutex.
753
754 // Returns true iff this expectation matches the given arguments.
755 // L >= g_gmock_mutex
756 bool Matches(const ArgumentTuple& args) const {
757 g_gmock_mutex.AssertHeld();
758 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
759 }
760
761 // Returns true iff this expectation should handle the given arguments.
762 // L >= g_gmock_mutex
763 bool ShouldHandleArguments(const ArgumentTuple& args) const {
764 g_gmock_mutex.AssertHeld();
765
766 // In case the action count wasn't checked when the expectation
767 // was defined (e.g. if this expectation has no WillRepeatedly()
768 // or RetiresOnSaturation() clause), we check it when the
769 // expectation is used for the first time.
770 CheckActionCountIfNotDone();
771 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
772 }
773
774 // Describes the result of matching the arguments against this
775 // expectation to the given ostream.
776 // L >= g_gmock_mutex
777 void DescribeMatchResultTo(const ArgumentTuple& args,
778 ::std::ostream* os) const {
779 g_gmock_mutex.AssertHeld();
780
781 if (is_retired()) {
782 *os << " Expected: the expectation is active\n"
783 << " Actual: it is retired\n";
784 } else if (!Matches(args)) {
785 if (!TupleMatches(matchers_, args)) {
786 DescribeMatchFailureTupleTo(matchers_, args, os);
787 }
788 if (!extra_matcher_.Matches(args)) {
789 *os << " Expected: ";
790 extra_matcher_.DescribeTo(os);
791 *os << "\n Actual: false";
792
793 internal::ExplainMatchResultAsNeededTo<const ArgumentTuple&>(
794 extra_matcher_, args, os);
795 *os << "\n";
796 }
797 } else if (!AllPrerequisitesAreSatisfied()) {
798 *os << " Expected: all pre-requisites are satisfied\n"
799 << " Actual: the following immediate pre-requisites "
800 << "are not satisfied:\n";
801 ExpectationBaseSet unsatisfied_prereqs;
802 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
803 int i = 0;
804 for (ExpectationBaseSet::const_iterator it = unsatisfied_prereqs.begin();
805 it != unsatisfied_prereqs.end(); ++it) {
806 (*it)->DescribeLocationTo(os);
807 *os << "pre-requisite #" << i++ << "\n";
808 }
809 *os << " (end of pre-requisites)\n";
810 } else {
811 // This line is here just for completeness' sake. It will never
812 // be executed as currently the DescribeMatchResultTo() function
813 // is called only when the mock function call does NOT match the
814 // expectation.
815 *os << "The call matches the expectation.\n";
816 }
817 }
818
819 // Returns the action that should be taken for the current invocation.
820 // L >= g_gmock_mutex
821 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
822 const ArgumentTuple& args) const {
823 g_gmock_mutex.AssertHeld();
824 const int count = call_count();
825 Assert(count >= 1, __FILE__, __LINE__,
826 "call_count() is <= 0 when GetCurrentAction() is "
827 "called - this should never happen.");
828
829 const int action_count = static_cast<int>(actions().size());
830 if (action_count > 0 && !repeated_action_specified_ &&
831 count > action_count) {
832 // If there is at least one WillOnce() and no WillRepeatedly(),
833 // we warn the user when the WillOnce() clauses ran out.
834 ::std::stringstream ss;
835 DescribeLocationTo(&ss);
836 ss << "Actions ran out.\n"
837 << "Called " << count << " times, but only "
838 << action_count << " WillOnce()"
839 << (action_count == 1 ? " is" : "s are") << " specified - ";
840 mocker->DescribeDefaultActionTo(args, &ss);
841 Log(WARNING, ss.str(), 1);
842 }
843
844 return count <= action_count ? actions()[count - 1] : repeated_action();
845 }
846
847 // Given the arguments of a mock function call, if the call will
848 // over-saturate this expectation, returns the default action;
849 // otherwise, returns the next action in this expectation. Also
850 // describes *what* happened to 'what', and explains *why* Google
851 // Mock does it to 'why'. This method is not const as it calls
852 // IncrementCallCount().
853 // L >= g_gmock_mutex
854 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
855 const ArgumentTuple& args,
856 ::std::ostream* what,
857 ::std::ostream* why) {
858 g_gmock_mutex.AssertHeld();
859 if (IsSaturated()) {
860 // We have an excessive call.
861 IncrementCallCount();
862 *what << "Mock function called more times than expected - ";
863 mocker->DescribeDefaultActionTo(args, what);
864 DescribeCallCountTo(why);
865
866 // TODO(wan): allow the user to control whether unexpected calls
867 // should fail immediately or continue using a flag
868 // --gmock_unexpected_calls_are_fatal.
869 return DoDefault();
870 }
871
872 IncrementCallCount();
873 RetireAllPreRequisites();
874
875 if (retires_on_saturation() && IsSaturated()) {
876 Retire();
877 }
878
879 // Must be done after IncrementCount()!
880 *what << "Expected mock function call.\n";
881 return GetCurrentAction(mocker, args);
882 }
883
884 // Checks the action count (i.e. the number of WillOnce() and
885 // WillRepeatedly() clauses) against the cardinality if this hasn't
886 // been done before. Prints a warning if there are too many or too
887 // few actions.
888 // L < mutex_
889 void CheckActionCountIfNotDone() const {
890 bool should_check = false;
891 {
892 MutexLock l(&mutex_);
893 if (!action_count_checked_) {
894 action_count_checked_ = true;
895 should_check = true;
896 }
897 }
898
899 if (should_check) {
900 if (!cardinality_specified_) {
901 // The cardinality was inferred - no need to check the action
902 // count against it.
903 return;
904 }
905
906 // The cardinality was explicitly specified.
907 const int action_count = static_cast<int>(actions_.size());
908 const int upper_bound = cardinality().ConservativeUpperBound();
909 const int lower_bound = cardinality().ConservativeLowerBound();
910 bool too_many; // True if there are too many actions, or false
911 // if there are too few.
912 if (action_count > upper_bound ||
913 (action_count == upper_bound && repeated_action_specified_)) {
914 too_many = true;
915 } else if (0 < action_count && action_count < lower_bound &&
916 !repeated_action_specified_) {
917 too_many = false;
918 } else {
919 return;
920 }
921
922 ::std::stringstream ss;
923 DescribeLocationTo(&ss);
924 ss << "Too " << (too_many ? "many" : "few")
925 << " actions specified.\n"
926 << "Expected to be ";
927 cardinality().DescribeTo(&ss);
928 ss << ", but has " << (too_many ? "" : "only ")
929 << action_count << " WillOnce()"
930 << (action_count == 1 ? "" : "s");
931 if (repeated_action_specified_) {
932 ss << " and a WillRepeatedly()";
933 }
934 ss << ".";
935 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
936 }
937 }
938
939 // All the fields below won't change once the EXPECT_CALL()
940 // statement finishes.
941 FunctionMockerBase<F>* const owner_;
942 ArgumentMatcherTuple matchers_;
943 Matcher<const ArgumentTuple&> extra_matcher_;
944 std::vector<Action<F> > actions_;
945 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
946 Action<F> repeated_action_;
947 bool retires_on_saturation_;
948 Clause last_clause_;
949 mutable bool action_count_checked_; // Under mutex_.
950 mutable Mutex mutex_; // Protects action_count_checked_.
951}; // class Expectation
952
953// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
954// specifying the default behavior of, or expectation on, a mock
955// function.
956
957// Note: class MockSpec really belongs to the ::testing namespace.
958// However if we define it in ::testing, MSVC will complain when
959// classes in ::testing::internal declare it as a friend class
960// template. To workaround this compiler bug, we define MockSpec in
961// ::testing::internal and import it into ::testing.
962
963template <typename F>
964class MockSpec {
965 public:
966 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
967 typedef typename internal::Function<F>::ArgumentMatcherTuple
968 ArgumentMatcherTuple;
969
970 // Constructs a MockSpec object, given the function mocker object
971 // that the spec is associated with.
972 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
973 : function_mocker_(function_mocker) {}
974
975 // Adds a new default action spec to the function mocker and returns
976 // the newly created spec.
977 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
978 const char* file, int line, const char* obj, const char* call) {
979 LogWithLocation(internal::INFO, file, line,
980 string("ON_CALL(") + obj + ", " + call + ") invoked");
981 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
982 }
983
984 // Adds a new expectation spec to the function mocker and returns
985 // the newly created spec.
986 internal::Expectation<F>& InternalExpectedAt(
987 const char* file, int line, const char* obj, const char* call) {
988 LogWithLocation(internal::INFO, file, line,
989 string("EXPECT_CALL(") + obj + ", " + call + ") invoked");
990 return function_mocker_->AddNewExpectation(file, line, matchers_);
991 }
992
993 private:
994 template <typename Function>
995 friend class internal::FunctionMocker;
996
997 void SetMatchers(const ArgumentMatcherTuple& matchers) {
998 matchers_ = matchers;
999 }
1000
1001 // Logs a message including file and line number information.
1002 void LogWithLocation(testing::internal::LogSeverity severity,
1003 const char* file, int line,
1004 const string& message) {
1005 ::std::ostringstream s;
1006 s << file << ":" << line << ": " << message << ::std::endl;
1007 Log(severity, s.str(), 0);
1008 }
1009
1010 // The function mocker that owns this spec.
1011 internal::FunctionMockerBase<F>* const function_mocker_;
1012 // The argument matchers specified in the spec.
1013 ArgumentMatcherTuple matchers_;
1014}; // class MockSpec
1015
1016// MSVC warns about using 'this' in base member initializer list, so
1017// we need to temporarily disable the warning. We have to do it for
1018// the entire class to suppress the warning, even though it's about
1019// the constructor only.
1020
1021#ifdef _MSC_VER
1022#pragma warning(push) // Saves the current warning state.
1023#pragma warning(disable:4355) // Temporarily disables warning 4355.
1024#endif // _MSV_VER
1025
1026// The base of the function mocker class for the given function type.
1027// We put the methods in this class instead of its child to avoid code
1028// bloat.
1029template <typename F>
1030class FunctionMockerBase : public UntypedFunctionMockerBase {
1031 public:
1032 typedef typename Function<F>::Result Result;
1033 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1034 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1035
1036 FunctionMockerBase() : mock_obj_(NULL), name_(""), current_spec_(this) {}
1037
1038 // The destructor verifies that all expectations on this mock
1039 // function have been satisfied. If not, it will report Google Test
1040 // non-fatal failures for the violations.
1041 // L < g_gmock_mutex
1042 virtual ~FunctionMockerBase() {
1043 MutexLock l(&g_gmock_mutex);
1044 VerifyAndClearExpectationsLocked();
1045 Mock::UnregisterLocked(this);
1046 }
1047
1048 // Returns the ON_CALL spec that matches this mock function with the
1049 // given arguments; returns NULL if no matching ON_CALL is found.
1050 // L = *
1051 const DefaultActionSpec<F>* FindDefaultActionSpec(
1052 const ArgumentTuple& args) const {
1053 for (typename std::vector<DefaultActionSpec<F> >::const_reverse_iterator it
1054 = default_actions_.rbegin();
1055 it != default_actions_.rend(); ++it) {
1056 const DefaultActionSpec<F>& spec = *it;
1057 if (spec.Matches(args))
1058 return &spec;
1059 }
1060
1061 return NULL;
1062 }
1063
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001064 // Performs the default action of this mock function on the given arguments
1065 // and returns the result. Asserts with a helpful call descrption if there is
1066 // no valid return value. This method doesn't depend on the mutable state of
1067 // this object, and thus can be called concurrently without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001068 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001069 Result PerformDefaultAction(const ArgumentTuple& args,
1070 const string& call_description) const {
shiqiane35fdd92008-12-10 05:08:54 +00001071 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001072 if (spec != NULL) {
1073 return spec->GetAction().Perform(args);
1074 }
1075 Assert(DefaultValue<Result>::Exists(), "", -1,
1076 call_description + "\n The mock function has no default action "
1077 "set, and its return type has no default value set.");
1078 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001079 }
1080
1081 // Registers this function mocker and the mock object owning it;
1082 // returns a reference to the function mocker object. This is only
1083 // called by the ON_CALL() and EXPECT_CALL() macros.
1084 FunctionMocker<F>& RegisterOwner(const void* mock_obj) {
1085 Mock::Register(mock_obj, this);
zhanyong.wan946bc642009-03-31 00:05:30 +00001086 return *::testing::internal::down_cast<FunctionMocker<F>*>(this);
shiqiane35fdd92008-12-10 05:08:54 +00001087 }
1088
1089 // The following two functions are from UntypedFunctionMockerBase.
1090
1091 // Verifies that all expectations on this mock function have been
1092 // satisfied. Reports one or more Google Test non-fatal failures
1093 // and returns false if not.
1094 // L >= g_gmock_mutex
1095 virtual bool VerifyAndClearExpectationsLocked();
1096
1097 // Clears the ON_CALL()s set on this mock function.
1098 // L >= g_gmock_mutex
1099 virtual void ClearDefaultActionsLocked() {
1100 g_gmock_mutex.AssertHeld();
1101 default_actions_.clear();
1102 }
1103
1104 // Sets the name of the function being mocked. Will be called upon
1105 // each invocation of this mock function.
1106 // L < g_gmock_mutex
1107 void SetOwnerAndName(const void* mock_obj, const char* name) {
1108 // We protect name_ under g_gmock_mutex in case this mock function
1109 // is called from two threads concurrently.
1110 MutexLock l(&g_gmock_mutex);
1111 mock_obj_ = mock_obj;
1112 name_ = name;
1113 }
1114
1115 // Returns the address of the mock object this method belongs to.
1116 // Must be called after SetOwnerAndName() has been called.
1117 // L < g_gmock_mutex
1118 const void* MockObject() const {
1119 const void* mock_obj;
1120 {
1121 // We protect mock_obj_ under g_gmock_mutex in case this mock
1122 // function is called from two threads concurrently.
1123 MutexLock l(&g_gmock_mutex);
1124 mock_obj = mock_obj_;
1125 }
1126 return mock_obj;
1127 }
1128
1129 // Returns the name of the function being mocked. Must be called
1130 // after SetOwnerAndName() has been called.
1131 // L < g_gmock_mutex
1132 const char* Name() const {
1133 const char* name;
1134 {
1135 // We protect name_ under g_gmock_mutex in case this mock
1136 // function is called from two threads concurrently.
1137 MutexLock l(&g_gmock_mutex);
1138 name = name_;
1139 }
1140 return name;
1141 }
1142 protected:
1143 template <typename Function>
1144 friend class MockSpec;
1145
1146 template <typename R, typename Function>
1147 friend class InvokeWithHelper;
1148
1149 // Returns the result of invoking this mock function with the given
1150 // arguments. This function can be safely called from multiple
1151 // threads concurrently.
1152 // L < g_gmock_mutex
1153 Result InvokeWith(const ArgumentTuple& args) {
1154 return InvokeWithHelper<Result, F>::InvokeAndPrintResult(this, args);
1155 }
1156
1157 // Adds and returns a default action spec for this mock function.
1158 DefaultActionSpec<F>& AddNewDefaultActionSpec(
1159 const char* file, int line,
1160 const ArgumentMatcherTuple& m) {
1161 default_actions_.push_back(DefaultActionSpec<F>(file, line, m));
1162 return default_actions_.back();
1163 }
1164
1165 // Adds and returns an expectation spec for this mock function.
1166 Expectation<F>& AddNewExpectation(
1167 const char* file, int line,
1168 const ArgumentMatcherTuple& m) {
1169 const linked_ptr<Expectation<F> > expectation(
1170 new Expectation<F>(this, file, line, m));
1171 expectations_.push_back(expectation);
1172
1173 // Adds this expectation into the implicit sequence if there is one.
1174 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1175 if (implicit_sequence != NULL) {
1176 implicit_sequence->AddExpectation(expectation);
1177 }
1178
1179 return *expectation;
1180 }
1181
1182 // The current spec (either default action spec or expectation spec)
1183 // being described on this function mocker.
1184 MockSpec<F>& current_spec() { return current_spec_; }
1185 private:
1186 template <typename Func> friend class Expectation;
1187
1188 typedef std::vector<internal::linked_ptr<Expectation<F> > > Expectations;
1189
1190 // Gets the internal::linked_ptr<ExpectationBase> object that co-owns 'exp'.
1191 internal::linked_ptr<ExpectationBase> GetLinkedExpectationBase(
1192 Expectation<F>* exp) {
1193 for (typename Expectations::const_iterator it = expectations_.begin();
1194 it != expectations_.end(); ++it) {
1195 if (it->get() == exp) {
1196 return *it;
1197 }
1198 }
1199
1200 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
1201 return internal::linked_ptr<ExpectationBase>(NULL);
1202 // The above statement is just to make the code compile, and will
1203 // never be executed.
1204 }
1205
1206 // Some utilities needed for implementing InvokeWith().
1207
1208 // Describes what default action will be performed for the given
1209 // arguments.
1210 // L = *
1211 void DescribeDefaultActionTo(const ArgumentTuple& args,
1212 ::std::ostream* os) const {
1213 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1214
1215 if (spec == NULL) {
1216 *os << (internal::type_equals<Result, void>::value ?
1217 "returning directly.\n" :
1218 "returning default value.\n");
1219 } else {
1220 *os << "taking default action specified at:\n"
1221 << spec->file() << ":" << spec->line() << ":\n";
1222 }
1223 }
1224
1225 // Writes a message that the call is uninteresting (i.e. neither
1226 // explicitly expected nor explicitly unexpected) to the given
1227 // ostream.
1228 // L < g_gmock_mutex
1229 void DescribeUninterestingCall(const ArgumentTuple& args,
1230 ::std::ostream* os) const {
1231 *os << "Uninteresting mock function call - ";
1232 DescribeDefaultActionTo(args, os);
1233 *os << " Function call: " << Name();
1234 UniversalPrinter<ArgumentTuple>::Print(args, os);
1235 }
1236
1237 // Critical section: We must find the matching expectation and the
1238 // corresponding action that needs to be taken in an ATOMIC
1239 // transaction. Otherwise another thread may call this mock
1240 // method in the middle and mess up the state.
1241 //
1242 // However, performing the action has to be left out of the critical
1243 // section. The reason is that we have no control on what the
1244 // action does (it can invoke an arbitrary user function or even a
1245 // mock function) and excessive locking could cause a dead lock.
1246 // L < g_gmock_mutex
1247 bool FindMatchingExpectationAndAction(
1248 const ArgumentTuple& args, Expectation<F>** exp, Action<F>* action,
1249 bool* is_excessive, ::std::ostream* what, ::std::ostream* why) {
1250 MutexLock l(&g_gmock_mutex);
1251 *exp = this->FindMatchingExpectationLocked(args);
1252 if (*exp == NULL) { // A match wasn't found.
1253 *action = DoDefault();
1254 this->FormatUnexpectedCallMessageLocked(args, what, why);
1255 return false;
1256 }
1257
1258 // This line must be done before calling GetActionForArguments(),
1259 // which will increment the call count for *exp and thus affect
1260 // its saturation status.
1261 *is_excessive = (*exp)->IsSaturated();
1262 *action = (*exp)->GetActionForArguments(this, args, what, why);
1263 return true;
1264 }
1265
1266 // Returns the expectation that matches the arguments, or NULL if no
1267 // expectation matches them.
1268 // L >= g_gmock_mutex
1269 Expectation<F>* FindMatchingExpectationLocked(
1270 const ArgumentTuple& args) const {
1271 g_gmock_mutex.AssertHeld();
1272 for (typename Expectations::const_reverse_iterator it =
1273 expectations_.rbegin();
1274 it != expectations_.rend(); ++it) {
1275 Expectation<F>* const exp = it->get();
1276 if (exp->ShouldHandleArguments(args)) {
1277 return exp;
1278 }
1279 }
1280 return NULL;
1281 }
1282
1283 // Returns a message that the arguments don't match any expectation.
1284 // L >= g_gmock_mutex
1285 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1286 ::std::ostream* os,
1287 ::std::ostream* why) const {
1288 g_gmock_mutex.AssertHeld();
1289 *os << "\nUnexpected mock function call - ";
1290 DescribeDefaultActionTo(args, os);
1291 PrintTriedExpectationsLocked(args, why);
1292 }
1293
1294 // Prints a list of expectations that have been tried against the
1295 // current mock function call.
1296 // L >= g_gmock_mutex
1297 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1298 ::std::ostream* why) const {
1299 g_gmock_mutex.AssertHeld();
1300 const int count = static_cast<int>(expectations_.size());
1301 *why << "Google Mock tried the following " << count << " "
1302 << (count == 1 ? "expectation, but it didn't match" :
1303 "expectations, but none matched")
1304 << ":\n";
1305 for (int i = 0; i < count; i++) {
1306 *why << "\n";
1307 expectations_[i]->DescribeLocationTo(why);
1308 if (count > 1) {
1309 *why << "tried expectation #" << i;
1310 }
1311 *why << "\n";
1312 expectations_[i]->DescribeMatchResultTo(args, why);
1313 expectations_[i]->DescribeCallCountTo(why);
1314 }
1315 }
1316
1317 // Address of the mock object this mock method belongs to.
1318 const void* mock_obj_; // Protected by g_gmock_mutex.
1319
1320 // Name of the function being mocked.
1321 const char* name_; // Protected by g_gmock_mutex.
1322
1323 // The current spec (either default action spec or expectation spec)
1324 // being described on this function mocker.
1325 MockSpec<F> current_spec_;
1326
1327 // All default action specs for this function mocker.
1328 std::vector<DefaultActionSpec<F> > default_actions_;
1329 // All expectations for this function mocker.
1330 Expectations expectations_;
1331}; // class FunctionMockerBase
1332
1333#ifdef _MSC_VER
1334#pragma warning(pop) // Restores the warning state.
1335#endif // _MSV_VER
1336
1337// Implements methods of FunctionMockerBase.
1338
1339// Verifies that all expectations on this mock function have been
1340// satisfied. Reports one or more Google Test non-fatal failures and
1341// returns false if not.
1342// L >= g_gmock_mutex
1343template <typename F>
1344bool FunctionMockerBase<F>::VerifyAndClearExpectationsLocked() {
1345 g_gmock_mutex.AssertHeld();
1346 bool expectations_met = true;
1347 for (typename Expectations::const_iterator it = expectations_.begin();
1348 it != expectations_.end(); ++it) {
1349 Expectation<F>* const exp = it->get();
1350
1351 if (exp->IsOverSaturated()) {
1352 // There was an upper-bound violation. Since the error was
1353 // already reported when it occurred, there is no need to do
1354 // anything here.
1355 expectations_met = false;
1356 } else if (!exp->IsSatisfied()) {
1357 expectations_met = false;
1358 ::std::stringstream ss;
1359 ss << "Actual function call count doesn't match this expectation.\n";
1360 // No need to show the source file location of the expectation
1361 // in the description, as the Expect() call that follows already
1362 // takes care of it.
1363 exp->DescribeCallCountTo(&ss);
1364 Expect(false, exp->file(), exp->line(), ss.str());
1365 }
1366 }
1367 expectations_.clear();
1368 return expectations_met;
1369}
1370
1371// Reports an uninteresting call (whose description is in msg) in the
1372// manner specified by 'reaction'.
1373void ReportUninterestingCall(CallReaction reaction, const string& msg);
1374
1375// When an uninteresting or unexpected mock function is called, we
1376// want to print its return value to assist the user debugging. Since
1377// there's nothing to print when the function returns void, we need to
1378// specialize the logic of FunctionMockerBase<F>::InvokeWith() for
1379// void return values.
1380//
1381// C++ doesn't allow us to specialize a member function template
1382// unless we also specialize its enclosing class, so we had to let
1383// InvokeWith() delegate its work to a helper class InvokeWithHelper,
1384// which can then be specialized.
1385//
1386// Note that InvokeWithHelper must be a class template (as opposed to
1387// a function template), as only class templates can be partially
1388// specialized.
1389template <typename Result, typename F>
1390class InvokeWithHelper {
1391 public:
1392 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1393
1394 // Calculates the result of invoking the function mocked by mocker
1395 // with the given arguments, prints it, and returns it.
1396 // L < g_gmock_mutex
1397 static Result InvokeAndPrintResult(
1398 FunctionMockerBase<F>* mocker,
1399 const ArgumentTuple& args) {
1400 if (mocker->expectations_.size() == 0) {
1401 // No expectation is set on this mock method - we have an
1402 // uninteresting call.
1403
1404 // Warns about the uninteresting call.
1405 ::std::stringstream ss;
1406 mocker->DescribeUninterestingCall(args, &ss);
1407
1408 // We must get Google Mock's reaction on uninteresting calls
1409 // made on this mock object BEFORE performing the action,
1410 // because the action may DELETE the mock object and make the
1411 // following expression meaningless.
1412 const CallReaction reaction =
1413 Mock::GetReactionOnUninterestingCalls(mocker->MockObject());
1414
1415 // Calculates the function result.
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001416 Result result = mocker->PerformDefaultAction(args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001417
1418 // Prints the function result.
1419 ss << "\n Returns: ";
1420 UniversalPrinter<Result>::Print(result, &ss);
1421 ReportUninterestingCall(reaction, ss.str());
1422
1423 return result;
1424 }
1425
1426 bool is_excessive = false;
1427 ::std::stringstream ss;
1428 ::std::stringstream why;
zhanyong.wan6f147692009-03-03 06:44:08 +00001429 ::std::stringstream loc;
shiqiane35fdd92008-12-10 05:08:54 +00001430 Action<F> action;
1431 Expectation<F>* exp;
1432
1433 // The FindMatchingExpectationAndAction() function acquires and
1434 // releases g_gmock_mutex.
1435 const bool found = mocker->FindMatchingExpectationAndAction(
1436 args, &exp, &action, &is_excessive, &ss, &why);
1437 ss << " Function call: " << mocker->Name();
1438 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
zhanyong.wan6f147692009-03-03 06:44:08 +00001439 // In case the action deletes a piece of the expectation, we
1440 // generate the message beforehand.
1441 if (found && !is_excessive) {
1442 exp->DescribeLocationTo(&loc);
1443 }
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001444 Result result = action.IsDoDefault() ?
1445 mocker->PerformDefaultAction(args, ss.str())
shiqiane35fdd92008-12-10 05:08:54 +00001446 : action.Perform(args);
1447 ss << "\n Returns: ";
1448 UniversalPrinter<Result>::Print(result, &ss);
1449 ss << "\n" << why.str();
1450
1451 if (found) {
1452 if (is_excessive) {
1453 // We had an upper-bound violation and the failure message is in ss.
1454 Expect(false, exp->file(), exp->line(), ss.str());
1455 } else {
1456 // We had an expected call and the matching expectation is
1457 // described in ss.
shiqiane35fdd92008-12-10 05:08:54 +00001458 Log(INFO, loc.str() + ss.str(), 3);
1459 }
1460 } else {
1461 // No expectation matches this call - reports a failure.
1462 Expect(false, NULL, -1, ss.str());
1463 }
1464 return result;
1465 }
1466}; // class InvokeWithHelper
1467
1468// This specialization helps to implement
1469// FunctionMockerBase<F>::InvokeWith() for void-returning functions.
1470template <typename F>
1471class InvokeWithHelper<void, F> {
1472 public:
1473 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1474
1475 // Invokes the function mocked by mocker with the given arguments.
1476 // L < g_gmock_mutex
1477 static void InvokeAndPrintResult(FunctionMockerBase<F>* mocker,
1478 const ArgumentTuple& args) {
1479 const int count = static_cast<int>(mocker->expectations_.size());
1480 if (count == 0) {
1481 // No expectation is set on this mock method - we have an
1482 // uninteresting call.
1483 ::std::stringstream ss;
1484 mocker->DescribeUninterestingCall(args, &ss);
1485
1486 // We must get Google Mock's reaction on uninteresting calls
1487 // made on this mock object BEFORE performing the action,
1488 // because the action may DELETE the mock object and make the
1489 // following expression meaningless.
1490 const CallReaction reaction =
1491 Mock::GetReactionOnUninterestingCalls(mocker->MockObject());
1492
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001493 mocker->PerformDefaultAction(args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001494 ReportUninterestingCall(reaction, ss.str());
1495 return;
1496 }
1497
1498 bool is_excessive = false;
1499 ::std::stringstream ss;
1500 ::std::stringstream why;
zhanyong.wan6f147692009-03-03 06:44:08 +00001501 ::std::stringstream loc;
shiqiane35fdd92008-12-10 05:08:54 +00001502 Action<F> action;
1503 Expectation<F>* exp;
1504
1505 // The FindMatchingExpectationAndAction() function acquires and
1506 // releases g_gmock_mutex.
1507 const bool found = mocker->FindMatchingExpectationAndAction(
1508 args, &exp, &action, &is_excessive, &ss, &why);
1509 ss << " Function call: " << mocker->Name();
1510 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1511 ss << "\n" << why.str();
zhanyong.wan6f147692009-03-03 06:44:08 +00001512 // In case the action deletes a piece of the expectation, we
1513 // generate the message beforehand.
1514 if (found && !is_excessive) {
1515 exp->DescribeLocationTo(&loc);
1516 }
shiqiane35fdd92008-12-10 05:08:54 +00001517 if (action.IsDoDefault()) {
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001518 mocker->PerformDefaultAction(args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001519 } else {
1520 action.Perform(args);
1521 }
1522
1523 if (found) {
1524 // A matching expectation and corresponding action were found.
1525 if (is_excessive) {
1526 // We had an upper-bound violation and the failure message is in ss.
1527 Expect(false, exp->file(), exp->line(), ss.str());
1528 } else {
1529 // We had an expected call and the matching expectation is
1530 // described in ss.
shiqiane35fdd92008-12-10 05:08:54 +00001531 Log(INFO, loc.str() + ss.str(), 3);
1532 }
1533 } else {
1534 // No matching expectation was found - reports an error.
1535 Expect(false, NULL, -1, ss.str());
1536 }
1537 }
1538}; // class InvokeWithHelper<void, F>
1539
1540} // namespace internal
1541
1542// The style guide prohibits "using" statements in a namespace scope
1543// inside a header file. However, the MockSpec class template is
1544// meant to be defined in the ::testing namespace. The following line
1545// is just a trick for working around a bug in MSVC 8.0, which cannot
1546// handle it if we define MockSpec in ::testing.
1547using internal::MockSpec;
1548
1549// Const(x) is a convenient function for obtaining a const reference
1550// to x. This is useful for setting expectations on an overloaded
1551// const mock method, e.g.
1552//
1553// class MockFoo : public FooInterface {
1554// public:
1555// MOCK_METHOD0(Bar, int());
1556// MOCK_CONST_METHOD0(Bar, int&());
1557// };
1558//
1559// MockFoo foo;
1560// // Expects a call to non-const MockFoo::Bar().
1561// EXPECT_CALL(foo, Bar());
1562// // Expects a call to const MockFoo::Bar().
1563// EXPECT_CALL(Const(foo), Bar());
1564template <typename T>
1565inline const T& Const(const T& x) { return x; }
1566
1567} // namespace testing
1568
1569// A separate macro is required to avoid compile errors when the name
1570// of the method used in call is a result of macro expansion.
1571// See CompilesWithMethodNameExpandedFromMacro tests in
1572// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001573#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001574 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1575 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001576#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001577
zhanyong.wane0d051e2009-02-19 00:33:37 +00001578#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001579 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001580#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001581
1582#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_