"mace-bench/3rdparty/SevenNet/sevenn/nn/__init__.py" did not exist on "251f5af2c202731f3ca89cd91b68a1725254a0ff"
gmock-spec-builders.h 79 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

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

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

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

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

89
90
namespace testing {

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

// A set of expectation handles.
class ExpectationSet;

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

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

// Base class for expectations.
class ExpectationBase;

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

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

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

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

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

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

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

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

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

  // 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(
172
      const void* untyped_args, const void** untyped_action, bool* is_excessive,
173
      ::std::ostream* what, ::std::ostream* why)
174
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
175
176
177
178
179
180
181
182
183

  // 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.
184
  void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
185
186
187
188

  // 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.
189
190
  void SetOwnerAndName(const void* mock_obj, const char* name)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
191
192
193
194

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

  // Returns the name of this mock method.  Must be called after
  // SetOwnerAndName() has been called.
199
  const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
200
201
202
203

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

misterg's avatar
misterg committed
204
  using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

  // 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
223
224
225
226
227
228
229
230
  //
  // 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.
231
  UntypedExpectations untyped_expectations_;
232
233
};  // class UntypedFunctionMockerBase

234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// 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,
252
    kWillByDefault
253
254
255
  };

  // Asserts that the ON_CALL() statement has a certain property.
256
257
  void AssertSpecProperty(bool property,
                          const std::string& failure_message) const {
258
259
260
261
    Assert(property, file_, line_, failure_message);
  }

  // Expects that the ON_CALL() statement has a certain property.
262
263
  void ExpectSpecProperty(bool property,
                          const std::string& failure_message) const {
264
265
266
267
268
269
270
271
272
273
274
275
    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.
276
template <typename F>
277
class OnCallSpec : public UntypedOnCallSpecBase {
278
279
280
281
 public:
  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;

282
  // Constructs an OnCallSpec object from the information inside
283
  // the parenthesis of an ON_CALL() statement.
284
285
286
  OnCallSpec(const char* a_file, int a_line,
             const ArgumentMatcherTuple& matchers)
      : UntypedOnCallSpecBase(a_file, a_line),
287
        matchers_(matchers),
Abseil Team's avatar
Abseil Team committed
288
289
290
291
        // 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&>()) {}
292

293
  // Implements the .With() clause.
294
  OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
295
    // Makes sure this is called at most once.
296
297
    ExpectSpecProperty(last_clause_ < kWith,
                       ".With() cannot appear "
298
                       "more than once in an ON_CALL().");
299
    last_clause_ = kWith;
300
301
302
303
304
305

    extra_matcher_ = m;
    return *this;
  }

  // Implements the .WillByDefault() clause.
306
  OnCallSpec& WillByDefault(const Action<F>& action) {
307
    ExpectSpecProperty(last_clause_ < kWillByDefault,
308
309
                       ".WillByDefault() must appear "
                       "exactly once in an ON_CALL().");
310
    last_clause_ = kWillByDefault;
311
312
313
314
315
316
317

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

318
  // Returns true if and only if the given arguments match the matchers.
319
320
321
322
323
324
  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 {
325
    AssertSpecProperty(last_clause_ == kWillByDefault,
326
327
328
329
                       ".WillByDefault() must appear exactly "
                       "once in an ON_CALL().");
    return action_;
  }
330

331
332
333
334
 private:
  // The information in statement
  //
  //   ON_CALL(mock_object, Method(matchers))
335
  //       .With(multi-argument-matcher)
336
337
338
339
340
341
342
343
344
345
346
347
  //       .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_;
348
};  // class OnCallSpec
349

zhanyong.wan's avatar
zhanyong.wan committed
350
// Possible reactions on uninteresting calls.
351
enum CallReaction {
zhanyong.wan's avatar
zhanyong.wan committed
352
353
  kAllow,
  kWarn,
354
  kFail,
355
356
357
358
359
};

}  // namespace internal

