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