blob: 74a095da7571c4b9a6a50e48dce971eef38b50f0 [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.
zhanyong.wan5905ba02010-02-24 17:21:37 +0000115GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000116
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.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000145 DefaultActionSpec(const char* a_file, int a_line,
shiqiane35fdd92008-12-10 05:08:54 +0000146 const ArgumentMatcherTuple& matchers)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000147 : file_(a_file),
148 line_(a_line),
shiqiane35fdd92008-12-10 05:08:54 +0000149 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 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000199
shiqiane35fdd92008-12-10 05:08:54 +0000200 private:
201 // Gives each clause in the ON_CALL() statement a name.
202 enum Clause {
203 // Do not change the order of the enum members! The run-time
204 // syntax checking relies on it.
zhanyong.wanbf550852009-06-09 06:09:53 +0000205 kNone,
206 kWith,
207 kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000208 };
209
210 // Asserts that the ON_CALL() statement has a certain property.
211 void AssertSpecProperty(bool property, const string& failure_message) const {
212 Assert(property, file_, line_, failure_message);
213 }
214
215 // Expects that the ON_CALL() statement has a certain property.
216 void ExpectSpecProperty(bool property, const string& failure_message) const {
217 Expect(property, file_, line_, failure_message);
218 }
219
220 // The information in statement
221 //
222 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000223 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000224 // .WillByDefault(action);
225 //
226 // is recorded in the data members like this:
227 //
228 // source file that contains the statement => file_
229 // line number of the statement => line_
230 // matchers => matchers_
231 // multi-argument-matcher => extra_matcher_
232 // action => action_
233 const char* file_;
234 int line_;
235 ArgumentMatcherTuple matchers_;
236 Matcher<const ArgumentTuple&> extra_matcher_;
237 Action<F> action_;
238
239 // The last clause in the ON_CALL() statement as seen so far.
zhanyong.wanbf550852009-06-09 06:09:53 +0000240 // Initially kNone and changes as the statement is parsed.
shiqiane35fdd92008-12-10 05:08:54 +0000241 Clause last_clause_;
242}; // class DefaultActionSpec
243
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000244// Possible reactions on uninteresting calls. TODO(wan@google.com):
245// rename the enum values to the kFoo style.
shiqiane35fdd92008-12-10 05:08:54 +0000246enum CallReaction {
247 ALLOW,
248 WARN,
249 FAIL,
250};
251
252} // namespace internal
253
254// Utilities for manipulating mock objects.
255class Mock {
256 public:
257 // The following public methods can be called concurrently.
258
zhanyong.wandf35a762009-04-22 22:25:31 +0000259 // Tells Google Mock to ignore mock_obj when checking for leaked
260 // mock objects.
261 static void AllowLeak(const void* mock_obj);
262
shiqiane35fdd92008-12-10 05:08:54 +0000263 // Verifies and clears all expectations on the given mock object.
264 // If the expectations aren't satisfied, generates one or more
265 // Google Test non-fatal failures and returns false.
266 static bool VerifyAndClearExpectations(void* mock_obj);
267
268 // Verifies all expectations on the given mock object and clears its
269 // default actions and expectations. Returns true iff the
270 // verification was successful.
271 static bool VerifyAndClear(void* mock_obj);
272 private:
273 // Needed for a function mocker to register itself (so that we know
274 // how to clear a mock object).
275 template <typename F>
276 friend class internal::FunctionMockerBase;
277
shiqiane35fdd92008-12-10 05:08:54 +0000278 template <typename M>
279 friend class NiceMock;
280
281 template <typename M>
282 friend class StrictMock;
283
284 // Tells Google Mock to allow uninteresting calls on the given mock
285 // object.
286 // L < g_gmock_mutex
287 static void AllowUninterestingCalls(const void* mock_obj);
288
289 // Tells Google Mock to warn the user about uninteresting calls on
290 // the given mock object.
291 // L < g_gmock_mutex
292 static void WarnUninterestingCalls(const void* mock_obj);
293
294 // Tells Google Mock to fail uninteresting calls on the given mock
295 // object.
296 // L < g_gmock_mutex
297 static void FailUninterestingCalls(const void* mock_obj);
298
299 // Tells Google Mock the given mock object is being destroyed and
300 // its entry in the call-reaction table should be removed.
301 // L < g_gmock_mutex
302 static void UnregisterCallReaction(const void* mock_obj);
303
304 // Returns the reaction Google Mock will have on uninteresting calls
305 // made on the given mock object.
306 // L < g_gmock_mutex
307 static internal::CallReaction GetReactionOnUninterestingCalls(
308 const void* mock_obj);
309
310 // Verifies that all expectations on the given mock object have been
311 // satisfied. Reports one or more Google Test non-fatal failures
312 // and returns false if not.
313 // L >= g_gmock_mutex
314 static bool VerifyAndClearExpectationsLocked(void* mock_obj);
315
316 // Clears all ON_CALL()s set on the given mock object.
317 // L >= g_gmock_mutex
318 static void ClearDefaultActionsLocked(void* mock_obj);
319
320 // Registers a mock object and a mock method it owns.
321 // L < g_gmock_mutex
322 static void Register(const void* mock_obj,
323 internal::UntypedFunctionMockerBase* mocker);
324
zhanyong.wandf35a762009-04-22 22:25:31 +0000325 // Tells Google Mock where in the source code mock_obj is used in an
326 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
327 // information helps the user identify which object it is.
328 // L < g_gmock_mutex
329 static void RegisterUseByOnCallOrExpectCall(
330 const void* mock_obj, const char* file, int line);
331
shiqiane35fdd92008-12-10 05:08:54 +0000332 // Unregisters a mock method; removes the owning mock object from
333 // the registry when the last mock method associated with it has
334 // been unregistered. This is called only in the destructor of
335 // FunctionMockerBase.
336 // L >= g_gmock_mutex
337 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
338}; // class Mock
339
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000340// An abstract handle of an expectation. Useful in the .After()
341// clause of EXPECT_CALL() for setting the (partial) order of
342// expectations. The syntax:
343//
344// Expectation e1 = EXPECT_CALL(...)...;
345// EXPECT_CALL(...).After(e1)...;
346//
347// sets two expectations where the latter can only be matched after
348// the former has been satisfied.
349//
350// Notes:
351// - This class is copyable and has value semantics.
352// - Constness is shallow: a const Expectation object itself cannot
353// be modified, but the mutable methods of the ExpectationBase
354// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000355// - The constructors and destructor are defined out-of-line because
356// the Symbian WINSCW compiler wants to otherwise instantiate them
357// when it sees this class definition, at which point it doesn't have
358// ExpectationBase available yet, leading to incorrect destruction
359// in the linked_ptr (or compilation errors if using a checking
360// linked_ptr).
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000361class Expectation {
362 public:
363 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000364 Expectation();
365
366 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000367
368 // This single-argument ctor must not be explicit, in order to support the
369 // Expectation e = EXPECT_CALL(...);
370 // syntax.
371 //
372 // A TypedExpectation object stores its pre-requisites as
373 // Expectation objects, and needs to call the non-const Retire()
374 // method on the ExpectationBase objects they reference. Therefore
375 // Expectation must receive a *non-const* reference to the
376 // ExpectationBase object.
377 Expectation(internal::ExpectationBase& exp); // NOLINT
378
379 // The compiler-generated copy ctor and operator= work exactly as
380 // intended, so we don't need to define our own.
381
382 // Returns true iff rhs references the same expectation as this object does.
383 bool operator==(const Expectation& rhs) const {
384 return expectation_base_ == rhs.expectation_base_;
385 }
386
387 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
388
389 private:
390 friend class ExpectationSet;
391 friend class Sequence;
392 friend class ::testing::internal::ExpectationBase;
393
394 template <typename F>
395 friend class ::testing::internal::FunctionMockerBase;
396
397 template <typename F>
398 friend class ::testing::internal::TypedExpectation;
399
400 // This comparator is needed for putting Expectation objects into a set.
401 class Less {
402 public:
403 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
404 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
405 }
406 };
407
408 typedef ::std::set<Expectation, Less> Set;
409
410 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000411 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000412
413 // Returns the expectation this object references.
414 const internal::linked_ptr<internal::ExpectationBase>&
415 expectation_base() const {
416 return expectation_base_;
417 }
418
419 // A linked_ptr that co-owns the expectation this handle references.
420 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
421};
422
423// A set of expectation handles. Useful in the .After() clause of
424// EXPECT_CALL() for setting the (partial) order of expectations. The
425// syntax:
426//
427// ExpectationSet es;
428// es += EXPECT_CALL(...)...;
429// es += EXPECT_CALL(...)...;
430// EXPECT_CALL(...).After(es)...;
431//
432// sets three expectations where the last one can only be matched
433// after the first two have both been satisfied.
434//
435// This class is copyable and has value semantics.
436class ExpectationSet {
437 public:
438 // A bidirectional iterator that can read a const element in the set.
439 typedef Expectation::Set::const_iterator const_iterator;
440
441 // An object stored in the set. This is an alias of Expectation.
442 typedef Expectation::Set::value_type value_type;
443
444 // Constructs an empty set.
445 ExpectationSet() {}
446
447 // This single-argument ctor must not be explicit, in order to support the
448 // ExpectationSet es = EXPECT_CALL(...);
449 // syntax.
450 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
451 *this += Expectation(exp);
452 }
453
454 // This single-argument ctor implements implicit conversion from
455 // Expectation and thus must not be explicit. This allows either an
456 // Expectation or an ExpectationSet to be used in .After().
457 ExpectationSet(const Expectation& e) { // NOLINT
458 *this += e;
459 }
460
461 // The compiler-generator ctor and operator= works exactly as
462 // intended, so we don't need to define our own.
463
464 // Returns true iff rhs contains the same set of Expectation objects
465 // as this does.
466 bool operator==(const ExpectationSet& rhs) const {
467 return expectations_ == rhs.expectations_;
468 }
469
470 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
471
472 // Implements the syntax
473 // expectation_set += EXPECT_CALL(...);
474 ExpectationSet& operator+=(const Expectation& e) {
475 expectations_.insert(e);
476 return *this;
477 }
478
479 int size() const { return static_cast<int>(expectations_.size()); }
480
481 const_iterator begin() const { return expectations_.begin(); }
482 const_iterator end() const { return expectations_.end(); }
483
484 private:
485 Expectation::Set expectations_;
486};
487
488
shiqiane35fdd92008-12-10 05:08:54 +0000489// Sequence objects are used by a user to specify the relative order
490// in which the expectations should match. They are copyable (we rely
491// on the compiler-defined copy constructor and assignment operator).
492class Sequence {
493 public:
494 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000495 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000496
497 // Adds an expectation to this sequence. The caller must ensure
498 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000499 void AddExpectation(const Expectation& expectation) const;
500
shiqiane35fdd92008-12-10 05:08:54 +0000501 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000502 // The last expectation in this sequence. We use a linked_ptr here
503 // because Sequence objects are copyable and we want the copies to
504 // be aliases. The linked_ptr allows the copies to co-own and share
505 // the same Expectation object.
506 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000507}; // class Sequence
508
509// An object of this type causes all EXPECT_CALL() statements
510// encountered in its scope to be put in an anonymous sequence. The
511// work is done in the constructor and destructor. You should only
512// create an InSequence object on the stack.
513//
514// The sole purpose for this class is to support easy definition of
515// sequential expectations, e.g.
516//
517// {
518// InSequence dummy; // The name of the object doesn't matter.
519//
520// // The following expectations must match in the order they appear.
521// EXPECT_CALL(a, Bar())...;
522// EXPECT_CALL(a, Baz())...;
523// ...
524// EXPECT_CALL(b, Xyz())...;
525// }
526//
527// You can create InSequence objects in multiple threads, as long as
528// they are used to affect different mock objects. The idea is that
529// each thread can create and set up its own mocks as if it's the only
530// thread. However, for clarity of your tests we recommend you to set
531// up mocks in the main thread unless you have a good reason not to do
532// so.
533class InSequence {
534 public:
535 InSequence();
536 ~InSequence();
537 private:
538 bool sequence_created_;
539
540 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wane0d051e2009-02-19 00:33:37 +0000541} GMOCK_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000542
543namespace internal {
544
545// Points to the implicit sequence introduced by a living InSequence
546// object (if any) in the current thread or NULL.
547extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
548
549// Base class for implementing expectations.
550//
551// There are two reasons for having a type-agnostic base class for
552// Expectation:
553//
554// 1. We need to store collections of expectations of different
555// types (e.g. all pre-requisites of a particular expectation, all
556// expectations in a sequence). Therefore these expectation objects
557// must share a common base class.
558//
559// 2. We can avoid binary code bloat by moving methods not depending
560// on the template argument of Expectation to the base class.
561//
562// This class is internal and mustn't be used by user code directly.
563class ExpectationBase {
564 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000565 // source_text is the EXPECT_CALL(...) source that created this Expectation.
566 ExpectationBase(const char* file, int line, const string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000567
568 virtual ~ExpectationBase();
569
570 // Where in the source file was the expectation spec defined?
571 const char* file() const { return file_; }
572 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000573 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000574 // Returns the cardinality specified in the expectation spec.
575 const Cardinality& cardinality() const { return cardinality_; }
576
577 // Describes the source file location of this expectation.
578 void DescribeLocationTo(::std::ostream* os) const {
579 *os << file() << ":" << line() << ": ";
580 }
581
582 // Describes how many times a function call matching this
583 // expectation has occurred.
584 // L >= g_gmock_mutex
585 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000586
shiqiane35fdd92008-12-10 05:08:54 +0000587 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000588 friend class ::testing::Expectation;
shiqiane35fdd92008-12-10 05:08:54 +0000589
590 enum Clause {
591 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000592 kNone,
593 kWith,
594 kTimes,
595 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000596 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000597 kWillOnce,
598 kWillRepeatedly,
599 kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000600 };
601
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000602 // Returns an Expectation object that references and co-owns this
603 // expectation.
604 virtual Expectation GetHandle() = 0;
605
shiqiane35fdd92008-12-10 05:08:54 +0000606 // Asserts that the EXPECT_CALL() statement has the given property.
607 void AssertSpecProperty(bool property, const string& failure_message) const {
608 Assert(property, file_, line_, failure_message);
609 }
610
611 // Expects that the EXPECT_CALL() statement has the given property.
612 void ExpectSpecProperty(bool property, const string& failure_message) const {
613 Expect(property, file_, line_, failure_message);
614 }
615
616 // Explicitly specifies the cardinality of this expectation. Used
617 // by the subclasses to implement the .Times() clause.
618 void SpecifyCardinality(const Cardinality& cardinality);
619
620 // Returns true iff the user specified the cardinality explicitly
621 // using a .Times().
622 bool cardinality_specified() const { return cardinality_specified_; }
623
624 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000625 void set_cardinality(const Cardinality& a_cardinality) {
626 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000627 }
628
629 // The following group of methods should only be called after the
630 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
631 // the current thread.
632
633 // Retires all pre-requisites of this expectation.
634 // L >= g_gmock_mutex
635 void RetireAllPreRequisites();
636
637 // Returns true iff this expectation is retired.
638 // L >= g_gmock_mutex
639 bool is_retired() const {
640 g_gmock_mutex.AssertHeld();
641 return retired_;
642 }
643
644 // Retires this expectation.
645 // L >= g_gmock_mutex
646 void Retire() {
647 g_gmock_mutex.AssertHeld();
648 retired_ = true;
649 }
650
651 // Returns true iff this expectation is satisfied.
652 // L >= g_gmock_mutex
653 bool IsSatisfied() const {
654 g_gmock_mutex.AssertHeld();
655 return cardinality().IsSatisfiedByCallCount(call_count_);
656 }
657
658 // Returns true iff this expectation is saturated.
659 // L >= g_gmock_mutex
660 bool IsSaturated() const {
661 g_gmock_mutex.AssertHeld();
662 return cardinality().IsSaturatedByCallCount(call_count_);
663 }
664
665 // Returns true iff this expectation is over-saturated.
666 // L >= g_gmock_mutex
667 bool IsOverSaturated() const {
668 g_gmock_mutex.AssertHeld();
669 return cardinality().IsOverSaturatedByCallCount(call_count_);
670 }
671
672 // Returns true iff all pre-requisites of this expectation are satisfied.
673 // L >= g_gmock_mutex
674 bool AllPrerequisitesAreSatisfied() const;
675
676 // Adds unsatisfied pre-requisites of this expectation to 'result'.
677 // L >= g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000678 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const;
shiqiane35fdd92008-12-10 05:08:54 +0000679
680 // Returns the number this expectation has been invoked.
681 // L >= g_gmock_mutex
682 int call_count() const {
683 g_gmock_mutex.AssertHeld();
684 return call_count_;
685 }
686
687 // Increments the number this expectation has been invoked.
688 // L >= g_gmock_mutex
689 void IncrementCallCount() {
690 g_gmock_mutex.AssertHeld();
691 call_count_++;
692 }
693
694 private:
695 friend class ::testing::Sequence;
696 friend class ::testing::internal::ExpectationTester;
697
698 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000699 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000700
701 // This group of fields are part of the spec and won't change after
702 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000703 const char* file_; // The file that contains the expectation.
704 int line_; // The line number of the expectation.
705 const string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000706 // True iff the cardinality is specified explicitly.
707 bool cardinality_specified_;
708 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000709 // The immediate pre-requisites (i.e. expectations that must be
710 // satisfied before this expectation can be matched) of this
711 // expectation. We use linked_ptr in the set because we want an
712 // Expectation object to be co-owned by its FunctionMocker and its
713 // successors. This allows multiple mock objects to be deleted at
714 // different times.
715 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000716
717 // This group of fields are the current state of the expectation,
718 // and can change as the mock function is called.
719 int call_count_; // How many times this expectation has been invoked.
720 bool retired_; // True iff this expectation has retired.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000721
722 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000723}; // class ExpectationBase
724
725// Impements an expectation for the given function type.
726template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000727class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000728 public:
729 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
730 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
731 typedef typename Function<F>::Result Result;
732
vladlosev6c54a5e2009-10-21 06:15:34 +0000733 TypedExpectation(FunctionMockerBase<F>* owner,
zhanyong.wan32de5f52009-12-23 00:13:23 +0000734 const char* a_file, int a_line, const string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000735 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000736 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000737 owner_(owner),
738 matchers_(m),
vladlosev6c54a5e2009-10-21 06:15:34 +0000739 extra_matcher_specified_(false),
zhanyong.wan18490652009-05-11 18:54:08 +0000740 // By default, extra_matcher_ should match anything. However,
741 // we cannot initialize it with _ as that triggers a compiler
742 // bug in Symbian's C++ compiler (cannot decide between two
743 // overloaded constructors of Matcher<const ArgumentTuple&>).
744 extra_matcher_(A<const ArgumentTuple&>()),
shiqiane35fdd92008-12-10 05:08:54 +0000745 repeated_action_specified_(false),
746 repeated_action_(DoDefault()),
747 retires_on_saturation_(false),
zhanyong.wanbf550852009-06-09 06:09:53 +0000748 last_clause_(kNone),
shiqiane35fdd92008-12-10 05:08:54 +0000749 action_count_checked_(false) {}
750
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000751 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000752 // Check the validity of the action count if it hasn't been done
753 // yet (for example, if the expectation was never used).
754 CheckActionCountIfNotDone();
755 }
756
zhanyong.wanbf550852009-06-09 06:09:53 +0000757 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000758 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000759 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000760 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000761 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000762 "more than once in an EXPECT_CALL().");
763 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000764 ExpectSpecProperty(last_clause_ < kWith,
765 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000766 "clause in an EXPECT_CALL().");
767 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000768 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000769
770 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000771 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000772 return *this;
773 }
774
775 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000776 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000777 if (last_clause_ ==kTimes) {
shiqiane35fdd92008-12-10 05:08:54 +0000778 ExpectSpecProperty(false,
779 ".Times() cannot appear "
780 "more than once in an EXPECT_CALL().");
781 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000782 ExpectSpecProperty(last_clause_ < kTimes,
shiqiane35fdd92008-12-10 05:08:54 +0000783 ".Times() cannot appear after "
784 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
785 "or .RetiresOnSaturation().");
786 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000787 last_clause_ = kTimes;
shiqiane35fdd92008-12-10 05:08:54 +0000788
zhanyong.wan32de5f52009-12-23 00:13:23 +0000789 ExpectationBase::SpecifyCardinality(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000790 return *this;
791 }
792
793 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000794 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000795 return Times(Exactly(n));
796 }
797
798 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000799 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000800 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000801 ".InSequence() cannot appear after .After(),"
802 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000803 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000804 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000805
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000806 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000807 return *this;
808 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000809 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000810 return InSequence(s1).InSequence(s2);
811 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000812 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
813 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000814 return InSequence(s1, s2).InSequence(s3);
815 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000816 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
817 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000818 return InSequence(s1, s2, s3).InSequence(s4);
819 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000820 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
821 const Sequence& s3, const Sequence& s4,
822 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000823 return InSequence(s1, s2, s3, s4).InSequence(s5);
824 }
825
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000826 // Implements that .After() clause.
827 TypedExpectation& After(const ExpectationSet& s) {
828 ExpectSpecProperty(last_clause_ <= kAfter,
829 ".After() cannot appear after .WillOnce(),"
830 " .WillRepeatedly(), or "
831 ".RetiresOnSaturation().");
832 last_clause_ = kAfter;
833
834 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
835 immediate_prerequisites_ += *it;
836 }
837 return *this;
838 }
839 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
840 return After(s1).After(s2);
841 }
842 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
843 const ExpectationSet& s3) {
844 return After(s1, s2).After(s3);
845 }
846 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
847 const ExpectationSet& s3, const ExpectationSet& s4) {
848 return After(s1, s2, s3).After(s4);
849 }
850 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
851 const ExpectationSet& s3, const ExpectationSet& s4,
852 const ExpectationSet& s5) {
853 return After(s1, s2, s3, s4).After(s5);
854 }
855
shiqiane35fdd92008-12-10 05:08:54 +0000856 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000857 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000858 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000859 ".WillOnce() cannot appear after "
860 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000861 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +0000862
863 actions_.push_back(action);
864 if (!cardinality_specified()) {
865 set_cardinality(Exactly(static_cast<int>(actions_.size())));
866 }
867 return *this;
868 }
869
870 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000871 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000872 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +0000873 ExpectSpecProperty(false,
874 ".WillRepeatedly() cannot appear "
875 "more than once in an EXPECT_CALL().");
876 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000877 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +0000878 ".WillRepeatedly() cannot appear "
879 "after .RetiresOnSaturation().");
880 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000881 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +0000882 repeated_action_specified_ = true;
883
884 repeated_action_ = action;
885 if (!cardinality_specified()) {
886 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
887 }
888
889 // Now that no more action clauses can be specified, we check
890 // whether their count makes sense.
891 CheckActionCountIfNotDone();
892 return *this;
893 }
894
895 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000896 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +0000897 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000898 ".RetiresOnSaturation() cannot appear "
899 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +0000900 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +0000901 retires_on_saturation_ = true;
902
903 // Now that no more action clauses can be specified, we check
904 // whether their count makes sense.
905 CheckActionCountIfNotDone();
906 return *this;
907 }
908
909 // Returns the matchers for the arguments as specified inside the
910 // EXPECT_CALL() macro.
911 const ArgumentMatcherTuple& matchers() const {
912 return matchers_;
913 }
914
zhanyong.wanbf550852009-06-09 06:09:53 +0000915 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +0000916 const Matcher<const ArgumentTuple&>& extra_matcher() const {
917 return extra_matcher_;
918 }
919
920 // Returns the sequence of actions specified by the .WillOnce() clause.
921 const std::vector<Action<F> >& actions() const { return actions_; }
922
923 // Returns the action specified by the .WillRepeatedly() clause.
924 const Action<F>& repeated_action() const { return repeated_action_; }
925
926 // Returns true iff the .RetiresOnSaturation() clause was specified.
927 bool retires_on_saturation() const { return retires_on_saturation_; }
928
929 // Describes how many times a function call matching this
930 // expectation has occurred (implements
931 // ExpectationBase::DescribeCallCountTo()).
932 // L >= g_gmock_mutex
933 virtual void DescribeCallCountTo(::std::ostream* os) const {
934 g_gmock_mutex.AssertHeld();
935
936 // Describes how many times the function is expected to be called.
937 *os << " Expected: to be ";
938 cardinality().DescribeTo(os);
939 *os << "\n Actual: ";
940 Cardinality::DescribeActualCallCountTo(call_count(), os);
941
942 // Describes the state of the expectation (e.g. is it satisfied?
943 // is it active?).
944 *os << " - " << (IsOverSaturated() ? "over-saturated" :
945 IsSaturated() ? "saturated" :
946 IsSatisfied() ? "satisfied" : "unsatisfied")
947 << " and "
948 << (is_retired() ? "retired" : "active");
949 }
vladlosev6c54a5e2009-10-21 06:15:34 +0000950
951 void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
952 if (extra_matcher_specified_) {
953 *os << " Expected args: ";
954 extra_matcher_.DescribeTo(os);
955 *os << "\n";
956 }
957 }
958
shiqiane35fdd92008-12-10 05:08:54 +0000959 private:
960 template <typename Function>
961 friend class FunctionMockerBase;
962
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000963 // Returns an Expectation object that references and co-owns this
964 // expectation.
965 virtual Expectation GetHandle() {
966 return owner_->GetHandleOf(this);
967 }
968
shiqiane35fdd92008-12-10 05:08:54 +0000969 // The following methods will be called only after the EXPECT_CALL()
970 // statement finishes and when the current thread holds
971 // g_gmock_mutex.
972
973 // Returns true iff this expectation matches the given arguments.
974 // L >= g_gmock_mutex
975 bool Matches(const ArgumentTuple& args) const {
976 g_gmock_mutex.AssertHeld();
977 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
978 }
979
980 // Returns true iff this expectation should handle the given arguments.
981 // L >= g_gmock_mutex
982 bool ShouldHandleArguments(const ArgumentTuple& args) const {
983 g_gmock_mutex.AssertHeld();
984
985 // In case the action count wasn't checked when the expectation
986 // was defined (e.g. if this expectation has no WillRepeatedly()
987 // or RetiresOnSaturation() clause), we check it when the
988 // expectation is used for the first time.
989 CheckActionCountIfNotDone();
990 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
991 }
992
993 // Describes the result of matching the arguments against this
994 // expectation to the given ostream.
995 // L >= g_gmock_mutex
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000996 void ExplainMatchResultTo(const ArgumentTuple& args,
997 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000998 g_gmock_mutex.AssertHeld();
999
1000 if (is_retired()) {
1001 *os << " Expected: the expectation is active\n"
1002 << " Actual: it is retired\n";
1003 } else if (!Matches(args)) {
1004 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001005 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001006 }
zhanyong.wan82113312010-01-08 21:55:40 +00001007 StringMatchResultListener listener;
1008 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001009 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001010 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001011 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001012
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001013 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001014 *os << "\n";
1015 }
1016 } else if (!AllPrerequisitesAreSatisfied()) {
1017 *os << " Expected: all pre-requisites are satisfied\n"
1018 << " Actual: the following immediate pre-requisites "
1019 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001020 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001021 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1022 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001023 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001024 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001025 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001026 *os << "pre-requisite #" << i++ << "\n";
1027 }
1028 *os << " (end of pre-requisites)\n";
1029 } else {
1030 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001031 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001032 // is called only when the mock function call does NOT match the
1033 // expectation.
1034 *os << "The call matches the expectation.\n";
1035 }
1036 }
1037
1038 // Returns the action that should be taken for the current invocation.
1039 // L >= g_gmock_mutex
1040 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
1041 const ArgumentTuple& args) const {
1042 g_gmock_mutex.AssertHeld();
1043 const int count = call_count();
1044 Assert(count >= 1, __FILE__, __LINE__,
1045 "call_count() is <= 0 when GetCurrentAction() is "
1046 "called - this should never happen.");
1047
1048 const int action_count = static_cast<int>(actions().size());
1049 if (action_count > 0 && !repeated_action_specified_ &&
1050 count > action_count) {
1051 // If there is at least one WillOnce() and no WillRepeatedly(),
1052 // we warn the user when the WillOnce() clauses ran out.
1053 ::std::stringstream ss;
1054 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001055 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001056 << "Called " << count << " times, but only "
1057 << action_count << " WillOnce()"
1058 << (action_count == 1 ? " is" : "s are") << " specified - ";
1059 mocker->DescribeDefaultActionTo(args, &ss);
1060 Log(WARNING, ss.str(), 1);
1061 }
1062
1063 return count <= action_count ? actions()[count - 1] : repeated_action();
1064 }
1065
1066 // Given the arguments of a mock function call, if the call will
1067 // over-saturate this expectation, returns the default action;
1068 // otherwise, returns the next action in this expectation. Also
1069 // describes *what* happened to 'what', and explains *why* Google
1070 // Mock does it to 'why'. This method is not const as it calls
1071 // IncrementCallCount().
1072 // L >= g_gmock_mutex
1073 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
1074 const ArgumentTuple& args,
1075 ::std::ostream* what,
1076 ::std::ostream* why) {
1077 g_gmock_mutex.AssertHeld();
1078 if (IsSaturated()) {
1079 // We have an excessive call.
1080 IncrementCallCount();
1081 *what << "Mock function called more times than expected - ";
1082 mocker->DescribeDefaultActionTo(args, what);
1083 DescribeCallCountTo(why);
1084
1085 // TODO(wan): allow the user to control whether unexpected calls
1086 // should fail immediately or continue using a flag
1087 // --gmock_unexpected_calls_are_fatal.
1088 return DoDefault();
1089 }
1090
1091 IncrementCallCount();
1092 RetireAllPreRequisites();
1093
1094 if (retires_on_saturation() && IsSaturated()) {
1095 Retire();
1096 }
1097
1098 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001099 *what << "Mock function call matches " << source_text() <<"...\n";
shiqiane35fdd92008-12-10 05:08:54 +00001100 return GetCurrentAction(mocker, args);
1101 }
1102
1103 // Checks the action count (i.e. the number of WillOnce() and
1104 // WillRepeatedly() clauses) against the cardinality if this hasn't
1105 // been done before. Prints a warning if there are too many or too
1106 // few actions.
1107 // L < mutex_
1108 void CheckActionCountIfNotDone() const {
1109 bool should_check = false;
1110 {
1111 MutexLock l(&mutex_);
1112 if (!action_count_checked_) {
1113 action_count_checked_ = true;
1114 should_check = true;
1115 }
1116 }
1117
1118 if (should_check) {
1119 if (!cardinality_specified_) {
1120 // The cardinality was inferred - no need to check the action
1121 // count against it.
1122 return;
1123 }
1124
1125 // The cardinality was explicitly specified.
1126 const int action_count = static_cast<int>(actions_.size());
1127 const int upper_bound = cardinality().ConservativeUpperBound();
1128 const int lower_bound = cardinality().ConservativeLowerBound();
1129 bool too_many; // True if there are too many actions, or false
1130 // if there are too few.
1131 if (action_count > upper_bound ||
1132 (action_count == upper_bound && repeated_action_specified_)) {
1133 too_many = true;
1134 } else if (0 < action_count && action_count < lower_bound &&
1135 !repeated_action_specified_) {
1136 too_many = false;
1137 } else {
1138 return;
1139 }
1140
1141 ::std::stringstream ss;
1142 DescribeLocationTo(&ss);
1143 ss << "Too " << (too_many ? "many" : "few")
vladlosev6c54a5e2009-10-21 06:15:34 +00001144 << " actions specified in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001145 << "Expected to be ";
1146 cardinality().DescribeTo(&ss);
1147 ss << ", but has " << (too_many ? "" : "only ")
1148 << action_count << " WillOnce()"
1149 << (action_count == 1 ? "" : "s");
1150 if (repeated_action_specified_) {
1151 ss << " and a WillRepeatedly()";
1152 }
1153 ss << ".";
1154 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
1155 }
1156 }
1157
1158 // All the fields below won't change once the EXPECT_CALL()
1159 // statement finishes.
1160 FunctionMockerBase<F>* const owner_;
1161 ArgumentMatcherTuple matchers_;
vladlosev6c54a5e2009-10-21 06:15:34 +00001162 bool extra_matcher_specified_;
shiqiane35fdd92008-12-10 05:08:54 +00001163 Matcher<const ArgumentTuple&> extra_matcher_;
1164 std::vector<Action<F> > actions_;
1165 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
1166 Action<F> repeated_action_;
1167 bool retires_on_saturation_;
1168 Clause last_clause_;
1169 mutable bool action_count_checked_; // Under mutex_.
1170 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +00001171
1172 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001173}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001174
1175// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1176// specifying the default behavior of, or expectation on, a mock
1177// function.
1178
1179// Note: class MockSpec really belongs to the ::testing namespace.
1180// However if we define it in ::testing, MSVC will complain when
1181// classes in ::testing::internal declare it as a friend class
1182// template. To workaround this compiler bug, we define MockSpec in
1183// ::testing::internal and import it into ::testing.
1184
1185template <typename F>
1186class MockSpec {
1187 public:
1188 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1189 typedef typename internal::Function<F>::ArgumentMatcherTuple
1190 ArgumentMatcherTuple;
1191
1192 // Constructs a MockSpec object, given the function mocker object
1193 // that the spec is associated with.
1194 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1195 : function_mocker_(function_mocker) {}
1196
1197 // Adds a new default action spec to the function mocker and returns
1198 // the newly created spec.
1199 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
1200 const char* file, int line, const char* obj, const char* call) {
1201 LogWithLocation(internal::INFO, file, line,
1202 string("ON_CALL(") + obj + ", " + call + ") invoked");
1203 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
1204 }
1205
1206 // Adds a new expectation spec to the function mocker and returns
1207 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001208 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001209 const char* file, int line, const char* obj, const char* call) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001210 const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
1211 LogWithLocation(internal::INFO, file, line, source_text + " invoked");
1212 return function_mocker_->AddNewExpectation(
1213 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001214 }
1215
1216 private:
1217 template <typename Function>
1218 friend class internal::FunctionMocker;
1219
1220 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1221 matchers_ = matchers;
1222 }
1223
1224 // Logs a message including file and line number information.
1225 void LogWithLocation(testing::internal::LogSeverity severity,
1226 const char* file, int line,
1227 const string& message) {
1228 ::std::ostringstream s;
1229 s << file << ":" << line << ": " << message << ::std::endl;
1230 Log(severity, s.str(), 0);
1231 }
1232
1233 // The function mocker that owns this spec.
1234 internal::FunctionMockerBase<F>* const function_mocker_;
1235 // The argument matchers specified in the spec.
1236 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001237
1238 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001239}; // class MockSpec
1240
1241// MSVC warns about using 'this' in base member initializer list, so
1242// we need to temporarily disable the warning. We have to do it for
1243// the entire class to suppress the warning, even though it's about
1244// the constructor only.
1245
1246#ifdef _MSC_VER
1247#pragma warning(push) // Saves the current warning state.
1248#pragma warning(disable:4355) // Temporarily disables warning 4355.
1249#endif // _MSV_VER
1250
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001251// C++ treats the void type specially. For example, you cannot define
1252// a void-typed variable or pass a void value to a function.
1253// ActionResultHolder<T> holds a value of type T, where T must be a
1254// copyable type or void (T doesn't need to be default-constructable).
1255// It hides the syntactic difference between void and other types, and
1256// is used to unify the code for invoking both void-returning and
1257// non-void-returning mock functions. This generic definition is used
1258// when T is not void.
1259template <typename T>
1260class ActionResultHolder {
1261 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00001262 explicit ActionResultHolder(T a_value) : value_(a_value) {}
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001263
1264 // The compiler-generated copy constructor and assignment operator
1265 // are exactly what we need, so we don't need to define them.
1266
1267 T value() const { return value_; }
1268
1269 // Prints the held value as an action's result to os.
1270 void PrintAsActionResult(::std::ostream* os) const {
1271 *os << "\n Returns: ";
1272 UniversalPrinter<T>::Print(value_, os);
1273 }
1274
1275 // Performs the given mock function's default action and returns the
1276 // result in a ActionResultHolder.
1277 template <typename Function, typename Arguments>
1278 static ActionResultHolder PerformDefaultAction(
1279 const FunctionMockerBase<Function>* func_mocker,
1280 const Arguments& args,
1281 const string& call_description) {
1282 return ActionResultHolder(
1283 func_mocker->PerformDefaultAction(args, call_description));
1284 }
1285
1286 // Performs the given action and returns the result in a
1287 // ActionResultHolder.
1288 template <typename Function, typename Arguments>
1289 static ActionResultHolder PerformAction(const Action<Function>& action,
1290 const Arguments& args) {
1291 return ActionResultHolder(action.Perform(args));
1292 }
1293
1294 private:
1295 T value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001296
1297 // T could be a reference type, so = isn't supported.
1298 GTEST_DISALLOW_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001299};
1300
1301// Specialization for T = void.
1302template <>
1303class ActionResultHolder<void> {
1304 public:
1305 ActionResultHolder() {}
1306 void value() const {}
1307 void PrintAsActionResult(::std::ostream* /* os */) const {}
1308
1309 template <typename Function, typename Arguments>
1310 static ActionResultHolder PerformDefaultAction(
1311 const FunctionMockerBase<Function>* func_mocker,
1312 const Arguments& args,
1313 const string& call_description) {
1314 func_mocker->PerformDefaultAction(args, call_description);
1315 return ActionResultHolder();
1316 }
1317
1318 template <typename Function, typename Arguments>
1319 static ActionResultHolder PerformAction(const Action<Function>& action,
1320 const Arguments& args) {
1321 action.Perform(args);
1322 return ActionResultHolder();
1323 }
1324};
1325
shiqiane35fdd92008-12-10 05:08:54 +00001326// The base of the function mocker class for the given function type.
1327// We put the methods in this class instead of its child to avoid code
1328// bloat.
1329template <typename F>
1330class FunctionMockerBase : public UntypedFunctionMockerBase {
1331 public:
1332 typedef typename Function<F>::Result Result;
1333 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1334 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1335
1336 FunctionMockerBase() : mock_obj_(NULL), name_(""), current_spec_(this) {}
1337
1338 // The destructor verifies that all expectations on this mock
1339 // function have been satisfied. If not, it will report Google Test
1340 // non-fatal failures for the violations.
1341 // L < g_gmock_mutex
1342 virtual ~FunctionMockerBase() {
1343 MutexLock l(&g_gmock_mutex);
1344 VerifyAndClearExpectationsLocked();
1345 Mock::UnregisterLocked(this);
1346 }
1347
1348 // Returns the ON_CALL spec that matches this mock function with the
1349 // given arguments; returns NULL if no matching ON_CALL is found.
1350 // L = *
1351 const DefaultActionSpec<F>* FindDefaultActionSpec(
1352 const ArgumentTuple& args) const {
1353 for (typename std::vector<DefaultActionSpec<F> >::const_reverse_iterator it
1354 = default_actions_.rbegin();
1355 it != default_actions_.rend(); ++it) {
1356 const DefaultActionSpec<F>& spec = *it;
1357 if (spec.Matches(args))
1358 return &spec;
1359 }
1360
1361 return NULL;
1362 }
1363
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001364 // Performs the default action of this mock function on the given arguments
1365 // and returns the result. Asserts with a helpful call descrption if there is
1366 // no valid return value. This method doesn't depend on the mutable state of
1367 // this object, and thus can be called concurrently without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001368 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001369 Result PerformDefaultAction(const ArgumentTuple& args,
1370 const string& call_description) const {
shiqiane35fdd92008-12-10 05:08:54 +00001371 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001372 if (spec != NULL) {
1373 return spec->GetAction().Perform(args);
1374 }
1375 Assert(DefaultValue<Result>::Exists(), "", -1,
1376 call_description + "\n The mock function has no default action "
1377 "set, and its return type has no default value set.");
1378 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001379 }
1380
1381 // Registers this function mocker and the mock object owning it;
1382 // returns a reference to the function mocker object. This is only
1383 // called by the ON_CALL() and EXPECT_CALL() macros.
zhanyong.wandf35a762009-04-22 22:25:31 +00001384 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001385 FunctionMocker<F>& RegisterOwner(const void* mock_obj) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001386 {
1387 MutexLock l(&g_gmock_mutex);
1388 mock_obj_ = mock_obj;
1389 }
shiqiane35fdd92008-12-10 05:08:54 +00001390 Mock::Register(mock_obj, this);
zhanyong.wan946bc642009-03-31 00:05:30 +00001391 return *::testing::internal::down_cast<FunctionMocker<F>*>(this);
shiqiane35fdd92008-12-10 05:08:54 +00001392 }
1393
1394 // The following two functions are from UntypedFunctionMockerBase.
1395
1396 // Verifies that all expectations on this mock function have been
1397 // satisfied. Reports one or more Google Test non-fatal failures
1398 // and returns false if not.
1399 // L >= g_gmock_mutex
1400 virtual bool VerifyAndClearExpectationsLocked();
1401
1402 // Clears the ON_CALL()s set on this mock function.
1403 // L >= g_gmock_mutex
1404 virtual void ClearDefaultActionsLocked() {
1405 g_gmock_mutex.AssertHeld();
1406 default_actions_.clear();
1407 }
1408
1409 // Sets the name of the function being mocked. Will be called upon
1410 // each invocation of this mock function.
1411 // L < g_gmock_mutex
1412 void SetOwnerAndName(const void* mock_obj, const char* name) {
1413 // We protect name_ under g_gmock_mutex in case this mock function
1414 // is called from two threads concurrently.
1415 MutexLock l(&g_gmock_mutex);
1416 mock_obj_ = mock_obj;
1417 name_ = name;
1418 }
1419
1420 // Returns the address of the mock object this method belongs to.
1421 // Must be called after SetOwnerAndName() has been called.
1422 // L < g_gmock_mutex
1423 const void* MockObject() const {
1424 const void* mock_obj;
1425 {
1426 // We protect mock_obj_ under g_gmock_mutex in case this mock
1427 // function is called from two threads concurrently.
1428 MutexLock l(&g_gmock_mutex);
1429 mock_obj = mock_obj_;
1430 }
1431 return mock_obj;
1432 }
1433
1434 // Returns the name of the function being mocked. Must be called
1435 // after SetOwnerAndName() has been called.
1436 // L < g_gmock_mutex
1437 const char* Name() const {
1438 const char* name;
1439 {
1440 // We protect name_ under g_gmock_mutex in case this mock
1441 // function is called from two threads concurrently.
1442 MutexLock l(&g_gmock_mutex);
1443 name = name_;
1444 }
1445 return name;
1446 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001447
shiqiane35fdd92008-12-10 05:08:54 +00001448 protected:
1449 template <typename Function>
1450 friend class MockSpec;
1451
shiqiane35fdd92008-12-10 05:08:54 +00001452 // Returns the result of invoking this mock function with the given
1453 // arguments. This function can be safely called from multiple
1454 // threads concurrently.
1455 // L < g_gmock_mutex
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001456 Result InvokeWith(const ArgumentTuple& args);
shiqiane35fdd92008-12-10 05:08:54 +00001457
1458 // Adds and returns a default action spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001459 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001460 DefaultActionSpec<F>& AddNewDefaultActionSpec(
1461 const char* file, int line,
1462 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001463 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
shiqiane35fdd92008-12-10 05:08:54 +00001464 default_actions_.push_back(DefaultActionSpec<F>(file, line, m));
1465 return default_actions_.back();
1466 }
1467
1468 // Adds and returns an expectation spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001469 // L < g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001470 TypedExpectation<F>& AddNewExpectation(
vladlosev6c54a5e2009-10-21 06:15:34 +00001471 const char* file,
1472 int line,
1473 const string& source_text,
shiqiane35fdd92008-12-10 05:08:54 +00001474 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001475 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001476 const linked_ptr<TypedExpectation<F> > expectation(
vladlosev6c54a5e2009-10-21 06:15:34 +00001477 new TypedExpectation<F>(this, file, line, source_text, m));
shiqiane35fdd92008-12-10 05:08:54 +00001478 expectations_.push_back(expectation);
1479
1480 // Adds this expectation into the implicit sequence if there is one.
1481 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1482 if (implicit_sequence != NULL) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001483 implicit_sequence->AddExpectation(Expectation(expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001484 }
1485
1486 return *expectation;
1487 }
1488
1489 // The current spec (either default action spec or expectation spec)
1490 // being described on this function mocker.
1491 MockSpec<F>& current_spec() { return current_spec_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001492
shiqiane35fdd92008-12-10 05:08:54 +00001493 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001494 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001495
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001496 typedef std::vector<internal::linked_ptr<TypedExpectation<F> > >
1497 TypedExpectations;
shiqiane35fdd92008-12-10 05:08:54 +00001498
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001499 // Returns an Expectation object that references and co-owns exp,
1500 // which must be an expectation on this mock function.
1501 Expectation GetHandleOf(TypedExpectation<F>* exp) {
1502 for (typename TypedExpectations::const_iterator it = expectations_.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001503 it != expectations_.end(); ++it) {
1504 if (it->get() == exp) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001505 return Expectation(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001506 }
1507 }
1508
1509 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001510 return Expectation();
shiqiane35fdd92008-12-10 05:08:54 +00001511 // The above statement is just to make the code compile, and will
1512 // never be executed.
1513 }
1514
1515 // Some utilities needed for implementing InvokeWith().
1516
1517 // Describes what default action will be performed for the given
1518 // arguments.
1519 // L = *
1520 void DescribeDefaultActionTo(const ArgumentTuple& args,
1521 ::std::ostream* os) const {
1522 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1523
1524 if (spec == NULL) {
1525 *os << (internal::type_equals<Result, void>::value ?
1526 "returning directly.\n" :
1527 "returning default value.\n");
1528 } else {
1529 *os << "taking default action specified at:\n"
1530 << spec->file() << ":" << spec->line() << ":\n";
1531 }
1532 }
1533
1534 // Writes a message that the call is uninteresting (i.e. neither
1535 // explicitly expected nor explicitly unexpected) to the given
1536 // ostream.
1537 // L < g_gmock_mutex
1538 void DescribeUninterestingCall(const ArgumentTuple& args,
1539 ::std::ostream* os) const {
1540 *os << "Uninteresting mock function call - ";
1541 DescribeDefaultActionTo(args, os);
1542 *os << " Function call: " << Name();
1543 UniversalPrinter<ArgumentTuple>::Print(args, os);
1544 }
1545
1546 // Critical section: We must find the matching expectation and the
1547 // corresponding action that needs to be taken in an ATOMIC
1548 // transaction. Otherwise another thread may call this mock
1549 // method in the middle and mess up the state.
1550 //
1551 // However, performing the action has to be left out of the critical
1552 // section. The reason is that we have no control on what the
1553 // action does (it can invoke an arbitrary user function or even a
1554 // mock function) and excessive locking could cause a dead lock.
1555 // L < g_gmock_mutex
1556 bool FindMatchingExpectationAndAction(
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001557 const ArgumentTuple& args, TypedExpectation<F>** exp, Action<F>* action,
shiqiane35fdd92008-12-10 05:08:54 +00001558 bool* is_excessive, ::std::ostream* what, ::std::ostream* why) {
1559 MutexLock l(&g_gmock_mutex);
1560 *exp = this->FindMatchingExpectationLocked(args);
1561 if (*exp == NULL) { // A match wasn't found.
1562 *action = DoDefault();
1563 this->FormatUnexpectedCallMessageLocked(args, what, why);
1564 return false;
1565 }
1566
1567 // This line must be done before calling GetActionForArguments(),
1568 // which will increment the call count for *exp and thus affect
1569 // its saturation status.
1570 *is_excessive = (*exp)->IsSaturated();
1571 *action = (*exp)->GetActionForArguments(this, args, what, why);
1572 return true;
1573 }
1574
1575 // Returns the expectation that matches the arguments, or NULL if no
1576 // expectation matches them.
1577 // L >= g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001578 TypedExpectation<F>* FindMatchingExpectationLocked(
shiqiane35fdd92008-12-10 05:08:54 +00001579 const ArgumentTuple& args) const {
1580 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001581 for (typename TypedExpectations::const_reverse_iterator it =
shiqiane35fdd92008-12-10 05:08:54 +00001582 expectations_.rbegin();
1583 it != expectations_.rend(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001584 TypedExpectation<F>* const exp = it->get();
shiqiane35fdd92008-12-10 05:08:54 +00001585 if (exp->ShouldHandleArguments(args)) {
1586 return exp;
1587 }
1588 }
1589 return NULL;
1590 }
1591
1592 // Returns a message that the arguments don't match any expectation.
1593 // L >= g_gmock_mutex
1594 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1595 ::std::ostream* os,
1596 ::std::ostream* why) const {
1597 g_gmock_mutex.AssertHeld();
1598 *os << "\nUnexpected mock function call - ";
1599 DescribeDefaultActionTo(args, os);
1600 PrintTriedExpectationsLocked(args, why);
1601 }
1602
1603 // Prints a list of expectations that have been tried against the
1604 // current mock function call.
1605 // L >= g_gmock_mutex
1606 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1607 ::std::ostream* why) const {
1608 g_gmock_mutex.AssertHeld();
1609 const int count = static_cast<int>(expectations_.size());
1610 *why << "Google Mock tried the following " << count << " "
1611 << (count == 1 ? "expectation, but it didn't match" :
1612 "expectations, but none matched")
1613 << ":\n";
1614 for (int i = 0; i < count; i++) {
1615 *why << "\n";
1616 expectations_[i]->DescribeLocationTo(why);
1617 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001618 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001619 }
vladlosev6c54a5e2009-10-21 06:15:34 +00001620 *why << expectations_[i]->source_text() << "...\n";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001621 expectations_[i]->ExplainMatchResultTo(args, why);
shiqiane35fdd92008-12-10 05:08:54 +00001622 expectations_[i]->DescribeCallCountTo(why);
1623 }
1624 }
1625
zhanyong.wandf35a762009-04-22 22:25:31 +00001626 // Address of the mock object this mock method belongs to. Only
1627 // valid after this mock method has been called or
1628 // ON_CALL/EXPECT_CALL has been invoked on it.
shiqiane35fdd92008-12-10 05:08:54 +00001629 const void* mock_obj_; // Protected by g_gmock_mutex.
1630
zhanyong.wandf35a762009-04-22 22:25:31 +00001631 // Name of the function being mocked. Only valid after this mock
1632 // method has been called.
shiqiane35fdd92008-12-10 05:08:54 +00001633 const char* name_; // Protected by g_gmock_mutex.
1634
1635 // The current spec (either default action spec or expectation spec)
1636 // being described on this function mocker.
1637 MockSpec<F> current_spec_;
1638
1639 // All default action specs for this function mocker.
1640 std::vector<DefaultActionSpec<F> > default_actions_;
1641 // All expectations for this function mocker.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001642 TypedExpectations expectations_;
zhanyong.wan16cf4732009-05-14 20:55:30 +00001643
1644 // There is no generally useful and implementable semantics of
1645 // copying a mock object, so copying a mock is usually a user error.
1646 // Thus we disallow copying function mockers. If the user really
1647 // wants to copy a mock object, he should implement his own copy
1648 // operation, for example:
1649 //
1650 // class MockFoo : public Foo {
1651 // public:
1652 // // Defines a copy constructor explicitly.
1653 // MockFoo(const MockFoo& src) {}
1654 // ...
1655 // };
1656 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001657}; // class FunctionMockerBase
1658
1659#ifdef _MSC_VER
1660#pragma warning(pop) // Restores the warning state.
1661#endif // _MSV_VER
1662
1663// Implements methods of FunctionMockerBase.
1664
1665// Verifies that all expectations on this mock function have been
1666// satisfied. Reports one or more Google Test non-fatal failures and
1667// returns false if not.
1668// L >= g_gmock_mutex
1669template <typename F>
1670bool FunctionMockerBase<F>::VerifyAndClearExpectationsLocked() {
1671 g_gmock_mutex.AssertHeld();
1672 bool expectations_met = true;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001673 for (typename TypedExpectations::const_iterator it = expectations_.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001674 it != expectations_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001675 TypedExpectation<F>* const exp = it->get();
shiqiane35fdd92008-12-10 05:08:54 +00001676
1677 if (exp->IsOverSaturated()) {
1678 // There was an upper-bound violation. Since the error was
1679 // already reported when it occurred, there is no need to do
1680 // anything here.
1681 expectations_met = false;
1682 } else if (!exp->IsSatisfied()) {
1683 expectations_met = false;
1684 ::std::stringstream ss;
vladlosev6c54a5e2009-10-21 06:15:34 +00001685 ss << "Actual function call count doesn't match "
1686 << exp->source_text() << "...\n";
shiqiane35fdd92008-12-10 05:08:54 +00001687 // No need to show the source file location of the expectation
1688 // in the description, as the Expect() call that follows already
1689 // takes care of it.
vladlosev6c54a5e2009-10-21 06:15:34 +00001690 exp->MaybeDescribeExtraMatcherTo(&ss);
shiqiane35fdd92008-12-10 05:08:54 +00001691 exp->DescribeCallCountTo(&ss);
1692 Expect(false, exp->file(), exp->line(), ss.str());
1693 }
1694 }
1695 expectations_.clear();
1696 return expectations_met;
1697}
1698
1699// Reports an uninteresting call (whose description is in msg) in the
1700// manner specified by 'reaction'.
1701void ReportUninterestingCall(CallReaction reaction, const string& msg);
1702
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001703// Calculates the result of invoking this mock function with the given
1704// arguments, prints it, and returns it.
1705// L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001706template <typename F>
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001707typename Function<F>::Result FunctionMockerBase<F>::InvokeWith(
1708 const typename Function<F>::ArgumentTuple& args) {
1709 typedef ActionResultHolder<Result> ResultHolder;
shiqiane35fdd92008-12-10 05:08:54 +00001710
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001711 if (expectations_.size() == 0) {
1712 // No expectation is set on this mock method - we have an
1713 // uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001714
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001715 // We must get Google Mock's reaction on uninteresting calls
1716 // made on this mock object BEFORE performing the action,
1717 // because the action may DELETE the mock object and make the
1718 // following expression meaningless.
1719 const CallReaction reaction =
1720 Mock::GetReactionOnUninterestingCalls(MockObject());
shiqiane35fdd92008-12-10 05:08:54 +00001721
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001722 // True iff we need to print this call's arguments and return
1723 // value. This definition must be kept in sync with
1724 // the behavior of ReportUninterestingCall().
1725 const bool need_to_report_uninteresting_call =
1726 // If the user allows this uninteresting call, we print it
1727 // only when he wants informational messages.
1728 reaction == ALLOW ? LogIsVisible(INFO) :
1729 // If the user wants this to be a warning, we print it only
1730 // when he wants to see warnings.
1731 reaction == WARN ? LogIsVisible(WARNING) :
1732 // Otherwise, the user wants this to be an error, and we
1733 // should always print detailed information in the error.
1734 true;
1735
1736 if (!need_to_report_uninteresting_call) {
1737 // Perform the action without printing the call information.
1738 return PerformDefaultAction(args, "");
shiqiane35fdd92008-12-10 05:08:54 +00001739 }
1740
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001741 // Warns about the uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001742 ::std::stringstream ss;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001743 DescribeUninterestingCall(args, &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001744
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001745 // Calculates the function result.
1746 const ResultHolder result =
1747 ResultHolder::PerformDefaultAction(this, args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001748
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001749 // Prints the function result.
1750 result.PrintAsActionResult(&ss);
1751
1752 ReportUninterestingCall(reaction, ss.str());
1753 return result.value();
shiqiane35fdd92008-12-10 05:08:54 +00001754 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001755
1756 bool is_excessive = false;
1757 ::std::stringstream ss;
1758 ::std::stringstream why;
1759 ::std::stringstream loc;
1760 Action<F> action;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001761 TypedExpectation<F>* exp;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001762
1763 // The FindMatchingExpectationAndAction() function acquires and
1764 // releases g_gmock_mutex.
1765 const bool found = FindMatchingExpectationAndAction(
1766 args, &exp, &action, &is_excessive, &ss, &why);
1767
1768 // True iff we need to print the call's arguments and return value.
1769 // This definition must be kept in sync with the uses of Expect()
1770 // and Log() in this function.
1771 const bool need_to_report_call = !found || is_excessive || LogIsVisible(INFO);
1772 if (!need_to_report_call) {
1773 // Perform the action without printing the call information.
1774 return action.IsDoDefault() ? PerformDefaultAction(args, "") :
1775 action.Perform(args);
1776 }
1777
1778 ss << " Function call: " << Name();
1779 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1780
1781 // In case the action deletes a piece of the expectation, we
1782 // generate the message beforehand.
1783 if (found && !is_excessive) {
1784 exp->DescribeLocationTo(&loc);
1785 }
1786
1787 const ResultHolder result = action.IsDoDefault() ?
1788 ResultHolder::PerformDefaultAction(this, args, ss.str()) :
1789 ResultHolder::PerformAction(action, args);
1790 result.PrintAsActionResult(&ss);
1791 ss << "\n" << why.str();
1792
1793 if (!found) {
1794 // No expectation matches this call - reports a failure.
1795 Expect(false, NULL, -1, ss.str());
1796 } else if (is_excessive) {
1797 // We had an upper-bound violation and the failure message is in ss.
1798 Expect(false, exp->file(), exp->line(), ss.str());
1799 } else {
1800 // We had an expected call and the matching expectation is
1801 // described in ss.
1802 Log(INFO, loc.str() + ss.str(), 2);
1803 }
1804 return result.value();
1805}
shiqiane35fdd92008-12-10 05:08:54 +00001806
1807} // namespace internal
1808
1809// The style guide prohibits "using" statements in a namespace scope
1810// inside a header file. However, the MockSpec class template is
1811// meant to be defined in the ::testing namespace. The following line
1812// is just a trick for working around a bug in MSVC 8.0, which cannot
1813// handle it if we define MockSpec in ::testing.
1814using internal::MockSpec;
1815
1816// Const(x) is a convenient function for obtaining a const reference
1817// to x. This is useful for setting expectations on an overloaded
1818// const mock method, e.g.
1819//
1820// class MockFoo : public FooInterface {
1821// public:
1822// MOCK_METHOD0(Bar, int());
1823// MOCK_CONST_METHOD0(Bar, int&());
1824// };
1825//
1826// MockFoo foo;
1827// // Expects a call to non-const MockFoo::Bar().
1828// EXPECT_CALL(foo, Bar());
1829// // Expects a call to const MockFoo::Bar().
1830// EXPECT_CALL(Const(foo), Bar());
1831template <typename T>
1832inline const T& Const(const T& x) { return x; }
1833
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001834// Constructs an Expectation object that references and co-owns exp.
1835inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1836 : expectation_base_(exp.GetHandle().expectation_base()) {}
1837
shiqiane35fdd92008-12-10 05:08:54 +00001838} // namespace testing
1839
1840// A separate macro is required to avoid compile errors when the name
1841// of the method used in call is a result of macro expansion.
1842// See CompilesWithMethodNameExpandedFromMacro tests in
1843// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001844#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001845 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1846 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001847#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001848
zhanyong.wane0d051e2009-02-19 00:33:37 +00001849#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001850 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001851#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001852
1853#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_