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

58
59
60
// IWYU pragma: private, include "gmock/gmock.h"
// IWYU pragma: friend gmock/.*

Abseil Team's avatar
Abseil Team committed
61
62
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
63

Adam Badura's avatar
Adam Badura committed
64
#include <functional>
65
#include <map>
misterg's avatar
misterg committed
66
#include <memory>
67
68
69
#include <set>
#include <sstream>
#include <string>
70
#include <type_traits>
Abseil Team's avatar
Abseil Team committed
71
#include <utility>
72
#include <vector>
73

74
75
76
77
78
79
#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"
80

Gennadiy Civil's avatar
Gennadiy Civil committed
81
#if GTEST_HAS_EXCEPTIONS
82
#include <stdexcept>  // NOLINT
Gennadiy Civil's avatar
Gennadiy Civil committed
83
84
#endif

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

88
89
namespace testing {

90
91
92
93
94
95
// An abstract handle of an expectation.
class Expectation;

// A set of expectation handles.
class ExpectationSet;

96
97
98
99
// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
// and MUST NOT BE USED IN USER CODE!!!
namespace internal {

100
// Implements a mock function.
101
102
template <typename F>
class FunctionMocker;
103
104
105
106

// Base class for expectations.
class ExpectationBase;

107
// Implements an expectation.
108
109
template <typename F>
class TypedExpectation;
110

111
112
113
// Helper class for testing the Expectation class template.
class ExpectationTester;

Abseil Team's avatar
Abseil Team committed
114
115
116
117
118
119
120
121
// Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
template <typename MockClass>
class NiceMockImpl;
template <typename MockClass>
class StrictMockImpl;
template <typename MockClass>
class NaggyMockImpl;

122
123
124
125
126
127
128
129
130
131
132
// 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.
133
GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
134

135
136
137
// Untyped base class for ActionResultHolder<R>.
class UntypedActionResultHolderBase;

Abseil Team's avatar
Abseil Team committed
138
// Abstract base class of FunctionMocker.  This is the
139
// type-agnostic part of the function mocker interface.  Its pure
Abseil Team's avatar
Abseil Team committed
140
// virtual methods are implemented by FunctionMocker.
141
class GTEST_API_ UntypedFunctionMockerBase {
142
 public:
143
144
  UntypedFunctionMockerBase();
  virtual ~UntypedFunctionMockerBase();
145
146
147
148

  // 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.
149
150
  bool VerifyAndClearExpectationsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
151
152

  // Clears the ON_CALL()s set on this mock function.
153
154
  virtual void ClearDefaultActionsLocked()
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
155
156
157
158
159
160
161
162
163
164
165

  // 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
166
      void* untyped_args, const std::string& call_description) const = 0;
167
168
169
170
171

  // 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
172
      const void* untyped_action, void* untyped_args) const = 0;
173
174
175
176

  // Writes a message that the call is uninteresting (i.e. neither
  // explicitly expected nor explicitly unexpected) to the given
  // ostream.
177
178
179
  virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
                                                ::std::ostream* os) const
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
180
181
182
183
184
185
186
187

  // 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(
188
      const void* untyped_args, const void** untyped_action, bool* is_excessive,
189
      ::std::ostream* what, ::std::ostream* why)
190
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
191
192
193
194
195
196
197
198
199

  // 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.
200
  void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
201
202
203
204

  // 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.
205
206
  void SetOwnerAndName(const void* mock_obj, const char* name)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
207
208
209
210

  // Returns the mock object this mock method belongs to.  Must be
  // called after RegisterOwner() or SetOwnerAndName() has been
  // called.
211
  const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
212
213
214

  // Returns the name of this mock method.  Must be called after
  // SetOwnerAndName() has been called.
215
  const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
216
217
218
219
220

  // 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
221
222
  UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
223
224
225
226

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

misterg's avatar
misterg committed
227
  using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

  // 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
246
247
248
249
250
251
252
253
  //
  // 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.
254
  UntypedExpectations untyped_expectations_;
255
256
};  // class UntypedFunctionMockerBase

257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// 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,
275
    kWillByDefault
276
277
278
  };

  // Asserts that the ON_CALL() statement has a certain property.
279
280
  void AssertSpecProperty(bool property,
                          const std::string& failure_message) const {
281
282
283
284
    Assert(property, file_, line_, failure_message);
  }

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

305
  // Constructs an OnCallSpec object from the information inside
306
  // the parenthesis of an ON_CALL() statement.
307
308
309
  OnCallSpec(const char* a_file, int a_line,
             const ArgumentMatcherTuple& matchers)
      : UntypedOnCallSpecBase(a_file, a_line),
310
        matchers_(matchers),
Abseil Team's avatar
Abseil Team committed
311
312
313
314
        // By default, extra_matcher_ should match anything.  However,
        // we cannot initialize it with _ as that causes ambiguity between
        // Matcher's copy and move constructor for some argument types.
        extra_matcher_(A<const ArgumentTuple&>()) {}
315

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

    extra_matcher_ = m;
    return *this;
  }

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

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

341
  // Returns true if and only if the given arguments match the matchers.
342
343
344
345
346
347
  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 {
348
    AssertSpecProperty(last_clause_ == kWillByDefault,
349
350
351
352
                       ".WillByDefault() must appear exactly "
                       "once in an ON_CALL().");
    return action_;
  }
353

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

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

}  // namespace internal

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

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

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

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

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

414
 private:
415
416
  friend class internal::UntypedFunctionMockerBase;

417
418
419
  // Needed for a function mocker to register itself (so that we know
  // how to clear a mock object).
  template <typename F>
Abseil Team's avatar
Abseil Team committed
420
  friend class internal::FunctionMocker;
