gmock-spec-builders.h 65.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)

// Google Mock - a framework for writing C++ mock classes.
//
// This file implements the ON_CALL() and EXPECT_CALL() macros.
//
// A user can use the ON_CALL() macro to specify the default action of
// a mock method.  The syntax is:
//
//   ON_CALL(mock_object, Method(argument-matchers))
40
//       .With(multi-argument-matcher)
41
42
//       .WillByDefault(action);
//
43
//  where the .With() clause is optional.
44
45
46
47
48
//
// A user can use the EXPECT_CALL() macro to specify an expectation on
// a mock method.  The syntax is:
//
//   EXPECT_CALL(mock_object, Method(argument-matchers))
49
//       .With(multi-argument-matchers)
50
51
//       .Times(cardinality)
//       .InSequence(sequences)
52
//       .After(expectations)
53
54
55
56
//       .WillOnce(action)
//       .WillRepeatedly(action)
//       .RetiresOnSaturation();
//
57
58
// where all clauses are optional, and .InSequence()/.After()/
// .WillOnce() can appear any number of times.
59
60
61
62
63
64
65
66
67
68

#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_

#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>

69
70
71
72
73
74
#include "gmock/gmock-actions.h"
#include "gmock/gmock-cardinalities.h"
#include "gmock/gmock-matchers.h"
#include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
75
76
77

namespace testing {

78
79
80
81
82
83
// An abstract handle of an expectation.
class Expectation;

// A set of expectation handles.
class ExpectationSet;

84
85
86
87
// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
// and MUST NOT BE USED IN USER CODE!!!
namespace internal {

88
89
// Implements a mock function.
template <typename F> class FunctionMocker;
90
91
92
93

// Base class for expectations.
class ExpectationBase;

94
95
96
// Implements an expectation.
template <typename F> class TypedExpectation;

97
98
99
100
// Helper class for testing the Expectation class template.
class ExpectationTester;

// Base class for function mockers.
101
template <typename F> class FunctionMockerBase;
102
103
104
105
106
107
108
109
110
111
112
113

// Protects the mock object registry (in class Mock), all function
// mockers, and all expectations.
//
// The reason we don't use more fine-grained protection is: when a
// mock function Foo() is called, it needs to consult its expectations
// to see which one should be picked.  If another thread is allowed to
// call a mock function (either Foo() or a different one) at the same
// time, it could affect the "retired" attributes of Foo()'s
// expectations when InSequence() is used, and thus affect which
// expectation gets picked.  Therefore, we sequence all mock function
// calls to ensure the integrity of the mock objects' states.
114
GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
115

116
117
118
// Untyped base class for ActionResultHolder<R>.
class UntypedActionResultHolderBase;

119
120
121
// Abstract base class of FunctionMockerBase.  This is the
// type-agnostic part of the function mocker interface.  Its pure
// virtual methods are implemented by FunctionMockerBase.
122
class GTEST_API_ UntypedFunctionMockerBase {
123
 public:
124
125
  UntypedFunctionMockerBase();
  virtual ~UntypedFunctionMockerBase();
126
127
128
129

  // Verifies that all expectations on this mock function have been
  // satisfied.  Reports one or more Google Test non-fatal failures
  // and returns false if not.
130
131
  bool VerifyAndClearExpectationsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
132
133

  // Clears the ON_CALL()s set on this mock function.
134
135
  virtual void ClearDefaultActionsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

  // In all of the following Untyped* functions, it's the caller's
  // responsibility to guarantee the correctness of the arguments'
  // types.

  // Performs the default action with the given arguments and returns
  // the action's result.  The call description string will be used in
  // the error message to describe the call in the case the default
  // action fails.
  // L = *
  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
      const void* untyped_args,
      const string& call_description) const = 0;

  // Performs the given action with the given arguments and returns
  // the action's result.
  // L = *
  virtual UntypedActionResultHolderBase* UntypedPerformAction(
      const void* untyped_action,
      const void* untyped_args) const = 0;

  // Writes a message that the call is uninteresting (i.e. neither
  // explicitly expected nor explicitly unexpected) to the given
  // ostream.
160
161
162
163
  virtual void UntypedDescribeUninterestingCall(
      const void* untyped_args,
      ::std::ostream* os) const
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
164
165
166
167
168
169
170
171
172
173

  // Returns the expectation that matches the given function arguments
  // (or NULL is there's no match); when a match is found,
  // untyped_action is set to point to the action that should be
  // performed (or NULL if the action is "do default"), and
  // is_excessive is modified to indicate whether the call exceeds the
  // expected number.
  virtual const ExpectationBase* UntypedFindMatchingExpectation(
      const void* untyped_args,
      const void** untyped_action, bool* is_excessive,
174
175
      ::std::ostream* what, ::std::ostream* why)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
176
177
178
179
180
181
182
183
184
185

  // Prints the given function arguments to the ostream.
  virtual void UntypedPrintArgs(const void* untyped_args,
                                ::std::ostream* os) const = 0;

  // Sets the mock object this mock method belongs to, and registers
  // this information in the global mock registry.  Will be called
  // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
  // method.
  // TODO(wan@google.com): rename to SetAndRegisterOwner().
186
187
  void RegisterOwner(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
188
189
190
191

  // Sets the mock object this mock method belongs to, and sets the
  // name of the mock function.  Will be called upon each invocation
  // of this mock function.
192
193
  void SetOwnerAndName(const void* mock_obj, const char* name)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
194
195
196
197

  // Returns the mock object this mock method belongs to.  Must be
  // called after RegisterOwner() or SetOwnerAndName() has been
  // called.
198
199
  const void* MockObject() const
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
200
201
202

  // Returns the name of this mock method.  Must be called after
  // SetOwnerAndName() has been called.
203
204
  const char* Name() const
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
205
206
207
208
209
210

  // Returns the result of invoking this mock function with the given
  // arguments.  This function can be safely called from multiple
  // threads concurrently.  The caller is responsible for deleting the
  // result.
  const UntypedActionResultHolderBase* UntypedInvokeWith(
211
212
      const void* untyped_args)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

 protected:
  typedef std::vector<const void*> UntypedOnCallSpecs;

  typedef std::vector<internal::linked_ptr<ExpectationBase> >
  UntypedExpectations;

  // Returns an Expectation object that references and co-owns exp,
  // which must be an expectation on this mock function.
  Expectation GetHandleOf(ExpectationBase* exp);

  // Address of the mock object this mock method belongs to.  Only
  // valid after this mock method has been called or
  // ON_CALL/EXPECT_CALL has been invoked on it.
  const void* mock_obj_;  // Protected by g_gmock_mutex.

  // Name of the function being mocked.  Only valid after this mock
  // method has been called.
  const char* name_;  // Protected by g_gmock_mutex.

  // All default action specs for this function mocker.
  UntypedOnCallSpecs untyped_on_call_specs_;

  // All expectations for this function mocker.
  UntypedExpectations untyped_expectations_;
238
239
};  // class UntypedFunctionMockerBase

240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Untyped base class for OnCallSpec<F>.
class UntypedOnCallSpecBase {
 public:
  // The arguments are the location of the ON_CALL() statement.
  UntypedOnCallSpecBase(const char* a_file, int a_line)
      : file_(a_file), line_(a_line), last_clause_(kNone) {}

  // Where in the source file was the default action spec defined?
  const char* file() const { return file_; }
  int line() const { return line_; }

 protected:
  // Gives each clause in the ON_CALL() statement a name.
  enum Clause {
    // Do not change the order of the enum members!  The run-time
    // syntax checking relies on it.
    kNone,
    kWith,
258
    kWillByDefault
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
  };

