bloaty/third_party/googletest/googlemock/include/gmock/gmock-spec-builders.h
Go to the documentation of this file.
1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file implements the ON_CALL() and EXPECT_CALL() macros.
34 //
35 // A user can use the ON_CALL() macro to specify the default action of
36 // a mock method. The syntax is:
37 //
38 // ON_CALL(mock_object, Method(argument-matchers))
39 // .With(multi-argument-matcher)
40 // .WillByDefault(action);
41 //
42 // where the .With() clause is optional.
43 //
44 // A user can use the EXPECT_CALL() macro to specify an expectation on
45 // a mock method. The syntax is:
46 //
47 // EXPECT_CALL(mock_object, Method(argument-matchers))
48 // .With(multi-argument-matchers)
49 // .Times(cardinality)
50 // .InSequence(sequences)
51 // .After(expectations)
52 // .WillOnce(action)
53 // .WillRepeatedly(action)
54 // .RetiresOnSaturation();
55 //
56 // where all clauses are optional, and .InSequence()/.After()/
57 // .WillOnce() can appear any number of times.
58 
59 // GOOGLETEST_CM0002 DO NOT DELETE
60 
61 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
63 
64 #include <functional>
65 #include <map>
66 #include <memory>
67 #include <set>
68 #include <sstream>
69 #include <string>
70 #include <type_traits>
71 #include <utility>
72 #include <vector>
73 #include "gmock/gmock-actions.h"
74 #include "gmock/gmock-cardinalities.h"
75 #include "gmock/gmock-matchers.h"
76 #include "gmock/internal/gmock-internal-utils.h"
77 #include "gmock/internal/gmock-port.h"
78 #include "gtest/gtest.h"
79 
80 #if GTEST_HAS_EXCEPTIONS
81 # include <stdexcept> // NOLINT
82 #endif
83 
85 /* class A needs to have dll-interface to be used by clients of class B */)
86 
88 
89 // An abstract handle of an expectation.
90 class Expectation;
91 
92 // A set of expectation handles.
93 class ExpectationSet;
94 
95 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
96 // and MUST NOT BE USED IN USER CODE!!!
97 namespace internal {
98 
99 // Implements a mock function.
100 template <typename F> class FunctionMocker;
101 
102 // Base class for expectations.
103 class ExpectationBase;
104 
105 // Implements an expectation.
106 template <typename F> class TypedExpectation;
107 
108 // Helper class for testing the Expectation class template.
109 class ExpectationTester;
110 
111 // Protects the mock object registry (in class Mock), all function
112 // mockers, and all expectations.
113 //
114 // The reason we don't use more fine-grained protection is: when a
115 // mock function Foo() is called, it needs to consult its expectations
116 // to see which one should be picked. If another thread is allowed to
117 // call a mock function (either Foo() or a different one) at the same
118 // time, it could affect the "retired" attributes of Foo()'s
119 // expectations when InSequence() is used, and thus affect which
120 // expectation gets picked. Therefore, we sequence all mock function
121 // calls to ensure the integrity of the mock objects' states.
123 
124 // Untyped base class for ActionResultHolder<R>.
125 class UntypedActionResultHolderBase;
126 
127 // Abstract base class of FunctionMocker. This is the
128 // type-agnostic part of the function mocker interface. Its pure
129 // virtual methods are implemented by FunctionMocker.
130 class GTEST_API_ UntypedFunctionMockerBase {
131  public:
132  UntypedFunctionMockerBase();
133  virtual ~UntypedFunctionMockerBase();
134 
135  // Verifies that all expectations on this mock function have been
136  // satisfied. Reports one or more Google Test non-fatal failures
137  // and returns false if not.
138  bool VerifyAndClearExpectationsLocked()
139  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
140 
141  // Clears the ON_CALL()s set on this mock function.
142  virtual void ClearDefaultActionsLocked()
143  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
144 
145  // In all of the following Untyped* functions, it's the caller's
146  // responsibility to guarantee the correctness of the arguments'
147  // types.
148 
149  // Performs the default action with the given arguments and returns
150  // the action's result. The call description string will be used in
151  // the error message to describe the call in the case the default
152  // action fails.
153  // L = *
154  virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
155  void* untyped_args, const std::string& call_description) const = 0;
156 
157  // Performs the given action with the given arguments and returns
158  // the action's result.
159  // L = *
160  virtual UntypedActionResultHolderBase* UntypedPerformAction(
161  const void* untyped_action, void* untyped_args) const = 0;
162 
163  // Writes a message that the call is uninteresting (i.e. neither
164  // explicitly expected nor explicitly unexpected) to the given
165  // ostream.
166  virtual void UntypedDescribeUninterestingCall(
167  const void* untyped_args,
168  ::std::ostream* os) const
169  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
170 
171  // Returns the expectation that matches the given function arguments
172  // (or NULL is there's no match); when a match is found,
173  // untyped_action is set to point to the action that should be
174  // performed (or NULL if the action is "do default"), and
175  // is_excessive is modified to indicate whether the call exceeds the
176  // expected number.
177  virtual const ExpectationBase* UntypedFindMatchingExpectation(
178  const void* untyped_args,
179  const void** untyped_action, bool* is_excessive,
180  ::std::ostream* what, ::std::ostream* why)
181  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
182 
183  // Prints the given function arguments to the ostream.
184  virtual void UntypedPrintArgs(const void* untyped_args,
185  ::std::ostream* os) const = 0;
186 
187  // Sets the mock object this mock method belongs to, and registers
188  // this information in the global mock registry. Will be called
189  // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
190  // method.
191  void RegisterOwner(const void* mock_obj)
192  GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
193 
194  // Sets the mock object this mock method belongs to, and sets the
195  // name of the mock function. Will be called upon each invocation
196  // of this mock function.
197  void SetOwnerAndName(const void* mock_obj, const char* name)
198  GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
199 
200  // Returns the mock object this mock method belongs to. Must be
201  // called after RegisterOwner() or SetOwnerAndName() has been
202  // called.
203  const void* MockObject() const
204  GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
205 
206  // Returns the name of this mock method. Must be called after
207  // SetOwnerAndName() has been called.
208  const char* Name() const
209  GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
210 
211  // Returns the result of invoking this mock function with the given
212  // arguments. This function can be safely called from multiple
213  // threads concurrently. The caller is responsible for deleting the
214  // result.
215  UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
216  GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
217 
218  protected:
219  typedef std::vector<const void*> UntypedOnCallSpecs;
220 
221  using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
222 
223  // Returns an Expectation object that references and co-owns exp,
224  // which must be an expectation on this mock function.
225  Expectation GetHandleOf(ExpectationBase* exp);
226 
227  // Address of the mock object this mock method belongs to. Only
228  // valid after this mock method has been called or
229  // ON_CALL/EXPECT_CALL has been invoked on it.
230  const void* mock_obj_; // Protected by g_gmock_mutex.
231 
232  // Name of the function being mocked. Only valid after this mock
233  // method has been called.
234  const char* name_; // Protected by g_gmock_mutex.
235 
236  // All default action specs for this function mocker.
237  UntypedOnCallSpecs untyped_on_call_specs_;
238 
239  // All expectations for this function mocker.
240  //
241  // It's undefined behavior to interleave expectations (EXPECT_CALLs
242  // or ON_CALLs) and mock function calls. Also, the order of
243  // expectations is important. Therefore it's a logic race condition
244  // to read/write untyped_expectations_ concurrently. In order for
245  // tools like tsan to catch concurrent read/write accesses to
246  // untyped_expectations, we deliberately leave accesses to it
247  // unprotected.
248  UntypedExpectations untyped_expectations_;
249 }; // class UntypedFunctionMockerBase
250 
251 // Untyped base class for OnCallSpec<F>.
252 class UntypedOnCallSpecBase {
253  public:
254  // The arguments are the location of the ON_CALL() statement.
255  UntypedOnCallSpecBase(const char* a_file, int a_line)
256  : file_(a_file), line_(a_line), last_clause_(kNone) {}
257 
258  // Where in the source file was the default action spec defined?
259  const char* file() const { return file_; }
260  int line() const { return line_; }
261 
262  protected:
263  // Gives each clause in the ON_CALL() statement a name.
264  enum Clause {
265  // Do not change the order of the enum members! The run-time
266  // syntax checking relies on it.
267  kNone,
268  kWith,
269  kWillByDefault
270  };
271 
272  // Asserts that the ON_CALL() statement has a certain property.
273  void AssertSpecProperty(bool property,
274  const std::string& failure_message) const {
275  Assert(property, file_, line_, failure_message);
276  }
277 
278  // Expects that the ON_CALL() statement has a certain property.
279  void ExpectSpecProperty(bool property,
280  const std::string& failure_message) const {
281  Expect(property, file_, line_, failure_message);
282  }
283 
284  const char* file_;
285  int line_;
286 
287  // The last clause in the ON_CALL() statement as seen so far.
288  // Initially kNone and changes as the statement is parsed.
289  Clause last_clause_;
290 }; // class UntypedOnCallSpecBase
291 
292 // This template class implements an ON_CALL spec.
293 template <typename F>
294 class OnCallSpec : public UntypedOnCallSpecBase {
295  public:
296  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
297  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
298 
299  // Constructs an OnCallSpec object from the information inside
300  // the parenthesis of an ON_CALL() statement.
301  OnCallSpec(const char* a_file, int a_line,
302  const ArgumentMatcherTuple& matchers)
303  : UntypedOnCallSpecBase(a_file, a_line),
305  // By default, extra_matcher_ should match anything. However,
306  // we cannot initialize it with _ as that causes ambiguity between
307  // Matcher's copy and move constructor for some argument types.
308  extra_matcher_(A<const ArgumentTuple&>()) {}
309 
310  // Implements the .With() clause.
311  OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
312  // Makes sure this is called at most once.
313  ExpectSpecProperty(last_clause_ < kWith,
314  ".With() cannot appear "
315  "more than once in an ON_CALL().");
316  last_clause_ = kWith;
317 
318  extra_matcher_ = m;
319  return *this;
320  }
321 
322  // Implements the .WillByDefault() clause.
323  OnCallSpec& WillByDefault(const Action<F>& action) {
324  ExpectSpecProperty(last_clause_ < kWillByDefault,
325  ".WillByDefault() must appear "
326  "exactly once in an ON_CALL().");
327  last_clause_ = kWillByDefault;
328 
329  ExpectSpecProperty(!action.IsDoDefault(),
330  "DoDefault() cannot be used in ON_CALL().");
331  action_ = action;
332  return *this;
333  }
334 
335  // Returns true if the given arguments match the matchers.
336  bool Matches(const ArgumentTuple& args) const {
337  return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
338  }
339 
340  // Returns the action specified by the user.
341  const Action<F>& GetAction() const {
342  AssertSpecProperty(last_clause_ == kWillByDefault,
343  ".WillByDefault() must appear exactly "
344  "once in an ON_CALL().");
345  return action_;
346  }
347 
348  private:
349  // The information in statement
350  //
351  // ON_CALL(mock_object, Method(matchers))
352  // .With(multi-argument-matcher)
353  // .WillByDefault(action);
354  //
355  // is recorded in the data members like this:
356  //
357  // source file that contains the statement => file_
358  // line number of the statement => line_
359  // matchers => matchers_
360  // multi-argument-matcher => extra_matcher_
361  // action => action_
362  ArgumentMatcherTuple matchers_;
363  Matcher<const ArgumentTuple&> extra_matcher_;
364  Action<F> action_;
365 }; // class OnCallSpec
366 
367 // Possible reactions on uninteresting calls.
368 enum CallReaction {
369  kAllow,
370  kWarn,
371  kFail,
372 };
373 
374 } // namespace internal
375 
376 // Utilities for manipulating mock objects.
377 class GTEST_API_ Mock {
378  public:
379  // The following public methods can be called concurrently.
380 
381  // Tells Google Mock to ignore mock_obj when checking for leaked
382  // mock objects.
383  static void AllowLeak(const void* mock_obj)
384  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
385 
386  // Verifies and clears all expectations on the given mock object.
387  // If the expectations aren't satisfied, generates one or more
388  // Google Test non-fatal failures and returns false.
389  static bool VerifyAndClearExpectations(void* mock_obj)
390  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
391 
392  // Verifies all expectations on the given mock object and clears its
393  // default actions and expectations. Returns true if the
394  // verification was successful.
395  static bool VerifyAndClear(void* mock_obj)
396  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
397 
398  // Returns whether the mock was created as a naggy mock (default)
399  static bool IsNaggy(void* mock_obj)
400  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
401  // Returns whether the mock was created as a nice mock
402  static bool IsNice(void* mock_obj)
403  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
404  // Returns whether the mock was created as a strict mock
405  static bool IsStrict(void* mock_obj)
406  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
407 
408  private:
409  friend class internal::UntypedFunctionMockerBase;
410 
411  // Needed for a function mocker to register itself (so that we know
412  // how to clear a mock object).
413  template <typename F>
414  friend class internal::FunctionMocker;
415 
416  template <typename M>
417  friend class NiceMock;
418 
419  template <typename M>
420  friend class NaggyMock;
421 
422  template <typename M>
423  friend class StrictMock;
424 
425  // Tells Google Mock to allow uninteresting calls on the given mock
426  // object.
427  static void AllowUninterestingCalls(const void* mock_obj)
428  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
429 
430  // Tells Google Mock to warn the user about uninteresting calls on
431  // the given mock object.
432  static void WarnUninterestingCalls(const void* mock_obj)
433  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
434 
435  // Tells Google Mock to fail uninteresting calls on the given mock
436  // object.
437  static void FailUninterestingCalls(const void* mock_obj)
438  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
439 
440  // Tells Google Mock the given mock object is being destroyed and
441  // its entry in the call-reaction table should be removed.
442  static void UnregisterCallReaction(const void* mock_obj)
443  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
444 
445  // Returns the reaction Google Mock will have on uninteresting calls
446  // made on the given mock object.
447  static internal::CallReaction GetReactionOnUninterestingCalls(
448  const void* mock_obj)
449  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
450 
451  // Verifies that all expectations on the given mock object have been
452  // satisfied. Reports one or more Google Test non-fatal failures
453  // and returns false if not.
454  static bool VerifyAndClearExpectationsLocked(void* mock_obj)
455  GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
456 
457  // Clears all ON_CALL()s set on the given mock object.
458  static void ClearDefaultActionsLocked(void* mock_obj)
459  GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
460 
461  // Registers a mock object and a mock method it owns.
462  static void Register(
463  const void* mock_obj,
464  internal::UntypedFunctionMockerBase* mocker)
465  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
466 
467  // Tells Google Mock where in the source code mock_obj is used in an
468  // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
469  // information helps the user identify which object it is.
470  static void RegisterUseByOnCallOrExpectCall(
471  const void* mock_obj, const char* file, int line)
472  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
473 
474  // Unregisters a mock method; removes the owning mock object from
475  // the registry when the last mock method associated with it has
476  // been unregistered. This is called only in the destructor of
477  // FunctionMocker.
478  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
479  GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
480 }; // class Mock
481 
482 // An abstract handle of an expectation. Useful in the .After()
483 // clause of EXPECT_CALL() for setting the (partial) order of
484 // expectations. The syntax:
485 //
486 // Expectation e1 = EXPECT_CALL(...)...;
487 // EXPECT_CALL(...).After(e1)...;
488 //
489 // sets two expectations where the latter can only be matched after
490 // the former has been satisfied.
491 //
492 // Notes:
493 // - This class is copyable and has value semantics.
494 // - Constness is shallow: a const Expectation object itself cannot
495 // be modified, but the mutable methods of the ExpectationBase
496 // object it references can be called via expectation_base().
497 
498 class GTEST_API_ Expectation {
499  public:
500  // Constructs a null object that doesn't reference any expectation.
501  Expectation();
502 
503  ~Expectation();
504 
505  // This single-argument ctor must not be explicit, in order to support the
506  // Expectation e = EXPECT_CALL(...);
507  // syntax.
508  //
509  // A TypedExpectation object stores its pre-requisites as
510  // Expectation objects, and needs to call the non-const Retire()
511  // method on the ExpectationBase objects they reference. Therefore
512  // Expectation must receive a *non-const* reference to the
513  // ExpectationBase object.
514  Expectation(internal::ExpectationBase& exp); // NOLINT
515 
516  // The compiler-generated copy ctor and operator= work exactly as
517  // intended, so we don't need to define our own.
518 
519  // Returns true if rhs references the same expectation as this object does.
520  bool operator==(const Expectation& rhs) const {
521  return expectation_base_ == rhs.expectation_base_;
522  }
523 
524  bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
525 
526  private:
527  friend class ExpectationSet;
528  friend class Sequence;
529  friend class ::testing::internal::ExpectationBase;
530  friend class ::testing::internal::UntypedFunctionMockerBase;
531 
532  template <typename F>
533  friend class ::testing::internal::FunctionMocker;
534 
535  template <typename F>
536  friend class ::testing::internal::TypedExpectation;
537 
538  // This comparator is needed for putting Expectation objects into a set.
539  class Less {
540  public:
541  bool operator()(const Expectation& lhs, const Expectation& rhs) const {
542  return lhs.expectation_base_.get() < rhs.expectation_base_.get();
543  }
544  };
545 
546  typedef ::std::set<Expectation, Less> Set;
547 
548  Expectation(
549  const std::shared_ptr<internal::ExpectationBase>& expectation_base);
550 
551  // Returns the expectation this object references.
552  const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
553  return expectation_base_;
554  }
555 
556  // A shared_ptr that co-owns the expectation this handle references.
557  std::shared_ptr<internal::ExpectationBase> expectation_base_;
558 };
559 
560 // A set of expectation handles. Useful in the .After() clause of
561 // EXPECT_CALL() for setting the (partial) order of expectations. The
562 // syntax:
563 //
564 // ExpectationSet es;
565 // es += EXPECT_CALL(...)...;
566 // es += EXPECT_CALL(...)...;
567 // EXPECT_CALL(...).After(es)...;
568 //
569 // sets three expectations where the last one can only be matched
570 // after the first two have both been satisfied.
571 //
572 // This class is copyable and has value semantics.
573 class ExpectationSet {
574  public:
575  // A bidirectional iterator that can read a const element in the set.
576  typedef Expectation::Set::const_iterator const_iterator;
577 
578  // An object stored in the set. This is an alias of Expectation.
580 
581  // Constructs an empty set.
582  ExpectationSet() {}
583 
584  // This single-argument ctor must not be explicit, in order to support the
585  // ExpectationSet es = EXPECT_CALL(...);
586  // syntax.
587  ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
588  *this += Expectation(exp);
589  }
590 
591  // This single-argument ctor implements implicit conversion from
592  // Expectation and thus must not be explicit. This allows either an
593  // Expectation or an ExpectationSet to be used in .After().
594  ExpectationSet(const Expectation& e) { // NOLINT
595  *this += e;
596  }
597 
598  // The compiler-generator ctor and operator= works exactly as
599  // intended, so we don't need to define our own.
600 
601  // Returns true if rhs contains the same set of Expectation objects
602  // as this does.
603  bool operator==(const ExpectationSet& rhs) const {
604  return expectations_ == rhs.expectations_;
605  }
606 
607  bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
608 
609  // Implements the syntax
610  // expectation_set += EXPECT_CALL(...);
611  ExpectationSet& operator+=(const Expectation& e) {
612  expectations_.insert(e);
613  return *this;
614  }
615 
616  int size() const { return static_cast<int>(expectations_.size()); }
617 
618  const_iterator begin() const { return expectations_.begin(); }
619  const_iterator end() const { return expectations_.end(); }
620 
621  private:
622  Expectation::Set expectations_;
623 };
624 
625 
626 // Sequence objects are used by a user to specify the relative order
627 // in which the expectations should match. They are copyable (we rely
628 // on the compiler-defined copy constructor and assignment operator).
629 class GTEST_API_ Sequence {
630  public:
631  // Constructs an empty sequence.
632  Sequence() : last_expectation_(new Expectation) {}
633 
634  // Adds an expectation to this sequence. The caller must ensure
635  // that no other thread is accessing this Sequence object.
636  void AddExpectation(const Expectation& expectation) const;
637 
638  private:
639  // The last expectation in this sequence.
640  std::shared_ptr<Expectation> last_expectation_;
641 }; // class Sequence
642 
643 // An object of this type causes all EXPECT_CALL() statements
644 // encountered in its scope to be put in an anonymous sequence. The
645 // work is done in the constructor and destructor. You should only
646 // create an InSequence object on the stack.
647 //
648 // The sole purpose for this class is to support easy definition of
649 // sequential expectations, e.g.
650 //
651 // {
652 // InSequence dummy; // The name of the object doesn't matter.
653 //
654 // // The following expectations must match in the order they appear.
655 // EXPECT_CALL(a, Bar())...;
656 // EXPECT_CALL(a, Baz())...;
657 // ...
658 // EXPECT_CALL(b, Xyz())...;
659 // }
660 //
661 // You can create InSequence objects in multiple threads, as long as
662 // they are used to affect different mock objects. The idea is that
663 // each thread can create and set up its own mocks as if it's the only
664 // thread. However, for clarity of your tests we recommend you to set
665 // up mocks in the main thread unless you have a good reason not to do
666 // so.
667 class GTEST_API_ InSequence {
668  public:
669  InSequence();
670  ~InSequence();
671  private:
672  bool sequence_created_;
673 
674  GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
676 
677 namespace internal {
678 
679 // Points to the implicit sequence introduced by a living InSequence
680 // object (if any) in the current thread or NULL.
681 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
682 
683 // Base class for implementing expectations.
684 //
685 // There are two reasons for having a type-agnostic base class for
686 // Expectation:
687 //
688 // 1. We need to store collections of expectations of different
689 // types (e.g. all pre-requisites of a particular expectation, all
690 // expectations in a sequence). Therefore these expectation objects
691 // must share a common base class.
692 //
693 // 2. We can avoid binary code bloat by moving methods not depending
694 // on the template argument of Expectation to the base class.
695 //
696 // This class is internal and mustn't be used by user code directly.
697 class GTEST_API_ ExpectationBase {
698  public:
699  // source_text is the EXPECT_CALL(...) source that created this Expectation.
700  ExpectationBase(const char* file, int line, const std::string& source_text);
701 
702  virtual ~ExpectationBase();
703 
704  // Where in the source file was the expectation spec defined?
705  const char* file() const { return file_; }
706  int line() const { return line_; }
707  const char* source_text() const { return source_text_.c_str(); }
708  // Returns the cardinality specified in the expectation spec.
709  const Cardinality& cardinality() const { return cardinality_; }
710 
711  // Describes the source file location of this expectation.
712  void DescribeLocationTo(::std::ostream* os) const {
713  *os << FormatFileLocation(file(), line()) << " ";
714  }
715 
716  // Describes how many times a function call matching this
717  // expectation has occurred.
718  void DescribeCallCountTo(::std::ostream* os) const
719  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
720 
721  // If this mock method has an extra matcher (i.e. .With(matcher)),
722  // describes it to the ostream.
723  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
724 
725  protected:
726  friend class ::testing::Expectation;
727  friend class UntypedFunctionMockerBase;
728 
729  enum Clause {
730  // Don't change the order of the enum members!
731  kNone,
732  kWith,
733  kTimes,
734  kInSequence,
735  kAfter,
736  kWillOnce,
737  kWillRepeatedly,
738  kRetiresOnSaturation
739  };
740 
741  typedef std::vector<const void*> UntypedActions;
742 
743  // Returns an Expectation object that references and co-owns this
744  // expectation.
745  virtual Expectation GetHandle() = 0;
746 
747  // Asserts that the EXPECT_CALL() statement has the given property.
748  void AssertSpecProperty(bool property,
749  const std::string& failure_message) const {
750  Assert(property, file_, line_, failure_message);
751  }
752 
753  // Expects that the EXPECT_CALL() statement has the given property.
754  void ExpectSpecProperty(bool property,
755  const std::string& failure_message) const {
756  Expect(property, file_, line_, failure_message);
757  }
758 
759  // Explicitly specifies the cardinality of this expectation. Used
760  // by the subclasses to implement the .Times() clause.
761  void SpecifyCardinality(const Cardinality& cardinality);
762 
763  // Returns true if the user specified the cardinality explicitly
764  // using a .Times().
765  bool cardinality_specified() const { return cardinality_specified_; }
766 
767  // Sets the cardinality of this expectation spec.
768  void set_cardinality(const Cardinality& a_cardinality) {
769  cardinality_ = a_cardinality;
770  }
771 
772  // The following group of methods should only be called after the
773  // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
774  // the current thread.
775 
776  // Retires all pre-requisites of this expectation.
777  void RetireAllPreRequisites()
778  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
779 
780  // Returns true if this expectation is retired.
781  bool is_retired() const
782  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
783  g_gmock_mutex.AssertHeld();
784  return retired_;
785  }
786 
787  // Retires this expectation.
788  void Retire()
789  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
790  g_gmock_mutex.AssertHeld();
791  retired_ = true;
792  }
793 
794  // Returns true if this expectation is satisfied.
795  bool IsSatisfied() const
796  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
797  g_gmock_mutex.AssertHeld();
798  return cardinality().IsSatisfiedByCallCount(call_count_);
799  }
800 
801  // Returns true if this expectation is saturated.
802  bool IsSaturated() const
803  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
804  g_gmock_mutex.AssertHeld();
805  return cardinality().IsSaturatedByCallCount(call_count_);
806  }
807 
808  // Returns true if this expectation is over-saturated.
809  bool IsOverSaturated() const
810  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
811  g_gmock_mutex.AssertHeld();
812  return cardinality().IsOverSaturatedByCallCount(call_count_);
813  }
814 
815  // Returns true if all pre-requisites of this expectation are satisfied.
816  bool AllPrerequisitesAreSatisfied() const
817  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
818 
819  // Adds unsatisfied pre-requisites of this expectation to 'result'.
820  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
821  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
822 
823  // Returns the number this expectation has been invoked.
824  int call_count() const
825  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
826  g_gmock_mutex.AssertHeld();
827  return call_count_;
828  }
829 
830  // Increments the number this expectation has been invoked.
831  void IncrementCallCount()
832  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
833  g_gmock_mutex.AssertHeld();
834  call_count_++;
835  }
836 
837  // Checks the action count (i.e. the number of WillOnce() and
838  // WillRepeatedly() clauses) against the cardinality if this hasn't
839  // been done before. Prints a warning if there are too many or too
840  // few actions.
841  void CheckActionCountIfNotDone() const
843 
844  friend class ::testing::Sequence;
845  friend class ::testing::internal::ExpectationTester;
846 
847  template <typename Function>
848  friend class TypedExpectation;
849 
850  // Implements the .Times() clause.
851  void UntypedTimes(const Cardinality& a_cardinality);
852 
853  // This group of fields are part of the spec and won't change after
854  // an EXPECT_CALL() statement finishes.
855  const char* file_; // The file that contains the expectation.
856  int line_; // The line number of the expectation.
857  const std::string source_text_; // The EXPECT_CALL(...) source text.
858  // True if the cardinality is specified explicitly.
859  bool cardinality_specified_;
860  Cardinality cardinality_; // The cardinality of the expectation.
861  // The immediate pre-requisites (i.e. expectations that must be
862  // satisfied before this expectation can be matched) of this
863  // expectation. We use std::shared_ptr in the set because we want an
864  // Expectation object to be co-owned by its FunctionMocker and its
865  // successors. This allows multiple mock objects to be deleted at
866  // different times.
867  ExpectationSet immediate_prerequisites_;
868 
869  // This group of fields are the current state of the expectation,
870  // and can change as the mock function is called.
871  int call_count_; // How many times this expectation has been invoked.
872  bool retired_; // True if this expectation has retired.
873  UntypedActions untyped_actions_;
874  bool extra_matcher_specified_;
875  bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
876  bool retires_on_saturation_;
877  Clause last_clause_;
878  mutable bool action_count_checked_; // Under mutex_.
879  mutable Mutex mutex_; // Protects action_count_checked_.
880 
881  GTEST_DISALLOW_ASSIGN_(ExpectationBase);
882 }; // class ExpectationBase
883 
884 // Impements an expectation for the given function type.
885 template <typename F>
886 class TypedExpectation : public ExpectationBase {
887  public:
888  typedef typename Function<F>::ArgumentTuple ArgumentTuple;
889  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
890  typedef typename Function<F>::Result Result;
891 
892  TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
893  const std::string& a_source_text,
894  const ArgumentMatcherTuple& m)
895  : ExpectationBase(a_file, a_line, a_source_text),
896  owner_(owner),
897  matchers_(m),
898  // By default, extra_matcher_ should match anything. However,
899  // we cannot initialize it with _ as that causes ambiguity between
900  // Matcher's copy and move constructor for some argument types.
901  extra_matcher_(A<const ArgumentTuple&>()),
902  repeated_action_(DoDefault()) {}
903 
904  ~TypedExpectation() override {
905  // Check the validity of the action count if it hasn't been done
906  // yet (for example, if the expectation was never used).
907  CheckActionCountIfNotDone();
908  for (UntypedActions::const_iterator it = untyped_actions_.begin();
909  it != untyped_actions_.end(); ++it) {
910  delete static_cast<const Action<F>*>(*it);
911  }
912  }
913 
914  // Implements the .With() clause.
915  TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
916  if (last_clause_ == kWith) {
917  ExpectSpecProperty(false,
918  ".With() cannot appear "
919  "more than once in an EXPECT_CALL().");
920  } else {
921  ExpectSpecProperty(last_clause_ < kWith,
922  ".With() must be the first "
923  "clause in an EXPECT_CALL().");
924  }
925  last_clause_ = kWith;
926 
927  extra_matcher_ = m;
928  extra_matcher_specified_ = true;
929  return *this;
930  }
931 
932  // Implements the .Times() clause.
933  TypedExpectation& Times(const Cardinality& a_cardinality) {
934  ExpectationBase::UntypedTimes(a_cardinality);
935  return *this;
936  }
937 
938  // Implements the .Times() clause.
939  TypedExpectation& Times(int n) {
940  return Times(Exactly(n));
941  }
942 
943  // Implements the .InSequence() clause.
944  TypedExpectation& InSequence(const Sequence& s) {
945  ExpectSpecProperty(last_clause_ <= kInSequence,
946  ".InSequence() cannot appear after .After(),"
947  " .WillOnce(), .WillRepeatedly(), or "
948  ".RetiresOnSaturation().");
949  last_clause_ = kInSequence;
950 
951  s.AddExpectation(GetHandle());
952  return *this;
953  }
954  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
955  return InSequence(s1).InSequence(s2);
956  }
957  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
958  const Sequence& s3) {
959  return InSequence(s1, s2).InSequence(s3);
960  }
961  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
962  const Sequence& s3, const Sequence& s4) {
963  return InSequence(s1, s2, s3).InSequence(s4);
964  }
965  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
966  const Sequence& s3, const Sequence& s4,
967  const Sequence& s5) {
968  return InSequence(s1, s2, s3, s4).InSequence(s5);
969  }
970 
971  // Implements that .After() clause.
972  TypedExpectation& After(const ExpectationSet& s) {
973  ExpectSpecProperty(last_clause_ <= kAfter,
974  ".After() cannot appear after .WillOnce(),"
975  " .WillRepeatedly(), or "
976  ".RetiresOnSaturation().");
977  last_clause_ = kAfter;
978 
979  for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
980  immediate_prerequisites_ += *it;
981  }
982  return *this;
983  }
984  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
985  return After(s1).After(s2);
986  }
987  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
988  const ExpectationSet& s3) {
989  return After(s1, s2).After(s3);
990  }
991  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
992  const ExpectationSet& s3, const ExpectationSet& s4) {
993  return After(s1, s2, s3).After(s4);
994  }
995  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
996  const ExpectationSet& s3, const ExpectationSet& s4,
997  const ExpectationSet& s5) {
998  return After(s1, s2, s3, s4).After(s5);
999  }
1000 
1001  // Implements the .WillOnce() clause.
1002  TypedExpectation& WillOnce(const Action<F>& action) {
1003  ExpectSpecProperty(last_clause_ <= kWillOnce,
1004  ".WillOnce() cannot appear after "
1005  ".WillRepeatedly() or .RetiresOnSaturation().");
1006  last_clause_ = kWillOnce;
1007 
1008  untyped_actions_.push_back(new Action<F>(action));
1009  if (!cardinality_specified()) {
1010  set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1011  }
1012  return *this;
1013  }
1014 
1015  // Implements the .WillRepeatedly() clause.
1016  TypedExpectation& WillRepeatedly(const Action<F>& action) {
1017  if (last_clause_ == kWillRepeatedly) {
1018  ExpectSpecProperty(false,
1019  ".WillRepeatedly() cannot appear "
1020  "more than once in an EXPECT_CALL().");
1021  } else {
1022  ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1023  ".WillRepeatedly() cannot appear "
1024  "after .RetiresOnSaturation().");
1025  }
1026  last_clause_ = kWillRepeatedly;
1027  repeated_action_specified_ = true;
1028 
1029  repeated_action_ = action;
1030  if (!cardinality_specified()) {
1031  set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1032  }
1033 
1034  // Now that no more action clauses can be specified, we check
1035  // whether their count makes sense.
1036  CheckActionCountIfNotDone();
1037  return *this;
1038  }
1039 
1040  // Implements the .RetiresOnSaturation() clause.
1041  TypedExpectation& RetiresOnSaturation() {
1042  ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1043  ".RetiresOnSaturation() cannot appear "
1044  "more than once.");
1045  last_clause_ = kRetiresOnSaturation;
1046  retires_on_saturation_ = true;
1047 
1048  // Now that no more action clauses can be specified, we check
1049  // whether their count makes sense.
1050  CheckActionCountIfNotDone();
1051  return *this;
1052  }
1053 
1054  // Returns the matchers for the arguments as specified inside the
1055  // EXPECT_CALL() macro.
1056  const ArgumentMatcherTuple& matchers() const {
1057  return matchers_;
1058  }
1059 
1060  // Returns the matcher specified by the .With() clause.
1061  const Matcher<const ArgumentTuple&>& extra_matcher() const {
1062  return extra_matcher_;
1063  }
1064 
1065  // Returns the action specified by the .WillRepeatedly() clause.
1066  const Action<F>& repeated_action() const { return repeated_action_; }
1067 
1068  // If this mock method has an extra matcher (i.e. .With(matcher)),
1069  // describes it to the ostream.
1070  void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
1071  if (extra_matcher_specified_) {
1072  *os << " Expected args: ";
1073  extra_matcher_.DescribeTo(os);
1074  *os << "\n";
1075  }
1076  }
1077 
1078  private:
1079  template <typename Function>
1080  friend class FunctionMocker;
1081 
1082  // Returns an Expectation object that references and co-owns this
1083  // expectation.
1084  Expectation GetHandle() override { return owner_->GetHandleOf(this); }
1085 
1086  // The following methods will be called only after the EXPECT_CALL()
1087  // statement finishes and when the current thread holds
1088  // g_gmock_mutex.
1089 
1090  // Returns true if this expectation matches the given arguments.
1091  bool Matches(const ArgumentTuple& args) const
1092  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1093  g_gmock_mutex.AssertHeld();
1094  return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1095  }
1096 
1097  // Returns true if this expectation should handle the given arguments.
1098  bool ShouldHandleArguments(const ArgumentTuple& args) const
1099  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1100  g_gmock_mutex.AssertHeld();
1101 
1102  // In case the action count wasn't checked when the expectation
1103  // was defined (e.g. if this expectation has no WillRepeatedly()
1104  // or RetiresOnSaturation() clause), we check it when the
1105  // expectation is used for the first time.
1106  CheckActionCountIfNotDone();
1107  return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1108  }
1109 
1110  // Describes the result of matching the arguments against this
1111  // expectation to the given ostream.
1112  void ExplainMatchResultTo(
1113  const ArgumentTuple& args,
1114  ::std::ostream* os) const
1115  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1116  g_gmock_mutex.AssertHeld();
1117 
1118  if (is_retired()) {
1119  *os << " Expected: the expectation is active\n"
1120  << " Actual: it is retired\n";
1121  } else if (!Matches(args)) {
1122  if (!TupleMatches(matchers_, args)) {
1124  }
1125  StringMatchResultListener listener;
1126  if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1127  *os << " Expected args: ";
1128  extra_matcher_.DescribeTo(os);
1129  *os << "\n Actual: don't match";
1130 
1131  internal::PrintIfNotEmpty(listener.str(), os);
1132  *os << "\n";
1133  }
1134  } else if (!AllPrerequisitesAreSatisfied()) {
1135  *os << " Expected: all pre-requisites are satisfied\n"
1136  << " Actual: the following immediate pre-requisites "
1137  << "are not satisfied:\n";
1138  ExpectationSet unsatisfied_prereqs;
1139  FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1140  int i = 0;
1141  for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1142  it != unsatisfied_prereqs.end(); ++it) {
1143  it->expectation_base()->DescribeLocationTo(os);
1144  *os << "pre-requisite #" << i++ << "\n";
1145  }
1146  *os << " (end of pre-requisites)\n";
1147  } else {
1148  // This line is here just for completeness' sake. It will never
1149  // be executed as currently the ExplainMatchResultTo() function
1150  // is called only when the mock function call does NOT match the
1151  // expectation.
1152  *os << "The call matches the expectation.\n";
1153  }
1154  }
1155 
1156  // Returns the action that should be taken for the current invocation.
1157  const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
1158  const ArgumentTuple& args) const
1159  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1160  g_gmock_mutex.AssertHeld();
1161  const int count = call_count();
1162  Assert(count >= 1, __FILE__, __LINE__,
1163  "call_count() is <= 0 when GetCurrentAction() is "
1164  "called - this should never happen.");
1165 
1166  const int action_count = static_cast<int>(untyped_actions_.size());
1167  if (action_count > 0 && !repeated_action_specified_ &&
1168  count > action_count) {
1169  // If there is at least one WillOnce() and no WillRepeatedly(),
1170  // we warn the user when the WillOnce() clauses ran out.
1171  ::std::stringstream ss;
1172  DescribeLocationTo(&ss);
1173  ss << "Actions ran out in " << source_text() << "...\n"
1174  << "Called " << count << " times, but only "
1175  << action_count << " WillOnce()"
1176  << (action_count == 1 ? " is" : "s are") << " specified - ";
1177  mocker->DescribeDefaultActionTo(args, &ss);
1178  Log(kWarning, ss.str(), 1);
1179  }
1180 
1181  return count <= action_count
1182  ? *static_cast<const Action<F>*>(
1183  untyped_actions_[static_cast<size_t>(count - 1)])
1184  : repeated_action();
1185  }
1186 
1187  // Given the arguments of a mock function call, if the call will
1188  // over-saturate this expectation, returns the default action;
1189  // otherwise, returns the next action in this expectation. Also
1190  // describes *what* happened to 'what', and explains *why* Google
1191  // Mock does it to 'why'. This method is not const as it calls
1192  // IncrementCallCount(). A return value of NULL means the default
1193  // action.
1194  const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
1195  const ArgumentTuple& args,
1196  ::std::ostream* what,
1197  ::std::ostream* why)
1198  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1199  g_gmock_mutex.AssertHeld();
1200  if (IsSaturated()) {
1201  // We have an excessive call.
1202  IncrementCallCount();
1203  *what << "Mock function called more times than expected - ";
1204  mocker->DescribeDefaultActionTo(args, what);
1205  DescribeCallCountTo(why);
1206 
1207  return nullptr;
1208  }
1209 
1210  IncrementCallCount();
1211  RetireAllPreRequisites();
1212 
1213  if (retires_on_saturation_ && IsSaturated()) {
1214  Retire();
1215  }
1216 
1217  // Must be done after IncrementCount()!
1218  *what << "Mock function call matches " << source_text() <<"...\n";
1219  return &(GetCurrentAction(mocker, args));
1220  }
1221 
1222  // All the fields below won't change once the EXPECT_CALL()
1223  // statement finishes.
1224  FunctionMocker<F>* const owner_;
1225  ArgumentMatcherTuple matchers_;
1226  Matcher<const ArgumentTuple&> extra_matcher_;
1227  Action<F> repeated_action_;
1228 
1229  GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1230 }; // class TypedExpectation
1231 
1232 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1233 // specifying the default behavior of, or expectation on, a mock
1234 // function.
1235 
1236 // Note: class MockSpec really belongs to the ::testing namespace.
1237 // However if we define it in ::testing, MSVC will complain when
1238 // classes in ::testing::internal declare it as a friend class
1239 // template. To workaround this compiler bug, we define MockSpec in
1240 // ::testing::internal and import it into ::testing.
1241 
1242 // Logs a message including file and line number information.
1244  const char* file, int line,
1245  const std::string& message);
1246 
1247 template <typename F>
1248 class MockSpec {
1249  public:
1250  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1251  typedef typename internal::Function<F>::ArgumentMatcherTuple
1252  ArgumentMatcherTuple;
1253 
1254  // Constructs a MockSpec object, given the function mocker object
1255  // that the spec is associated with.
1256  MockSpec(internal::FunctionMocker<F>* function_mocker,
1257  const ArgumentMatcherTuple& matchers)
1258  : function_mocker_(function_mocker), matchers_(matchers) {}
1259 
1260  // Adds a new default action spec to the function mocker and returns
1261  // the newly created spec.
1262  internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1263  const char* file, int line, const char* obj, const char* call) {
1264  LogWithLocation(internal::kInfo, file, line,
1265  std::string("ON_CALL(") + obj + ", " + call + ") invoked");
1266  return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1267  }
1268 
1269  // Adds a new expectation spec to the function mocker and returns
1270  // the newly created spec.
1271  internal::TypedExpectation<F>& InternalExpectedAt(
1272  const char* file, int line, const char* obj, const char* call) {
1273  const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1274  call + ")");
1275  LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1276  return function_mocker_->AddNewExpectation(
1277  file, line, source_text, matchers_);
1278  }
1279 
1280  // This operator overload is used to swallow the superfluous parameter list
1281  // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1282  // explanation.
1283  MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1284  return *this;
1285  }
1286 
1287  private:
1288  template <typename Function>
1289  friend class internal::FunctionMocker;
1290 
1291  // The function mocker that owns this spec.
1292  internal::FunctionMocker<F>* const function_mocker_;
1293  // The argument matchers specified in the spec.
1294  ArgumentMatcherTuple matchers_;
1295 
1296  GTEST_DISALLOW_ASSIGN_(MockSpec);
1297 }; // class MockSpec
1298 
1299 // Wrapper type for generically holding an ordinary value or lvalue reference.
1300 // If T is not a reference type, it must be copyable or movable.
1301 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1302 // T is a move-only value type (which means that it will always be copyable
1303 // if the current platform does not support move semantics).
1304 //
1305 // The primary template defines handling for values, but function header
1306 // comments describe the contract for the whole template (including
1307 // specializations).
1308 template <typename T>
1309 class ReferenceOrValueWrapper {
1310  public:
1311  // Constructs a wrapper from the given value/reference.
1312  explicit ReferenceOrValueWrapper(T value)
1313  : value_(std::move(value)) {
1314  }
1315 
1316  // Unwraps and returns the underlying value/reference, exactly as
1317  // originally passed. The behavior of calling this more than once on
1318  // the same object is unspecified.
1319  T Unwrap() { return std::move(value_); }
1320 
1321  // Provides nondestructive access to the underlying value/reference.
1322  // Always returns a const reference (more precisely,
1323  // const RemoveReference<T>&). The behavior of calling this after
1324  // calling Unwrap on the same object is unspecified.
1325  const T& Peek() const {
1326  return value_;
1327  }
1328 
1329  private:
1330  T value_;
1331 };
1332 
1333 // Specialization for lvalue reference types. See primary template
1334 // for documentation.
1335 template <typename T>
1336 class ReferenceOrValueWrapper<T&> {
1337  public:
1338  // Workaround for debatable pass-by-reference lint warning (c-library-team
1339  // policy precludes NOLINT in this context)
1340  typedef T& reference;
1341  explicit ReferenceOrValueWrapper(reference ref)
1342  : value_ptr_(&ref) {}
1343  T& Unwrap() { return *value_ptr_; }
1344  const T& Peek() const { return *value_ptr_; }
1345 
1346  private:
1347  T* value_ptr_;
1348 };
1349 
1350 // MSVC warns about using 'this' in base member initializer list, so
1351 // we need to temporarily disable the warning. We have to do it for
1352 // the entire class to suppress the warning, even though it's about
1353 // the constructor only.
1355 
1356 // C++ treats the void type specially. For example, you cannot define
1357 // a void-typed variable or pass a void value to a function.
1358 // ActionResultHolder<T> holds a value of type T, where T must be a
1359 // copyable type or void (T doesn't need to be default-constructable).
1360 // It hides the syntactic difference between void and other types, and
1361 // is used to unify the code for invoking both void-returning and
1362 // non-void-returning mock functions.
1363 
1364 // Untyped base class for ActionResultHolder<T>.
1365 class UntypedActionResultHolderBase {
1366  public:
1367  virtual ~UntypedActionResultHolderBase() {}
1368 
1369  // Prints the held value as an action's result to os.
1370  virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1371 };
1372 
1373 // This generic definition is used when T is not void.
1374 template <typename T>
1375 class ActionResultHolder : public UntypedActionResultHolderBase {
1376  public:
1377  // Returns the held value. Must not be called more than once.
1378  T Unwrap() {
1379  return result_.Unwrap();
1380  }
1381 
1382  // Prints the held value as an action's result to os.
1383  void PrintAsActionResult(::std::ostream* os) const override {
1384  *os << "\n Returns: ";
1385  // T may be a reference type, so we don't use UniversalPrint().
1386  UniversalPrinter<T>::Print(result_.Peek(), os);
1387  }
1388 
1389  // Performs the given mock function's default action and returns the
1390  // result in a new-ed ActionResultHolder.
1391  template <typename F>
1392  static ActionResultHolder* PerformDefaultAction(
1393  const FunctionMocker<F>* func_mocker,
1394  typename Function<F>::ArgumentTuple&& args,
1395  const std::string& call_description) {
1396  return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1397  std::move(args), call_description)));
1398  }
1399 
1400  // Performs the given action and returns the result in a new-ed
1401  // ActionResultHolder.
1402  template <typename F>
1403  static ActionResultHolder* PerformAction(
1404  const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
1405  return new ActionResultHolder(
1406  Wrapper(action.Perform(std::move(args))));
1407  }
1408 
1409  private:
1410  typedef ReferenceOrValueWrapper<T> Wrapper;
1411 
1412  explicit ActionResultHolder(Wrapper result)
1413  : result_(std::move(result)) {
1414  }
1415 
1416  Wrapper result_;
1417 
1418  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1419 };
1420 
1421 // Specialization for T = void.
1422 template <>
1423 class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1424  public:
1425  void Unwrap() { }
1426 
1427  void PrintAsActionResult(::std::ostream* /* os */) const override {}
1428 
1429  // Performs the given mock function's default action and returns ownership
1430  // of an empty ActionResultHolder*.
1431  template <typename F>
1432  static ActionResultHolder* PerformDefaultAction(
1433  const FunctionMocker<F>* func_mocker,
1434  typename Function<F>::ArgumentTuple&& args,
1435  const std::string& call_description) {
1436  func_mocker->PerformDefaultAction(std::move(args), call_description);
1437  return new ActionResultHolder;
1438  }
1439 
1440  // Performs the given action and returns ownership of an empty
1441  // ActionResultHolder*.
1442  template <typename F>
1443  static ActionResultHolder* PerformAction(
1444  const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
1445  action.Perform(std::move(args));
1446  return new ActionResultHolder;
1447  }
1448 
1449  private:
1450  ActionResultHolder() {}
1451  GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1452 };
1453 
1454 template <typename F>
1455 class FunctionMocker;
1456 
1457 template <typename R, typename... Args>
1458 class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
1459  using F = R(Args...);
1460 
1461  public:
1462  using Result = R;
1463  using ArgumentTuple = std::tuple<Args...>;
1464  using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1465 
1466  FunctionMocker() {}
1467 
1468  // There is no generally useful and implementable semantics of
1469  // copying a mock object, so copying a mock is usually a user error.
1470  // Thus we disallow copying function mockers. If the user really
1471  // wants to copy a mock object, they should implement their own copy
1472  // operation, for example:
1473  //
1474  // class MockFoo : public Foo {
1475  // public:
1476  // // Defines a copy constructor explicitly.
1477  // MockFoo(const MockFoo& src) {}
1478  // ...
1479  // };
1480  FunctionMocker(const FunctionMocker&) = delete;
1481  FunctionMocker& operator=(const FunctionMocker&) = delete;
1482 
1483  // The destructor verifies that all expectations on this mock
1484  // function have been satisfied. If not, it will report Google Test
1485  // non-fatal failures for the violations.
1486  ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1487  MutexLock l(&g_gmock_mutex);
1488  VerifyAndClearExpectationsLocked();
1489  Mock::UnregisterLocked(this);
1490  ClearDefaultActionsLocked();
1491  }
1492 
1493  // Returns the ON_CALL spec that matches this mock function with the
1494  // given arguments; returns NULL if no matching ON_CALL is found.
1495  // L = *
1496  const OnCallSpec<F>* FindOnCallSpec(
1497  const ArgumentTuple& args) const {
1498  for (UntypedOnCallSpecs::const_reverse_iterator it
1499  = untyped_on_call_specs_.rbegin();
1500  it != untyped_on_call_specs_.rend(); ++it) {
1501  const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1502  if (spec->Matches(args))
1503  return spec;
1504  }
1505 
1506  return nullptr;
1507  }
1508 
1509  // Performs the default action of this mock function on the given
1510  // arguments and returns the result. Asserts (or throws if
1511  // exceptions are enabled) with a helpful call descrption if there
1512  // is no valid return value. This method doesn't depend on the
1513  // mutable state of this object, and thus can be called concurrently
1514  // without locking.
1515  // L = *
1516  Result PerformDefaultAction(ArgumentTuple&& args,
1517  const std::string& call_description) const {
1518  const OnCallSpec<F>* const spec =
1519  this->FindOnCallSpec(args);
1520  if (spec != nullptr) {
1521  return spec->GetAction().Perform(std::move(args));
1522  }
1523  const std::string message =
1524  call_description +
1525  "\n The mock function has no default action "
1526  "set, and its return type has no default value set.";
1527 #if GTEST_HAS_EXCEPTIONS
1528  if (!DefaultValue<Result>::Exists()) {
1529  throw std::runtime_error(message);
1530  }
1531 #else
1532  Assert(DefaultValue<Result>::Exists(), "", -1, message);
1533 #endif
1534  return DefaultValue<Result>::Get();
1535  }
1536 
1537  // Performs the default action with the given arguments and returns
1538  // the action's result. The call description string will be used in
1539  // the error message to describe the call in the case the default
1540  // action fails. The caller is responsible for deleting the result.
1541  // L = *
1542  UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1543  void* untyped_args, // must point to an ArgumentTuple
1544  const std::string& call_description) const override {
1545  ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1546  return ResultHolder::PerformDefaultAction(this, std::move(*args),
1547  call_description);
1548  }
1549 
1550  // Performs the given action with the given arguments and returns
1551  // the action's result. The caller is responsible for deleting the
1552  // result.
1553  // L = *
1554  UntypedActionResultHolderBase* UntypedPerformAction(
1555  const void* untyped_action, void* untyped_args) const override {
1556  // Make a copy of the action before performing it, in case the
1557  // action deletes the mock object (and thus deletes itself).
1558  const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1559  ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1560  return ResultHolder::PerformAction(action, std::move(*args));
1561  }
1562 
1563  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1564  // clears the ON_CALL()s set on this mock function.
1565  void ClearDefaultActionsLocked() override
1566  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1567  g_gmock_mutex.AssertHeld();
1568 
1569  // Deleting our default actions may trigger other mock objects to be
1570  // deleted, for example if an action contains a reference counted smart
1571  // pointer to that mock object, and that is the last reference. So if we
1572  // delete our actions within the context of the global mutex we may deadlock
1573  // when this method is called again. Instead, make a copy of the set of
1574  // actions to delete, clear our set within the mutex, and then delete the
1575  // actions outside of the mutex.
1576  UntypedOnCallSpecs specs_to_delete;
1577  untyped_on_call_specs_.swap(specs_to_delete);
1578 
1579  g_gmock_mutex.Unlock();
1580  for (UntypedOnCallSpecs::const_iterator it =
1581  specs_to_delete.begin();
1582  it != specs_to_delete.end(); ++it) {
1583  delete static_cast<const OnCallSpec<F>*>(*it);
1584  }
1585 
1586  // Lock the mutex again, since the caller expects it to be locked when we
1587  // return.
1588  g_gmock_mutex.Lock();
1589  }
1590 
1591  // Returns the result of invoking this mock function with the given
1592  // arguments. This function can be safely called from multiple
1593  // threads concurrently.
1594  Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1595  ArgumentTuple tuple(std::forward<Args>(args)...);
1596  std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
1597  this->UntypedInvokeWith(static_cast<void*>(&tuple))));
1598  return holder->Unwrap();
1599  }
1600 
1601  MockSpec<F> With(Matcher<Args>... m) {
1602  return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
1603  }
1604 
1605  protected:
1606  template <typename Function>
1607  friend class MockSpec;
1608 
1609  typedef ActionResultHolder<Result> ResultHolder;
1610 
1611  // Adds and returns a default action spec for this mock function.
1612  OnCallSpec<F>& AddNewOnCallSpec(
1613  const char* file, int line,
1614  const ArgumentMatcherTuple& m)
1615  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1616  Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1617  OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1618  untyped_on_call_specs_.push_back(on_call_spec);
1619  return *on_call_spec;
1620  }
1621 
1622  // Adds and returns an expectation spec for this mock function.
1623  TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1624  const std::string& source_text,
1625  const ArgumentMatcherTuple& m)
1626  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1627  Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1628  TypedExpectation<F>* const expectation =
1629  new TypedExpectation<F>(this, file, line, source_text, m);
1630  const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1631  // See the definition of untyped_expectations_ for why access to
1632  // it is unprotected here.
1633  untyped_expectations_.push_back(untyped_expectation);
1634 
1635  // Adds this expectation into the implicit sequence if there is one.
1636  Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1637  if (implicit_sequence != nullptr) {
1638  implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1639  }
1640 
1641  return *expectation;
1642  }
1643 
1644  private:
1645  template <typename Func> friend class TypedExpectation;
1646 
1647  // Some utilities needed for implementing UntypedInvokeWith().
1648 
1649  // Describes what default action will be performed for the given
1650  // arguments.
1651  // L = *
1652  void DescribeDefaultActionTo(const ArgumentTuple& args,
1653  ::std::ostream* os) const {
1654  const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1655 
1656  if (spec == nullptr) {
1657  *os << (std::is_void<Result>::value ? "returning directly.\n"
1658  : "returning default value.\n");
1659  } else {
1660  *os << "taking default action specified at:\n"
1661  << FormatFileLocation(spec->file(), spec->line()) << "\n";
1662  }
1663  }
1664 
1665  // Writes a message that the call is uninteresting (i.e. neither
1666  // explicitly expected nor explicitly unexpected) to the given
1667  // ostream.
1668  void UntypedDescribeUninterestingCall(const void* untyped_args,
1669  ::std::ostream* os) const override
1670  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1671  const ArgumentTuple& args =
1672  *static_cast<const ArgumentTuple*>(untyped_args);
1673  *os << "Uninteresting mock function call - ";
1674  DescribeDefaultActionTo(args, os);
1675  *os << " Function call: " << Name();
1676  UniversalPrint(args, os);
1677  }
1678 
1679  // Returns the expectation that matches the given function arguments
1680  // (or NULL is there's no match); when a match is found,
1681  // untyped_action is set to point to the action that should be
1682  // performed (or NULL if the action is "do default"), and
1683  // is_excessive is modified to indicate whether the call exceeds the
1684  // expected number.
1685  //
1686  // Critical section: We must find the matching expectation and the
1687  // corresponding action that needs to be taken in an ATOMIC
1688  // transaction. Otherwise another thread may call this mock
1689  // method in the middle and mess up the state.
1690  //
1691  // However, performing the action has to be left out of the critical
1692  // section. The reason is that we have no control on what the
1693  // action does (it can invoke an arbitrary user function or even a
1694  // mock function) and excessive locking could cause a dead lock.
1695  const ExpectationBase* UntypedFindMatchingExpectation(
1696  const void* untyped_args, const void** untyped_action, bool* is_excessive,
1697  ::std::ostream* what, ::std::ostream* why) override
1698  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1699  const ArgumentTuple& args =
1700  *static_cast<const ArgumentTuple*>(untyped_args);
1701  MutexLock l(&g_gmock_mutex);
1702  TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1703  if (exp == nullptr) { // A match wasn't found.
1704  this->FormatUnexpectedCallMessageLocked(args, what, why);
1705  return nullptr;
1706  }
1707 
1708  // This line must be done before calling GetActionForArguments(),
1709  // which will increment the call count for *exp and thus affect
1710  // its saturation status.
1711  *is_excessive = exp->IsSaturated();
1712  const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1713  if (action != nullptr && action->IsDoDefault())
1714  action = nullptr; // Normalize "do default" to NULL.
1715  *untyped_action = action;
1716  return exp;
1717  }
1718 
1719  // Prints the given function arguments to the ostream.
1720  void UntypedPrintArgs(const void* untyped_args,
1721  ::std::ostream* os) const override {
1722  const ArgumentTuple& args =
1723  *static_cast<const ArgumentTuple*>(untyped_args);
1724  UniversalPrint(args, os);
1725  }
1726 
1727  // Returns the expectation that matches the arguments, or NULL if no
1728  // expectation matches them.
1729  TypedExpectation<F>* FindMatchingExpectationLocked(
1730  const ArgumentTuple& args) const
1731  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1732  g_gmock_mutex.AssertHeld();
1733  // See the definition of untyped_expectations_ for why access to
1734  // it is unprotected here.
1735  for (typename UntypedExpectations::const_reverse_iterator it =
1736  untyped_expectations_.rbegin();
1737  it != untyped_expectations_.rend(); ++it) {
1738  TypedExpectation<F>* const exp =
1739  static_cast<TypedExpectation<F>*>(it->get());
1740  if (exp->ShouldHandleArguments(args)) {
1741  return exp;
1742  }
1743  }
1744  return nullptr;
1745  }
1746 
1747  // Returns a message that the arguments don't match any expectation.
1748  void FormatUnexpectedCallMessageLocked(
1749  const ArgumentTuple& args,
1750  ::std::ostream* os,
1751  ::std::ostream* why) const
1752  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1753  g_gmock_mutex.AssertHeld();
1754  *os << "\nUnexpected mock function call - ";
1755  DescribeDefaultActionTo(args, os);
1756  PrintTriedExpectationsLocked(args, why);
1757  }
1758 
1759  // Prints a list of expectations that have been tried against the
1760  // current mock function call.
1761  void PrintTriedExpectationsLocked(
1762  const ArgumentTuple& args,
1763  ::std::ostream* why) const
1764  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1765  g_gmock_mutex.AssertHeld();
1766  const size_t count = untyped_expectations_.size();
1767  *why << "Google Mock tried the following " << count << " "
1768  << (count == 1 ? "expectation, but it didn't match" :
1769  "expectations, but none matched")
1770  << ":\n";
1771  for (size_t i = 0; i < count; i++) {
1772  TypedExpectation<F>* const expectation =
1773  static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1774  *why << "\n";
1775  expectation->DescribeLocationTo(why);
1776  if (count > 1) {
1777  *why << "tried expectation #" << i << ": ";
1778  }
1779  *why << expectation->source_text() << "...\n";
1780  expectation->ExplainMatchResultTo(args, why);
1781  expectation->DescribeCallCountTo(why);
1782  }
1783  }
1784 }; // class FunctionMocker
1785 
1787 
1788 // Reports an uninteresting call (whose description is in msg) in the
1789 // manner specified by 'reaction'.
1790 void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
1791 
1792 } // namespace internal
1793 
1794 // A MockFunction<F> class has one mock method whose type is F. It is
1795 // useful when you just want your test code to emit some messages and
1796 // have Google Mock verify the right messages are sent (and perhaps at
1797 // the right times). For example, if you are exercising code:
1798 //
1799 // Foo(1);
1800 // Foo(2);
1801 // Foo(3);
1802 //
1803 // and want to verify that Foo(1) and Foo(3) both invoke
1804 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1805 //
1806 // TEST(FooTest, InvokesBarCorrectly) {
1807 // MyMock mock;
1808 // MockFunction<void(string check_point_name)> check;
1809 // {
1810 // InSequence s;
1811 //
1812 // EXPECT_CALL(mock, Bar("a"));
1813 // EXPECT_CALL(check, Call("1"));
1814 // EXPECT_CALL(check, Call("2"));
1815 // EXPECT_CALL(mock, Bar("a"));
1816 // }
1817 // Foo(1);
1818 // check.Call("1");
1819 // Foo(2);
1820 // check.Call("2");
1821 // Foo(3);
1822 // }
1823 //
1824 // The expectation spec says that the first Bar("a") must happen
1825 // before check point "1", the second Bar("a") must happen after check
1826 // point "2", and nothing should happen between the two check
1827 // points. The explicit check points make it easy to tell which
1828 // Bar("a") is called by which call to Foo().
1829 //
1830 // MockFunction<F> can also be used to exercise code that accepts
1831 // std::function<F> callbacks. To do so, use AsStdFunction() method
1832 // to create std::function proxy forwarding to original object's Call.
1833 // Example:
1834 //
1835 // TEST(FooTest, RunsCallbackWithBarArgument) {
1836 // MockFunction<int(string)> callback;
1837 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1838 // Foo(callback.AsStdFunction());
1839 // }
1840 template <typename F>
1841 class MockFunction;
1842 
1843 template <typename R, typename... Args>
1844 class MockFunction<R(Args...)> {
1845  public:
1846  MockFunction() {}
1847  MockFunction(const MockFunction&) = delete;
1848  MockFunction& operator=(const MockFunction&) = delete;
1849 
1850  std::function<R(Args...)> AsStdFunction() {
1851  return [this](Args... args) -> R {
1852  return this->Call(std::forward<Args>(args)...);
1853  };
1854  }
1855 
1856  // Implementation detail: the expansion of the MOCK_METHOD macro.
1857  R Call(Args... args) {
1858  mock_.SetOwnerAndName(this, "Call");
1859  return mock_.Invoke(std::forward<Args>(args)...);
1860  }
1861 
1862  internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1863  mock_.RegisterOwner(this);
1864  return mock_.With(std::move(m)...);
1865  }
1866 
1867  internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
1868  R (*)(Args...)) {
1869  return this->gmock_Call(::testing::A<Args>()...);
1870  }
1871 
1872  private:
1873  internal::FunctionMocker<R(Args...)> mock_;
1874 };
1875 
1876 // The style guide prohibits "using" statements in a namespace scope
1877 // inside a header file. However, the MockSpec class template is
1878 // meant to be defined in the ::testing namespace. The following line
1879 // is just a trick for working around a bug in MSVC 8.0, which cannot
1880 // handle it if we define MockSpec in ::testing.
1881 using internal::MockSpec;
1882 
1883 // Const(x) is a convenient function for obtaining a const reference
1884 // to x. This is useful for setting expectations on an overloaded
1885 // const mock method, e.g.
1886 //
1887 // class MockFoo : public FooInterface {
1888 // public:
1889 // MOCK_METHOD0(Bar, int());
1890 // MOCK_CONST_METHOD0(Bar, int&());
1891 // };
1892 //
1893 // MockFoo foo;
1894 // // Expects a call to non-const MockFoo::Bar().
1895 // EXPECT_CALL(foo, Bar());
1896 // // Expects a call to const MockFoo::Bar().
1897 // EXPECT_CALL(Const(foo), Bar());
1898 template <typename T>
1899 inline const T& Const(const T& x) { return x; }
1900 
1901 // Constructs an Expectation object that references and co-owns exp.
1902 inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1903  : expectation_base_(exp.GetHandle().expectation_base()) {}
1904 
1905 } // namespace testing
1906 
1908 
1909 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1910 // required to avoid compile errors when the name of the method used in call is
1911 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1912 // tests in internal/gmock-spec-builders_test.cc for more details.
1913 //
1914 // This macro supports statements both with and without parameter matchers. If
1915 // the parameter list is omitted, gMock will accept any parameters, which allows
1916 // tests to be written that don't need to encode the number of method
1917 // parameter. This technique may only be used for non-overloaded methods.
1918 //
1919 // // These are the same:
1920 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1921 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1922 //
1923 // // As are these:
1924 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1925 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1926 //
1927 // // Can also specify args if you want, of course:
1928 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1929 //
1930 // // Overloads work as long as you specify parameters:
1931 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1932 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1933 //
1934 // // Oops! Which overload did you want?
1935 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1936 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1937 //
1938 // How this works: The mock class uses two overloads of the gmock_Method
1939 // expectation setter method plus an operator() overload on the MockSpec object.
1940 // In the matcher list form, the macro expands to:
1941 //
1942 // // This statement:
1943 // ON_CALL(mock, TwoArgsMethod(_, 45))...
1944 //
1945 // // ...expands to:
1946 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1947 // |-------------v---------------||------------v-------------|
1948 // invokes first overload swallowed by operator()
1949 //
1950 // // ...which is essentially:
1951 // mock.gmock_TwoArgsMethod(_, 45)...
1952 //
1953 // Whereas the form without a matcher list:
1954 //
1955 // // This statement:
1956 // ON_CALL(mock, TwoArgsMethod)...
1957 //
1958 // // ...expands to:
1959 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1960 // |-----------------------v--------------------------|
1961 // invokes second overload
1962 //
1963 // // ...which is essentially:
1964 // mock.gmock_TwoArgsMethod(_, _)...
1965 //
1966 // The WithoutMatchers() argument is used to disambiguate overloads and to
1967 // block the caller from accidentally invoking the second overload directly. The
1968 // second argument is an internal type derived from the method signature. The
1969 // failure to disambiguate two overloads of this method in the ON_CALL statement
1970 // is how we block callers from setting expectations on overloaded methods.
1971 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1972  ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
1973  nullptr) \
1974  .Setter(__FILE__, __LINE__, #mock_expr, #call)
1975 
1976 #define ON_CALL(obj, call) \
1977  GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1978 
1979 #define EXPECT_CALL(obj, call) \
1980  GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
1981 
1982 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
_gevent_test_main.result
result
Definition: _gevent_test_main.py:96
obj
OPENSSL_EXPORT const ASN1_OBJECT * obj
Definition: x509.h:1671
testing
Definition: aws_request_signer_test.cc:25
regen-readme.it
it
Definition: regen-readme.py:15
testing::internal::ExplainMatchFailureTupleTo
void ExplainMatchFailureTupleTo(const MatcherTuple &matchers, const ValueTuple &values, ::std::ostream *os)
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:5629
bloat_diff.severity
def severity
Definition: bloat_diff.py:143
grpc_event_engine::experimental::slice_detail::operator==
bool operator==(const BaseSlice &a, const BaseSlice &b)
Definition: include/grpc/event_engine/slice.h:117
MutexLock
#define MutexLock(x)
Definition: bloaty/third_party/re2/util/mutex.h:125
file
const grpc_generator::File * file
Definition: python_private_generator.h:38
GTEST_API_
#define GTEST_API_
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:754
begin
char * begin
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1007
Assert
#define Assert(cond, msg)
Definition: bloaty/third_party/zlib/zutil.h:248
testing::internal::Log
GTEST_API_ void Log(LogSeverity severity, const std::string &message, int stack_frames_to_skip)
Definition: bloaty/third_party/googletest/googlemock/src/gmock-internal-utils.cc:149
std::tr1::make_tuple
tuple make_tuple()
Definition: cares/cares/test/gmock-1.8.0/gtest/gtest.h:1619
Expectation::Expectation
Expectation(const char *f, int l, grpc_completion_type t, void *tag_arg, bool check_success_arg, int success_arg, bool *seen_arg)
Definition: cq_verifier.cc:57
file_
FileDescriptorProto * file_
Definition: bloaty/third_party/protobuf/src/google/protobuf/compiler/annotation_test_util.cc:68
testing::gtest_printers_test::Print
std::string Print(const T &value)
Definition: bloaty/third_party/googletest/googletest/test/googletest-printers-test.cc:233
testing::internal::FormatFileLocation
GTEST_API_ ::std::string FormatFileLocation(const char *file, int line)
Definition: bloaty/third_party/googletest/googletest/src/gtest-port.cc:1018
line_
int line_
Definition: bloaty/third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc:1468
matchers
XdsRouteConfigResource::Route::Matchers matchers
Definition: xds_server_config_fetcher.cc:317
google::protobuf::operator+=
Duration & operator+=(Duration &d1, const Duration &d2)
Definition: third_party/bloaty/third_party/protobuf/src/google/protobuf/util/time_util.cc:406
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
file
Definition: bloaty/third_party/zlib/examples/gzappend.c:170
setup.name
name
Definition: setup.py:542
matchers_
std::tuple< M... > matchers_
Definition: abseil-cpp/absl/container/internal/layout_test.cc:1261
name_
const std::string name_
Definition: priority.cc:233
testing::internal::kWarning
@ kWarning
Definition: bloaty/third_party/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h:296
testing::Const
const T & Const(const T &x)
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:11004
run_interop_tests.spec
def spec
Definition: run_interop_tests.py:1394
message
char * message
Definition: libuv/docs/code/tty-gravity/main.c:12
T
#define T(upbtypeconst, upbtype, ctype, default_value)
testing::internal::LogWithLocation
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char *file, int line, const std::string &message)
Definition: bloaty/third_party/googletest/googlemock/src/gmock-spec-builders.cc:69
call
FilterStackCall * call
Definition: call.cc:750
namespace
Definition: namespace.py:1
absl::synchronization_internal::Get
static GraphId Get(const IdMap &id, int num)
Definition: abseil-cpp/absl/synchronization/internal/graphcycles_test.cc:44
GTEST_ATTRIBUTE_UNUSED_
#define GTEST_ATTRIBUTE_UNUSED_
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:655
GTEST_DISALLOW_ASSIGN_
#define GTEST_DISALLOW_ASSIGN_(type)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:678
asyncio_get_stats.args
args
Definition: asyncio_get_stats.py:40
absl::move
constexpr absl::remove_reference_t< T > && move(T &&t) noexcept
Definition: abseil-cpp/absl/utility/utility.h:221
end
char * end
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1008
hpack_encoder_fixtures::Args
Args({0, 16384})
re2::Result
TestInstance::Result Result
Definition: bloaty/third_party/re2/re2/testing/tester.cc:96
testing::internal::TupleMatches
bool TupleMatches(const MatcherTuple &matcher_tuple, const ValueTuple &value_tuple)
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:5615
expectations_
std::map< void *, bool > expectations_
Definition: async_end2end_test.cc:201
GTEST_EXCLUSIVE_LOCK_REQUIRED_
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:2198
ref
unsigned ref
Definition: cxa_demangle.cpp:4909
absl::compare_internal::value_type
int8_t value_type
Definition: abseil-cpp/absl/types/compare.h:45
operator!=
bool operator!=(const Bytes &a, const Bytes &b)
Definition: boringssl-with-bazel/src/crypto/test/test_util.h:58
GTEST_LOCK_EXCLUDED_
#define GTEST_LOCK_EXCLUDED_(locks)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:2199
testing::internal::CallReaction
CallReaction
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:9539
x
int x
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3610
testing::internal::kFail
@ kFail
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:9542
GTEST_DISABLE_MSC_WARNINGS_PUSH_
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251) namespace testing
Definition: bloaty/third_party/googletest/googlemock/include/gmock/gmock-spec-builders.h:84
F
#define F(b, c, d)
Definition: md4.c:112
n
int n
Definition: abseil-cpp/absl/container/btree_test.cc:1080
msg
std::string msg
Definition: client_interceptors_end2end_test.cc:372
testing::internal::LogSeverity
LogSeverity
Definition: bloaty/third_party/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h:294
GTEST_DISALLOW_COPY_AND_ASSIGN_
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:683
Mock
Definition: bloaty/third_party/googletest/googlemock/test/gmock-nice-strict_test.cc:40
value_
int value_
Definition: orphanable_test.cc:38
value
const char * value
Definition: hpack_parser_table.cc:165
testing::Matches
internal::MatcherAsPredicate< M > Matches(M matcher)
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:9160
client.action
action
Definition: examples/python/xds/client.py:49
google::protobuf.internal::Cardinality
Cardinality
Definition: bloaty/third_party/protobuf/src/google/protobuf/generated_message_table_driven_lite.h:68
count
int * count
Definition: bloaty/third_party/googletest/googlemock/test/gmock_stress_test.cc:96
tests.unit._server_ssl_cert_config_test.Call
Call
Definition: _server_ssl_cert_config_test.py:70
testing::internal::kAllow
@ kAllow
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:9540
google::protobuf.internal::Mutex
WrappedMutex Mutex
Definition: bloaty/third_party/protobuf/src/google/protobuf/stubs/mutex.h:113
testing::internal::kWarn
@ kWarn
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:9541
A
Definition: miscompile_with_no_unique_address_test.cc:23
Expectation
Definition: cq_verifier.cc:56
regen-readme.line
line
Definition: regen-readme.py:30
testing::Invoke
std::decay< FunctionImpl >::type Invoke(FunctionImpl &&function_impl)
Definition: bloaty/third_party/googletest/googlemock/include/gmock/gmock-actions.h:1084
GTEST_DISABLE_MSC_WARNINGS_POP_
#define GTEST_DISABLE_MSC_WARNINGS_POP_()
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:309
testing::internal::PrintIfNotEmpty
void PrintIfNotEmpty(const internal::string &explanation, ::std::ostream *os)
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:5497
internal
Definition: benchmark/test/output_test_helper.cc:20
testing::Exactly
GTEST_API_ Cardinality Exactly(int n)
Definition: bloaty/third_party/googletest/googlemock/src/gmock-cardinalities.cc:153
mutex_
internal::WrappedMutex mutex_
Definition: bloaty/third_party/protobuf/src/google/protobuf/message.cc:569
testing::DoDefault
internal::DoDefaultAction DoDefault()
Definition: bloaty/third_party/googletest/googlemock/include/gmock/gmock-actions.h:1042
testing::internal::UniversalPrint
void UniversalPrint(const T &value, ::std::ostream *os)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest-printers.h:865
function
std::function< bool(GrpcTool *, int, const char **, const CliCredentials &, GrpcToolOutputCallback)> function
Definition: grpc_tool.cc:250
run_grpclb_interop_tests.l
dictionary l
Definition: run_grpclb_interop_tests.py:410
size
voidpf void uLong size
Definition: bloaty/third_party/zlib/contrib/minizip/ioapi.h:136
GTEST_DECLARE_STATIC_MUTEX_
#define GTEST_DECLARE_STATIC_MUTEX_(mutex)
Definition: bloaty/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:1860
absl::flags_internal::Retire
void Retire(const char *name, FlagFastTypeId type_id, char *buf)
Definition: abseil-cpp/absl/flags/reflection.cc:281
regress.m
m
Definition: regress/regress.py:25
testing::AtLeast
GTEST_API_ Cardinality AtLeast(int n)
Definition: bloaty/third_party/googletest/googlemock/src/gmock-cardinalities.cc:139
testing::internal::ReportUninterestingCall
void ReportUninterestingCall(CallReaction reaction, const std::string &msg)
Definition: bloaty/third_party/googletest/googlemock/src/gmock-spec-builders.cc:279
testing::internal::Expect
void Expect(bool condition, const char *file, int line, const std::string &msg)
Definition: bloaty/third_party/googletest/googlemock/include/gmock/internal/gmock-internal-utils.h:282
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
expectation
struct expectation expectation
Definition: cq_verifier_internal.h:24
testing::internal::g_gmock_implicit_sequence
GTEST_API_ ThreadLocal< Sequence * > g_gmock_implicit_sequence
Definition: bloaty/third_party/googletest/googlemock/src/gmock-spec-builders.cc:275


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:36