421

Abseil Team's avatar
Abseil Team committed
422
423
424
425
426
427
  template <typename MockClass>
  friend class internal::NiceMockImpl;
  template <typename MockClass>
  friend class internal::NaggyMockImpl;
  template <typename MockClass>
  friend class internal::StrictMockImpl;
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(
452
      const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
453
454
455
456

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

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

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

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

476
477
478
  // 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
Abseil Team's avatar
Abseil Team committed
479
  // FunctionMocker.
480
481
  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
482
483
};  // class Mock

484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// 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().
misterg's avatar
misterg committed
499

500
class GTEST_API_ Expectation {
501
502
 public:
  // Constructs a null object that doesn't reference any expectation.
503
  Expectation();
Arthur O'Dwyer's avatar
Arthur O'Dwyer committed
504
505
506
507
  Expectation(Expectation&&) = default;
  Expectation(const Expectation&) = default;
  Expectation& operator=(Expectation&&) = default;
  Expectation& operator=(const Expectation&) = default;
508
  ~Expectation();
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

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

524
525
  // Returns true if and only if rhs references the same expectation as this
  // object does.
526
527
528
529
530
531
532
533
534
535
  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;
536
  friend class ::testing::internal::UntypedFunctionMockerBase;
537
538

  template <typename F>
Abseil Team's avatar
Abseil Team committed
539
  friend class ::testing::internal::FunctionMocker;
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554

  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(
misterg's avatar
misterg committed
555
      const std::shared_ptr<internal::ExpectationBase>& expectation_base);
556
557

  // Returns the expectation this object references.
misterg's avatar
misterg committed
558
  const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
559
560
561
    return expectation_base_;
  }

misterg's avatar
misterg committed
562
563
  // A shared_ptr that co-owns the expectation this handle references.
  std::shared_ptr<internal::ExpectationBase> expectation_base_;
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
};

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

607
608
  // Returns true if and only if rhs contains the same set of Expectation
  // objects as this does.
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
  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_;
};

631
632
633
// 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).
634
class GTEST_API_ Sequence {
635
636
 public:
  // Constructs an empty sequence.
637
  Sequence() : last_expectation_(new Expectation) {}
638
639
640

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

643
 private:
misterg's avatar
misterg committed
644
645
  // The last expectation in this sequence.
  std::shared_ptr<Expectation> last_expectation_;
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
};  // 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.
672
class GTEST_API_ InSequence {
673
674
675
 public:
  InSequence();
  ~InSequence();
676

677
678
679
680
 private:
  bool sequence_created_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);  // NOLINT
681
} GTEST_ATTRIBUTE_UNUSED_;
682
683
684
685
686

namespace internal {

// Points to the implicit sequence introduced by a living InSequence
// object (if any) in the current thread or NULL.
687
GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702

// 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.
703
class GTEST_API_ ExpectationBase {
704
 public:
705
  // source_text is the EXPECT_CALL(...) source that created this Expectation.
706
  ExpectationBase(const char* file, int line, const std::string& source_text);
707
708
709
710
711
712

  virtual ~ExpectationBase();

  // Where in the source file was the expectation spec defined?
  const char* file() const { return file_; }
  int line() const { return line_; }
713
  const char* source_text() const { return source_text_.c_str(); }
714
715
716
717
718
  // 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 {
719
    *os << FormatFileLocation(file(), line()) << " ";
720
721
722
723
  }

  // Describes how many times a function call matching this
  // expectation has occurred.
724
725
  void DescribeCallCountTo(::std::ostream* os) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
726
727
728
729

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

731
 protected:
732
  friend class ::testing::Expectation;
733
  friend class UntypedFunctionMockerBase;
734
735
736

  enum Clause {
    // Don't change the order of the enum members!
737
738
739
740
    kNone,
    kWith,
    kTimes,
    kInSequence,
741
    kAfter,
742
743
    kWillOnce,
    kWillRepeatedly,
744
    kRetiresOnSaturation
745
746
  };

747
748
  typedef std::vector<const void*> UntypedActions;

749
750
751
752
  // Returns an Expectation object that references and co-owns this
  // expectation.
  virtual Expectation GetHandle() = 0;

753
  // Asserts that the EXPECT_CALL() statement has the given property.
754
755
  void AssertSpecProperty(bool property,
                          const std::string& failure_message) const {
756
757
758
759
    Assert(property, file_, line_, failure_message);
  }

  // Expects that the EXPECT_CALL() statement has the given property.
760
761
  void ExpectSpecProperty(bool property,
                          const std::string& failure_message) const {
762
763
764
765
766
767
768
    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);

769
770
  // Returns true if and only if the user specified the cardinality
  // explicitly using a .Times().
771
772
773
  bool cardinality_specified() const { return cardinality_specified_; }

  // Sets the cardinality of this expectation spec.
774
775
  void set_cardinality(const Cardinality& a_cardinality) {
    cardinality_ = a_cardinality;
776
777
778
779
780
781
782
  }

  // 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.
783
  void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
784

785
  // Returns true if and only if this expectation is retired.
786
  bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
787
788
789
790
791
    g_gmock_mutex.AssertHeld();
    return retired_;
  }

  // Retires this expectation.
792
  void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
793
794
795
796
    g_gmock_mutex.AssertHeld();
    retired_ = true;
  }

797
  // Returns true if and only if this expectation is satisfied.
798
  bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
799
800
801
802
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSatisfiedByCallCount(call_count_);
  }

803
  // Returns true if and only if this expectation is saturated.
804
  bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
805
806
807
808
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSaturatedByCallCount(call_count_);
  }

809
  // Returns true if and only if this expectation is over-saturated.
810
  bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
