The source code and dockerfile for the GSW2024 AI Lab.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

1687 lines
60 KiB

2 months ago
  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. // The ACTION* family of macros can be used in a namespace scope to
  32. // define custom actions easily. The syntax:
  33. //
  34. // ACTION(name) { statements; }
  35. //
  36. // will define an action with the given name that executes the
  37. // statements. The value returned by the statements will be used as
  38. // the return value of the action. Inside the statements, you can
  39. // refer to the K-th (0-based) argument of the mock function by
  40. // 'argK', and refer to its type by 'argK_type'. For example:
  41. //
  42. // ACTION(IncrementArg1) {
  43. // arg1_type temp = arg1;
  44. // return ++(*temp);
  45. // }
  46. //
  47. // allows you to write
  48. //
  49. // ...WillOnce(IncrementArg1());
  50. //
  51. // You can also refer to the entire argument tuple and its type by
  52. // 'args' and 'args_type', and refer to the mock function type and its
  53. // return type by 'function_type' and 'return_type'.
  54. //
  55. // Note that you don't need to specify the types of the mock function
  56. // arguments. However rest assured that your code is still type-safe:
  57. // you'll get a compiler error if *arg1 doesn't support the ++
  58. // operator, or if the type of ++(*arg1) isn't compatible with the
  59. // mock function's return type, for example.
  60. //
  61. // Sometimes you'll want to parameterize the action. For that you can use
  62. // another macro:
  63. //
  64. // ACTION_P(name, param_name) { statements; }
  65. //
  66. // For example:
  67. //
  68. // ACTION_P(Add, n) { return arg0 + n; }
  69. //
  70. // will allow you to write:
  71. //
  72. // ...WillOnce(Add(5));
  73. //
  74. // Note that you don't need to provide the type of the parameter
  75. // either. If you need to reference the type of a parameter named
  76. // 'foo', you can write 'foo_type'. For example, in the body of
  77. // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
  78. // of 'n'.
  79. //
  80. // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
  81. // multi-parameter actions.
  82. //
  83. // For the purpose of typing, you can view
  84. //
  85. // ACTION_Pk(Foo, p1, ..., pk) { ... }
  86. //
  87. // as shorthand for
  88. //
  89. // template <typename p1_type, ..., typename pk_type>
  90. // FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
  91. //
  92. // In particular, you can provide the template type arguments
  93. // explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
  94. // although usually you can rely on the compiler to infer the types
  95. // for you automatically. You can assign the result of expression
  96. // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
  97. // pk_type>. This can be useful when composing actions.
  98. //
  99. // You can also overload actions with different numbers of parameters:
  100. //
  101. // ACTION_P(Plus, a) { ... }
  102. // ACTION_P2(Plus, a, b) { ... }
  103. //
  104. // While it's tempting to always use the ACTION* macros when defining
  105. // a new action, you should also consider implementing ActionInterface
  106. // or using MakePolymorphicAction() instead, especially if you need to
  107. // use the action a lot. While these approaches require more work,
  108. // they give you more control on the types of the mock function
  109. // arguments and the action parameters, which in general leads to
  110. // better compiler error messages that pay off in the long run. They
  111. // also allow overloading actions based on parameter types (as opposed
  112. // to just based on the number of parameters).
  113. //
  114. // CAVEAT:
  115. //
  116. // ACTION*() can only be used in a namespace scope as templates cannot be
  117. // declared inside of a local class.
  118. // Users can, however, define any local functors (e.g. a lambda) that
  119. // can be used as actions.
  120. //
  121. // MORE INFORMATION:
  122. //
  123. // To learn more about using these macros, please search for 'ACTION' on
  124. // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
  125. // GOOGLETEST_CM0002 DO NOT DELETE
  126. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  127. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  128. #ifndef _WIN32_WCE
  129. # include <errno.h>
  130. #endif
  131. #include <algorithm>
  132. #include <functional>
  133. #include <memory>
  134. #include <string>
  135. #include <tuple>
  136. #include <type_traits>
  137. #include <utility>
  138. #include "gmock/internal/gmock-internal-utils.h"
  139. #include "gmock/internal/gmock-port.h"
  140. #include "gmock/internal/gmock-pp.h"
  141. #ifdef _MSC_VER
  142. # pragma warning(push)
  143. # pragma warning(disable:4100)
  144. #endif
  145. namespace testing {
  146. // To implement an action Foo, define:
  147. // 1. a class FooAction that implements the ActionInterface interface, and
  148. // 2. a factory function that creates an Action object from a
  149. // const FooAction*.
  150. //
  151. // The two-level delegation design follows that of Matcher, providing
  152. // consistency for extension developers. It also eases ownership
  153. // management as Action objects can now be copied like plain values.
  154. namespace internal {
  155. // BuiltInDefaultValueGetter<T, true>::Get() returns a
  156. // default-constructed T value. BuiltInDefaultValueGetter<T,
  157. // false>::Get() crashes with an error.
  158. //
  159. // This primary template is used when kDefaultConstructible is true.
  160. template <typename T, bool kDefaultConstructible>
  161. struct BuiltInDefaultValueGetter {
  162. static T Get() { return T(); }
  163. };
  164. template <typename T>
  165. struct BuiltInDefaultValueGetter<T, false> {
  166. static T Get() {
  167. Assert(false, __FILE__, __LINE__,
  168. "Default action undefined for the function return type.");
  169. return internal::Invalid<T>();
  170. // The above statement will never be reached, but is required in
  171. // order for this function to compile.
  172. }
  173. };
  174. // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
  175. // for type T, which is NULL when T is a raw pointer type, 0 when T is
  176. // a numeric type, false when T is bool, or "" when T is string or
  177. // std::string. In addition, in C++11 and above, it turns a
  178. // default-constructed T value if T is default constructible. For any
  179. // other type T, the built-in default T value is undefined, and the
  180. // function will abort the process.
  181. template <typename T>
  182. class BuiltInDefaultValue {
  183. public:
  184. // This function returns true if and only if type T has a built-in default
  185. // value.
  186. static bool Exists() {
  187. return ::std::is_default_constructible<T>::value;
  188. }
  189. static T Get() {
  190. return BuiltInDefaultValueGetter<
  191. T, ::std::is_default_constructible<T>::value>::Get();
  192. }
  193. };
  194. // This partial specialization says that we use the same built-in
  195. // default value for T and const T.
  196. template <typename T>
  197. class BuiltInDefaultValue<const T> {
  198. public:
  199. static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
  200. static T Get() { return BuiltInDefaultValue<T>::Get(); }
  201. };
  202. // This partial specialization defines the default values for pointer
  203. // types.
  204. template <typename T>
  205. class BuiltInDefaultValue<T*> {
  206. public:
  207. static bool Exists() { return true; }
  208. static T* Get() { return nullptr; }
  209. };
  210. // The following specializations define the default values for
  211. // specific types we care about.
  212. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
  213. template <> \
  214. class BuiltInDefaultValue<type> { \
  215. public: \
  216. static bool Exists() { return true; } \
  217. static type Get() { return value; } \
  218. }
  219. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
  220. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
  221. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
  222. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
  223. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
  224. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
  225. // There's no need for a default action for signed wchar_t, as that
  226. // type is the same as wchar_t for gcc, and invalid for MSVC.
  227. //
  228. // There's also no need for a default action for unsigned wchar_t, as
  229. // that type is the same as unsigned int for gcc, and invalid for
  230. // MSVC.
  231. #if GMOCK_WCHAR_T_IS_NATIVE_
  232. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
  233. #endif
  234. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
  235. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
  236. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
  237. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
  238. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
  239. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
  240. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT
  241. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT
  242. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
  243. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
  244. #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
  245. // Simple two-arg form of std::disjunction.
  246. template <typename P, typename Q>
  247. using disjunction = typename ::std::conditional<P::value, P, Q>::type;
  248. } // namespace internal
  249. // When an unexpected function call is encountered, Google Mock will
  250. // let it return a default value if the user has specified one for its
  251. // return type, or if the return type has a built-in default value;
  252. // otherwise Google Mock won't know what value to return and will have
  253. // to abort the process.
  254. //
  255. // The DefaultValue<T> class allows a user to specify the
  256. // default value for a type T that is both copyable and publicly
  257. // destructible (i.e. anything that can be used as a function return
  258. // type). The usage is:
  259. //
  260. // // Sets the default value for type T to be foo.
  261. // DefaultValue<T>::Set(foo);
  262. template <typename T>
  263. class DefaultValue {
  264. public:
  265. // Sets the default value for type T; requires T to be
  266. // copy-constructable and have a public destructor.
  267. static void Set(T x) {
  268. delete producer_;
  269. producer_ = new FixedValueProducer(x);
  270. }
  271. // Provides a factory function to be called to generate the default value.
  272. // This method can be used even if T is only move-constructible, but it is not
  273. // limited to that case.
  274. typedef T (*FactoryFunction)();
  275. static void SetFactory(FactoryFunction factory) {
  276. delete producer_;
  277. producer_ = new FactoryValueProducer(factory);
  278. }
  279. // Unsets the default value for type T.
  280. static void Clear() {
  281. delete producer_;
  282. producer_ = nullptr;
  283. }
  284. // Returns true if and only if the user has set the default value for type T.
  285. static bool IsSet() { return producer_ != nullptr; }
  286. // Returns true if T has a default return value set by the user or there
  287. // exists a built-in default value.
  288. static bool Exists() {
  289. return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
  290. }
  291. // Returns the default value for type T if the user has set one;
  292. // otherwise returns the built-in default value. Requires that Exists()
  293. // is true, which ensures that the return value is well-defined.
  294. static T Get() {
  295. return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
  296. : producer_->Produce();
  297. }
  298. private:
  299. class ValueProducer {
  300. public:
  301. virtual ~ValueProducer() {}
  302. virtual T Produce() = 0;
  303. };
  304. class FixedValueProducer : public ValueProducer {
  305. public:
  306. explicit FixedValueProducer(T value) : value_(value) {}
  307. T Produce() override { return value_; }
  308. private:
  309. const T value_;
  310. GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
  311. };
  312. class FactoryValueProducer : public ValueProducer {
  313. public:
  314. explicit FactoryValueProducer(FactoryFunction factory)
  315. : factory_(factory) {}
  316. T Produce() override { return factory_(); }
  317. private:
  318. const FactoryFunction factory_;
  319. GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
  320. };
  321. static ValueProducer* producer_;
  322. };
  323. // This partial specialization allows a user to set default values for
  324. // reference types.
  325. template <typename T>
  326. class DefaultValue<T&> {
  327. public:
  328. // Sets the default value for type T&.
  329. static void Set(T& x) { // NOLINT
  330. address_ = &x;
  331. }
  332. // Unsets the default value for type T&.
  333. static void Clear() { address_ = nullptr; }
  334. // Returns true if and only if the user has set the default value for type T&.
  335. static bool IsSet() { return address_ != nullptr; }
  336. // Returns true if T has a default return value set by the user or there
  337. // exists a built-in default value.
  338. static bool Exists() {
  339. return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
  340. }
  341. // Returns the default value for type T& if the user has set one;
  342. // otherwise returns the built-in default value if there is one;
  343. // otherwise aborts the process.
  344. static T& Get() {
  345. return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
  346. : *address_;
  347. }
  348. private:
  349. static T* address_;
  350. };
  351. // This specialization allows DefaultValue<void>::Get() to
  352. // compile.
  353. template <>
  354. class DefaultValue<void> {
  355. public:
  356. static bool Exists() { return true; }
  357. static void Get() {}
  358. };
  359. // Points to the user-set default value for type T.
  360. template <typename T>
  361. typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
  362. // Points to the user-set default value for type T&.
  363. template <typename T>
  364. T* DefaultValue<T&>::address_ = nullptr;
  365. // Implement this interface to define an action for function type F.
  366. template <typename F>
  367. class ActionInterface {
  368. public:
  369. typedef typename internal::Function<F>::Result Result;
  370. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  371. ActionInterface() {}
  372. virtual ~ActionInterface() {}
  373. // Performs the action. This method is not const, as in general an
  374. // action can have side effects and be stateful. For example, a
  375. // get-the-next-element-from-the-collection action will need to
  376. // remember the current element.
  377. virtual Result Perform(const ArgumentTuple& args) = 0;
  378. private:
  379. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
  380. };
  381. // An Action<F> is a copyable and IMMUTABLE (except by assignment)
  382. // object that represents an action to be taken when a mock function
  383. // of type F is called. The implementation of Action<T> is just a
  384. // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
  385. // You can view an object implementing ActionInterface<F> as a
  386. // concrete action (including its current state), and an Action<F>
  387. // object as a handle to it.
  388. template <typename F>
  389. class Action {
  390. // Adapter class to allow constructing Action from a legacy ActionInterface.
  391. // New code should create Actions from functors instead.
  392. struct ActionAdapter {
  393. // Adapter must be copyable to satisfy std::function requirements.
  394. ::std::shared_ptr<ActionInterface<F>> impl_;
  395. template <typename... Args>
  396. typename internal::Function<F>::Result operator()(Args&&... args) {
  397. return impl_->Perform(
  398. ::std::forward_as_tuple(::std::forward<Args>(args)...));
  399. }
  400. };
  401. template <typename G>
  402. using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
  403. public:
  404. typedef typename internal::Function<F>::Result Result;
  405. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  406. // Constructs a null Action. Needed for storing Action objects in
  407. // STL containers.
  408. Action() {}
  409. // Construct an Action from a specified callable.
  410. // This cannot take std::function directly, because then Action would not be
  411. // directly constructible from lambda (it would require two conversions).
  412. template <
  413. typename G,
  414. typename = typename std::enable_if<internal::disjunction<
  415. IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
  416. G>>::value>::type>
  417. Action(G&& fun) { // NOLINT
  418. Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
  419. }
  420. // Constructs an Action from its implementation.
  421. explicit Action(ActionInterface<F>* impl)
  422. : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
  423. // This constructor allows us to turn an Action<Func> object into an
  424. // Action<F>, as long as F's arguments can be implicitly converted
  425. // to Func's and Func's return type can be implicitly converted to F's.
  426. template <typename Func>
  427. explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
  428. // Returns true if and only if this is the DoDefault() action.
  429. bool IsDoDefault() const { return fun_ == nullptr; }
  430. // Performs the action. Note that this method is const even though
  431. // the corresponding method in ActionInterface is not. The reason
  432. // is that a const Action<F> means that it cannot be re-bound to
  433. // another concrete action, not that the concrete action it binds to
  434. // cannot change state. (Think of the difference between a const
  435. // pointer and a pointer to const.)
  436. Result Perform(ArgumentTuple args) const {
  437. if (IsDoDefault()) {
  438. internal::IllegalDoDefault(__FILE__, __LINE__);
  439. }
  440. return internal::Apply(fun_, ::std::move(args));
  441. }
  442. private:
  443. template <typename G>
  444. friend class Action;
  445. template <typename G>
  446. void Init(G&& g, ::std::true_type) {
  447. fun_ = ::std::forward<G>(g);
  448. }
  449. template <typename G>
  450. void Init(G&& g, ::std::false_type) {
  451. fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
  452. }
  453. template <typename FunctionImpl>
  454. struct IgnoreArgs {
  455. template <typename... Args>
  456. Result operator()(const Args&...) const {
  457. return function_impl();
  458. }
  459. FunctionImpl function_impl;
  460. };
  461. // fun_ is an empty function if and only if this is the DoDefault() action.
  462. ::std::function<F> fun_;
  463. };
  464. // The PolymorphicAction class template makes it easy to implement a
  465. // polymorphic action (i.e. an action that can be used in mock
  466. // functions of than one type, e.g. Return()).
  467. //
  468. // To define a polymorphic action, a user first provides a COPYABLE
  469. // implementation class that has a Perform() method template:
  470. //
  471. // class FooAction {
  472. // public:
  473. // template <typename Result, typename ArgumentTuple>
  474. // Result Perform(const ArgumentTuple& args) const {
  475. // // Processes the arguments and returns a result, using
  476. // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
  477. // }
  478. // ...
  479. // };
  480. //
  481. // Then the user creates the polymorphic action using
  482. // MakePolymorphicAction(object) where object has type FooAction. See
  483. // the definition of Return(void) and SetArgumentPointee<N>(value) for
  484. // complete examples.
  485. template <typename Impl>
  486. class PolymorphicAction {
  487. public:
  488. explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
  489. template <typename F>
  490. operator Action<F>() const {
  491. return Action<F>(new MonomorphicImpl<F>(impl_));
  492. }
  493. private:
  494. template <typename F>
  495. class MonomorphicImpl : public ActionInterface<F> {
  496. public:
  497. typedef typename internal::Function<F>::Result Result;
  498. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  499. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  500. Result Perform(const ArgumentTuple& args) override {
  501. return impl_.template Perform<Result>(args);
  502. }
  503. private:
  504. Impl impl_;
  505. };
  506. Impl impl_;
  507. };
  508. // Creates an Action from its implementation and returns it. The
  509. // created Action object owns the implementation.
  510. template <typename F>
  511. Action<F> MakeAction(ActionInterface<F>* impl) {
  512. return Action<F>(impl);
  513. }
  514. // Creates a polymorphic action from its implementation. This is
  515. // easier to use than the PolymorphicAction<Impl> constructor as it
  516. // doesn't require you to explicitly write the template argument, e.g.
  517. //
  518. // MakePolymorphicAction(foo);
  519. // vs
  520. // PolymorphicAction<TypeOfFoo>(foo);
  521. template <typename Impl>
  522. inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
  523. return PolymorphicAction<Impl>(impl);
  524. }
  525. namespace internal {
  526. // Helper struct to specialize ReturnAction to execute a move instead of a copy
  527. // on return. Useful for move-only types, but could be used on any type.
  528. template <typename T>
  529. struct ByMoveWrapper {
  530. explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
  531. T payload;
  532. };
  533. // Implements the polymorphic Return(x) action, which can be used in
  534. // any function that returns the type of x, regardless of the argument
  535. // types.
  536. //
  537. // Note: The value passed into Return must be converted into
  538. // Function<F>::Result when this action is cast to Action<F> rather than
  539. // when that action is performed. This is important in scenarios like
  540. //
  541. // MOCK_METHOD1(Method, T(U));
  542. // ...
  543. // {
  544. // Foo foo;
  545. // X x(&foo);
  546. // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
  547. // }
  548. //
  549. // In the example above the variable x holds reference to foo which leaves
  550. // scope and gets destroyed. If copying X just copies a reference to foo,
  551. // that copy will be left with a hanging reference. If conversion to T
  552. // makes a copy of foo, the above code is safe. To support that scenario, we
  553. // need to make sure that the type conversion happens inside the EXPECT_CALL
  554. // statement, and conversion of the result of Return to Action<T(U)> is a
  555. // good place for that.
  556. //
  557. // The real life example of the above scenario happens when an invocation
  558. // of gtl::Container() is passed into Return.
  559. //
  560. template <typename R>
  561. class ReturnAction {
  562. public:
  563. // Constructs a ReturnAction object from the value to be returned.
  564. // 'value' is passed by value instead of by const reference in order
  565. // to allow Return("string literal") to compile.
  566. explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
  567. // This template type conversion operator allows Return(x) to be
  568. // used in ANY function that returns x's type.
  569. template <typename F>
  570. operator Action<F>() const { // NOLINT
  571. // Assert statement belongs here because this is the best place to verify
  572. // conditions on F. It produces the clearest error messages
  573. // in most compilers.
  574. // Impl really belongs in this scope as a local class but can't
  575. // because MSVC produces duplicate symbols in different translation units
  576. // in this case. Until MS fixes that bug we put Impl into the class scope
  577. // and put the typedef both here (for use in assert statement) and
  578. // in the Impl class. But both definitions must be the same.
  579. typedef typename Function<F>::Result Result;
  580. GTEST_COMPILE_ASSERT_(
  581. !std::is_reference<Result>::value,
  582. use_ReturnRef_instead_of_Return_to_return_a_reference);
  583. static_assert(!std::is_void<Result>::value,
  584. "Can't use Return() on an action expected to return `void`.");
  585. return Action<F>(new Impl<R, F>(value_));
  586. }
  587. private:
  588. // Implements the Return(x) action for a particular function type F.
  589. template <typename R_, typename F>
  590. class Impl : public ActionInterface<F> {
  591. public:
  592. typedef typename Function<F>::Result Result;
  593. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  594. // The implicit cast is necessary when Result has more than one
  595. // single-argument constructor (e.g. Result is std::vector<int>) and R
  596. // has a type conversion operator template. In that case, value_(value)
  597. // won't compile as the compiler doesn't known which constructor of
  598. // Result to call. ImplicitCast_ forces the compiler to convert R to
  599. // Result without considering explicit constructors, thus resolving the
  600. // ambiguity. value_ is then initialized using its copy constructor.
  601. explicit Impl(const std::shared_ptr<R>& value)
  602. : value_before_cast_(*value),
  603. value_(ImplicitCast_<Result>(value_before_cast_)) {}
  604. Result Perform(const ArgumentTuple&) override { return value_; }
  605. private:
  606. GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
  607. Result_cannot_be_a_reference_type);
  608. // We save the value before casting just in case it is being cast to a
  609. // wrapper type.
  610. R value_before_cast_;
  611. Result value_;
  612. GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
  613. };
  614. // Partially specialize for ByMoveWrapper. This version of ReturnAction will
  615. // move its contents instead.
  616. template <typename R_, typename F>
  617. class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
  618. public:
  619. typedef typename Function<F>::Result Result;
  620. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  621. explicit Impl(const std::shared_ptr<R>& wrapper)
  622. : performed_(false), wrapper_(wrapper) {}
  623. Result Perform(const ArgumentTuple&) override {
  624. GTEST_CHECK_(!performed_)
  625. << "A ByMove() action should only be performed once.";
  626. performed_ = true;
  627. return std::move(wrapper_->payload);
  628. }
  629. private:
  630. bool performed_;
  631. const std::shared_ptr<R> wrapper_;
  632. };
  633. const std::shared_ptr<R> value_;
  634. };
  635. // Implements the ReturnNull() action.
  636. class ReturnNullAction {
  637. public:
  638. // Allows ReturnNull() to be used in any pointer-returning function. In C++11
  639. // this is enforced by returning nullptr, and in non-C++11 by asserting a
  640. // pointer type on compile time.
  641. template <typename Result, typename ArgumentTuple>
  642. static Result Perform(const ArgumentTuple&) {
  643. return nullptr;
  644. }
  645. };
  646. // Implements the Return() action.
  647. class ReturnVoidAction {
  648. public:
  649. // Allows Return() to be used in any void-returning function.
  650. template <typename Result, typename ArgumentTuple>
  651. static void Perform(const ArgumentTuple&) {
  652. static_assert(std::is_void<Result>::value, "Result should be void.");
  653. }
  654. };
  655. // Implements the polymorphic ReturnRef(x) action, which can be used
  656. // in any function that returns a reference to the type of x,
  657. // regardless of the argument types.
  658. template <typename T>
  659. class ReturnRefAction {
  660. public:
  661. // Constructs a ReturnRefAction object from the reference to be returned.
  662. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
  663. // This template type conversion operator allows ReturnRef(x) to be
  664. // used in ANY function that returns a reference to x's type.
  665. template <typename F>
  666. operator Action<F>() const {
  667. typedef typename Function<F>::Result Result;
  668. // Asserts that the function return type is a reference. This
  669. // catches the user error of using ReturnRef(x) when Return(x)
  670. // should be used, and generates some helpful error message.
  671. GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
  672. use_Return_instead_of_ReturnRef_to_return_a_value);
  673. return Action<F>(new Impl<F>(ref_));
  674. }
  675. private:
  676. // Implements the ReturnRef(x) action for a particular function type F.
  677. template <typename F>
  678. class Impl : public ActionInterface<F> {
  679. public:
  680. typedef typename Function<F>::Result Result;
  681. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  682. explicit Impl(T& ref) : ref_(ref) {} // NOLINT
  683. Result Perform(const ArgumentTuple&) override { return ref_; }
  684. private:
  685. T& ref_;
  686. };
  687. T& ref_;
  688. };
  689. // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
  690. // used in any function that returns a reference to the type of x,
  691. // regardless of the argument types.
  692. template <typename T>
  693. class ReturnRefOfCopyAction {
  694. public:
  695. // Constructs a ReturnRefOfCopyAction object from the reference to
  696. // be returned.
  697. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
  698. // This template type conversion operator allows ReturnRefOfCopy(x) to be
  699. // used in ANY function that returns a reference to x's type.
  700. template <typename F>
  701. operator Action<F>() const {
  702. typedef typename Function<F>::Result Result;
  703. // Asserts that the function return type is a reference. This
  704. // catches the user error of using ReturnRefOfCopy(x) when Return(x)
  705. // should be used, and generates some helpful error message.
  706. GTEST_COMPILE_ASSERT_(
  707. std::is_reference<Result>::value,
  708. use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
  709. return Action<F>(new Impl<F>(value_));
  710. }
  711. private:
  712. // Implements the ReturnRefOfCopy(x) action for a particular function type F.
  713. template <typename F>
  714. class Impl : public ActionInterface<F> {
  715. public:
  716. typedef typename Function<F>::Result Result;
  717. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  718. explicit Impl(const T& value) : value_(value) {} // NOLINT
  719. Result Perform(const ArgumentTuple&) override { return value_; }
  720. private:
  721. T value_;
  722. };
  723. const T value_;
  724. };
  725. // Implements the polymorphic ReturnRoundRobin(v) action, which can be
  726. // used in any function that returns the element_type of v.
  727. template <typename T>
  728. class ReturnRoundRobinAction {
  729. public:
  730. explicit ReturnRoundRobinAction(std::vector<T> values) {
  731. GTEST_CHECK_(!values.empty())
  732. << "ReturnRoundRobin requires at least one element.";
  733. state_->values = std::move(values);
  734. }
  735. template <typename... Args>
  736. T operator()(Args&&...) const {
  737. return state_->Next();
  738. }
  739. private:
  740. struct State {
  741. T Next() {
  742. T ret_val = values[i++];
  743. if (i == values.size()) i = 0;
  744. return ret_val;
  745. }
  746. std::vector<T> values;
  747. size_t i = 0;
  748. };
  749. std::shared_ptr<State> state_ = std::make_shared<State>();
  750. };
  751. // Implements the polymorphic DoDefault() action.
  752. class DoDefaultAction {
  753. public:
  754. // This template type conversion operator allows DoDefault() to be
  755. // used in any function.
  756. template <typename F>
  757. operator Action<F>() const { return Action<F>(); } // NOLINT
  758. };
  759. // Implements the Assign action to set a given pointer referent to a
  760. // particular value.
  761. template <typename T1, typename T2>
  762. class AssignAction {
  763. public:
  764. AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
  765. template <typename Result, typename ArgumentTuple>
  766. void Perform(const ArgumentTuple& /* args */) const {
  767. *ptr_ = value_;
  768. }
  769. private:
  770. T1* const ptr_;
  771. const T2 value_;
  772. };
  773. #if !GTEST_OS_WINDOWS_MOBILE
  774. // Implements the SetErrnoAndReturn action to simulate return from
  775. // various system calls and libc functions.
  776. template <typename T>
  777. class SetErrnoAndReturnAction {
  778. public:
  779. SetErrnoAndReturnAction(int errno_value, T result)
  780. : errno_(errno_value),
  781. result_(result) {}
  782. template <typename Result, typename ArgumentTuple>
  783. Result Perform(const ArgumentTuple& /* args */) const {
  784. errno = errno_;
  785. return result_;
  786. }
  787. private:
  788. const int errno_;
  789. const T result_;
  790. };
  791. #endif // !GTEST_OS_WINDOWS_MOBILE
  792. // Implements the SetArgumentPointee<N>(x) action for any function
  793. // whose N-th argument (0-based) is a pointer to x's type.
  794. template <size_t N, typename A, typename = void>
  795. struct SetArgumentPointeeAction {
  796. A value;
  797. template <typename... Args>
  798. void operator()(const Args&... args) const {
  799. *::std::get<N>(std::tie(args...)) = value;
  800. }
  801. };
  802. // Implements the Invoke(object_ptr, &Class::Method) action.
  803. template <class Class, typename MethodPtr>
  804. struct InvokeMethodAction {
  805. Class* const obj_ptr;
  806. const MethodPtr method_ptr;
  807. template <typename... Args>
  808. auto operator()(Args&&... args) const
  809. -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
  810. return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
  811. }
  812. };
  813. // Implements the InvokeWithoutArgs(f) action. The template argument
  814. // FunctionImpl is the implementation type of f, which can be either a
  815. // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
  816. // Action<F> as long as f's type is compatible with F.
  817. template <typename FunctionImpl>
  818. struct InvokeWithoutArgsAction {
  819. FunctionImpl function_impl;
  820. // Allows InvokeWithoutArgs(f) to be used as any action whose type is
  821. // compatible with f.
  822. template <typename... Args>
  823. auto operator()(const Args&...) -> decltype(function_impl()) {
  824. return function_impl();
  825. }
  826. };
  827. // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
  828. template <class Class, typename MethodPtr>
  829. struct InvokeMethodWithoutArgsAction {
  830. Class* const obj_ptr;
  831. const MethodPtr method_ptr;
  832. using ReturnType =
  833. decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
  834. template <typename... Args>
  835. ReturnType operator()(const Args&...) const {
  836. return (obj_ptr->*method_ptr)();
  837. }
  838. };
  839. // Implements the IgnoreResult(action) action.
  840. template <typename A>
  841. class IgnoreResultAction {
  842. public:
  843. explicit IgnoreResultAction(const A& action) : action_(action) {}
  844. template <typename F>
  845. operator Action<F>() const {
  846. // Assert statement belongs here because this is the best place to verify
  847. // conditions on F. It produces the clearest error messages
  848. // in most compilers.
  849. // Impl really belongs in this scope as a local class but can't
  850. // because MSVC produces duplicate symbols in different translation units
  851. // in this case. Until MS fixes that bug we put Impl into the class scope
  852. // and put the typedef both here (for use in assert statement) and
  853. // in the Impl class. But both definitions must be the same.
  854. typedef typename internal::Function<F>::Result Result;
  855. // Asserts at compile time that F returns void.
  856. static_assert(std::is_void<Result>::value, "Result type should be void.");
  857. return Action<F>(new Impl<F>(action_));
  858. }
  859. private:
  860. template <typename F>
  861. class Impl : public ActionInterface<F> {
  862. public:
  863. typedef typename internal::Function<F>::Result Result;
  864. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  865. explicit Impl(const A& action) : action_(action) {}
  866. void Perform(const ArgumentTuple& args) override {
  867. // Performs the action and ignores its result.
  868. action_.Perform(args);
  869. }
  870. private:
  871. // Type OriginalFunction is the same as F except that its return
  872. // type is IgnoredValue.
  873. typedef typename internal::Function<F>::MakeResultIgnoredValue
  874. OriginalFunction;
  875. const Action<OriginalFunction> action_;
  876. };
  877. const A action_;
  878. };
  879. template <typename InnerAction, size_t... I>
  880. struct WithArgsAction {
  881. InnerAction action;
  882. // The inner action could be anything convertible to Action<X>.
  883. // We use the conversion operator to detect the signature of the inner Action.
  884. template <typename R, typename... Args>
  885. operator Action<R(Args...)>() const { // NOLINT
  886. using TupleType = std::tuple<Args...>;
  887. Action<R(typename std::tuple_element<I, TupleType>::type...)>
  888. converted(action);
  889. return [converted](Args... args) -> R {
  890. return converted.Perform(std::forward_as_tuple(
  891. std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
  892. };
  893. }
  894. };
  895. template <typename... Actions>
  896. struct DoAllAction {
  897. private:
  898. template <typename T>
  899. using NonFinalType =
  900. typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
  901. template <typename ActionT, size_t... I>
  902. std::vector<ActionT> Convert(IndexSequence<I...>) const {
  903. return {ActionT(std::get<I>(actions))...};
  904. }
  905. public:
  906. std::tuple<Actions...> actions;
  907. template <typename R, typename... Args>
  908. operator Action<R(Args...)>() const { // NOLINT
  909. struct Op {
  910. std::vector<Action<void(NonFinalType<Args>...)>> converted;
  911. Action<R(Args...)> last;
  912. R operator()(Args... args) const {
  913. auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
  914. for (auto& a : converted) {
  915. a.Perform(tuple_args);
  916. }
  917. return last.Perform(std::move(tuple_args));
  918. }
  919. };
  920. return Op{Convert<Action<void(NonFinalType<Args>...)>>(
  921. MakeIndexSequence<sizeof...(Actions) - 1>()),
  922. std::get<sizeof...(Actions) - 1>(actions)};
  923. }
  924. };
  925. template <typename T, typename... Params>
  926. struct ReturnNewAction {
  927. T* operator()() const {
  928. return internal::Apply(
  929. [](const Params&... unpacked_params) {
  930. return new T(unpacked_params...);
  931. },
  932. params);
  933. }
  934. std::tuple<Params...> params;
  935. };
  936. template <size_t k>
  937. struct ReturnArgAction {
  938. template <typename... Args>
  939. auto operator()(const Args&... args) const ->
  940. typename std::tuple_element<k, std::tuple<Args...>>::type {
  941. return std::get<k>(std::tie(args...));
  942. }
  943. };
  944. template <size_t k, typename Ptr>
  945. struct SaveArgAction {
  946. Ptr pointer;
  947. template <typename... Args>
  948. void operator()(const Args&... args) const {
  949. *pointer = std::get<k>(std::tie(args...));
  950. }
  951. };
  952. template <size_t k, typename Ptr>
  953. struct SaveArgPointeeAction {
  954. Ptr pointer;
  955. template <typename... Args>
  956. void operator()(const Args&... args) const {
  957. *pointer = *std::get<k>(std::tie(args...));
  958. }
  959. };
  960. template <size_t k, typename T>
  961. struct SetArgRefereeAction {
  962. T value;
  963. template <typename... Args>
  964. void operator()(Args&&... args) const {
  965. using argk_type =
  966. typename ::std::tuple_element<k, std::tuple<Args...>>::type;
  967. static_assert(std::is_lvalue_reference<argk_type>::value,
  968. "Argument must be a reference type.");
  969. std::get<k>(std::tie(args...)) = value;
  970. }
  971. };
  972. template <size_t k, typename I1, typename I2>
  973. struct SetArrayArgumentAction {
  974. I1 first;
  975. I2 last;
  976. template <typename... Args>
  977. void operator()(const Args&... args) const {
  978. auto value = std::get<k>(std::tie(args...));
  979. for (auto it = first; it != last; ++it, (void)++value) {
  980. *value = *it;
  981. }
  982. }
  983. };
  984. template <size_t k>
  985. struct DeleteArgAction {
  986. template <typename... Args>
  987. void operator()(const Args&... args) const {
  988. delete std::get<k>(std::tie(args...));
  989. }
  990. };
  991. template <typename Ptr>
  992. struct ReturnPointeeAction {
  993. Ptr pointer;
  994. template <typename... Args>
  995. auto operator()(const Args&...) const -> decltype(*pointer) {
  996. return *pointer;
  997. }
  998. };
  999. #if GTEST_HAS_EXCEPTIONS
  1000. template <typename T>
  1001. struct ThrowAction {
  1002. T exception;
  1003. // We use a conversion operator to adapt to any return type.
  1004. template <typename R, typename... Args>
  1005. operator Action<R(Args...)>() const { // NOLINT
  1006. T copy = exception;
  1007. return [copy](Args...) -> R { throw copy; };
  1008. }
  1009. };
  1010. #endif // GTEST_HAS_EXCEPTIONS
  1011. } // namespace internal
  1012. // An Unused object can be implicitly constructed from ANY value.
  1013. // This is handy when defining actions that ignore some or all of the
  1014. // mock function arguments. For example, given
  1015. //
  1016. // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
  1017. // MOCK_METHOD3(Bar, double(int index, double x, double y));
  1018. //
  1019. // instead of
  1020. //
  1021. // double DistanceToOriginWithLabel(const string& label, double x, double y) {
  1022. // return sqrt(x*x + y*y);
  1023. // }
  1024. // double DistanceToOriginWithIndex(int index, double x, double y) {
  1025. // return sqrt(x*x + y*y);
  1026. // }
  1027. // ...
  1028. // EXPECT_CALL(mock, Foo("abc", _, _))
  1029. // .WillOnce(Invoke(DistanceToOriginWithLabel));
  1030. // EXPECT_CALL(mock, Bar(5, _, _))
  1031. // .WillOnce(Invoke(DistanceToOriginWithIndex));
  1032. //
  1033. // you could write
  1034. //
  1035. // // We can declare any uninteresting argument as Unused.
  1036. // double DistanceToOrigin(Unused, double x, double y) {
  1037. // return sqrt(x*x + y*y);
  1038. // }
  1039. // ...
  1040. // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
  1041. // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
  1042. typedef internal::IgnoredValue Unused;
  1043. // Creates an action that does actions a1, a2, ..., sequentially in
  1044. // each invocation. All but the last action will have a readonly view of the
  1045. // arguments.
  1046. template <typename... Action>
  1047. internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
  1048. Action&&... action) {
  1049. return {std::forward_as_tuple(std::forward<Action>(action)...)};
  1050. }
  1051. // WithArg<k>(an_action) creates an action that passes the k-th
  1052. // (0-based) argument of the mock function to an_action and performs
  1053. // it. It adapts an action accepting one argument to one that accepts
  1054. // multiple arguments. For convenience, we also provide
  1055. // WithArgs<k>(an_action) (defined below) as a synonym.
  1056. template <size_t k, typename InnerAction>
  1057. internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
  1058. WithArg(InnerAction&& action) {
  1059. return {std::forward<InnerAction>(action)};
  1060. }
  1061. // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
  1062. // the selected arguments of the mock function to an_action and
  1063. // performs it. It serves as an adaptor between actions with
  1064. // different argument lists.
  1065. template <size_t k, size_t... ks, typename InnerAction>
  1066. internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
  1067. WithArgs(InnerAction&& action) {
  1068. return {std::forward<InnerAction>(action)};
  1069. }
  1070. // WithoutArgs(inner_action) can be used in a mock function with a
  1071. // non-empty argument list to perform inner_action, which takes no
  1072. // argument. In other words, it adapts an action accepting no
  1073. // argument to one that accepts (and ignores) arguments.
  1074. template <typename InnerAction>
  1075. internal::WithArgsAction<typename std::decay<InnerAction>::type>
  1076. WithoutArgs(InnerAction&& action) {
  1077. return {std::forward<InnerAction>(action)};
  1078. }
  1079. // Creates an action that returns 'value'. 'value' is passed by value
  1080. // instead of const reference - otherwise Return("string literal")
  1081. // will trigger a compiler error about using array as initializer.
  1082. template <typename R>
  1083. internal::ReturnAction<R> Return(R value) {
  1084. return internal::ReturnAction<R>(std::move(value));
  1085. }
  1086. // Creates an action that returns NULL.
  1087. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
  1088. return MakePolymorphicAction(internal::ReturnNullAction());
  1089. }
  1090. // Creates an action that returns from a void function.
  1091. inline PolymorphicAction<internal::ReturnVoidAction> Return() {
  1092. return MakePolymorphicAction(internal::ReturnVoidAction());
  1093. }
  1094. // Creates an action that returns the reference to a variable.
  1095. template <typename R>
  1096. inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
  1097. return internal::ReturnRefAction<R>(x);
  1098. }
  1099. // Prevent using ReturnRef on reference to temporary.
  1100. template <typename R, R* = nullptr>
  1101. internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
  1102. // Creates an action that returns the reference to a copy of the
  1103. // argument. The copy is created when the action is constructed and
  1104. // lives as long as the action.
  1105. template <typename R>
  1106. inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
  1107. return internal::ReturnRefOfCopyAction<R>(x);
  1108. }
  1109. // Modifies the parent action (a Return() action) to perform a move of the
  1110. // argument instead of a copy.
  1111. // Return(ByMove()) actions can only be executed once and will assert this
  1112. // invariant.
  1113. template <typename R>
  1114. internal::ByMoveWrapper<R> ByMove(R x) {
  1115. return internal::ByMoveWrapper<R>(std::move(x));
  1116. }
  1117. // Creates an action that returns an element of `vals`. Calling this action will
  1118. // repeatedly return the next value from `vals` until it reaches the end and
  1119. // will restart from the beginning.
  1120. template <typename T>
  1121. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
  1122. return internal::ReturnRoundRobinAction<T>(std::move(vals));
  1123. }
  1124. // Creates an action that returns an element of `vals`. Calling this action will
  1125. // repeatedly return the next value from `vals` until it reaches the end and
  1126. // will restart from the beginning.
  1127. template <typename T>
  1128. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
  1129. std::initializer_list<T> vals) {
  1130. return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
  1131. }
  1132. // Creates an action that does the default action for the give mock function.
  1133. inline internal::DoDefaultAction DoDefault() {
  1134. return internal::DoDefaultAction();
  1135. }
  1136. // Creates an action that sets the variable pointed by the N-th
  1137. // (0-based) function argument to 'value'.
  1138. template <size_t N, typename T>
  1139. internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
  1140. return {std::move(value)};
  1141. }
  1142. // The following version is DEPRECATED.
  1143. template <size_t N, typename T>
  1144. internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
  1145. return {std::move(value)};
  1146. }
  1147. // Creates an action that sets a pointer referent to a given value.
  1148. template <typename T1, typename T2>
  1149. PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
  1150. return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
  1151. }
  1152. #if !GTEST_OS_WINDOWS_MOBILE
  1153. // Creates an action that sets errno and returns the appropriate error.
  1154. template <typename T>
  1155. PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
  1156. SetErrnoAndReturn(int errval, T result) {
  1157. return MakePolymorphicAction(
  1158. internal::SetErrnoAndReturnAction<T>(errval, result));
  1159. }
  1160. #endif // !GTEST_OS_WINDOWS_MOBILE
  1161. // Various overloads for Invoke().
  1162. // Legacy function.
  1163. // Actions can now be implicitly constructed from callables. No need to create
  1164. // wrapper objects.
  1165. // This function exists for backwards compatibility.
  1166. template <typename FunctionImpl>
  1167. typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
  1168. return std::forward<FunctionImpl>(function_impl);
  1169. }
  1170. // Creates an action that invokes the given method on the given object
  1171. // with the mock function's arguments.
  1172. template <class Class, typename MethodPtr>
  1173. internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
  1174. MethodPtr method_ptr) {
  1175. return {obj_ptr, method_ptr};
  1176. }
  1177. // Creates an action that invokes 'function_impl' with no argument.
  1178. template <typename FunctionImpl>
  1179. internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
  1180. InvokeWithoutArgs(FunctionImpl function_impl) {
  1181. return {std::move(function_impl)};
  1182. }
  1183. // Creates an action that invokes the given method on the given object
  1184. // with no argument.
  1185. template <class Class, typename MethodPtr>
  1186. internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
  1187. Class* obj_ptr, MethodPtr method_ptr) {
  1188. return {obj_ptr, method_ptr};
  1189. }
  1190. // Creates an action that performs an_action and throws away its
  1191. // result. In other words, it changes the return type of an_action to
  1192. // void. an_action MUST NOT return void, or the code won't compile.
  1193. template <typename A>
  1194. inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
  1195. return internal::IgnoreResultAction<A>(an_action);
  1196. }
  1197. // Creates a reference wrapper for the given L-value. If necessary,
  1198. // you can explicitly specify the type of the reference. For example,
  1199. // suppose 'derived' is an object of type Derived, ByRef(derived)
  1200. // would wrap a Derived&. If you want to wrap a const Base& instead,
  1201. // where Base is a base class of Derived, just write:
  1202. //
  1203. // ByRef<const Base>(derived)
  1204. //
  1205. // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
  1206. // However, it may still be used for consistency with ByMove().
  1207. template <typename T>
  1208. inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
  1209. return ::std::reference_wrapper<T>(l_value);
  1210. }
  1211. // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
  1212. // instance of type T, constructed on the heap with constructor arguments
  1213. // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
  1214. template <typename T, typename... Params>
  1215. internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
  1216. Params&&... params) {
  1217. return {std::forward_as_tuple(std::forward<Params>(params)...)};
  1218. }
  1219. // Action ReturnArg<k>() returns the k-th argument of the mock function.
  1220. template <size_t k>
  1221. internal::ReturnArgAction<k> ReturnArg() {
  1222. return {};
  1223. }
  1224. // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
  1225. // mock function to *pointer.
  1226. template <size_t k, typename Ptr>
  1227. internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
  1228. return {pointer};
  1229. }
  1230. // Action SaveArgPointee<k>(pointer) saves the value pointed to
  1231. // by the k-th (0-based) argument of the mock function to *pointer.
  1232. template <size_t k, typename Ptr>
  1233. internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
  1234. return {pointer};
  1235. }
  1236. // Action SetArgReferee<k>(value) assigns 'value' to the variable
  1237. // referenced by the k-th (0-based) argument of the mock function.
  1238. template <size_t k, typename T>
  1239. internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
  1240. T&& value) {
  1241. return {std::forward<T>(value)};
  1242. }
  1243. // Action SetArrayArgument<k>(first, last) copies the elements in
  1244. // source range [first, last) to the array pointed to by the k-th
  1245. // (0-based) argument, which can be either a pointer or an
  1246. // iterator. The action does not take ownership of the elements in the
  1247. // source range.
  1248. template <size_t k, typename I1, typename I2>
  1249. internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
  1250. I2 last) {
  1251. return {first, last};
  1252. }
  1253. // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
  1254. // function.
  1255. template <size_t k>
  1256. internal::DeleteArgAction<k> DeleteArg() {
  1257. return {};
  1258. }
  1259. // This action returns the value pointed to by 'pointer'.
  1260. template <typename Ptr>
  1261. internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
  1262. return {pointer};
  1263. }
  1264. // Action Throw(exception) can be used in a mock function of any type
  1265. // to throw the given exception. Any copyable value can be thrown.
  1266. #if GTEST_HAS_EXCEPTIONS
  1267. template <typename T>
  1268. internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
  1269. return {std::forward<T>(exception)};
  1270. }
  1271. #endif // GTEST_HAS_EXCEPTIONS
  1272. namespace internal {
  1273. // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
  1274. // defines an action that can be used in a mock function. Typically,
  1275. // these actions only care about a subset of the arguments of the mock
  1276. // function. For example, if such an action only uses the second
  1277. // argument, it can be used in any mock function that takes >= 2
  1278. // arguments where the type of the second argument is compatible.
  1279. //
  1280. // Therefore, the action implementation must be prepared to take more
  1281. // arguments than it needs. The ExcessiveArg type is used to
  1282. // represent those excessive arguments. In order to keep the compiler
  1283. // error messages tractable, we define it in the testing namespace
  1284. // instead of testing::internal. However, this is an INTERNAL TYPE
  1285. // and subject to change without notice, so a user MUST NOT USE THIS
  1286. // TYPE DIRECTLY.
  1287. struct ExcessiveArg {};
  1288. // Builds an implementation of an Action<> for some particular signature, using
  1289. // a class defined by an ACTION* macro.
  1290. template <typename F, typename Impl> struct ActionImpl;
  1291. template <typename Impl>
  1292. struct ImplBase {
  1293. struct Holder {
  1294. // Allows each copy of the Action<> to get to the Impl.
  1295. explicit operator const Impl&() const { return *ptr; }
  1296. std::shared_ptr<Impl> ptr;
  1297. };
  1298. using type = typename std::conditional<std::is_constructible<Impl>::value,
  1299. Impl, Holder>::type;
  1300. };
  1301. template <typename R, typename... Args, typename Impl>
  1302. struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
  1303. using Base = typename ImplBase<Impl>::type;
  1304. using function_type = R(Args...);
  1305. using args_type = std::tuple<Args...>;
  1306. ActionImpl() = default; // Only defined if appropriate for Base.
  1307. explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} { }
  1308. R operator()(Args&&... arg) const {
  1309. static constexpr size_t kMaxArgs =
  1310. sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
  1311. return Apply(MakeIndexSequence<kMaxArgs>{},
  1312. MakeIndexSequence<10 - kMaxArgs>{},
  1313. args_type{std::forward<Args>(arg)...});
  1314. }
  1315. template <std::size_t... arg_id, std::size_t... excess_id>
  1316. R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
  1317. const args_type& args) const {
  1318. // Impl need not be specific to the signature of action being implemented;
  1319. // only the implementing function body needs to have all of the specific
  1320. // types instantiated. Up to 10 of the args that are provided by the
  1321. // args_type get passed, followed by a dummy of unspecified type for the
  1322. // remainder up to 10 explicit args.
  1323. static constexpr ExcessiveArg kExcessArg{};
  1324. return static_cast<const Impl&>(*this).template gmock_PerformImpl<
  1325. /*function_type=*/function_type, /*return_type=*/R,
  1326. /*args_type=*/args_type,
  1327. /*argN_type=*/typename std::tuple_element<arg_id, args_type>::type...>(
  1328. /*args=*/args, std::get<arg_id>(args)...,
  1329. ((void)excess_id, kExcessArg)...);
  1330. }
  1331. };
  1332. // Stores a default-constructed Impl as part of the Action<>'s
  1333. // std::function<>. The Impl should be trivial to copy.
  1334. template <typename F, typename Impl>
  1335. ::testing::Action<F> MakeAction() {
  1336. return ::testing::Action<F>(ActionImpl<F, Impl>());
  1337. }
  1338. // Stores just the one given instance of Impl.
  1339. template <typename F, typename Impl>
  1340. ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
  1341. return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
  1342. }
  1343. #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
  1344. , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
  1345. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
  1346. const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
  1347. GMOCK_INTERNAL_ARG_UNUSED, , 10)
  1348. #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
  1349. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
  1350. const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
  1351. #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
  1352. #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
  1353. GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
  1354. #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
  1355. #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
  1356. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
  1357. #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
  1358. #define GMOCK_ACTION_TYPE_PARAMS_(params) \
  1359. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
  1360. #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
  1361. , param##_type gmock_p##i
  1362. #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
  1363. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
  1364. #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
  1365. , std::forward<param##_type>(gmock_p##i)
  1366. #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
  1367. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
  1368. #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
  1369. , param(::std::forward<param##_type>(gmock_p##i))
  1370. #define GMOCK_ACTION_INIT_PARAMS_(params) \
  1371. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
  1372. #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
  1373. #define GMOCK_ACTION_FIELD_PARAMS_(params) \
  1374. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
  1375. #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
  1376. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1377. class full_name { \
  1378. public: \
  1379. explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
  1380. : impl_(std::make_shared<gmock_Impl>( \
  1381. GMOCK_ACTION_GVALUE_PARAMS_(params))) { } \
  1382. full_name(const full_name&) = default; \
  1383. full_name(full_name&&) noexcept = default; \
  1384. template <typename F> \
  1385. operator ::testing::Action<F>() const { \
  1386. return ::testing::internal::MakeAction<F>(impl_); \
  1387. } \
  1388. private: \
  1389. class gmock_Impl { \
  1390. public: \
  1391. explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
  1392. : GMOCK_ACTION_INIT_PARAMS_(params) {} \
  1393. template <typename function_type, typename return_type, \
  1394. typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1395. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  1396. GMOCK_ACTION_FIELD_PARAMS_(params) \
  1397. }; \
  1398. std::shared_ptr<const gmock_Impl> impl_; \
  1399. }; \
  1400. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1401. inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
  1402. GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
  1403. return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
  1404. GMOCK_ACTION_GVALUE_PARAMS_(params)); \
  1405. } \
  1406. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1407. template <typename function_type, typename return_type, typename args_type, \
  1408. GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1409. return_type full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl:: \
  1410. gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  1411. } // namespace internal
  1412. // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
  1413. #define ACTION(name) \
  1414. class name##Action { \
  1415. public: \
  1416. explicit name##Action() noexcept {} \
  1417. name##Action(const name##Action&) noexcept {} \
  1418. template <typename F> \
  1419. operator ::testing::Action<F>() const { \
  1420. return ::testing::internal::MakeAction<F, gmock_Impl>(); \
  1421. } \
  1422. private: \
  1423. class gmock_Impl { \
  1424. public: \
  1425. template <typename function_type, typename return_type, \
  1426. typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1427. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  1428. }; \
  1429. }; \
  1430. inline name##Action name() GTEST_MUST_USE_RESULT_; \
  1431. inline name##Action name() { return name##Action(); } \
  1432. template <typename function_type, typename return_type, typename args_type, \
  1433. GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1434. return_type name##Action::gmock_Impl::gmock_PerformImpl( \
  1435. GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  1436. #define ACTION_P(name, ...) \
  1437. GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
  1438. #define ACTION_P2(name, ...) \
  1439. GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
  1440. #define ACTION_P3(name, ...) \
  1441. GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
  1442. #define ACTION_P4(name, ...) \
  1443. GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
  1444. #define ACTION_P5(name, ...) \
  1445. GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
  1446. #define ACTION_P6(name, ...) \
  1447. GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
  1448. #define ACTION_P7(name, ...) \
  1449. GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
  1450. #define ACTION_P8(name, ...) \
  1451. GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
  1452. #define ACTION_P9(name, ...) \
  1453. GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
  1454. #define ACTION_P10(name, ...) \
  1455. GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
  1456. } // namespace testing
  1457. #ifdef _MSC_VER
  1458. # pragma warning(pop)
  1459. #endif
  1460. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_