  // Asserts that the ON_CALL() statement has a certain property.
  void AssertSpecProperty(bool property, const string& failure_message) const {
    Assert(property, file_, line_, failure_message);
  }

  // Expects that the ON_CALL() statement has a certain property.
  void ExpectSpecProperty(bool property, const string& failure_message) const {
    Expect(property, file_, line_, failure_message);
  }

  const char* file_;
  int line_;

  // The last clause in the ON_CALL() statement as seen so far.
  // Initially kNone and changes as the statement is parsed.
  Clause last_clause_;
};  // class UntypedOnCallSpecBase

// This template class implements an ON_CALL spec.
280
template <typename F>
281
class OnCallSpec : public UntypedOnCallSpecBase {
282
283
284
285
 public:
  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;

286
  // Constructs an OnCallSpec object from the information inside
287
  // the parenthesis of an ON_CALL() statement.
288
289
290
  OnCallSpec(const char* a_file, int a_line,
             const ArgumentMatcherTuple& matchers)
      : UntypedOnCallSpecBase(a_file, a_line),
291
        matchers_(matchers),
292
293
294
295
        // By default, extra_matcher_ should match anything.  However,
        // we cannot initialize it with _ as that triggers a compiler
        // bug in Symbian's C++ compiler (cannot decide between two
        // overloaded constructors of Matcher<const ArgumentTuple&>).
296
        extra_matcher_(A<const ArgumentTuple&>()) {
297
298
  }

299
  // Implements the .With() clause.
300
  OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
301
    // Makes sure this is called at most once.
302
303
    ExpectSpecProperty(last_clause_ < kWith,
                       ".With() cannot appear "
304
                       "more than once in an ON_CALL().");
305
    last_clause_ = kWith;
306
307
308
309
310
311

    extra_matcher_ = m;
    return *this;
  }

  // Implements the .WillByDefault() clause.
312
  OnCallSpec& WillByDefault(const Action<F>& action) {
313
    ExpectSpecProperty(last_clause_ < kWillByDefault,
314
315
                       ".WillByDefault() must appear "
                       "exactly once in an ON_CALL().");
316
    last_clause_ = kWillByDefault;
317
318
319
320
321
322
323
324
325
326
327
328
329
330

    ExpectSpecProperty(!action.IsDoDefault(),
                       "DoDefault() cannot be used in ON_CALL().");
    action_ = action;
    return *this;
  }

  // Returns true iff the given arguments match the matchers.
  bool Matches(const ArgumentTuple& args) const {
    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  }

  // Returns the action specified by the user.
  const Action<F>& GetAction() const {
331
    AssertSpecProperty(last_clause_ == kWillByDefault,
332
333
334
335
                       ".WillByDefault() must appear exactly "
                       "once in an ON_CALL().");
    return action_;
  }
336

337
338
339
340
 private:
  // The information in statement
  //
  //   ON_CALL(mock_object, Method(matchers))
341
  //       .With(multi-argument-matcher)
342
343
344
345
346
347
348
349
350
351
352
353
  //       .WillByDefault(action);
  //
  // is recorded in the data members like this:
  //
  //   source file that contains the statement => file_
  //   line number of the statement            => line_
  //   matchers                                => matchers_
  //   multi-argument-matcher                  => extra_matcher_
  //   action                                  => action_
  ArgumentMatcherTuple matchers_;
  Matcher<const ArgumentTuple&> extra_matcher_;
  Action<F> action_;
354
};  // class OnCallSpec
355

zhanyong.wan's avatar
zhanyong.wan committed
356
// Possible reactions on uninteresting calls.
357
enum CallReaction {
zhanyong.wan's avatar
zhanyong.wan committed
358
359
360
  kAllow,
  kWarn,
  kFail
361
362
363
364
365
};

}  // namespace internal

