gmock-spec-builders.h 71.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
// 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.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
29

30
31
32
33
34
35
36
37
38

// 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))
39
//       .With(multi-argument-matcher)
40
41
//       .WillByDefault(action);
//
42
//  where the .With() clause is optional.
43
44
45
46
47
//
// 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))
48
//       .With(multi-argument-matchers)
49
50
//       .Times(cardinality)
//       .InSequence(sequences)
51
//       .After(expectations)
52
53
54
55
//       .WillOnce(action)
//       .WillRepeatedly(action)
//       .RetiresOnSaturation();
//
56
57
// where all clauses are optional, and .InSequence()/.After()/
// .WillOnce() can appear any number of times.
58

Gennadiy Civil's avatar
 
Gennadiy Civil committed
59
60
// GOOGLETEST_CM0002 DO NOT DELETE

61
62
63
64
65
66
67
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_

#include <map>
#include <set>
#include <sstream>
#include <string>
Abseil Team's avatar
Abseil Team committed
68
#include <utility>
69
#include <vector>
70
71
72
73
74
75
#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"
76

Gennadiy Civil's avatar
Gennadiy Civil committed
77
78
79
80
#if GTEST_HAS_EXCEPTIONS
# include <stdexcept>  // NOLINT
#endif

misterg's avatar
misterg committed
81
82
83
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
/* class A needs to have dll-interface to be used by clients of class B */)

84
85
namespace testing {

86
87
88
89
90
91
// An abstract handle of an expectation.
class Expectation;

// A set of expectation handles.
class ExpectationSet;

92
93
94
95
// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
// and MUST NOT BE USED IN USER CODE!!!
namespace internal {

96
97
// Implements a mock function.
template <typename F> class FunctionMocker;
98
99
100
101

// Base class for expectations.
class ExpectationBase;

102
103
104
// Implements an expectation.
template <typename F> class TypedExpectation;

105
106
107
108
// Helper class for testing the Expectation class template.
class ExpectationTester;

// Base class for function mockers.
109
template <typename F> class FunctionMockerBase;
110
111
112
113
114
115
116
117
118
119
120
121

// 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.
122
GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
123

124
125
126
// Untyped base class for ActionResultHolder<R>.
class UntypedActionResultHolderBase;

127
128
129
// Abstract base class of FunctionMockerBase.  This is the
// type-agnostic part of the function mocker interface.  Its pure
// virtual methods are implemented by FunctionMockerBase.
130
class GTEST_API_ UntypedFunctionMockerBase {
131
 public:
132
133
  UntypedFunctionMockerBase();
  virtual ~UntypedFunctionMockerBase();
134
135
136
137

  // 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.
138
139
  bool VerifyAndClearExpectationsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
140
141

  // Clears the ON_CALL()s set on this mock function.
142
143
  virtual void ClearDefaultActionsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
144
145
146
147
148
149
150
151
152
153
154

  // 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(
Gennadiy Civil's avatar
Gennadiy Civil committed
155
      void* untyped_args, const std::string& call_description) const = 0;
156
157
158
159
160

  // Performs the given action with the given arguments and returns
  // the action's result.
  // L = *
  virtual UntypedActionResultHolderBase* UntypedPerformAction(
Gennadiy Civil's avatar
Gennadiy Civil committed
161
      const void* untyped_action, void* untyped_args) const = 0;
162
163
164
165

  // Writes a message that the call is uninteresting (i.e. neither
  // explicitly expected nor explicitly unexpected) to the given
  // ostream.
166
167
168
169
  virtual void UntypedDescribeUninterestingCall(
      const void* untyped_args,
      ::std::ostream* os) const
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
170
171
172
173
174
175
176
177
178
179

  // 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,
180
181
      ::std::ostream* what, ::std::ostream* why)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
182
183
184
185
186
187
188
189
190

  // 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.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
191
  // FIXME: rename to SetAndRegisterOwner().
192
193
  void RegisterOwner(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
194
195
196
197

  // 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.
198
199
  void SetOwnerAndName(const void* mock_obj, const char* name)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
200
201
202
203

  // Returns the mock object this mock method belongs to.  Must be
  // called after RegisterOwner() or SetOwnerAndName() has been
  // called.
204
205
  const void* MockObject() const
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
206
207
208

  // Returns the name of this mock method.  Must be called after
  // SetOwnerAndName() has been called.
209
210
  const char* Name() const
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
211
212
213
214
215

  // 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.
Gennadiy Civil's avatar
Gennadiy Civil committed
216
217
  UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241

 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.
Gennadiy Civil's avatar
Gennadiy Civil committed
242
243
244
245
246
247
248
249
  //
  // It's undefined behavior to interleave expectations (EXPECT_CALLs
  // or ON_CALLs) and mock function calls.  Also, the order of
  // expectations is important.  Therefore it's a logic race condition
  // to read/write untyped_expectations_ concurrently.  In order for
  // tools like tsan to catch concurrent read/write accesses to
  // untyped_expectations, we deliberately leave accesses to it
  // unprotected.
250
  UntypedExpectations untyped_expectations_;
251
252
};  // class UntypedFunctionMockerBase

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// 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,
271
    kWillByDefault
272
273
274
  };

  // Asserts that the ON_CALL() statement has a certain property.
275
276
  void AssertSpecProperty(bool property,
                          const std::string& failure_message) const {
277
278
279
280
    Assert(property, file_, line_, failure_message);
  }

  // Expects that the ON_CALL() statement has a certain property.
