You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1142 lines
39 KiB

  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. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file implements some commonly used actions.
  32. // GOOGLETEST_CM0002 DO NOT DELETE
  33. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  34. #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  35. #ifndef _WIN32_WCE
  36. # include <errno.h>
  37. #endif
  38. #include <algorithm>
  39. #include <functional>
  40. #include <memory>
  41. #include <string>
  42. #include <type_traits>
  43. #include <utility>
  44. #include "gmock/internal/gmock-internal-utils.h"
  45. #include "gmock/internal/gmock-port.h"
  46. #ifdef _MSC_VER
  47. # pragma warning(push)
  48. # pragma warning(disable:4100)
  49. #endif
  50. namespace testing {
  51. // To implement an action Foo, define:
  52. // 1. a class FooAction that implements the ActionInterface interface, and
  53. // 2. a factory function that creates an Action object from a
  54. // const FooAction*.
  55. //
  56. // The two-level delegation design follows that of Matcher, providing
  57. // consistency for extension developers. It also eases ownership
  58. // management as Action objects can now be copied like plain values.
  59. namespace internal {
  60. // BuiltInDefaultValueGetter<T, true>::Get() returns a
  61. // default-constructed T value. BuiltInDefaultValueGetter<T,
  62. // false>::Get() crashes with an error.
  63. //
  64. // This primary template is used when kDefaultConstructible is true.
  65. template <typename T, bool kDefaultConstructible>
  66. struct BuiltInDefaultValueGetter {
  67. static T Get() { return T(); }
  68. };
  69. template <typename T>
  70. struct BuiltInDefaultValueGetter<T, false> {
  71. static T Get() {
  72. Assert(false, __FILE__, __LINE__,
  73. "Default action undefined for the function return type.");
  74. return internal::Invalid<T>();
  75. // The above statement will never be reached, but is required in
  76. // order for this function to compile.
  77. }
  78. };
  79. // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
  80. // for type T, which is NULL when T is a raw pointer type, 0 when T is
  81. // a numeric type, false when T is bool, or "" when T is string or
  82. // std::string. In addition, in C++11 and above, it turns a
  83. // default-constructed T value if T is default constructible. For any
  84. // other type T, the built-in default T value is undefined, and the
  85. // function will abort the process.
  86. template <typename T>
  87. class BuiltInDefaultValue {
  88. public:
  89. // This function returns true if and only if type T has a built-in default
  90. // value.
  91. static bool Exists() {
  92. return ::std::is_default_constructible<T>::value;
  93. }
  94. static T Get() {
  95. return BuiltInDefaultValueGetter<
  96. T, ::std::is_default_constructible<T>::value>::Get();
  97. }
  98. };
  99. // This partial specialization says that we use the same built-in
  100. // default value for T and const T.
  101. template <typename T>
  102. class BuiltInDefaultValue<const T> {
  103. public:
  104. static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
  105. static T Get() { return BuiltInDefaultValue<T>::Get(); }
  106. };
  107. // This partial specialization defines the default values for pointer
  108. // types.
  109. template <typename T>
  110. class BuiltInDefaultValue<T*> {
  111. public:
  112. static bool Exists() { return true; }
  113. static T* Get() { return nullptr; }
  114. };
  115. // The following specializations define the default values for
  116. // specific types we care about.
  117. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
  118. template <> \
  119. class BuiltInDefaultValue<type> { \
  120. public: \
  121. static bool Exists() { return true; } \
  122. static type Get() { return value; } \
  123. }
  124. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
  125. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
  126. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
  127. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
  128. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
  129. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
  130. // There's no need for a default action for signed wchar_t, as that
  131. // type is the same as wchar_t for gcc, and invalid for MSVC.
  132. //
  133. // There's also no need for a default action for unsigned wchar_t, as
  134. // that type is the same as unsigned int for gcc, and invalid for
  135. // MSVC.
  136. #if GMOCK_WCHAR_T_IS_NATIVE_
  137. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
  138. #endif
  139. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
  140. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
  141. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
  142. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
  143. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
  144. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
  145. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
  146. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
  147. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
  148. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
  149. #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
  150. } // namespace internal
  151. // When an unexpected function call is encountered, Google Mock will
  152. // let it return a default value if the user has specified one for its
  153. // return type, or if the return type has a built-in default value;
  154. // otherwise Google Mock won't know what value to return and will have
  155. // to abort the process.
  156. //
  157. // The DefaultValue<T> class allows a user to specify the
  158. // default value for a type T that is both copyable and publicly
  159. // destructible (i.e. anything that can be used as a function return
  160. // type). The usage is:
  161. //
  162. // // Sets the default value for type T to be foo.
  163. // DefaultValue<T>::Set(foo);
  164. template <typename T>
  165. class DefaultValue {
  166. public:
  167. // Sets the default value for type T; requires T to be
  168. // copy-constructable and have a public destructor.
  169. static void Set(T x) {
  170. delete producer_;
  171. producer_ = new FixedValueProducer(x);
  172. }
  173. // Provides a factory function to be called to generate the default value.
  174. // This method can be used even if T is only move-constructible, but it is not
  175. // limited to that case.
  176. typedef T (*FactoryFunction)();
  177. static void SetFactory(FactoryFunction factory) {
  178. delete producer_;
  179. producer_ = new FactoryValueProducer(factory);
  180. }
  181. // Unsets the default value for type T.
  182. static void Clear() {
  183. delete producer_;
  184. producer_ = nullptr;
  185. }
  186. // Returns true if and only if the user has set the default value for type T.
  187. static bool IsSet() { return producer_ != nullptr; }
  188. // Returns true if T has a default return value set by the user or there
  189. // exists a built-in default value.
  190. static bool Exists() {
  191. return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
  192. }
  193. // Returns the default value for type T if the user has set one;
  194. // otherwise returns the built-in default value. Requires that Exists()
  195. // is true, which ensures that the return value is well-defined.
  196. static T Get() {
  197. return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
  198. : producer_->Produce();
  199. }
  200. private:
  201. class ValueProducer {
  202. public:
  203. virtual ~ValueProducer() {}
  204. virtual T Produce() = 0;
  205. };
  206. class FixedValueProducer : public ValueProducer {
  207. public:
  208. explicit FixedValueProducer(T value) : value_(value) {}
  209. T Produce() override { return value_; }
  210. private:
  211. const T value_;
  212. GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
  213. };
  214. class FactoryValueProducer : public ValueProducer {
  215. public:
  216. explicit FactoryValueProducer(FactoryFunction factory)
  217. : factory_(factory) {}
  218. T Produce() override { return factory_(); }
  219. private:
  220. const FactoryFunction factory_;
  221. GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
  222. };
  223. static ValueProducer* producer_;
  224. };
  225. // This partial specialization allows a user to set default values for
  226. // reference types.
  227. template <typename T>
  228. class DefaultValue<T&> {
  229. public:
  230. // Sets the default value for type T&.
  231. static void Set(T& x) { // NOLINT
  232. address_ = &x;
  233. }
  234. // Unsets the default value for type T&.
  235. static void Clear() { address_ = nullptr; }
  236. // Returns true if and only if the user has set the default value for type T&.
  237. static bool IsSet() { return address_ != nullptr; }
  238. // Returns true if T has a default return value set by the user or there
  239. // exists a built-in default value.
  240. static bool Exists() {
  241. return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
  242. }
  243. // Returns the default value for type T& if the user has set one;
  244. // otherwise returns the built-in default value if there is one;
  245. // otherwise aborts the process.
  246. static T& Get() {
  247. return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
  248. : *address_;
  249. }
  250. private:
  251. static T* address_;
  252. };
  253. // This specialization allows DefaultValue<void>::Get() to
  254. // compile.
  255. template <>
  256. class DefaultValue<void> {
  257. public:
  258. static bool Exists() { return true; }
  259. static void Get() {}
  260. };
  261. // Points to the user-set default value for type T.
  262. template <typename T>
  263. typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
  264. // Points to the user-set default value for type T&.
  265. template <typename T>
  266. T* DefaultValue<T&>::address_ = nullptr;
  267. // Implement this interface to define an action for function type F.
  268. template <typename F>
  269. class ActionInterface {
  270. public:
  271. typedef typename internal::Function<F>::Result Result;
  272. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  273. ActionInterface() {}
  274. virtual ~ActionInterface() {}
  275. // Performs the action. This method is not const, as in general an
  276. // action can have side effects and be stateful. For example, a
  277. // get-the-next-element-from-the-collection action will need to
  278. // remember the current element.
  279. virtual Result Perform(const ArgumentTuple& args) = 0;
  280. private:
  281. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
  282. };
  283. // An Action<F> is a copyable and IMMUTABLE (except by assignment)
  284. // object that represents an action to be taken when a mock function
  285. // of type F is called. The implementation of Action<T> is just a
  286. // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
  287. // You can view an object implementing ActionInterface<F> as a
  288. // concrete action (including its current state), and an Action<F>
  289. // object as a handle to it.
  290. template <typename F>
  291. class Action {
  292. // Adapter class to allow constructing Action from a legacy ActionInterface.
  293. // New code should create Actions from functors instead.
  294. struct ActionAdapter {
  295. // Adapter must be copyable to satisfy std::function requirements.
  296. ::std::shared_ptr<ActionInterface<F>> impl_;
  297. template <typename... Args>
  298. typename internal::Function<F>::Result operator()(Args&&... args) {
  299. return impl_->Perform(
  300. ::std::forward_as_tuple(::std::forward<Args>(args)...));
  301. }
  302. };
  303. public:
  304. typedef typename internal::Function<F>::Result Result;
  305. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  306. // Constructs a null Action. Needed for storing Action objects in
  307. // STL containers.
  308. Action() {}
  309. // Construct an Action from a specified callable.
  310. // This cannot take std::function directly, because then Action would not be
  311. // directly constructible from lambda (it would require two conversions).
  312. template <typename G,
  313. typename = typename ::std::enable_if<
  314. ::std::is_constructible<::std::function<F>, G>::value>::type>
  315. Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
  316. // Constructs an Action from its implementation.
  317. explicit Action(ActionInterface<F>* impl)
  318. : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
  319. // This constructor allows us to turn an Action<Func> object into an
  320. // Action<F>, as long as F's arguments can be implicitly converted
  321. // to Func's and Func's return type can be implicitly converted to F's.
  322. template <typename Func>
  323. explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
  324. // Returns true if and only if this is the DoDefault() action.
  325. bool IsDoDefault() const { return fun_ == nullptr; }
  326. // Performs the action. Note that this method is const even though
  327. // the corresponding method in ActionInterface is not. The reason
  328. // is that a const Action<F> means that it cannot be re-bound to
  329. // another concrete action, not that the concrete action it binds to
  330. // cannot change state. (Think of the difference between a const
  331. // pointer and a pointer to const.)
  332. Result Perform(ArgumentTuple args) const {
  333. if (IsDoDefault()) {
  334. internal::IllegalDoDefault(__FILE__, __LINE__);
  335. }
  336. return internal::Apply(fun_, ::std::move(args));
  337. }
  338. private:
  339. template <typename G>
  340. friend class Action;
  341. // fun_ is an empty function if and only if this is the DoDefault() action.
  342. ::std::function<F> fun_;
  343. };
  344. // The PolymorphicAction class template makes it easy to implement a
  345. // polymorphic action (i.e. an action that can be used in mock
  346. // functions of than one type, e.g. Return()).
  347. //
  348. // To define a polymorphic action, a user first provides a COPYABLE
  349. // implementation class that has a Perform() method template:
  350. //
  351. // class FooAction {
  352. // public:
  353. // template <typename Result, typename ArgumentTuple>
  354. // Result Perform(const ArgumentTuple& args) const {
  355. // // Processes the arguments and returns a result, using
  356. // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
  357. // }
  358. // ...
  359. // };
  360. //
  361. // Then the user creates the polymorphic action using
  362. // MakePolymorphicAction(object) where object has type FooAction. See
  363. // the definition of Return(void) and SetArgumentPointee<N>(value) for
  364. // complete examples.
  365. template <typename Impl>
  366. class PolymorphicAction {
  367. public:
  368. explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
  369. template <typename F>
  370. operator Action<F>() const {
  371. return Action<F>(new MonomorphicImpl<F>(impl_));
  372. }
  373. private:
  374. template <typename F>
  375. class MonomorphicImpl : public ActionInterface<F> {
  376. public:
  377. typedef typename internal::Function<F>::Result Result;
  378. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  379. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  380. Result Perform(const ArgumentTuple& args) override {
  381. return impl_.template Perform<Result>(args);
  382. }
  383. private:
  384. Impl impl_;
  385. GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
  386. };
  387. Impl impl_;
  388. GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
  389. };
  390. // Creates an Action from its implementation and returns it. The
  391. // created Action object owns the implementation.
  392. template <typename F>
  393. Action<F> MakeAction(ActionInterface<F>* impl) {
  394. return Action<F>(impl);
  395. }
  396. // Creates a polymorphic action from its implementation. This is
  397. // easier to use than the PolymorphicAction<Impl> constructor as it
  398. // doesn't require you to explicitly write the template argument, e.g.
  399. //
  400. // MakePolymorphicAction(foo);
  401. // vs
  402. // PolymorphicAction<TypeOfFoo>(foo);
  403. template <typename Impl>
  404. inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
  405. return PolymorphicAction<Impl>(impl);
  406. }
  407. namespace internal {
  408. // Helper struct to specialize ReturnAction to execute a move instead of a copy
  409. // on return. Useful for move-only types, but could be used on any type.
  410. template <typename T>
  411. struct ByMoveWrapper {
  412. explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
  413. T payload;
  414. };
  415. // Implements the polymorphic Return(x) action, which can be used in
  416. // any function that returns the type of x, regardless of the argument
  417. // types.
  418. //
  419. // Note: The value passed into Return must be converted into
  420. // Function<F>::Result when this action is cast to Action<F> rather than
  421. // when that action is performed. This is important in scenarios like
  422. //
  423. // MOCK_METHOD1(Method, T(U));
  424. // ...
  425. // {
  426. // Foo foo;
  427. // X x(&foo);
  428. // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
  429. // }
  430. //
  431. // In the example above the variable x holds reference to foo which leaves
  432. // scope and gets destroyed. If copying X just copies a reference to foo,
  433. // that copy will be left with a hanging reference. If conversion to T
  434. // makes a copy of foo, the above code is safe. To support that scenario, we
  435. // need to make sure that the type conversion happens inside the EXPECT_CALL
  436. // statement, and conversion of the result of Return to Action<T(U)> is a
  437. // good place for that.
  438. //
  439. // The real life example of the above scenario happens when an invocation
  440. // of gtl::Container() is passed into Return.
  441. //
  442. template <typename R>
  443. class ReturnAction {
  444. public:
  445. // Constructs a ReturnAction object from the value to be returned.
  446. // 'value' is passed by value instead of by const reference in order
  447. // to allow Return("string literal") to compile.
  448. explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
  449. // This template type conversion operator allows Return(x) to be
  450. // used in ANY function that returns x's type.
  451. template <typename F>
  452. operator Action<F>() const { // NOLINT
  453. // Assert statement belongs here because this is the best place to verify
  454. // conditions on F. It produces the clearest error messages
  455. // in most compilers.
  456. // Impl really belongs in this scope as a local class but can't
  457. // because MSVC produces duplicate symbols in different translation units
  458. // in this case. Until MS fixes that bug we put Impl into the class scope
  459. // and put the typedef both here (for use in assert statement) and
  460. // in the Impl class. But both definitions must be the same.
  461. typedef typename Function<F>::Result Result;
  462. GTEST_COMPILE_ASSERT_(
  463. !std::is_reference<Result>::value,
  464. use_ReturnRef_instead_of_Return_to_return_a_reference);
  465. static_assert(!std::is_void<Result>::value,
  466. "Can't use Return() on an action expected to return `void`.");
  467. return Action<F>(new Impl<R, F>(value_));
  468. }
  469. private:
  470. // Implements the Return(x) action for a particular function type F.
  471. template <typename R_, typename F>
  472. class Impl : public ActionInterface<F> {
  473. public:
  474. typedef typename Function<F>::Result Result;
  475. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  476. // The implicit cast is necessary when Result has more than one
  477. // single-argument constructor (e.g. Result is std::vector<int>) and R
  478. // has a type conversion operator template. In that case, value_(value)
  479. // won't compile as the compiler doesn't known which constructor of
  480. // Result to call. ImplicitCast_ forces the compiler to convert R to
  481. // Result without considering explicit constructors, thus resolving the
  482. // ambiguity. value_ is then initialized using its copy constructor.
  483. explicit Impl(const std::shared_ptr<R>& value)
  484. : value_before_cast_(*value),
  485. value_(ImplicitCast_<Result>(value_before_cast_)) {}
  486. Result Perform(const ArgumentTuple&) override { return value_; }
  487. private:
  488. GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
  489. Result_cannot_be_a_reference_type);
  490. // We save the value before casting just in case it is being cast to a
  491. // wrapper type.
  492. R value_before_cast_;
  493. Result value_;
  494. GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
  495. };
  496. // Partially specialize for ByMoveWrapper. This version of ReturnAction will
  497. // move its contents instead.
  498. template <typename R_, typename F>
  499. class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
  500. public:
  501. typedef typename Function<F>::Result Result;
  502. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  503. explicit Impl(const std::shared_ptr<R>& wrapper)
  504. : performed_(false), wrapper_(wrapper) {}
  505. Result Perform(const ArgumentTuple&) override {
  506. GTEST_CHECK_(!performed_)
  507. << "A ByMove() action should only be performed once.";
  508. performed_ = true;
  509. return std::move(wrapper_->payload);
  510. }
  511. private:
  512. bool performed_;
  513. const std::shared_ptr<R> wrapper_;
  514. GTEST_DISALLOW_ASSIGN_(Impl);
  515. };
  516. const std::shared_ptr<R> value_;
  517. GTEST_DISALLOW_ASSIGN_(ReturnAction);
  518. };
  519. // Implements the ReturnNull() action.
  520. class ReturnNullAction {
  521. public:
  522. // Allows ReturnNull() to be used in any pointer-returning function. In C++11
  523. // this is enforced by returning nullptr, and in non-C++11 by asserting a
  524. // pointer type on compile time.
  525. template <typename Result, typename ArgumentTuple>
  526. static Result Perform(const ArgumentTuple&) {
  527. return nullptr;
  528. }
  529. };
  530. // Implements the Return() action.
  531. class ReturnVoidAction {
  532. public:
  533. // Allows Return() to be used in any void-returning function.
  534. template <typename Result, typename ArgumentTuple>
  535. static void Perform(const ArgumentTuple&) {
  536. static_assert(std::is_void<Result>::value, "Result should be void.");
  537. }
  538. };
  539. // Implements the polymorphic ReturnRef(x) action, which can be used
  540. // in any function that returns a reference to the type of x,
  541. // regardless of the argument types.
  542. template <typename T>
  543. class ReturnRefAction {
  544. public:
  545. // Constructs a ReturnRefAction object from the reference to be returned.
  546. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
  547. // This template type conversion operator allows ReturnRef(x) to be
  548. // used in ANY function that returns a reference to x's type.
  549. template <typename F>
  550. operator Action<F>() const {
  551. typedef typename Function<F>::Result Result;
  552. // Asserts that the function return type is a reference. This
  553. // catches the user error of using ReturnRef(x) when Return(x)
  554. // should be used, and generates some helpful error message.
  555. GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
  556. use_Return_instead_of_ReturnRef_to_return_a_value);
  557. return Action<F>(new Impl<F>(ref_));
  558. }
  559. private:
  560. // Implements the ReturnRef(x) action for a particular function type F.
  561. template <typename F>
  562. class Impl : public ActionInterface<F> {
  563. public:
  564. typedef typename Function<F>::Result Result;
  565. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  566. explicit Impl(T& ref) : ref_(ref) {} // NOLINT
  567. Result Perform(const ArgumentTuple&) override { return ref_; }
  568. private:
  569. T& ref_;
  570. GTEST_DISALLOW_ASSIGN_(Impl);
  571. };
  572. T& ref_;
  573. GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
  574. };
  575. // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
  576. // used in any function that returns a reference to the type of x,
  577. // regardless of the argument types.
  578. template <typename T>
  579. class ReturnRefOfCopyAction {
  580. public:
  581. // Constructs a ReturnRefOfCopyAction object from the reference to
  582. // be returned.
  583. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
  584. // This template type conversion operator allows ReturnRefOfCopy(x) to be
  585. // used in ANY function that returns a reference to x's type.
  586. template <typename F>
  587. operator Action<F>() const {
  588. typedef typename Function<F>::Result Result;
  589. // Asserts that the function return type is a reference. This
  590. // catches the user error of using ReturnRefOfCopy(x) when Return(x)
  591. // should be used, and generates some helpful error message.
  592. GTEST_COMPILE_ASSERT_(
  593. std::is_reference<Result>::value,
  594. use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
  595. return Action<F>(new Impl<F>(value_));
  596. }
  597. private:
  598. // Implements the ReturnRefOfCopy(x) action for a particular function type F.
  599. template <typename F>
  600. class Impl : public ActionInterface<F> {
  601. public:
  602. typedef typename Function<F>::Result Result;
  603. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  604. explicit Impl(const T& value) : value_(value) {} // NOLINT
  605. Result Perform(const ArgumentTuple&) override { return value_; }
  606. private:
  607. T value_;
  608. GTEST_DISALLOW_ASSIGN_(Impl);
  609. };
  610. const T value_;
  611. GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
  612. };
  613. // Implements the polymorphic DoDefault() action.
  614. class DoDefaultAction {
  615. public:
  616. // This template type conversion operator allows DoDefault() to be
  617. // used in any function.
  618. template <typename F>
  619. operator Action<F>() const { return Action<F>(); } // NOLINT
  620. };
  621. // Implements the Assign action to set a given pointer referent to a
  622. // particular value.
  623. template <typename T1, typename T2>
  624. class AssignAction {
  625. public:
  626. AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
  627. template <typename Result, typename ArgumentTuple>
  628. void Perform(const ArgumentTuple& /* args */) const {
  629. *ptr_ = value_;
  630. }
  631. private:
  632. T1* const ptr_;
  633. const T2 value_;
  634. GTEST_DISALLOW_ASSIGN_(AssignAction);
  635. };
  636. #if !GTEST_OS_WINDOWS_MOBILE
  637. // Implements the SetErrnoAndReturn action to simulate return from
  638. // various system calls and libc functions.
  639. template <typename T>
  640. class SetErrnoAndReturnAction {
  641. public:
  642. SetErrnoAndReturnAction(int errno_value, T result)
  643. : errno_(errno_value),
  644. result_(result) {}
  645. template <typename Result, typename ArgumentTuple>
  646. Result Perform(const ArgumentTuple& /* args */) const {
  647. errno = errno_;
  648. return result_;
  649. }
  650. private:
  651. const int errno_;
  652. const T result_;
  653. GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
  654. };
  655. #endif // !GTEST_OS_WINDOWS_MOBILE
  656. // Implements the SetArgumentPointee<N>(x) action for any function
  657. // whose N-th argument (0-based) is a pointer to x's type.
  658. template <size_t N, typename A, typename = void>
  659. struct SetArgumentPointeeAction {
  660. A value;
  661. template <typename... Args>
  662. void operator()(const Args&... args) const {
  663. *::std::get<N>(std::tie(args...)) = value;
  664. }
  665. };
  666. // Implements the Invoke(object_ptr, &Class::Method) action.
  667. template <class Class, typename MethodPtr>
  668. struct InvokeMethodAction {
  669. Class* const obj_ptr;
  670. const MethodPtr method_ptr;
  671. template <typename... Args>
  672. auto operator()(Args&&... args) const
  673. -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
  674. return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
  675. }
  676. };
  677. // Implements the InvokeWithoutArgs(f) action. The template argument
  678. // FunctionImpl is the implementation type of f, which can be either a
  679. // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
  680. // Action<F> as long as f's type is compatible with F.
  681. template <typename FunctionImpl>
  682. struct InvokeWithoutArgsAction {
  683. FunctionImpl function_impl;
  684. // Allows InvokeWithoutArgs(f) to be used as any action whose type is
  685. // compatible with f.
  686. template <typename... Args>
  687. auto operator()(const Args&...) -> decltype(function_impl()) {
  688. return function_impl();
  689. }
  690. };
  691. // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
  692. template <class Class, typename MethodPtr>
  693. struct InvokeMethodWithoutArgsAction {
  694. Class* const obj_ptr;
  695. const MethodPtr method_ptr;
  696. using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
  697. template <typename... Args>
  698. ReturnType operator()(const Args&...) const {
  699. return (obj_ptr->*method_ptr)();
  700. }
  701. };
  702. // Implements the IgnoreResult(action) action.
  703. template <typename A>
  704. class IgnoreResultAction {
  705. public:
  706. explicit IgnoreResultAction(const A& action) : action_(action) {}
  707. template <typename F>
  708. operator Action<F>() const {
  709. // Assert statement belongs here because this is the best place to verify
  710. // conditions on F. It produces the clearest error messages
  711. // in most compilers.
  712. // Impl really belongs in this scope as a local class but can't
  713. // because MSVC produces duplicate symbols in different translation units
  714. // in this case. Until MS fixes that bug we put Impl into the class scope
  715. // and put the typedef both here (for use in assert statement) and
  716. // in the Impl class. But both definitions must be the same.
  717. typedef typename internal::Function<F>::Result Result;
  718. // Asserts at compile time that F returns void.
  719. static_assert(std::is_void<Result>::value, "Result type should be void.");
  720. return Action<F>(new Impl<F>(action_));
  721. }
  722. private:
  723. template <typename F>
  724. class Impl : public ActionInterface<F> {
  725. public:
  726. typedef typename internal::Function<F>::Result Result;
  727. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  728. explicit Impl(const A& action) : action_(action) {}
  729. void Perform(const ArgumentTuple& args) override {
  730. // Performs the action and ignores its result.
  731. action_.Perform(args);
  732. }
  733. private:
  734. // Type OriginalFunction is the same as F except that its return
  735. // type is IgnoredValue.
  736. typedef typename internal::Function<F>::MakeResultIgnoredValue
  737. OriginalFunction;
  738. const Action<OriginalFunction> action_;
  739. GTEST_DISALLOW_ASSIGN_(Impl);
  740. };
  741. const A action_;
  742. GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
  743. };
  744. template <typename InnerAction, size_t... I>
  745. struct WithArgsAction {
  746. InnerAction action;
  747. // The inner action could be anything convertible to Action<X>.
  748. // We use the conversion operator to detect the signature of the inner Action.
  749. template <typename R, typename... Args>
  750. operator Action<R(Args...)>() const { // NOLINT
  751. Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)>
  752. converted(action);
  753. return [converted](Args... args) -> R {
  754. return converted.Perform(std::forward_as_tuple(
  755. std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
  756. };
  757. }
  758. };
  759. template <typename... Actions>
  760. struct DoAllAction {
  761. private:
  762. template <typename... Args, size_t... I>
  763. std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
  764. return {std::get<I>(actions)...};
  765. }
  766. public:
  767. std::tuple<Actions...> actions;
  768. template <typename R, typename... Args>
  769. operator Action<R(Args...)>() const { // NOLINT
  770. struct Op {
  771. std::vector<Action<void(Args...)>> converted;
  772. Action<R(Args...)> last;
  773. R operator()(Args... args) const {
  774. auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
  775. for (auto& a : converted) {
  776. a.Perform(tuple_args);
  777. }
  778. return last.Perform(tuple_args);
  779. }
  780. };
  781. return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
  782. std::get<sizeof...(Actions) - 1>(actions)};
  783. }
  784. };
  785. } // namespace internal
  786. // An Unused object can be implicitly constructed from ANY value.
  787. // This is handy when defining actions that ignore some or all of the
  788. // mock function arguments. For example, given
  789. //
  790. // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
  791. // MOCK_METHOD3(Bar, double(int index, double x, double y));
  792. //
  793. // instead of
  794. //
  795. // double DistanceToOriginWithLabel(const string& label, double x, double y) {
  796. // return sqrt(x*x + y*y);
  797. // }
  798. // double DistanceToOriginWithIndex(int index, double x, double y) {
  799. // return sqrt(x*x + y*y);
  800. // }
  801. // ...
  802. // EXPECT_CALL(mock, Foo("abc", _, _))
  803. // .WillOnce(Invoke(DistanceToOriginWithLabel));
  804. // EXPECT_CALL(mock, Bar(5, _, _))
  805. // .WillOnce(Invoke(DistanceToOriginWithIndex));
  806. //
  807. // you could write
  808. //
  809. // // We can declare any uninteresting argument as Unused.
  810. // double DistanceToOrigin(Unused, double x, double y) {
  811. // return sqrt(x*x + y*y);
  812. // }
  813. // ...
  814. // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
  815. // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
  816. typedef internal::IgnoredValue Unused;
  817. // Creates an action that does actions a1, a2, ..., sequentially in
  818. // each invocation.
  819. template <typename... Action>
  820. internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
  821. Action&&... action) {
  822. return {std::forward_as_tuple(std::forward<Action>(action)...)};
  823. }
  824. // WithArg<k>(an_action) creates an action that passes the k-th
  825. // (0-based) argument of the mock function to an_action and performs
  826. // it. It adapts an action accepting one argument to one that accepts
  827. // multiple arguments. For convenience, we also provide
  828. // WithArgs<k>(an_action) (defined below) as a synonym.
  829. template <size_t k, typename InnerAction>
  830. internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
  831. WithArg(InnerAction&& action) {
  832. return {std::forward<InnerAction>(action)};
  833. }
  834. // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
  835. // the selected arguments of the mock function to an_action and
  836. // performs it. It serves as an adaptor between actions with
  837. // different argument lists.
  838. template <size_t k, size_t... ks, typename InnerAction>
  839. internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
  840. WithArgs(InnerAction&& action) {
  841. return {std::forward<InnerAction>(action)};
  842. }
  843. // WithoutArgs(inner_action) can be used in a mock function with a
  844. // non-empty argument list to perform inner_action, which takes no
  845. // argument. In other words, it adapts an action accepting no
  846. // argument to one that accepts (and ignores) arguments.
  847. template <typename InnerAction>
  848. internal::WithArgsAction<typename std::decay<InnerAction>::type>
  849. WithoutArgs(InnerAction&& action) {
  850. return {std::forward<InnerAction>(action)};
  851. }
  852. // Creates an action that returns 'value'. 'value' is passed by value
  853. // instead of const reference - otherwise Return("string literal")
  854. // will trigger a compiler error about using array as initializer.
  855. template <typename R>
  856. internal::ReturnAction<R> Return(R value) {
  857. return internal::ReturnAction<R>(std::move(value));
  858. }
  859. // Creates an action that returns NULL.
  860. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
  861. return MakePolymorphicAction(internal::ReturnNullAction());
  862. }
  863. // Creates an action that returns from a void function.
  864. inline PolymorphicAction<internal::ReturnVoidAction> Return() {
  865. return MakePolymorphicAction(internal::ReturnVoidAction());
  866. }
  867. // Creates an action that returns the reference to a variable.
  868. template <typename R>
  869. inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
  870. return internal::ReturnRefAction<R>(x);
  871. }
  872. // Creates an action that returns the reference to a copy of the
  873. // argument. The copy is created when the action is constructed and
  874. // lives as long as the action.
  875. template <typename R>
  876. inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
  877. return internal::ReturnRefOfCopyAction<R>(x);
  878. }
  879. // Modifies the parent action (a Return() action) to perform a move of the
  880. // argument instead of a copy.
  881. // Return(ByMove()) actions can only be executed once and will assert this
  882. // invariant.
  883. template <typename R>
  884. internal::ByMoveWrapper<R> ByMove(R x) {
  885. return internal::ByMoveWrapper<R>(std::move(x));
  886. }
  887. // Creates an action that does the default action for the give mock function.
  888. inline internal::DoDefaultAction DoDefault() {
  889. return internal::DoDefaultAction();
  890. }
  891. // Creates an action that sets the variable pointed by the N-th
  892. // (0-based) function argument to 'value'.
  893. template <size_t N, typename T>
  894. internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) {
  895. return {std::move(x)};
  896. }
  897. // The following version is DEPRECATED.
  898. template <size_t N, typename T>
  899. internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) {
  900. return {std::move(x)};
  901. }
  902. // Creates an action that sets a pointer referent to a given value.
  903. template <typename T1, typename T2>
  904. PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
  905. return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
  906. }
  907. #if !GTEST_OS_WINDOWS_MOBILE
  908. // Creates an action that sets errno and returns the appropriate error.
  909. template <typename T>
  910. PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
  911. SetErrnoAndReturn(int errval, T result) {
  912. return MakePolymorphicAction(
  913. internal::SetErrnoAndReturnAction<T>(errval, result));
  914. }
  915. #endif // !GTEST_OS_WINDOWS_MOBILE
  916. // Various overloads for Invoke().
  917. // Legacy function.
  918. // Actions can now be implicitly constructed from callables. No need to create
  919. // wrapper objects.
  920. // This function exists for backwards compatibility.
  921. template <typename FunctionImpl>
  922. typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
  923. return std::forward<FunctionImpl>(function_impl);
  924. }
  925. // Creates an action that invokes the given method on the given object
  926. // with the mock function's arguments.
  927. template <class Class, typename MethodPtr>
  928. internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
  929. MethodPtr method_ptr) {
  930. return {obj_ptr, method_ptr};
  931. }
  932. // Creates an action that invokes 'function_impl' with no argument.
  933. template <typename FunctionImpl>
  934. internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
  935. InvokeWithoutArgs(FunctionImpl function_impl) {
  936. return {std::move(function_impl)};
  937. }
  938. // Creates an action that invokes the given method on the given object
  939. // with no argument.
  940. template <class Class, typename MethodPtr>
  941. internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
  942. Class* obj_ptr, MethodPtr method_ptr) {
  943. return {obj_ptr, method_ptr};
  944. }
  945. // Creates an action that performs an_action and throws away its
  946. // result. In other words, it changes the return type of an_action to
  947. // void. an_action MUST NOT return void, or the code won't compile.
  948. template <typename A>
  949. inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
  950. return internal::IgnoreResultAction<A>(an_action);
  951. }
  952. // Creates a reference wrapper for the given L-value. If necessary,
  953. // you can explicitly specify the type of the reference. For example,
  954. // suppose 'derived' is an object of type Derived, ByRef(derived)
  955. // would wrap a Derived&. If you want to wrap a const Base& instead,
  956. // where Base is a base class of Derived, just write:
  957. //
  958. // ByRef<const Base>(derived)
  959. //
  960. // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
  961. // However, it may still be used for consistency with ByMove().
  962. template <typename T>
  963. inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
  964. return ::std::reference_wrapper<T>(l_value);
  965. }
  966. } // namespace testing
  967. #ifdef _MSC_VER
  968. # pragma warning(pop)
  969. #endif
  970. #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_