// Utilities for manipulating mock objects.
366
class GTEST_API_ Mock {
367
368
369
 public:
  // The following public methods can be called concurrently.

370
371
  // Tells Google Mock to ignore mock_obj when checking for leaked
  // mock objects.
372
373
  static void AllowLeak(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
374

375
376
377
  // Verifies and clears all expectations on the given mock object.
  // If the expectations aren't satisfied, generates one or more
  // Google Test non-fatal failures and returns false.
378
379
  static bool VerifyAndClearExpectations(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
380
381
382
383

  // Verifies all expectations on the given mock object and clears its
  // default actions and expectations.  Returns true iff the
  // verification was successful.
384
385
  static bool VerifyAndClear(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
386

387
 private:
388
389
  friend class internal::UntypedFunctionMockerBase;

390
391
392
393
394
395
396
397
398
399
400
401
402
  // Needed for a function mocker to register itself (so that we know
  // how to clear a mock object).
  template <typename F>
  friend class internal::FunctionMockerBase;

  template <typename M>
  friend class NiceMock;

  template <typename M>
  friend class StrictMock;

  // Tells Google Mock to allow uninteresting calls on the given mock
  // object.
403
404
  static void AllowUninterestingCalls(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
405
406
407

  // Tells Google Mock to warn the user about uninteresting calls on
  // the given mock object.
408
409
  static void WarnUninterestingCalls(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
410
411
412

  // Tells Google Mock to fail uninteresting calls on the given mock
  // object.
413
414
  static void FailUninterestingCalls(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
415
416
417

  // Tells Google Mock the given mock object is being destroyed and
  // its entry in the call-reaction table should be removed.
418
419
  static void UnregisterCallReaction(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
420
421
422
423

  // Returns the reaction Google Mock will have on uninteresting calls
  // made on the given mock object.
  static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan's avatar
zhanyong.wan committed
424
      const void* mock_obj)
425
          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
426
427
428
429

  // Verifies that all expectations on the given mock object have been
  // satisfied.  Reports one or more Google Test non-fatal failures
  // and returns false if not.
430
431
  static bool VerifyAndClearExpectationsLocked(void* mock_obj)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
432
433

  // Clears all ON_CALL()s set on the given mock object.
434
435
  static void ClearDefaultActionsLocked(void* mock_obj)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
436
437

  // Registers a mock object and a mock method it owns.
438
439
440
441
  static void Register(
      const void* mock_obj,
      internal::UntypedFunctionMockerBase* mocker)
          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
442

443
444
445
446
  // Tells Google Mock where in the source code mock_obj is used in an
  // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
  // information helps the user identify which object it is.
  static void RegisterUseByOnCallOrExpectCall(
447
448
      const void* mock_obj, const char* file, int line)
          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
449

450
451
452
453
  // Unregisters a mock method; removes the owning mock object from
  // the registry when the last mock method associated with it has
  // been unregistered.  This is called only in the destructor of
  // FunctionMockerBase.
454
455
  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
456
457
};  // class Mock

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// An abstract handle of an expectation.  Useful in the .After()
// clause of EXPECT_CALL() for setting the (partial) order of
// expectations.  The syntax:
//
//   Expectation e1 = EXPECT_CALL(...)...;
//   EXPECT_CALL(...).After(e1)...;
//
// sets two expectations where the latter can only be matched after
// the former has been satisfied.
//
// Notes:
//   - This class is copyable and has value semantics.
//   - Constness is shallow: a const Expectation object itself cannot
//     be modified, but the mutable methods of the ExpectationBase
//     object it references can be called via expectation_base().
473
474
475
476
477
478
//   - The constructors and destructor are defined out-of-line because
//     the Symbian WINSCW compiler wants to otherwise instantiate them
//     when it sees this class definition, at which point it doesn't have
//     ExpectationBase available yet, leading to incorrect destruction
//     in the linked_ptr (or compilation errors if using a checking
//     linked_ptr).
479
class GTEST_API_ Expectation {
480
481
 public:
  // Constructs a null object that doesn't reference any expectation.
482
483
484
  Expectation();

  ~Expectation();
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

  // This single-argument ctor must not be explicit, in order to support the
  //   Expectation e = EXPECT_CALL(...);
  // syntax.
  //
  // A TypedExpectation object stores its pre-requisites as
  // Expectation objects, and needs to call the non-const Retire()
  // method on the ExpectationBase objects they reference.  Therefore
  // Expectation must receive a *non-const* reference to the
  // ExpectationBase object.
  Expectation(internal::ExpectationBase& exp);  // NOLINT

  // The compiler-generated copy ctor and operator= work exactly as
  // intended, so we don't need to define our own.

  // Returns true iff rhs references the same expectation as this object does.
  bool operator==(const Expectation& rhs) const {
    return expectation_base_ == rhs.expectation_base_;
  }

  bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }

 private:
  friend class ExpectationSet;
  friend class Sequence;
  friend class ::testing::internal::ExpectationBase;
511
  friend class ::testing::internal::UntypedFunctionMockerBase;
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529

  template <typename F>
  friend class ::testing::internal::FunctionMockerBase;

  template <typename F>
  friend class ::testing::internal::TypedExpectation;

  // This comparator is needed for putting Expectation objects into a set.
  class Less {
   public:
    bool operator()(const Expectation& lhs, const Expectation& rhs) const {
      return lhs.expectation_base_.get() < rhs.expectation_base_.get();
    }
  };

  typedef ::std::set<Expectation, Less> Set;

  Expectation(
530
      const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

  // Returns the expectation this object references.
  const internal::linked_ptr<internal::ExpectationBase>&
  expectation_base() const {
    return expectation_base_;
  }

  // A linked_ptr that co-owns the expectation this handle references.
  internal::linked_ptr<internal::ExpectationBase> expectation_base_;
};

// A set of expectation handles.  Useful in the .After() clause of
// EXPECT_CALL() for setting the (partial) order of expectations.  The
// syntax:
//
//   ExpectationSet es;
//   es += EXPECT_CALL(...)...;
//   es += EXPECT_CALL(...)...;
//   EXPECT_CALL(...).After(es)...;
//
// sets three expectations where the last one can only be matched
// after the first two have both been satisfied.
//
// This class is copyable and has value semantics.
class ExpectationSet {
 public:
  // A bidirectional iterator that can read a const element in the set.
  typedef Expectation::Set::const_iterator const_iterator;

  // An object stored in the set.  This is an alias of Expectation.
  typedef Expectation::Set::value_type value_type;

  // Constructs an empty set.
  ExpectationSet() {}

  // This single-argument ctor must not be explicit, in order to support the
  //   ExpectationSet es = EXPECT_CALL(...);
  // syntax.
  ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT
    *this += Expectation(exp);
  }

  // This single-argument ctor implements implicit conversion from
  // Expectation and thus must not be explicit.  This allows either an
  // Expectation or an ExpectationSet to be used in .After().
  ExpectationSet(const Expectation& e) {  // NOLINT
    *this += e;
  }

  // The compiler-generator ctor and operator= works exactly as
  // intended, so we don't need to define our own.

  // Returns true iff rhs contains the same set of Expectation objects
  // as this does.
  bool operator==(const ExpectationSet& rhs) const {
    return expectations_ == rhs.expectations_;
  }

  bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }

  // Implements the syntax
  //   expectation_set += EXPECT_CALL(...);
  ExpectationSet& operator+=(const Expectation& e) {
    expectations_.insert(e);
    return *this;
  }

  int size() const { return static_cast<int>(expectations_.size()); }

  const_iterator begin() const { return expectations_.begin(); }
  const_iterator end() const { return expectations_.end(); }

 private:
  Expectation::Set expectations_;
};


608
609
610
// Sequence objects are used by a user to specify the relative order
// in which the expectations should match.  They are copyable (we rely
// on the compiler-defined copy constructor and assignment operator).
611
class GTEST_API_ Sequence {
612
613
 public:
  // Constructs an empty sequence.
614
  Sequence() : last_expectation_(new Expectation) {}
615
616
617

  // Adds an expectation to this sequence.  The caller must ensure
  // that no other thread is accessing this Sequence object.
618
619
  void AddExpectation(const Expectation& expectation) const;

620
 private:
621
622
623
624
625
  // The last expectation in this sequence.  We use a linked_ptr here
  // because Sequence objects are copyable and we want the copies to
  // be aliases.  The linked_ptr allows the copies to co-own and share
  // the same Expectation object.
  internal::linked_ptr<Expectation> last_expectation_;
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
};  // class Sequence

// An object of this type causes all EXPECT_CALL() statements
// encountered in its scope to be put in an anonymous sequence.  The
// work is done in the constructor and destructor.  You should only
// create an InSequence object on the stack.
//
// The sole purpose for this class is to support easy definition of
// sequential expectations, e.g.
//
//   {
//     InSequence dummy;  // The name of the object doesn't matter.
//
//     // The following expectations must match in the order they appear.
//     EXPECT_CALL(a, Bar())...;
//     EXPECT_CALL(a, Baz())...;
//     ...
//     EXPECT_CALL(b, Xyz())...;
//   }
//
// You can create InSequence objects in multiple threads, as long as
// they are used to affect different mock objects.  The idea is that
// each thread can create and set up its own mocks as if it's the only
// thread.  However, for clarity of your tests we recommend you to set
// up mocks in the main thread unless you have a good reason not to do
// so.
652
class GTEST_API_ InSequence {
653
654
655
656
657
658
659
 public:
  InSequence();
  ~InSequence();
 private:
  bool sequence_created_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
660
} GTEST_ATTRIBUTE_UNUSED_;
661
662
663
664
665

namespace internal {

// Points to the implicit sequence introduced by a living InSequence
// object (if any) in the current thread or NULL.
666
GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681

// Base class for implementing expectations.
//
// There are two reasons for having a type-agnostic base class for
// Expectation:
//
//   1. We need to store collections of expectations of different
//   types (e.g. all pre-requisites of a particular expectation, all
//   expectations in a sequence).  Therefore these expectation objects
//   must share a common base class.
//
//   2. We can avoid binary code bloat by moving methods not depending
//   on the template argument of Expectation to the base class.
//
// This class is internal and mustn't be used by user code directly.
682
class GTEST_API_ ExpectationBase {
683
 public:
684
685
  // source_text is the EXPECT_CALL(...) source that created this Expectation.
  ExpectationBase(const char* file, int line, const string& source_text);
686
687
688
689
690
691

  virtual ~ExpectationBase();

  // Where in the source file was the expectation spec defined?
  const char* file() const { return file_; }
  int line() const { return line_; }
692
  const char* source_text() const { return source_text_.c_str(); }
693
694
695
696
697
  // Returns the cardinality specified in the expectation spec.
  const Cardinality& cardinality() const { return cardinality_; }

  // Describes the source file location of this expectation.
  void DescribeLocationTo(::std::ostream* os) const {
698
    *os << FormatFileLocation(file(), line()) << " ";
699
700
701
702
  }

  // Describes how many times a function call matching this
  // expectation has occurred.
703
704
  void DescribeCallCountTo(::std::ostream* os) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
705
706
707
708

  // If this mock method has an extra matcher (i.e. .With(matcher)),
  // describes it to the ostream.
  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
709

710
 protected:
711
  friend class ::testing::Expectation;
712
  friend class UntypedFunctionMockerBase;
713
714
715

  enum Clause {
    // Don't change the order of the enum members!
716
717
718
719
    kNone,
    kWith,
    kTimes,
    kInSequence,
720
    kAfter,
721
722
    kWillOnce,
    kWillRepeatedly,
723
    kRetiresOnSaturation
724
725
  };

726
727
  typedef std::vector<const void*> UntypedActions;

728
729
730
731
  // Returns an Expectation object that references and co-owns this
  // expectation.
  virtual Expectation GetHandle() = 0;

732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
  // Asserts that the EXPECT_CALL() statement has the given property.
  void AssertSpecProperty(bool property, const string& failure_message) const {
    Assert(property, file_, line_, failure_message);
  }

  // Expects that the EXPECT_CALL() statement has the given property.
  void ExpectSpecProperty(bool property, const string& failure_message) const {
    Expect(property, file_, line_, failure_message);
  }

  // Explicitly specifies the cardinality of this expectation.  Used
  // by the subclasses to implement the .Times() clause.
  void SpecifyCardinality(const Cardinality& cardinality);

  // Returns true iff the user specified the cardinality explicitly
  // using a .Times().
  bool cardinality_specified() const { return cardinality_specified_; }

  // Sets the cardinality of this expectation spec.
751
752
  void set_cardinality(const Cardinality& a_cardinality) {
    cardinality_ = a_cardinality;
753
754
755
756
757
758
759
  }

  // The following group of methods should only be called after the
  // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
  // the current thread.

  // Retires all pre-requisites of this expectation.
760
761
  void RetireAllPreRequisites()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
762
763

  // Returns true iff this expectation is retired.
764
765
  bool is_retired() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
766
767
768
769
770
    g_gmock_mutex.AssertHeld();
    return retired_;
  }

  // Retires this expectation.
771
772
  void Retire()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
773
774
775
776
777
    g_gmock_mutex.AssertHeld();
    retired_ = true;
  }

  // Returns true iff this expectation is satisfied.
778
779
  bool IsSatisfied() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
780
781
782
783
784
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSatisfiedByCallCount(call_count_);
  }

  // Returns true iff this expectation is saturated.
785
786
  bool IsSaturated() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
787
788
789
790
791
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSaturatedByCallCount(call_count_);
  }

  // Returns true iff this expectation is over-saturated.
792
793
  bool IsOverSaturated() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
794
795
796
797
798
    g_gmock_mutex.AssertHeld();
    return cardinality().IsOverSaturatedByCallCount(call_count_);
  }