281
282
  void ExpectSpecProperty(bool property,
                          const std::string& failure_message) const {
283
284
285
286
287
288
289
290
291
292
293
294
    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.
295
template <typename F>
296
class OnCallSpec : public UntypedOnCallSpecBase {
297
298
299
300
 public:
  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;

301
  // Constructs an OnCallSpec object from the information inside
302
  // the parenthesis of an ON_CALL() statement.
303
304
305
  OnCallSpec(const char* a_file, int a_line,
             const ArgumentMatcherTuple& matchers)
      : UntypedOnCallSpecBase(a_file, a_line),
306
        matchers_(matchers),
307
308
309
310
        // 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&>).
311
        extra_matcher_(A<const ArgumentTuple&>()) {
312
313
  }

314
  // Implements the .With() clause.
315
  OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
316
    // Makes sure this is called at most once.
317
318
    ExpectSpecProperty(last_clause_ < kWith,
                       ".With() cannot appear "
319
                       "more than once in an ON_CALL().");
320
    last_clause_ = kWith;
321
322
323
324
325
326

    extra_matcher_ = m;
    return *this;
  }

  // Implements the .WillByDefault() clause.
327
  OnCallSpec& WillByDefault(const Action<F>& action) {
328
    ExpectSpecProperty(last_clause_ < kWillByDefault,
329
330
                       ".WillByDefault() must appear "
                       "exactly once in an ON_CALL().");
331
    last_clause_ = kWillByDefault;
332
333
334
335
336
337
338
339
340
341
342
343
344
345

    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 {
346
    AssertSpecProperty(last_clause_ == kWillByDefault,
347
348
349
350
                       ".WillByDefault() must appear exactly "
                       "once in an ON_CALL().");
    return action_;
  }
351

352
353
354
355
 private:
  // The information in statement
  //
  //   ON_CALL(mock_object, Method(matchers))
356
  //       .With(multi-argument-matcher)
357
358
359
360
361
362
363
364
365
366
367
368
  //       .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_;
369
};  // class OnCallSpec
370

zhanyong.wan's avatar
zhanyong.wan committed
371
// Possible reactions on uninteresting calls.
372
enum CallReaction {
zhanyong.wan's avatar
zhanyong.wan committed
373
374
  kAllow,
  kWarn,
375
  kFail,
376
377
378
379
380
};

}  // namespace internal