// Utilities for manipulating mock objects.
360
class GTEST_API_ Mock {
361
362
363
 public:
  // The following public methods can be called concurrently.

364
365
  // Tells Google Mock to ignore mock_obj when checking for leaked
  // mock objects.
366
367
  static void AllowLeak(const void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
368

369
370
371
  // 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.
372
373
  static bool VerifyAndClearExpectations(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
374
375

  // Verifies all expectations on the given mock object and clears its
376
  // default actions and expectations.  Returns true if and only if the
377
  // verification was successful.
378
379
  static bool VerifyAndClear(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
380

381
  // Returns whether the mock was created as a naggy mock (default)
382
383
  static bool IsNaggy(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
384
  // Returns whether the mock was created as a nice mock
385
386
  static bool IsNice(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
387
  // Returns whether the mock was created as a strict mock
388
389
390
  static bool IsStrict(void* mock_obj)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);

391
 private:
392
393
  friend class internal::UntypedFunctionMockerBase;

394
395
396
  // 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
397
  friend class internal::FunctionMocker;
398

Abseil Team's avatar
Abseil Team committed
399
400
401
402
403
404
  template <typename MockClass>
  friend class internal::NiceMockImpl;
  template <typename MockClass>
  friend class internal::NaggyMockImpl;
  template <typename MockClass>
  friend class internal::StrictMockImpl;
405
406
407

  // Tells Google Mock to allow uninteresting calls on the given mock
  // object.
408
  static void AllowUninterestingCalls(uintptr_t mock_obj)
409
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
410
411
412

  // Tells Google Mock to warn the user about uninteresting calls on
  // the given mock object.
413
  static void WarnUninterestingCalls(uintptr_t mock_obj)
414
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
415
416
417

  // Tells Google Mock to fail uninteresting calls on the given mock
  // object.
418
  static void FailUninterestingCalls(uintptr_t mock_obj)
419
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
420
421
422

  // Tells Google Mock the given mock object is being destroyed and
  // its entry in the call-reaction table should be removed.
423
  static void UnregisterCallReaction(uintptr_t mock_obj)
424
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
425
426
427
428

  // Returns the reaction Google Mock will have on uninteresting calls
  // made on the given mock object.
  static internal::CallReaction GetReactionOnUninterestingCalls(
429
      const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
430
431
432
433

  // 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.
434
435
  static bool VerifyAndClearExpectationsLocked(void* mock_obj)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
436
437

  // Clears all ON_CALL()s set on the given mock object.
438
439
  static void ClearDefaultActionsLocked(void* mock_obj)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
440
441

  // Registers a mock object and a mock method it owns.
442
443
444
  static void Register(const void* mock_obj,
                       internal::UntypedFunctionMockerBase* mocker)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
445

446
447
448
  // 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.
449
450
451
  static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,
                                              const char* file, int line)
      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
452

453
454
455
  // 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
456
  // FunctionMocker.
457
458
  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
459
460
};  // class Mock

461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// 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
476

477
class GTEST_API_ Expectation {
478
479
 public:
  // Constructs a null object that doesn't reference any expectation.
480
  Expectation();
Arthur O'Dwyer's avatar
Arthur O'Dwyer committed
481
482
483
484
  Expectation(Expectation&&) = default;
  Expectation(const Expectation&) = default;
  Expectation& operator=(Expectation&&) = default;
  Expectation& operator=(const Expectation&) = default;
485
  ~Expectation();
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

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

501
502
  // Returns true if and only if rhs references the same expectation as this
  // object does.
503
504
505
506
507
508
509
510
511
512
  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;
513
  friend class ::testing::internal::UntypedFunctionMockerBase;
514
515

  template <typename F>
Abseil Team's avatar
Abseil Team committed
516
  friend class ::testing::internal::FunctionMocker;
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531

  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
532
      const std::shared_ptr<internal::ExpectationBase>& expectation_base);
533
534

  // Returns the expectation this object references.
misterg's avatar
misterg committed
535
  const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
536
537
538
    return expectation_base_;
  }

misterg's avatar
misterg committed
539
540
  // A shared_ptr that co-owns the expectation this handle references.
  std::shared_ptr<internal::ExpectationBase> expectation_base_;
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
};

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

584
585
  // Returns true if and only if rhs contains the same set of Expectation
  // objects as this does.
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
  bool operator==(const ExpectationSet& rhs) const {
    return expectations_ == rhs.expectations_;
  }

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

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

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

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

 private:
  Expectation::Set expectations_;
};

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

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

620
 private:
misterg's avatar
misterg committed
621
622
  // The last expectation in this sequence.
  std::shared_ptr<Expectation> last_expectation_;
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
};  // 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.
649
class GTEST_API_ InSequence {
650
651
652
 public:
  InSequence();
  ~InSequence();
653

654
655
656
 private:
  bool sequence_created_;

657
658
  InSequence(const InSequence&) = delete;
  InSequence& operator=(const InSequence&) = delete;
659
} GTEST_ATTRIBUTE_UNUSED_;
660
661
662
663
664

namespace internal {

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

// 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.
681
class GTEST_API_ ExpectationBase {
682
 public:
683
  // source_text is the EXPECT_CALL(...) source that created this Expectation.
684
  ExpectationBase(const char* file, int line, const std::string& source_text);
685
686
687
688
689
690

  virtual ~ExpectationBase();

  // Where in the source file was the expectation spec defined?
  const char* file() const { return file_; }
  int line() const { return line_; }
691
  const char* source_text() const { return source_text_.c_str(); }
692
693
694
695
696
  // 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 {
697
    *os << FormatFileLocation(file(), line()) << " ";
698
699
700
701
  }

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

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

709
710
711
712
713
714
  // Do not rely on this for correctness.
  // This is only for making human-readable test output easier to understand.
  void UntypedDescription(std::string description) {
    description_ = std::move(description);
  }

715
 protected:
716
  friend class ::testing::Expectation;
717
  friend class UntypedFunctionMockerBase;
718
719
720