811
812
813
814
    g_gmock_mutex.AssertHeld();
    return cardinality().IsOverSaturatedByCallCount(call_count_);
  }

815
816
  // Returns true if and only if all pre-requisites of this expectation are
  // satisfied.
817
818
  bool AllPrerequisitesAreSatisfied() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
819
820

  // Adds unsatisfied pre-requisites of this expectation to 'result'.
821
822
  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
823
824

  // Returns the number this expectation has been invoked.
825
  int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
826
827
828
829
830
    g_gmock_mutex.AssertHeld();
    return call_count_;
  }

  // Increments the number this expectation has been invoked.
831
  void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
832
833
834
835
    g_gmock_mutex.AssertHeld();
    call_count_++;
  }

836
837
838
839
  // 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.
840
  void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);
841

842
843
844
845
  friend class ::testing::Sequence;
  friend class ::testing::internal::ExpectationTester;

  template <typename Function>
846
  friend class TypedExpectation;
847

848
849
850
  // Implements the .Times() clause.
  void UntypedTimes(const Cardinality& a_cardinality);

851
852
  // This group of fields are part of the spec and won't change after
  // an EXPECT_CALL() statement finishes.
853
854
  const char* file_;               // The file that contains the expectation.
  int line_;                       // The line number of the expectation.
855
  const std::string source_text_;  // The EXPECT_CALL(...) source text.
856
  // True if and only if the cardinality is specified explicitly.
857
  bool cardinality_specified_;
858
  Cardinality cardinality_;  // The cardinality of the expectation.
859
860
  // The immediate pre-requisites (i.e. expectations that must be
  // satisfied before this expectation can be matched) of this
misterg's avatar
misterg committed
861
  // expectation.  We use std::shared_ptr in the set because we want an
862
863
864
865
  // 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_;
866
867
868
869

  // 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.
870
  bool retired_;    // True if and only if this expectation has retired.
871
872
873
874
875
876
  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_.
877
878
  mutable Mutex mutex_;                // Protects action_count_checked_.
};                                     // class ExpectationBase
879

slowy07's avatar
slowy07 committed
880
// Implements an expectation for the given function type.
881
template <typename F>
882
class TypedExpectation : public ExpectationBase {
883
884
885
886
887
 public:
  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  typedef typename Function<F>::Result Result;

Abseil Team's avatar
Abseil Team committed
888
  TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
889
                   const std::string& a_source_text,
890
                   const ArgumentMatcherTuple& m)
891
      : ExpectationBase(a_file, a_line, a_source_text),
892
893
        owner_(owner),
        matchers_(m),
Abseil Team's avatar
Abseil Team committed
894
895
896
897
        // By default, extra_matcher_ should match anything.  However,
        // we cannot initialize it with _ as that causes ambiguity between
        // Matcher's copy and move constructor for some argument types.
        extra_matcher_(A<const ArgumentTuple&>()),
898
        repeated_action_(DoDefault()) {}
899

Abseil Team's avatar
Abseil Team committed
900
  ~TypedExpectation() override {
901
902
903
    // Check the validity of the action count if it hasn't been done
    // yet (for example, if the expectation was never used).
    CheckActionCountIfNotDone();
904
905
906
907
    for (UntypedActions::const_iterator it = untyped_actions_.begin();
         it != untyped_actions_.end(); ++it) {
      delete static_cast<const Action<F>*>(*it);
    }
908
909
  }

910
  // Implements the .With() clause.
911
  TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
912
    if (last_clause_ == kWith) {
913
      ExpectSpecProperty(false,
914
                         ".With() cannot appear "
915
916
                         "more than once in an EXPECT_CALL().");
    } else {
917
918
      ExpectSpecProperty(last_clause_ < kWith,
                         ".With() must be the first "
919
920
                         "clause in an EXPECT_CALL().");
    }
921
    last_clause_ = kWith;
922
923

    extra_matcher_ = m;
924
    extra_matcher_specified_ = true;
925
926
927
928
    return *this;
  }

  // Implements the .Times() clause.
929
  TypedExpectation& Times(const Cardinality& a_cardinality) {
930
    ExpectationBase::UntypedTimes(a_cardinality);
931
932
933
934
    return *this;
  }

  // Implements the .Times() clause.
935
  TypedExpectation& Times(int n) { return Times(Exactly(n)); }
936
937

  // Implements the .InSequence() clause.
938
  TypedExpectation& InSequence(const Sequence& s) {
939
    ExpectSpecProperty(last_clause_ <= kInSequence,
940
941
                       ".InSequence() cannot appear after .After(),"
                       " .WillOnce(), .WillRepeatedly(), or "
942
                       ".RetiresOnSaturation().");
943
    last_clause_ = kInSequence;
944

945
    s.AddExpectation(GetHandle());
946
947
    return *this;
  }
948
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
949
950
    return InSequence(s1).InSequence(s2);
  }
951
952
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3) {
953
954
    return InSequence(s1, s2).InSequence(s3);
  }
955
956
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3, const Sequence& s4) {
957
958
    return InSequence(s1, s2, s3).InSequence(s4);
  }
959
960
961
  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
                               const Sequence& s3, const Sequence& s4,
                               const Sequence& s5) {
962
963
964
    return InSequence(s1, s2, s3, s4).InSequence(s5);
  }

965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
  // 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);
  }