// Utilities for manipulating mock objects.
381
class GTEST_API_ Mock {
382
383
384
 public:
  // The following public methods can be called concurrently.

385
386
  // Tells Google Mock to ignore mock_obj when checking for leaked
  // mock objects.
387
388
  static void AllowLeak(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
389

390
391
392
  // 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.
393
394
  static bool VerifyAndClearExpectations(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
395
396
397
398

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

402
  // Returns whether the mock was created as a naggy mock (default)
403
404
  static bool IsNaggy(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
405
  // Returns whether the mock was created as a nice mock
406
407
  static bool IsNice(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
408
  // Returns whether the mock was created as a strict mock
409
410
411
  static bool IsStrict(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);

412
 private:
413
414
  friend class internal::UntypedFunctionMockerBase;

415
416
417
418
419
420
  // 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>
421
  friend class NiceMock;
422

zhanyong.wan's avatar
zhanyong.wan committed
423
  template <typename M>
424
  friend class NaggyMock;
zhanyong.wan's avatar
zhanyong.wan committed
425

426
  template <typename M>
427
  friend class StrictMock;
428
429
430

  // Tells Google Mock to allow uninteresting calls on the given mock
  // object.
431
432
  static void AllowUninterestingCalls(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
433
434
435

  // Tells Google Mock to warn the user about uninteresting calls on
  // the given mock object.
436
437
  static void WarnUninterestingCalls(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
438
439
440

  // Tells Google Mock to fail uninteresting calls on the given mock
  // object.
441
442
  static void FailUninterestingCalls(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
443
444
445

  // Tells Google Mock the given mock object is being destroyed and
  // its entry in the call-reaction table should be removed.
446
447
  static void UnregisterCallReaction(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
448
449
450
451

  // 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
452
      const void* mock_obj)
453
          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
454
455
456
457

  // 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.
458
459
  static bool VerifyAndClearExpectationsLocked(void* mock_obj)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
460
461

  // Clears all ON_CALL()s set on the given mock object.
462
463
  static void ClearDefaultActionsLocked(void* mock_obj)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
464
465

  // Registers a mock object and a mock method it owns.
466
467
468
469
  static void Register(
      const void* mock_obj,
      internal::UntypedFunctionMockerBase* mocker)
          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
470

471
472
473
474
  // 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(
475
476
      const void* mock_obj, const char* file, int line)
          GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
477

478
479
480
481
  // 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.
482
483
  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
484
485
};  // class Mock

486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// 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().
501
502
503
504
505
506
//   - 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).
507
class GTEST_API_ Expectation {
508
509
 public:
  // Constructs a null object that doesn't reference any expectation.
510
511
512
  Expectation();

  ~Expectation();
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538

  // 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;
539
  friend class ::testing::internal::UntypedFunctionMockerBase;
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557

  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(
558
      const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635

  // 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_;
};


636
637
638
// 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).
639
class GTEST_API_ Sequence {
640
641
 public:
  // Constructs an empty sequence.
642
  Sequence() : last_expectation_(new Expectation) {}
643
644
645

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

648
 private:
649
650
651
652
653
  // 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_;
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
};  // 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.
680
class GTEST_API_ InSequence {
681
682
683
684
685
686
687
 public:
  InSequence();
  ~InSequence();
 private:
  bool sequence_created_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
688
} GTEST_ATTRIBUTE_UNUSED_;
689
690
691
692
693

namespace internal {

// Points to the implicit sequence introduced by a living InSequence
// object (if any) in the current thread or NULL.
694
GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709

// 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.
710
class GTEST_API_ ExpectationBase {
711
 public:
712
  // source_text is the EXPECT_CALL(...) source that created this Expectation.
713
  ExpectationBase(const char* file, int line, const std::string& source_text);
714
715
716
717
718
719

  virtual ~ExpectationBase();

  // Where in the source file was the expectation spec defined?
  const char* file() const { return file_; }
  int line() const { return line_; }
720
  const char* source_text() const { return source_text_.c_str(); }
721
722
723
724
725
  // 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 {
726
    *os << FormatFileLocation(file(), line()) << " ";
727
728
729
730
  }

  // Describes how many times a function call matching this
  // expectation has occurred.
731
732
  void DescribeCallCountTo(::std::ostream* os) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
733
734
735
736

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

738
 protected:
739
  friend class ::testing::Expectation;
740
  friend class UntypedFunctionMockerBase;
741
742
743

  enum Clause {
    // Don't change the order of the enum members!
744
745
746
747
    kNone,
    kWith,
    kTimes,
    kInSequence,
748
    kAfter,
749
750
    kWillOnce,
    kWillRepeatedly,
751
    kRetiresOnSaturation
752
753
  };

754
755
  typedef std::vector<const void*> UntypedActions;

756
757
758
759
  // Returns an Expectation object that references and co-owns this
  // expectation.
  virtual Expectation GetHandle() = 0;

760
  // Asserts that the EXPECT_CALL() statement has the given property.
761
762
  void AssertSpecProperty(bool property,
                          const std::string& failure_message) const {
763
764
765
766
    Assert(property, file_, line_, failure_message);
  }

  // Expects that the EXPECT_CALL() statement has the given property.
767
768
  void ExpectSpecProperty(bool property,
                          const std::string& failure_message) const {
769
770
771
772
773
774
775
776
777
778
779
780
    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.
781
782
  void set_cardinality(const Cardinality& a_cardinality) {
    cardinality_ = a_cardinality;
783
784
785
786
787
788
789
  }

  // 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.
790
791
  void RetireAllPreRequisites()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
792
793

  // Returns true iff this expectation is retired.
794
795
  bool is_retired() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
796
797
798
799
800
    g_gmock_mutex.AssertHeld();
    return retired_;
  }

  // Retires this expectation.
801
802
  void Retire()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
803
804
805
806
807
    g_gmock_mutex.AssertHeld();
    retired_ = true;
  }

  // Returns true iff this expectation is satisfied.
808
809
  bool IsSatisfied() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
810
811
812
813
814
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSatisfiedByCallCount(call_count_);
  }

  // Returns true iff this expectation is saturated.
815
816
  bool IsSaturated() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
817
818
819
820
821
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSaturatedByCallCount(call_count_);
  }

  // Returns true iff this expectation is over-saturated.
822
823
  bool IsOverSaturated() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
824
825
826
827
828
    g_gmock_mutex.AssertHeld();
    return cardinality().IsOverSaturatedByCallCount(call_count_);
  }

  // Returns true iff all pre-requisites of this expectation are satisfied.
829
830
  bool AllPrerequisitesAreSatisfied() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
831
832

  // Adds unsatisfied pre-requisites of this expectation to 'result'.
833
834
  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
835
836

  // Returns the number this expectation has been invoked.
837
838
  int call_count() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
839
840
841
842
843
    g_gmock_mutex.AssertHeld();
    return call_count_;
  }

  // Increments the number this expectation has been invoked.
844
845
  void IncrementCallCount()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
846
847
848
849
    g_gmock_mutex.AssertHeld();
    call_count_++;
  }

850
851
852
853
  // 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.
854
855
  void CheckActionCountIfNotDone() const
      GTEST_LOCK_EXCLUDED_(mutex_);
856

857
858
859
860
  friend class ::testing::Sequence;
  friend class ::testing::internal::ExpectationTester;

  template <typename Function>
861
  friend class TypedExpectation;
862

863
864
865
  // Implements the .Times() clause.
  void UntypedTimes(const Cardinality& a_cardinality);

866
867
  // This group of fields are part of the spec and won't change after
  // an EXPECT_CALL() statement finishes.
868
869
  const char* file_;          // The file that contains the expectation.
  int line_;                  // The line number of the expectation.
870
  const std::string source_text_;  // The EXPECT_CALL(...) source text.
871
872
873
  // True iff the cardinality is specified explicitly.
  bool cardinality_specified_;
  Cardinality cardinality_;            // The cardinality of the expectation.
874
875
876
877
878
879
880
  // 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_;
881
882
883
884
885

  // 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.
886
887
888
889
890
891
892
  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_.
893
894

  GTEST_DISALLOW_ASSIGN_(ExpectationBase);
895
896
897
898
};  // class ExpectationBase

// Impements an expectation for the given function type.
template <typename F>
899
class TypedExpectation : public ExpectationBase {
900
901
902
903
904
 public:
  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  typedef typename Function<F>::Result Result;

905
906
  TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line,
                   const std::string& a_source_text,
907
                   const ArgumentMatcherTuple& m)
908
      : ExpectationBase(a_file, a_line, a_source_text),
909
910
        owner_(owner),
        matchers_(m),
911
912
913
914
915
        // 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&>()),
916
        repeated_action_(DoDefault()) {}
917

918
  virtual ~TypedExpectation() {
919
920
921
    // Check the validity of the action count if it hasn't been done
    // yet (for example, if the expectation was never used).
    CheckActionCountIfNotDone();
922
923
924
925
    for (UntypedActions::const_iterator it = untyped_actions_.begin();
         it != untyped_actions_.end(); ++it) {
      delete static_cast<const Action<F>*>(*it);
    }
926
927
  }

928
  // Implements the .With() clause.
929
  TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
930
    if (last_clause_ == kWith) {
931
      ExpectSpecProperty(false,
932
                         ".With() cannot appear "
933
934
                         "more than once in an EXPECT_CALL().");
    } else {
935
936
      ExpectSpecProperty(last_clause_ < kWith,
                         ".With() must be the first "
937
938
                         "clause in an EXPECT_CALL().");
    }
939
    last_clause_ = kWith;
940
941