  enum Clause {
    // Don't change the order of the enum members!
721
722
723
724
    kNone,
    kWith,
    kTimes,
    kInSequence,
725
    kAfter,
726
727
    kWillOnce,
    kWillRepeatedly,
728
    kRetiresOnSaturation
729
730
  };

731
732
  typedef std::vector<const void*> UntypedActions;

733
734
735
736
  // Returns an Expectation object that references and co-owns this
  // expectation.
  virtual Expectation GetHandle() = 0;

737
  // Asserts that the EXPECT_CALL() statement has the given property.
738
739
  void AssertSpecProperty(bool property,
                          const std::string& failure_message) const {
740
741
742
743
    Assert(property, file_, line_, failure_message);
  }

  // Expects that the EXPECT_CALL() statement has the given property.
744
745
  void ExpectSpecProperty(bool property,
                          const std::string& failure_message) const {
746
747
748
749
750
751
752
    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);

753
754
  // Returns true if and only if the user specified the cardinality
  // explicitly using a .Times().
755
756
757
  bool cardinality_specified() const { return cardinality_specified_; }

  // Sets the cardinality of this expectation spec.
758
759
  void set_cardinality(const Cardinality& a_cardinality) {
    cardinality_ = a_cardinality;
760
761
762
763
764
765
766
  }

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

769
  // Returns true if and only if this expectation is retired.
770
  bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
771
772
773
774
775
    g_gmock_mutex.AssertHeld();
    return retired_;
  }

  // Retires this expectation.
776
  void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
777
778
779
780
    g_gmock_mutex.AssertHeld();
    retired_ = true;
  }

781
782
783
  // Returns a human-readable description of this expectation.
  // Do not rely on this for correctness. It is only for human readability.
  const std::string& GetDescription() const { return description_; }
784

785
  // Returns true if and only if this expectation is satisfied.
786
  bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
787
788
789
790
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSatisfiedByCallCount(call_count_);
  }

791
  // Returns true if and only if this expectation is saturated.
792
  bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
793
794
795
796
    g_gmock_mutex.AssertHeld();
    return cardinality().IsSaturatedByCallCount(call_count_);
  }

797
  // Returns true if and only if this expectation is over-saturated.
798
  bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
799
800
801
802
    g_gmock_mutex.AssertHeld();
    return cardinality().IsOverSaturatedByCallCount(call_count_);
  }

803
804
  // Returns true if and only if all pre-requisites of this expectation are
  // satisfied.
805
806
  bool AllPrerequisitesAreSatisfied() const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
807
808

  // Adds unsatisfied pre-requisites of this expectation to 'result'.
809
810
  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
811
812

  // Returns the number this expectation has been invoked.
813
  int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
814
815
816
817
818
    g_gmock_mutex.AssertHeld();
    return call_count_;
  }

  // Increments the number this expectation has been invoked.
819
  void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
820
821
822
823
    g_gmock_mutex.AssertHeld();
    call_count_++;
  }

824
825
826
827
  // 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.
828
  void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);
829

830
831
832
833
  friend class ::testing::Sequence;
  friend class ::testing::internal::ExpectationTester;

  template <typename Function>
834
  friend class TypedExpectation;
835

836
837
838
  // Implements the .Times() clause.
  void UntypedTimes(const Cardinality& a_cardinality);

839
840
  // This group of fields are part of the spec and won't change after
  // an EXPECT_CALL() statement finishes.
841
842
  const char* file_;               // The file that contains the expectation.
  int line_;                       // The line number of the expectation.
843
  const std::string source_text_;  // The EXPECT_CALL(...) source text.
844
  std::string description_;        // User-readable name for the expectation.
845
  // True if and only if the cardinality is specified explicitly.
846
  bool cardinality_specified_;
847
  Cardinality cardinality_;  // The cardinality of the expectation.
848
849
  // The immediate pre-requisites (i.e. expectations that must be
  // satisfied before this expectation can be matched) of this
misterg's avatar
misterg committed
850
  // expectation.  We use std::shared_ptr in the set because we want an
851
852
853
854
  // 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_;
855
856
857
858

  // 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.
859
  bool retired_;    // True if and only if this expectation has retired.
860
861
862
863
864
865
  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_.
866
867
  mutable Mutex mutex_;                // Protects action_count_checked_.
};                                     // class ExpectationBase
868
869

template <typename F>
870
871
872
873
874
875
876
877
class TypedExpectation;

// Implements an expectation for the given function type.
template <typename R, typename... Args>
class TypedExpectation<R(Args...)> : public ExpectationBase {
 private:
  using F = R(Args...);

878
879
880
881
882
 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
883
  TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
884
                   const std::string& a_source_text,
885
                   const ArgumentMatcherTuple& m)
886
      : ExpectationBase(a_file, a_line, a_source_text),
887
888
        owner_(owner),
        matchers_(m),
Abseil Team's avatar
Abseil Team committed
889
890
891
892
        // 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&>()),
893
        repeated_action_(DoDefault()) {}
894

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

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

    extra_matcher_ = m;
919
    extra_matcher_specified_ = true;
920
921
922
    return *this;
  }

