blob: 1676056ce8a0960b9beffca5e42788266d716888 [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
zhanyong.wan53e08c42010-09-14 05:38:21 +000069#include "gmock/gmock-actions.h"
70#include "gmock/gmock-cardinalities.h"
71#include "gmock/gmock-matchers.h"
72#include "gmock/internal/gmock-internal-utils.h"
73#include "gmock/internal/gmock-port.h"
74#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000075
76namespace testing {
77
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000078// An abstract handle of an expectation.
79class Expectation;
80
81// A set of expectation handles.
82class ExpectationSet;
83
shiqiane35fdd92008-12-10 05:08:54 +000084// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
85// and MUST NOT BE USED IN USER CODE!!!
86namespace internal {
87
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000088// Implements a mock function.
89template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000090
91// Base class for expectations.
92class ExpectationBase;
93
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000094// Implements an expectation.
95template <typename F> class TypedExpectation;
96
shiqiane35fdd92008-12-10 05:08:54 +000097// Helper class for testing the Expectation class template.
98class ExpectationTester;
99
100// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000101template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000102
shiqiane35fdd92008-12-10 05:08:54 +0000103// Protects the mock object registry (in class Mock), all function
104// mockers, and all expectations.
105//
106// The reason we don't use more fine-grained protection is: when a
107// mock function Foo() is called, it needs to consult its expectations
108// to see which one should be picked. If another thread is allowed to
109// call a mock function (either Foo() or a different one) at the same
110// time, it could affect the "retired" attributes of Foo()'s
111// expectations when InSequence() is used, and thus affect which
112// expectation gets picked. Therefore, we sequence all mock function
113// calls to ensure the integrity of the mock objects' states.
zhanyong.wan5905ba02010-02-24 17:21:37 +0000114GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000115
116// Abstract base class of FunctionMockerBase. This is the
117// type-agnostic part of the function mocker interface. Its pure
118// virtual methods are implemented by FunctionMockerBase.
119class UntypedFunctionMockerBase {
120 public:
121 virtual ~UntypedFunctionMockerBase() {}
122
123 // Verifies that all expectations on this mock function have been
124 // satisfied. Reports one or more Google Test non-fatal failures
125 // and returns false if not.
126 // L >= g_gmock_mutex
127 virtual bool VerifyAndClearExpectationsLocked() = 0;
128
129 // Clears the ON_CALL()s set on this mock function.
130 // L >= g_gmock_mutex
131 virtual void ClearDefaultActionsLocked() = 0;
132}; // class UntypedFunctionMockerBase
133
134// This template class implements a default action spec (i.e. an
135// ON_CALL() statement).
136template <typename F>
137class DefaultActionSpec {
138 public:
139 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
140 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
141
142 // Constructs a DefaultActionSpec object from the information inside
143 // the parenthesis of an ON_CALL() statement.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000144 DefaultActionSpec(const char* a_file, int a_line,
shiqiane35fdd92008-12-10 05:08:54 +0000145 const ArgumentMatcherTuple& matchers)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000146 : file_(a_file),
147 line_(a_line),
shiqiane35fdd92008-12-10 05:08:54 +0000148 matchers_(matchers),
zhanyong.wan18490652009-05-11 18:54:08 +0000149 // By default, extra_matcher_ should match anything. However,
150 // we cannot initialize it with _ as that triggers a compiler
151 // bug in Symbian's C++ compiler (cannot decide between two
152 // overloaded constructors of Matcher<const ArgumentTuple&>).
153 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.wanbf550852009-06-09 06:09:53 +0000154 last_clause_(kNone) {
shiqiane35fdd92008-12-10 05:08:54 +0000155 }
156
157 // Where in the source file was the default action spec defined?
158 const char* file() const { return file_; }
159 int line() const { return line_; }
160
zhanyong.wanbf550852009-06-09 06:09:53 +0000161 // Implements the .With() clause.
162 DefaultActionSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000163 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000164 ExpectSpecProperty(last_clause_ < kWith,
165 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000166 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000167 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000168
169 extra_matcher_ = m;
170 return *this;
171 }
172
173 // Implements the .WillByDefault() clause.
174 DefaultActionSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000175 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000176 ".WillByDefault() must appear "
177 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000178 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000179
180 ExpectSpecProperty(!action.IsDoDefault(),
181 "DoDefault() cannot be used in ON_CALL().");
182 action_ = action;
183 return *this;
184 }
185
186 // Returns true iff the given arguments match the matchers.
187 bool Matches(const ArgumentTuple& args) const {
188 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
189 }
190
191 // Returns the action specified by the user.
192 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000193 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000194 ".WillByDefault() must appear exactly "
195 "once in an ON_CALL().");
196 return action_;
197 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000198
shiqiane35fdd92008-12-10 05:08:54 +0000199 private:
200 // Gives each clause in the ON_CALL() statement a name.
201 enum Clause {
202 // Do not change the order of the enum members! The run-time
203 // syntax checking relies on it.
zhanyong.wanbf550852009-06-09 06:09:53 +0000204 kNone,
205 kWith,
206 kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000207 };
208
209 // Asserts that the ON_CALL() statement has a certain property.
210 void AssertSpecProperty(bool property, const string& failure_message) const {
211 Assert(property, file_, line_, failure_message);
212 }
213
214 // Expects that the ON_CALL() statement has a certain property.
215 void ExpectSpecProperty(bool property, const string& failure_message) const {
216 Expect(property, file_, line_, failure_message);
217 }
218
219 // The information in statement
220 //
221 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000222 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000223 // .WillByDefault(action);
224 //
225 // is recorded in the data members like this:
226 //
227 // source file that contains the statement => file_
228 // line number of the statement => line_
229 // matchers => matchers_
230 // multi-argument-matcher => extra_matcher_
231 // action => action_
232 const char* file_;
233 int line_;
234 ArgumentMatcherTuple matchers_;
235 Matcher<const ArgumentTuple&> extra_matcher_;
236 Action<F> action_;
237
238 // The last clause in the ON_CALL() statement as seen so far.
zhanyong.wanbf550852009-06-09 06:09:53 +0000239 // Initially kNone and changes as the statement is parsed.
shiqiane35fdd92008-12-10 05:08:54 +0000240 Clause last_clause_;
241}; // class DefaultActionSpec
242
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000243// Possible reactions on uninteresting calls. TODO(wan@google.com):
244// rename the enum values to the kFoo style.
shiqiane35fdd92008-12-10 05:08:54 +0000245enum CallReaction {
246 ALLOW,
247 WARN,
248 FAIL,
249};
250
251} // namespace internal
252
253// Utilities for manipulating mock objects.
254class Mock {
255 public:
256 // The following public methods can be called concurrently.
257
zhanyong.wandf35a762009-04-22 22:25:31 +0000258 // Tells Google Mock to ignore mock_obj when checking for leaked
259 // mock objects.
260 static void AllowLeak(const void* mock_obj);
261
shiqiane35fdd92008-12-10 05:08:54 +0000262 // Verifies and clears all expectations on the given mock object.
263 // If the expectations aren't satisfied, generates one or more
264 // Google Test non-fatal failures and returns false.
265 static bool VerifyAndClearExpectations(void* mock_obj);
266
267 // Verifies all expectations on the given mock object and clears its
268 // default actions and expectations. Returns true iff the
269 // verification was successful.
270 static bool VerifyAndClear(void* mock_obj);
271 private:
272 // Needed for a function mocker to register itself (so that we know
273 // how to clear a mock object).
274 template <typename F>
275 friend class internal::FunctionMockerBase;
276
shiqiane35fdd92008-12-10 05:08:54 +0000277 template <typename M>
278 friend class NiceMock;
279
280 template <typename M>
281 friend class StrictMock;
282
283 // Tells Google Mock to allow uninteresting calls on the given mock
284 // object.
285 // L < g_gmock_mutex
286 static void AllowUninterestingCalls(const void* mock_obj);
287
288 // Tells Google Mock to warn the user about uninteresting calls on
289 // the given mock object.
290 // L < g_gmock_mutex
291 static void WarnUninterestingCalls(const void* mock_obj);
292
293 // Tells Google Mock to fail uninteresting calls on the given mock
294 // object.
295 // L < g_gmock_mutex
296 static void FailUninterestingCalls(const void* mock_obj);
297
298 // Tells Google Mock the given mock object is being destroyed and
299 // its entry in the call-reaction table should be removed.
300 // L < g_gmock_mutex
301 static void UnregisterCallReaction(const void* mock_obj);
302
303 // Returns the reaction Google Mock will have on uninteresting calls
304 // made on the given mock object.
305 // L < g_gmock_mutex
306 static internal::CallReaction GetReactionOnUninterestingCalls(
307 const void* mock_obj);
308
309 // Verifies that all expectations on the given mock object have been
310 // satisfied. Reports one or more Google Test non-fatal failures
311 // and returns false if not.
312 // L >= g_gmock_mutex
313 static bool VerifyAndClearExpectationsLocked(void* mock_obj);
314
315 // Clears all ON_CALL()s set on the given mock object.
316 // L >= g_gmock_mutex
317 static void ClearDefaultActionsLocked(void* mock_obj);
318
319 // Registers a mock object and a mock method it owns.
320 // L < g_gmock_mutex
321 static void Register(const void* mock_obj,
322 internal::UntypedFunctionMockerBase* mocker);
323
zhanyong.wandf35a762009-04-22 22:25:31 +0000324 // Tells Google Mock where in the source code mock_obj is used in an
325 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
326 // information helps the user identify which object it is.
327 // L < g_gmock_mutex
328 static void RegisterUseByOnCallOrExpectCall(
329 const void* mock_obj, const char* file, int line);
330
shiqiane35fdd92008-12-10 05:08:54 +0000331 // Unregisters a mock method; removes the owning mock object from
332 // the registry when the last mock method associated with it has
333 // been unregistered. This is called only in the destructor of
334 // FunctionMockerBase.
335 // L >= g_gmock_mutex
336 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
337}; // class Mock
338
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000339// An abstract handle of an expectation. Useful in the .After()
340// clause of EXPECT_CALL() for setting the (partial) order of
341// expectations. The syntax:
342//
343// Expectation e1 = EXPECT_CALL(...)...;
344// EXPECT_CALL(...).After(e1)...;
345//
346// sets two expectations where the latter can only be matched after
347// the former has been satisfied.
348//
349// Notes:
350// - This class is copyable and has value semantics.
351// - Constness is shallow: a const Expectation object itself cannot
352// be modified, but the mutable methods of the ExpectationBase
353// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000354// - The constructors and destructor are defined out-of-line because
355// the Symbian WINSCW compiler wants to otherwise instantiate them
356// when it sees this class definition, at which point it doesn't have
357// ExpectationBase available yet, leading to incorrect destruction
358// in the linked_ptr (or compilation errors if using a checking
359// linked_ptr).
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000360class Expectation {
361 public:
362 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000363 Expectation();
364
365 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000366
367 // This single-argument ctor must not be explicit, in order to support the
368 // Expectation e = EXPECT_CALL(...);
369 // syntax.
370 //
371 // A TypedExpectation object stores its pre-requisites as
372 // Expectation objects, and needs to call the non-const Retire()
373 // method on the ExpectationBase objects they reference. Therefore
374 // Expectation must receive a *non-const* reference to the
375 // ExpectationBase object.
376 Expectation(internal::ExpectationBase& exp); // NOLINT
377
378 // The compiler-generated copy ctor and operator= work exactly as
379 // intended, so we don't need to define our own.
380
381 // Returns true iff rhs references the same expectation as this object does.
382 bool operator==(const Expectation& rhs) const {
383 return expectation_base_ == rhs.expectation_base_;
384 }
385
386 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
387
388 private:
389 friend class ExpectationSet;
390 friend class Sequence;
391 friend class ::testing::internal::ExpectationBase;
392
393 template <typename F>
394 friend class ::testing::internal::FunctionMockerBase;
395
396 template <typename F>
397 friend class ::testing::internal::TypedExpectation;
398
399 // This comparator is needed for putting Expectation objects into a set.
400 class Less {
401 public:
402 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
403 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
404 }
405 };
406
407 typedef ::std::set<Expectation, Less> Set;
408
409 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000410 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000411
412 // Returns the expectation this object references.
413 const internal::linked_ptr<internal::ExpectationBase>&
414 expectation_base() const {
415 return expectation_base_;
416 }
417
418 // A linked_ptr that co-owns the expectation this handle references.
419 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
420};
421
422// A set of expectation handles. Useful in the .After() clause of
423// EXPECT_CALL() for setting the (partial) order of expectations. The
424// syntax:
425//
426// ExpectationSet es;
427// es += EXPECT_CALL(...)...;
428// es += EXPECT_CALL(...)...;
429// EXPECT_CALL(...).After(es)...;
430//
431// sets three expectations where the last one can only be matched
432// after the first two have both been satisfied.
433//
434// This class is copyable and has value semantics.
435class ExpectationSet {
436 public:
437 // A bidirectional iterator that can read a const element in the set.
438 typedef Expectation::Set::const_iterator const_iterator;
439
440 // An object stored in the set. This is an alias of Expectation.
441 typedef Expectation::Set::value_type value_type;
442
443 // Constructs an empty set.
444 ExpectationSet() {}
445
446 // This single-argument ctor must not be explicit, in order to support the
447 // ExpectationSet es = EXPECT_CALL(...);
448 // syntax.
449 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
450 *this += Expectation(exp);
451 }
452
453 // This single-argument ctor implements implicit conversion from
454 // Expectation and thus must not be explicit. This allows either an
455 // Expectation or an ExpectationSet to be used in .After().
456 ExpectationSet(const Expectation& e) { // NOLINT
457 *this += e;
458 }
459
460 // The compiler-generator ctor and operator= works exactly as
461 // intended, so we don't need to define our own.
462
463 // Returns true iff rhs contains the same set of Expectation objects
464 // as this does.
465 bool operator==(const ExpectationSet& rhs) const {
466 return expectations_ == rhs.expectations_;
467 }
468
469 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
470
471 // Implements the syntax
472 // expectation_set += EXPECT_CALL(...);
473 ExpectationSet& operator+=(const Expectation& e) {
474 expectations_.insert(e);
475 return *this;
476 }
477
478 int size() const { return static_cast<int>(expectations_.size()); }
479
480 const_iterator begin() const { return expectations_.begin(); }
481 const_iterator end() const { return expectations_.end(); }
482
483 private:
484 Expectation::Set expectations_;
485};
486
487
shiqiane35fdd92008-12-10 05:08:54 +0000488// Sequence objects are used by a user to specify the relative order
489// in which the expectations should match. They are copyable (we rely
490// on the compiler-defined copy constructor and assignment operator).
491class Sequence {
492 public:
493 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000494 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000495
496 // Adds an expectation to this sequence. The caller must ensure
497 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000498 void AddExpectation(const Expectation& expectation) const;
499
shiqiane35fdd92008-12-10 05:08:54 +0000500 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000501 // The last expectation in this sequence. We use a linked_ptr here
502 // because Sequence objects are copyable and we want the copies to
503 // be aliases. The linked_ptr allows the copies to co-own and share
504 // the same Expectation object.
505 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000506}; // class Sequence
507
508// An object of this type causes all EXPECT_CALL() statements
509// encountered in its scope to be put in an anonymous sequence. The
510// work is done in the constructor and destructor. You should only
511// create an InSequence object on the stack.
512//
513// The sole purpose for this class is to support easy definition of
514// sequential expectations, e.g.
515//
516// {
517// InSequence dummy; // The name of the object doesn't matter.
518//
519// // The following expectations must match in the order they appear.
520// EXPECT_CALL(a, Bar())...;
521// EXPECT_CALL(a, Baz())...;
522// ...
523// EXPECT_CALL(b, Xyz())...;
524// }
525//
526// You can create InSequence objects in multiple threads, as long as
527// they are used to affect different mock objects. The idea is that
528// each thread can create and set up its own mocks as if it's the only
529// thread. However, for clarity of your tests we recommend you to set
530// up mocks in the main thread unless you have a good reason not to do
531// so.
532class InSequence {
533 public:
534 InSequence();
535 ~InSequence();
536 private:
537 bool sequence_created_;
538
539 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000540} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000541
542namespace internal {
543
544// Points to the implicit sequence introduced by a living InSequence
545// object (if any) in the current thread or NULL.
546extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
547
548// Base class for implementing expectations.
549//
550// There are two reasons for having a type-agnostic base class for
551// Expectation:
552//
553// 1. We need to store collections of expectations of different
554// types (e.g. all pre-requisites of a particular expectation, all
555// expectations in a sequence). Therefore these expectation objects
556// must share a common base class.
557//
558// 2. We can avoid binary code bloat by moving methods not depending
559// on the template argument of Expectation to the base class.
560//
561// This class is internal and mustn't be used by user code directly.
562class ExpectationBase {
563 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000564 // source_text is the EXPECT_CALL(...) source that created this Expectation.
565 ExpectationBase(const char* file, int line, const string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000566
567 virtual ~ExpectationBase();
568
569 // Where in the source file was the expectation spec defined?
570 const char* file() const { return file_; }
571 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000572 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000573 // Returns the cardinality specified in the expectation spec.
574 const Cardinality& cardinality() const { return cardinality_; }
575
576 // Describes the source file location of this expectation.
577 void DescribeLocationTo(::std::ostream* os) const {
578 *os << file() << ":" << line() << ": ";
579 }
580
581 // Describes how many times a function call matching this
582 // expectation has occurred.
583 // L >= g_gmock_mutex
584 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000585
shiqiane35fdd92008-12-10 05:08:54 +0000586 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000587 friend class ::testing::Expectation;
shiqiane35fdd92008-12-10 05:08:54 +0000588
589 enum Clause {
590 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000591 kNone,
592 kWith,
593 kTimes,
594 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000595 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000596 kWillOnce,
597 kWillRepeatedly,
598 kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000599 };
600
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000601 // Returns an Expectation object that references and co-owns this
602 // expectation.
603 virtual Expectation GetHandle() = 0;
604
shiqiane35fdd92008-12-10 05:08:54 +0000605 // Asserts that the EXPECT_CALL() statement has the given property.
606 void AssertSpecProperty(bool property, const string& failure_message) const {
607 Assert(property, file_, line_, failure_message);
608 }
609
610 // Expects that the EXPECT_CALL() statement has the given property.
611 void ExpectSpecProperty(bool property, const string& failure_message) const {
612 Expect(property, file_, line_, failure_message);
613 }
614
615 // Explicitly specifies the cardinality of this expectation. Used
616 // by the subclasses to implement the .Times() clause.
617 void SpecifyCardinality(const Cardinality& cardinality);
618
619 // Returns true iff the user specified the cardinality explicitly
620 // using a .Times().
621 bool cardinality_specified() const { return cardinality_specified_; }
622
623 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000624 void set_cardinality(const Cardinality& a_cardinality) {
625 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000626 }
627
628 // The following group of methods should only be called after the
629 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
630 // the current thread.
631
632 // Retires all pre-requisites of this expectation.
633 // L >= g_gmock_mutex
634 void RetireAllPreRequisites();
635
636 // Returns true iff this expectation is retired.
637 // L >= g_gmock_mutex
638 bool is_retired() const {
639 g_gmock_mutex.AssertHeld();
640 return retired_;
641 }
642
643 // Retires this expectation.
644 // L >= g_gmock_mutex
645 void Retire() {
646 g_gmock_mutex.AssertHeld();
647 retired_ = true;
648 }
649
650 // Returns true iff this expectation is satisfied.
651 // L >= g_gmock_mutex
652 bool IsSatisfied() const {
653 g_gmock_mutex.AssertHeld();
654 return cardinality().IsSatisfiedByCallCount(call_count_);
655 }
656
657 // Returns true iff this expectation is saturated.
658 // L >= g_gmock_mutex
659 bool IsSaturated() const {
660 g_gmock_mutex.AssertHeld();
661 return cardinality().IsSaturatedByCallCount(call_count_);
662 }
663
664 // Returns true iff this expectation is over-saturated.
665 // L >= g_gmock_mutex
666 bool IsOverSaturated() const {
667 g_gmock_mutex.AssertHeld();
668 return cardinality().IsOverSaturatedByCallCount(call_count_);
669 }
670
671 // Returns true iff all pre-requisites of this expectation are satisfied.
672 // L >= g_gmock_mutex
673 bool AllPrerequisitesAreSatisfied() const;
674
675 // Adds unsatisfied pre-requisites of this expectation to 'result'.
676 // L >= g_gmock_mutex
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000677 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const;
shiqiane35fdd92008-12-10 05:08:54 +0000678
679 // Returns the number this expectation has been invoked.
680 // L >= g_gmock_mutex
681 int call_count() const {
682 g_gmock_mutex.AssertHeld();
683 return call_count_;
684 }
685
686 // Increments the number this expectation has been invoked.
687 // L >= g_gmock_mutex
688 void IncrementCallCount() {
689 g_gmock_mutex.AssertHeld();
690 call_count_++;
691 }
692
693 private:
694 friend class ::testing::Sequence;
695 friend class ::testing::internal::ExpectationTester;
696
697 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000698 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000699
700 // This group of fields are part of the spec and won't change after
701 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000702 const char* file_; // The file that contains the expectation.
703 int line_; // The line number of the expectation.
704 const string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000705 // True iff the cardinality is specified explicitly.
706 bool cardinality_specified_;
707 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000708 // The immediate pre-requisites (i.e. expectations that must be
709 // satisfied before this expectation can be matched) of this
710 // expectation. We use linked_ptr in the set because we want an
711 // Expectation object to be co-owned by its FunctionMocker and its
712 // successors. This allows multiple mock objects to be deleted at
713 // different times.
714 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000715
716 // This group of fields are the current state of the expectation,
717 // and can change as the mock function is called.
718 int call_count_; // How many times this expectation has been invoked.
719 bool retired_; // True iff this expectation has retired.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000720
721 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000722}; // class ExpectationBase
723
724// Impements an expectation for the given function type.
725template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000726class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000727 public:
728 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
729 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
730 typedef typename Function<F>::Result Result;
731
vladlosev6c54a5e2009-10-21 06:15:34 +0000732 TypedExpectation(FunctionMockerBase<F>* owner,
zhanyong.wan32de5f52009-12-23 00:13:23 +0000733 const char* a_file, int a_line, const string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000734 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000735 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000736 owner_(owner),
737 matchers_(m),
vladlosev6c54a5e2009-10-21 06:15:34 +0000738 extra_matcher_specified_(false),
zhanyong.wan18490652009-05-11 18:54:08 +0000739 // By default, extra_matcher_ should match anything. However,
740 // we cannot initialize it with _ as that triggers a compiler
741 // bug in Symbian's C++ compiler (cannot decide between two
742 // overloaded constructors of Matcher<const ArgumentTuple&>).
743 extra_matcher_(A<const ArgumentTuple&>()),
shiqiane35fdd92008-12-10 05:08:54 +0000744 repeated_action_specified_(false),
745 repeated_action_(DoDefault()),
746 retires_on_saturation_(false),
zhanyong.wanbf550852009-06-09 06:09:53 +0000747 last_clause_(kNone),
shiqiane35fdd92008-12-10 05:08:54 +0000748 action_count_checked_(false) {}
749
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000750 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000751 // Check the validity of the action count if it hasn't been done
752 // yet (for example, if the expectation was never used).
753 CheckActionCountIfNotDone();
754 }
755
zhanyong.wanbf550852009-06-09 06:09:53 +0000756 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000757 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000758 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000759 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000760 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000761 "more than once in an EXPECT_CALL().");
762 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000763 ExpectSpecProperty(last_clause_ < kWith,
764 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000765 "clause in an EXPECT_CALL().");
766 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000767 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000768
769 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000770 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000771 return *this;
772 }
773
774 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000775 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000776 if (last_clause_ ==kTimes) {
shiqiane35fdd92008-12-10 05:08:54 +0000777 ExpectSpecProperty(false,
778 ".Times() cannot appear "
779 "more than once in an EXPECT_CALL().");
780 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000781 ExpectSpecProperty(last_clause_ < kTimes,
shiqiane35fdd92008-12-10 05:08:54 +0000782 ".Times() cannot appear after "
783 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
784 "or .RetiresOnSaturation().");
785 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000786 last_clause_ = kTimes;
shiqiane35fdd92008-12-10 05:08:54 +0000787
zhanyong.wan32de5f52009-12-23 00:13:23 +0000788 ExpectationBase::SpecifyCardinality(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000789 return *this;
790 }
791
792 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000793 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000794 return Times(Exactly(n));
795 }
796
797 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000798 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000799 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000800 ".InSequence() cannot appear after .After(),"
801 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000802 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000803 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000804
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000805 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000806 return *this;
807 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000808 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000809 return InSequence(s1).InSequence(s2);
810 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000811 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
812 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000813 return InSequence(s1, s2).InSequence(s3);
814 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000815 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
816 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000817 return InSequence(s1, s2, s3).InSequence(s4);
818 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000819 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
820 const Sequence& s3, const Sequence& s4,
821 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000822 return InSequence(s1, s2, s3, s4).InSequence(s5);
823 }
824
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000825 // Implements that .After() clause.
826 TypedExpectation& After(const ExpectationSet& s) {
827 ExpectSpecProperty(last_clause_ <= kAfter,
828 ".After() cannot appear after .WillOnce(),"
829 " .WillRepeatedly(), or "
830 ".RetiresOnSaturation().");
831 last_clause_ = kAfter;
832
833 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
834 immediate_prerequisites_ += *it;
835 }
836 return *this;
837 }
838 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
839 return After(s1).After(s2);
840 }
841 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
842 const ExpectationSet& s3) {
843 return After(s1, s2).After(s3);
844 }
845 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
846 const ExpectationSet& s3, const ExpectationSet& s4) {
847 return After(s1, s2, s3).After(s4);
848 }
849 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
850 const ExpectationSet& s3, const ExpectationSet& s4,
851 const ExpectationSet& s5) {
852 return After(s1, s2, s3, s4).After(s5);
853 }
854
shiqiane35fdd92008-12-10 05:08:54 +0000855 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000856 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000857 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000858 ".WillOnce() cannot appear after "
859 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000860 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +0000861
862 actions_.push_back(action);
863 if (!cardinality_specified()) {
864 set_cardinality(Exactly(static_cast<int>(actions_.size())));
865 }
866 return *this;
867 }
868
869 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000870 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000871 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +0000872 ExpectSpecProperty(false,
873 ".WillRepeatedly() cannot appear "
874 "more than once in an EXPECT_CALL().");
875 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000876 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +0000877 ".WillRepeatedly() cannot appear "
878 "after .RetiresOnSaturation().");
879 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000880 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +0000881 repeated_action_specified_ = true;
882
883 repeated_action_ = action;
884 if (!cardinality_specified()) {
885 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
886 }
887
888 // Now that no more action clauses can be specified, we check
889 // whether their count makes sense.
890 CheckActionCountIfNotDone();
891 return *this;
892 }
893
894 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000895 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +0000896 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000897 ".RetiresOnSaturation() cannot appear "
898 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +0000899 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +0000900 retires_on_saturation_ = true;
901
902 // Now that no more action clauses can be specified, we check
903 // whether their count makes sense.
904 CheckActionCountIfNotDone();
905 return *this;
906 }
907
908 // Returns the matchers for the arguments as specified inside the
909 // EXPECT_CALL() macro.
910 const ArgumentMatcherTuple& matchers() const {
911 return matchers_;
912 }
913
zhanyong.wanbf550852009-06-09 06:09:53 +0000914 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +0000915 const Matcher<const ArgumentTuple&>& extra_matcher() const {
916 return extra_matcher_;
917 }
918
919 // Returns the sequence of actions specified by the .WillOnce() clause.
920 const std::vector<Action<F> >& actions() const { return actions_; }
921
922 // Returns the action specified by the .WillRepeatedly() clause.
923 const Action<F>& repeated_action() const { return repeated_action_; }
924
925 // Returns true iff the .RetiresOnSaturation() clause was specified.
926 bool retires_on_saturation() const { return retires_on_saturation_; }
927
928 // Describes how many times a function call matching this
929 // expectation has occurred (implements
930 // ExpectationBase::DescribeCallCountTo()).
931 // L >= g_gmock_mutex
932 virtual void DescribeCallCountTo(::std::ostream* os) const {
933 g_gmock_mutex.AssertHeld();
934
935 // Describes how many times the function is expected to be called.
936 *os << " Expected: to be ";
937 cardinality().DescribeTo(os);
938 *os << "\n Actual: ";
939 Cardinality::DescribeActualCallCountTo(call_count(), os);
940
941 // Describes the state of the expectation (e.g. is it satisfied?
942 // is it active?).
943 *os << " - " << (IsOverSaturated() ? "over-saturated" :
944 IsSaturated() ? "saturated" :
945 IsSatisfied() ? "satisfied" : "unsatisfied")
946 << " and "
947 << (is_retired() ? "retired" : "active");
948 }
vladlosev6c54a5e2009-10-21 06:15:34 +0000949
950 void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
951 if (extra_matcher_specified_) {
952 *os << " Expected args: ";
953 extra_matcher_.DescribeTo(os);
954 *os << "\n";
955 }
956 }
957
shiqiane35fdd92008-12-10 05:08:54 +0000958 private:
959 template <typename Function>
960 friend class FunctionMockerBase;
961
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000962 // Returns an Expectation object that references and co-owns this
963 // expectation.
964 virtual Expectation GetHandle() {
965 return owner_->GetHandleOf(this);
966 }
967
shiqiane35fdd92008-12-10 05:08:54 +0000968 // The following methods will be called only after the EXPECT_CALL()
969 // statement finishes and when the current thread holds
970 // g_gmock_mutex.
971
972 // Returns true iff this expectation matches the given arguments.
973 // L >= g_gmock_mutex
974 bool Matches(const ArgumentTuple& args) const {
975 g_gmock_mutex.AssertHeld();
976 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
977 }
978
979 // Returns true iff this expectation should handle the given arguments.
980 // L >= g_gmock_mutex
981 bool ShouldHandleArguments(const ArgumentTuple& args) const {
982 g_gmock_mutex.AssertHeld();
983
984 // In case the action count wasn't checked when the expectation
985 // was defined (e.g. if this expectation has no WillRepeatedly()
986 // or RetiresOnSaturation() clause), we check it when the
987 // expectation is used for the first time.
988 CheckActionCountIfNotDone();
989 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
990 }
991
992 // Describes the result of matching the arguments against this
993 // expectation to the given ostream.
994 // L >= g_gmock_mutex
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000995 void ExplainMatchResultTo(const ArgumentTuple& args,
996 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000997 g_gmock_mutex.AssertHeld();
998
999 if (is_retired()) {
1000 *os << " Expected: the expectation is active\n"
1001 << " Actual: it is retired\n";
1002 } else if (!Matches(args)) {
1003 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001004 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001005 }
zhanyong.wan82113312010-01-08 21:55:40 +00001006 StringMatchResultListener listener;
1007 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001008 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001009 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001010 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001011
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001012 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001013 *os << "\n";
1014 }
1015 } else if (!AllPrerequisitesAreSatisfied()) {
1016 *os << " Expected: all pre-requisites are satisfied\n"
1017 << " Actual: the following immediate pre-requisites "
1018 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001019 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001020 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1021 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001022 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001023 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001024 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001025 *os << "pre-requisite #" << i++ << "\n";
1026 }
1027 *os << " (end of pre-requisites)\n";
1028 } else {
1029 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001030 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001031 // is called only when the mock function call does NOT match the
1032 // expectation.
1033 *os << "The call matches the expectation.\n";
1034 }
1035 }
1036
1037 // Returns the action that should be taken for the current invocation.
1038 // L >= g_gmock_mutex
1039 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
1040 const ArgumentTuple& args) const {
1041 g_gmock_mutex.AssertHeld();
1042 const int count = call_count();
1043 Assert(count >= 1, __FILE__, __LINE__,
1044 "call_count() is <= 0 when GetCurrentAction() is "
1045 "called - this should never happen.");
1046
1047 const int action_count = static_cast<int>(actions().size());
1048 if (action_count > 0 && !repeated_action_specified_ &&
1049 count > action_count) {
1050 // If there is at least one WillOnce() and no WillRepeatedly(),
1051 // we warn the user when the WillOnce() clauses ran out.
1052 ::std::stringstream ss;
1053 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001054 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001055 << "Called " << count << " times, but only "
1056 << action_count << " WillOnce()"
1057 << (action_count == 1 ? " is" : "s are") << " specified - ";
1058 mocker->DescribeDefaultActionTo(args, &ss);
1059 Log(WARNING, ss.str(), 1);
1060 }
1061
1062 return count <= action_count ? actions()[count - 1] : repeated_action();
1063 }
1064
1065 // Given the arguments of a mock function call, if the call will
1066 // over-saturate this expectation, returns the default action;
1067 // otherwise, returns the next action in this expectation. Also
1068 // describes *what* happened to 'what', and explains *why* Google
1069 // Mock does it to 'why'. This method is not const as it calls
1070 // IncrementCallCount().
1071 // L >= g_gmock_mutex
1072 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
1073 const ArgumentTuple& args,
1074 ::std::ostream* what,
1075 ::std::ostream* why) {
1076 g_gmock_mutex.AssertHeld();
1077 if (IsSaturated()) {
1078 // We have an excessive call.
1079 IncrementCallCount();
1080 *what << "Mock function called more times than expected - ";
1081 mocker->DescribeDefaultActionTo(args, what);
1082 DescribeCallCountTo(why);
1083
1084 // TODO(wan): allow the user to control whether unexpected calls
1085 // should fail immediately or continue using a flag
1086 // --gmock_unexpected_calls_are_fatal.
1087 return DoDefault();
1088 }
1089
1090 IncrementCallCount();
1091 RetireAllPreRequisites();
1092
1093 if (retires_on_saturation() && IsSaturated()) {
1094 Retire();
1095 }
1096
1097 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001098 *what << "Mock function call matches " << source_text() <<"...\n";
shiqiane35fdd92008-12-10 05:08:54 +00001099 return GetCurrentAction(mocker, args);
1100 }
1101
1102 // Checks the action count (i.e. the number of WillOnce() and
1103 // WillRepeatedly() clauses) against the cardinality if this hasn't
1104 // been done before. Prints a warning if there are too many or too
1105 // few actions.
1106 // L < mutex_
1107 void CheckActionCountIfNotDone() const {
1108 bool should_check = false;
1109 {
1110 MutexLock l(&mutex_);
1111 if (!action_count_checked_) {
1112 action_count_checked_ = true;
1113 should_check = true;
1114 }
1115 }
1116
1117 if (should_check) {
1118 if (!cardinality_specified_) {
1119 // The cardinality was inferred - no need to check the action
1120 // count against it.
1121 return;
1122 }
1123
1124 // The cardinality was explicitly specified.
1125 const int action_count = static_cast<int>(actions_.size());
1126 const int upper_bound = cardinality().ConservativeUpperBound();
1127 const int lower_bound = cardinality().ConservativeLowerBound();
1128 bool too_many; // True if there are too many actions, or false
1129 // if there are too few.
1130 if (action_count > upper_bound ||
1131 (action_count == upper_bound && repeated_action_specified_)) {
1132 too_many = true;
1133 } else if (0 < action_count && action_count < lower_bound &&
1134 !repeated_action_specified_) {
1135 too_many = false;
1136 } else {
1137 return;
1138 }
1139
1140 ::std::stringstream ss;
1141 DescribeLocationTo(&ss);
1142 ss << "Too " << (too_many ? "many" : "few")
vladlosev6c54a5e2009-10-21 06:15:34 +00001143 << " actions specified in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001144 << "Expected to be ";
1145 cardinality().DescribeTo(&ss);
1146 ss << ", but has " << (too_many ? "" : "only ")
1147 << action_count << " WillOnce()"
1148 << (action_count == 1 ? "" : "s");
1149 if (repeated_action_specified_) {
1150 ss << " and a WillRepeatedly()";
1151 }
1152 ss << ".";
1153 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
1154 }
1155 }
1156
1157 // All the fields below won't change once the EXPECT_CALL()
1158 // statement finishes.
1159 FunctionMockerBase<F>* const owner_;
1160 ArgumentMatcherTuple matchers_;
vladlosev6c54a5e2009-10-21 06:15:34 +00001161 bool extra_matcher_specified_;
shiqiane35fdd92008-12-10 05:08:54 +00001162 Matcher<const ArgumentTuple&> extra_matcher_;
1163 std::vector<Action<F> > actions_;
1164 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
1165 Action<F> repeated_action_;
1166 bool retires_on_saturation_;
1167 Clause last_clause_;
1168 mutable bool action_count_checked_; // Under mutex_.
1169 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +00001170
1171 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001172}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001173
1174// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1175// specifying the default behavior of, or expectation on, a mock
1176// function.
1177
1178// Note: class MockSpec really belongs to the ::testing namespace.
1179// However if we define it in ::testing, MSVC will complain when
1180// classes in ::testing::internal declare it as a friend class
1181// template. To workaround this compiler bug, we define MockSpec in
1182// ::testing::internal and import it into ::testing.
1183
1184template <typename F>
1185class MockSpec {
1186 public:
1187 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1188 typedef typename internal::Function<F>::ArgumentMatcherTuple
1189 ArgumentMatcherTuple;
1190
1191 // Constructs a MockSpec object, given the function mocker object
1192 // that the spec is associated with.
1193 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1194 : function_mocker_(function_mocker) {}
1195
1196 // Adds a new default action spec to the function mocker and returns
1197 // the newly created spec.
1198 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
1199 const char* file, int line, const char* obj, const char* call) {
1200 LogWithLocation(internal::INFO, file, line,
1201 string("ON_CALL(") + obj + ", " + call + ") invoked");
1202 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
1203 }
1204
1205 // Adds a new expectation spec to the function mocker and returns
1206 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001207 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001208 const char* file, int line, const char* obj, const char* call) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001209 const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
1210 LogWithLocation(internal::INFO, file, line, source_text + " invoked");
1211 return function_mocker_->AddNewExpectation(
1212 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001213 }
1214
1215 private:
1216 template <typename Function>
1217 friend class internal::FunctionMocker;
1218
1219 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1220 matchers_ = matchers;
1221 }
1222
1223 // Logs a message including file and line number information.
1224 void LogWithLocation(testing::internal::LogSeverity severity,
1225 const char* file, int line,
1226 const string& message) {
1227 ::std::ostringstream s;
1228 s << file << ":" << line << ": " << message << ::std::endl;
1229 Log(severity, s.str(), 0);
1230 }
1231
1232 // The function mocker that owns this spec.
1233 internal::FunctionMockerBase<F>* const function_mocker_;
1234 // The argument matchers specified in the spec.
1235 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001236
1237 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001238}; // class MockSpec
1239
1240// MSVC warns about using 'this' in base member initializer list, so
1241// we need to temporarily disable the warning. We have to do it for
1242// the entire class to suppress the warning, even though it's about
1243// the constructor only.
1244
1245#ifdef _MSC_VER
1246#pragma warning(push) // Saves the current warning state.
1247#pragma warning(disable:4355) // Temporarily disables warning 4355.
1248#endif // _MSV_VER
1249
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001250// C++ treats the void type specially. For example, you cannot define
1251// a void-typed variable or pass a void value to a function.
1252// ActionResultHolder<T> holds a value of type T, where T must be a
1253// copyable type or void (T doesn't need to be default-constructable).
1254// It hides the syntactic difference between void and other types, and
1255// is used to unify the code for invoking both void-returning and
1256// non-void-returning mock functions. This generic definition is used
1257// when T is not void.
1258template <typename T>
1259class ActionResultHolder {
1260 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00001261 explicit ActionResultHolder(T a_value) : value_(a_value) {}
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001262
1263 // The compiler-generated copy constructor and assignment operator
1264 // are exactly what we need, so we don't need to define them.
1265
1266 T value() const { return value_; }
1267
1268 // Prints the held value as an action's result to os.
1269 void PrintAsActionResult(::std::ostream* os) const {
1270 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001271 // T may be a reference type, so we don't use UniversalPrint().
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001272 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();
vladloseve2e8ba42010-05-13 18:16:03 +00001543 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001544 }
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();
vladloseve2e8ba42010-05-13 18:16:03 +00001779 UniversalPrint(args, &ss);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001780
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_