  // Returns true iff all pre-requisites of this expectation are satisfied.
799
800
  bool AllPrerequisitesAreSatisfied() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
801
802

  // Adds unsatisfied pre-requisites of this expectation to 'result'.
803
804
  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
805
806

  // Returns the number this expectation has been invoked.
807
808
  int call_count() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
809
810
811
812
813
    g_gmock_mutex.AssertHeld();
    return call_count_;
  }

  // Increments the number this expectation has been invoked.
814
815
  void IncrementCallCount()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
816
817
818
819
    g_gmock_mutex.AssertHeld();
    call_count_++;
  }

820
821
822
823
  // Checks the action count (i.e. the number of WillOnce() and
  // WillRepeatedly() clauses) against the cardinality if this hasn't
  // been done before.  Prints a warning if there are too many or too
  // few actions.
824
825
  void CheckActionCountIfNotDone() const
      GTEST_LOCK_EXCLUDED_(mutex_);
826

827
828
829
830
  friend class ::testing::Sequence;
  friend class ::testing::internal::ExpectationTester;

  template <typename Function>
831
  friend class TypedExpectation;
832

833
834
835
  // Implements the .Times() clause.
  void UntypedTimes(const Cardinality& a_cardinality);

836
837
  // This group of fields are part of the spec and won't change after
  // an EXPECT_CALL() statement finishes.
838
839
840
  const char* file_;          // The file that contains the expectation.
  int line_;                  // The line number of the expectation.
  const string source_text_;  // The EXPECT_CALL(...) source text.
841
842
843
  // True iff the cardinality is specified explicitly.
  bool cardinality_specified_;
  Cardinality cardinality_;            // The cardinality of the expectation.
844
845
846
847
848
849
850
  // The immediate pre-requisites (i.e. expectations that must be
  // satisfied before this expectation can be matched) of this
  // expectation.  We use linked_ptr in the set because we want an
  // Expectation object to be co-owned by its FunctionMocker and its
  // successors.  This allows multiple mock objects to be deleted at
  // different times.
  ExpectationSet immediate_prerequisites_;
851
852
853
854
855

  // This group of fields are the current state of the expectation,
  // and can change as the mock function is called.
  int call_count_;  // How many times this expectation has been invoked.
  bool retired_;    // True iff this expectation has retired.
856
857
858
859
860
861
862
  UntypedActions untyped_actions_;
  bool extra_matcher_specified_;
  bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.
  bool retires_on_saturation_;
  Clause last_clause_;
  mutable bool action_count_checked_;  // Under mutex_.
  mutable Mutex mutex_;  // Protects action_count_checked_.
863
864

  GTEST_DISALLOW_ASSIGN_(ExpectationBase);
865
866
867
868
};  // class ExpectationBase

// Impements an expectation for the given function type.
template <typename F>
869
class TypedExpectation : public ExpectationBase {
870
871
872
873
874
 public:
  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  typedef typename Function<F>::Result Result;

875
  TypedExpectation(FunctionMockerBase<F>* owner,
876
                   const char* a_file, int a_line, const string& a_source_text,
877
                   const ArgumentMatcherTuple& m)
878
      : ExpectationBase(a_file, a_line, a_source_text),
879
880
        owner_(owner),
        matchers_(m),
881
882
883
884
885
        // By default, extra_matcher_ should match anything.  However,
        // we cannot initialize it with _ as that triggers a compiler
        // bug in Symbian's C++ compiler (cannot decide between two
        // overloaded constructors of Matcher<const ArgumentTuple&>).
        extra_matcher_(A<const ArgumentTuple&>()),
886
        repeated_action_(DoDefault()) {}
887

888
  virtual ~TypedExpectation() {
889
890
891
    // Check the validity of the action count if it hasn't been done
    // yet (for example, if the expectation was never used).
    CheckActionCountIfNotDone();
892
893
894
895
    for (UntypedActions::const_iterator it = untyped_actions_.begin();
         it != untyped_actions_.end(); ++it) {
      delete static_cast<const Action<F>*>(*it);
    }
896
897
  }

898
  // Implements the .With() clause.
899
  TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
900
    if (last_clause_ == kWith) {
901
      ExpectSpecProperty(false,
902
                         ".With() cannot appear "
903
904
                         "more than once in an EXPECT_CALL().");
    } else {
905
906
      ExpectSpecProperty(last_clause_ < kWith,
                         ".With() must be the first "
907
908
                         "clause in an EXPECT_CALL().");
    }
909
    last_clause_ = kWith;
910
911

    extra_matcher_ = m;
912
    extra_matcher_specified_ = true;
913
914
915
916
    return *this;
  }

  // Implements the .Times() clause.
917
  TypedExpectation& Times(const Cardinality& a_cardinality) {
918
    ExpectationBase::UntypedTimes(a_cardinality);
919
920
921
922
    return *this;
  }

  // Implements the .Times() clause.
923
  TypedExpectation& Times(int n) {
924
925
926
927
    return Times(Exactly(n));
  }

  // Implements the .InSequence() clause.
928
  TypedExpectation& InSequence(const Sequence& s) {
929
    ExpectSpecProperty(last_clause_ <= kInSequence,
930
931
                       ".InSequence() cannot appear after .After(),"
                       " .WillOnce(), .WillRepeatedly(), or "
932
                       ".RetiresOnSaturation().");
933
    last_clause_ = kInSequence;
934

935
    s.AddExpectation(GetHandle());
936
937
    return *this;
  }
938
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
939
940
    return InSequence(s1).InSequence(s2);
  }