923
924
925
926
  // Do not rely on this for correctness.
  // This is only for making human-readable test output easier to understand.
  TypedExpectation& Description(std::string name) {
    ExpectationBase::UntypedDescription(std::move(name));
927
928
929
    return *this;
  }

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

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

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

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

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
995
996
  // 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);
  }

997
998
  // Preferred, type-safe overload: consume anything that can be directly
  // converted to a OnceAction, except for Action<F> objects themselves.
999
  TypedExpectation& WillOnce(OnceAction<F> once_action) {
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
    // Call the overload below, smuggling the OnceAction as a copyable callable.
    // We know this is safe because a WillOnce action will not be called more
    // than once.
    return WillOnce(Action<F>(ActionAdaptor{
        std::make_shared<OnceAction<F>>(std::move(once_action)),
    }));
  }

  // Fallback overload: accept Action<F> objects and those actions that define
  // `operator Action<F>` but not `operator OnceAction<F>`.
  //
  // This is templated in order to cause the overload above to be preferred
  // when the input is convertible to either type.
  template <int&... ExplicitArgumentBarrier, typename = void>
  TypedExpectation& WillOnce(Action<F> action) {
1015
    ExpectSpecProperty(last_clause_ <= kWillOnce,
1016
1017
                       ".WillOnce() cannot appear after "
                       ".WillRepeatedly() or .RetiresOnSaturation().");
1018
    last_clause_ = kWillOnce;
1019

1020
    untyped_actions_.push_back(new Action<F>(std::move(action)));
1021

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

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

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

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

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

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

1079
1080
  // If this mock method has an extra matcher (i.e. .With(matcher)),
  // describes it to the ostream.
Abseil Team's avatar
Abseil Team committed
1081
  void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
1082
1083
1084
1085
1086
1087
1088
    if (extra_matcher_specified_) {
      *os << "    Expected args: ";
      extra_matcher_.DescribeTo(os);
      *os << "\n";
    }
  }

1089
1090
 private:
  template <typename Function>
Abseil Team's avatar
Abseil Team committed
1091
  friend class FunctionMocker;
1092

1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
  // An adaptor that turns a OneAction<F> into something compatible with
  // Action<F>. Must be called at most once.
  struct ActionAdaptor {
    std::shared_ptr<OnceAction<R(Args...)>> once_action;

    R operator()(Args&&... args) const {
      return std::move(*once_action).Call(std::forward<Args>(args)...);
    }
  };

1103
1104
  // Returns an Expectation object that references and co-owns this
  // expectation.
Abseil Team's avatar
Abseil Team committed
1105
  Expectation GetHandle() override { return owner_->GetHandleOf(this); }
1106

1107
1108
1109
1110
  // The following methods will be called only after the EXPECT_CALL()
  // statement finishes and when the current thread holds
  // g_gmock_mutex.

1111
  // Returns true if and only if this expectation matches the given arguments.
1112
1113
  bool Matches(const ArgumentTuple& args) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1114
1115
1116
1117
    g_gmock_mutex.AssertHeld();
    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  }

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

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

1186
    const int action_count = static_cast<int>(untyped_actions_.size());
1187
1188
1189
1190
1191
1192
    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);
1193
      ss << "Actions ran out in " << source_text() << "...\n"
1194
1195
1196
         << "Called " << count << " times, but only " << action_count
         << " WillOnce()" << (action_count == 1 ? " is" : "s are")
         << " specified - ";
1197
      mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan's avatar
zhanyong.wan committed
1198
      Log(kWarning, ss.str(), 1);
1199
1200
    }

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

  // 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
1212
1213
  // IncrementCallCount().  A return value of NULL means the default
  // action.
Abseil Team's avatar
Abseil Team committed
1214
1215
1216
1217
1218
  const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
                                         const ArgumentTuple& args,
                                         ::std::ostream* what,
                                         ::std::ostream* why)
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1219
    g_gmock_mutex.AssertHeld();
1220
    const ::std::string& expectation_description = GetDescription();
1221
1222
1223
    if (IsSaturated()) {
      // We have an excessive call.
      IncrementCallCount();
1224
1225
1226
      *what << "Mock function ";
      if (!expectation_description.empty()) {
        *what << "\"" << expectation_description << "\" ";
1227
      }
1228
      *what << "called more times than expected - ";
1229
1230
1231
      mocker->DescribeDefaultActionTo(args, what);
      DescribeCallCountTo(why);

1232
      return nullptr;
1233
1234
1235
1236
1237
    }

    IncrementCallCount();
    RetireAllPreRequisites();

1238
    if (retires_on_saturation_ && IsSaturated()) {
1239
1240
1241
1242
      Retire();
    }

    // Must be done after IncrementCount()!
1243
1244
1245
    *what << "Mock function ";
    if (!expectation_description.empty()) {
      *what << "\"" << expectation_description << "\" ";
1246
    }
1247
    *what << "call matches " << source_text() << "...\n";
1248
    return &(GetCurrentAction(mocker, args));
1249
1250
1251
1252
  }

  // All the fields below won't change once the EXPECT_CALL()
  // statement finishes.
Abseil Team's avatar
Abseil Team committed
1253
  FunctionMocker<F>* const owner_;