995
996
  // Implements the .WillOnce() clause for copyable actions.
  TypedExpectation& WillOnce(OnceAction<F> once_action) {
997
    ExpectSpecProperty(last_clause_ <= kWillOnce,
998
999
                       ".WillOnce() cannot appear after "
                       ".WillRepeatedly() or .RetiresOnSaturation().");
1000
    last_clause_ = kWillOnce;
1001

1002
1003
1004
    untyped_actions_.push_back(
        new Action<F>(std::move(once_action).ReleaseAction()));

1005
    if (!cardinality_specified()) {
1006
      set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1007
1008
1009
1010
1011
    }
    return *this;
  }

  // Implements the .WillRepeatedly() clause.
1012
  TypedExpectation& WillRepeatedly(const Action<F>& action) {
1013
    if (last_clause_ == kWillRepeatedly) {
1014
1015
1016
1017
      ExpectSpecProperty(false,
                         ".WillRepeatedly() cannot appear "
                         "more than once in an EXPECT_CALL().");
    } else {
1018
      ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1019
1020
1021
                         ".WillRepeatedly() cannot appear "
                         "after .RetiresOnSaturation().");
    }
1022
    last_clause_ = kWillRepeatedly;
1023
1024
1025
1026
    repeated_action_specified_ = true;

    repeated_action_ = action;
    if (!cardinality_specified()) {
1027
      set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1028
1029
1030
1031
1032
1033
1034
1035
1036
    }

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

  // Implements the .RetiresOnSaturation() clause.
1037
  TypedExpectation& RetiresOnSaturation() {
1038
    ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1039
1040
                       ".RetiresOnSaturation() cannot appear "
                       "more than once.");
1041
    last_clause_ = kRetiresOnSaturation;
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
    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.
1052
  const ArgumentMatcherTuple& matchers() const { return matchers_; }
1053

1054
  // Returns the matcher specified by the .With() clause.
1055
1056
1057
1058
1059
1060
1061
  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_; }

1062
1063
  // If this mock method has an extra matcher (i.e. .With(matcher)),
  // describes it to the ostream.
Abseil Team's avatar
Abseil Team committed
1064
  void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
1065
1066
1067
1068
1069
1070
1071
    if (extra_matcher_specified_) {
      *os << "    Expected args: ";
      extra_matcher_.DescribeTo(os);
      *os << "\n";
    }
  }

1072
1073
 private:
  template <typename Function>
Abseil Team's avatar
Abseil Team committed
1074
  friend class FunctionMocker;
1075

1076
1077
  // Returns an Expectation object that references and co-owns this
  // expectation.
Abseil Team's avatar
Abseil Team committed
1078
  Expectation GetHandle() override { return owner_->GetHandleOf(this); }
1079

1080
1081
1082
1083
  // The following methods will be called only after the EXPECT_CALL()
  // statement finishes and when the current thread holds
  // g_gmock_mutex.

1084
  // Returns true if and only if this expectation matches the given arguments.
1085
1086
  bool Matches(const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1087
1088
1089
1090
    g_gmock_mutex.AssertHeld();
    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  }

1091
1092
  // Returns true if and only if this expectation should handle the given
  // arguments.
1093
1094
  bool ShouldHandleArguments(const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
    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.
1107
1108
  void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1109
1110
1111
1112
1113
1114
1115
    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)) {
1116
        ExplainMatchFailureTupleTo(matchers_, args, os);
1117
      }
zhanyong.wan's avatar
zhanyong.wan committed
1118
1119
      StringMatchResultListener listener;
      if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1120
        *os << "    Expected args: ";
1121
        extra_matcher_.DescribeTo(os);
1122
        *os << "\n           Actual: don't match";
1123

1124
        internal::PrintIfNotEmpty(listener.str(), os);
1125
1126
1127
1128
1129
1130
        *os << "\n";
      }
    } else if (!AllPrerequisitesAreSatisfied()) {
      *os << "         Expected: all pre-requisites are satisfied\n"
          << "           Actual: the following immediate pre-requisites "
          << "are not satisfied:\n";
1131
      ExpectationSet unsatisfied_prereqs;
1132
1133
      FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
      int i = 0;
1134
      for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1135
           it != unsatisfied_prereqs.end(); ++it) {
1136
        it->expectation_base()->DescribeLocationTo(os);
1137
1138
1139
1140
1141
        *os << "pre-requisite #" << i++ << "\n";
      }
      *os << "                   (end of pre-requisites)\n";
    } else {
      // This line is here just for completeness' sake.  It will never
1142
      // be executed as currently the ExplainMatchResultTo() function
1143
1144
1145
1146
1147
1148
1149
      // 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.
Abseil Team's avatar
Abseil Team committed
1150
1151
1152
  const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
                                    const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1153
1154
1155
1156
1157
1158
    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.");

1159
    const int action_count = static_cast<int>(untyped_actions_.size());
1160
1161
1162
1163
1164
1165
    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);
1166
      ss << "Actions ran out in " << source_text() << "...\n"
1167
1168
1169
         << "Called " << count << " times, but only " << action_count
         << " WillOnce()" << (action_count == 1 ? " is" : "s are")
         << " specified - ";
1170
      mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan's avatar
zhanyong.wan committed
1171
      Log(kWarning, ss.str(), 1);
1172
1173
    }

1174
1175
1176
1177
    return count <= action_count
               ? *static_cast<const Action<F>*>(
                     untyped_actions_[static_cast<size_t>(count - 1)])
               : repeated_action();
1178
1179
1180
1181
1182
1183
1184
  }

  // 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
1185
1186
  // IncrementCallCount().  A return value of NULL means the default
  // action.
Abseil Team's avatar
Abseil Team committed
1187
1188
1189
1190
1191
  const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
                                         const ArgumentTuple& args,
                                         ::std::ostream* what,
                                         ::std::ostream* why)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1192
1193
1194
1195
1196
1197
1198
1199
    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);

1200
      return nullptr;
1201
1202
1203
1204
1205
    }

    IncrementCallCount();
    RetireAllPreRequisites();