    extra_matcher_ = m;
942
    extra_matcher_specified_ = true;
943
944
945
946
    return *this;
  }

  // Implements the .Times() clause.
947
  TypedExpectation& Times(const Cardinality& a_cardinality) {
948
    ExpectationBase::UntypedTimes(a_cardinality);
949
950
951
952
    return *this;
  }

  // Implements the .Times() clause.
953
  TypedExpectation& Times(int n) {
954
955
956
957
    return Times(Exactly(n));
  }

  // Implements the .InSequence() clause.
958
  TypedExpectation& InSequence(const Sequence& s) {
959
    ExpectSpecProperty(last_clause_ <= kInSequence,
960
961
                       ".InSequence() cannot appear after .After(),"
                       " .WillOnce(), .WillRepeatedly(), or "
962
                       ".RetiresOnSaturation().");
963
    last_clause_ = kInSequence;
964

965
    s.AddExpectation(GetHandle());
966
967
    return *this;
  }
968
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
969
970
    return InSequence(s1).InSequence(s2);
  }
971
972
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3) {
973
974
    return InSequence(s1, s2).InSequence(s3);
  }
975
976
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3, const Sequence& s4) {
977
978
    return InSequence(s1, s2, s3).InSequence(s4);
  }
979
980
981
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3, const Sequence& s4,
                               const Sequence& s5) {
982
983
984
    return InSequence(s1, s2, s3, s4).InSequence(s5);
  }

985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
  // 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);
  }

1015
  // Implements the .WillOnce() clause.
1016
  TypedExpectation& WillOnce(const Action<F>& action) {
1017
    ExpectSpecProperty(last_clause_ <= kWillOnce,
1018
1019
                       ".WillOnce() cannot appear after "
                       ".WillRepeatedly() or .RetiresOnSaturation().");
1020
    last_clause_ = kWillOnce;
1021

1022
    untyped_actions_.push_back(new Action<F>(action));
1023
    if (!cardinality_specified()) {
1024
      set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1025
1026
1027
1028
1029
    }
    return *this;
  }

  // Implements the .WillRepeatedly() clause.
1030
  TypedExpectation& WillRepeatedly(const Action<F>& action) {
1031
    if (last_clause_ == kWillRepeatedly) {
1032
1033
1034
1035
      ExpectSpecProperty(false,
                         ".WillRepeatedly() cannot appear "
                         "more than once in an EXPECT_CALL().");
    } else {
1036
      ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1037
1038
1039
                         ".WillRepeatedly() cannot appear "
                         "after .RetiresOnSaturation().");
    }
1040
    last_clause_ = kWillRepeatedly;
1041
1042
1043
1044
    repeated_action_specified_ = true;

    repeated_action_ = action;
    if (!cardinality_specified()) {
1045
      set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1046
1047
1048
1049
1050
1051
1052
1053
1054
    }

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

  // Implements the .RetiresOnSaturation() clause.
1055
  TypedExpectation& RetiresOnSaturation() {
1056
    ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1057
1058
                       ".RetiresOnSaturation() cannot appear "
                       "more than once.");
1059
    last_clause_ = kRetiresOnSaturation;
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
    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_;
  }

1074
  // Returns the matcher specified by the .With() clause.
1075
1076
1077
1078
1079
1080
1081
  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_; }

1082
1083
1084
  // If this mock method has an extra matcher (i.e. .With(matcher)),
  // describes it to the ostream.
  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
1085
1086
1087
1088
1089
1090
1091
    if (extra_matcher_specified_) {
      *os << "    Expected args: ";
      extra_matcher_.DescribeTo(os);
      *os << "\n";
    }
  }

1092
1093
1094
1095
 private:
  template <typename Function>
  friend class FunctionMockerBase;

1096
1097
1098
1099
1100
1101
  // Returns an Expectation object that references and co-owns this
  // expectation.
  virtual Expectation GetHandle() {
    return owner_->GetHandleOf(this);
  }

1102
1103
1104
1105
1106
  // 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.
1107
1108
  bool Matches(const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1109
1110
1111
1112
1113
    g_gmock_mutex.AssertHeld();
    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  }

  // Returns true iff this expectation should handle the given arguments.
1114
1115
  bool ShouldHandleArguments(const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
    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.
1128
1129
1130
1131
  void ExplainMatchResultTo(
      const ArgumentTuple& args,
      ::std::ostream* os) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1132
1133
1134
1135
1136
1137
1138
    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)) {
1139
        ExplainMatchFailureTupleTo(matchers_, args, os);
1140
      }
zhanyong.wan's avatar
zhanyong.wan committed
1141
1142
      StringMatchResultListener listener;
      if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1143
        *os << "    Expected args: ";
1144
        extra_matcher_.DescribeTo(os);
1145
        *os << "\n           Actual: don't match";
1146

1147
        internal::PrintIfNotEmpty(listener.str(), os);