1254
1255
1256
  ArgumentMatcherTuple matchers_;
  Matcher<const ArgumentTuple&> extra_matcher_;
  Action<F> repeated_action_;
1257

1258
1259
  TypedExpectation(const TypedExpectation&) = delete;
  TypedExpectation& operator=(const TypedExpectation&) = delete;
1260
};  // class TypedExpectation
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271

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

1272
// Logs a message including file and line number information.
1273
1274
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
                                const char* file, int line,
1275
                                const std::string& message);
1276

1277
1278
1279
1280
template <typename F>
class MockSpec {
 public:
  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1281
1282
  typedef
      typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1283
1284
1285

  // Constructs a MockSpec object, given the function mocker object
  // that the spec is associated with.
Abseil Team's avatar
Abseil Team committed
1286
  MockSpec(internal::FunctionMocker<F>* function_mocker,
Gennadiy Civil's avatar
Gennadiy Civil committed
1287
1288
           const ArgumentMatcherTuple& matchers)
      : function_mocker_(function_mocker), matchers_(matchers) {}
1289
1290
1291

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

  // Adds a new expectation spec to the function mocker and returns
  // the newly created spec.
1302
1303
1304
  internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,
                                                    const char* obj,
                                                    const char* call) {
1305
1306
    const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
                                  call + ")");
zhanyong.wan's avatar
zhanyong.wan committed
1307
    LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1308
1309
    return function_mocker_->AddNewExpectation(file, line, source_text,
                                               matchers_);
1310
1311
  }

1312
1313
1314
1315
1316
1317
1318
  // 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;
  }

1319
1320
1321
1322
1323
 private:
  template <typename Function>
  friend class internal::FunctionMocker;

  // The function mocker that owns this spec.
Abseil Team's avatar
Abseil Team committed
1324
  internal::FunctionMocker<F>* const function_mocker_;
1325
1326
1327
1328
  // The argument matchers specified in the spec.
  ArgumentMatcherTuple matchers_;
};  // class MockSpec

1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
// 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.
1342
  explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
1343
1344
1345
1346

  // 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
1347
  T Unwrap() { return std::move(value_); }
1348
1349
1350

  // Provides nondestructive access to the underlying value/reference.
  // Always returns a const reference (more precisely,
kuzkry's avatar
kuzkry committed
1351
1352
  // const std::add_lvalue_reference<T>::type). The behavior of calling this
  // after calling Unwrap on the same object is unspecified.
1353
  const T& Peek() const { return value_; }
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366

 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;
1367
  explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
1368
1369
1370
1371
1372
1373
1374
  T& Unwrap() { return *value_ptr_; }
  const T& Peek() const { return *value_ptr_; }

 private:
  T* value_ptr_;
};

1375
// Prints the held value as an action's result to os.
1376
template <typename T>
1377
1378
1379
1380
1381
void PrintAsActionResult(const T& result, std::ostream& os) {
  os << "\n          Returns: ";
  // T may be a reference type, so we don't use UniversalPrint().
  UniversalPrinter<T>::Print(result, &os);
}
1382

1383
1384
1385
1386
// Reports an uninteresting call (whose description is in msg) in the
// manner specified by 'reaction'.
GTEST_API_ void ReportUninterestingCall(CallReaction reaction,
                                        const std::string& msg);
1387

1388
1389
// A generic RAII type that runs a user-provided function in its destructor.
class Cleanup final {
1390
 public:
1391
1392
  explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}
  ~Cleanup() { f_(); }
1393
1394

 private:
1395
  std::function<void()> f_;
1396
1397
};

1398
template <typename F>
Abseil Team's avatar
Abseil Team committed
1399
1400
1401
class FunctionMocker;

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

1405
 public:
Abseil Team's avatar
Abseil Team committed
1406
1407
1408
  using Result = R;
  using ArgumentTuple = std::tuple<Args...>;
  using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1409

Abseil Team's avatar
Abseil Team committed
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
  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;
1426
1427
1428
1429

  // 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
1430
  ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1431
1432
1433
    MutexLock l(&g_gmock_mutex);
    VerifyAndClearExpectationsLocked();
    Mock::UnregisterLocked(this);
1434
    ClearDefaultActionsLocked();
1435
1436
1437
1438
1439
  }

  // Returns the ON_CALL spec that matches this mock function with the
  // given arguments; returns NULL if no matching ON_CALL is found.
  // L = *
1440
1441
1442
  const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {
    for (UntypedOnCallSpecs::const_reverse_iterator it =
             untyped_on_call_specs_.rbegin();
1443
1444
         it != untyped_on_call_specs_.rend(); ++it) {
      const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1445
      if (spec->Matches(args)) return spec;
1446
1447
    }

1448
    return nullptr;
1449
1450
  }

1451
1452
  // Performs the default action of this mock function on the given
  // arguments and returns the result. Asserts (or throws if
1453
  // exceptions are enabled) with a helpful call description if there
1454
1455
1456
  // 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.
1457
  // L = *