1206
    if (retires_on_saturation_ && IsSaturated()) {
1207
1208
1209
1210
      Retire();
    }

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

  // All the fields below won't change once the EXPECT_CALL()
  // statement finishes.
Abseil Team's avatar
Abseil Team committed
1217
  FunctionMocker<F>* const owner_;
1218
1219
1220
  ArgumentMatcherTuple matchers_;
  Matcher<const ArgumentTuple&> extra_matcher_;
  Action<F> repeated_action_;
1221
1222

  GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1223
};  // class TypedExpectation
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234

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

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

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

  // Constructs a MockSpec object, given the function mocker object
  // that the spec is associated with.
Abseil Team's avatar
Abseil Team committed
1249
  MockSpec(internal::FunctionMocker<F>* function_mocker,
Gennadiy Civil's avatar
Gennadiy Civil committed
1250
1251
           const ArgumentMatcherTuple& matchers)
      : function_mocker_(function_mocker), matchers_(matchers) {}
1252
1253
1254

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

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

1275
1276
1277
1278
1279
1280
1281
  // 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;
  }

1282
1283
1284
1285
1286
 private:
  template <typename Function>
  friend class internal::FunctionMocker;

  // The function mocker that owns this spec.
Abseil Team's avatar
Abseil Team committed
1287
  internal::FunctionMocker<F>* const function_mocker_;
1288
1289
1290
1291
  // The argument matchers specified in the spec.
  ArgumentMatcherTuple matchers_;
};  // class MockSpec

1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
// 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.
1305
  explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
1306
1307
1308
1309

  // 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
1310
  T Unwrap() { return std::move(value_); }
1311
1312
1313

  // Provides nondestructive access to the underlying value/reference.
  // Always returns a const reference (more precisely,
kuzkry's avatar
kuzkry committed
1314
1315
  // const std::add_lvalue_reference<T>::type). The behavior of calling this
  // after calling Unwrap on the same object is unspecified.
1316
  const T& Peek() const { return value_; }
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329

 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;
1330
  explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
1331
1332
1333
1334
1335
1336
1337
  T& Unwrap() { return *value_ptr_; }
  const T& Peek() const { return *value_ptr_; }

 private:
  T* value_ptr_;
};

1338
1339
1340
1341
1342
1343
// 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
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
// 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.
1356
template <typename T>
1357
class ActionResultHolder : public UntypedActionResultHolderBase {
1358
 public:
1359
  // Returns the held value. Must not be called more than once.
1360
  T Unwrap() { return result_.Unwrap(); }
1361
1362

  // Prints the held value as an action's result to os.
Abseil Team's avatar
Abseil Team committed
1363
  void PrintAsActionResult(::std::ostream* os) const override {
1364
    *os << "\n          Returns: ";
vladlosev's avatar
vladlosev committed
1365
    // T may be a reference type, so we don't use UniversalPrint().
1366
    UniversalPrinter<T>::Print(result_.Peek(), os);
1367
1368
1369
  }

  // Performs the given mock function's default action and returns the
1370
1371
1372
  // result in a new-ed ActionResultHolder.
  template <typename F>
  static ActionResultHolder* PerformDefaultAction(
Abseil Team's avatar
Abseil Team committed
1373
      const FunctionMocker<F>* func_mocker,
Abseil Team's avatar
Abseil Team committed
1374
      typename Function<F>::ArgumentTuple&& args,
1375
      const std::string& call_description) {
1376
1377
    return new ActionResultHolder(Wrapper(
        func_mocker->PerformDefaultAction(std::move(args), call_description)));
1378
1379
  }

1380
  // Performs the given action and returns the result in a new-ed
1381
  // ActionResultHolder.
1382
  template <typename F>
Gennadiy Civil's avatar
Gennadiy Civil committed
1383
  static ActionResultHolder* PerformAction(
Abseil Team's avatar
Abseil Team committed
1384
      const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
1385
    return new ActionResultHolder(Wrapper(action.Perform(std::move(args))));
1386
1387
1388
  }

 private:
1389
  typedef ReferenceOrValueWrapper<T> Wrapper;
1390

1391
  explicit ActionResultHolder(Wrapper result) : result_(std::move(result)) {}
1392
1393
1394
1395

  Wrapper result_;

  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1396
1397
1398
1399
};

// Specialization for T = void.
template <>
1400
class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1401
 public:
1402
  void Unwrap() {}
1403

Abseil Team's avatar
Abseil Team committed
1404
  void PrintAsActionResult(::std::ostream* /* os */) const override {}
1405

1406
1407
  // Performs the given mock function's default action and returns ownership
  // of an empty ActionResultHolder*.
1408
1409
  template <typename F>
  static ActionResultHolder* PerformDefaultAction(
Abseil Team's avatar
Abseil Team committed
1410
      const FunctionMocker<F>* func_mocker,
Abseil Team's avatar
Abseil Team committed
1411
      typename Function<F>::ArgumentTuple&& args,
1412
      const std::string& call_description) {
Abseil Team's avatar
Abseil Team committed
1413
    func_mocker->PerformDefaultAction(std::move(args), call_description);
1414
    return new ActionResultHolder;
1415
1416
  }

1417
1418
  // Performs the given action and returns ownership of an empty
  // ActionResultHolder*.
1419
1420
  template <typename F>
  static ActionResultHolder* PerformAction(
Abseil Team's avatar
Abseil Team committed
1421
1422
      const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
    action.Perform(std::move(args));
1423
    return new ActionResultHolder;
1424
  }
1425
1426
1427
1428

 private:
  ActionResultHolder() {}
  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1429
1430
};