941
942
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3) {
943
944
    return InSequence(s1, s2).InSequence(s3);
  }
945
946
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3, const Sequence& s4) {
947
948
    return InSequence(s1, s2, s3).InSequence(s4);
  }
949
950
951
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3, const Sequence& s4,
                               const Sequence& s5) {
952
953
954
    return InSequence(s1, s2, s3, s4).InSequence(s5);
  }

955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
  // Implements that .After() clause.
  TypedExpectation& After(const ExpectationSet& s) {
    ExpectSpecProperty(last_clause_ <= kAfter,
                       ".After() cannot appear after .WillOnce(),"
                       " .WillRepeatedly(), or "
                       ".RetiresOnSaturation().");
    last_clause_ = kAfter;

    for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
      immediate_prerequisites_ += *it;
    }
    return *this;
  }
  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
    return After(s1).After(s2);
  }
  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
                          const ExpectationSet& s3) {
    return After(s1, s2).After(s3);
  }
  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
                          const ExpectationSet& s3, const ExpectationSet& s4) {
    return After(s1, s2, s3).After(s4);
  }
  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
                          const ExpectationSet& s3, const ExpectationSet& s4,
                          const ExpectationSet& s5) {
    return After(s1, s2, s3, s4).After(s5);
  }

985
  // Implements the .WillOnce() clause.
986
  TypedExpectation& WillOnce(const Action<F>& action) {
987
    ExpectSpecProperty(last_clause_ <= kWillOnce,
988
989
                       ".WillOnce() cannot appear after "
                       ".WillRepeatedly() or .RetiresOnSaturation().");
990
    last_clause_ = kWillOnce;
991

992
    untyped_actions_.push_back(new Action<F>(action));
993
    if (!cardinality_specified()) {
994
      set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
995
996
997
998
999
    }
    return *this;
  }

  // Implements the .WillRepeatedly() clause.
1000
  TypedExpectation& WillRepeatedly(const Action<F>& action) {
1001
    if (last_clause_ == kWillRepeatedly) {
1002
1003
1004
1005
      ExpectSpecProperty(false,
                         ".WillRepeatedly() cannot appear "
                         "more than once in an EXPECT_CALL().");
    } else {
1006
      ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1007
1008
1009
                         ".WillRepeatedly() cannot appear "
                         "after .RetiresOnSaturation().");
    }
1010
    last_clause_ = kWillRepeatedly;
1011
1012
1013
1014
    repeated_action_specified_ = true;

    repeated_action_ = action;
    if (!cardinality_specified()) {
1015
      set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1016
1017
1018
1019
1020
1021
1022
1023
1024
    }

    // Now that no more action clauses can be specified, we check
    // whether their count makes sense.
    CheckActionCountIfNotDone();
    return *this;
  }

  // Implements the .RetiresOnSaturation() clause.
1025
  TypedExpectation& RetiresOnSaturation() {
1026
    ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1027
1028
                       ".RetiresOnSaturation() cannot appear "
                       "more than once.");
1029
    last_clause_ = kRetiresOnSaturation;
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
    retires_on_saturation_ = true;

    // Now that no more action clauses can be specified, we check
    // whether their count makes sense.
    CheckActionCountIfNotDone();
    return *this;
  }

  // Returns the matchers for the arguments as specified inside the
  // EXPECT_CALL() macro.
  const ArgumentMatcherTuple& matchers() const {
    return matchers_;
  }

1044
  // Returns the matcher specified by the .With() clause.
1045
1046
1047
1048
1049
1050
1051
  const Matcher<const ArgumentTuple&>& extra_matcher() const {
    return extra_matcher_;
  }

  // Returns the action specified by the .WillRepeatedly() clause.
  const Action<F>& repeated_action() const { return repeated_action_; }

1052
1053
1054
  // If this mock method has an extra matcher (i.e. .With(matcher)),
  // describes it to the ostream.
  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
1055
1056
1057
1058
1059
1060
1061
    if (extra_matcher_specified_) {
      *os << "    Expected args: ";
      extra_matcher_.DescribeTo(os);
      *os << "\n";
    }
  }

1062
1063
1064
1065
 private:
  template <typename Function>
  friend class FunctionMockerBase;

1066
1067
1068
1069
1070
1071
  // Returns an Expectation object that references and co-owns this
  // expectation.
  virtual Expectation GetHandle() {
    return owner_->GetHandleOf(this);
  }

1072
1073
1074
1075
1076
  // The following methods will be called only after the EXPECT_CALL()
  // statement finishes and when the current thread holds
  // g_gmock_mutex.

  // Returns true iff this expectation matches the given arguments.
1077
1078
  bool Matches(const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1079
1080
1081
1082
1083
    g_gmock_mutex.AssertHeld();
    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  }

  // Returns true iff this expectation should handle the given arguments.
1084
1085
  bool ShouldHandleArguments(const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
    g_gmock_mutex.AssertHeld();

    // In case the action count wasn't checked when the expectation
    // was defined (e.g. if this expectation has no WillRepeatedly()
    // or RetiresOnSaturation() clause), we check it when the
    // expectation is used for the first time.
    CheckActionCountIfNotDone();
    return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
  }

  // Describes the result of matching the arguments against this
  // expectation to the given ostream.
1098
1099
1100
1101
  void ExplainMatchResultTo(
      const ArgumentTuple& args,
      ::std::ostream* os) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1102
1103
1104
1105
1106
1107
1108
    g_gmock_mutex.AssertHeld();

    if (is_retired()) {
      *os << "         Expected: the expectation is active\n"
          << "           Actual: it is retired\n";
    } else if (!Matches(args)) {
      if (!TupleMatches(matchers_, args)) {
1109
        ExplainMatchFailureTupleTo(matchers_, args, os);
1110
      }
zhanyong.wan's avatar
zhanyong.wan committed
1111
1112
      StringMatchResultListener listener;
      if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1113
        *os << "    Expected args: ";
1114
        extra_matcher_.DescribeTo(os);
1115
        *os << "\n           Actual: don't match";
1116

1117
        internal::PrintIfNotEmpty(listener.str(), os);
1118
1119
1120
1121
1122
1123
        *os << "\n";
      }
    } else if (!AllPrerequisitesAreSatisfied()) {
      *os << "         Expected: all pre-requisites are satisfied\n"
          << "           Actual: the following immediate pre-requisites "
          << "are not satisfied:\n";
1124
      ExpectationSet unsatisfied_prereqs;
1125
1126
      FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
      int i = 0;
1127
      for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1128
           it != unsatisfied_prereqs.end(); ++it) {
1129
        it->expectation_base()->DescribeLocationTo(os);
1130
1131
1132
1133
1134
        *os << "pre-requisite #" << i++ << "\n";
      }
      *os << "                   (end of pre-requisites)\n";
    } else {
      // This line is here just for completeness' sake.  It will never
1135
      // be executed as currently the ExplainMatchResultTo() function
1136
1137
1138
1139
1140
1141
1142
      // is called only when the mock function call does NOT match the
      // expectation.
      *os << "The call matches the expectation.\n";
    }
  }

  // Returns the action that should be taken for the current invocation.
1143
1144
1145
1146
  const Action<F>& GetCurrentAction(
      const FunctionMockerBase<F>* mocker,
      const ArgumentTuple& args) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1147
1148
1149
1150
1151
1152
    g_gmock_mutex.AssertHeld();
    const int count = call_count();
    Assert(count >= 1, __FILE__, __LINE__,
           "call_count() is <= 0 when GetCurrentAction() is "
           "called - this should never happen.");

1153
    const int action_count = static_cast<int>(untyped_actions_.size());