Abseil Team's avatar
Abseil Team committed
1458
  Result PerformDefaultAction(ArgumentTuple&& args,
Abseil Team's avatar
Abseil Team committed
1459
                              const std::string& call_description) const {
1460
    const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);
1461
    if (spec != nullptr) {
Abseil Team's avatar
Abseil Team committed
1462
      return spec->GetAction().Perform(std::move(args));
1463
    }
1464
1465
    const std::string message =
        call_description +
1466
1467
1468
1469
1470
1471
1472
1473
1474
        "\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
1475
    return DefaultValue<Result>::Get();
1476
1477
  }

1478
1479
  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
  // clears the ON_CALL()s set on this mock function.
Abseil Team's avatar
Abseil Team committed
1480
  void ClearDefaultActionsLocked() override
1481
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1482
    g_gmock_mutex.AssertHeld();
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494

    // 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();
1495
    for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
1496
         it != specs_to_delete.end(); ++it) {
1497
      delete static_cast<const OnCallSpec<F>*>(*it);
1498
    }
1499
1500
1501
1502

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

1505
1506
1507
  // 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
1508
  Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1509
    return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));
1510
  }
1511

Abseil Team's avatar
Abseil Team committed
1512
1513
1514
1515
1516
1517
1518
1519
  MockSpec<F> With(Matcher<Args>... m) {
    return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
  }

 protected:
  template <typename Function>
  friend class MockSpec;

1520
  // Adds and returns a default action spec for this mock function.
1521
1522
1523
  OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
                                  const ArgumentMatcherTuple& m)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1524
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1525
1526
1527
    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;
1528
1529
1530
  }

  // Adds and returns an expectation spec for this mock function.
1531
1532
1533
1534
  TypedExpectation<F>& AddNewExpectation(const char* file, int line,
                                         const std::string& source_text,
                                         const ArgumentMatcherTuple& m)
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1535
    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1536
1537
    TypedExpectation<F>* const expectation =
        new TypedExpectation<F>(this, file, line, source_text, m);
misterg's avatar
misterg committed
1538
    const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
Gennadiy Civil's avatar
Gennadiy Civil committed
1539
1540
    // See the definition of untyped_expectations_ for why access to
    // it is unprotected here.
1541
    untyped_expectations_.push_back(untyped_expectation);
1542
1543
1544

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

    return *expectation;
  }

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

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

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

1565
    if (spec == nullptr) {
1566
1567
      *os << (std::is_void<Result>::value ? "returning directly.\n"
                                          : "returning default value.\n");
1568
1569
    } else {
      *os << "taking default action specified at:\n"
1570
          << FormatFileLocation(spec->file(), spec->line()) << "\n";
1571
1572
1573
1574
1575
1576
    }
  }

  // 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
1577
1578
1579
  void UntypedDescribeUninterestingCall(const void* untyped_args,
                                        ::std::ostream* os) const override
      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1580
1581
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1582
1583
1584
    *os << "Uninteresting mock function call - ";
    DescribeDefaultActionTo(args, os);
    *os << "    Function call: " << Name();
vladlosev's avatar
vladlosev committed
1585
    UniversalPrint(args, os);
1586
1587
  }

1588
1589
1590
1591
1592
1593
1594
  // 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.
  //
1595
1596
1597
1598
1599
1600
1601
1602
1603
  // 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
1604
1605
1606
1607
  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) {
1608
1609
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
1610
    MutexLock l(&g_gmock_mutex);
1611
    TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1612
    if (exp == nullptr) {  // A match wasn't found.
1613
      this->FormatUnexpectedCallMessageLocked(args, what, why);
1614
      return nullptr;
1615
1616
1617
1618
1619
    }

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

  // Prints the given function arguments to the ostream.
Abseil Team's avatar
Abseil Team committed
1629
1630
  void UntypedPrintArgs(const void* untyped_args,
                        ::std::ostream* os) const override {
1631
1632
1633
    const ArgumentTuple& args =
        *static_cast<const ArgumentTuple*>(untyped_args);
    UniversalPrint(args, os);
1634
1635
1636
1637
  }

  // Returns the expectation that matches the arguments, or NULL if no
  // expectation matches them.
1638
1639
  TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)
      const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1640
    g_gmock_mutex.AssertHeld();
Gennadiy Civil's avatar
Gennadiy Civil committed
1641
1642
    // See the definition of untyped_expectations_ for why access to
    // it is unprotected here.
1643
1644
1645
1646
1647
    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());
1648
1649
1650
1651
      if (exp->ShouldHandleArguments(args)) {
        return exp;
      }
    }
1652
    return nullptr;
1653
1654
1655
  }

  // Returns a message that the arguments don't match any expectation.
1656
1657
1658
1659
  void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
                                         ::std::ostream* os,
                                         ::std::ostream* why) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1660
1661
1662
1663
1664
1665
1666
1667
    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.
1668
1669
1670
  void PrintTriedExpectationsLocked(const ArgumentTuple& args,
                                    ::std::ostream* why) const
      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1671
    g_gmock_mutex.AssertHeld();