1431
template <typename F>
Abseil Team's avatar
Abseil Team committed
1432
1433
1434
class FunctionMocker;

template <typename R, typename... Args>
Abseil Team's avatar
Abseil Team committed
1435
class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
Abseil Team's avatar
Abseil Team committed
1436
1437
  using F = R(Args...);

1438
 public:
Abseil Team's avatar
Abseil Team committed
1439
1440
1441
  using Result = R;
  using ArgumentTuple = std::tuple<Args...>;
  using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1442

Abseil Team's avatar
Abseil Team committed
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
  FunctionMocker() {}

  // 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, they should implement their own copy
  // operation, for example:
  //
  //   class MockFoo : public Foo {
  //    public:
  //     // Defines a copy constructor explicitly.
  //     MockFoo(const MockFoo& src) {}
  //     ...
  //   };
  FunctionMocker(const FunctionMocker&) = delete;
  FunctionMocker& operator=(const FunctionMocker&) = delete;
1459
1460
1461
1462

  // 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.
Abseil Team's avatar
Abseil Team committed
1463
  ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1464
1465
1466
    MutexLock l(&g_gmock_mutex);
    VerifyAndClearExpectationsLocked();
    Mock::UnregisterLocked(this);
1467
    ClearDefaultActionsLocked();
1468
1469
1470
1471
1472
  }

  // Returns the ON_CALL spec that matches this mock function with the
  // given arguments; returns NULL if no matching ON_CALL is found.
  // L = *
1473
1474
1475
  const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {
    for (UntypedOnCallSpecs::const_reverse_iterator it =
             untyped_on_call_specs_.rbegin();
1476
1477
         it != untyped_on_call_specs_.rend(); ++it) {
      const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1478
      if (spec->Matches(args)) return spec;
1479
1480
    }

1481
    return nullptr;
1482
1483
  }

1484
1485
  // Performs the default action of this mock function on the given
  // arguments and returns the result. Asserts (or throws if
1486
  // exceptions are enabled) with a helpful call description if there
1487
1488
1489
  // 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.
1490
  // L = *
Abseil Team's avatar
Abseil Team committed
1491
  Result PerformDefaultAction(ArgumentTuple&& args,
Abseil Team's avatar
Abseil Team committed
1492
                              const std::string& call_description) const {
1493
    const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);
1494
    if (spec != nullptr) {
Abseil Team's avatar
Abseil Team committed
1495
      return spec->GetAction().Perform(std::move(args));
1496
    }
1497
1498
    const std::string message =
        call_description +
1499
1500
1501
1502
1503
1504
1505
1506
1507
        "\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
1508
    return DefaultValue<Result>::Get();
1509
1510
  }

1511
1512
1513
1514
1515
  // 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 = *
Abseil Team's avatar
Abseil Team committed
1516
  UntypedActionResultHolderBase* UntypedPerformDefaultAction(
Gennadiy Civil's avatar
Gennadiy Civil committed
1517
      void* untyped_args,  // must point to an ArgumentTuple
Abseil Team's avatar
Abseil Team committed
1518
      const std::string& call_description) const override {
Gennadiy Civil's avatar
Gennadiy Civil committed
1519
    ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team's avatar
Abseil Team committed
1520
    return ResultHolder::PerformDefaultAction(this, std::move(*args),
Gennadiy Civil's avatar
Gennadiy Civil committed
1521
                                              call_description);
1522
1523
  }

1524
1525
1526
1527
  // Performs the given action with the given arguments and returns
  // the action's result.  The caller is responsible for deleting the
  // result.
  // L = *
Abseil Team's avatar
Abseil Team committed
1528
1529
  UntypedActionResultHolderBase* UntypedPerformAction(
      const void* untyped_action, void* untyped_args) const override {
1530
1531
1532
    // 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
1533
    ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
Abseil Team's avatar
Abseil Team committed
1534
    return ResultHolder::PerformAction(action, std::move(*args));
1535
1536
1537
1538
  }

  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
  // clears the ON_CALL()s set on this mock function.
Abseil Team's avatar
Abseil Team committed
1539
  void ClearDefaultActionsLocked() override
1540
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1541
    g_gmock_mutex.AssertHeld();
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553

    // 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();
1554
    for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
1555
         it != specs_to_delete.end(); ++it) {
1556
      delete static_cast<const OnCallSpec<F>*>(*it);
1557
    }
1558
1559
1560
1561

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

1564
1565
1566
  // 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
1567
1568
1569
1570
  Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
    ArgumentTuple tuple(std::forward<Args>(args)...);
    std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
        this->UntypedInvokeWith(static_cast<void*>(&tuple))));
1571
    return holder->Unwrap();
1572
  }
1573

Abseil Team's avatar
Abseil Team committed
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
  MockSpec<F> With(Matcher<Args>... m) {
    return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
  }

 protected:
  template <typename Function>
  friend class MockSpec;

  typedef ActionResultHolder<Result> ResultHolder;

1584
  // Adds and returns a default action spec for this mock function.
1585
1586
1587
  OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
                                  const ArgumentMatcherTuple& m)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1588
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1589
1590
1591
    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;
1592
1593
1594
  }

  // Adds and returns an expectation spec for this mock function.
1595
1596
1597
1598
  TypedExpectation<F>& AddNewExpectation(const char* file, int line,
                                         const std::string& source_text,
                                         const ArgumentMatcherTuple& m)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1599
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1600
1601
    TypedExpectation<F>* const expectation =
        new TypedExpectation<F>(this, file, line, source_text, m);
misterg's avatar
misterg committed
1602
    const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civil's avatar
Gennadiy Civil committed
1603
1604
    // See the definition of untyped_expectations_ for why access to
    // it is unprotected here.
