blob: 765e06d9b501b0911e9a1e7d4141f70008aee76e [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))
zhanyong.wanbf550852009-06-09 06:09:53 +000040// .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +000041// .WillByDefault(action);
42//
zhanyong.wanbf550852009-06-09 06:09:53 +000043// where the .With() clause is optional.
shiqiane35fdd92008-12-10 05:08:54 +000044//
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))
zhanyong.wanbf550852009-06-09 06:09:53 +000049// .With(multi-argument-matchers)
shiqiane35fdd92008-12-10 05:08:54 +000050// .Times(cardinality)
51// .InSequence(sequences)
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000052// .After(expectations)
shiqiane35fdd92008-12-10 05:08:54 +000053// .WillOnce(action)
54// .WillRepeatedly(action)
55// .RetiresOnSaturation();
56//
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000057// where all clauses are optional, and .InSequence()/.After()/
58// .WillOnce() can appear any number of times.
shiqiane35fdd92008-12-10 05:08:54 +000059
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
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000079// An abstract handle of an expectation.
80class Expectation;
81
82// A set of expectation handles.
83class ExpectationSet;
84
shiqiane35fdd92008-12-10 05:08:54 +000085// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
86// and MUST NOT BE USED IN USER CODE!!!
87namespace internal {
88
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000089// Implements a mock function.
90template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000091
92// Base class for expectations.
93class ExpectationBase;
94
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000095// Implements an expectation.
96template <typename F> class TypedExpectation;
97
shiqiane35fdd92008-12-10 05:08:54 +000098// Helper class for testing the Expectation class template.
99class ExpectationTester;
100
101// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000102template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000103
shiqiane35fdd92008-12-10 05:08:54 +0000104// Protects the mock object registry (in class Mock), all function
105// mockers, and all expectations.
106//
107// The reason we don't use more fine-grained protection is: when a
108// mock function Foo() is called, it needs to consult its expectations
109// to see which one should be picked. If another thread is allowed to
110// call a mock function (either Foo() or a different one) at the same
111// time, it could affect the "retired" attributes of Foo()'s
112// expectations when InSequence() is used, and thus affect which
113// expectation gets picked. Therefore, we sequence all mock function
114// calls to ensure the integrity of the mock objects' states.
115extern Mutex g_gmock_mutex;
116
117// Abstract base class of FunctionMockerBase. This is the
118// type-agnostic part of the function mocker interface. Its pure
119// virtual methods are implemented by FunctionMockerBase.
120class UntypedFunctionMockerBase {
121 public:
122 virtual ~UntypedFunctionMockerBase() {}
123
124 // Verifies that all expectations on this mock function have been
125 // satisfied. Reports one or more Google Test non-fatal failures
126 // and returns false if not.
127 // L >= g_gmock_mutex
128 virtual bool VerifyAndClearExpectationsLocked() = 0;
129
130 // Clears the ON_CALL()s set on this mock function.
131 // L >= g_gmock_mutex
132 virtual void ClearDefaultActionsLocked() = 0;
133}; // class UntypedFunctionMockerBase
134
135// This template class implements a default action spec (i.e. an
136// ON_CALL() statement).
137template <typename F>
138class DefaultActionSpec {
139 public:
140 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
141 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
142
143 // Constructs a DefaultActionSpec object from the information inside
144 // the parenthesis of an ON_CALL() statement.
145 DefaultActionSpec(const char* file, int line,
146 const ArgumentMatcherTuple& matchers)
147 : file_(file),
148 line_(line),
149 matchers_(matchers),
zhanyong.wan18490652009-05-11 18:54:08 +0000150 // By default, extra_matcher_ should match anything. However,
151 // we cannot initialize it with _ as that triggers a compiler
152 // bug in Symbian's C++ compiler (cannot decide between two
153 // overloaded constructors of Matcher<const ArgumentTuple&>).
154 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.wanbf550852009-06-09 06:09:53 +0000155 last_clause_(kNone) {
shiqiane35fdd92008-12-10 05:08:54 +0000156 }
157
158 // Where in the source file was the default action spec defined?
159 const char* file() const { return file_; }
160 int line() const { return line_; }
161
zhanyong.wanbf550852009-06-09 06:09:53 +0000162 // Implements the .With() clause.
163 DefaultActionSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000164 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000165 ExpectSpecProperty(last_clause_ < kWith,
166 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000167 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000168 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000169
170 extra_matcher_ = m;
171 return *this;
172 }
173
174 // Implements the .WillByDefault() clause.
175 DefaultActionSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000176 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000177 ".WillByDefault() must appear "
178 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000179 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000180
181 ExpectSpecProperty(!action.IsDoDefault(),
182 "DoDefault() cannot be used in ON_CALL().");
183 action_ = action;
184 return *this;
185 }
186
187 // Returns true iff the given arguments match the matchers.
188 bool Matches(const ArgumentTuple& args) const {
189 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
190 }
191
192 // Returns the action specified by the user.
193 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000194 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000195 ".WillByDefault() must appear exactly "
196 "once in an ON_CALL().");
197 return action_;
198 }
199 private:
200 // Gives each clause in the ON_CALL() statement a name.
201 enum Clause {
202 // Do not change the order of the enum members! The run-time
203 // syntax checking relies on it.
zhanyong.wanbf550852009-06-09 06:09:53 +0000204 kNone,
205 kWith,
206 kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000207 };
208
209 // Asserts that the ON_CALL() statement has a certain property.
210 void AssertSpecProperty(bool property, const string& failure_message) const {
211 Assert(property, file_, line_, failure_message);
212 }
213
214 // Expects that the ON_CALL() statement has a certain property.
215 void ExpectSpecProperty(bool property, const string& failure_message) const {
216 Expect(property, file_, line_, failure_message);
217 }
218
219 // The information in statement
220 //
221 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000222 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000223 // .WillByDefault(action);
224 //
225 // is recorded in the data members like this:
226 //
227 // source file that contains the statement => file_
228 // line number of the statement => line_
229 // matchers => matchers_
230 // multi-argument-matcher => extra_matcher_
231 // action => action_
232 const char* file_;
233 int line_;
234 ArgumentMatcherTuple matchers_;
235 Matcher<const ArgumentTuple&> extra_matcher_;
236 Action<F> action_;
237
238 // The last clause in the ON_CALL() statement as seen so far.
zhanyong.wanbf550852009-06-09 06:09:53 +0000239 // Initially kNone and changes as the statement is parsed.
shiqiane35fdd92008-12-10 05:08:54 +0000240 Clause last_clause_;
241}; // class DefaultActionSpec
242
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000243// Possible reactions on uninteresting calls. TODO(wan@google.com):
244// rename the enum values to the kFoo style.
shiqiane35fdd92008-12-10 05:08:54 +0000245enum CallReaction {
246 ALLOW,
247 WARN,
248 FAIL,
249};
250
251} // namespace internal
252
253// Utilities for manipulating mock objects.
254class Mock {
255 public:
256 // The following public methods can be called concurrently.
257
zhanyong.wandf35a762009-04-22 22:25:31 +0000258 // Tells Google Mock to ignore mock_obj when checking for leaked
259 // mock objects.
260 static void AllowLeak(const void* mock_obj);
261
shiqiane35fdd92008-12-10 05:08:54 +0000262 // Verifies and clears all expectations on the given mock object.
263 // If the expectations aren't satisfied, generates one or more
264 // Google Test non-fatal failures and returns false.
265 static bool VerifyAndClearExpectations(void* mock_obj);
266
267 // Verifies all expectations on the given mock object and clears its
268 // default actions and expectations. Returns true iff the
269 // verification was successful.
270 static bool VerifyAndClear(void* mock_obj);
271 private:
272 // Needed for a function mocker to register itself (so that we know
273 // how to clear a mock object).
274 template <typename F>
275 friend class internal::FunctionMockerBase;
276
shiqiane35fdd92008-12-10 05:08:54 +0000277 template <typename M>
278 friend class NiceMock;
279
280 template <typename M>
281 friend class StrictMock;
282
283 // Tells Google Mock to allow uninteresting calls on the given mock
284 // object.
285 // L < g_gmock_mutex
286 static void AllowUninterestingCalls(const void* mock_obj);
287
288 // Tells Google Mock to warn the user about uninteresting calls on
289 // the given mock object.
290 // L < g_gmock_mutex
291 static void WarnUninterestingCalls(const void* mock_obj);
292
293 // Tells Google Mock to fail uninteresting calls on the given mock
294 // object.
295 // L < g_gmock_mutex
296 static void FailUninterestingCalls(const void* mock_obj);
297
298 // Tells Google Mock the given mock object is being destroyed and
299 // its entry in the call-reaction table should be removed.
300 // L < g_gmock_mutex
301 static void UnregisterCallReaction(const void* mock_obj);
302
303 // Returns the reaction Google Mock will have on uninteresting calls
304 // made on the given mock object.
305 // L < g_gmock_mutex
306 static internal::CallReaction GetReactionOnUninterestingCalls(
307 const void* mock_obj);
308
309 // Verifies that all expectations on the given mock object have been
310 // satisfied. Reports one or more Google Test non-fatal failures
311 // and returns false if not.
312 // L >= g_gmock_mutex
313 static bool VerifyAndClearExpectationsLocked(void* mock_obj);
314
315 // Clears all ON_CALL()s set on the given mock object.
316 // L >= g_gmock_mutex
317 static void ClearDefaultActionsLocked(void* mock_obj);
318
319 // Registers a mock object and a mock method it owns.
320 // L < g_gmock_mutex
321 static void Register(const void* mock_obj,
322 internal::UntypedFunctionMockerBase* mocker);
323
zhanyong.wandf35a762009-04-22 22:25:31 +0000324 // Tells Google Mock where in the source code mock_obj is used in an
325 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
326 // information helps the user identify which object it is.
327 // L < g_gmock_mutex
328 static void RegisterUseByOnCallOrExpectCall(
329 const void* mock_obj, const char* file, int line);
330
shiqiane35fdd92008-12-10 05:08:54 +0000331 // Unregisters a mock method; removes the owning mock object from
332 // the registry when the last mock method associated with it has
333 // been unregistered. This is called only in the destructor of
334 // FunctionMockerBase.
335 // L >= g_gmock_mutex
336 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
337}; // class Mock
338
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000339// An abstract handle of an expectation. Useful in the .After()
340// clause of EXPECT_CALL() for setting the (partial) order of
341// expectations. The syntax:
342//
343// Expectation e1 = EXPECT_CALL(...)...;
344// EXPECT_CALL(...).After(e1)...;
345//
346// sets two expectations where the latter can only be matched after
347// the former has been satisfied.
348//
349// Notes:
350// - This class is copyable and has value semantics.
351// - Constness is shallow: a const Expectation object itself cannot
352// be modified, but the mutable methods of the ExpectationBase
353// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000354// - The constructors and destructor are defined out-of-line because
355// the Symbian WINSCW compiler wants to otherwise instantiate them
356// when it sees this class definition, at which point it doesn't have
357// ExpectationBase available yet, leading to incorrect destruction
358// in the linked_ptr (or compilation errors if using a checking
359// linked_ptr).
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000360class Expectation {
361 public:
362 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000363 Expectation();
364
365 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000366
367 // This single-argument ctor must not be explicit, in order to support the
368 // Expectation e = EXPECT_CALL(...);
369 // syntax.
370 //
371 // A TypedExpectation object stores its pre-requisites as
372 // Expectation objects, and needs to call the non-const Retire()
373 // method on the ExpectationBase objects they reference. Therefore
374 // Expectation must receive a *non-const* reference to the
375 // ExpectationBase object.
376 Expectation(internal::ExpectationBase& exp); // NOLINT
377
378 // The compiler-generated copy ctor and operator= work exactly as
379 // intended, so we don't need to define our own.
380
381 // Returns true iff rhs references the same expectation as this object does.
382 bool operator==(const Expectation& rhs) const {
383 return expectation_base_ == rhs.expectation_base_;
384 }
385
386 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
387
388 private:
389 friend class ExpectationSet;
390 friend class Sequence;
391 friend class ::testing::internal::ExpectationBase;
392
393 template <typename F>
394 friend class ::testing::internal::FunctionMockerBase;
395
396 template <typename F>
397 friend class ::testing::internal::TypedExpectation;
398
399 // This comparator is needed for putting Expectation objects into a set.
400 class Less {
401 public:
402 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
403 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
404 }
405 };
406
407 typedef ::std::set<Expectation, Less> Set;
408
409 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000410 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000411
412 // Returns the expectation this object references.
413 const internal::linked_ptr<internal::ExpectationBase>&
414 expectation_base() const {
415 return expectation_base_;
416 }
417
418 // A linked_ptr that co-owns the expectation this handle references.
419 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
420};
421
422// A set of expectation handles. Useful in the .After() clause of
423// EXPECT_CALL() for setting the (partial) order of expectations. The
424// syntax:
425//
426// ExpectationSet es;
427// es += EXPECT_CALL(...)...;
428// es += EXPECT_CALL(...)...;
429// EXPECT_CALL(...).After(es)...;
430//
431// sets three expectations where the last one can only be matched
432// after the first two have both been satisfied.
433//
434// This class is copyable and has value semantics.
435class ExpectationSet {
436 public:
437 // A bidirectional iterator that can read a const element in the set.
438 typedef Expectation::Set::const_iterator const_iterator;
439
440 // An object stored in the set. This is an alias of Expectation.
441 typedef Expectation::Set::value_type value_type;
442
443 // Constructs an empty set.
444 ExpectationSet() {}
445
446 // This single-argument ctor must not be explicit, in order to support the
447 // ExpectationSet es = EXPECT_CALL(...);
448 // syntax.
449 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
450 *this += Expectation(exp);
451 }
452
453 // This single-argument ctor implements implicit conversion from
454 // Expectation and thus must not be explicit. This allows either an
455 // Expectation or an ExpectationSet to be used in .After().
456 ExpectationSet(const Expectation& e) { // NOLINT
457 *this += e;
458 }
459
460 // The compiler-generator ctor and operator= works exactly as
461 // intended, so we don't need to define our own.
462
463 // Returns true iff rhs contains the same set of Expectation objects
464 // as this does.
465 bool operator==(const ExpectationSet& rhs) const {
466 return expectations_ == rhs.expectations_;
467 }
468
469 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
470
471 // Implements the syntax
472 // expectation_set += EXPECT_CALL(...);
473 ExpectationSet& operator+=(const Expectation& e) {
474 expectations_.insert(e);
475 return *this;
476 }
477
478 int size() const { return static_cast<int>(expectations_.size()); }
479
480 const_iterator begin() const { return expectations_.begin(); }
481 const_iterator end() const { return expectations_.end(); }
482
483 private:
484 Expectation::Set expectations_;
485};
486
487
shiqiane35fdd92008-12-10 05:08:54 +0000488// Sequence objects are used by a user to specify the relative order
489// in which the expectations should match. They are copyable (we rely
490// on the compiler-defined copy constructor and assignment operator).
491class Sequence {
492 public:
493 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000494 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000495
496 // Adds an expectation to this sequence. The caller must ensure
497 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000498 void AddExpectation(const Expectation& expectation) const;
499
shiqiane35fdd92008-12-10 05:08:54 +0000500 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000501 // The last expectation in this sequence. We use a linked_ptr here
502 // because Sequence objects are copyable and we want the copies to
503 // be aliases. The linked_ptr allows the copies to co-own and share
504 // the same Expectation object.
505 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000506}; // class Sequence
507
508// An object of this type causes all EXPECT_CALL() statements
509// encountered in its scope to be put in an anonymous sequence. The
510// work is done in the constructor and destructor. You should only
511// create an InSequence object on the stack.
512//
513// The sole purpose for this class is to support easy definition of
514// sequential expectations, e.g.
515//
516// {
517// InSequence dummy; // The name of the object doesn't matter.
518//
519// // The following expectations must match in the order they appear.
520// EXPECT_CALL(a, Bar())...;
521// EXPECT_CALL(a, Baz())...;
522// ...
523// EXPECT_CALL(b, Xyz())...;
524// }
525//
526// You can create InSequence objects in multiple threads, as long as
527// they are used to affect different mock objects. The idea is that
528// each thread can create and set up its own mocks as if it's the only
529// thread. However, for clarity of your tests we recommend you to set
530// up mocks in the main thread unless you have a good reason not to do
531// so.
532class InSequence {
533 public:
534 InSequence();
535 ~InSequence();
536 private:
537 bool sequence_created_;
538
539 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wane0d051e2009-02-19 00:33:37 +0000540} GMOCK_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000541
542namespace internal {
543
544// Points to the implicit sequence introduced by a living InSequence
545// object (if any) in the current thread or NULL.
546extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
547
548// Base class for implementing expectations.
549//
550// There are two reasons for having a type-agnostic base class for
551// Expectation:
552//
553// 1. We need to store collections of expectations of different
554// types (e.g. all pre-requisites of a particular expectation, all
555// expectations in a sequence). Therefore these expectation objects
556// must share a common base class.
557//
558// 2. We can avoid binary code bloat by moving methods not depending
559// on the template argument of Expectation to the base class.
560//
561// This class is internal and mustn't be used by user code directly.
562class ExpectationBase {
563 public:
564 ExpectationBase(const char* file, int line);
565
566 virtual ~ExpectationBase();
567
568 // Where in the source file was the expectation spec defined?
569 const char* file() const { return file_; }
570 int line() const { return line_; }
571
572 // Returns the cardinality specified in the expectation spec.
573 const Cardinality& cardinality() const { return cardinality_; }
574
575 // Describes the source file location of this expectation.
576 void DescribeLocationTo(::std::ostream* os) const {
577 *os << file() << ":" << line() << ": ";
578 }
579
580 // Describes how many times a function call matching this
581 // expectation has occurred.
582 // L >= g_gmock_mutex
583 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
584 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000585 friend class ::testing::Expectation;
shiqiane35fdd92008-12-10 05:08:54 +0000586
587 enum Clause {
588 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000589 kNone,
590 kWith,
591 kTimes,
592 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000593 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000594 kWillOnce,
595 kWillRepeatedly,
596 kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000597 };
598
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000599 // Returns an Expectation object that references and co-owns this
600 // expectation.
601 virtual Expectation GetHandle() = 0;
602
shiqiane35fdd92008-12-10 05:08:54 +0000603 // Asserts that the EXPECT_CALL() statement has the given property.
604 void AssertSpecProperty(bool property, const string& failure_message) const {
605 Assert(property, file_, line_, failure_message);
606 }
607
608 // Expects that the EXPECT_CALL() statement has the given property.
609 void ExpectSpecProperty(bool property, const string& failure_message) const {
610 Expect(property, file_, line_, failure_message);
611 }
612
613 // Explicitly specifies the cardinality of this expectation. Used
614 // by the subclasses to implement the .Times() clause.
615 void SpecifyCardinality(const Cardinality& cardinality);
616
617 // Returns true iff the user specified the cardinality explicitly
618 // using a .Times().
619 bool cardinality_specified() const { return cardinality_specified_; }
620
621 // Sets the cardinality of this expectation spec.
622 void set_cardinality(const Cardinality& cardinality) {
623 cardinality_ = cardinality;
624 }
625
626 // The following group of methods should only be called after the
627 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
628 // the current thread.
629
630 // Retires all pre-requisites of this expectation.
631 // L >= g_gmock_mutex
632 void RetireAllPreRequisites();
633
634 // Returns true iff this expectation is retired.
635 // L >= g_gmock_mutex
636 bool is_retired() const {
637 g_gmock_mutex.AssertHeld();
638 return retired_;
639 }
640
641 // Retires this expectation.
642 // L >= g_gmock_mutex
643 void Retire() {
644 g_gmock_mutex.AssertHeld();
645 retired_ = true;
646 }
647
648 // Returns true iff this expectation is satisfied.
649 // L >= g_gmock_mutex
650 bool IsSatisfied() const {
651 g_gmock_mutex.AssertHeld();
652 return cardinality().IsSatisfiedByCallCount(call_count_);
653 }
654
655 // Returns true iff this expectation is saturated.
656 // L >= g_gmock_mutex
657 bool IsSaturated() const {
658 g_gmock_mutex.AssertHeld();
659 return cardinality().IsSaturatedByCallCount(call_count_);
660 }
661
662 // Returns true iff this expectation is over-saturated.
663 // L >= g_gmock_mutex
664 bool IsOverSaturated() const {
665 g_gmock_mutex.AssertHeld();
666 return cardinality().IsOverSaturatedByCallCount(call_count_);
667 }
668
669 // Returns true iff all pre-requisites of this expectation are satisfied.
670 // L >= g_gmock_mutex
671 bool AllPrerequisitesAreSatisfied() const;
672
673 // Adds unsatisfied pre-requisites of this expectation to 'result'.
674 // L >= g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000675 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const;
shiqiane35fdd92008-12-10 05:08:54 +0000676
677 // Returns the number this expectation has been invoked.
678 // L >= g_gmock_mutex
679 int call_count() const {
680 g_gmock_mutex.AssertHeld();
681 return call_count_;
682 }
683
684 // Increments the number this expectation has been invoked.
685 // L >= g_gmock_mutex
686 void IncrementCallCount() {
687 g_gmock_mutex.AssertHeld();
688 call_count_++;
689 }
690
691 private:
692 friend class ::testing::Sequence;
693 friend class ::testing::internal::ExpectationTester;
694
695 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000696 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000697
698 // This group of fields are part of the spec and won't change after
699 // an EXPECT_CALL() statement finishes.
700 const char* file_; // The file that contains the expectation.
701 int line_; // The line number of the expectation.
702 // True iff the cardinality is specified explicitly.
703 bool cardinality_specified_;
704 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000705 // The immediate pre-requisites (i.e. expectations that must be
706 // satisfied before this expectation can be matched) of this
707 // expectation. We use linked_ptr in the set because we want an
708 // Expectation object to be co-owned by its FunctionMocker and its
709 // successors. This allows multiple mock objects to be deleted at
710 // different times.
711 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000712
713 // This group of fields are the current state of the expectation,
714 // and can change as the mock function is called.
715 int call_count_; // How many times this expectation has been invoked.
716 bool retired_; // True iff this expectation has retired.
717}; // class ExpectationBase
718
719// Impements an expectation for the given function type.
720template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000721class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000722 public:
723 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
724 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
725 typedef typename Function<F>::Result Result;
726
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000727 TypedExpectation(FunctionMockerBase<F>* owner, const char* file, int line,
728 const ArgumentMatcherTuple& m)
shiqiane35fdd92008-12-10 05:08:54 +0000729 : ExpectationBase(file, line),
730 owner_(owner),
731 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000732 // By default, extra_matcher_ should match anything. However,
733 // we cannot initialize it with _ as that triggers a compiler
734 // bug in Symbian's C++ compiler (cannot decide between two
735 // overloaded constructors of Matcher<const ArgumentTuple&>).
736 extra_matcher_(A<const ArgumentTuple&>()),
shiqiane35fdd92008-12-10 05:08:54 +0000737 repeated_action_specified_(false),
738 repeated_action_(DoDefault()),
739 retires_on_saturation_(false),
zhanyong.wanbf550852009-06-09 06:09:53 +0000740 last_clause_(kNone),
shiqiane35fdd92008-12-10 05:08:54 +0000741 action_count_checked_(false) {}
742
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000743 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000744 // Check the validity of the action count if it hasn't been done
745 // yet (for example, if the expectation was never used).
746 CheckActionCountIfNotDone();
747 }
748
zhanyong.wanbf550852009-06-09 06:09:53 +0000749 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000750 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000751 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000752 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000753 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000754 "more than once in an EXPECT_CALL().");
755 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000756 ExpectSpecProperty(last_clause_ < kWith,
757 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000758 "clause in an EXPECT_CALL().");
759 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000760 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000761
762 extra_matcher_ = m;
763 return *this;
764 }
765
766 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000767 TypedExpectation& Times(const Cardinality& cardinality) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000768 if (last_clause_ ==kTimes) {
shiqiane35fdd92008-12-10 05:08:54 +0000769 ExpectSpecProperty(false,
770 ".Times() cannot appear "
771 "more than once in an EXPECT_CALL().");
772 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000773 ExpectSpecProperty(last_clause_ < kTimes,
shiqiane35fdd92008-12-10 05:08:54 +0000774 ".Times() cannot appear after "
775 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
776 "or .RetiresOnSaturation().");
777 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000778 last_clause_ = kTimes;
shiqiane35fdd92008-12-10 05:08:54 +0000779
780 ExpectationBase::SpecifyCardinality(cardinality);
781 return *this;
782 }
783
784 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000785 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000786 return Times(Exactly(n));
787 }
788
789 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000790 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000791 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000792 ".InSequence() cannot appear after .After(),"
793 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000794 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000795 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000796
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000797 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000798 return *this;
799 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000800 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000801 return InSequence(s1).InSequence(s2);
802 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000803 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
804 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000805 return InSequence(s1, s2).InSequence(s3);
806 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000807 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
808 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000809 return InSequence(s1, s2, s3).InSequence(s4);
810 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000811 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
812 const Sequence& s3, const Sequence& s4,
813 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000814 return InSequence(s1, s2, s3, s4).InSequence(s5);
815 }
816
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000817 // Implements that .After() clause.
818 TypedExpectation& After(const ExpectationSet& s) {
819 ExpectSpecProperty(last_clause_ <= kAfter,
820 ".After() cannot appear after .WillOnce(),"
821 " .WillRepeatedly(), or "
822 ".RetiresOnSaturation().");
823 last_clause_ = kAfter;
824
825 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
826 immediate_prerequisites_ += *it;
827 }
828 return *this;
829 }
830 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
831 return After(s1).After(s2);
832 }
833 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
834 const ExpectationSet& s3) {
835 return After(s1, s2).After(s3);
836 }
837 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
838 const ExpectationSet& s3, const ExpectationSet& s4) {
839 return After(s1, s2, s3).After(s4);
840 }
841 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
842 const ExpectationSet& s3, const ExpectationSet& s4,
843 const ExpectationSet& s5) {
844 return After(s1, s2, s3, s4).After(s5);
845 }
846
shiqiane35fdd92008-12-10 05:08:54 +0000847 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000848 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000849 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000850 ".WillOnce() cannot appear after "
851 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000852 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +0000853
854 actions_.push_back(action);
855 if (!cardinality_specified()) {
856 set_cardinality(Exactly(static_cast<int>(actions_.size())));
857 }
858 return *this;
859 }
860
861 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000862 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000863 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +0000864 ExpectSpecProperty(false,
865 ".WillRepeatedly() cannot appear "
866 "more than once in an EXPECT_CALL().");
867 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000868 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +0000869 ".WillRepeatedly() cannot appear "
870 "after .RetiresOnSaturation().");
871 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000872 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +0000873 repeated_action_specified_ = true;
874
875 repeated_action_ = action;
876 if (!cardinality_specified()) {
877 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
878 }
879
880 // Now that no more action clauses can be specified, we check
881 // whether their count makes sense.
882 CheckActionCountIfNotDone();
883 return *this;
884 }
885
886 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000887 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +0000888 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000889 ".RetiresOnSaturation() cannot appear "
890 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +0000891 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +0000892 retires_on_saturation_ = true;
893
894 // Now that no more action clauses can be specified, we check
895 // whether their count makes sense.
896 CheckActionCountIfNotDone();
897 return *this;
898 }
899
900 // Returns the matchers for the arguments as specified inside the
901 // EXPECT_CALL() macro.
902 const ArgumentMatcherTuple& matchers() const {
903 return matchers_;
904 }
905
zhanyong.wanbf550852009-06-09 06:09:53 +0000906 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +0000907 const Matcher<const ArgumentTuple&>& extra_matcher() const {
908 return extra_matcher_;
909 }
910
911 // Returns the sequence of actions specified by the .WillOnce() clause.
912 const std::vector<Action<F> >& actions() const { return actions_; }
913
914 // Returns the action specified by the .WillRepeatedly() clause.
915 const Action<F>& repeated_action() const { return repeated_action_; }
916
917 // Returns true iff the .RetiresOnSaturation() clause was specified.
918 bool retires_on_saturation() const { return retires_on_saturation_; }
919
920 // Describes how many times a function call matching this
921 // expectation has occurred (implements
922 // ExpectationBase::DescribeCallCountTo()).
923 // L >= g_gmock_mutex
924 virtual void DescribeCallCountTo(::std::ostream* os) const {
925 g_gmock_mutex.AssertHeld();
926
927 // Describes how many times the function is expected to be called.
928 *os << " Expected: to be ";
929 cardinality().DescribeTo(os);
930 *os << "\n Actual: ";
931 Cardinality::DescribeActualCallCountTo(call_count(), os);
932
933 // Describes the state of the expectation (e.g. is it satisfied?
934 // is it active?).
935 *os << " - " << (IsOverSaturated() ? "over-saturated" :
936 IsSaturated() ? "saturated" :
937 IsSatisfied() ? "satisfied" : "unsatisfied")
938 << " and "
939 << (is_retired() ? "retired" : "active");
940 }
941 private:
942 template <typename Function>
943 friend class FunctionMockerBase;
944
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000945 // Returns an Expectation object that references and co-owns this
946 // expectation.
947 virtual Expectation GetHandle() {
948 return owner_->GetHandleOf(this);
949 }
950
shiqiane35fdd92008-12-10 05:08:54 +0000951 // The following methods will be called only after the EXPECT_CALL()
952 // statement finishes and when the current thread holds
953 // g_gmock_mutex.
954
955 // Returns true iff this expectation matches the given arguments.
956 // L >= g_gmock_mutex
957 bool Matches(const ArgumentTuple& args) const {
958 g_gmock_mutex.AssertHeld();
959 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
960 }
961
962 // Returns true iff this expectation should handle the given arguments.
963 // L >= g_gmock_mutex
964 bool ShouldHandleArguments(const ArgumentTuple& args) const {
965 g_gmock_mutex.AssertHeld();
966
967 // In case the action count wasn't checked when the expectation
968 // was defined (e.g. if this expectation has no WillRepeatedly()
969 // or RetiresOnSaturation() clause), we check it when the
970 // expectation is used for the first time.
971 CheckActionCountIfNotDone();
972 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
973 }
974
975 // Describes the result of matching the arguments against this
976 // expectation to the given ostream.
977 // L >= g_gmock_mutex
978 void DescribeMatchResultTo(const ArgumentTuple& args,
979 ::std::ostream* os) const {
980 g_gmock_mutex.AssertHeld();
981
982 if (is_retired()) {
983 *os << " Expected: the expectation is active\n"
984 << " Actual: it is retired\n";
985 } else if (!Matches(args)) {
986 if (!TupleMatches(matchers_, args)) {
987 DescribeMatchFailureTupleTo(matchers_, args, os);
988 }
989 if (!extra_matcher_.Matches(args)) {
zhanyong.wan2661c682009-06-09 05:42:12 +0000990 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +0000991 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +0000992 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +0000993
994 internal::ExplainMatchResultAsNeededTo<const ArgumentTuple&>(
995 extra_matcher_, args, os);
996 *os << "\n";
997 }
998 } else if (!AllPrerequisitesAreSatisfied()) {
999 *os << " Expected: all pre-requisites are satisfied\n"
1000 << " Actual: the following immediate pre-requisites "
1001 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001002 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001003 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1004 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001005 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001006 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001007 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001008 *os << "pre-requisite #" << i++ << "\n";
1009 }
1010 *os << " (end of pre-requisites)\n";
1011 } else {
1012 // This line is here just for completeness' sake. It will never
1013 // be executed as currently the DescribeMatchResultTo() function
1014 // is called only when the mock function call does NOT match the
1015 // expectation.
1016 *os << "The call matches the expectation.\n";
1017 }
1018 }
1019
1020 // Returns the action that should be taken for the current invocation.
1021 // L >= g_gmock_mutex
1022 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
1023 const ArgumentTuple& args) const {
1024 g_gmock_mutex.AssertHeld();
1025 const int count = call_count();
1026 Assert(count >= 1, __FILE__, __LINE__,
1027 "call_count() is <= 0 when GetCurrentAction() is "
1028 "called - this should never happen.");
1029
1030 const int action_count = static_cast<int>(actions().size());
1031 if (action_count > 0 && !repeated_action_specified_ &&
1032 count > action_count) {
1033 // If there is at least one WillOnce() and no WillRepeatedly(),
1034 // we warn the user when the WillOnce() clauses ran out.
1035 ::std::stringstream ss;
1036 DescribeLocationTo(&ss);
1037 ss << "Actions ran out.\n"
1038 << "Called " << count << " times, but only "
1039 << action_count << " WillOnce()"
1040 << (action_count == 1 ? " is" : "s are") << " specified - ";
1041 mocker->DescribeDefaultActionTo(args, &ss);
1042 Log(WARNING, ss.str(), 1);
1043 }
1044
1045 return count <= action_count ? actions()[count - 1] : repeated_action();
1046 }
1047
1048 // Given the arguments of a mock function call, if the call will
1049 // over-saturate this expectation, returns the default action;
1050 // otherwise, returns the next action in this expectation. Also
1051 // describes *what* happened to 'what', and explains *why* Google
1052 // Mock does it to 'why'. This method is not const as it calls
1053 // IncrementCallCount().
1054 // L >= g_gmock_mutex
1055 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
1056 const ArgumentTuple& args,
1057 ::std::ostream* what,
1058 ::std::ostream* why) {
1059 g_gmock_mutex.AssertHeld();
1060 if (IsSaturated()) {
1061 // We have an excessive call.
1062 IncrementCallCount();
1063 *what << "Mock function called more times than expected - ";
1064 mocker->DescribeDefaultActionTo(args, what);
1065 DescribeCallCountTo(why);
1066
1067 // TODO(wan): allow the user to control whether unexpected calls
1068 // should fail immediately or continue using a flag
1069 // --gmock_unexpected_calls_are_fatal.
1070 return DoDefault();
1071 }
1072
1073 IncrementCallCount();
1074 RetireAllPreRequisites();
1075
1076 if (retires_on_saturation() && IsSaturated()) {
1077 Retire();
1078 }
1079
1080 // Must be done after IncrementCount()!
1081 *what << "Expected mock function call.\n";
1082 return GetCurrentAction(mocker, args);
1083 }
1084
1085 // Checks the action count (i.e. the number of WillOnce() and
1086 // WillRepeatedly() clauses) against the cardinality if this hasn't
1087 // been done before. Prints a warning if there are too many or too
1088 // few actions.
1089 // L < mutex_
1090 void CheckActionCountIfNotDone() const {
1091 bool should_check = false;
1092 {
1093 MutexLock l(&mutex_);
1094 if (!action_count_checked_) {
1095 action_count_checked_ = true;
1096 should_check = true;
1097 }
1098 }
1099
1100 if (should_check) {
1101 if (!cardinality_specified_) {
1102 // The cardinality was inferred - no need to check the action
1103 // count against it.
1104 return;
1105 }
1106
1107 // The cardinality was explicitly specified.
1108 const int action_count = static_cast<int>(actions_.size());
1109 const int upper_bound = cardinality().ConservativeUpperBound();
1110 const int lower_bound = cardinality().ConservativeLowerBound();
1111 bool too_many; // True if there are too many actions, or false
1112 // if there are too few.
1113 if (action_count > upper_bound ||
1114 (action_count == upper_bound && repeated_action_specified_)) {
1115 too_many = true;
1116 } else if (0 < action_count && action_count < lower_bound &&
1117 !repeated_action_specified_) {
1118 too_many = false;
1119 } else {
1120 return;
1121 }
1122
1123 ::std::stringstream ss;
1124 DescribeLocationTo(&ss);
1125 ss << "Too " << (too_many ? "many" : "few")
1126 << " actions specified.\n"
1127 << "Expected to be ";
1128 cardinality().DescribeTo(&ss);
1129 ss << ", but has " << (too_many ? "" : "only ")
1130 << action_count << " WillOnce()"
1131 << (action_count == 1 ? "" : "s");
1132 if (repeated_action_specified_) {
1133 ss << " and a WillRepeatedly()";
1134 }
1135 ss << ".";
1136 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
1137 }
1138 }
1139
1140 // All the fields below won't change once the EXPECT_CALL()
1141 // statement finishes.
1142 FunctionMockerBase<F>* const owner_;
1143 ArgumentMatcherTuple matchers_;
1144 Matcher<const ArgumentTuple&> extra_matcher_;
1145 std::vector<Action<F> > actions_;
1146 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
1147 Action<F> repeated_action_;
1148 bool retires_on_saturation_;
1149 Clause last_clause_;
1150 mutable bool action_count_checked_; // Under mutex_.
1151 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001152}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001153
1154// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1155// specifying the default behavior of, or expectation on, a mock
1156// function.
1157
1158// Note: class MockSpec really belongs to the ::testing namespace.
1159// However if we define it in ::testing, MSVC will complain when
1160// classes in ::testing::internal declare it as a friend class
1161// template. To workaround this compiler bug, we define MockSpec in
1162// ::testing::internal and import it into ::testing.
1163
1164template <typename F>
1165class MockSpec {
1166 public:
1167 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1168 typedef typename internal::Function<F>::ArgumentMatcherTuple
1169 ArgumentMatcherTuple;
1170
1171 // Constructs a MockSpec object, given the function mocker object
1172 // that the spec is associated with.
1173 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1174 : function_mocker_(function_mocker) {}
1175
1176 // Adds a new default action spec to the function mocker and returns
1177 // the newly created spec.
1178 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
1179 const char* file, int line, const char* obj, const char* call) {
1180 LogWithLocation(internal::INFO, file, line,
1181 string("ON_CALL(") + obj + ", " + call + ") invoked");
1182 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
1183 }
1184
1185 // Adds a new expectation spec to the function mocker and returns
1186 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001187 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001188 const char* file, int line, const char* obj, const char* call) {
1189 LogWithLocation(internal::INFO, file, line,
1190 string("EXPECT_CALL(") + obj + ", " + call + ") invoked");
1191 return function_mocker_->AddNewExpectation(file, line, matchers_);
1192 }
1193
1194 private:
1195 template <typename Function>
1196 friend class internal::FunctionMocker;
1197
1198 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1199 matchers_ = matchers;
1200 }
1201
1202 // Logs a message including file and line number information.
1203 void LogWithLocation(testing::internal::LogSeverity severity,
1204 const char* file, int line,
1205 const string& message) {
1206 ::std::ostringstream s;
1207 s << file << ":" << line << ": " << message << ::std::endl;
1208 Log(severity, s.str(), 0);
1209 }
1210
1211 // The function mocker that owns this spec.
1212 internal::FunctionMockerBase<F>* const function_mocker_;
1213 // The argument matchers specified in the spec.
1214 ArgumentMatcherTuple matchers_;
1215}; // class MockSpec
1216
1217// MSVC warns about using 'this' in base member initializer list, so
1218// we need to temporarily disable the warning. We have to do it for
1219// the entire class to suppress the warning, even though it's about
1220// the constructor only.
1221
1222#ifdef _MSC_VER
1223#pragma warning(push) // Saves the current warning state.
1224#pragma warning(disable:4355) // Temporarily disables warning 4355.
1225#endif // _MSV_VER
1226
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001227// C++ treats the void type specially. For example, you cannot define
1228// a void-typed variable or pass a void value to a function.
1229// ActionResultHolder<T> holds a value of type T, where T must be a
1230// copyable type or void (T doesn't need to be default-constructable).
1231// It hides the syntactic difference between void and other types, and
1232// is used to unify the code for invoking both void-returning and
1233// non-void-returning mock functions. This generic definition is used
1234// when T is not void.
1235template <typename T>
1236class ActionResultHolder {
1237 public:
1238 explicit ActionResultHolder(T value) : value_(value) {}
1239
1240 // The compiler-generated copy constructor and assignment operator
1241 // are exactly what we need, so we don't need to define them.
1242
1243 T value() const { return value_; }
1244
1245 // Prints the held value as an action's result to os.
1246 void PrintAsActionResult(::std::ostream* os) const {
1247 *os << "\n Returns: ";
1248 UniversalPrinter<T>::Print(value_, os);
1249 }
1250
1251 // Performs the given mock function's default action and returns the
1252 // result in a ActionResultHolder.
1253 template <typename Function, typename Arguments>
1254 static ActionResultHolder PerformDefaultAction(
1255 const FunctionMockerBase<Function>* func_mocker,
1256 const Arguments& args,
1257 const string& call_description) {
1258 return ActionResultHolder(
1259 func_mocker->PerformDefaultAction(args, call_description));
1260 }
1261
1262 // Performs the given action and returns the result in a
1263 // ActionResultHolder.
1264 template <typename Function, typename Arguments>
1265 static ActionResultHolder PerformAction(const Action<Function>& action,
1266 const Arguments& args) {
1267 return ActionResultHolder(action.Perform(args));
1268 }
1269
1270 private:
1271 T value_;
1272};
1273
1274// Specialization for T = void.
1275template <>
1276class ActionResultHolder<void> {
1277 public:
1278 ActionResultHolder() {}
1279 void value() const {}
1280 void PrintAsActionResult(::std::ostream* /* os */) const {}
1281
1282 template <typename Function, typename Arguments>
1283 static ActionResultHolder PerformDefaultAction(
1284 const FunctionMockerBase<Function>* func_mocker,
1285 const Arguments& args,
1286 const string& call_description) {
1287 func_mocker->PerformDefaultAction(args, call_description);
1288 return ActionResultHolder();
1289 }
1290
1291 template <typename Function, typename Arguments>
1292 static ActionResultHolder PerformAction(const Action<Function>& action,
1293 const Arguments& args) {
1294 action.Perform(args);
1295 return ActionResultHolder();
1296 }
1297};
1298
shiqiane35fdd92008-12-10 05:08:54 +00001299// The base of the function mocker class for the given function type.
1300// We put the methods in this class instead of its child to avoid code
1301// bloat.
1302template <typename F>
1303class FunctionMockerBase : public UntypedFunctionMockerBase {
1304 public:
1305 typedef typename Function<F>::Result Result;
1306 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1307 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1308
1309 FunctionMockerBase() : mock_obj_(NULL), name_(""), current_spec_(this) {}
1310
1311 // The destructor verifies that all expectations on this mock
1312 // function have been satisfied. If not, it will report Google Test
1313 // non-fatal failures for the violations.
1314 // L < g_gmock_mutex
1315 virtual ~FunctionMockerBase() {
1316 MutexLock l(&g_gmock_mutex);
1317 VerifyAndClearExpectationsLocked();
1318 Mock::UnregisterLocked(this);
1319 }
1320
1321 // Returns the ON_CALL spec that matches this mock function with the
1322 // given arguments; returns NULL if no matching ON_CALL is found.
1323 // L = *
1324 const DefaultActionSpec<F>* FindDefaultActionSpec(
1325 const ArgumentTuple& args) const {
1326 for (typename std::vector<DefaultActionSpec<F> >::const_reverse_iterator it
1327 = default_actions_.rbegin();
1328 it != default_actions_.rend(); ++it) {
1329 const DefaultActionSpec<F>& spec = *it;
1330 if (spec.Matches(args))
1331 return &spec;
1332 }
1333
1334 return NULL;
1335 }
1336
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001337 // Performs the default action of this mock function on the given arguments
1338 // and returns the result. Asserts with a helpful call descrption if there is
1339 // no valid return value. This method doesn't depend on the mutable state of
1340 // this object, and thus can be called concurrently without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001341 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001342 Result PerformDefaultAction(const ArgumentTuple& args,
1343 const string& call_description) const {
shiqiane35fdd92008-12-10 05:08:54 +00001344 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001345 if (spec != NULL) {
1346 return spec->GetAction().Perform(args);
1347 }
1348 Assert(DefaultValue<Result>::Exists(), "", -1,
1349 call_description + "\n The mock function has no default action "
1350 "set, and its return type has no default value set.");
1351 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001352 }
1353
1354 // Registers this function mocker and the mock object owning it;
1355 // returns a reference to the function mocker object. This is only
1356 // called by the ON_CALL() and EXPECT_CALL() macros.
zhanyong.wandf35a762009-04-22 22:25:31 +00001357 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001358 FunctionMocker<F>& RegisterOwner(const void* mock_obj) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001359 {
1360 MutexLock l(&g_gmock_mutex);
1361 mock_obj_ = mock_obj;
1362 }
shiqiane35fdd92008-12-10 05:08:54 +00001363 Mock::Register(mock_obj, this);
zhanyong.wan946bc642009-03-31 00:05:30 +00001364 return *::testing::internal::down_cast<FunctionMocker<F>*>(this);
shiqiane35fdd92008-12-10 05:08:54 +00001365 }
1366
1367 // The following two functions are from UntypedFunctionMockerBase.
1368
1369 // Verifies that all expectations on this mock function have been
1370 // satisfied. Reports one or more Google Test non-fatal failures
1371 // and returns false if not.
1372 // L >= g_gmock_mutex
1373 virtual bool VerifyAndClearExpectationsLocked();
1374
1375 // Clears the ON_CALL()s set on this mock function.
1376 // L >= g_gmock_mutex
1377 virtual void ClearDefaultActionsLocked() {
1378 g_gmock_mutex.AssertHeld();
1379 default_actions_.clear();
1380 }
1381
1382 // Sets the name of the function being mocked. Will be called upon
1383 // each invocation of this mock function.
1384 // L < g_gmock_mutex
1385 void SetOwnerAndName(const void* mock_obj, const char* name) {
1386 // We protect name_ under g_gmock_mutex in case this mock function
1387 // is called from two threads concurrently.
1388 MutexLock l(&g_gmock_mutex);
1389 mock_obj_ = mock_obj;
1390 name_ = name;
1391 }
1392
1393 // Returns the address of the mock object this method belongs to.
1394 // Must be called after SetOwnerAndName() has been called.
1395 // L < g_gmock_mutex
1396 const void* MockObject() const {
1397 const void* mock_obj;
1398 {
1399 // We protect mock_obj_ under g_gmock_mutex in case this mock
1400 // function is called from two threads concurrently.
1401 MutexLock l(&g_gmock_mutex);
1402 mock_obj = mock_obj_;
1403 }
1404 return mock_obj;
1405 }
1406
1407 // Returns the name of the function being mocked. Must be called
1408 // after SetOwnerAndName() has been called.
1409 // L < g_gmock_mutex
1410 const char* Name() const {
1411 const char* name;
1412 {
1413 // We protect name_ under g_gmock_mutex in case this mock
1414 // function is called from two threads concurrently.
1415 MutexLock l(&g_gmock_mutex);
1416 name = name_;
1417 }
1418 return name;
1419 }
1420 protected:
1421 template <typename Function>
1422 friend class MockSpec;
1423
shiqiane35fdd92008-12-10 05:08:54 +00001424 // Returns the result of invoking this mock function with the given
1425 // arguments. This function can be safely called from multiple
1426 // threads concurrently.
1427 // L < g_gmock_mutex
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001428 Result InvokeWith(const ArgumentTuple& args);
shiqiane35fdd92008-12-10 05:08:54 +00001429
1430 // Adds and returns a default action spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001431 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001432 DefaultActionSpec<F>& AddNewDefaultActionSpec(
1433 const char* file, int line,
1434 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001435 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
shiqiane35fdd92008-12-10 05:08:54 +00001436 default_actions_.push_back(DefaultActionSpec<F>(file, line, m));
1437 return default_actions_.back();
1438 }
1439
1440 // Adds and returns an expectation spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001441 // L < g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001442 TypedExpectation<F>& AddNewExpectation(
shiqiane35fdd92008-12-10 05:08:54 +00001443 const char* file, int line,
1444 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001445 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001446 const linked_ptr<TypedExpectation<F> > expectation(
1447 new TypedExpectation<F>(this, file, line, m));
shiqiane35fdd92008-12-10 05:08:54 +00001448 expectations_.push_back(expectation);
1449
1450 // Adds this expectation into the implicit sequence if there is one.
1451 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1452 if (implicit_sequence != NULL) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001453 implicit_sequence->AddExpectation(Expectation(expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001454 }
1455
1456 return *expectation;
1457 }
1458
1459 // The current spec (either default action spec or expectation spec)
1460 // being described on this function mocker.
1461 MockSpec<F>& current_spec() { return current_spec_; }
1462 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001463 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001464
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001465 typedef std::vector<internal::linked_ptr<TypedExpectation<F> > >
1466 TypedExpectations;
shiqiane35fdd92008-12-10 05:08:54 +00001467
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001468 // Returns an Expectation object that references and co-owns exp,
1469 // which must be an expectation on this mock function.
1470 Expectation GetHandleOf(TypedExpectation<F>* exp) {
1471 for (typename TypedExpectations::const_iterator it = expectations_.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001472 it != expectations_.end(); ++it) {
1473 if (it->get() == exp) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001474 return Expectation(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001475 }
1476 }
1477
1478 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001479 return Expectation();
shiqiane35fdd92008-12-10 05:08:54 +00001480 // The above statement is just to make the code compile, and will
1481 // never be executed.
1482 }
1483
1484 // Some utilities needed for implementing InvokeWith().
1485
1486 // Describes what default action will be performed for the given
1487 // arguments.
1488 // L = *
1489 void DescribeDefaultActionTo(const ArgumentTuple& args,
1490 ::std::ostream* os) const {
1491 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1492
1493 if (spec == NULL) {
1494 *os << (internal::type_equals<Result, void>::value ?
1495 "returning directly.\n" :
1496 "returning default value.\n");
1497 } else {
1498 *os << "taking default action specified at:\n"
1499 << spec->file() << ":" << spec->line() << ":\n";
1500 }
1501 }
1502
1503 // Writes a message that the call is uninteresting (i.e. neither
1504 // explicitly expected nor explicitly unexpected) to the given
1505 // ostream.
1506 // L < g_gmock_mutex
1507 void DescribeUninterestingCall(const ArgumentTuple& args,
1508 ::std::ostream* os) const {
1509 *os << "Uninteresting mock function call - ";
1510 DescribeDefaultActionTo(args, os);
1511 *os << " Function call: " << Name();
1512 UniversalPrinter<ArgumentTuple>::Print(args, os);
1513 }
1514
1515 // Critical section: We must find the matching expectation and the
1516 // corresponding action that needs to be taken in an ATOMIC
1517 // transaction. Otherwise another thread may call this mock
1518 // method in the middle and mess up the state.
1519 //
1520 // However, performing the action has to be left out of the critical
1521 // section. The reason is that we have no control on what the
1522 // action does (it can invoke an arbitrary user function or even a
1523 // mock function) and excessive locking could cause a dead lock.
1524 // L < g_gmock_mutex
1525 bool FindMatchingExpectationAndAction(
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001526 const ArgumentTuple& args, TypedExpectation<F>** exp, Action<F>* action,
shiqiane35fdd92008-12-10 05:08:54 +00001527 bool* is_excessive, ::std::ostream* what, ::std::ostream* why) {
1528 MutexLock l(&g_gmock_mutex);
1529 *exp = this->FindMatchingExpectationLocked(args);
1530 if (*exp == NULL) { // A match wasn't found.
1531 *action = DoDefault();
1532 this->FormatUnexpectedCallMessageLocked(args, what, why);
1533 return false;
1534 }
1535
1536 // This line must be done before calling GetActionForArguments(),
1537 // which will increment the call count for *exp and thus affect
1538 // its saturation status.
1539 *is_excessive = (*exp)->IsSaturated();
1540 *action = (*exp)->GetActionForArguments(this, args, what, why);
1541 return true;
1542 }
1543
1544 // Returns the expectation that matches the arguments, or NULL if no
1545 // expectation matches them.
1546 // L >= g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001547 TypedExpectation<F>* FindMatchingExpectationLocked(
shiqiane35fdd92008-12-10 05:08:54 +00001548 const ArgumentTuple& args) const {
1549 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001550 for (typename TypedExpectations::const_reverse_iterator it =
shiqiane35fdd92008-12-10 05:08:54 +00001551 expectations_.rbegin();
1552 it != expectations_.rend(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001553 TypedExpectation<F>* const exp = it->get();
shiqiane35fdd92008-12-10 05:08:54 +00001554 if (exp->ShouldHandleArguments(args)) {
1555 return exp;
1556 }
1557 }
1558 return NULL;
1559 }
1560
1561 // Returns a message that the arguments don't match any expectation.
1562 // L >= g_gmock_mutex
1563 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1564 ::std::ostream* os,
1565 ::std::ostream* why) const {
1566 g_gmock_mutex.AssertHeld();
1567 *os << "\nUnexpected mock function call - ";
1568 DescribeDefaultActionTo(args, os);
1569 PrintTriedExpectationsLocked(args, why);
1570 }
1571
1572 // Prints a list of expectations that have been tried against the
1573 // current mock function call.
1574 // L >= g_gmock_mutex
1575 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1576 ::std::ostream* why) const {
1577 g_gmock_mutex.AssertHeld();
1578 const int count = static_cast<int>(expectations_.size());
1579 *why << "Google Mock tried the following " << count << " "
1580 << (count == 1 ? "expectation, but it didn't match" :
1581 "expectations, but none matched")
1582 << ":\n";
1583 for (int i = 0; i < count; i++) {
1584 *why << "\n";
1585 expectations_[i]->DescribeLocationTo(why);
1586 if (count > 1) {
1587 *why << "tried expectation #" << i;
1588 }
1589 *why << "\n";
1590 expectations_[i]->DescribeMatchResultTo(args, why);
1591 expectations_[i]->DescribeCallCountTo(why);
1592 }
1593 }
1594
zhanyong.wandf35a762009-04-22 22:25:31 +00001595 // Address of the mock object this mock method belongs to. Only
1596 // valid after this mock method has been called or
1597 // ON_CALL/EXPECT_CALL has been invoked on it.
shiqiane35fdd92008-12-10 05:08:54 +00001598 const void* mock_obj_; // Protected by g_gmock_mutex.
1599
zhanyong.wandf35a762009-04-22 22:25:31 +00001600 // Name of the function being mocked. Only valid after this mock
1601 // method has been called.
shiqiane35fdd92008-12-10 05:08:54 +00001602 const char* name_; // Protected by g_gmock_mutex.
1603
1604 // The current spec (either default action spec or expectation spec)
1605 // being described on this function mocker.
1606 MockSpec<F> current_spec_;
1607
1608 // All default action specs for this function mocker.
1609 std::vector<DefaultActionSpec<F> > default_actions_;
1610 // All expectations for this function mocker.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001611 TypedExpectations expectations_;
zhanyong.wan16cf4732009-05-14 20:55:30 +00001612
1613 // There is no generally useful and implementable semantics of
1614 // copying a mock object, so copying a mock is usually a user error.
1615 // Thus we disallow copying function mockers. If the user really
1616 // wants to copy a mock object, he should implement his own copy
1617 // operation, for example:
1618 //
1619 // class MockFoo : public Foo {
1620 // public:
1621 // // Defines a copy constructor explicitly.
1622 // MockFoo(const MockFoo& src) {}
1623 // ...
1624 // };
1625 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001626}; // class FunctionMockerBase
1627
1628#ifdef _MSC_VER
1629#pragma warning(pop) // Restores the warning state.
1630#endif // _MSV_VER
1631
1632// Implements methods of FunctionMockerBase.
1633
1634// Verifies that all expectations on this mock function have been
1635// satisfied. Reports one or more Google Test non-fatal failures and
1636// returns false if not.
1637// L >= g_gmock_mutex
1638template <typename F>
1639bool FunctionMockerBase<F>::VerifyAndClearExpectationsLocked() {
1640 g_gmock_mutex.AssertHeld();
1641 bool expectations_met = true;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001642 for (typename TypedExpectations::const_iterator it = expectations_.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001643 it != expectations_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001644 TypedExpectation<F>* const exp = it->get();
shiqiane35fdd92008-12-10 05:08:54 +00001645
1646 if (exp->IsOverSaturated()) {
1647 // There was an upper-bound violation. Since the error was
1648 // already reported when it occurred, there is no need to do
1649 // anything here.
1650 expectations_met = false;
1651 } else if (!exp->IsSatisfied()) {
1652 expectations_met = false;
1653 ::std::stringstream ss;
1654 ss << "Actual function call count doesn't match this expectation.\n";
1655 // No need to show the source file location of the expectation
1656 // in the description, as the Expect() call that follows already
1657 // takes care of it.
1658 exp->DescribeCallCountTo(&ss);
1659 Expect(false, exp->file(), exp->line(), ss.str());
1660 }
1661 }
1662 expectations_.clear();
1663 return expectations_met;
1664}
1665
1666// Reports an uninteresting call (whose description is in msg) in the
1667// manner specified by 'reaction'.
1668void ReportUninterestingCall(CallReaction reaction, const string& msg);
1669
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001670// Calculates the result of invoking this mock function with the given
1671// arguments, prints it, and returns it.
1672// L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001673template <typename F>
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001674typename Function<F>::Result FunctionMockerBase<F>::InvokeWith(
1675 const typename Function<F>::ArgumentTuple& args) {
1676 typedef ActionResultHolder<Result> ResultHolder;
shiqiane35fdd92008-12-10 05:08:54 +00001677
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001678 if (expectations_.size() == 0) {
1679 // No expectation is set on this mock method - we have an
1680 // uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001681
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001682 // We must get Google Mock's reaction on uninteresting calls
1683 // made on this mock object BEFORE performing the action,
1684 // because the action may DELETE the mock object and make the
1685 // following expression meaningless.
1686 const CallReaction reaction =
1687 Mock::GetReactionOnUninterestingCalls(MockObject());
shiqiane35fdd92008-12-10 05:08:54 +00001688
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001689 // True iff we need to print this call's arguments and return
1690 // value. This definition must be kept in sync with
1691 // the behavior of ReportUninterestingCall().
1692 const bool need_to_report_uninteresting_call =
1693 // If the user allows this uninteresting call, we print it
1694 // only when he wants informational messages.
1695 reaction == ALLOW ? LogIsVisible(INFO) :
1696 // If the user wants this to be a warning, we print it only
1697 // when he wants to see warnings.
1698 reaction == WARN ? LogIsVisible(WARNING) :
1699 // Otherwise, the user wants this to be an error, and we
1700 // should always print detailed information in the error.
1701 true;
1702
1703 if (!need_to_report_uninteresting_call) {
1704 // Perform the action without printing the call information.
1705 return PerformDefaultAction(args, "");
shiqiane35fdd92008-12-10 05:08:54 +00001706 }
1707
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001708 // Warns about the uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001709 ::std::stringstream ss;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001710 DescribeUninterestingCall(args, &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001711
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001712 // Calculates the function result.
1713 const ResultHolder result =
1714 ResultHolder::PerformDefaultAction(this, args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001715
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001716 // Prints the function result.
1717 result.PrintAsActionResult(&ss);
1718
1719 ReportUninterestingCall(reaction, ss.str());
1720 return result.value();
shiqiane35fdd92008-12-10 05:08:54 +00001721 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001722
1723 bool is_excessive = false;
1724 ::std::stringstream ss;
1725 ::std::stringstream why;
1726 ::std::stringstream loc;
1727 Action<F> action;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001728 TypedExpectation<F>* exp;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001729
1730 // The FindMatchingExpectationAndAction() function acquires and
1731 // releases g_gmock_mutex.
1732 const bool found = FindMatchingExpectationAndAction(
1733 args, &exp, &action, &is_excessive, &ss, &why);
1734
1735 // True iff we need to print the call's arguments and return value.
1736 // This definition must be kept in sync with the uses of Expect()
1737 // and Log() in this function.
1738 const bool need_to_report_call = !found || is_excessive || LogIsVisible(INFO);
1739 if (!need_to_report_call) {
1740 // Perform the action without printing the call information.
1741 return action.IsDoDefault() ? PerformDefaultAction(args, "") :
1742 action.Perform(args);
1743 }
1744
1745 ss << " Function call: " << Name();
1746 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1747
1748 // In case the action deletes a piece of the expectation, we
1749 // generate the message beforehand.
1750 if (found && !is_excessive) {
1751 exp->DescribeLocationTo(&loc);
1752 }
1753
1754 const ResultHolder result = action.IsDoDefault() ?
1755 ResultHolder::PerformDefaultAction(this, args, ss.str()) :
1756 ResultHolder::PerformAction(action, args);
1757 result.PrintAsActionResult(&ss);
1758 ss << "\n" << why.str();
1759
1760 if (!found) {
1761 // No expectation matches this call - reports a failure.
1762 Expect(false, NULL, -1, ss.str());
1763 } else if (is_excessive) {
1764 // We had an upper-bound violation and the failure message is in ss.
1765 Expect(false, exp->file(), exp->line(), ss.str());
1766 } else {
1767 // We had an expected call and the matching expectation is
1768 // described in ss.
1769 Log(INFO, loc.str() + ss.str(), 2);
1770 }
1771 return result.value();
1772}
shiqiane35fdd92008-12-10 05:08:54 +00001773
1774} // namespace internal
1775
1776// The style guide prohibits "using" statements in a namespace scope
1777// inside a header file. However, the MockSpec class template is
1778// meant to be defined in the ::testing namespace. The following line
1779// is just a trick for working around a bug in MSVC 8.0, which cannot
1780// handle it if we define MockSpec in ::testing.
1781using internal::MockSpec;
1782
1783// Const(x) is a convenient function for obtaining a const reference
1784// to x. This is useful for setting expectations on an overloaded
1785// const mock method, e.g.
1786//
1787// class MockFoo : public FooInterface {
1788// public:
1789// MOCK_METHOD0(Bar, int());
1790// MOCK_CONST_METHOD0(Bar, int&());
1791// };
1792//
1793// MockFoo foo;
1794// // Expects a call to non-const MockFoo::Bar().
1795// EXPECT_CALL(foo, Bar());
1796// // Expects a call to const MockFoo::Bar().
1797// EXPECT_CALL(Const(foo), Bar());
1798template <typename T>
1799inline const T& Const(const T& x) { return x; }
1800
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001801// Constructs an Expectation object that references and co-owns exp.
1802inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1803 : expectation_base_(exp.GetHandle().expectation_base()) {}
1804
shiqiane35fdd92008-12-10 05:08:54 +00001805} // namespace testing
1806
1807// A separate macro is required to avoid compile errors when the name
1808// of the method used in call is a result of macro expansion.
1809// See CompilesWithMethodNameExpandedFromMacro tests in
1810// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001811#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001812 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1813 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001814#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001815
zhanyong.wane0d051e2009-02-19 00:33:37 +00001816#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001817 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001818#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001819
1820#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_