1154
1155
1156
1157
1158
1159
    if (action_count > 0 && !repeated_action_specified_ &&
        count > action_count) {
      // If there is at least one WillOnce() and no WillRepeatedly(),
      // we warn the user when the WillOnce() clauses ran out.
      ::std::stringstream ss;
      DescribeLocationTo(&ss);
1160
      ss << "Actions ran out in " << source_text() << "...\n"
1161
1162
1163
1164
         << "Called " << count << " times, but only "
         << action_count << " WillOnce()"
         << (action_count == 1 ? " is" : "s are") << " specified - ";
      mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan's avatar
zhanyong.wan committed
1165
      Log(kWarning, ss.str(), 1);
1166
1167
    }

1168
1169
1170
    return count <= action_count ?
        *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
        repeated_action();
1171
1172
1173
1174
1175
1176
1177
  }

  // Given the arguments of a mock function call, if the call will
  // over-saturate this expectation, returns the default action;
  // otherwise, returns the next action in this expectation.  Also
  // describes *what* happened to 'what', and explains *why* Google
  // Mock does it to 'why'.  This method is not const as it calls
1178
1179
  // IncrementCallCount().  A return value of NULL means the default
  // action.
1180
1181
1182
1183
1184
1185
  const Action<F>* GetActionForArguments(
      const FunctionMockerBase<F>* mocker,
      const ArgumentTuple& args,
      ::std::ostream* what,
      ::std::ostream* why)
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1186
1187
1188
1189
1190
1191
1192
1193
    g_gmock_mutex.AssertHeld();
    if (IsSaturated()) {
      // We have an excessive call.
      IncrementCallCount();
      *what << "Mock function called more times than expected - ";
      mocker->DescribeDefaultActionTo(args, what);
      DescribeCallCountTo(why);

1194
1195
1196
1197
      // TODO(wan@google.com): allow the user to control whether
      // unexpected calls should fail immediately or continue using a
      // flag --gmock_unexpected_calls_are_fatal.
      return NULL;
1198
1199
1200
1201
1202
    }

    IncrementCallCount();
    RetireAllPreRequisites();

1203
    if (retires_on_saturation_ && IsSaturated()) {
1204
1205
1206
1207
      Retire();
    }

    // Must be done after IncrementCount()!
1208
    *what << "Mock function call matches " << source_text() <<"...\n";
1209
    return &(GetCurrentAction(mocker, args));
1210
1211
1212
1213
1214
1215
1216
1217
  }

  // All the fields below won't change once the EXPECT_CALL()
  // statement finishes.
  FunctionMockerBase<F>* const owner_;
  ArgumentMatcherTuple matchers_;
  Matcher<const ArgumentTuple&> extra_matcher_;
  Action<F> repeated_action_;
1218
1219

  GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1220
};  // class TypedExpectation
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231

// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
// specifying the default behavior of, or expectation on, a mock
// function.

// Note: class MockSpec really belongs to the ::testing namespace.
// However if we define it in ::testing, MSVC will complain when
// classes in ::testing::internal declare it as a friend class
// template.  To workaround this compiler bug, we define MockSpec in
// ::testing::internal and import it into ::testing.

1232
// Logs a message including file and line number information.
1233
1234
1235
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
                                const char* file, int line,
                                const string& message);
1236

1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
template <typename F>
class MockSpec {
 public:
  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename internal::Function<F>::ArgumentMatcherTuple
      ArgumentMatcherTuple;

  // Constructs a MockSpec object, given the function mocker object
  // that the spec is associated with.
  explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
      : function_mocker_(function_mocker) {}

  // Adds a new default action spec to the function mocker and returns
  // the newly created spec.
1251
  internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1252
      const char* file, int line, const char* obj, const char* call) {
zhanyong.wan's avatar
zhanyong.wan committed
1253
    LogWithLocation(internal::kInfo, file, line,
1254
        string("ON_CALL(") + obj + ", " + call + ") invoked");
1255
    return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1256
1257
1258
1259
  }

  // Adds a new expectation spec to the function mocker and returns
  // the newly created spec.
1260
  internal::TypedExpectation<F>& InternalExpectedAt(
1261
      const char* file, int line, const char* obj, const char* call) {
1262
    const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
zhanyong.wan's avatar
zhanyong.wan committed
1263
    LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1264
1265
    return function_mocker_->AddNewExpectation(
        file, line, source_text, matchers_);
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
  }

 private:
  template <typename Function>
  friend class internal::FunctionMocker;

  void SetMatchers(const ArgumentMatcherTuple& matchers) {
    matchers_ = matchers;
  }

  // The function mocker that owns this spec.
  internal::FunctionMockerBase<F>* const function_mocker_;
  // The argument matchers specified in the spec.
  ArgumentMatcherTuple matchers_;
1280
1281

  GTEST_DISALLOW_ASSIGN_(MockSpec);
1282
1283
1284
1285
1286
1287
1288
1289
};  // class MockSpec

// MSVC warns about using 'this' in base member initializer list, so
// we need to temporarily disable the warning.  We have to do it for
// the entire class to suppress the warning, even though it's about
// the constructor only.

#ifdef _MSC_VER
1290
1291
# pragma warning(push)          // Saves the current warning state.
# pragma warning(disable:4355)  // Temporarily disables warning 4355.
1292
1293
#endif  // _MSV_VER

1294
1295
1296
1297
1298
1299
// C++ treats the void type specially.  For example, you cannot define
// a void-typed variable or pass a void value to a function.
// ActionResultHolder<T> holds a value of type T, where T must be a
// copyable type or void (T doesn't need to be default-constructable).
// It hides the syntactic difference between void and other types, and
// is used to unify the code for invoking both void-returning and
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
// non-void-returning mock functions.

// Untyped base class for ActionResultHolder<T>.
class UntypedActionResultHolderBase {
 public:
  virtual ~UntypedActionResultHolderBase() {}

  // Prints the held value as an action's result to os.
  virtual void PrintAsActionResult(::std::ostream* os) const = 0;
};

// This generic definition is used when T is not void.
1312
template <typename T>
1313
class ActionResultHolder : public UntypedActionResultHolderBase {
1314
 public:
1315
  explicit ActionResultHolder(T a_value) : value_(a_value) {}
1316
1317
1318
1319

  // The compiler-generated copy constructor and assignment operator
  // are exactly what we need, so we don't need to define them.

1320
1321
1322
1323
1324
1325
  // Returns the held value and deletes this object.
  T GetValueAndDelete() const {
    T retval(value_);
    delete this;
    return retval;
  }
1326
1327

  // Prints the held value as an action's result to os.
1328
  virtual void PrintAsActionResult(::std::ostream* os) const {
1329
    *os << "\n          Returns: ";
vladlosev's avatar
vladlosev committed
1330
    // T may be a reference type, so we don't use UniversalPrint().
1331
1332
1333
1334
    UniversalPrinter<T>::Print(value_, os);
  }

  // Performs the given mock function's default action and returns the
1335
1336
1337
1338
1339
  // result in a new-ed ActionResultHolder.
  template <typename F>
  static ActionResultHolder* PerformDefaultAction(
      const FunctionMockerBase<F>* func_mocker,
      const typename Function<F>::ArgumentTuple& args,
1340
      const string& call_description) {
1341
    return new ActionResultHolder(
1342
1343
1344
        func_mocker->PerformDefaultAction(args, call_description));
  }

1345
  // Performs the given action and returns the result in a new-ed
1346
  // ActionResultHolder.
1347
1348
1349
1350
1351
  template <typename F>
  static ActionResultHolder*
  PerformAction(const Action<F>& action,
                const typename Function<F>::ArgumentTuple& args) {
    return new ActionResultHolder(action.Perform(args));
1352
1353
1354
1355
  }

 private:
  T value_;
1356
1357
1358