1605
    untyped_expectations_.push_back(untyped_expectation);
1606
1607
1608

    // Adds this expectation into the implicit sequence if there is one.
    Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1609
    if (implicit_sequence != nullptr) {
1610
      implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1611
1612
1613
1614
1615
1616
    }

    return *expectation;
  }

 private:
1617
1618
  template <typename Func>
  friend class TypedExpectation;
1619

1620
  // Some utilities needed for implementing UntypedInvokeWith().
1621
1622
1623
1624
1625
1626

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

1629
    if (spec == nullptr) {
1630
1631
      *os << (std::is_void<Result>::value ? "returning directly.\n"
                                          : "returning default value.\n");
1632
1633
    } else {
      *os << "taking default action specified at:\n"
1634
          << FormatFileLocation(spec->file(), spec->line()) << "\n";
1635
1636
1637
1638
1639
1640
    }
  }

  // Writes a message that the call is uninteresting (i.e. neither
  // explicitly expected nor explicitly unexpected) to the given
  // ostream.
Abseil Team's avatar
Abseil Team committed
1641
1642
1643
  void UntypedDescribeUninterestingCall(const void* untyped_args,
                                        ::std::ostream* os) const override
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1644
1645
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1646
1647
1648
    *os << "Uninteresting mock function call - ";
    DescribeDefaultActionTo(args, os);
    *os << "    Function call: " << Name();
vladlosev's avatar
vladlosev committed
1649
    UniversalPrint(args, os);
1650
1651
  }

1652
1653
1654
1655
1656
1657
1658
  // 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.
  //
1659
1660
1661
1662
1663
1664
1665
1666
1667
  // 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.
Abseil Team's avatar
Abseil Team committed
1668
1669
1670
1671
  const ExpectationBase* UntypedFindMatchingExpectation(
      const void* untyped_args, const void** untyped_action, bool* is_excessive,
      ::std::ostream* what, ::std::ostream* why) override
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1672
1673
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1674
    MutexLock l(&g_gmock_mutex);
1675
    TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1676
    if (exp == nullptr) {  // A match wasn't found.
1677
      this->FormatUnexpectedCallMessageLocked(args, what, why);
1678
      return nullptr;
1679
1680
1681
1682
1683
    }

    // This line must be done before calling GetActionForArguments(),
    // which will increment the call count for *exp and thus affect
    // its saturation status.
1684
1685
    *is_excessive = exp->IsSaturated();
    const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1686
1687
    if (action != nullptr && action->IsDoDefault())
      action = nullptr;  // Normalize "do default" to NULL.
1688
1689
1690
1691
1692
    *untyped_action = action;
    return exp;
  }

  // Prints the given function arguments to the ostream.
Abseil Team's avatar
Abseil Team committed
1693
1694
  void UntypedPrintArgs(const void* untyped_args,
                        ::std::ostream* os) const override {
1695
1696
1697
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
    UniversalPrint(args, os);
1698
1699
1700
1701
  }

  // Returns the expectation that matches the arguments, or NULL if no
  // expectation matches them.
1702
1703
  TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)
      const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1704
    g_gmock_mutex.AssertHeld();
Gennadiy Civil's avatar
Gennadiy Civil committed
1705
1706
    // See the definition of untyped_expectations_ for why access to
    // it is unprotected here.
1707
1708
1709
1710
1711
    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());
1712
1713
1714
1715
      if (exp->ShouldHandleArguments(args)) {
        return exp;
      }
    }
1716
    return nullptr;
1717
1718
1719
  }

  // Returns a message that the arguments don't match any expectation.
1720
1721
1722
1723
  void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
                                         ::std::ostream* os,
                                         ::std::ostream* why) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1724
1725
1726
1727
1728
1729
1730
1731
    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.
1732
1733
1734
  void PrintTriedExpectationsLocked(const ArgumentTuple& args,
                                    ::std::ostream* why) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1735
    g_gmock_mutex.AssertHeld();
1736
    const size_t count = untyped_expectations_.size();
1737
    *why << "Google Mock tried the following " << count << " "
1738
1739
         << (count == 1 ? "expectation, but it didn't match"
                        : "expectations, but none matched")
1740
         << ":\n";
1741
    for (size_t i = 0; i < count; i++) {
1742
1743
      TypedExpectation<F>* const expectation =
          static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1744
      *why << "\n";
1745
      expectation->DescribeLocationTo(why);
1746
      if (count > 1) {
1747
        *why << "tried expectation #" << i << ": ";
1748
      }
1749
1750
1751
      *why << expectation->source_text() << "...\n";
      expectation->ExplainMatchResultTo(args, why);
      expectation->DescribeCallCountTo(why);
1752
1753
    }
  }
Abseil Team's avatar
Abseil Team committed
1754
};  // class FunctionMocker
1755
1756
1757

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

}  // namespace internal

1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
namespace internal {

template <typename F>
class MockFunction;

template <typename R, typename... Args>
class MockFunction<R(Args...)> {
 public:
  MockFunction(const MockFunction&) = delete;
  MockFunction& operator=(const MockFunction&) = delete;

  std::function<R(Args...)> AsStdFunction() {
    return [this](Args... args) -> R {
      return this->Call(std::forward<Args>(args)...);
    };
  }

  // Implementation detail: the expansion of the MOCK_METHOD macro.
  R Call(Args... args) {
    mock_.SetOwnerAndName(this, "Call");
    return mock_.Invoke(std::forward<Args>(args)...);
  }

  MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
    mock_.RegisterOwner(this);
    return mock_.With(std::move(m)...);
  }

1790
  MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
    return this->gmock_Call(::testing::A<Args>()...);
  }

 protected:
  MockFunction() = default;
  ~MockFunction() = default;

 private:
  FunctionMocker<R(Args...)> mock_;
};

