blob: b570c00caa1bd8adf303cbb56a76b9fb5d07c7c4 [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)
52// .WillOnce(action)
53// .WillRepeatedly(action)
54// .RetiresOnSaturation();
55//
56// where all clauses are optional, .InSequence() and .WillOnce() can
57// appear any number of times, and .Times() can be omitted only if
58// .WillOnce() or .WillRepeatedly() is present.
59
60#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
61#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62
63#include <map>
64#include <set>
65#include <sstream>
66#include <string>
67#include <vector>
68
69#include <gmock/gmock-actions.h>
70#include <gmock/gmock-cardinalities.h>
71#include <gmock/gmock-matchers.h>
72#include <gmock/gmock-printers.h>
73#include <gmock/internal/gmock-internal-utils.h>
74#include <gmock/internal/gmock-port.h>
75#include <gtest/gtest.h>
76
77namespace testing {
78
79// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
80// and MUST NOT BE USED IN USER CODE!!!
81namespace internal {
82
83template <typename F>
84class FunctionMocker;
85
86// Base class for expectations.
87class ExpectationBase;
88
89// Helper class for testing the Expectation class template.
90class ExpectationTester;
91
92// Base class for function mockers.
93template <typename F>
94class FunctionMockerBase;
95
shiqiane35fdd92008-12-10 05:08:54 +000096// Protects the mock object registry (in class Mock), all function
97// mockers, and all expectations.
98//
99// The reason we don't use more fine-grained protection is: when a
100// mock function Foo() is called, it needs to consult its expectations
101// to see which one should be picked. If another thread is allowed to
102// call a mock function (either Foo() or a different one) at the same
103// time, it could affect the "retired" attributes of Foo()'s
104// expectations when InSequence() is used, and thus affect which
105// expectation gets picked. Therefore, we sequence all mock function
106// calls to ensure the integrity of the mock objects' states.
107extern Mutex g_gmock_mutex;
108
109// Abstract base class of FunctionMockerBase. This is the
110// type-agnostic part of the function mocker interface. Its pure
111// virtual methods are implemented by FunctionMockerBase.
112class UntypedFunctionMockerBase {
113 public:
114 virtual ~UntypedFunctionMockerBase() {}
115
116 // Verifies that all expectations on this mock function have been
117 // satisfied. Reports one or more Google Test non-fatal failures
118 // and returns false if not.
119 // L >= g_gmock_mutex
120 virtual bool VerifyAndClearExpectationsLocked() = 0;
121
122 // Clears the ON_CALL()s set on this mock function.
123 // L >= g_gmock_mutex
124 virtual void ClearDefaultActionsLocked() = 0;
125}; // class UntypedFunctionMockerBase
126
127// This template class implements a default action spec (i.e. an
128// ON_CALL() statement).
129template <typename F>
130class DefaultActionSpec {
131 public:
132 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
133 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
134
135 // Constructs a DefaultActionSpec object from the information inside
136 // the parenthesis of an ON_CALL() statement.
137 DefaultActionSpec(const char* file, int line,
138 const ArgumentMatcherTuple& matchers)
139 : file_(file),
140 line_(line),
141 matchers_(matchers),
zhanyong.wan18490652009-05-11 18:54:08 +0000142 // By default, extra_matcher_ should match anything. However,
143 // we cannot initialize it with _ as that triggers a compiler
144 // bug in Symbian's C++ compiler (cannot decide between two
145 // overloaded constructors of Matcher<const ArgumentTuple&>).
146 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.wanbf550852009-06-09 06:09:53 +0000147 last_clause_(kNone) {
shiqiane35fdd92008-12-10 05:08:54 +0000148 }
149
150 // Where in the source file was the default action spec defined?
151 const char* file() const { return file_; }
152 int line() const { return line_; }
153
zhanyong.wanbf550852009-06-09 06:09:53 +0000154 // Implements the .With() clause.
155 DefaultActionSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000156 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000157 ExpectSpecProperty(last_clause_ < kWith,
158 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000159 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000160 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000161
162 extra_matcher_ = m;
163 return *this;
164 }
165
zhanyong.wanbf550852009-06-09 06:09:53 +0000166 // Implements the .WithArguments() clause as a synonym of .With()
167 // for backward compatibility. WithArguments() is deprecated and
168 // new code should always use With(), as .With(Args<1, 2>(m)) is
169 // clearer than .WithArguments(Args<1, 2>(m)).
170 DefaultActionSpec& WithArguments(const Matcher<const ArgumentTuple&>& m) {
171 return With(m);
172 }
173
shiqiane35fdd92008-12-10 05:08:54 +0000174 // Implements the .WillByDefault() clause.
175 DefaultActionSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000176 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000177 ".WillByDefault() must appear "
178 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000179 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000180
181 ExpectSpecProperty(!action.IsDoDefault(),
182 "DoDefault() cannot be used in ON_CALL().");
183 action_ = action;
184 return *this;
185 }
186
187 // Returns true iff the given arguments match the matchers.
188 bool Matches(const ArgumentTuple& args) const {
189 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
190 }
191
192 // Returns the action specified by the user.
193 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000194 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000195 ".WillByDefault() must appear exactly "
196 "once in an ON_CALL().");
197 return action_;
198 }
199 private:
200 // Gives each clause in the ON_CALL() statement a name.
201 enum Clause {
202 // Do not change the order of the enum members! The run-time
203 // syntax checking relies on it.
zhanyong.wanbf550852009-06-09 06:09:53 +0000204 kNone,
205 kWith,
206 kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000207 };
208
209 // Asserts that the ON_CALL() statement has a certain property.
210 void AssertSpecProperty(bool property, const string& failure_message) const {
211 Assert(property, file_, line_, failure_message);
212 }
213
214 // Expects that the ON_CALL() statement has a certain property.
215 void ExpectSpecProperty(bool property, const string& failure_message) const {
216 Expect(property, file_, line_, failure_message);
217 }
218
219 // The information in statement
220 //
221 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000222 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000223 // .WillByDefault(action);
224 //
225 // is recorded in the data members like this:
226 //
227 // source file that contains the statement => file_
228 // line number of the statement => line_
229 // matchers => matchers_
230 // multi-argument-matcher => extra_matcher_
231 // action => action_
232 const char* file_;
233 int line_;
234 ArgumentMatcherTuple matchers_;
235 Matcher<const ArgumentTuple&> extra_matcher_;
236 Action<F> action_;
237
238 // The last clause in the ON_CALL() statement as seen so far.
zhanyong.wanbf550852009-06-09 06:09:53 +0000239 // Initially kNone and changes as the statement is parsed.
shiqiane35fdd92008-12-10 05:08:54 +0000240 Clause last_clause_;
241}; // class DefaultActionSpec
242
243// Possible reactions on uninteresting calls.
244enum CallReaction {
245 ALLOW,
246 WARN,
247 FAIL,
248};
249
250} // namespace internal
251
252// Utilities for manipulating mock objects.
253class Mock {
254 public:
255 // The following public methods can be called concurrently.
256
zhanyong.wandf35a762009-04-22 22:25:31 +0000257 // Tells Google Mock to ignore mock_obj when checking for leaked
258 // mock objects.
259 static void AllowLeak(const void* mock_obj);
260
shiqiane35fdd92008-12-10 05:08:54 +0000261 // Verifies and clears all expectations on the given mock object.
262 // If the expectations aren't satisfied, generates one or more
263 // Google Test non-fatal failures and returns false.
264 static bool VerifyAndClearExpectations(void* mock_obj);
265
266 // Verifies all expectations on the given mock object and clears its
267 // default actions and expectations. Returns true iff the
268 // verification was successful.
269 static bool VerifyAndClear(void* mock_obj);
270 private:
271 // Needed for a function mocker to register itself (so that we know
272 // how to clear a mock object).
273 template <typename F>
274 friend class internal::FunctionMockerBase;
275
shiqiane35fdd92008-12-10 05:08:54 +0000276 template <typename M>
277 friend class NiceMock;
278
279 template <typename M>
280 friend class StrictMock;
281
282 // Tells Google Mock to allow uninteresting calls on the given mock
283 // object.
284 // L < g_gmock_mutex
285 static void AllowUninterestingCalls(const void* mock_obj);
286
287 // Tells Google Mock to warn the user about uninteresting calls on
288 // the given mock object.
289 // L < g_gmock_mutex
290 static void WarnUninterestingCalls(const void* mock_obj);
291
292 // Tells Google Mock to fail uninteresting calls on the given mock
293 // object.
294 // L < g_gmock_mutex
295 static void FailUninterestingCalls(const void* mock_obj);
296
297 // Tells Google Mock the given mock object is being destroyed and
298 // its entry in the call-reaction table should be removed.
299 // L < g_gmock_mutex
300 static void UnregisterCallReaction(const void* mock_obj);
301
302 // Returns the reaction Google Mock will have on uninteresting calls
303 // made on the given mock object.
304 // L < g_gmock_mutex
305 static internal::CallReaction GetReactionOnUninterestingCalls(
306 const void* mock_obj);
307
308 // Verifies that all expectations on the given mock object have been
309 // satisfied. Reports one or more Google Test non-fatal failures
310 // and returns false if not.
311 // L >= g_gmock_mutex
312 static bool VerifyAndClearExpectationsLocked(void* mock_obj);
313
314 // Clears all ON_CALL()s set on the given mock object.
315 // L >= g_gmock_mutex
316 static void ClearDefaultActionsLocked(void* mock_obj);
317
318 // Registers a mock object and a mock method it owns.
319 // L < g_gmock_mutex
320 static void Register(const void* mock_obj,
321 internal::UntypedFunctionMockerBase* mocker);
322
zhanyong.wandf35a762009-04-22 22:25:31 +0000323 // Tells Google Mock where in the source code mock_obj is used in an
324 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
325 // information helps the user identify which object it is.
326 // L < g_gmock_mutex
327 static void RegisterUseByOnCallOrExpectCall(
328 const void* mock_obj, const char* file, int line);
329
shiqiane35fdd92008-12-10 05:08:54 +0000330 // Unregisters a mock method; removes the owning mock object from
331 // the registry when the last mock method associated with it has
332 // been unregistered. This is called only in the destructor of
333 // FunctionMockerBase.
334 // L >= g_gmock_mutex
335 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
336}; // class Mock
337
338// Sequence objects are used by a user to specify the relative order
339// in which the expectations should match. They are copyable (we rely
340// on the compiler-defined copy constructor and assignment operator).
341class Sequence {
342 public:
343 // Constructs an empty sequence.
344 Sequence()
345 : last_expectation_(
346 new internal::linked_ptr<internal::ExpectationBase>(NULL)) {}
347
348 // Adds an expectation to this sequence. The caller must ensure
349 // that no other thread is accessing this Sequence object.
350 void AddExpectation(
351 const internal::linked_ptr<internal::ExpectationBase>& expectation) const;
352 private:
353 // The last expectation in this sequence. We use a nested
354 // linked_ptr here because:
355 // - Sequence objects are copyable, and we want the copies to act
356 // as aliases. The outer linked_ptr allows the copies to co-own
357 // and share the same state.
358 // - An Expectation object is co-owned (via linked_ptr) by its
359 // FunctionMocker and its successors (other Expectation objects).
360 // Hence the inner linked_ptr.
361 internal::linked_ptr<internal::linked_ptr<internal::ExpectationBase> >
362 last_expectation_;
363}; // class Sequence
364
365// An object of this type causes all EXPECT_CALL() statements
366// encountered in its scope to be put in an anonymous sequence. The
367// work is done in the constructor and destructor. You should only
368// create an InSequence object on the stack.
369//
370// The sole purpose for this class is to support easy definition of
371// sequential expectations, e.g.
372//
373// {
374// InSequence dummy; // The name of the object doesn't matter.
375//
376// // The following expectations must match in the order they appear.
377// EXPECT_CALL(a, Bar())...;
378// EXPECT_CALL(a, Baz())...;
379// ...
380// EXPECT_CALL(b, Xyz())...;
381// }
382//
383// You can create InSequence objects in multiple threads, as long as
384// they are used to affect different mock objects. The idea is that
385// each thread can create and set up its own mocks as if it's the only
386// thread. However, for clarity of your tests we recommend you to set
387// up mocks in the main thread unless you have a good reason not to do
388// so.
389class InSequence {
390 public:
391 InSequence();
392 ~InSequence();
393 private:
394 bool sequence_created_;
395
396 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wane0d051e2009-02-19 00:33:37 +0000397} GMOCK_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000398
399namespace internal {
400
401// Points to the implicit sequence introduced by a living InSequence
402// object (if any) in the current thread or NULL.
403extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
404
405// Base class for implementing expectations.
406//
407// There are two reasons for having a type-agnostic base class for
408// Expectation:
409//
410// 1. We need to store collections of expectations of different
411// types (e.g. all pre-requisites of a particular expectation, all
412// expectations in a sequence). Therefore these expectation objects
413// must share a common base class.
414//
415// 2. We can avoid binary code bloat by moving methods not depending
416// on the template argument of Expectation to the base class.
417//
418// This class is internal and mustn't be used by user code directly.
419class ExpectationBase {
420 public:
421 ExpectationBase(const char* file, int line);
422
423 virtual ~ExpectationBase();
424
425 // Where in the source file was the expectation spec defined?
426 const char* file() const { return file_; }
427 int line() const { return line_; }
428
429 // Returns the cardinality specified in the expectation spec.
430 const Cardinality& cardinality() const { return cardinality_; }
431
432 // Describes the source file location of this expectation.
433 void DescribeLocationTo(::std::ostream* os) const {
434 *os << file() << ":" << line() << ": ";
435 }
436
437 // Describes how many times a function call matching this
438 // expectation has occurred.
439 // L >= g_gmock_mutex
440 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
441 protected:
442 typedef std::set<linked_ptr<ExpectationBase>,
443 LinkedPtrLessThan<ExpectationBase> >
444 ExpectationBaseSet;
445
446 enum Clause {
447 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000448 kNone,
449 kWith,
450 kTimes,
451 kInSequence,
452 kWillOnce,
453 kWillRepeatedly,
454 kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000455 };
456
457 // Asserts that the EXPECT_CALL() statement has the given property.
458 void AssertSpecProperty(bool property, const string& failure_message) const {
459 Assert(property, file_, line_, failure_message);
460 }
461
462 // Expects that the EXPECT_CALL() statement has the given property.
463 void ExpectSpecProperty(bool property, const string& failure_message) const {
464 Expect(property, file_, line_, failure_message);
465 }
466
467 // Explicitly specifies the cardinality of this expectation. Used
468 // by the subclasses to implement the .Times() clause.
469 void SpecifyCardinality(const Cardinality& cardinality);
470
471 // Returns true iff the user specified the cardinality explicitly
472 // using a .Times().
473 bool cardinality_specified() const { return cardinality_specified_; }
474
475 // Sets the cardinality of this expectation spec.
476 void set_cardinality(const Cardinality& cardinality) {
477 cardinality_ = cardinality;
478 }
479
480 // The following group of methods should only be called after the
481 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
482 // the current thread.
483
484 // Retires all pre-requisites of this expectation.
485 // L >= g_gmock_mutex
486 void RetireAllPreRequisites();
487
488 // Returns true iff this expectation is retired.
489 // L >= g_gmock_mutex
490 bool is_retired() const {
491 g_gmock_mutex.AssertHeld();
492 return retired_;
493 }
494
495 // Retires this expectation.
496 // L >= g_gmock_mutex
497 void Retire() {
498 g_gmock_mutex.AssertHeld();
499 retired_ = true;
500 }
501
502 // Returns true iff this expectation is satisfied.
503 // L >= g_gmock_mutex
504 bool IsSatisfied() const {
505 g_gmock_mutex.AssertHeld();
506 return cardinality().IsSatisfiedByCallCount(call_count_);
507 }
508
509 // Returns true iff this expectation is saturated.
510 // L >= g_gmock_mutex
511 bool IsSaturated() const {
512 g_gmock_mutex.AssertHeld();
513 return cardinality().IsSaturatedByCallCount(call_count_);
514 }
515
516 // Returns true iff this expectation is over-saturated.
517 // L >= g_gmock_mutex
518 bool IsOverSaturated() const {
519 g_gmock_mutex.AssertHeld();
520 return cardinality().IsOverSaturatedByCallCount(call_count_);
521 }
522
523 // Returns true iff all pre-requisites of this expectation are satisfied.
524 // L >= g_gmock_mutex
525 bool AllPrerequisitesAreSatisfied() const;
526
527 // Adds unsatisfied pre-requisites of this expectation to 'result'.
528 // L >= g_gmock_mutex
529 void FindUnsatisfiedPrerequisites(ExpectationBaseSet* result) const;
530
531 // Returns the number this expectation has been invoked.
532 // L >= g_gmock_mutex
533 int call_count() const {
534 g_gmock_mutex.AssertHeld();
535 return call_count_;
536 }
537
538 // Increments the number this expectation has been invoked.
539 // L >= g_gmock_mutex
540 void IncrementCallCount() {
541 g_gmock_mutex.AssertHeld();
542 call_count_++;
543 }
544
545 private:
546 friend class ::testing::Sequence;
547 friend class ::testing::internal::ExpectationTester;
548
549 template <typename Function>
550 friend class Expectation;
551
552 // This group of fields are part of the spec and won't change after
553 // an EXPECT_CALL() statement finishes.
554 const char* file_; // The file that contains the expectation.
555 int line_; // The line number of the expectation.
556 // True iff the cardinality is specified explicitly.
557 bool cardinality_specified_;
558 Cardinality cardinality_; // The cardinality of the expectation.
559 // The immediate pre-requisites of this expectation. We use
560 // linked_ptr in the set because we want an Expectation object to be
561 // co-owned by its FunctionMocker and its successors. This allows
562 // multiple mock objects to be deleted at different times.
563 ExpectationBaseSet immediate_prerequisites_;
564
565 // This group of fields are the current state of the expectation,
566 // and can change as the mock function is called.
567 int call_count_; // How many times this expectation has been invoked.
568 bool retired_; // True iff this expectation has retired.
569}; // class ExpectationBase
570
571// Impements an expectation for the given function type.
572template <typename F>
573class Expectation : public ExpectationBase {
574 public:
575 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
576 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
577 typedef typename Function<F>::Result Result;
578
579 Expectation(FunctionMockerBase<F>* owner, const char* file, int line,
580 const ArgumentMatcherTuple& m)
581 : ExpectationBase(file, line),
582 owner_(owner),
583 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000584 // By default, extra_matcher_ should match anything. However,
585 // we cannot initialize it with _ as that triggers a compiler
586 // bug in Symbian's C++ compiler (cannot decide between two
587 // overloaded constructors of Matcher<const ArgumentTuple&>).
588 extra_matcher_(A<const ArgumentTuple&>()),
shiqiane35fdd92008-12-10 05:08:54 +0000589 repeated_action_specified_(false),
590 repeated_action_(DoDefault()),
591 retires_on_saturation_(false),
zhanyong.wanbf550852009-06-09 06:09:53 +0000592 last_clause_(kNone),
shiqiane35fdd92008-12-10 05:08:54 +0000593 action_count_checked_(false) {}
594
595 virtual ~Expectation() {
596 // Check the validity of the action count if it hasn't been done
597 // yet (for example, if the expectation was never used).
598 CheckActionCountIfNotDone();
599 }
600
zhanyong.wanbf550852009-06-09 06:09:53 +0000601 // Implements the .With() clause.
602 Expectation& With(const Matcher<const ArgumentTuple&>& m) {
603 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000604 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000605 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000606 "more than once in an EXPECT_CALL().");
607 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000608 ExpectSpecProperty(last_clause_ < kWith,
609 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000610 "clause in an EXPECT_CALL().");
611 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000612 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000613
614 extra_matcher_ = m;
615 return *this;
616 }
617
zhanyong.wanbf550852009-06-09 06:09:53 +0000618 // Implements the .WithArguments() clause as a synonym of .With().
619 // This is deprecated and new code should always use With().
620 Expectation& WithArguments(const Matcher<const ArgumentTuple&>& m) {
621 return With(m);
622 }
623
shiqiane35fdd92008-12-10 05:08:54 +0000624 // Implements the .Times() clause.
625 Expectation& Times(const Cardinality& cardinality) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000626 if (last_clause_ ==kTimes) {
shiqiane35fdd92008-12-10 05:08:54 +0000627 ExpectSpecProperty(false,
628 ".Times() cannot appear "
629 "more than once in an EXPECT_CALL().");
630 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000631 ExpectSpecProperty(last_clause_ < kTimes,
shiqiane35fdd92008-12-10 05:08:54 +0000632 ".Times() cannot appear after "
633 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
634 "or .RetiresOnSaturation().");
635 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000636 last_clause_ = kTimes;
shiqiane35fdd92008-12-10 05:08:54 +0000637
638 ExpectationBase::SpecifyCardinality(cardinality);
639 return *this;
640 }
641
642 // Implements the .Times() clause.
643 Expectation& Times(int n) {
644 return Times(Exactly(n));
645 }
646
647 // Implements the .InSequence() clause.
648 Expectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000649 ExpectSpecProperty(last_clause_ <= kInSequence,
shiqiane35fdd92008-12-10 05:08:54 +0000650 ".InSequence() cannot appear after .WillOnce(),"
651 " .WillRepeatedly(), or "
652 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000653 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000654
655 s.AddExpectation(owner_->GetLinkedExpectationBase(this));
656 return *this;
657 }
658 Expectation& InSequence(const Sequence& s1, const Sequence& s2) {
659 return InSequence(s1).InSequence(s2);
660 }
661 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
662 const Sequence& s3) {
663 return InSequence(s1, s2).InSequence(s3);
664 }
665 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
666 const Sequence& s3, const Sequence& s4) {
667 return InSequence(s1, s2, s3).InSequence(s4);
668 }
669 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
670 const Sequence& s3, const Sequence& s4,
671 const Sequence& s5) {
672 return InSequence(s1, s2, s3, s4).InSequence(s5);
673 }
674
675 // Implements the .WillOnce() clause.
676 Expectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000677 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000678 ".WillOnce() cannot appear after "
679 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000680 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +0000681
682 actions_.push_back(action);
683 if (!cardinality_specified()) {
684 set_cardinality(Exactly(static_cast<int>(actions_.size())));
685 }
686 return *this;
687 }
688
689 // Implements the .WillRepeatedly() clause.
690 Expectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000691 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +0000692 ExpectSpecProperty(false,
693 ".WillRepeatedly() cannot appear "
694 "more than once in an EXPECT_CALL().");
695 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000696 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +0000697 ".WillRepeatedly() cannot appear "
698 "after .RetiresOnSaturation().");
699 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000700 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +0000701 repeated_action_specified_ = true;
702
703 repeated_action_ = action;
704 if (!cardinality_specified()) {
705 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
706 }
707
708 // Now that no more action clauses can be specified, we check
709 // whether their count makes sense.
710 CheckActionCountIfNotDone();
711 return *this;
712 }
713
714 // Implements the .RetiresOnSaturation() clause.
715 Expectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +0000716 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +0000717 ".RetiresOnSaturation() cannot appear "
718 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +0000719 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +0000720 retires_on_saturation_ = true;
721
722 // Now that no more action clauses can be specified, we check
723 // whether their count makes sense.
724 CheckActionCountIfNotDone();
725 return *this;
726 }
727
728 // Returns the matchers for the arguments as specified inside the
729 // EXPECT_CALL() macro.
730 const ArgumentMatcherTuple& matchers() const {
731 return matchers_;
732 }
733
zhanyong.wanbf550852009-06-09 06:09:53 +0000734 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +0000735 const Matcher<const ArgumentTuple&>& extra_matcher() const {
736 return extra_matcher_;
737 }
738
739 // Returns the sequence of actions specified by the .WillOnce() clause.
740 const std::vector<Action<F> >& actions() const { return actions_; }
741
742 // Returns the action specified by the .WillRepeatedly() clause.
743 const Action<F>& repeated_action() const { return repeated_action_; }
744
745 // Returns true iff the .RetiresOnSaturation() clause was specified.
746 bool retires_on_saturation() const { return retires_on_saturation_; }
747
748 // Describes how many times a function call matching this
749 // expectation has occurred (implements
750 // ExpectationBase::DescribeCallCountTo()).
751 // L >= g_gmock_mutex
752 virtual void DescribeCallCountTo(::std::ostream* os) const {
753 g_gmock_mutex.AssertHeld();
754
755 // Describes how many times the function is expected to be called.
756 *os << " Expected: to be ";
757 cardinality().DescribeTo(os);
758 *os << "\n Actual: ";
759 Cardinality::DescribeActualCallCountTo(call_count(), os);
760
761 // Describes the state of the expectation (e.g. is it satisfied?
762 // is it active?).
763 *os << " - " << (IsOverSaturated() ? "over-saturated" :
764 IsSaturated() ? "saturated" :
765 IsSatisfied() ? "satisfied" : "unsatisfied")
766 << " and "
767 << (is_retired() ? "retired" : "active");
768 }
769 private:
770 template <typename Function>
771 friend class FunctionMockerBase;
772
shiqiane35fdd92008-12-10 05:08:54 +0000773 // The following methods will be called only after the EXPECT_CALL()
774 // statement finishes and when the current thread holds
775 // g_gmock_mutex.
776
777 // Returns true iff this expectation matches the given arguments.
778 // L >= g_gmock_mutex
779 bool Matches(const ArgumentTuple& args) const {
780 g_gmock_mutex.AssertHeld();
781 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
782 }
783
784 // Returns true iff this expectation should handle the given arguments.
785 // L >= g_gmock_mutex
786 bool ShouldHandleArguments(const ArgumentTuple& args) const {
787 g_gmock_mutex.AssertHeld();
788
789 // In case the action count wasn't checked when the expectation
790 // was defined (e.g. if this expectation has no WillRepeatedly()
791 // or RetiresOnSaturation() clause), we check it when the
792 // expectation is used for the first time.
793 CheckActionCountIfNotDone();
794 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
795 }
796
797 // Describes the result of matching the arguments against this
798 // expectation to the given ostream.
799 // L >= g_gmock_mutex
800 void DescribeMatchResultTo(const ArgumentTuple& args,
801 ::std::ostream* os) const {
802 g_gmock_mutex.AssertHeld();
803
804 if (is_retired()) {
805 *os << " Expected: the expectation is active\n"
806 << " Actual: it is retired\n";
807 } else if (!Matches(args)) {
808 if (!TupleMatches(matchers_, args)) {
809 DescribeMatchFailureTupleTo(matchers_, args, os);
810 }
811 if (!extra_matcher_.Matches(args)) {
zhanyong.wan2661c682009-06-09 05:42:12 +0000812 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +0000813 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +0000814 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +0000815
816 internal::ExplainMatchResultAsNeededTo<const ArgumentTuple&>(
817 extra_matcher_, args, os);
818 *os << "\n";
819 }
820 } else if (!AllPrerequisitesAreSatisfied()) {
821 *os << " Expected: all pre-requisites are satisfied\n"
822 << " Actual: the following immediate pre-requisites "
823 << "are not satisfied:\n";
824 ExpectationBaseSet unsatisfied_prereqs;
825 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
826 int i = 0;
827 for (ExpectationBaseSet::const_iterator it = unsatisfied_prereqs.begin();
828 it != unsatisfied_prereqs.end(); ++it) {
829 (*it)->DescribeLocationTo(os);
830 *os << "pre-requisite #" << i++ << "\n";
831 }
832 *os << " (end of pre-requisites)\n";
833 } else {
834 // This line is here just for completeness' sake. It will never
835 // be executed as currently the DescribeMatchResultTo() function
836 // is called only when the mock function call does NOT match the
837 // expectation.
838 *os << "The call matches the expectation.\n";
839 }
840 }
841
842 // Returns the action that should be taken for the current invocation.
843 // L >= g_gmock_mutex
844 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
845 const ArgumentTuple& args) const {
846 g_gmock_mutex.AssertHeld();
847 const int count = call_count();
848 Assert(count >= 1, __FILE__, __LINE__,
849 "call_count() is <= 0 when GetCurrentAction() is "
850 "called - this should never happen.");
851
852 const int action_count = static_cast<int>(actions().size());
853 if (action_count > 0 && !repeated_action_specified_ &&
854 count > action_count) {
855 // If there is at least one WillOnce() and no WillRepeatedly(),
856 // we warn the user when the WillOnce() clauses ran out.
857 ::std::stringstream ss;
858 DescribeLocationTo(&ss);
859 ss << "Actions ran out.\n"
860 << "Called " << count << " times, but only "
861 << action_count << " WillOnce()"
862 << (action_count == 1 ? " is" : "s are") << " specified - ";
863 mocker->DescribeDefaultActionTo(args, &ss);
864 Log(WARNING, ss.str(), 1);
865 }
866
867 return count <= action_count ? actions()[count - 1] : repeated_action();
868 }
869
870 // Given the arguments of a mock function call, if the call will
871 // over-saturate this expectation, returns the default action;
872 // otherwise, returns the next action in this expectation. Also
873 // describes *what* happened to 'what', and explains *why* Google
874 // Mock does it to 'why'. This method is not const as it calls
875 // IncrementCallCount().
876 // L >= g_gmock_mutex
877 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
878 const ArgumentTuple& args,
879 ::std::ostream* what,
880 ::std::ostream* why) {
881 g_gmock_mutex.AssertHeld();
882 if (IsSaturated()) {
883 // We have an excessive call.
884 IncrementCallCount();
885 *what << "Mock function called more times than expected - ";
886 mocker->DescribeDefaultActionTo(args, what);
887 DescribeCallCountTo(why);
888
889 // TODO(wan): allow the user to control whether unexpected calls
890 // should fail immediately or continue using a flag
891 // --gmock_unexpected_calls_are_fatal.
892 return DoDefault();
893 }
894
895 IncrementCallCount();
896 RetireAllPreRequisites();
897
898 if (retires_on_saturation() && IsSaturated()) {
899 Retire();
900 }
901
902 // Must be done after IncrementCount()!
903 *what << "Expected mock function call.\n";
904 return GetCurrentAction(mocker, args);
905 }
906
907 // Checks the action count (i.e. the number of WillOnce() and
908 // WillRepeatedly() clauses) against the cardinality if this hasn't
909 // been done before. Prints a warning if there are too many or too
910 // few actions.
911 // L < mutex_
912 void CheckActionCountIfNotDone() const {
913 bool should_check = false;
914 {
915 MutexLock l(&mutex_);
916 if (!action_count_checked_) {
917 action_count_checked_ = true;
918 should_check = true;
919 }
920 }
921
922 if (should_check) {
923 if (!cardinality_specified_) {
924 // The cardinality was inferred - no need to check the action
925 // count against it.
926 return;
927 }
928
929 // The cardinality was explicitly specified.
930 const int action_count = static_cast<int>(actions_.size());
931 const int upper_bound = cardinality().ConservativeUpperBound();
932 const int lower_bound = cardinality().ConservativeLowerBound();
933 bool too_many; // True if there are too many actions, or false
934 // if there are too few.
935 if (action_count > upper_bound ||
936 (action_count == upper_bound && repeated_action_specified_)) {
937 too_many = true;
938 } else if (0 < action_count && action_count < lower_bound &&
939 !repeated_action_specified_) {
940 too_many = false;
941 } else {
942 return;
943 }
944
945 ::std::stringstream ss;
946 DescribeLocationTo(&ss);
947 ss << "Too " << (too_many ? "many" : "few")
948 << " actions specified.\n"
949 << "Expected to be ";
950 cardinality().DescribeTo(&ss);
951 ss << ", but has " << (too_many ? "" : "only ")
952 << action_count << " WillOnce()"
953 << (action_count == 1 ? "" : "s");
954 if (repeated_action_specified_) {
955 ss << " and a WillRepeatedly()";
956 }
957 ss << ".";
958 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
959 }
960 }
961
962 // All the fields below won't change once the EXPECT_CALL()
963 // statement finishes.
964 FunctionMockerBase<F>* const owner_;
965 ArgumentMatcherTuple matchers_;
966 Matcher<const ArgumentTuple&> extra_matcher_;
967 std::vector<Action<F> > actions_;
968 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
969 Action<F> repeated_action_;
970 bool retires_on_saturation_;
971 Clause last_clause_;
972 mutable bool action_count_checked_; // Under mutex_.
973 mutable Mutex mutex_; // Protects action_count_checked_.
974}; // class Expectation
975
976// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
977// specifying the default behavior of, or expectation on, a mock
978// function.
979
980// Note: class MockSpec really belongs to the ::testing namespace.
981// However if we define it in ::testing, MSVC will complain when
982// classes in ::testing::internal declare it as a friend class
983// template. To workaround this compiler bug, we define MockSpec in
984// ::testing::internal and import it into ::testing.
985
986template <typename F>
987class MockSpec {
988 public:
989 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
990 typedef typename internal::Function<F>::ArgumentMatcherTuple
991 ArgumentMatcherTuple;
992
993 // Constructs a MockSpec object, given the function mocker object
994 // that the spec is associated with.
995 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
996 : function_mocker_(function_mocker) {}
997
998 // Adds a new default action spec to the function mocker and returns
999 // the newly created spec.
1000 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
1001 const char* file, int line, const char* obj, const char* call) {
1002 LogWithLocation(internal::INFO, file, line,
1003 string("ON_CALL(") + obj + ", " + call + ") invoked");
1004 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
1005 }
1006
1007 // Adds a new expectation spec to the function mocker and returns
1008 // the newly created spec.
1009 internal::Expectation<F>& InternalExpectedAt(
1010 const char* file, int line, const char* obj, const char* call) {
1011 LogWithLocation(internal::INFO, file, line,
1012 string("EXPECT_CALL(") + obj + ", " + call + ") invoked");
1013 return function_mocker_->AddNewExpectation(file, line, matchers_);
1014 }
1015
1016 private:
1017 template <typename Function>
1018 friend class internal::FunctionMocker;
1019
1020 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1021 matchers_ = matchers;
1022 }
1023
1024 // Logs a message including file and line number information.
1025 void LogWithLocation(testing::internal::LogSeverity severity,
1026 const char* file, int line,
1027 const string& message) {
1028 ::std::ostringstream s;
1029 s << file << ":" << line << ": " << message << ::std::endl;
1030 Log(severity, s.str(), 0);
1031 }
1032
1033 // The function mocker that owns this spec.
1034 internal::FunctionMockerBase<F>* const function_mocker_;
1035 // The argument matchers specified in the spec.
1036 ArgumentMatcherTuple matchers_;
1037}; // class MockSpec
1038
1039// MSVC warns about using 'this' in base member initializer list, so
1040// we need to temporarily disable the warning. We have to do it for
1041// the entire class to suppress the warning, even though it's about
1042// the constructor only.
1043
1044#ifdef _MSC_VER
1045#pragma warning(push) // Saves the current warning state.
1046#pragma warning(disable:4355) // Temporarily disables warning 4355.
1047#endif // _MSV_VER
1048
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001049// C++ treats the void type specially. For example, you cannot define
1050// a void-typed variable or pass a void value to a function.
1051// ActionResultHolder<T> holds a value of type T, where T must be a
1052// copyable type or void (T doesn't need to be default-constructable).
1053// It hides the syntactic difference between void and other types, and
1054// is used to unify the code for invoking both void-returning and
1055// non-void-returning mock functions. This generic definition is used
1056// when T is not void.
1057template <typename T>
1058class ActionResultHolder {
1059 public:
1060 explicit ActionResultHolder(T value) : value_(value) {}
1061
1062 // The compiler-generated copy constructor and assignment operator
1063 // are exactly what we need, so we don't need to define them.
1064
1065 T value() const { return value_; }
1066
1067 // Prints the held value as an action's result to os.
1068 void PrintAsActionResult(::std::ostream* os) const {
1069 *os << "\n Returns: ";
1070 UniversalPrinter<T>::Print(value_, os);
1071 }
1072
1073 // Performs the given mock function's default action and returns the
1074 // result in a ActionResultHolder.
1075 template <typename Function, typename Arguments>
1076 static ActionResultHolder PerformDefaultAction(
1077 const FunctionMockerBase<Function>* func_mocker,
1078 const Arguments& args,
1079 const string& call_description) {
1080 return ActionResultHolder(
1081 func_mocker->PerformDefaultAction(args, call_description));
1082 }
1083
1084 // Performs the given action and returns the result in a
1085 // ActionResultHolder.
1086 template <typename Function, typename Arguments>
1087 static ActionResultHolder PerformAction(const Action<Function>& action,
1088 const Arguments& args) {
1089 return ActionResultHolder(action.Perform(args));
1090 }
1091
1092 private:
1093 T value_;
1094};
1095
1096// Specialization for T = void.
1097template <>
1098class ActionResultHolder<void> {
1099 public:
1100 ActionResultHolder() {}
1101 void value() const {}
1102 void PrintAsActionResult(::std::ostream* /* os */) const {}
1103
1104 template <typename Function, typename Arguments>
1105 static ActionResultHolder PerformDefaultAction(
1106 const FunctionMockerBase<Function>* func_mocker,
1107 const Arguments& args,
1108 const string& call_description) {
1109 func_mocker->PerformDefaultAction(args, call_description);
1110 return ActionResultHolder();
1111 }
1112
1113 template <typename Function, typename Arguments>
1114 static ActionResultHolder PerformAction(const Action<Function>& action,
1115 const Arguments& args) {
1116 action.Perform(args);
1117 return ActionResultHolder();
1118 }
1119};
1120
shiqiane35fdd92008-12-10 05:08:54 +00001121// The base of the function mocker class for the given function type.
1122// We put the methods in this class instead of its child to avoid code
1123// bloat.
1124template <typename F>
1125class FunctionMockerBase : public UntypedFunctionMockerBase {
1126 public:
1127 typedef typename Function<F>::Result Result;
1128 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1129 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1130
1131 FunctionMockerBase() : mock_obj_(NULL), name_(""), current_spec_(this) {}
1132
1133 // The destructor verifies that all expectations on this mock
1134 // function have been satisfied. If not, it will report Google Test
1135 // non-fatal failures for the violations.
1136 // L < g_gmock_mutex
1137 virtual ~FunctionMockerBase() {
1138 MutexLock l(&g_gmock_mutex);
1139 VerifyAndClearExpectationsLocked();
1140 Mock::UnregisterLocked(this);
1141 }
1142
1143 // Returns the ON_CALL spec that matches this mock function with the
1144 // given arguments; returns NULL if no matching ON_CALL is found.
1145 // L = *
1146 const DefaultActionSpec<F>* FindDefaultActionSpec(
1147 const ArgumentTuple& args) const {
1148 for (typename std::vector<DefaultActionSpec<F> >::const_reverse_iterator it
1149 = default_actions_.rbegin();
1150 it != default_actions_.rend(); ++it) {
1151 const DefaultActionSpec<F>& spec = *it;
1152 if (spec.Matches(args))
1153 return &spec;
1154 }
1155
1156 return NULL;
1157 }
1158
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001159 // Performs the default action of this mock function on the given arguments
1160 // and returns the result. Asserts with a helpful call descrption if there is
1161 // no valid return value. This method doesn't depend on the mutable state of
1162 // this object, and thus can be called concurrently without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001163 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001164 Result PerformDefaultAction(const ArgumentTuple& args,
1165 const string& call_description) const {
shiqiane35fdd92008-12-10 05:08:54 +00001166 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001167 if (spec != NULL) {
1168 return spec->GetAction().Perform(args);
1169 }
1170 Assert(DefaultValue<Result>::Exists(), "", -1,
1171 call_description + "\n The mock function has no default action "
1172 "set, and its return type has no default value set.");
1173 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001174 }
1175
1176 // Registers this function mocker and the mock object owning it;
1177 // returns a reference to the function mocker object. This is only
1178 // called by the ON_CALL() and EXPECT_CALL() macros.
zhanyong.wandf35a762009-04-22 22:25:31 +00001179 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001180 FunctionMocker<F>& RegisterOwner(const void* mock_obj) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001181 {
1182 MutexLock l(&g_gmock_mutex);
1183 mock_obj_ = mock_obj;
1184 }
shiqiane35fdd92008-12-10 05:08:54 +00001185 Mock::Register(mock_obj, this);
zhanyong.wan946bc642009-03-31 00:05:30 +00001186 return *::testing::internal::down_cast<FunctionMocker<F>*>(this);
shiqiane35fdd92008-12-10 05:08:54 +00001187 }
1188
1189 // The following two functions are from UntypedFunctionMockerBase.
1190
1191 // Verifies that all expectations on this mock function have been
1192 // satisfied. Reports one or more Google Test non-fatal failures
1193 // and returns false if not.
1194 // L >= g_gmock_mutex
1195 virtual bool VerifyAndClearExpectationsLocked();
1196
1197 // Clears the ON_CALL()s set on this mock function.
1198 // L >= g_gmock_mutex
1199 virtual void ClearDefaultActionsLocked() {
1200 g_gmock_mutex.AssertHeld();
1201 default_actions_.clear();
1202 }
1203
1204 // Sets the name of the function being mocked. Will be called upon
1205 // each invocation of this mock function.
1206 // L < g_gmock_mutex
1207 void SetOwnerAndName(const void* mock_obj, const char* name) {
1208 // We protect name_ under g_gmock_mutex in case this mock function
1209 // is called from two threads concurrently.
1210 MutexLock l(&g_gmock_mutex);
1211 mock_obj_ = mock_obj;
1212 name_ = name;
1213 }
1214
1215 // Returns the address of the mock object this method belongs to.
1216 // Must be called after SetOwnerAndName() has been called.
1217 // L < g_gmock_mutex
1218 const void* MockObject() const {
1219 const void* mock_obj;
1220 {
1221 // We protect mock_obj_ under g_gmock_mutex in case this mock
1222 // function is called from two threads concurrently.
1223 MutexLock l(&g_gmock_mutex);
1224 mock_obj = mock_obj_;
1225 }
1226 return mock_obj;
1227 }
1228
1229 // Returns the name of the function being mocked. Must be called
1230 // after SetOwnerAndName() has been called.
1231 // L < g_gmock_mutex
1232 const char* Name() const {
1233 const char* name;
1234 {
1235 // We protect name_ under g_gmock_mutex in case this mock
1236 // function is called from two threads concurrently.
1237 MutexLock l(&g_gmock_mutex);
1238 name = name_;
1239 }
1240 return name;
1241 }
1242 protected:
1243 template <typename Function>
1244 friend class MockSpec;
1245
shiqiane35fdd92008-12-10 05:08:54 +00001246 // Returns the result of invoking this mock function with the given
1247 // arguments. This function can be safely called from multiple
1248 // threads concurrently.
1249 // L < g_gmock_mutex
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001250 Result InvokeWith(const ArgumentTuple& args);
shiqiane35fdd92008-12-10 05:08:54 +00001251
1252 // Adds and returns a default action spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001253 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001254 DefaultActionSpec<F>& AddNewDefaultActionSpec(
1255 const char* file, int line,
1256 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001257 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
shiqiane35fdd92008-12-10 05:08:54 +00001258 default_actions_.push_back(DefaultActionSpec<F>(file, line, m));
1259 return default_actions_.back();
1260 }
1261
1262 // Adds and returns an expectation spec for this mock function.
zhanyong.wandf35a762009-04-22 22:25:31 +00001263 // L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001264 Expectation<F>& AddNewExpectation(
1265 const char* file, int line,
1266 const ArgumentMatcherTuple& m) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001267 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
shiqiane35fdd92008-12-10 05:08:54 +00001268 const linked_ptr<Expectation<F> > expectation(
1269 new Expectation<F>(this, file, line, m));
1270 expectations_.push_back(expectation);
1271
1272 // Adds this expectation into the implicit sequence if there is one.
1273 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1274 if (implicit_sequence != NULL) {
1275 implicit_sequence->AddExpectation(expectation);
1276 }
1277
1278 return *expectation;
1279 }
1280
1281 // The current spec (either default action spec or expectation spec)
1282 // being described on this function mocker.
1283 MockSpec<F>& current_spec() { return current_spec_; }
1284 private:
1285 template <typename Func> friend class Expectation;
1286
1287 typedef std::vector<internal::linked_ptr<Expectation<F> > > Expectations;
1288
1289 // Gets the internal::linked_ptr<ExpectationBase> object that co-owns 'exp'.
1290 internal::linked_ptr<ExpectationBase> GetLinkedExpectationBase(
1291 Expectation<F>* exp) {
1292 for (typename Expectations::const_iterator it = expectations_.begin();
1293 it != expectations_.end(); ++it) {
1294 if (it->get() == exp) {
1295 return *it;
1296 }
1297 }
1298
1299 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
1300 return internal::linked_ptr<ExpectationBase>(NULL);
1301 // The above statement is just to make the code compile, and will
1302 // never be executed.
1303 }
1304
1305 // Some utilities needed for implementing InvokeWith().
1306
1307 // Describes what default action will be performed for the given
1308 // arguments.
1309 // L = *
1310 void DescribeDefaultActionTo(const ArgumentTuple& args,
1311 ::std::ostream* os) const {
1312 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1313
1314 if (spec == NULL) {
1315 *os << (internal::type_equals<Result, void>::value ?
1316 "returning directly.\n" :
1317 "returning default value.\n");
1318 } else {
1319 *os << "taking default action specified at:\n"
1320 << spec->file() << ":" << spec->line() << ":\n";
1321 }
1322 }
1323
1324 // Writes a message that the call is uninteresting (i.e. neither
1325 // explicitly expected nor explicitly unexpected) to the given
1326 // ostream.
1327 // L < g_gmock_mutex
1328 void DescribeUninterestingCall(const ArgumentTuple& args,
1329 ::std::ostream* os) const {
1330 *os << "Uninteresting mock function call - ";
1331 DescribeDefaultActionTo(args, os);
1332 *os << " Function call: " << Name();
1333 UniversalPrinter<ArgumentTuple>::Print(args, os);
1334 }
1335
1336 // Critical section: We must find the matching expectation and the
1337 // corresponding action that needs to be taken in an ATOMIC
1338 // transaction. Otherwise another thread may call this mock
1339 // method in the middle and mess up the state.
1340 //
1341 // However, performing the action has to be left out of the critical
1342 // section. The reason is that we have no control on what the
1343 // action does (it can invoke an arbitrary user function or even a
1344 // mock function) and excessive locking could cause a dead lock.
1345 // L < g_gmock_mutex
1346 bool FindMatchingExpectationAndAction(
1347 const ArgumentTuple& args, Expectation<F>** exp, Action<F>* action,
1348 bool* is_excessive, ::std::ostream* what, ::std::ostream* why) {
1349 MutexLock l(&g_gmock_mutex);
1350 *exp = this->FindMatchingExpectationLocked(args);
1351 if (*exp == NULL) { // A match wasn't found.
1352 *action = DoDefault();
1353 this->FormatUnexpectedCallMessageLocked(args, what, why);
1354 return false;
1355 }
1356
1357 // This line must be done before calling GetActionForArguments(),
1358 // which will increment the call count for *exp and thus affect
1359 // its saturation status.
1360 *is_excessive = (*exp)->IsSaturated();
1361 *action = (*exp)->GetActionForArguments(this, args, what, why);
1362 return true;
1363 }
1364
1365 // Returns the expectation that matches the arguments, or NULL if no
1366 // expectation matches them.
1367 // L >= g_gmock_mutex
1368 Expectation<F>* FindMatchingExpectationLocked(
1369 const ArgumentTuple& args) const {
1370 g_gmock_mutex.AssertHeld();
1371 for (typename Expectations::const_reverse_iterator it =
1372 expectations_.rbegin();
1373 it != expectations_.rend(); ++it) {
1374 Expectation<F>* const exp = it->get();
1375 if (exp->ShouldHandleArguments(args)) {
1376 return exp;
1377 }
1378 }
1379 return NULL;
1380 }
1381
1382 // Returns a message that the arguments don't match any expectation.
1383 // L >= g_gmock_mutex
1384 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1385 ::std::ostream* os,
1386 ::std::ostream* why) const {
1387 g_gmock_mutex.AssertHeld();
1388 *os << "\nUnexpected mock function call - ";
1389 DescribeDefaultActionTo(args, os);
1390 PrintTriedExpectationsLocked(args, why);
1391 }
1392
1393 // Prints a list of expectations that have been tried against the
1394 // current mock function call.
1395 // L >= g_gmock_mutex
1396 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1397 ::std::ostream* why) const {
1398 g_gmock_mutex.AssertHeld();
1399 const int count = static_cast<int>(expectations_.size());
1400 *why << "Google Mock tried the following " << count << " "
1401 << (count == 1 ? "expectation, but it didn't match" :
1402 "expectations, but none matched")
1403 << ":\n";
1404 for (int i = 0; i < count; i++) {
1405 *why << "\n";
1406 expectations_[i]->DescribeLocationTo(why);
1407 if (count > 1) {
1408 *why << "tried expectation #" << i;
1409 }
1410 *why << "\n";
1411 expectations_[i]->DescribeMatchResultTo(args, why);
1412 expectations_[i]->DescribeCallCountTo(why);
1413 }
1414 }
1415
zhanyong.wandf35a762009-04-22 22:25:31 +00001416 // Address of the mock object this mock method belongs to. Only
1417 // valid after this mock method has been called or
1418 // ON_CALL/EXPECT_CALL has been invoked on it.
shiqiane35fdd92008-12-10 05:08:54 +00001419 const void* mock_obj_; // Protected by g_gmock_mutex.
1420
zhanyong.wandf35a762009-04-22 22:25:31 +00001421 // Name of the function being mocked. Only valid after this mock
1422 // method has been called.
shiqiane35fdd92008-12-10 05:08:54 +00001423 const char* name_; // Protected by g_gmock_mutex.
1424
1425 // The current spec (either default action spec or expectation spec)
1426 // being described on this function mocker.
1427 MockSpec<F> current_spec_;
1428
1429 // All default action specs for this function mocker.
1430 std::vector<DefaultActionSpec<F> > default_actions_;
1431 // All expectations for this function mocker.
1432 Expectations expectations_;
zhanyong.wan16cf4732009-05-14 20:55:30 +00001433
1434 // There is no generally useful and implementable semantics of
1435 // copying a mock object, so copying a mock is usually a user error.
1436 // Thus we disallow copying function mockers. If the user really
1437 // wants to copy a mock object, he should implement his own copy
1438 // operation, for example:
1439 //
1440 // class MockFoo : public Foo {
1441 // public:
1442 // // Defines a copy constructor explicitly.
1443 // MockFoo(const MockFoo& src) {}
1444 // ...
1445 // };
1446 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001447}; // class FunctionMockerBase
1448
1449#ifdef _MSC_VER
1450#pragma warning(pop) // Restores the warning state.
1451#endif // _MSV_VER
1452
1453// Implements methods of FunctionMockerBase.
1454
1455// Verifies that all expectations on this mock function have been
1456// satisfied. Reports one or more Google Test non-fatal failures and
1457// returns false if not.
1458// L >= g_gmock_mutex
1459template <typename F>
1460bool FunctionMockerBase<F>::VerifyAndClearExpectationsLocked() {
1461 g_gmock_mutex.AssertHeld();
1462 bool expectations_met = true;
1463 for (typename Expectations::const_iterator it = expectations_.begin();
1464 it != expectations_.end(); ++it) {
1465 Expectation<F>* const exp = it->get();
1466
1467 if (exp->IsOverSaturated()) {
1468 // There was an upper-bound violation. Since the error was
1469 // already reported when it occurred, there is no need to do
1470 // anything here.
1471 expectations_met = false;
1472 } else if (!exp->IsSatisfied()) {
1473 expectations_met = false;
1474 ::std::stringstream ss;
1475 ss << "Actual function call count doesn't match this expectation.\n";
1476 // No need to show the source file location of the expectation
1477 // in the description, as the Expect() call that follows already
1478 // takes care of it.
1479 exp->DescribeCallCountTo(&ss);
1480 Expect(false, exp->file(), exp->line(), ss.str());
1481 }
1482 }
1483 expectations_.clear();
1484 return expectations_met;
1485}
1486
1487// Reports an uninteresting call (whose description is in msg) in the
1488// manner specified by 'reaction'.
1489void ReportUninterestingCall(CallReaction reaction, const string& msg);
1490
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001491// Calculates the result of invoking this mock function with the given
1492// arguments, prints it, and returns it.
1493// L < g_gmock_mutex
shiqiane35fdd92008-12-10 05:08:54 +00001494template <typename F>
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001495typename Function<F>::Result FunctionMockerBase<F>::InvokeWith(
1496 const typename Function<F>::ArgumentTuple& args) {
1497 typedef ActionResultHolder<Result> ResultHolder;
shiqiane35fdd92008-12-10 05:08:54 +00001498
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001499 if (expectations_.size() == 0) {
1500 // No expectation is set on this mock method - we have an
1501 // uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001502
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001503 // We must get Google Mock's reaction on uninteresting calls
1504 // made on this mock object BEFORE performing the action,
1505 // because the action may DELETE the mock object and make the
1506 // following expression meaningless.
1507 const CallReaction reaction =
1508 Mock::GetReactionOnUninterestingCalls(MockObject());
shiqiane35fdd92008-12-10 05:08:54 +00001509
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001510 // True iff we need to print this call's arguments and return
1511 // value. This definition must be kept in sync with
1512 // the behavior of ReportUninterestingCall().
1513 const bool need_to_report_uninteresting_call =
1514 // If the user allows this uninteresting call, we print it
1515 // only when he wants informational messages.
1516 reaction == ALLOW ? LogIsVisible(INFO) :
1517 // If the user wants this to be a warning, we print it only
1518 // when he wants to see warnings.
1519 reaction == WARN ? LogIsVisible(WARNING) :
1520 // Otherwise, the user wants this to be an error, and we
1521 // should always print detailed information in the error.
1522 true;
1523
1524 if (!need_to_report_uninteresting_call) {
1525 // Perform the action without printing the call information.
1526 return PerformDefaultAction(args, "");
shiqiane35fdd92008-12-10 05:08:54 +00001527 }
1528
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001529 // Warns about the uninteresting call.
shiqiane35fdd92008-12-10 05:08:54 +00001530 ::std::stringstream ss;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001531 DescribeUninterestingCall(args, &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001532
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001533 // Calculates the function result.
1534 const ResultHolder result =
1535 ResultHolder::PerformDefaultAction(this, args, ss.str());
shiqiane35fdd92008-12-10 05:08:54 +00001536
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001537 // Prints the function result.
1538 result.PrintAsActionResult(&ss);
1539
1540 ReportUninterestingCall(reaction, ss.str());
1541 return result.value();
shiqiane35fdd92008-12-10 05:08:54 +00001542 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001543
1544 bool is_excessive = false;
1545 ::std::stringstream ss;
1546 ::std::stringstream why;
1547 ::std::stringstream loc;
1548 Action<F> action;
1549 Expectation<F>* exp;
1550
1551 // The FindMatchingExpectationAndAction() function acquires and
1552 // releases g_gmock_mutex.
1553 const bool found = FindMatchingExpectationAndAction(
1554 args, &exp, &action, &is_excessive, &ss, &why);
1555
1556 // True iff we need to print the call's arguments and return value.
1557 // This definition must be kept in sync with the uses of Expect()
1558 // and Log() in this function.
1559 const bool need_to_report_call = !found || is_excessive || LogIsVisible(INFO);
1560 if (!need_to_report_call) {
1561 // Perform the action without printing the call information.
1562 return action.IsDoDefault() ? PerformDefaultAction(args, "") :
1563 action.Perform(args);
1564 }
1565
1566 ss << " Function call: " << Name();
1567 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1568
1569 // In case the action deletes a piece of the expectation, we
1570 // generate the message beforehand.
1571 if (found && !is_excessive) {
1572 exp->DescribeLocationTo(&loc);
1573 }
1574
1575 const ResultHolder result = action.IsDoDefault() ?
1576 ResultHolder::PerformDefaultAction(this, args, ss.str()) :
1577 ResultHolder::PerformAction(action, args);
1578 result.PrintAsActionResult(&ss);
1579 ss << "\n" << why.str();
1580
1581 if (!found) {
1582 // No expectation matches this call - reports a failure.
1583 Expect(false, NULL, -1, ss.str());
1584 } else if (is_excessive) {
1585 // We had an upper-bound violation and the failure message is in ss.
1586 Expect(false, exp->file(), exp->line(), ss.str());
1587 } else {
1588 // We had an expected call and the matching expectation is
1589 // described in ss.
1590 Log(INFO, loc.str() + ss.str(), 2);
1591 }
1592 return result.value();
1593}
shiqiane35fdd92008-12-10 05:08:54 +00001594
1595} // namespace internal
1596
1597// The style guide prohibits "using" statements in a namespace scope
1598// inside a header file. However, the MockSpec class template is
1599// meant to be defined in the ::testing namespace. The following line
1600// is just a trick for working around a bug in MSVC 8.0, which cannot
1601// handle it if we define MockSpec in ::testing.
1602using internal::MockSpec;
1603
1604// Const(x) is a convenient function for obtaining a const reference
1605// to x. This is useful for setting expectations on an overloaded
1606// const mock method, e.g.
1607//
1608// class MockFoo : public FooInterface {
1609// public:
1610// MOCK_METHOD0(Bar, int());
1611// MOCK_CONST_METHOD0(Bar, int&());
1612// };
1613//
1614// MockFoo foo;
1615// // Expects a call to non-const MockFoo::Bar().
1616// EXPECT_CALL(foo, Bar());
1617// // Expects a call to const MockFoo::Bar().
1618// EXPECT_CALL(Const(foo), Bar());
1619template <typename T>
1620inline const T& Const(const T& x) { return x; }
1621
1622} // namespace testing
1623
1624// A separate macro is required to avoid compile errors when the name
1625// of the method used in call is a result of macro expansion.
1626// See CompilesWithMethodNameExpandedFromMacro tests in
1627// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001628#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001629 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1630 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001631#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001632
zhanyong.wane0d051e2009-02-19 00:33:37 +00001633#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001634 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001635#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001636
1637#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_