blob: 0748d9d41d906d04a9edeffd9d464ce53a001b82 [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().
354class Expectation {
355 public:
356 // Constructs a null object that doesn't reference any expectation.
357 Expectation() {}
358
359 // This single-argument ctor must not be explicit, in order to support the
360 // Expectation e = EXPECT_CALL(...);
361 // syntax.
362 //
363 // A TypedExpectation object stores its pre-requisites as
364 // Expectation objects, and needs to call the non-const Retire()
365 // method on the ExpectationBase objects they reference. Therefore
366 // Expectation must receive a *non-const* reference to the
367 // ExpectationBase object.
368 Expectation(internal::ExpectationBase& exp); // NOLINT
369
370 // The compiler-generated copy ctor and operator= work exactly as
371 // intended, so we don't need to define our own.
372
373 // Returns true iff rhs references the same expectation as this object does.
374 bool operator==(const Expectation& rhs) const {
375 return expectation_base_ == rhs.expectation_base_;
376 }
377
378 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
379
380 private:
381 friend class ExpectationSet;
382 friend class Sequence;
383 friend class ::testing::internal::ExpectationBase;
384
385 template <typename F>
386 friend class ::testing::internal::FunctionMockerBase;
387
388 template <typename F>
389 friend class ::testing::internal::TypedExpectation;
390
391 // This comparator is needed for putting Expectation objects into a set.
392 class Less {
393 public:
394 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
395 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
396 }
397 };
398
399 typedef ::std::set<Expectation, Less> Set;
400
401 Expectation(
402 const internal::linked_ptr<internal::ExpectationBase>& expectation_base) :
403 expectation_base_(expectation_base) {}
404
405 // Returns the expectation this object references.
406 const internal::linked_ptr<internal::ExpectationBase>&
407 expectation_base() const {
408 return expectation_base_;
409 }
410
411 // A linked_ptr that co-owns the expectation this handle references.
412 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
413};
414
415// A set of expectation handles. Useful in the .After() clause of
416// EXPECT_CALL() for setting the (partial) order of expectations. The
417// syntax:
418//
419// ExpectationSet es;
420// es += EXPECT_CALL(...)...;
421// es += EXPECT_CALL(...)...;
422// EXPECT_CALL(...).After(es)...;
423//
424// sets three expectations where the last one can only be matched
425// after the first two have both been satisfied.
426//
427// This class is copyable and has value semantics.
428class ExpectationSet {
429 public:
430 // A bidirectional iterator that can read a const element in the set.
431 typedef Expectation::Set::const_iterator const_iterator;
432
433 // An object stored in the set. This is an alias of Expectation.
434 typedef Expectation::Set::value_type value_type;
435
436 // Constructs an empty set.
437 ExpectationSet() {}
438
439 // This single-argument ctor must not be explicit, in order to support the
440 // ExpectationSet es = EXPECT_CALL(...);
441 // syntax.
442 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
443 *this += Expectation(exp);
444 }
445
446 // This single-argument ctor implements implicit conversion from
447 // Expectation and thus must not be explicit. This allows either an
448 // Expectation or an ExpectationSet to be used in .After().
449 ExpectationSet(const Expectation& e) { // NOLINT
450 *this += e;
451 }
452
453 // The compiler-generator ctor and operator= works exactly as
454 // intended, so we don't need to define our own.
455
456 // Returns true iff rhs contains the same set of Expectation objects
457 // as this does.
458 bool operator==(const ExpectationSet& rhs) const {
459 return expectations_ == rhs.expectations_;
460 }
461
462 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
463
464 // Implements the syntax
465 // expectation_set += EXPECT_CALL(...);
466 ExpectationSet& operator+=(const Expectation& e) {
467 expectations_.insert(e);
468 return *this;
469 }
470
471 int size() const { return static_cast<int>(expectations_.size()); }
472
473 const_iterator begin() const { return expectations_.begin(); }
474 const_iterator end() const { return expectations_.end(); }
475
476 private:
477 Expectation::Set expectations_;
478};
479
480
shiqiane35fdd92008-12-10 05:08:54 +0000481// Sequence objects are used by a user to specify the relative order
482// in which the expectations should match. They are copyable (we rely
483// on the compiler-defined copy constructor and assignment operator).
484class Sequence {
485 public:
486 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000487 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000488
489 // Adds an expectation to this sequence. The caller must ensure
490 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000491 void AddExpectation(const Expectation& expectation) const;
492
shiqiane35fdd92008-12-10 05:08:54 +0000493 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000494 // The last expectation in this sequence. We use a linked_ptr here
495 // because Sequence objects are copyable and we want the copies to
496 // be aliases. The linked_ptr allows the copies to co-own and share
497 // the same Expectation object.
498 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000499}; // class Sequence
500
501// An object of this type causes all EXPECT_CALL() statements
502// encountered in its scope to be put in an anonymous sequence. The
503// work is done in the constructor and destructor. You should only
504// create an InSequence object on the stack.
505//
506// The sole purpose for this class is to support easy definition of
507// sequential expectations, e.g.
508//
509// {
510// InSequence dummy; // The name of the object doesn't matter.
511//
512// // The following expectations must match in the order they appear.
513// EXPECT_CALL(a, Bar())...;
514// EXPECT_CALL(a, Baz())...;
515// ...
516// EXPECT_CALL(b, Xyz())...;
517// }
518//
519// You can create InSequence objects in multiple threads, as long as
520// they are used to affect different mock objects. The idea is that
521// each thread can create and set up its own mocks as if it's the only
522// thread. However, for clarity of your tests we recommend you to set
523// up mocks in the main thread unless you have a good reason not to do
524// so.
525class InSequence {
526 public:
527 InSequence();
528 ~InSequence();
529 private:
530 bool sequence_created_;
531
532 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wane0d051e2009-02-19 00:33:37 +0000533} GMOCK_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000534
535namespace internal {
536
537// Points to the implicit sequence introduced by a living InSequence
538// object (if any) in the current thread or NULL.
539extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
540
541// Base class for implementing expectations.
542//
543// There are two reasons for having a type-agnostic base class for
544// Expectation:
545//
546// 1. We need to store collections of expectations of different
547// types (e.g. all pre-requisites of a particular expectation, all
548// expectations in a sequence). Therefore these expectation objects
549// must share a common base class.
550//
551// 2. We can avoid binary code bloat by moving methods not depending
552// on the template argument of Expectation to the base class.
553//
554// This class is internal and mustn't be used by user code directly.
555class ExpectationBase {
556 public:
557 ExpectationBase(const char* file, int line);
558
559 virtual ~ExpectationBase();
560
561 // Where in the source file was the expectation spec defined?
562 const char* file() const { return file_; }
563 int line() const { return line_; }
564
565 // Returns the cardinality specified in the expectation spec.
566 const Cardinality& cardinality() const { return cardinality_; }
567
568 // Describes the source file location of this expectation.
569 void DescribeLocationTo(::std::ostream* os) const {
570 *os << file() << ":" << line() << ": ";
571 }
572
573 // Describes how many times a function call matching this
574 // expectation has occurred.
575 // L >= g_gmock_mutex
576 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
577 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000578 friend class ::testing::Expectation;
shiqiane35fdd92008-12-10 05:08:54 +0000579
580 enum Clause {
581 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000582 kNone,
583 kWith,
584 kTimes,
585 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000586 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000587 kWillOnce,
588 kWillRepeatedly,
589 kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000590 };
591
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000592 // Returns an Expectation object that references and co-owns this
593 // expectation.
594 virtual Expectation GetHandle() = 0;
595
shiqiane35fdd92008-12-10 05:08:54 +0000596 // Asserts that the EXPECT_CALL() statement has the given property.
597 void AssertSpecProperty(bool property, const string& failure_message) const {
598 Assert(property, file_, line_, failure_message);
599 }
600
601 // Expects that the EXPECT_CALL() statement has the given property.
602 void ExpectSpecProperty(bool property, const string& failure_message) const {
603 Expect(property, file_, line_, failure_message);
604 }
605
606 // Explicitly specifies the cardinality of this expectation. Used
607 // by the subclasses to implement the .Times() clause.
608 void SpecifyCardinality(const Cardinality& cardinality);
609
610 // Returns true iff the user specified the cardinality explicitly
611 // using a .Times().
612 bool cardinality_specified() const { return cardinality_specified_; }
613
614 // Sets the cardinality of this expectation spec.
615 void set_cardinality(const Cardinality& cardinality) {
616 cardinality_ = cardinality;
617 }
618
619 // The following group of methods should only be called after the
620 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
621 // the current thread.
622
623 // Retires all pre-requisites of this expectation.
624 // L >= g_gmock_mutex
625 void RetireAllPreRequisites();
626
627 // Returns true iff this expectation is retired.
628 // L >= g_gmock_mutex
629 bool is_retired() const {
630 g_gmock_mutex.AssertHeld();
631 return retired_;
632 }
633
634 // Retires this expectation.
635 // L >= g_gmock_mutex
636 void Retire() {
637 g_gmock_mutex.AssertHeld();
638 retired_ = true;
639 }
640
641 // Returns true iff this expectation is satisfied.
642 // L >= g_gmock_mutex
643 bool IsSatisfied() const {
644 g_gmock_mutex.AssertHeld();
645 return cardinality().IsSatisfiedByCallCount(call_count_);
646 }
647
648 // Returns true iff this expectation is saturated.
649 // L >= g_gmock_mutex
650 bool IsSaturated() const {
651 g_gmock_mutex.AssertHeld();
652 return cardinality().IsSaturatedByCallCount(call_count_);
653 }
654
655 // Returns true iff this expectation is over-saturated.
656 // L >= g_gmock_mutex
657 bool IsOverSaturated() const {
658 g_gmock_mutex.AssertHeld();
659 return cardinality().IsOverSaturatedByCallCount(call_count_);
660 }
661
662 // Returns true iff all pre-requisites of this expectation are satisfied.
663 // L >= g_gmock_mutex
664 bool AllPrerequisitesAreSatisfied() const;
665
666 // Adds unsatisfied pre-requisites of this expectation to 'result'.
667 // L >= g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000668 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const;
shiqiane35fdd92008-12-10 05:08:54 +0000669
670 // Returns the number this expectation has been invoked.
671 // L >= g_gmock_mutex
672 int call_count() const {
673 g_gmock_mutex.AssertHeld();
674 return call_count_;
675 }
676
677 // Increments the number this expectation has been invoked.
678 // L >= g_gmock_mutex
679 void IncrementCallCount() {
680 g_gmock_mutex.AssertHeld();
681 call_count_++;
682 }
683
684 private:
685 friend class ::testing::Sequence;
686 friend class ::testing::internal::ExpectationTester;
687
688 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000689 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000690
691 // This group of fields are part of the spec and won't change after
692 // an EXPECT_CALL() statement finishes.
693 const char* file_; // The file that contains the expectation.
694 int line_; // The line number of the expectation.
695 // True iff the cardinality is specified explicitly.
696 bool cardinality_specified_;
697 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000698 // The immediate pre-requisites (i.e. expectations that must be
699 // satisfied before this expectation can be matched) of this
700 // expectation. We use linked_ptr in the set because we want an
701 // Expectation object to be co-owned by its FunctionMocker and its
702 // successors. This allows multiple mock objects to be deleted at
703 // different times.
704 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000705
706 // This group of fields are the current state of the expectation,
707 // and can change as the mock function is called.
708 int call_count_; // How many times this expectation has been invoked.
709 bool retired_; // True iff this expectation has retired.
710}; // class ExpectationBase
711
712// Impements an expectation for the given function type.
713template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000714class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000715 public:
716 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
717 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
718 typedef typename Function<F>::Result Result;
719
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000720 TypedExpectation(FunctionMockerBase<F>* owner, const char* file, int line,
721 const ArgumentMatcherTuple& m)
shiqiane35fdd92008-12-10 05:08:54 +0000722 : ExpectationBase(file, line),
723 owner_(owner),
724 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000725 // By default, extra_matcher_ should match anything. However,
726 // we cannot initialize it with _ as that triggers a compiler
727 // bug in Symbian's C++ compiler (cannot decide between two
728 // overloaded constructors of Matcher<const ArgumentTuple&>).
729 extra_matcher_(A<const ArgumentTuple&>()),
shiqiane35fdd92008-12-10 05:08:54 +0000730 repeated_action_specified_(false),
731 repeated_action_(DoDefault()),
732 retires_on_saturation_(false),
zhanyong.wanbf550852009-06-09 06:09:53 +0000733 last_clause_(kNone),
shiqiane35fdd92008-12-10 05:08:54 +0000734 action_count_checked_(false) {}
735
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000736 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000737 // Check the validity of the action count if it hasn't been done
738 // yet (for example, if the expectation was never used).
739 CheckActionCountIfNotDone();
740 }
741
zhanyong.wanbf550852009-06-09 06:09:53 +0000742 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000743 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000744 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000745 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000746 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000747 "more than once in an EXPECT_CALL().");
748 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000749 ExpectSpecProperty(last_clause_ < kWith,
750 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000751 "clause in an EXPECT_CALL().");
752 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000753 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000754
755 extra_matcher_ = m;
756 return *this;
757 }
758
759 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000760 TypedExpectation& Times(const Cardinality& cardinality) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000761 if (last_clause_ ==kTimes) {
shiqiane35fdd92008-12-10 05:08:54 +0000762 ExpectSpecProperty(false,
763 ".Times() cannot appear "
764 "more than once in an EXPECT_CALL().");
765 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000766 ExpectSpecProperty(last_clause_ < kTimes,
shiqiane35fdd92008-12-10 05:08:54 +0000767 ".Times() cannot appear after "
768 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
769 "or .RetiresOnSaturation().");
770 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000771 last_clause_ = kTimes;
shiqiane35fdd92008-12-10 05:08:54 +0000772
773 ExpectationBase::SpecifyCardinality(cardinality);
774 return *this;
775 }
776
777 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000778 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000779 return Times(Exactly(n));
780 }
781
782 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000783 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000784 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000785 ".InSequence() cannot appear after .After(),"
786 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000787 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000788 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000789
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000790 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000791 return *this;
792 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000793 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000794 return InSequence(s1).InSequence(s2);
795 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000796 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
797 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000798 return InSequence(s1, s2).InSequence(s3);
799 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000800 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
801 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000802 return InSequence(s1, s2, s3).InSequence(s4);
803 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000804 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
805 const Sequence& s3, const Sequence& s4,
806 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000807 return InSequence(s1, s2, s3, s4).InSequence(s5);
808 }
809
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000810 // Implements that .After() clause.
811 TypedExpectation& After(const ExpectationSet& s) {
812 ExpectSpecProperty(last_clause_ <= kAfter,
813 ".After() cannot appear after .WillOnce(),"
814 " .WillRepeatedly(), or "
815 ".RetiresOnSaturation().");
816 last_clause_ = kAfter;
817
818 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
819 immediate_prerequisites_ += *it;
820 }
821 return *this;
822 }
823 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
824 return After(s1).After(s2);
825 }
826 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
827 const ExpectationSet& s3) {
828 return After(s1, s2).After(s3);
829 }
830 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
831 const ExpectationSet& s3, const ExpectationSet& s4) {
832 return After(s1, s2, s3).After(s4);
833 }
834 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
835 const ExpectationSet& s3, const ExpectationSet& s4,
836 const ExpectationSet& s5) {
837 return After(s1, s2, s3, s4).After(s5);
838 }
839
shiqiane35fdd92008-12-10 05:08:54 +0000840 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000841 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000842 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000843 ".WillOnce() cannot appear after "
844 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000845 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +0000846
847 actions_.push_back(action);
848 if (!cardinality_specified()) {
849 set_cardinality(Exactly(static_cast<int>(actions_.size())));
850 }
851 return *this;
852 }
853
854 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000855 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000856 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +0000857 ExpectSpecProperty(false,
858 ".WillRepeatedly() cannot appear "
859 "more than once in an EXPECT_CALL().");
860 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000861 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +0000862 ".WillRepeatedly() cannot appear "
863 "after .RetiresOnSaturation().");
864 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000865 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +0000866 repeated_action_specified_ = true;
867
868 repeated_action_ = action;
869 if (!cardinality_specified()) {
870 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
871 }
872
873 // Now that no more action clauses can be specified, we check
874 // whether their count makes sense.
875 CheckActionCountIfNotDone();
876 return *this;
877 }
878
879 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000880 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +0000881 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000882 ".RetiresOnSaturation() cannot appear "
883 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +0000884 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +0000885 retires_on_saturation_ = true;
886
887 // Now that no more action clauses can be specified, we check
888 // whether their count makes sense.
889 CheckActionCountIfNotDone();
890 return *this;
891 }
892
893 // Returns the matchers for the arguments as specified inside the
894 // EXPECT_CALL() macro.
895 const ArgumentMatcherTuple& matchers() const {
896 return matchers_;
897 }
898
zhanyong.wanbf550852009-06-09 06:09:53 +0000899 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +0000900 const Matcher<const ArgumentTuple&>& extra_matcher() const {
901 return extra_matcher_;
902 }
903
904 // Returns the sequence of actions specified by the .WillOnce() clause.
905 const std::vector<Action<F> >& actions() const { return actions_; }
906
907 // Returns the action specified by the .WillRepeatedly() clause.
908 const Action<F>& repeated_action() const { return repeated_action_; }
909
910 // Returns true iff the .RetiresOnSaturation() clause was specified.
911 bool retires_on_saturation() const { return retires_on_saturation_; }
912
913 // Describes how many times a function call matching this
914 // expectation has occurred (implements
915 // ExpectationBase::DescribeCallCountTo()).
916 // L >= g_gmock_mutex
917 virtual void DescribeCallCountTo(::std::ostream* os) const {
918 g_gmock_mutex.AssertHeld();
919
920 // Describes how many times the function is expected to be called.
921 *os << " Expected: to be ";
922 cardinality().DescribeTo(os);
923 *os << "\n Actual: ";
924 Cardinality::DescribeActualCallCountTo(call_count(), os);
925
926 // Describes the state of the expectation (e.g. is it satisfied?
927 // is it active?).
928 *os << " - " << (IsOverSaturated() ? "over-saturated" :
929 IsSaturated() ? "saturated" :
930 IsSatisfied() ? "satisfied" : "unsatisfied")
931 << " and "
932 << (is_retired() ? "retired" : "active");
933 }
934 private:
935 template <typename Function>
936 friend class FunctionMockerBase;
937
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000938 // Returns an Expectation object that references and co-owns this
939 // expectation.
940 virtual Expectation GetHandle() {
941 return owner_->GetHandleOf(this);
942 }
943
shiqiane35fdd92008-12-10 05:08:54 +0000944 // The following methods will be called only after the EXPECT_CALL()
945 // statement finishes and when the current thread holds
946 // g_gmock_mutex.
947
948 // Returns true iff this expectation matches the given arguments.
949 // L >= g_gmock_mutex
950 bool Matches(const ArgumentTuple& args) const {
951 g_gmock_mutex.AssertHeld();
952 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
953 }
954
955 // Returns true iff this expectation should handle the given arguments.
956 // L >= g_gmock_mutex
957 bool ShouldHandleArguments(const ArgumentTuple& args) const {
958 g_gmock_mutex.AssertHeld();
959
960 // In case the action count wasn't checked when the expectation
961 // was defined (e.g. if this expectation has no WillRepeatedly()
962 // or RetiresOnSaturation() clause), we check it when the
963 // expectation is used for the first time.
964 CheckActionCountIfNotDone();
965 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
966 }
967
968 // Describes the result of matching the arguments against this
969 // expectation to the given ostream.
970 // L >= g_gmock_mutex
971 void DescribeMatchResultTo(const ArgumentTuple& args,
972 ::std::ostream* os) const {
973 g_gmock_mutex.AssertHeld();
974
975 if (is_retired()) {
976 *os << " Expected: the expectation is active\n"
977 << " Actual: it is retired\n";
978 } else if (!Matches(args)) {
979 if (!TupleMatches(matchers_, args)) {
980 DescribeMatchFailureTupleTo(matchers_, args, os);
981 }
982 if (!extra_matcher_.Matches(args)) {
zhanyong.wan2661c682009-06-09 05:42:12 +0000983 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +0000984 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +0000985 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +0000986
987 internal::ExplainMatchResultAsNeededTo<const ArgumentTuple&>(
988 extra_matcher_, args, os);
989 *os << "\n";
990 }
991 } else if (!AllPrerequisitesAreSatisfied()) {
992 *os << " Expected: all pre-requisites are satisfied\n"
993 << " Actual: the following immediate pre-requisites "
994 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000995 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +0000996 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
997 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000998 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +0000999 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001000 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001001 *os << "pre-requisite #" << i++ << "\n";
1002 }
1003 *os << " (end of pre-requisites)\n";
1004 } else {
1005 // This line is here just for completeness' sake. It will never
1006 // be executed as currently the DescribeMatchResultTo() function
1007 // is called only when the mock function call does NOT match the
1008 // expectation.
1009 *os << "The call matches the expectation.\n";
1010 }
1011 }
1012
1013 // Returns the action that should be taken for the current invocation.
1014 // L >= g_gmock_mutex
1015 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
1016 const ArgumentTuple& args) const {
1017 g_gmock_mutex.AssertHeld();
1018 const int count = call_count();
1019 Assert(count >= 1, __FILE__, __LINE__,
1020 "call_count() is <= 0 when GetCurrentAction() is "
1021 "called - this should never happen.");
1022
1023 const int action_count = static_cast<int>(actions().size());
1024 if (action_count > 0 && !repeated_action_specified_ &&
1025 count > action_count) {
1026 // If there is at least one WillOnce() and no WillRepeatedly(),
1027 // we warn the user when the WillOnce() clauses ran out.
1028 ::std::stringstream ss;
1029 DescribeLocationTo(&ss);
1030 ss << "Actions ran out.\n"
1031 << "Called " << count << " times, but only "
1032 << action_count << " WillOnce()"
1033 << (action_count == 1 ? " is" : "s are") << " specified - ";
1034 mocker->DescribeDefaultActionTo(args, &ss);
1035 Log(WARNING, ss.str(), 1);
1036 }
1037
1038 return count <= action_count ? actions()[count - 1] : repeated_action();
1039 }
1040
1041 // Given the arguments of a mock function call, if the call will
1042 // over-saturate this expectation, returns the default action;
1043 // otherwise, returns the next action in this expectation. Also
1044 // describes *what* happened to 'what', and explains *why* Google
1045 // Mock does it to 'why'. This method is not const as it calls
1046 // IncrementCallCount().
1047 // L >= g_gmock_mutex
1048 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
1049 const ArgumentTuple& args,
1050 ::std::ostream* what,
1051 ::std::ostream* why) {
1052 g_gmock_mutex.AssertHeld();
1053 if (IsSaturated()) {
1054 // We have an excessive call.
1055 IncrementCallCount();
1056 *what << "Mock function called more times than expected - ";
1057 mocker->DescribeDefaultActionTo(args, what);
1058 DescribeCallCountTo(why);
1059
1060 // TODO(wan): allow the user to control whether unexpected calls
1061 // should fail immediately or continue using a flag
1062 // --gmock_unexpected_calls_are_fatal.
1063 return DoDefault();
1064 }
1065
1066 IncrementCallCount();
1067 RetireAllPreRequisites();
1068
1069 if (retires_on_saturation() && IsSaturated()) {
1070 Retire();
1071 }
1072
1073 // Must be done after IncrementCount()!
1074 *what << "Expected mock function call.\n";
1075 return GetCurrentAction(mocker, args);
1076 }
1077
1078 // Checks the action count (i.e. the number of WillOnce() and
1079 // WillRepeatedly() clauses) against the cardinality if this hasn't
1080 // been done before. Prints a warning if there are too many or too
1081 // few actions.
1082 // L < mutex_
1083 void CheckActionCountIfNotDone() const {
1084 bool should_check = false;
1085 {
1086 MutexLock l(&mutex_);
1087 if (!action_count_checked_) {
1088 action_count_checked_ = true;
1089 should_check = true;
1090 }
1091 }
1092
1093 if (should_check) {
1094 if (!cardinality_specified_) {
1095 // The cardinality was inferred - no need to check the action
1096 // count against it.
1097 return;
1098 }
1099
1100 // The cardinality was explicitly specified.
1101 const int action_count = static_cast<int>(actions_.size());
1102 const int upper_bound = cardinality().ConservativeUpperBound();
1103 const int lower_bound = cardinality().ConservativeLowerBound();
1104 bool too_many; // True if there are too many actions, or false
1105 // if there are too few.
1106 if (action_count > upper_bound ||
1107 (action_count == upper_bound && repeated_action_specified_)) {
1108 too_many = true;
1109 } else if (0 < action_count && action_count < lower_bound &&
1110 !repeated_action_specified_) {
1111 too_many = false;
1112 } else {
1113 return;
1114 }
1115
1116 ::std::stringstream ss;
1117 DescribeLocationTo(&ss);
1118 ss << "Too " << (too_many ? "many" : "few")
1119 << " actions specified.\n"
1120 << "Expected to be ";
1121 cardinality().DescribeTo(&ss);
1122 ss << ", but has " << (too_many ? "" : "only ")
1123 << action_count << " WillOnce()"
1124 << (action_count == 1 ? "" : "s");
1125 if (repeated_action_specified_) {
1126 ss << " and a WillRepeatedly()";
1127 }
1128 ss << ".";
1129 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
1130 }
1131 }
1132
1133 // All the fields below won't change once the EXPECT_CALL()
1134 // statement finishes.
1135 FunctionMockerBase<F>* const owner_;
1136 ArgumentMatcherTuple matchers_;
1137 Matcher<const ArgumentTuple&> extra_matcher_;
1138 std::vector<Action<F> > actions_;
1139 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
1140 Action<F> repeated_action_;
1141 bool retires_on_saturation_;
1142 Clause last_clause_;
1143 mutable bool action_count_checked_; // Under mutex_.
1144 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001145}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001146
1147// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1148// specifying the default behavior of, or expectation on, a mock
1149// function.
1150
1151// Note: class MockSpec really belongs to the ::testing namespace.
1152// However if we define it in ::testing, MSVC will complain when
1153// classes in ::testing::internal declare it as a friend class
1154// template. To workaround this compiler bug, we define MockSpec in
1155// ::testing::internal and import it into ::testing.
1156
1157template <typename F>
1158class MockSpec {
1159 public:
1160 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1161 typedef typename internal::Function<F>::ArgumentMatcherTuple
1162 ArgumentMatcherTuple;
1163
1164 // Constructs a MockSpec object, given the function mocker object
1165 // that the spec is associated with.
1166 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1167 : function_mocker_(function_mocker) {}
1168
1169 // Adds a new default action spec to the function mocker and returns
1170 // the newly created spec.
1171 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
1172 const char* file, int line, const char* obj, const char* call) {
1173 LogWithLocation(internal::INFO, file, line,
1174 string("ON_CALL(") + obj + ", " + call + ") invoked");
1175 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
1176 }
1177
1178 // Adds a new expectation spec to the function mocker and returns
1179 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001180 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001181 const char* file, int line, const char* obj, const char* call) {
1182 LogWithLocation(internal::INFO, file, line,
1183 string("EXPECT_CALL(") + obj + ", " + call + ") invoked");
1184 return function_mocker_->AddNewExpectation(file, line, matchers_);
1185 }
1186
1187 private:
1188 template <typename Function>
1189 friend class internal::FunctionMocker;
1190
1191 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1192 matchers_ = matchers;
1193 }
1194
1195 // Logs a message including file and line number information.
1196 void LogWithLocation(testing::internal::LogSeverity severity,
1197 const char* file, int line,
1198 const string& message) {
1199 ::std::ostringstream s;
1200 s << file << ":" << line << ": " << message << ::std::endl;
1201 Log(severity, s.str(), 0);
1202 }
1203
1204 // The function mocker that owns this spec.
1205 internal::FunctionMockerBase<F>* const function_mocker_;
1206 // The argument matchers specified in the spec.
1207 ArgumentMatcherTuple matchers_;
1208}; // class MockSpec
1209
1210// MSVC warns about using 'this' in base member initializer list, so
1211// we need to temporarily disable the warning. We have to do it for
1212// the entire class to suppress the warning, even though it's about
1213// the constructor only.
1214
1215#ifdef _MSC_VER
1216#pragma warning(push) // Saves the current warning state.
1217#pragma warning(disable:4355) // Temporarily disables warning 4355.
1218#endif // _MSV_VER
1219
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001220// C++ treats the void type specially. For example, you cannot define
1221// a void-typed variable or pass a void value to a function.
1222// ActionResultHolder<T> holds a value of type T, where T must be a
1223// copyable type or void (T doesn't need to be default-constructable).
1224// It hides the syntactic difference between void and other types, and
1225// is used to unify the code for invoking both void-returning and
1226// non-void-returning mock functions. This generic definition is used
1227// when T is not void.
1228template <typename T>
1229class ActionResultHolder {
1230 public:
1231 explicit ActionResultHolder(T value) : value_(value) {}
1232
1233 // The compiler-generated copy constructor and assignment operator
1234 // are exactly what we need, so we don't need to define them.
1235
1236 T value() const { return value_; }
1237
1238 // Prints the held value as an action's result to os.
1239 void PrintAsActionResult(::std::ostream* os) const {
1240 *os << "\n Returns: ";
1241 UniversalPrinter<T>::Print(value_, os);
1242 }
1243
1244 // Performs the given mock function's default action and returns the
1245 // result in a ActionResultHolder.
1246 template <typename Function, typename Arguments>
1247 static ActionResultHolder PerformDefaultAction(
1248 const FunctionMockerBase<Function>* func_mocker,
1249 const Arguments& args,
1250 const string& call_description) {
1251 return ActionResultHolder(
1252 func_mocker->PerformDefaultAction(args, call_description));
1253 }
1254
1255 // Performs the given action and returns the result in a
1256 // ActionResultHolder.
1257 template <typename Function, typename Arguments>
1258 static ActionResultHolder PerformAction(const Action<Function>& action,
1259 const Arguments& args) {
1260 return ActionResultHolder(action.Perform(args));
1261 }
1262
1263 private:
1264 T value_;
1265};
1266
1267// Specialization for T = void.
1268template <>
1269class ActionResultHolder<void> {
1270 public:
1271 ActionResultHolder() {}
1272 void value() const {}
1273 void PrintAsActionResult(::std::ostream* /* os */) const {}
1274
1275 template <typename Function, typename Arguments>
1276 static ActionResultHolder PerformDefaultAction(
1277 const FunctionMockerBase<Function>* func_mocker,
1278 const Arguments& args,
1279 const string& call_description) {
1280 func_mocker->PerformDefaultAction(args, call_description);
1281 return ActionResultHolder();
1282 }
1283
1284 template <typename Function, typename Arguments>
1285 static ActionResultHolder PerformAction(const Action<Function>& action,
1286 const Arguments& args) {
1287 action.Perform(args);
1288 return ActionResultHolder();
1289 }
1290};
1291
shiqiane35fdd92008-12-10 05:08:54 +00001292// The base of the function mocker class for the given function type.
1293// We put the methods in this class instead of its child to avoid code
1294// bloat.
1295template <typename F>
1296class FunctionMockerBase : public UntypedFunctionMockerBase {
1297 public:
1298 typedef typename Function<F>::Result Result;
1299 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1300 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1301
1302 FunctionMockerBase() : mock_obj_(NULL), name_(""), current_spec_(this) {}
1303
1304 // The destructor verifies that all expectations on this mock
1305 // function have been satisfied. If not, it will report Google Test
1306 // non-fatal failures for the violations.
1307 // L < g_gmock_mutex
1308 virtual ~FunctionMockerBase() {
1309 MutexLock l(&g_gmock_mutex);
1310 VerifyAndClearExpectationsLocked();
1311 Mock::UnregisterLocked(this);
1312 }
1313
1314 // Returns the ON_CALL spec that matches this mock function with the
1315 // given arguments; returns NULL if no matching ON_CALL is found.
1316 // L = *
1317 const DefaultActionSpec<F>* FindDefaultActionSpec(
1318 const ArgumentTuple& args) const {
1319 for (typename std::vector<DefaultActionSpec<F> >::const_reverse_iterator it
1320 = default_actions_.rbegin();
1321 it != default_actions_.rend(); ++it) {
1322 const DefaultActionSpec<F>& spec = *it;
1323 if (spec.Matches(args))
1324 return &spec;
1325 }
1326
1327 return NULL;
1328 }
1329
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001330 // Performs the default action of this mock function on the given arguments
1331 // and returns the result. Asserts with a helpful call descrption if there is
1332 // no valid return value. This method doesn't depend on the mutable state of
1333 // this object, and thus can be called concurrently without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001334 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001335 Result PerformDefaultAction(const ArgumentTuple& args,
1336 const string& call_description) const {
shiqiane35fdd92008-12-10 05:08:54 +00001337 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001338 if (spec != NULL) {
1339 return spec->GetAction().Perform(args);
1340 }
1341 Assert(DefaultValue<Result>::Exists(), "", -1,
1342 call_description + "\n The mock function has no default action "
1343 "set, and its return type has no default value set.");
1344 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001345 }
1346
1347 // Registers this function mocker and the mock object owning it;
1348 // returns a reference to the function mocker object. This is only
1349 // called by the ON_CALL() and EXPECT_CALL() macros.
zhanyong.wandf35a762009-04-22 22:25:31 +00001350 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001351 FunctionMocker<F>& RegisterOwner(const void* mock_obj) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001352 {
1353 MutexLock l(&g_gmock_mutex);
1354 mock_obj_ = mock_obj;
1355 }
shiqiane35fdd92008-12-10 05:08:54 +00001356 Mock::Register(mock_obj, this);
zhanyong.wan946bc642009-03-31 00:05:30 +00001357 return *::testing::internal::down_cast<FunctionMocker<F>*>(this);
shiqiane35fdd92008-12-10 05:08:54 +00001358 }
1359
1360 // The following two functions are from UntypedFunctionMockerBase.
1361
1362 // Verifies that all expectations on this mock function have been
1363 // satisfied. Reports one or more Google Test non-fatal failures
1364 // and returns false if not.
1365 // L >= g_gmock_mutex
1366 virtual bool VerifyAndClearExpectationsLocked();
1367
1368 // Clears the ON_CALL()s set on this mock function.
1369 // L >= g_gmock_mutex
1370 virtual void ClearDefaultActionsLocked() {
1371 g_gmock_mutex.AssertHeld();
1372 default_actions_.clear();
1373 }
1374
1375 // Sets the name of the function being mocked. Will be called upon
1376 // each invocation of this mock function.
1377 // L < g_gmock_mutex
1378 void SetOwnerAndName(const void* mock_obj, const char* name) {
1379 // We protect name_ under g_gmock_mutex in case this mock function
1380 // is called from two threads concurrently.
1381 MutexLock l(&g_gmock_mutex);
1382 mock_obj_ = mock_obj;
1383 name_ = name;
1384 }
1385
1386 // Returns the address of the mock object this method belongs to.
1387 // Must be called after SetOwnerAndName() has been called.
1388 // L < g_gmock_mutex
1389 const void* MockObject() const {
1390 const void* mock_obj;
1391 {
1392 // We protect mock_obj_ under g_gmock_mutex in case this mock
1393 // function is called from two threads concurrently.
1394 MutexLock l(&g_gmock_mutex);
1395 mock_obj = mock_obj_;
1396 }
1397 return mock_obj;
1398 }
1399
1400 // Returns the name of the function being mocked. Must be called
1401 // after SetOwnerAndName() has been called.
1402 // L < g_gmock_mutex
1403 const char* Name() const {
1404 const char* name;
1405 {
1406 // We protect name_ under g_gmock_mutex in case this mock
1407 // function is called from two threads concurrently.
1408 MutexLock l(&g_gmock_mutex);
1409 name = name_;
1410 }
1411 return name;
1412 }
1413 protected:
1414 template <typename Function>
1415 friend class MockSpec;
1416
shiqiane35fdd92008-12-10 05:08:54 +00001417 // Returns the result of invoking this mock function with the given
1418 // arguments. This function can be safely called from multiple
1419 // threads concurrently.
1420 // L < g_gmock_mutex
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001421 Result InvokeWith(const ArgumentTuple& args);
shiqiane35fdd92008-12-10 05:08:54 +00001422
1423 // Adds and returns a default action spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001424 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001425 DefaultActionSpec<F>& AddNewDefaultActionSpec(
1426 const char* file, int line,
1427 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001428 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
shiqiane35fdd92008-12-10 05:08:54 +00001429 default_actions_.push_back(DefaultActionSpec<F>(file, line, m));
1430 return default_actions_.back();
1431 }
1432
1433 // Adds and returns an expectation spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001434 // L < g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001435 TypedExpectation<F>& AddNewExpectation(
shiqiane35fdd92008-12-10 05:08:54 +00001436 const char* file, int line,
1437 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001438 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001439 const linked_ptr<TypedExpectation<F> > expectation(
1440 new TypedExpectation<F>(this, file, line, m));
shiqiane35fdd92008-12-10 05:08:54 +00001441 expectations_.push_back(expectation);
1442
1443 // Adds this expectation into the implicit sequence if there is one.
1444 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1445 if (implicit_sequence != NULL) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001446 implicit_sequence->AddExpectation(Expectation(expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001447 }
1448
1449 return *expectation;
1450 }
1451
1452 // The current spec (either default action spec or expectation spec)
1453 // being described on this function mocker.
1454 MockSpec<F>& current_spec() { return current_spec_; }
1455 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001456 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001457
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001458 typedef std::vector<internal::linked_ptr<TypedExpectation<F> > >
1459 TypedExpectations;
shiqiane35fdd92008-12-10 05:08:54 +00001460
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001461 // Returns an Expectation object that references and co-owns exp,
1462 // which must be an expectation on this mock function.
1463 Expectation GetHandleOf(TypedExpectation<F>* exp) {
1464 for (typename TypedExpectations::const_iterator it = expectations_.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001465 it != expectations_.end(); ++it) {
1466 if (it->get() == exp) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001467 return Expectation(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001468 }
1469 }
1470
1471 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001472 return Expectation();
shiqiane35fdd92008-12-10 05:08:54 +00001473 // The above statement is just to make the code compile, and will
1474 // never be executed.
1475 }
1476
1477 // Some utilities needed for implementing InvokeWith().
1478
1479 // Describes what default action will be performed for the given
1480 // arguments.
1481 // L = *
1482 void DescribeDefaultActionTo(const ArgumentTuple& args,
1483 ::std::ostream* os) const {
1484 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1485
1486 if (spec == NULL) {
1487 *os << (internal::type_equals<Result, void>::value ?
1488 "returning directly.\n" :
1489 "returning default value.\n");
1490 } else {
1491 *os << "taking default action specified at:\n"
1492 << spec->file() << ":" << spec->line() << ":\n";
1493 }
1494 }
1495
1496 // Writes a message that the call is uninteresting (i.e. neither
1497 // explicitly expected nor explicitly unexpected) to the given
1498 // ostream.
1499 // L < g_gmock_mutex
1500 void DescribeUninterestingCall(const ArgumentTuple& args,
1501 ::std::ostream* os) const {
1502 *os << "Uninteresting mock function call - ";
1503 DescribeDefaultActionTo(args, os);
1504 *os << " Function call: " << Name();
1505 UniversalPrinter<ArgumentTuple>::Print(args, os);
1506 }
1507
1508 // Critical section: We must find the matching expectation and the
1509 // corresponding action that needs to be taken in an ATOMIC
1510 // transaction. Otherwise another thread may call this mock
1511 // method in the middle and mess up the state.
1512 //
1513 // However, performing the action has to be left out of the critical
1514 // section. The reason is that we have no control on what the
1515 // action does (it can invoke an arbitrary user function or even a
1516 // mock function) and excessive locking could cause a dead lock.
1517 // L < g_gmock_mutex
1518 bool FindMatchingExpectationAndAction(
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001519 const ArgumentTuple& args, TypedExpectation<F>** exp, Action<F>* action,
shiqiane35fdd92008-12-10 05:08:54 +00001520 bool* is_excessive, ::std::ostream* what, ::std::ostream* why) {
1521 MutexLock l(&g_gmock_mutex);
1522 *exp = this->FindMatchingExpectationLocked(args);
1523 if (*exp == NULL) { // A match wasn't found.
1524 *action = DoDefault();
1525 this->FormatUnexpectedCallMessageLocked(args, what, why);
1526 return false;
1527 }
1528
1529 // This line must be done before calling GetActionForArguments(),
1530 // which will increment the call count for *exp and thus affect
1531 // its saturation status.
1532 *is_excessive = (*exp)->IsSaturated();
1533 *action = (*exp)->GetActionForArguments(this, args, what, why);
1534 return true;
1535 }
1536
1537 // Returns the expectation that matches the arguments, or NULL if no
1538 // expectation matches them.
1539 // L >= g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001540 TypedExpectation<F>* FindMatchingExpectationLocked(
shiqiane35fdd92008-12-10 05:08:54 +00001541 const ArgumentTuple& args) const {
1542 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001543 for (typename TypedExpectations::const_reverse_iterator it =
shiqiane35fdd92008-12-10 05:08:54 +00001544 expectations_.rbegin();
1545 it != expectations_.rend(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001546 TypedExpectation<F>* const exp = it->get();
shiqiane35fdd92008-12-10 05:08:54 +00001547 if (exp->ShouldHandleArguments(args)) {
1548 return exp;
1549 }
1550 }
1551 return NULL;
1552 }
1553
1554 // Returns a message that the arguments don't match any expectation.
1555 // L >= g_gmock_mutex
1556 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1557 ::std::ostream* os,
1558 ::std::ostream* why) const {
1559 g_gmock_mutex.AssertHeld();
1560 *os << "\nUnexpected mock function call - ";
1561 DescribeDefaultActionTo(args, os);
1562 PrintTriedExpectationsLocked(args, why);
1563 }
1564
1565 // Prints a list of expectations that have been tried against the
1566 // current mock function call.
1567 // L >= g_gmock_mutex
1568 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1569 ::std::ostream* why) const {
1570 g_gmock_mutex.AssertHeld();
1571 const int count = static_cast<int>(expectations_.size());
1572 *why << "Google Mock tried the following " << count << " "
1573 << (count == 1 ? "expectation, but it didn't match" :
1574 "expectations, but none matched")
1575 << ":\n";
1576 for (int i = 0; i < count; i++) {
1577 *why << "\n";
1578 expectations_[i]->DescribeLocationTo(why);
1579 if (count > 1) {
1580 *why << "tried expectation #" << i;
1581 }
1582 *why << "\n";
1583 expectations_[i]->DescribeMatchResultTo(args, why);
1584 expectations_[i]->DescribeCallCountTo(why);
1585 }
1586 }
1587
zhanyong.wandf35a762009-04-22 22:25:31 +00001588 // Address of the mock object this mock method belongs to. Only
1589 // valid after this mock method has been called or
1590 // ON_CALL/EXPECT_CALL has been invoked on it.
shiqiane35fdd92008-12-10 05:08:54 +00001591 const void* mock_obj_; // Protected by g_gmock_mutex.
1592
zhanyong.wandf35a762009-04-22 22:25:31 +00001593 // Name of the function being mocked. Only valid after this mock
1594 // method has been called.
shiqiane35fdd92008-12-10 05:08:54 +00001595 const char* name_; // Protected by g_gmock_mutex.
1596
1597 // The current spec (either default action spec or expectation spec)
1598 // being described on this function mocker.
1599 MockSpec<F> current_spec_;
1600
1601 // All default action specs for this function mocker.
1602 std::vector<DefaultActionSpec<F> > default_actions_;
1603 // All expectations for this function mocker.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001604 TypedExpectations expectations_;
zhanyong.wan16cf4732009-05-14 20:55:30 +00001605
1606 // There is no generally useful and implementable semantics of
1607 // copying a mock object, so copying a mock is usually a user error.
1608 // Thus we disallow copying function mockers. If the user really
1609 // wants to copy a mock object, he should implement his own copy
1610 // operation, for example:
1611 //
1612 // class MockFoo : public Foo {
1613 // public:
1614 // // Defines a copy constructor explicitly.
1615 // MockFoo(const MockFoo& src) {}
1616 // ...
1617 // };
1618 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001619}; // class FunctionMockerBase
1620
1621#ifdef _MSC_VER
1622#pragma warning(pop) // Restores the warning state.
1623#endif // _MSV_VER
1624
1625// Implements methods of FunctionMockerBase.
1626
1627// Verifies that all expectations on this mock function have been
1628// satisfied. Reports one or more Google Test non-fatal failures and
1629// returns false if not.
1630// L >= g_gmock_mutex
1631template <typename F>
1632bool FunctionMockerBase<F>::VerifyAndClearExpectationsLocked() {
1633 g_gmock_mutex.AssertHeld();
1634 bool expectations_met = true;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001635 for (typename TypedExpectations::const_iterator it = expectations_.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001636 it != expectations_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001637 TypedExpectation<F>* const exp = it->get();
shiqiane35fdd92008-12-10 05:08:54 +00001638
1639 if (exp->IsOverSaturated()) {
1640 // There was an upper-bound violation. Since the error was
1641 // already reported when it occurred, there is no need to do
1642 // anything here.
1643 expectations_met = false;
1644 } else if (!exp->IsSatisfied()) {
1645 expectations_met = false;
1646 ::std::stringstream ss;
1647 ss << "Actual function call count doesn't match this expectation.\n";
1648 // No need to show the source file location of the expectation
1649 // in the description, as the Expect() call that follows already
1650 // takes care of it.
1651 exp->DescribeCallCountTo(&ss);
1652 Expect(false, exp->file(), exp->line(), ss.str());
1653 }
1654 }
1655 expectations_.clear();
1656 return expectations_met;
1657}
1658
1659// Reports an uninteresting call (whose description is in msg) in the
1660// manner specified by 'reaction'.
1661void ReportUninterestingCall(CallReaction reaction, const string& msg);
1662
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001663// Calculates the result of invoking this mock function with the given
1664// arguments, prints it, and returns it.
1665// L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001666template <typename F>
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001667typename Function<F>::Result FunctionMockerBase<F>::InvokeWith(
1668 const typename Function<F>::ArgumentTuple& args) {
1669 typedef ActionResultHolder<Result> ResultHolder;
shiqiane35fdd92008-12-10 05:08:54 +00001670
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001671 if (expectations_.size() == 0) {
1672 // No expectation is set on this mock method - we have an
1673 // uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001674
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001675 // We must get Google Mock's reaction on uninteresting calls
1676 // made on this mock object BEFORE performing the action,
1677 // because the action may DELETE the mock object and make the
1678 // following expression meaningless.
1679 const CallReaction reaction =
1680 Mock::GetReactionOnUninterestingCalls(MockObject());
shiqiane35fdd92008-12-10 05:08:54 +00001681
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001682 // True iff we need to print this call's arguments and return
1683 // value. This definition must be kept in sync with
1684 // the behavior of ReportUninterestingCall().
1685 const bool need_to_report_uninteresting_call =
1686 // If the user allows this uninteresting call, we print it
1687 // only when he wants informational messages.
1688 reaction == ALLOW ? LogIsVisible(INFO) :
1689 // If the user wants this to be a warning, we print it only
1690 // when he wants to see warnings.
1691 reaction == WARN ? LogIsVisible(WARNING) :
1692 // Otherwise, the user wants this to be an error, and we
1693 // should always print detailed information in the error.
1694 true;
1695
1696 if (!need_to_report_uninteresting_call) {
1697 // Perform the action without printing the call information.
1698 return PerformDefaultAction(args, "");
shiqiane35fdd92008-12-10 05:08:54 +00001699 }
1700
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001701 // Warns about the uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001702 ::std::stringstream ss;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001703 DescribeUninterestingCall(args, &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001704
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001705 // Calculates the function result.
1706 const ResultHolder result =
1707 ResultHolder::PerformDefaultAction(this, args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001708
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001709 // Prints the function result.
1710 result.PrintAsActionResult(&ss);
1711
1712 ReportUninterestingCall(reaction, ss.str());
1713 return result.value();
shiqiane35fdd92008-12-10 05:08:54 +00001714 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001715
1716 bool is_excessive = false;
1717 ::std::stringstream ss;
1718 ::std::stringstream why;
1719 ::std::stringstream loc;
1720 Action<F> action;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001721 TypedExpectation<F>* exp;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001722
1723 // The FindMatchingExpectationAndAction() function acquires and
1724 // releases g_gmock_mutex.
1725 const bool found = FindMatchingExpectationAndAction(
1726 args, &exp, &action, &is_excessive, &ss, &why);
1727
1728 // True iff we need to print the call's arguments and return value.
1729 // This definition must be kept in sync with the uses of Expect()
1730 // and Log() in this function.
1731 const bool need_to_report_call = !found || is_excessive || LogIsVisible(INFO);
1732 if (!need_to_report_call) {
1733 // Perform the action without printing the call information.
1734 return action.IsDoDefault() ? PerformDefaultAction(args, "") :
1735 action.Perform(args);
1736 }
1737
1738 ss << " Function call: " << Name();
1739 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1740
1741 // In case the action deletes a piece of the expectation, we
1742 // generate the message beforehand.
1743 if (found && !is_excessive) {
1744 exp->DescribeLocationTo(&loc);
1745 }
1746
1747 const ResultHolder result = action.IsDoDefault() ?
1748 ResultHolder::PerformDefaultAction(this, args, ss.str()) :
1749 ResultHolder::PerformAction(action, args);
1750 result.PrintAsActionResult(&ss);
1751 ss << "\n" << why.str();
1752
1753 if (!found) {
1754 // No expectation matches this call - reports a failure.
1755 Expect(false, NULL, -1, ss.str());
1756 } else if (is_excessive) {
1757 // We had an upper-bound violation and the failure message is in ss.
1758 Expect(false, exp->file(), exp->line(), ss.str());
1759 } else {
1760 // We had an expected call and the matching expectation is
1761 // described in ss.
1762 Log(INFO, loc.str() + ss.str(), 2);
1763 }
1764 return result.value();
1765}
shiqiane35fdd92008-12-10 05:08:54 +00001766
1767} // namespace internal
1768
1769// The style guide prohibits "using" statements in a namespace scope
1770// inside a header file. However, the MockSpec class template is
1771// meant to be defined in the ::testing namespace. The following line
1772// is just a trick for working around a bug in MSVC 8.0, which cannot
1773// handle it if we define MockSpec in ::testing.
1774using internal::MockSpec;
1775
1776// Const(x) is a convenient function for obtaining a const reference
1777// to x. This is useful for setting expectations on an overloaded
1778// const mock method, e.g.
1779//
1780// class MockFoo : public FooInterface {
1781// public:
1782// MOCK_METHOD0(Bar, int());
1783// MOCK_CONST_METHOD0(Bar, int&());
1784// };
1785//
1786// MockFoo foo;
1787// // Expects a call to non-const MockFoo::Bar().
1788// EXPECT_CALL(foo, Bar());
1789// // Expects a call to const MockFoo::Bar().
1790// EXPECT_CALL(Const(foo), Bar());
1791template <typename T>
1792inline const T& Const(const T& x) { return x; }
1793
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001794// Constructs an Expectation object that references and co-owns exp.
1795inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1796 : expectation_base_(exp.GetHandle().expectation_base()) {}
1797
shiqiane35fdd92008-12-10 05:08:54 +00001798} // namespace testing
1799
1800// A separate macro is required to avoid compile errors when the name
1801// of the method used in call is a result of macro expansion.
1802// See CompilesWithMethodNameExpandedFromMacro tests in
1803// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001804#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001805 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1806 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001807#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001808
zhanyong.wane0d051e2009-02-19 00:33:37 +00001809#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001810 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001811#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001812
1813#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_