/*
The SignatureOf<F> struct is a meta-function returning function signature
corresponding to the provided F argument.

It makes use of MockFunction easier by allowing it to accept more F arguments
than just function signatures.

Abseil Team's avatar
Abseil Team committed
1809
1810
1811
Specializations provided here cover a signature type itself and any template
that can be parameterized with a signature, including std::function and
boost::function.
1812
1813
*/

Abseil Team's avatar
Abseil Team committed
1814
template <typename F, typename = void>
1815
1816
1817
1818
1819
1820
1821
struct SignatureOf;

template <typename R, typename... Args>
struct SignatureOf<R(Args...)> {
  using type = R(Args...);
};

Abseil Team's avatar
Abseil Team committed
1822
1823
1824
1825
template <template <typename> class C, typename F>
struct SignatureOf<C<F>,
                   typename std::enable_if<std::is_function<F>::value>::type>
    : SignatureOf<F> {};
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836

template <typename F>
using SignatureOfT = typename SignatureOf<F>::type;

}  // namespace internal

// A MockFunction<F> type has one mock method whose type is
// internal::SignatureOfT<F>.  It is useful when you just want your
// test code to emit some messages and have Google Mock verify the
// right messages are sent (and perhaps at the right times).  For
// example, if you are exercising code:
Abseil Team's avatar
Abseil Team committed
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
//
//   Foo(1);
//   Foo(2);
//   Foo(3);
//
// and want to verify that Foo(1) and Foo(3) both invoke
// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
//
// TEST(FooTest, InvokesBarCorrectly) {
//   MyMock mock;
//   MockFunction<void(string check_point_name)> check;
//   {
//     InSequence s;
//
//     EXPECT_CALL(mock, Bar("a"));
//     EXPECT_CALL(check, Call("1"));
//     EXPECT_CALL(check, Call("2"));
//     EXPECT_CALL(mock, Bar("a"));
//   }
//   Foo(1);
//   check.Call("1");
//   Foo(2);
//   check.Call("2");
//   Foo(3);
// }
//
// The expectation spec says that the first Bar("a") must happen
// before check point "1", the second Bar("a") must happen after check
// point "2", and nothing should happen between the two check
// points. The explicit check points make it easy to tell which
// Bar("a") is called by which call to Foo().
//
// MockFunction<F> can also be used to exercise code that accepts
1870
1871
1872
// std::function<internal::SignatureOfT<F>> callbacks. To do so, use
// AsStdFunction() method to create std::function proxy forwarding to
// original object's Call. Example:
Abseil Team's avatar
Abseil Team committed
1873
1874
1875
1876
1877
1878
//
// TEST(FooTest, RunsCallbackWithBarArgument) {
//   MockFunction<int(string)> callback;
//   EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
//   Foo(callback.AsStdFunction());
// }
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
//
// The internal::SignatureOfT<F> indirection allows to use other types
// than just function signature type. This is typically useful when
// providing a mock for a predefined std::function type. Example:
//
// using FilterPredicate = std::function<bool(string)>;
// void MyFilterAlgorithm(FilterPredicate predicate);
//
// TEST(FooTest, FilterPredicateAlwaysAccepts) {
//   MockFunction<FilterPredicate> predicateMock;
//   EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
//   MyFilterAlgorithm(predicateMock.AsStdFunction());
// }
Abseil Team's avatar
Abseil Team committed
1892
template <typename F>
1893
1894
class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
  using Base = internal::MockFunction<internal::SignatureOfT<F>>;
Abseil Team's avatar
Abseil Team committed
1895
1896

 public:
1897
  using Base::Base;
Abseil Team's avatar
Abseil Team committed
1898
1899
};

1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
// 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>
1923
1924
1925
inline const T& Const(const T& x) {
  return x;
}
1926

1927
1928
1929
1930
// Constructs an Expectation object that references and co-owns exp.
inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
    : expectation_base_(exp.GetHandle().expectation_base()) {}

1931
1932
}  // namespace testing

misterg's avatar
misterg committed
1933
1934
GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251

1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
// 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:
1946
1947
//   ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
//   ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1948
1949
//
//   // As are these:
1950
1951
//   ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
//   ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1952
1953
//
//   // Can also specify args if you want, of course:
1954
//   ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1955
1956
//
//   // Overloads work as long as you specify parameters:
1957
1958
//   ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
//   ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1959
1960
//
//   // Oops! Which overload did you want?
1961
//   ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1962
1963
1964
1965
1966
1967
1968
//     => 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:
1969
//   ON_CALL(mock, TwoArgsMethod(_, 45))...
1970
//
1971
1972
//   // ...expands to:
//   mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1973
1974
1975
//   |-------------v---------------||------------v-------------|
//       invokes first overload        swallowed by operator()
//
1976
1977
//   // ...which is essentially:
//   mock.gmock_TwoArgsMethod(_, 45)...
1978
1979
1980
1981
//
// Whereas the form without a matcher list:
//
//   // This statement:
1982
//   ON_CALL(mock, TwoArgsMethod)...
1983
//
1984
1985
//   // ...expands to:
//   mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1986
1987
1988
//   |-----------------------v--------------------------|
//                 invokes second overload
//
1989
1990
//   // ...which is essentially:
//   mock.gmock_TwoArgsMethod(_, _)...
1991
1992
1993
1994
1995
1996
//
// 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.
1997
1998
1999
#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call)                    \
  ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
                             nullptr)                                   \
2000
2001
2002
2003
2004
2005
2006
      .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)
2007

Abseil Team's avatar
Abseil Team committed
2008
#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_