1148
1149
1150
1151
1152
1153
        *os << "\n";
      }
    } else if (!AllPrerequisitesAreSatisfied()) {
      *os << "         Expected: all pre-requisites are satisfied\n"
          << "           Actual: the following immediate pre-requisites "
          << "are not satisfied:\n";
1154
      ExpectationSet unsatisfied_prereqs;
1155
1156
      FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
      int i = 0;
1157
      for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1158
           it != unsatisfied_prereqs.end(); ++it) {
1159
        it->expectation_base()->DescribeLocationTo(os);
1160
1161
1162
1163
1164
        *os << "pre-requisite #" << i++ << "\n";
      }
      *os << "                   (end of pre-requisites)\n";
    } else {
      // This line is here just for completeness' sake.  It will never
1165
      // be executed as currently the ExplainMatchResultTo() function
1166
1167
1168
1169
1170
1171
1172
      // 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.
1173
1174
1175
1176
  const Action<F>& GetCurrentAction(
      const FunctionMockerBase<F>* mocker,
      const ArgumentTuple& args) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1177
1178
1179
1180
1181
1182
    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.");

1183
    const int action_count = static_cast<int>(untyped_actions_.size());
1184
1185
1186
1187
1188
1189
    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);
1190
      ss << "Actions ran out in " << source_text() << "...\n"
1191
1192
1193
1194
         << "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
1195
      Log(kWarning, ss.str(), 1);
1196
1197
    }

1198
1199
1200
1201
    return count <= action_count
               ? *static_cast<const Action<F>*>(
                     untyped_actions_[static_cast<size_t>(count - 1)])
               : repeated_action();
1202
1203
1204
1205
1206
1207
1208
  }

  // 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
1209
1210
  // IncrementCallCount().  A return value of NULL means the default
  // action.
1211
1212
1213
1214
1215
1216
  const Action<F>* GetActionForArguments(
      const FunctionMockerBase<F>* mocker,
      const ArgumentTuple& args,
      ::std::ostream* what,
      ::std::ostream* why)
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1217
1218
1219
1220
1221
1222
1223
1224
    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);

Gennadiy Civil's avatar
 
Gennadiy Civil committed
1225
      // FIXME: allow the user to control whether
1226
1227
      // unexpected calls should fail immediately or continue using a
      // flag --gmock_unexpected_calls_are_fatal.
1228
      return nullptr;
1229
1230
1231
1232
1233
    }

    IncrementCallCount();
    RetireAllPreRequisites();

1234
    if (retires_on_saturation_ && IsSaturated()) {
1235
1236
1237
1238
      Retire();
    }

    // Must be done after IncrementCount()!
1239
    *what << "Mock function call matches " << source_text() <<"...\n";
1240
    return &(GetCurrentAction(mocker, args));
1241
1242
1243
1244
1245
1246
1247
1248
  }

  // 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_;
1249
1250

  GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1251
};  // class TypedExpectation
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262

// 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.

1263
// Logs a message including file and line number information.
1264
1265
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
                                const char* file, int line,
1266
                                const std::string& message);
1267

1268
1269
1270
1271
1272
1273
1274
1275
1276
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.
Gennadiy Civil's avatar
Gennadiy Civil committed
1277
1278
1279
  MockSpec(internal::FunctionMockerBase<F>* function_mocker,
           const ArgumentMatcherTuple& matchers)
      : function_mocker_(function_mocker), matchers_(matchers) {}
1280
1281
1282

  // Adds a new default action spec to the function mocker and returns
  // the newly created spec.
1283
  internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1284
      const char* file, int line, const char* obj, const char* call) {
zhanyong.wan's avatar
zhanyong.wan committed
1285
    LogWithLocation(internal::kInfo, file, line,
1286
                    std::string("ON_CALL(") + obj + ", " + call + ") invoked");
1287
    return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1288
1289
1290
1291
  }

  // Adds a new expectation spec to the function mocker and returns
  // the newly created spec.
1292
  internal::TypedExpectation<F>& InternalExpectedAt(
1293
      const char* file, int line, const char* obj, const char* call) {
1294
1295
    const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
                                  call + ")");
zhanyong.wan's avatar
zhanyong.wan committed
1296
    LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1297
1298
    return function_mocker_->AddNewExpectation(
        file, line, source_text, matchers_);
1299
1300
  }

1301
1302
1303
1304
1305
1306
1307
  // This operator overload is used to swallow the superfluous parameter list
  // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
  // explanation.
  MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
    return *this;
  }

1308
1309
1310
1311
1312
1313
1314
1315
 private:
  template <typename Function>
  friend class internal::FunctionMocker;

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

  GTEST_DISALLOW_ASSIGN_(MockSpec);
1318
1319
};  // class MockSpec

1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
// Wrapper type for generically holding an ordinary value or lvalue reference.
// If T is not a reference type, it must be copyable or movable.
// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
// T is a move-only value type (which means that it will always be copyable
// if the current platform does not support move semantics).
//
// The primary template defines handling for values, but function header
// comments describe the contract for the whole template (including
// specializations).
template <typename T>
class ReferenceOrValueWrapper {
 public:
  // Constructs a wrapper from the given value/reference.
1333
  explicit ReferenceOrValueWrapper(T value)
Abseil Team's avatar
Abseil Team committed
1334
      : value_(std::move(value)) {
1335
  }
1336
1337
1338
1339

  // Unwraps and returns the underlying value/reference, exactly as
  // originally passed. The behavior of calling this more than once on
  // the same object is unspecified.
Abseil Team's avatar
Abseil Team committed
1340
  T Unwrap() { return std::move(value_); }
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370

  // Provides nondestructive access to the underlying value/reference.
  // Always returns a const reference (more precisely,
  // const RemoveReference<T>&). The behavior of calling this after
  // calling Unwrap on the same object is unspecified.
  const T& Peek() const {
    return value_;
  }

 private:
  T value_;
};

