Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/SciptableControllerFS15/src/external/gmock/include/gmock/gmock-spec-builders.h @ 10308

Last change on this file since 10308 was 9021, checked in by landauf, 13 years ago

added google test and google mock to external libraries

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