  // T could be a reference type, so = isn't supported.
  GTEST_DISALLOW_ASSIGN_(ActionResultHolder);
1359
1360
1361
1362
};

// Specialization for T = void.
template <>
1363
class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1364
 public:
1365
1366
1367
1368
1369
1370
1371
1372
1373
  void GetValueAndDelete() const { delete this; }

  virtual void PrintAsActionResult(::std::ostream* /* os */) const {}

  // Performs the given mock function's default action and returns NULL;
  template <typename F>
  static ActionResultHolder* PerformDefaultAction(
      const FunctionMockerBase<F>* func_mocker,
      const typename Function<F>::ArgumentTuple& args,
1374
1375
      const string& call_description) {
    func_mocker->PerformDefaultAction(args, call_description);
1376
    return NULL;
1377
1378
  }

1379
1380
1381
1382
1383
  // Performs the given action and returns NULL.
  template <typename F>
  static ActionResultHolder* PerformAction(
      const Action<F>& action,
      const typename Function<F>::ArgumentTuple& args) {
1384
    action.Perform(args);
1385
    return NULL;
1386
1387
1388
  }
};

1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
// The base of the function mocker class for the given function type.
// We put the methods in this class instead of its child to avoid code
// bloat.
template <typename F>
class FunctionMockerBase : public UntypedFunctionMockerBase {
 public:
  typedef typename Function<F>::Result Result;
  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;

1399
  FunctionMockerBase() : current_spec_(this) {}
1400
1401
1402
1403

  // The destructor verifies that all expectations on this mock
  // function have been satisfied.  If not, it will report Google Test
  // non-fatal failures for the violations.
1404
1405
  virtual ~FunctionMockerBase()
        GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1406
1407
1408
    MutexLock l(&g_gmock_mutex);
    VerifyAndClearExpectationsLocked();
    Mock::UnregisterLocked(this);
1409
    ClearDefaultActionsLocked();
1410
1411
1412
1413
1414
  }

  // Returns the ON_CALL spec that matches this mock function with the
  // given arguments; returns NULL if no matching ON_CALL is found.
  // L = *
1415
  const OnCallSpec<F>* FindOnCallSpec(
1416
      const ArgumentTuple& args) const {
1417
1418
1419
1420
1421
1422
    for (UntypedOnCallSpecs::const_reverse_iterator it
             = untyped_on_call_specs_.rbegin();
         it != untyped_on_call_specs_.rend(); ++it) {
      const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
      if (spec->Matches(args))
        return spec;
1423
1424
1425
1426
1427
    }

    return NULL;
  }

1428
1429
1430
1431
  // Performs the default action of this mock function on the given arguments
  // and returns the result. Asserts with a helpful call descrption if there is
  // no valid return value. This method doesn't depend on the mutable state of
  // this object, and thus can be called concurrently without locking.
1432
  // L = *
1433
1434
  Result PerformDefaultAction(const ArgumentTuple& args,
                              const string& call_description) const {
1435
1436
    const OnCallSpec<F>* const spec =
        this->FindOnCallSpec(args);
1437
1438
1439
1440
1441
1442
1443
    if (spec != NULL) {
      return spec->GetAction().Perform(args);
    }
    Assert(DefaultValue<Result>::Exists(), "", -1,
           call_description + "\n    The mock function has no default action "
           "set, and its return type has no default value set.");
    return DefaultValue<Result>::Get();
1444
1445
  }

1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
  // Performs the default action with the given arguments and returns
  // the action's result.  The call description string will be used in
  // the error message to describe the call in the case the default
  // action fails.  The caller is responsible for deleting the result.
  // L = *
  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
      const void* untyped_args,  // must point to an ArgumentTuple
      const string& call_description) const {
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
    return ResultHolder::PerformDefaultAction(this, args, call_description);
1457
1458
  }

1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
  // Performs the given action with the given arguments and returns
  // the action's result.  The caller is responsible for deleting the
  // result.
  // L = *
  virtual UntypedActionResultHolderBase* UntypedPerformAction(
      const void* untyped_action, const void* untyped_args) const {
    // Make a copy of the action before performing it, in case the
    // action deletes the mock object (and thus deletes itself).
    const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
    return ResultHolder::PerformAction(action, args);
  }

  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
  // clears the ON_CALL()s set on this mock function.
1475
1476
  virtual void ClearDefaultActionsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1477
    g_gmock_mutex.AssertHeld();
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489

    // Deleting our default actions may trigger other mock objects to be
    // deleted, for example if an action contains a reference counted smart
    // pointer to that mock object, and that is the last reference. So if we
    // delete our actions within the context of the global mutex we may deadlock
    // when this method is called again. Instead, make a copy of the set of
    // actions to delete, clear our set within the mutex, and then delete the
    // actions outside of the mutex.
    UntypedOnCallSpecs specs_to_delete;
    untyped_on_call_specs_.swap(specs_to_delete);

    g_gmock_mutex.Unlock();
1490
    for (UntypedOnCallSpecs::const_iterator it =
1491
1492
             specs_to_delete.begin();
         it != specs_to_delete.end(); ++it) {
1493
      delete static_cast<const OnCallSpec<F>*>(*it);
1494
    }
1495
1496
1497
1498

    // Lock the mutex again, since the caller expects it to be locked when we
    // return.
    g_gmock_mutex.Lock();
1499
  }
1500

1501
1502
1503
1504
 protected:
  template <typename Function>
  friend class MockSpec;

1505
1506
  typedef ActionResultHolder<Result> ResultHolder;

1507
1508
1509
  // Returns the result of invoking this mock function with the given
  // arguments.  This function can be safely called from multiple
  // threads concurrently.
1510
1511
  Result InvokeWith(const ArgumentTuple& args)
        GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1512
1513
1514
    return static_cast<const ResultHolder*>(
        this->UntypedInvokeWith(&args))->GetValueAndDelete();
  }
1515
1516

  // Adds and returns a default action spec for this mock function.
1517
  OnCallSpec<F>& AddNewOnCallSpec(
1518
      const char* file, int line,
1519
1520
      const ArgumentMatcherTuple& m)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1521
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1522
1523
1524
    OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
    untyped_on_call_specs_.push_back(on_call_spec);
    return *on_call_spec;
1525
1526
1527
  }

  // Adds and returns an expectation spec for this mock function.
1528
  TypedExpectation<F>& AddNewExpectation(
1529
1530
1531
      const char* file,
      int line,
      const string& source_text,
1532
1533
      const ArgumentMatcherTuple& m)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1534
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1535
1536
1537
1538
    TypedExpectation<F>* const expectation =
        new TypedExpectation<F>(this, file, line, source_text, m);
    const linked_ptr<ExpectationBase> untyped_expectation(expectation);
    untyped_expectations_.push_back(untyped_expectation);
1539
1540
1541
1542

    // Adds this expectation into the implicit sequence if there is one.
    Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
    if (implicit_sequence != NULL) {
1543
      implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1544
1545
1546
1547
1548
1549
1550
1551
    }

    return *expectation;
  }

  // The current spec (either default action spec or expectation spec)
  // being described on this function mocker.
  MockSpec<F>& current_spec() { return current_spec_; }
1552

1553
 private:
1554
  template <typename Func> friend class TypedExpectation;
1555

1556
  // Some utilities needed for implementing UntypedInvokeWith().
1557
1558
1559
1560
1561
1562

  // Describes what default action will be performed for the given
  // arguments.
  // L = *
  void DescribeDefaultActionTo(const ArgumentTuple& args,
                               ::std::ostream* os) const {
1563
    const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1564
1565
1566
1567
1568
1569
1570

    if (spec == NULL) {
      *os << (internal::type_equals<Result, void>::value ?
              "returning directly.\n" :
              "returning default value.\n");
    } else {
      *os << "taking default action specified at:\n"
1571
          << FormatFileLocation(spec->file(), spec->line()) << "\n";
1572
1573
1574
1575
1576
1577
    }
  }

  // Writes a message that the call is uninteresting (i.e. neither
  // explicitly expected nor explicitly unexpected) to the given
  // ostream.