// Specialization for lvalue reference types. See primary template
// for documentation.
template <typename T>
class ReferenceOrValueWrapper<T&> {
 public:
  // Workaround for debatable pass-by-reference lint warning (c-library-team
  // policy precludes NOLINT in this context)
  typedef T& reference;
  explicit ReferenceOrValueWrapper(reference ref)
      : value_ptr_(&ref) {}
  T& Unwrap() { return *value_ptr_; }
  const T& Peek() const { return *value_ptr_; }

 private:
  T* value_ptr_;
};

1371
1372
1373
1374
// 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.
misterg's avatar
misterg committed
1375
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
1376

1377
1378
1379
1380
1381
1382
// 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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
// 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.
1395
template <typename T>
1396
class ActionResultHolder : public UntypedActionResultHolderBase {
1397
 public:
1398
1399
1400
  // Returns the held value. Must not be called more than once.
  T Unwrap() {
    return result_.Unwrap();
1401
  }
1402
1403

  // Prints the held value as an action's result to os.
1404
  virtual void PrintAsActionResult(::std::ostream* os) const {
1405
    *os << "\n          Returns: ";
vladlosev's avatar
vladlosev committed
1406
    // T may be a reference type, so we don't use UniversalPrint().
1407
    UniversalPrinter<T>::Print(result_.Peek(), os);
1408
1409
1410
  }

  // Performs the given mock function's default action and returns the
1411
1412
1413
1414
  // result in a new-ed ActionResultHolder.
  template <typename F>
  static ActionResultHolder* PerformDefaultAction(
      const FunctionMockerBase<F>* func_mocker,
Abseil Team's avatar
Abseil Team committed
1415
      typename Function<F>::ArgumentTuple&& args,
1416
      const std::string& call_description) {
Gennadiy Civil's avatar
Gennadiy Civil committed
1417
    return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
Abseil Team's avatar
Abseil Team committed
1418
        std::move(args), call_description)));
1419
1420
  }

1421
  // Performs the given action and returns the result in a new-ed
1422
  // ActionResultHolder.
1423
  template <typename F>
Gennadiy Civil's avatar
Gennadiy Civil committed
1424
  static ActionResultHolder* PerformAction(
Abseil Team's avatar
Abseil Team committed
1425
      const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
Gennadiy Civil's avatar
Gennadiy Civil committed
1426
    return new ActionResultHolder(
Abseil Team's avatar
Abseil Team committed
1427
        Wrapper(action.Perform(std::move(args))));
1428
1429
1430
  }

 private:
1431
  typedef ReferenceOrValueWrapper<T> Wrapper;
1432

1433
  explicit ActionResultHolder(Wrapper result)
Abseil Team's avatar
Abseil Team committed
1434
      : result_(std::move(result)) {
1435
  }
1436
1437
1438
1439

  Wrapper result_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1440
1441
1442
1443
};

// Specialization for T = void.
template <>
1444
class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1445
 public:
1446
  void Unwrap() { }
1447
1448
1449

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

1450
1451
  // Performs the given mock function's default action and returns ownership
  // of an empty ActionResultHolder*.
1452
1453
1454
  template <typename F>
  static ActionResultHolder* PerformDefaultAction(
      const FunctionMockerBase<F>* func_mocker,
Abseil Team's avatar
Abseil Team committed
1455
      typename Function<F>::ArgumentTuple&& args,
1456
      const std::string& call_description) {
Abseil Team's avatar
Abseil Team committed
1457
    func_mocker->PerformDefaultAction(std::move(args), call_description);
1458
    return new ActionResultHolder;
1459
1460
  }

1461
1462
  // Performs the given action and returns ownership of an empty
  // ActionResultHolder*.
1463
1464
  template <typename F>
  static ActionResultHolder* PerformAction(
Abseil Team's avatar
Abseil Team committed
1465
1466
      const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
    action.Perform(std::move(args));
1467
    return new ActionResultHolder;
1468
  }
1469
1470
1471
1472

 private:
  ActionResultHolder() {}
  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1473
1474
};

1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
// 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;

Gennadiy Civil's avatar
Gennadiy Civil committed
1485
  FunctionMockerBase() {}
1486
1487
1488
1489

  // 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.
1490
1491
  virtual ~FunctionMockerBase()
        GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1492
1493
1494
    MutexLock l(&g_gmock_mutex);
    VerifyAndClearExpectationsLocked();
    Mock::UnregisterLocked(this);
1495
    ClearDefaultActionsLocked();
1496
1497
1498
1499
1500
  }

  // Returns the ON_CALL spec that matches this mock function with the
  // given arguments; returns NULL if no matching ON_CALL is found.
  // L = *
1501
  const OnCallSpec<F>* FindOnCallSpec(
1502
      const ArgumentTuple& args) const {
1503
1504
1505
1506
1507
1508
    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;
1509
1510
    }

1511
    return nullptr;
1512
1513
  }

1514
1515
1516
1517
1518
1519
  // Performs the default action of this mock function on the given
  // arguments and returns the result. Asserts (or throws if
  // exceptions are enabled) 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.
1520
  // L = *
Abseil Team's avatar
Abseil Team committed
1521
1522
  Result PerformDefaultAction(typename Function<F>::ArgumentTuple&& args,
                              const std::string& call_description) const {
1523
1524
    const OnCallSpec<F>* const spec =
        this->FindOnCallSpec(args);
1525
    if (spec != nullptr) {
Abseil Team's avatar
Abseil Team committed
1526
      return spec->GetAction().Perform(std::move(args));
1527
    }
1528
1529
    const std::string message =
        call_description +
1530
1531
1532
1533
1534
1535
1536
1537
1538
        "\n    The mock function has no default action "
        "set, and its return type has no default value set.";
#if GTEST_HAS_EXCEPTIONS
    if (!DefaultValue<Result>::Exists()) {
      throw std::runtime_error(message);
    }
#else
    Assert(DefaultValue<Result>::Exists(), "", -1, message);
#endif
1539
    return DefaultValue<Result>::Get();
1540
1541
  }

