[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / utils / unittest / googlemock / include / gmock / gmock-actions.h
blob0a997a2984479f271bca0ae14aad3af827ce27c2
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.
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.
31 // Google Mock - a framework for writing C++ mock classes.
33 // This file implements some commonly used actions.
35 // GOOGLETEST_CM0002 DO NOT DELETE
37 // IWYU pragma: private, include "gmock/gmock.h"
39 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
40 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
42 #ifndef _WIN32_WCE
43 # include <errno.h>
44 #endif
46 #include <algorithm>
47 #include <functional>
48 #include <memory>
49 #include <string>
50 #include <type_traits>
51 #include <utility>
53 #include "gmock/internal/gmock-internal-utils.h"
54 #include "gmock/internal/gmock-port.h"
56 #ifdef _MSC_VER
57 # pragma warning(push)
58 # pragma warning(disable:4100)
59 #endif
61 #ifdef __clang__
62 #if __has_warning("-Wdeprecated-copy")
63 #pragma clang diagnostic push
64 #pragma clang diagnostic ignored "-Wdeprecated-copy"
65 #endif
66 #endif
68 namespace testing {
70 // To implement an action Foo, define:
71 // 1. a class FooAction that implements the ActionInterface interface, and
72 // 2. a factory function that creates an Action object from a
73 // const FooAction*.
75 // The two-level delegation design follows that of Matcher, providing
76 // consistency for extension developers. It also eases ownership
77 // management as Action objects can now be copied like plain values.
79 namespace internal {
81 // BuiltInDefaultValueGetter<T, true>::Get() returns a
82 // default-constructed T value. BuiltInDefaultValueGetter<T,
83 // false>::Get() crashes with an error.
85 // This primary template is used when kDefaultConstructible is true.
86 template <typename T, bool kDefaultConstructible>
87 struct BuiltInDefaultValueGetter {
88 static T Get() { return T(); }
90 template <typename T>
91 struct BuiltInDefaultValueGetter<T, false> {
92 static T Get() {
93 Assert(false, __FILE__, __LINE__,
94 "Default action undefined for the function return type.");
95 return internal::Invalid<T>();
96 // The above statement will never be reached, but is required in
97 // order for this function to compile.
101 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
102 // for type T, which is NULL when T is a raw pointer type, 0 when T is
103 // a numeric type, false when T is bool, or "" when T is string or
104 // std::string. In addition, in C++11 and above, it turns a
105 // default-constructed T value if T is default constructible. For any
106 // other type T, the built-in default T value is undefined, and the
107 // function will abort the process.
108 template <typename T>
109 class BuiltInDefaultValue {
110 public:
111 // This function returns true if and only if type T has a built-in default
112 // value.
113 static bool Exists() {
114 return ::std::is_default_constructible<T>::value;
117 static T Get() {
118 return BuiltInDefaultValueGetter<
119 T, ::std::is_default_constructible<T>::value>::Get();
123 // This partial specialization says that we use the same built-in
124 // default value for T and const T.
125 template <typename T>
126 class BuiltInDefaultValue<const T> {
127 public:
128 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
129 static T Get() { return BuiltInDefaultValue<T>::Get(); }
132 // This partial specialization defines the default values for pointer
133 // types.
134 template <typename T>
135 class BuiltInDefaultValue<T*> {
136 public:
137 static bool Exists() { return true; }
138 static T* Get() { return nullptr; }
141 // The following specializations define the default values for
142 // specific types we care about.
143 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
144 template <> \
145 class BuiltInDefaultValue<type> { \
146 public: \
147 static bool Exists() { return true; } \
148 static type Get() { return value; } \
151 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
152 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
153 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
154 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
155 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
156 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
158 // There's no need for a default action for signed wchar_t, as that
159 // type is the same as wchar_t for gcc, and invalid for MSVC.
161 // There's also no need for a default action for unsigned wchar_t, as
162 // that type is the same as unsigned int for gcc, and invalid for
163 // MSVC.
164 #if GMOCK_WCHAR_T_IS_NATIVE_
165 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
166 #endif
168 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
169 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
170 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
171 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
172 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
173 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
174 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
175 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
176 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
177 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
179 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
181 } // namespace internal
183 // When an unexpected function call is encountered, Google Mock will
184 // let it return a default value if the user has specified one for its
185 // return type, or if the return type has a built-in default value;
186 // otherwise Google Mock won't know what value to return and will have
187 // to abort the process.
189 // The DefaultValue<T> class allows a user to specify the
190 // default value for a type T that is both copyable and publicly
191 // destructible (i.e. anything that can be used as a function return
192 // type). The usage is:
194 // // Sets the default value for type T to be foo.
195 // DefaultValue<T>::Set(foo);
196 template <typename T>
197 class DefaultValue {
198 public:
199 // Sets the default value for type T; requires T to be
200 // copy-constructable and have a public destructor.
201 static void Set(T x) {
202 delete producer_;
203 producer_ = new FixedValueProducer(x);
206 // Provides a factory function to be called to generate the default value.
207 // This method can be used even if T is only move-constructible, but it is not
208 // limited to that case.
209 typedef T (*FactoryFunction)();
210 static void SetFactory(FactoryFunction factory) {
211 delete producer_;
212 producer_ = new FactoryValueProducer(factory);
215 // Unsets the default value for type T.
216 static void Clear() {
217 delete producer_;
218 producer_ = nullptr;
221 // Returns true if and only if the user has set the default value for type T.
222 static bool IsSet() { return producer_ != nullptr; }
224 // Returns true if T has a default return value set by the user or there
225 // exists a built-in default value.
226 static bool Exists() {
227 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
230 // Returns the default value for type T if the user has set one;
231 // otherwise returns the built-in default value. Requires that Exists()
232 // is true, which ensures that the return value is well-defined.
233 static T Get() {
234 return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
235 : producer_->Produce();
238 private:
239 class ValueProducer {
240 public:
241 virtual ~ValueProducer() {}
242 virtual T Produce() = 0;
245 class FixedValueProducer : public ValueProducer {
246 public:
247 explicit FixedValueProducer(T value) : value_(value) {}
248 T Produce() override { return value_; }
250 private:
251 const T value_;
252 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
255 class FactoryValueProducer : public ValueProducer {
256 public:
257 explicit FactoryValueProducer(FactoryFunction factory)
258 : factory_(factory) {}
259 T Produce() override { return factory_(); }
261 private:
262 const FactoryFunction factory_;
263 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
266 static ValueProducer* producer_;
269 // This partial specialization allows a user to set default values for
270 // reference types.
271 template <typename T>
272 class DefaultValue<T&> {
273 public:
274 // Sets the default value for type T&.
275 static void Set(T& x) { // NOLINT
276 address_ = &x;
279 // Unsets the default value for type T&.
280 static void Clear() { address_ = nullptr; }
282 // Returns true if and only if the user has set the default value for type T&.
283 static bool IsSet() { return address_ != nullptr; }
285 // Returns true if T has a default return value set by the user or there
286 // exists a built-in default value.
287 static bool Exists() {
288 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
291 // Returns the default value for type T& if the user has set one;
292 // otherwise returns the built-in default value if there is one;
293 // otherwise aborts the process.
294 static T& Get() {
295 return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
296 : *address_;
299 private:
300 static T* address_;
303 // This specialization allows DefaultValue<void>::Get() to
304 // compile.
305 template <>
306 class DefaultValue<void> {
307 public:
308 static bool Exists() { return true; }
309 static void Get() {}
312 // Points to the user-set default value for type T.
313 template <typename T>
314 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
316 // Points to the user-set default value for type T&.
317 template <typename T>
318 T* DefaultValue<T&>::address_ = nullptr;
320 // Implement this interface to define an action for function type F.
321 template <typename F>
322 class ActionInterface {
323 public:
324 typedef typename internal::Function<F>::Result Result;
325 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
327 ActionInterface() {}
328 virtual ~ActionInterface() {}
330 // Performs the action. This method is not const, as in general an
331 // action can have side effects and be stateful. For example, a
332 // get-the-next-element-from-the-collection action will need to
333 // remember the current element.
334 virtual Result Perform(const ArgumentTuple& args) = 0;
336 private:
337 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
340 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
341 // object that represents an action to be taken when a mock function
342 // of type F is called. The implementation of Action<T> is just a
343 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
344 // You can view an object implementing ActionInterface<F> as a
345 // concrete action (including its current state), and an Action<F>
346 // object as a handle to it.
347 template <typename F>
348 class Action {
349 // Adapter class to allow constructing Action from a legacy ActionInterface.
350 // New code should create Actions from functors instead.
351 struct ActionAdapter {
352 // Adapter must be copyable to satisfy std::function requirements.
353 ::std::shared_ptr<ActionInterface<F>> impl_;
355 template <typename... Args>
356 typename internal::Function<F>::Result operator()(Args&&... args) {
357 return impl_->Perform(
358 ::std::forward_as_tuple(::std::forward<Args>(args)...));
362 public:
363 typedef typename internal::Function<F>::Result Result;
364 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
366 // Constructs a null Action. Needed for storing Action objects in
367 // STL containers.
368 Action() {}
370 // Construct an Action from a specified callable.
371 // This cannot take std::function directly, because then Action would not be
372 // directly constructible from lambda (it would require two conversions).
373 template <typename G,
374 typename = typename ::std::enable_if<
375 ::std::is_constructible<::std::function<F>, G>::value>::type>
376 Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
378 // Constructs an Action from its implementation.
379 explicit Action(ActionInterface<F>* impl)
380 : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
382 // This constructor allows us to turn an Action<Func> object into an
383 // Action<F>, as long as F's arguments can be implicitly converted
384 // to Func's and Func's return type can be implicitly converted to F's.
385 template <typename Func>
386 explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
388 // Returns true if and only if this is the DoDefault() action.
389 bool IsDoDefault() const { return fun_ == nullptr; }
391 // Performs the action. Note that this method is const even though
392 // the corresponding method in ActionInterface is not. The reason
393 // is that a const Action<F> means that it cannot be re-bound to
394 // another concrete action, not that the concrete action it binds to
395 // cannot change state. (Think of the difference between a const
396 // pointer and a pointer to const.)
397 Result Perform(ArgumentTuple args) const {
398 if (IsDoDefault()) {
399 internal::IllegalDoDefault(__FILE__, __LINE__);
401 return internal::Apply(fun_, ::std::move(args));
404 private:
405 template <typename G>
406 friend class Action;
408 // fun_ is an empty function if and only if this is the DoDefault() action.
409 ::std::function<F> fun_;
412 // The PolymorphicAction class template makes it easy to implement a
413 // polymorphic action (i.e. an action that can be used in mock
414 // functions of than one type, e.g. Return()).
416 // To define a polymorphic action, a user first provides a COPYABLE
417 // implementation class that has a Perform() method template:
419 // class FooAction {
420 // public:
421 // template <typename Result, typename ArgumentTuple>
422 // Result Perform(const ArgumentTuple& args) const {
423 // // Processes the arguments and returns a result, using
424 // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
425 // }
426 // ...
427 // };
429 // Then the user creates the polymorphic action using
430 // MakePolymorphicAction(object) where object has type FooAction. See
431 // the definition of Return(void) and SetArgumentPointee<N>(value) for
432 // complete examples.
433 template <typename Impl>
434 class PolymorphicAction {
435 public:
436 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
438 template <typename F>
439 operator Action<F>() const {
440 return Action<F>(new MonomorphicImpl<F>(impl_));
443 private:
444 template <typename F>
445 class MonomorphicImpl : public ActionInterface<F> {
446 public:
447 typedef typename internal::Function<F>::Result Result;
448 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
450 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
452 Result Perform(const ArgumentTuple& args) override {
453 return impl_.template Perform<Result>(args);
456 private:
457 Impl impl_;
459 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
462 Impl impl_;
464 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
467 // Creates an Action from its implementation and returns it. The
468 // created Action object owns the implementation.
469 template <typename F>
470 Action<F> MakeAction(ActionInterface<F>* impl) {
471 return Action<F>(impl);
474 // Creates a polymorphic action from its implementation. This is
475 // easier to use than the PolymorphicAction<Impl> constructor as it
476 // doesn't require you to explicitly write the template argument, e.g.
478 // MakePolymorphicAction(foo);
479 // vs
480 // PolymorphicAction<TypeOfFoo>(foo);
481 template <typename Impl>
482 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
483 return PolymorphicAction<Impl>(impl);
486 namespace internal {
488 // Helper struct to specialize ReturnAction to execute a move instead of a copy
489 // on return. Useful for move-only types, but could be used on any type.
490 template <typename T>
491 struct ByMoveWrapper {
492 explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
493 T payload;
496 // Implements the polymorphic Return(x) action, which can be used in
497 // any function that returns the type of x, regardless of the argument
498 // types.
500 // Note: The value passed into Return must be converted into
501 // Function<F>::Result when this action is cast to Action<F> rather than
502 // when that action is performed. This is important in scenarios like
504 // MOCK_METHOD1(Method, T(U));
505 // ...
506 // {
507 // Foo foo;
508 // X x(&foo);
509 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
510 // }
512 // In the example above the variable x holds reference to foo which leaves
513 // scope and gets destroyed. If copying X just copies a reference to foo,
514 // that copy will be left with a hanging reference. If conversion to T
515 // makes a copy of foo, the above code is safe. To support that scenario, we
516 // need to make sure that the type conversion happens inside the EXPECT_CALL
517 // statement, and conversion of the result of Return to Action<T(U)> is a
518 // good place for that.
520 // The real life example of the above scenario happens when an invocation
521 // of gtl::Container() is passed into Return.
523 template <typename R>
524 class ReturnAction {
525 public:
526 // Constructs a ReturnAction object from the value to be returned.
527 // 'value' is passed by value instead of by const reference in order
528 // to allow Return("string literal") to compile.
529 explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
531 // This template type conversion operator allows Return(x) to be
532 // used in ANY function that returns x's type.
533 template <typename F>
534 operator Action<F>() const { // NOLINT
535 // Assert statement belongs here because this is the best place to verify
536 // conditions on F. It produces the clearest error messages
537 // in most compilers.
538 // Impl really belongs in this scope as a local class but can't
539 // because MSVC produces duplicate symbols in different translation units
540 // in this case. Until MS fixes that bug we put Impl into the class scope
541 // and put the typedef both here (for use in assert statement) and
542 // in the Impl class. But both definitions must be the same.
543 typedef typename Function<F>::Result Result;
544 GTEST_COMPILE_ASSERT_(
545 !std::is_reference<Result>::value,
546 use_ReturnRef_instead_of_Return_to_return_a_reference);
547 static_assert(!std::is_void<Result>::value,
548 "Can't use Return() on an action expected to return `void`.");
549 return Action<F>(new Impl<R, F>(value_));
552 private:
553 // Implements the Return(x) action for a particular function type F.
554 template <typename R_, typename F>
555 class Impl : public ActionInterface<F> {
556 public:
557 typedef typename Function<F>::Result Result;
558 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
560 // The implicit cast is necessary when Result has more than one
561 // single-argument constructor (e.g. Result is std::vector<int>) and R
562 // has a type conversion operator template. In that case, value_(value)
563 // won't compile as the compiler doesn't known which constructor of
564 // Result to call. ImplicitCast_ forces the compiler to convert R to
565 // Result without considering explicit constructors, thus resolving the
566 // ambiguity. value_ is then initialized using its copy constructor.
567 explicit Impl(const std::shared_ptr<R>& value)
568 : value_before_cast_(*value),
569 value_(ImplicitCast_<Result>(value_before_cast_)) {}
571 Result Perform(const ArgumentTuple&) override { return value_; }
573 private:
574 GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
575 Result_cannot_be_a_reference_type);
576 // We save the value before casting just in case it is being cast to a
577 // wrapper type.
578 R value_before_cast_;
579 Result value_;
581 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
584 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
585 // move its contents instead.
586 template <typename R_, typename F>
587 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
588 public:
589 typedef typename Function<F>::Result Result;
590 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
592 explicit Impl(const std::shared_ptr<R>& wrapper)
593 : performed_(false), wrapper_(wrapper) {}
595 Result Perform(const ArgumentTuple&) override {
596 GTEST_CHECK_(!performed_)
597 << "A ByMove() action should only be performed once.";
598 performed_ = true;
599 return std::move(wrapper_->payload);
602 private:
603 bool performed_;
604 const std::shared_ptr<R> wrapper_;
606 GTEST_DISALLOW_ASSIGN_(Impl);
609 const std::shared_ptr<R> value_;
611 GTEST_DISALLOW_ASSIGN_(ReturnAction);
614 // Implements the ReturnNull() action.
615 class ReturnNullAction {
616 public:
617 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
618 // this is enforced by returning nullptr, and in non-C++11 by asserting a
619 // pointer type on compile time.
620 template <typename Result, typename ArgumentTuple>
621 static Result Perform(const ArgumentTuple&) {
622 return nullptr;
626 // Implements the Return() action.
627 class ReturnVoidAction {
628 public:
629 // Allows Return() to be used in any void-returning function.
630 template <typename Result, typename ArgumentTuple>
631 static void Perform(const ArgumentTuple&) {
632 static_assert(std::is_void<Result>::value, "Result should be void.");
636 // Implements the polymorphic ReturnRef(x) action, which can be used
637 // in any function that returns a reference to the type of x,
638 // regardless of the argument types.
639 template <typename T>
640 class ReturnRefAction {
641 public:
642 // Constructs a ReturnRefAction object from the reference to be returned.
643 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
645 // This template type conversion operator allows ReturnRef(x) to be
646 // used in ANY function that returns a reference to x's type.
647 template <typename F>
648 operator Action<F>() const {
649 typedef typename Function<F>::Result Result;
650 // Asserts that the function return type is a reference. This
651 // catches the user error of using ReturnRef(x) when Return(x)
652 // should be used, and generates some helpful error message.
653 GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
654 use_Return_instead_of_ReturnRef_to_return_a_value);
655 return Action<F>(new Impl<F>(ref_));
658 private:
659 // Implements the ReturnRef(x) action for a particular function type F.
660 template <typename F>
661 class Impl : public ActionInterface<F> {
662 public:
663 typedef typename Function<F>::Result Result;
664 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
666 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
668 Result Perform(const ArgumentTuple&) override { return ref_; }
670 private:
671 T& ref_;
673 GTEST_DISALLOW_ASSIGN_(Impl);
676 T& ref_;
678 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
681 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
682 // used in any function that returns a reference to the type of x,
683 // regardless of the argument types.
684 template <typename T>
685 class ReturnRefOfCopyAction {
686 public:
687 // Constructs a ReturnRefOfCopyAction object from the reference to
688 // be returned.
689 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
691 // This template type conversion operator allows ReturnRefOfCopy(x) to be
692 // used in ANY function that returns a reference to x's type.
693 template <typename F>
694 operator Action<F>() const {
695 typedef typename Function<F>::Result Result;
696 // Asserts that the function return type is a reference. This
697 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
698 // should be used, and generates some helpful error message.
699 GTEST_COMPILE_ASSERT_(
700 std::is_reference<Result>::value,
701 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
702 return Action<F>(new Impl<F>(value_));
705 private:
706 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
707 template <typename F>
708 class Impl : public ActionInterface<F> {
709 public:
710 typedef typename Function<F>::Result Result;
711 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
713 explicit Impl(const T& value) : value_(value) {} // NOLINT
715 Result Perform(const ArgumentTuple&) override { return value_; }
717 private:
718 T value_;
720 GTEST_DISALLOW_ASSIGN_(Impl);
723 const T value_;
725 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
728 // Implements the polymorphic DoDefault() action.
729 class DoDefaultAction {
730 public:
731 // This template type conversion operator allows DoDefault() to be
732 // used in any function.
733 template <typename F>
734 operator Action<F>() const { return Action<F>(); } // NOLINT
737 // Implements the Assign action to set a given pointer referent to a
738 // particular value.
739 template <typename T1, typename T2>
740 class AssignAction {
741 public:
742 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
744 template <typename Result, typename ArgumentTuple>
745 void Perform(const ArgumentTuple& /* args */) const {
746 *ptr_ = value_;
749 private:
750 T1* const ptr_;
751 const T2 value_;
753 GTEST_DISALLOW_ASSIGN_(AssignAction);
756 #if !GTEST_OS_WINDOWS_MOBILE
758 // Implements the SetErrnoAndReturn action to simulate return from
759 // various system calls and libc functions.
760 template <typename T>
761 class SetErrnoAndReturnAction {
762 public:
763 SetErrnoAndReturnAction(int errno_value, T result)
764 : errno_(errno_value),
765 result_(result) {}
766 template <typename Result, typename ArgumentTuple>
767 Result Perform(const ArgumentTuple& /* args */) const {
768 errno = errno_;
769 return result_;
772 private:
773 const int errno_;
774 const T result_;
776 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
779 #endif // !GTEST_OS_WINDOWS_MOBILE
781 // Implements the SetArgumentPointee<N>(x) action for any function
782 // whose N-th argument (0-based) is a pointer to x's type.
783 template <size_t N, typename A, typename = void>
784 struct SetArgumentPointeeAction {
785 A value;
787 template <typename... Args>
788 void operator()(const Args&... args) const {
789 *::std::get<N>(std::tie(args...)) = value;
793 // Implements the Invoke(object_ptr, &Class::Method) action.
794 template <class Class, typename MethodPtr>
795 struct InvokeMethodAction {
796 Class* const obj_ptr;
797 const MethodPtr method_ptr;
799 template <typename... Args>
800 auto operator()(Args&&... args) const
801 -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
802 return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
806 // Implements the InvokeWithoutArgs(f) action. The template argument
807 // FunctionImpl is the implementation type of f, which can be either a
808 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
809 // Action<F> as long as f's type is compatible with F.
810 template <typename FunctionImpl>
811 struct InvokeWithoutArgsAction {
812 FunctionImpl function_impl;
814 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
815 // compatible with f.
816 template <typename... Args>
817 auto operator()(const Args&...) -> decltype(function_impl()) {
818 return function_impl();
822 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
823 template <class Class, typename MethodPtr>
824 struct InvokeMethodWithoutArgsAction {
825 Class* const obj_ptr;
826 const MethodPtr method_ptr;
828 using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
830 template <typename... Args>
831 ReturnType operator()(const Args&...) const {
832 return (obj_ptr->*method_ptr)();
836 // Implements the IgnoreResult(action) action.
837 template <typename A>
838 class IgnoreResultAction {
839 public:
840 explicit IgnoreResultAction(const A& action) : action_(action) {}
842 template <typename F>
843 operator Action<F>() const {
844 // Assert statement belongs here because this is the best place to verify
845 // conditions on F. It produces the clearest error messages
846 // in most compilers.
847 // Impl really belongs in this scope as a local class but can't
848 // because MSVC produces duplicate symbols in different translation units
849 // in this case. Until MS fixes that bug we put Impl into the class scope
850 // and put the typedef both here (for use in assert statement) and
851 // in the Impl class. But both definitions must be the same.
852 typedef typename internal::Function<F>::Result Result;
854 // Asserts at compile time that F returns void.
855 static_assert(std::is_void<Result>::value, "Result type should be void.");
857 return Action<F>(new Impl<F>(action_));
860 private:
861 template <typename F>
862 class Impl : public ActionInterface<F> {
863 public:
864 typedef typename internal::Function<F>::Result Result;
865 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
867 explicit Impl(const A& action) : action_(action) {}
869 void Perform(const ArgumentTuple& args) override {
870 // Performs the action and ignores its result.
871 action_.Perform(args);
874 private:
875 // Type OriginalFunction is the same as F except that its return
876 // type is IgnoredValue.
877 typedef typename internal::Function<F>::MakeResultIgnoredValue
878 OriginalFunction;
880 const Action<OriginalFunction> action_;
882 GTEST_DISALLOW_ASSIGN_(Impl);
885 const A action_;
887 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
890 template <typename InnerAction, size_t... I>
891 struct WithArgsAction {
892 InnerAction action;
894 // The inner action could be anything convertible to Action<X>.
895 // We use the conversion operator to detect the signature of the inner Action.
896 template <typename R, typename... Args>
897 operator Action<R(Args...)>() const { // NOLINT
898 Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)>
899 converted(action);
901 return [converted](Args... args) -> R {
902 return converted.Perform(std::forward_as_tuple(
903 std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
908 template <typename... Actions>
909 struct DoAllAction {
910 private:
911 template <typename... Args, size_t... I>
912 std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
913 return {std::get<I>(actions)...};
916 public:
917 std::tuple<Actions...> actions;
919 template <typename R, typename... Args>
920 operator Action<R(Args...)>() const { // NOLINT
921 struct Op {
922 std::vector<Action<void(Args...)>> converted;
923 Action<R(Args...)> last;
924 R operator()(Args... args) const {
925 auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
926 for (auto& a : converted) {
927 a.Perform(tuple_args);
929 return last.Perform(tuple_args);
932 return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
933 std::get<sizeof...(Actions) - 1>(actions)};
937 } // namespace internal
939 // An Unused object can be implicitly constructed from ANY value.
940 // This is handy when defining actions that ignore some or all of the
941 // mock function arguments. For example, given
943 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
944 // MOCK_METHOD3(Bar, double(int index, double x, double y));
946 // instead of
948 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
949 // return sqrt(x*x + y*y);
950 // }
951 // double DistanceToOriginWithIndex(int index, double x, double y) {
952 // return sqrt(x*x + y*y);
953 // }
954 // ...
955 // EXPECT_CALL(mock, Foo("abc", _, _))
956 // .WillOnce(Invoke(DistanceToOriginWithLabel));
957 // EXPECT_CALL(mock, Bar(5, _, _))
958 // .WillOnce(Invoke(DistanceToOriginWithIndex));
960 // you could write
962 // // We can declare any uninteresting argument as Unused.
963 // double DistanceToOrigin(Unused, double x, double y) {
964 // return sqrt(x*x + y*y);
965 // }
966 // ...
967 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
968 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
969 typedef internal::IgnoredValue Unused;
971 // Creates an action that does actions a1, a2, ..., sequentially in
972 // each invocation.
973 template <typename... Action>
974 internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
975 Action&&... action) {
976 return {std::forward_as_tuple(std::forward<Action>(action)...)};
979 // WithArg<k>(an_action) creates an action that passes the k-th
980 // (0-based) argument of the mock function to an_action and performs
981 // it. It adapts an action accepting one argument to one that accepts
982 // multiple arguments. For convenience, we also provide
983 // WithArgs<k>(an_action) (defined below) as a synonym.
984 template <size_t k, typename InnerAction>
985 internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
986 WithArg(InnerAction&& action) {
987 return {std::forward<InnerAction>(action)};
990 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
991 // the selected arguments of the mock function to an_action and
992 // performs it. It serves as an adaptor between actions with
993 // different argument lists.
994 template <size_t k, size_t... ks, typename InnerAction>
995 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
996 WithArgs(InnerAction&& action) {
997 return {std::forward<InnerAction>(action)};
1000 // WithoutArgs(inner_action) can be used in a mock function with a
1001 // non-empty argument list to perform inner_action, which takes no
1002 // argument. In other words, it adapts an action accepting no
1003 // argument to one that accepts (and ignores) arguments.
1004 template <typename InnerAction>
1005 internal::WithArgsAction<typename std::decay<InnerAction>::type>
1006 WithoutArgs(InnerAction&& action) {
1007 return {std::forward<InnerAction>(action)};
1010 // Creates an action that returns 'value'. 'value' is passed by value
1011 // instead of const reference - otherwise Return("string literal")
1012 // will trigger a compiler error about using array as initializer.
1013 template <typename R>
1014 internal::ReturnAction<R> Return(R value) {
1015 return internal::ReturnAction<R>(std::move(value));
1018 // Creates an action that returns NULL.
1019 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1020 return MakePolymorphicAction(internal::ReturnNullAction());
1023 // Creates an action that returns from a void function.
1024 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1025 return MakePolymorphicAction(internal::ReturnVoidAction());
1028 // Creates an action that returns the reference to a variable.
1029 template <typename R>
1030 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1031 return internal::ReturnRefAction<R>(x);
1034 // Creates an action that returns the reference to a copy of the
1035 // argument. The copy is created when the action is constructed and
1036 // lives as long as the action.
1037 template <typename R>
1038 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1039 return internal::ReturnRefOfCopyAction<R>(x);
1042 // Modifies the parent action (a Return() action) to perform a move of the
1043 // argument instead of a copy.
1044 // Return(ByMove()) actions can only be executed once and will assert this
1045 // invariant.
1046 template <typename R>
1047 internal::ByMoveWrapper<R> ByMove(R x) {
1048 return internal::ByMoveWrapper<R>(std::move(x));
1051 // Creates an action that does the default action for the give mock function.
1052 inline internal::DoDefaultAction DoDefault() {
1053 return internal::DoDefaultAction();
1056 // Creates an action that sets the variable pointed by the N-th
1057 // (0-based) function argument to 'value'.
1058 template <size_t N, typename T>
1059 internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) {
1060 return {std::move(x)};
1063 // The following version is DEPRECATED.
1064 template <size_t N, typename T>
1065 internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) {
1066 return {std::move(x)};
1069 // Creates an action that sets a pointer referent to a given value.
1070 template <typename T1, typename T2>
1071 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1072 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1075 #if !GTEST_OS_WINDOWS_MOBILE
1077 // Creates an action that sets errno and returns the appropriate error.
1078 template <typename T>
1079 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1080 SetErrnoAndReturn(int errval, T result) {
1081 return MakePolymorphicAction(
1082 internal::SetErrnoAndReturnAction<T>(errval, result));
1085 #endif // !GTEST_OS_WINDOWS_MOBILE
1087 // Various overloads for Invoke().
1089 // Legacy function.
1090 // Actions can now be implicitly constructed from callables. No need to create
1091 // wrapper objects.
1092 // This function exists for backwards compatibility.
1093 template <typename FunctionImpl>
1094 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
1095 return std::forward<FunctionImpl>(function_impl);
1098 // Creates an action that invokes the given method on the given object
1099 // with the mock function's arguments.
1100 template <class Class, typename MethodPtr>
1101 internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
1102 MethodPtr method_ptr) {
1103 return {obj_ptr, method_ptr};
1106 // Creates an action that invokes 'function_impl' with no argument.
1107 template <typename FunctionImpl>
1108 internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
1109 InvokeWithoutArgs(FunctionImpl function_impl) {
1110 return {std::move(function_impl)};
1113 // Creates an action that invokes the given method on the given object
1114 // with no argument.
1115 template <class Class, typename MethodPtr>
1116 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
1117 Class* obj_ptr, MethodPtr method_ptr) {
1118 return {obj_ptr, method_ptr};
1121 // Creates an action that performs an_action and throws away its
1122 // result. In other words, it changes the return type of an_action to
1123 // void. an_action MUST NOT return void, or the code won't compile.
1124 template <typename A>
1125 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1126 return internal::IgnoreResultAction<A>(an_action);
1129 // Creates a reference wrapper for the given L-value. If necessary,
1130 // you can explicitly specify the type of the reference. For example,
1131 // suppose 'derived' is an object of type Derived, ByRef(derived)
1132 // would wrap a Derived&. If you want to wrap a const Base& instead,
1133 // where Base is a base class of Derived, just write:
1135 // ByRef<const Base>(derived)
1137 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
1138 // However, it may still be used for consistency with ByMove().
1139 template <typename T>
1140 inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
1141 return ::std::reference_wrapper<T>(l_value);
1144 } // namespace testing
1146 #ifdef __clang__
1147 #if __has_warning("-Wdeprecated-copy")
1148 #pragma clang diagnostic pop
1149 #endif
1150 #endif
1152 #ifdef _MSC_VER
1153 # pragma warning(pop)
1154 #endif
1157 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_