1672
    const size_t count = untyped_expectations_.size();
1673
    *why << "Google Mock tried the following " << count << " "
1674
1675
         << (count == 1 ? "expectation, but it didn't match"
                        : "expectations, but none matched")
1676
         << ":\n";
1677
    for (size_t i = 0; i < count; i++) {
1678
1679
      TypedExpectation<F>* const expectation =
          static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1680
      *why << "\n";
1681
      expectation->DescribeLocationTo(why);
1682
      if (count > 1) {
1683
        *why << "tried expectation #" << i << ": ";
1684
      }
1685
1686
1687
      *why << expectation->source_text() << "...\n";
      expectation->ExplainMatchResultTo(args, why);
      expectation->DescribeCallCountTo(why);
1688
1689
    }
  }
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736

  // Performs the given action (or the default if it's null) with the given
  // arguments and returns the action's result.
  // L = *
  R PerformAction(const void* untyped_action, ArgumentTuple&& args,
                  const std::string& call_description) const {
    if (untyped_action == nullptr) {
      return PerformDefaultAction(std::move(args), call_description);
    }

    // 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);
    return action.Perform(std::move(args));
  }

  // Is it possible to store an object of the supplied type in a local variable
  // for the sake of printing it, then return it on to the caller?
  template <typename T>
  using can_print_result = internal::conjunction<
      // void can't be stored as an object (and we also don't need to print it).
      internal::negation<std::is_void<T>>,
      // Non-moveable types can't be returned on to the user, so there's no way
      // for us to intercept and print them.
      std::is_move_constructible<T>>;

  // Perform the supplied action, printing the result to os.
  template <typename T = R,
            typename std::enable_if<can_print_result<T>::value, int>::type = 0>
  R PerformActionAndPrintResult(const void* const untyped_action,
                                ArgumentTuple&& args,
                                const std::string& call_description,
                                std::ostream& os) {
    R result = PerformAction(untyped_action, std::move(args), call_description);

    PrintAsActionResult(result, os);
    return std::forward<R>(result);
  }

  // An overload for when it's not possible to print the result. In this case we
  // simply perform the action.
  template <typename T = R,
            typename std::enable_if<
                internal::negation<can_print_result<T>>::value, int>::type = 0>
  R PerformActionAndPrintResult(const void* const untyped_action,
                                ArgumentTuple&& args,
                                const std::string& call_description,
1737
                                std::ostream&) {
1738
1739
1740
1741
1742
1743
1744
    return PerformAction(untyped_action, std::move(args), call_description);
  }

  // Returns the result of invoking this mock function with the given
  // arguments. This function can be safely called from multiple
  // threads concurrently.
  R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
Abseil Team's avatar
Abseil Team committed
1745
};  // class FunctionMocker
1746

1747
// Calculates the result of invoking this mock function with the given
1748
1749
1750
// arguments, prints it, and returns it.
template <typename R, typename... Args>
R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  // See the definition of untyped_expectations_ for why access to it
  // is unprotected here.
  if (untyped_expectations_.size() == 0) {
    // No expectation is set on this mock method - we have an
    // uninteresting call.

    // We must get Google Mock's reaction on uninteresting calls
    // made on this mock object BEFORE performing the action,
    // because the action may DELETE the mock object and make the
    // following expression meaningless.
    const CallReaction reaction =
        Mock::GetReactionOnUninterestingCalls(MockObject());

    // True if and only if we need to print this call's arguments and return
    // value.  This definition must be kept in sync with
    // the behavior of ReportUninterestingCall().
    const bool need_to_report_uninteresting_call =
        // If the user allows this uninteresting call, we print it
        // only when they want informational messages.
        reaction == kAllow ? LogIsVisible(kInfo) :
                           // If the user wants this to be a warning, we print
                           // it only when they want to see warnings.
            reaction == kWarn
            ? LogIsVisible(kWarning)
            :
            // Otherwise, the user wants this to be an error, and we
            // should always print detailed information in the error.
            true;

    if (!need_to_report_uninteresting_call) {
      // Perform the action without printing the call information.
1783
1784
      return this->PerformDefaultAction(
          std::move(args), "Function call: " + std::string(Name()));
1785
1786
1787
1788
    }

    // Warns about the uninteresting call.
    ::std::stringstream ss;
1789
    this->UntypedDescribeUninterestingCall(&args, &ss);
1790

1791
1792
1793
1794
1795
1796
1797
    // Perform the action, print the result, and then report the uninteresting
    // call.
    //
    // We use RAII to do the latter in case R is void or a non-moveable type. In
    // either case we can't assign it to a local variable.
    const Cleanup report_uninteresting_call(
        [&] { ReportUninterestingCall(reaction, ss.str()); });
1798

1799
    return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
  }

  bool is_excessive = false;
  ::std::stringstream ss;
  ::std::stringstream why;
  ::std::stringstream loc;
  const void* untyped_action = nullptr;

  // The UntypedFindMatchingExpectation() function acquires and
  // releases g_gmock_mutex.

  const ExpectationBase* const untyped_expectation =