1542
1543
1544
1545
1546
1547
  // 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(
Gennadiy Civil's avatar
Gennadiy Civil committed
1548
      void* untyped_args,  // must point to an ArgumentTuple
1549
      const std::string& call_description) const {
Gennadiy Civil's avatar
Gennadiy Civil committed
1550
    ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team's avatar
Abseil Team committed
1551
    return ResultHolder::PerformDefaultAction(this, std::move(*args),
Gennadiy Civil's avatar
Gennadiy Civil committed
1552
                                              call_description);
1553
1554
  }

1555
1556
1557
1558
1559
  // 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(
Gennadiy Civil's avatar
Gennadiy Civil committed
1560
      const void* untyped_action, void* untyped_args) const {
1561
1562
1563
    // 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);
Gennadiy Civil's avatar
Gennadiy Civil committed
1564
    ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team's avatar
Abseil Team committed
1565
    return ResultHolder::PerformAction(action, std::move(*args));
1566
1567
1568
1569
  }

  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
  // clears the ON_CALL()s set on this mock function.
1570
1571
  virtual void ClearDefaultActionsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1572
    g_gmock_mutex.AssertHeld();
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584

    // 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();
1585
    for (UntypedOnCallSpecs::const_iterator it =
1586
1587
             specs_to_delete.begin();
         it != specs_to_delete.end(); ++it) {
1588
      delete static_cast<const OnCallSpec<F>*>(*it);
1589
    }
1590
1591
1592
1593

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

1596
1597
1598
1599
 protected:
  template <typename Function>
  friend class MockSpec;

1600
1601
  typedef ActionResultHolder<Result> ResultHolder;

1602
1603
1604
  // Returns the result of invoking this mock function with the given
  // arguments.  This function can be safely called from multiple
  // threads concurrently.
Abseil Team's avatar
Abseil Team committed
1605
  Result InvokeWith(typename Function<F>::ArgumentTuple&& args)
Gennadiy Civil's avatar
Gennadiy Civil committed
1606
1607
1608
1609
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
    // const_cast is required since in C++98 we still pass ArgumentTuple around
    // by const& instead of rvalue reference.
    void* untyped_args = const_cast<void*>(static_cast<const void*>(&args));
1610
    scoped_ptr<ResultHolder> holder(
Gennadiy Civil's avatar
Gennadiy Civil committed
1611
        DownCast_<ResultHolder*>(this->UntypedInvokeWith(untyped_args)));
1612
    return holder->Unwrap();
1613
  }
1614
1615

  // Adds and returns a default action spec for this mock function.
1616
  OnCallSpec<F>& AddNewOnCallSpec(
1617
      const char* file, int line,
1618
1619
      const ArgumentMatcherTuple& m)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1620
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1621
1622
1623
    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;
1624
1625
1626
  }

  // Adds and returns an expectation spec for this mock function.
1627
1628
1629
1630
  TypedExpectation<F>& AddNewExpectation(const char* file, int line,
                                         const std::string& source_text,
                                         const ArgumentMatcherTuple& m)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1631
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1632
1633
1634
    TypedExpectation<F>* const expectation =
        new TypedExpectation<F>(this, file, line, source_text, m);
    const linked_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civil's avatar
Gennadiy Civil committed
1635
1636
    // See the definition of untyped_expectations_ for why access to
    // it is unprotected here.
1637
    untyped_expectations_.push_back(untyped_expectation);
1638
1639
1640

    // Adds this expectation into the implicit sequence if there is one.
    Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1641
    if (implicit_sequence != nullptr) {
1642
      implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1643
1644
1645
1646
1647
1648
    }

    return *expectation;
  }

 private:
1649
  template <typename Func> friend class TypedExpectation;
1650

1651
  // Some utilities needed for implementing UntypedInvokeWith().
1652
1653
1654
1655
1656
1657

  // Describes what default action will be performed for the given
  // arguments.
  // L = *
  void DescribeDefaultActionTo(const ArgumentTuple& args,
                               ::std::ostream* os) const {
1658
    const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1659

1660
    if (spec == nullptr) {
1661
1662
1663
1664
1665
      *os << (internal::type_equals<Result, void>::value ?
              "returning directly.\n" :
              "returning default value.\n");
    } else {
      *os << "taking default action specified at:\n"
1666
          << FormatFileLocation(spec->file(), spec->line()) << "\n";
1667
1668
1669
1670
1671
1672
    }
  }

  // Writes a message that the call is uninteresting (i.e. neither
  // explicitly expected nor explicitly unexpected) to the given
  // ostream.
1673
1674
1675
1676
  virtual void UntypedDescribeUninterestingCall(
      const void* untyped_args,
      ::std::ostream* os) const
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1677
1678
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1679
1680
1681
    *os << "Uninteresting mock function call - ";
    DescribeDefaultActionTo(args, os);
    *os << "    Function call: " << Name();
vladlosev's avatar
vladlosev committed
1682
    UniversalPrint(args, os);
1683
1684
  }

1685
1686
1687
1688
1689
1690
1691
  // 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.
  //
1692
1693
1694
1695
1696
1697
1698
1699
1700
  // 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.
1701
1702
1703
  virtual const ExpectationBase* UntypedFindMatchingExpectation(
      const void* untyped_args,
      const void** untyped_action, bool* is_excessive,
1704
1705
      ::std::ostream* what, ::std::ostream* why)
          GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1706
1707
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1708
    MutexLock l(&g_gmock_mutex);