1578
1579
1580
1581
  virtual void UntypedDescribeUninterestingCall(
      const void* untyped_args,
      ::std::ostream* os) const
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1582
1583
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1584
1585
1586
    *os << "Uninteresting mock function call - ";
    DescribeDefaultActionTo(args, os);
    *os << "    Function call: " << Name();
vladlosev's avatar
vladlosev committed
1587
    UniversalPrint(args, os);
1588
1589
  }

1590
1591
1592
1593
1594
1595
1596
  // Returns the expectation that matches the given function arguments
  // (or NULL is there's no match); when a match is found,
  // untyped_action is set to point to the action that should be
  // performed (or NULL if the action is "do default"), and
  // is_excessive is modified to indicate whether the call exceeds the
  // expected number.
  //
1597
1598
1599
1600
1601
1602
1603
1604
1605
  // Critical section: We must find the matching expectation and the
  // corresponding action that needs to be taken in an ATOMIC
  // transaction.  Otherwise another thread may call this mock
  // method in the middle and mess up the state.
  //
  // However, performing the action has to be left out of the critical
  // section.  The reason is that we have no control on what the
  // action does (it can invoke an arbitrary user function or even a
  // mock function) and excessive locking could cause a dead lock.
1606
1607
1608
  virtual const ExpectationBase* UntypedFindMatchingExpectation(
      const void* untyped_args,
      const void** untyped_action, bool* is_excessive,
1609
1610
      ::std::ostream* what, ::std::ostream* why)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1611
1612
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1613
    MutexLock l(&g_gmock_mutex);
1614
1615
    TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
    if (exp == NULL) {  // A match wasn't found.
1616
      this->FormatUnexpectedCallMessageLocked(args, what, why);
1617
      return NULL;
1618
1619
1620
1621
1622
    }

    // This line must be done before calling GetActionForArguments(),
    // which will increment the call count for *exp and thus affect
    // its saturation status.
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
    *is_excessive = exp->IsSaturated();
    const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
    if (action != NULL && action->IsDoDefault())
      action = NULL;  // Normalize "do default" to NULL.
    *untyped_action = action;
    return exp;
  }

  // Prints the given function arguments to the ostream.
  virtual void UntypedPrintArgs(const void* untyped_args,
                                ::std::ostream* os) const {
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
    UniversalPrint(args, os);
1637
1638
1639
1640
  }

  // Returns the expectation that matches the arguments, or NULL if no
  // expectation matches them.
1641
  TypedExpectation<F>* FindMatchingExpectationLocked(
1642
1643
      const ArgumentTuple& args) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1644
    g_gmock_mutex.AssertHeld();
1645
1646
1647
1648
1649
    for (typename UntypedExpectations::const_reverse_iterator it =
             untyped_expectations_.rbegin();
         it != untyped_expectations_.rend(); ++it) {
      TypedExpectation<F>* const exp =
          static_cast<TypedExpectation<F>*>(it->get());
1650
1651
1652
1653
1654
1655
1656
1657
      if (exp->ShouldHandleArguments(args)) {
        return exp;
      }
    }
    return NULL;
  }

  // Returns a message that the arguments don't match any expectation.
1658
1659
1660
1661
1662
  void FormatUnexpectedCallMessageLocked(
      const ArgumentTuple& args,
      ::std::ostream* os,
      ::std::ostream* why) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1663
1664
1665
1666
1667
1668
1669
1670
    g_gmock_mutex.AssertHeld();
    *os << "\nUnexpected mock function call - ";
    DescribeDefaultActionTo(args, os);
    PrintTriedExpectationsLocked(args, why);
  }

  // Prints a list of expectations that have been tried against the
  // current mock function call.
1671
1672
1673
1674
  void PrintTriedExpectationsLocked(
      const ArgumentTuple& args,
      ::std::ostream* why) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1675
    g_gmock_mutex.AssertHeld();
1676
    const int count = static_cast<int>(untyped_expectations_.size());
1677
1678
1679
1680
1681
    *why << "Google Mock tried the following " << count << " "
         << (count == 1 ? "expectation, but it didn't match" :
             "expectations, but none matched")
         << ":\n";
    for (int i = 0; i < count; i++) {
1682
1683
      TypedExpectation<F>* const expectation =
          static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1684
      *why << "\n";
1685
      expectation->DescribeLocationTo(why);
1686
      if (count > 1) {
1687
        *why << "tried expectation #" << i << ": ";
1688
      }
1689
1690
1691
      *why << expectation->source_text() << "...\n";
      expectation->ExplainMatchResultTo(args, why);
      expectation->DescribeCallCountTo(why);
1692
1693
1694
1695
1696
1697
1698
    }
  }

  // The current spec (either default action spec or expectation spec)
  // being described on this function mocker.
  MockSpec<F> current_spec_;

1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
  // There is no generally useful and implementable semantics of
  // copying a mock object, so copying a mock is usually a user error.
  // Thus we disallow copying function mockers.  If the user really
  // wants to copy a mock object, he should implement his own copy
  // operation, for example:
  //
  //   class MockFoo : public Foo {
  //    public:
  //     // Defines a copy constructor explicitly.
  //     MockFoo(const MockFoo& src) {}
  //     ...
  //   };
  GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
1712
1713
1714
};  // class FunctionMockerBase

#ifdef _MSC_VER
1715
# pragma warning(pop)  // Restores the warning state.
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
#endif  // _MSV_VER

// Implements methods of FunctionMockerBase.

// Verifies that all expectations on this mock function have been
// satisfied.  Reports one or more Google Test non-fatal failures and
// returns false if not.

// Reports an uninteresting call (whose description is in msg) in the
// manner specified by 'reaction'.
void ReportUninterestingCall(CallReaction reaction, const string& msg);

}  // namespace internal

// The style guide prohibits "using" statements in a namespace scope
// inside a header file.  However, the MockSpec class template is
// meant to be defined in the ::testing namespace.  The following line
// is just a trick for working around a bug in MSVC 8.0, which cannot
// handle it if we define MockSpec in ::testing.
using internal::MockSpec;

// Const(x) is a convenient function for obtaining a const reference
// to x.  This is useful for setting expectations on an overloaded
// const mock method, e.g.
//
//   class MockFoo : public FooInterface {
//    public:
//     MOCK_METHOD0(Bar, int());
//     MOCK_CONST_METHOD0(Bar, int&());
//   };
//
//   MockFoo foo;
//   // Expects a call to non-const MockFoo::Bar().
//   EXPECT_CALL(foo, Bar());
//   // Expects a call to const MockFoo::Bar().
//   EXPECT_CALL(Const(foo), Bar());
template <typename T>
inline const T& Const(const T& x) { return x; }

1755
1756
1757
1758
// Constructs an Expectation object that references and co-owns exp.
inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
    : expectation_base_(exp.GetHandle().expectation_base()) {}

1759
1760
1761
1762
1763
1764
}  // namespace testing

// A separate macro is required to avoid compile errors when the name
// of the method used in call is a result of macro expansion.
// See CompilesWithMethodNameExpandedFromMacro tests in
// internal/gmock-spec-builders_test.cc for more details.
1765
#define GMOCK_ON_CALL_IMPL_(obj, call) \
1766
1767
    ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
                                                    #obj, #call)
1768
#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
1769

1770
#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
1771
    ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
1772
#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
1773
1774

#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_