1812
      this->UntypedFindMatchingExpectation(&args, &untyped_action,
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
                                           &is_excessive, &ss, &why);
  const bool found = untyped_expectation != nullptr;

  // True if and only if we need to print the call's arguments
  // and return value.
  // This definition must be kept in sync with the uses of Expect()
  // and Log() in this function.
  const bool need_to_report_call =
      !found || is_excessive || LogIsVisible(kInfo);
  if (!need_to_report_call) {
    // Perform the action without printing the call information.
1824
    return PerformAction(untyped_action, std::move(args), "");
1825
1826
1827
  }

  ss << "    Function call: " << Name();
1828
  this->UntypedPrintArgs(&args, &ss);
1829
1830
1831
1832
1833
1834
1835

  // In case the action deletes a piece of the expectation, we
  // generate the message beforehand.
  if (found && !is_excessive) {
    untyped_expectation->DescribeLocationTo(&loc);
  }

1836
1837
1838
1839
1840
1841
  // Perform the action, print the result, and then fail or log in whatever way
  // is appropriate.
  //
  // We use RAII to do the latter in case R is void or a non-moveable type. In
  // either case we can't assign it to a local variable.
  const Cleanup handle_failures([&] {
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
    ss << "\n" << why.str();

    if (!found) {
      // No expectation matches this call - reports a failure.
      Expect(false, nullptr, -1, ss.str());
    } else if (is_excessive) {
      // We had an upper-bound violation and the failure message is in ss.
      Expect(false, untyped_expectation->file(), untyped_expectation->line(),
             ss.str());
    } else {
      // We had an expected call and the matching expectation is
      // described in ss.
      Log(kInfo, loc.str() + ss.str(), 2);
    }
1856
  });
1857

1858
1859
  return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
                                     ss);
1860
}
1861
1862
1863

}  // namespace internal

1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
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)...);
  }

1892
  MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
    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
1911
1912
1913
Specializations provided here cover a signature type itself and any template
that can be parameterized with a signature, including std::function and
boost::function.
1914
1915
*/

Abseil Team's avatar
Abseil Team committed
1916
template <typename F, typename = void>
1917
1918
1919
1920
1921
1922
1923
struct SignatureOf;

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

Abseil Team's avatar
Abseil Team committed
1924
1925
1926
1927
template <template <typename> class C, typename F>
struct SignatureOf<C<F>,
                   typename std::enable_if<std::is_function<F>::value>::type>
    : SignatureOf<F> {};
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938

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
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
//
//   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
1972
1973
1974
// 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
1975
1976
1977
1978
1979
1980
//
// TEST(FooTest, RunsCallbackWithBarArgument) {
//   MockFunction<int(string)> callback;
//   EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
//   Foo(callback.AsStdFunction());
// }
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
//
// 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
1994
template <typename F>
1995
1996
class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
  using Base = internal::MockFunction<internal::SignatureOfT<F>>;
Abseil Team's avatar
Abseil Team committed
1997
1998

 public:
1999
  using Base::Base;
Abseil Team's avatar
Abseil Team committed
2000
2001
};

2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
// 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>
2025
2026
2027
inline const T& Const(const T& x) {
  return x;
}
2028

2029
2030
2031
2032
// Constructs an Expectation object that references and co-owns exp.
inline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT
    : expectation_base_(exp.GetHandle().expectation_base()) {}

2033
2034
}  // namespace testing

misterg's avatar
misterg committed
2035
2036
GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251

2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
// 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:
2048
2049
//   ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
//   ON_CALL(mock, NoArgsMethod).WillByDefault(...);
2050
2051
//
//   // As are these:
2052
2053
//   ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
//   ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
2054
2055
//
//   // Can also specify args if you want, of course:
2056
//   ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
2057
2058
//
//   // Overloads work as long as you specify parameters:
2059
2060
//   ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
//   ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
2061
2062
//
//   // Oops! Which overload did you want?
2063
//   ON_CALL(mock, OverloadedMethod).WillByDefault(...);
2064
2065
2066
2067
2068
2069
2070
//     => 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:
2071
//   ON_CALL(mock, TwoArgsMethod(_, 45))...
2072
//
2073
2074
//   // ...expands to:
//   mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
2075
2076
2077
//   |-------------v---------------||------------v-------------|
//       invokes first overload        swallowed by operator()
//
2078
2079
//   // ...which is essentially:
//   mock.gmock_TwoArgsMethod(_, 45)...
2080
2081
2082
2083
//
// Whereas the form without a matcher list:
//
//   // This statement:
2084
//   ON_CALL(mock, TwoArgsMethod)...
2085
//
2086
2087
//   // ...expands to:
//   mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
2088
2089
2090
//   |-----------------------v--------------------------|
//                 invokes second overload
//
2091
2092
//   // ...which is essentially:
//   mock.gmock_TwoArgsMethod(_, _)...
2093
2094
2095
2096
2097
2098
//
// 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.
2099
2100
2101
#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call)                    \
  ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
                             nullptr)                                   \
2102
2103
2104
2105
2106
2107
2108
      .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)
2109

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