1709
    TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1710
    if (exp == nullptr) {  // A match wasn't found.
1711
      this->FormatUnexpectedCallMessageLocked(args, what, why);
1712
      return nullptr;
1713
1714
1715
1716
1717
    }

    // This line must be done before calling GetActionForArguments(),
    // which will increment the call count for *exp and thus affect
    // its saturation status.
1718
1719
    *is_excessive = exp->IsSaturated();
    const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1720
1721
    if (action != nullptr && action->IsDoDefault())
      action = nullptr;  // Normalize "do default" to NULL.
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
    *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);
1732
1733
1734
1735
  }

  // Returns the expectation that matches the arguments, or NULL if no
  // expectation matches them.
1736
  TypedExpectation<F>* FindMatchingExpectationLocked(
1737
1738
      const ArgumentTuple& args) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1739
    g_gmock_mutex.AssertHeld();
Gennadiy Civil's avatar
Gennadiy Civil committed
1740
1741
    // See the definition of untyped_expectations_ for why access to
    // it is unprotected here.
1742
1743
1744
1745
1746
    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());
1747
1748
1749
1750
      if (exp->ShouldHandleArguments(args)) {
        return exp;
      }
    }
1751
    return nullptr;
1752
1753
1754
  }

  // Returns a message that the arguments don't match any expectation.
1755
1756
1757
1758
1759
  void FormatUnexpectedCallMessageLocked(
      const ArgumentTuple& args,
      ::std::ostream* os,
      ::std::ostream* why) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1760
1761
1762
1763
1764
1765
1766
1767
    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.
1768
1769
1770
1771
  void PrintTriedExpectationsLocked(
      const ArgumentTuple& args,
      ::std::ostream* why) const
          GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1772
    g_gmock_mutex.AssertHeld();
1773
    const size_t count = untyped_expectations_.size();
1774
1775
1776
1777
    *why << "Google Mock tried the following " << count << " "
         << (count == 1 ? "expectation, but it didn't match" :
             "expectations, but none matched")
         << ":\n";
1778
    for (size_t i = 0; i < count; i++) {
1779
1780
      TypedExpectation<F>* const expectation =
          static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1781
      *why << "\n";
1782
      expectation->DescribeLocationTo(why);
1783
      if (count > 1) {
1784
        *why << "tried expectation #" << i << ": ";
1785
      }
1786
1787
1788
      *why << expectation->source_text() << "...\n";
      expectation->ExplainMatchResultTo(args, why);
      expectation->DescribeCallCountTo(why);
1789
1790
1791
    }
  }

1792
1793
1794
  // 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
1795
  // wants to copy a mock object, they should implement their own copy
1796
1797
1798
1799
1800
1801
1802
1803
1804
  // operation, for example:
  //
  //   class MockFoo : public Foo {
  //    public:
  //     // Defines a copy constructor explicitly.
  //     MockFoo(const MockFoo& src) {}
  //     ...
  //   };
  GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
1805
1806
};  // class FunctionMockerBase

misterg's avatar
misterg committed
1807
GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4355
1808
1809
1810
1811
1812
1813
1814
1815
1816

// 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'.
1817
void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845

}  // 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; }

1846
1847
1848
1849
// Constructs an Expectation object that references and co-owns exp.
inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
    : expectation_base_(exp.GetHandle().expectation_base()) {}

1850
1851
}  // namespace testing

misterg's avatar
misterg committed
1852
1853
GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251

1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
// Implementation for ON_CALL and EXPECT_CALL macros. 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.
//
// This macro supports statements both with and without parameter matchers. If
// the parameter list is omitted, gMock will accept any parameters, which allows
// tests to be written that don't need to encode the number of method
// parameter. This technique may only be used for non-overloaded methods.
//
//   // These are the same:
1865
1866
//   ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
//   ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1867
1868
//
//   // As are these:
1869
1870
//   ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
//   ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1871
1872
//
//   // Can also specify args if you want, of course:
1873
//   ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1874
1875
//
//   // Overloads work as long as you specify parameters:
1876
1877
//   ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
//   ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1878
1879
//
//   // Oops! Which overload did you want?
1880
//   ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1881
1882
1883
1884
1885
1886
1887
//     => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
//
// How this works: The mock class uses two overloads of the gmock_Method
// expectation setter method plus an operator() overload on the MockSpec object.
// In the matcher list form, the macro expands to:
//
//   // This statement:
1888
//   ON_CALL(mock, TwoArgsMethod(_, 45))...
1889
//
1890
1891
//   // ...expands to:
//   mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1892
1893
1894
//   |-------------v---------------||------------v-------------|
//       invokes first overload        swallowed by operator()
//
1895
1896
//   // ...which is essentially:
//   mock.gmock_TwoArgsMethod(_, 45)...
1897
1898
1899
1900
//
// Whereas the form without a matcher list:
//
//   // This statement:
1901
//   ON_CALL(mock, TwoArgsMethod)...
1902
//
1903
1904
//   // ...expands to:
//   mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1905
1906
1907
//   |-----------------------v--------------------------|
//                 invokes second overload
//
1908
1909
//   // ...which is essentially:
//   mock.gmock_TwoArgsMethod(_, _)...
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
//
// The WithoutMatchers() argument is used to disambiguate overloads and to
// block the caller from accidentally invoking the second overload directly. The
// second argument is an internal type derived from the method signature. The
// failure to disambiguate two overloads of this method in the ON_CALL statement
// is how we block callers from setting expectations on overloaded methods.
#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call)                          \
  ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \
      .Setter(__FILE__, __LINE__, #mock_expr, #call)

#define ON_CALL(obj, call) \
  GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)

#define EXPECT_CALL(obj, call) \
  GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
1925
1926

#endif  // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_