/testlibs/gmock/include/gmock/gmock-actions.h

https://github.com/deltaforge/nebu-app-hadoop · C Header · 1076 lines · 561 code · 164 blank · 351 comment · 9 complexity · 5a9106df9a0cd144ccc52635201315c8 MD5 · raw file

  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. // Google Mock - a framework for writing C++ mock classes.
  32. //
  33. // This file implements some commonly used actions.
  34. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  35. #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  36. #include <algorithm>
  37. #include <string>
  38. #ifndef _WIN32_WCE
  39. # include <errno.h>
  40. #endif
  41. #include "gmock/internal/gmock-internal-utils.h"
  42. #include "gmock/internal/gmock-port.h"
  43. namespace testing {
  44. // To implement an action Foo, define:
  45. // 1. a class FooAction that implements the ActionInterface interface, and
  46. // 2. a factory function that creates an Action object from a
  47. // const FooAction*.
  48. //
  49. // The two-level delegation design follows that of Matcher, providing
  50. // consistency for extension developers. It also eases ownership
  51. // management as Action objects can now be copied like plain values.
  52. namespace internal {
  53. template <typename F1, typename F2>
  54. class ActionAdaptor;
  55. // BuiltInDefaultValue<T>::Get() returns the "built-in" default
  56. // value for type T, which is NULL when T is a pointer type, 0 when T
  57. // is a numeric type, false when T is bool, or "" when T is string or
  58. // std::string. For any other type T, this value is undefined and the
  59. // function will abort the process.
  60. template <typename T>
  61. class BuiltInDefaultValue {
  62. public:
  63. // This function returns true iff type T has a built-in default value.
  64. static bool Exists() { return false; }
  65. static T Get() {
  66. Assert(false, __FILE__, __LINE__,
  67. "Default action undefined for the function return type.");
  68. return internal::Invalid<T>();
  69. // The above statement will never be reached, but is required in
  70. // order for this function to compile.
  71. }
  72. };
  73. // This partial specialization says that we use the same built-in
  74. // default value for T and const T.
  75. template <typename T>
  76. class BuiltInDefaultValue<const T> {
  77. public:
  78. static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
  79. static T Get() { return BuiltInDefaultValue<T>::Get(); }
  80. };
  81. // This partial specialization defines the default values for pointer
  82. // types.
  83. template <typename T>
  84. class BuiltInDefaultValue<T*> {
  85. public:
  86. static bool Exists() { return true; }
  87. static T* Get() { return NULL; }
  88. };
  89. // The following specializations define the default values for
  90. // specific types we care about.
  91. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
  92. template <> \
  93. class BuiltInDefaultValue<type> { \
  94. public: \
  95. static bool Exists() { return true; } \
  96. static type Get() { return value; } \
  97. }
  98. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
  99. #if GTEST_HAS_GLOBAL_STRING
  100. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
  101. #endif // GTEST_HAS_GLOBAL_STRING
  102. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
  103. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
  104. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
  105. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
  106. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
  107. // There's no need for a default action for signed wchar_t, as that
  108. // type is the same as wchar_t for gcc, and invalid for MSVC.
  109. //
  110. // There's also no need for a default action for unsigned wchar_t, as
  111. // that type is the same as unsigned int for gcc, and invalid for
  112. // MSVC.
  113. #if GMOCK_WCHAR_T_IS_NATIVE_
  114. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
  115. #endif
  116. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
  117. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
  118. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
  119. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
  120. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
  121. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
  122. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
  123. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
  124. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
  125. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
  126. #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
  127. } // namespace internal
  128. // When an unexpected function call is encountered, Google Mock will
  129. // let it return a default value if the user has specified one for its
  130. // return type, or if the return type has a built-in default value;
  131. // otherwise Google Mock won't know what value to return and will have
  132. // to abort the process.
  133. //
  134. // The DefaultValue<T> class allows a user to specify the
  135. // default value for a type T that is both copyable and publicly
  136. // destructible (i.e. anything that can be used as a function return
  137. // type). The usage is:
  138. //
  139. // // Sets the default value for type T to be foo.
  140. // DefaultValue<T>::Set(foo);
  141. template <typename T>
  142. class DefaultValue {
  143. public:
  144. // Sets the default value for type T; requires T to be
  145. // copy-constructable and have a public destructor.
  146. static void Set(T x) {
  147. delete value_;
  148. value_ = new T(x);
  149. }
  150. // Unsets the default value for type T.
  151. static void Clear() {
  152. delete value_;
  153. value_ = NULL;
  154. }
  155. // Returns true iff the user has set the default value for type T.
  156. static bool IsSet() { return value_ != NULL; }
  157. // Returns true if T has a default return value set by the user or there
  158. // exists a built-in default value.
  159. static bool Exists() {
  160. return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
  161. }
  162. // Returns the default value for type T if the user has set one;
  163. // otherwise returns the built-in default value if there is one;
  164. // otherwise aborts the process.
  165. static T Get() {
  166. return value_ == NULL ?
  167. internal::BuiltInDefaultValue<T>::Get() : *value_;
  168. }
  169. private:
  170. static const T* value_;
  171. };
  172. // This partial specialization allows a user to set default values for
  173. // reference types.
  174. template <typename T>
  175. class DefaultValue<T&> {
  176. public:
  177. // Sets the default value for type T&.
  178. static void Set(T& x) { // NOLINT
  179. address_ = &x;
  180. }
  181. // Unsets the default value for type T&.
  182. static void Clear() {
  183. address_ = NULL;
  184. }
  185. // Returns true iff the user has set the default value for type T&.
  186. static bool IsSet() { return address_ != NULL; }
  187. // Returns true if T has a default return value set by the user or there
  188. // exists a built-in default value.
  189. static bool Exists() {
  190. return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
  191. }
  192. // Returns the default value for type T& if the user has set one;
  193. // otherwise returns the built-in default value if there is one;
  194. // otherwise aborts the process.
  195. static T& Get() {
  196. return address_ == NULL ?
  197. internal::BuiltInDefaultValue<T&>::Get() : *address_;
  198. }
  199. private:
  200. static T* address_;
  201. };
  202. // This specialization allows DefaultValue<void>::Get() to
  203. // compile.
  204. template <>
  205. class DefaultValue<void> {
  206. public:
  207. static bool Exists() { return true; }
  208. static void Get() {}
  209. };
  210. // Points to the user-set default value for type T.
  211. template <typename T>
  212. const T* DefaultValue<T>::value_ = NULL;
  213. // Points to the user-set default value for type T&.
  214. template <typename T>
  215. T* DefaultValue<T&>::address_ = NULL;
  216. // Implement this interface to define an action for function type F.
  217. template <typename F>
  218. class ActionInterface {
  219. public:
  220. typedef typename internal::Function<F>::Result Result;
  221. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  222. ActionInterface() {}
  223. virtual ~ActionInterface() {}
  224. // Performs the action. This method is not const, as in general an
  225. // action can have side effects and be stateful. For example, a
  226. // get-the-next-element-from-the-collection action will need to
  227. // remember the current element.
  228. virtual Result Perform(const ArgumentTuple& args) = 0;
  229. private:
  230. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
  231. };
  232. // An Action<F> is a copyable and IMMUTABLE (except by assignment)
  233. // object that represents an action to be taken when a mock function
  234. // of type F is called. The implementation of Action<T> is just a
  235. // linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
  236. // Don't inherit from Action!
  237. //
  238. // You can view an object implementing ActionInterface<F> as a
  239. // concrete action (including its current state), and an Action<F>
  240. // object as a handle to it.
  241. template <typename F>
  242. class Action {
  243. public:
  244. typedef typename internal::Function<F>::Result Result;
  245. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  246. // Constructs a null Action. Needed for storing Action objects in
  247. // STL containers.
  248. Action() : impl_(NULL) {}
  249. // Constructs an Action from its implementation. A NULL impl is
  250. // used to represent the "do-default" action.
  251. explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
  252. // Copy constructor.
  253. Action(const Action& action) : impl_(action.impl_) {}
  254. // This constructor allows us to turn an Action<Func> object into an
  255. // Action<F>, as long as F's arguments can be implicitly converted
  256. // to Func's and Func's return type can be implicitly converted to
  257. // F's.
  258. template <typename Func>
  259. explicit Action(const Action<Func>& action);
  260. // Returns true iff this is the DoDefault() action.
  261. bool IsDoDefault() const { return impl_.get() == NULL; }
  262. // Performs the action. Note that this method is const even though
  263. // the corresponding method in ActionInterface is not. The reason
  264. // is that a const Action<F> means that it cannot be re-bound to
  265. // another concrete action, not that the concrete action it binds to
  266. // cannot change state. (Think of the difference between a const
  267. // pointer and a pointer to const.)
  268. Result Perform(const ArgumentTuple& args) const {
  269. internal::Assert(
  270. !IsDoDefault(), __FILE__, __LINE__,
  271. "You are using DoDefault() inside a composite action like "
  272. "DoAll() or WithArgs(). This is not supported for technical "
  273. "reasons. Please instead spell out the default action, or "
  274. "assign the default action to an Action variable and use "
  275. "the variable in various places.");
  276. return impl_->Perform(args);
  277. }
  278. private:
  279. template <typename F1, typename F2>
  280. friend class internal::ActionAdaptor;
  281. internal::linked_ptr<ActionInterface<F> > impl_;
  282. };
  283. // The PolymorphicAction class template makes it easy to implement a
  284. // polymorphic action (i.e. an action that can be used in mock
  285. // functions of than one type, e.g. Return()).
  286. //
  287. // To define a polymorphic action, a user first provides a COPYABLE
  288. // implementation class that has a Perform() method template:
  289. //
  290. // class FooAction {
  291. // public:
  292. // template <typename Result, typename ArgumentTuple>
  293. // Result Perform(const ArgumentTuple& args) const {
  294. // // Processes the arguments and returns a result, using
  295. // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
  296. // }
  297. // ...
  298. // };
  299. //
  300. // Then the user creates the polymorphic action using
  301. // MakePolymorphicAction(object) where object has type FooAction. See
  302. // the definition of Return(void) and SetArgumentPointee<N>(value) for
  303. // complete examples.
  304. template <typename Impl>
  305. class PolymorphicAction {
  306. public:
  307. explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
  308. template <typename F>
  309. operator Action<F>() const {
  310. return Action<F>(new MonomorphicImpl<F>(impl_));
  311. }
  312. private:
  313. template <typename F>
  314. class MonomorphicImpl : public ActionInterface<F> {
  315. public:
  316. typedef typename internal::Function<F>::Result Result;
  317. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  318. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  319. virtual Result Perform(const ArgumentTuple& args) {
  320. return impl_.template Perform<Result>(args);
  321. }
  322. private:
  323. Impl impl_;
  324. GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
  325. };
  326. Impl impl_;
  327. GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
  328. };
  329. // Creates an Action from its implementation and returns it. The
  330. // created Action object owns the implementation.
  331. template <typename F>
  332. Action<F> MakeAction(ActionInterface<F>* impl) {
  333. return Action<F>(impl);
  334. }
  335. // Creates a polymorphic action from its implementation. This is
  336. // easier to use than the PolymorphicAction<Impl> constructor as it
  337. // doesn't require you to explicitly write the template argument, e.g.
  338. //
  339. // MakePolymorphicAction(foo);
  340. // vs
  341. // PolymorphicAction<TypeOfFoo>(foo);
  342. template <typename Impl>
  343. inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
  344. return PolymorphicAction<Impl>(impl);
  345. }
  346. namespace internal {
  347. // Allows an Action<F2> object to pose as an Action<F1>, as long as F2
  348. // and F1 are compatible.
  349. template <typename F1, typename F2>
  350. class ActionAdaptor : public ActionInterface<F1> {
  351. public:
  352. typedef typename internal::Function<F1>::Result Result;
  353. typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
  354. explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
  355. virtual Result Perform(const ArgumentTuple& args) {
  356. return impl_->Perform(args);
  357. }
  358. private:
  359. const internal::linked_ptr<ActionInterface<F2> > impl_;
  360. GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
  361. };
  362. // Implements the polymorphic Return(x) action, which can be used in
  363. // any function that returns the type of x, regardless of the argument
  364. // types.
  365. //
  366. // Note: The value passed into Return must be converted into
  367. // Function<F>::Result when this action is cast to Action<F> rather than
  368. // when that action is performed. This is important in scenarios like
  369. //
  370. // MOCK_METHOD1(Method, T(U));
  371. // ...
  372. // {
  373. // Foo foo;
  374. // X x(&foo);
  375. // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
  376. // }
  377. //
  378. // In the example above the variable x holds reference to foo which leaves
  379. // scope and gets destroyed. If copying X just copies a reference to foo,
  380. // that copy will be left with a hanging reference. If conversion to T
  381. // makes a copy of foo, the above code is safe. To support that scenario, we
  382. // need to make sure that the type conversion happens inside the EXPECT_CALL
  383. // statement, and conversion of the result of Return to Action<T(U)> is a
  384. // good place for that.
  385. //
  386. template <typename R>
  387. class ReturnAction {
  388. public:
  389. // Constructs a ReturnAction object from the value to be returned.
  390. // 'value' is passed by value instead of by const reference in order
  391. // to allow Return("string literal") to compile.
  392. explicit ReturnAction(R value) : value_(value) {}
  393. // This template type conversion operator allows Return(x) to be
  394. // used in ANY function that returns x's type.
  395. template <typename F>
  396. operator Action<F>() const {
  397. // Assert statement belongs here because this is the best place to verify
  398. // conditions on F. It produces the clearest error messages
  399. // in most compilers.
  400. // Impl really belongs in this scope as a local class but can't
  401. // because MSVC produces duplicate symbols in different translation units
  402. // in this case. Until MS fixes that bug we put Impl into the class scope
  403. // and put the typedef both here (for use in assert statement) and
  404. // in the Impl class. But both definitions must be the same.
  405. typedef typename Function<F>::Result Result;
  406. GTEST_COMPILE_ASSERT_(
  407. !internal::is_reference<Result>::value,
  408. use_ReturnRef_instead_of_Return_to_return_a_reference);
  409. return Action<F>(new Impl<F>(value_));
  410. }
  411. private:
  412. // Implements the Return(x) action for a particular function type F.
  413. template <typename F>
  414. class Impl : public ActionInterface<F> {
  415. public:
  416. typedef typename Function<F>::Result Result;
  417. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  418. // The implicit cast is necessary when Result has more than one
  419. // single-argument constructor (e.g. Result is std::vector<int>) and R
  420. // has a type conversion operator template. In that case, value_(value)
  421. // won't compile as the compiler doesn't known which constructor of
  422. // Result to call. ImplicitCast_ forces the compiler to convert R to
  423. // Result without considering explicit constructors, thus resolving the
  424. // ambiguity. value_ is then initialized using its copy constructor.
  425. explicit Impl(R value)
  426. : value_(::testing::internal::ImplicitCast_<Result>(value)) {}
  427. virtual Result Perform(const ArgumentTuple&) { return value_; }
  428. private:
  429. GTEST_COMPILE_ASSERT_(!internal::is_reference<Result>::value,
  430. Result_cannot_be_a_reference_type);
  431. Result value_;
  432. GTEST_DISALLOW_ASSIGN_(Impl);
  433. };
  434. R value_;
  435. GTEST_DISALLOW_ASSIGN_(ReturnAction);
  436. };
  437. // Implements the ReturnNull() action.
  438. class ReturnNullAction {
  439. public:
  440. // Allows ReturnNull() to be used in any pointer-returning function.
  441. template <typename Result, typename ArgumentTuple>
  442. static Result Perform(const ArgumentTuple&) {
  443. GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
  444. ReturnNull_can_be_used_to_return_a_pointer_only);
  445. return NULL;
  446. }
  447. };
  448. // Implements the Return() action.
  449. class ReturnVoidAction {
  450. public:
  451. // Allows Return() to be used in any void-returning function.
  452. template <typename Result, typename ArgumentTuple>
  453. static void Perform(const ArgumentTuple&) {
  454. CompileAssertTypesEqual<void, Result>();
  455. }
  456. };
  457. // Implements the polymorphic ReturnRef(x) action, which can be used
  458. // in any function that returns a reference to the type of x,
  459. // regardless of the argument types.
  460. template <typename T>
  461. class ReturnRefAction {
  462. public:
  463. // Constructs a ReturnRefAction object from the reference to be returned.
  464. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
  465. // This template type conversion operator allows ReturnRef(x) to be
  466. // used in ANY function that returns a reference to x's type.
  467. template <typename F>
  468. operator Action<F>() const {
  469. typedef typename Function<F>::Result Result;
  470. // Asserts that the function return type is a reference. This
  471. // catches the user error of using ReturnRef(x) when Return(x)
  472. // should be used, and generates some helpful error message.
  473. GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value,
  474. use_Return_instead_of_ReturnRef_to_return_a_value);
  475. return Action<F>(new Impl<F>(ref_));
  476. }
  477. private:
  478. // Implements the ReturnRef(x) action for a particular function type F.
  479. template <typename F>
  480. class Impl : public ActionInterface<F> {
  481. public:
  482. typedef typename Function<F>::Result Result;
  483. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  484. explicit Impl(T& ref) : ref_(ref) {} // NOLINT
  485. virtual Result Perform(const ArgumentTuple&) {
  486. return ref_;
  487. }
  488. private:
  489. T& ref_;
  490. GTEST_DISALLOW_ASSIGN_(Impl);
  491. };
  492. T& ref_;
  493. GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
  494. };
  495. // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
  496. // used in any function that returns a reference to the type of x,
  497. // regardless of the argument types.
  498. template <typename T>
  499. class ReturnRefOfCopyAction {
  500. public:
  501. // Constructs a ReturnRefOfCopyAction object from the reference to
  502. // be returned.
  503. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
  504. // This template type conversion operator allows ReturnRefOfCopy(x) to be
  505. // used in ANY function that returns a reference to x's type.
  506. template <typename F>
  507. operator Action<F>() const {
  508. typedef typename Function<F>::Result Result;
  509. // Asserts that the function return type is a reference. This
  510. // catches the user error of using ReturnRefOfCopy(x) when Return(x)
  511. // should be used, and generates some helpful error message.
  512. GTEST_COMPILE_ASSERT_(
  513. internal::is_reference<Result>::value,
  514. use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
  515. return Action<F>(new Impl<F>(value_));
  516. }
  517. private:
  518. // Implements the ReturnRefOfCopy(x) action for a particular function type F.
  519. template <typename F>
  520. class Impl : public ActionInterface<F> {
  521. public:
  522. typedef typename Function<F>::Result Result;
  523. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  524. explicit Impl(const T& value) : value_(value) {} // NOLINT
  525. virtual Result Perform(const ArgumentTuple&) {
  526. return value_;
  527. }
  528. private:
  529. T value_;
  530. GTEST_DISALLOW_ASSIGN_(Impl);
  531. };
  532. const T value_;
  533. GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
  534. };
  535. // Implements the polymorphic DoDefault() action.
  536. class DoDefaultAction {
  537. public:
  538. // This template type conversion operator allows DoDefault() to be
  539. // used in any function.
  540. template <typename F>
  541. operator Action<F>() const { return Action<F>(NULL); }
  542. };
  543. // Implements the Assign action to set a given pointer referent to a
  544. // particular value.
  545. template <typename T1, typename T2>
  546. class AssignAction {
  547. public:
  548. AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
  549. template <typename Result, typename ArgumentTuple>
  550. void Perform(const ArgumentTuple& /* args */) const {
  551. *ptr_ = value_;
  552. }
  553. private:
  554. T1* const ptr_;
  555. const T2 value_;
  556. GTEST_DISALLOW_ASSIGN_(AssignAction);
  557. };
  558. #if !GTEST_OS_WINDOWS_MOBILE
  559. // Implements the SetErrnoAndReturn action to simulate return from
  560. // various system calls and libc functions.
  561. template <typename T>
  562. class SetErrnoAndReturnAction {
  563. public:
  564. SetErrnoAndReturnAction(int errno_value, T result)
  565. : errno_(errno_value),
  566. result_(result) {}
  567. template <typename Result, typename ArgumentTuple>
  568. Result Perform(const ArgumentTuple& /* args */) const {
  569. errno = errno_;
  570. return result_;
  571. }
  572. private:
  573. const int errno_;
  574. const T result_;
  575. GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
  576. };
  577. #endif // !GTEST_OS_WINDOWS_MOBILE
  578. // Implements the SetArgumentPointee<N>(x) action for any function
  579. // whose N-th argument (0-based) is a pointer to x's type. The
  580. // template parameter kIsProto is true iff type A is ProtocolMessage,
  581. // proto2::Message, or a sub-class of those.
  582. template <size_t N, typename A, bool kIsProto>
  583. class SetArgumentPointeeAction {
  584. public:
  585. // Constructs an action that sets the variable pointed to by the
  586. // N-th function argument to 'value'.
  587. explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
  588. template <typename Result, typename ArgumentTuple>
  589. void Perform(const ArgumentTuple& args) const {
  590. CompileAssertTypesEqual<void, Result>();
  591. *::std::tr1::get<N>(args) = value_;
  592. }
  593. private:
  594. const A value_;
  595. GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
  596. };
  597. template <size_t N, typename Proto>
  598. class SetArgumentPointeeAction<N, Proto, true> {
  599. public:
  600. // Constructs an action that sets the variable pointed to by the
  601. // N-th function argument to 'proto'. Both ProtocolMessage and
  602. // proto2::Message have the CopyFrom() method, so the same
  603. // implementation works for both.
  604. explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
  605. proto_->CopyFrom(proto);
  606. }
  607. template <typename Result, typename ArgumentTuple>
  608. void Perform(const ArgumentTuple& args) const {
  609. CompileAssertTypesEqual<void, Result>();
  610. ::std::tr1::get<N>(args)->CopyFrom(*proto_);
  611. }
  612. private:
  613. const internal::linked_ptr<Proto> proto_;
  614. GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
  615. };
  616. // Implements the InvokeWithoutArgs(f) action. The template argument
  617. // FunctionImpl is the implementation type of f, which can be either a
  618. // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
  619. // Action<F> as long as f's type is compatible with F (i.e. f can be
  620. // assigned to a tr1::function<F>).
  621. template <typename FunctionImpl>
  622. class InvokeWithoutArgsAction {
  623. public:
  624. // The c'tor makes a copy of function_impl (either a function
  625. // pointer or a functor).
  626. explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
  627. : function_impl_(function_impl) {}
  628. // Allows InvokeWithoutArgs(f) to be used as any action whose type is
  629. // compatible with f.
  630. template <typename Result, typename ArgumentTuple>
  631. Result Perform(const ArgumentTuple&) { return function_impl_(); }
  632. private:
  633. FunctionImpl function_impl_;
  634. GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction);
  635. };
  636. // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
  637. template <class Class, typename MethodPtr>
  638. class InvokeMethodWithoutArgsAction {
  639. public:
  640. InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
  641. : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
  642. template <typename Result, typename ArgumentTuple>
  643. Result Perform(const ArgumentTuple&) const {
  644. return (obj_ptr_->*method_ptr_)();
  645. }
  646. private:
  647. Class* const obj_ptr_;
  648. const MethodPtr method_ptr_;
  649. GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
  650. };
  651. // Implements the IgnoreResult(action) action.
  652. template <typename A>
  653. class IgnoreResultAction {
  654. public:
  655. explicit IgnoreResultAction(const A& action) : action_(action) {}
  656. template <typename F>
  657. operator Action<F>() const {
  658. // Assert statement belongs here because this is the best place to verify
  659. // conditions on F. It produces the clearest error messages
  660. // in most compilers.
  661. // Impl really belongs in this scope as a local class but can't
  662. // because MSVC produces duplicate symbols in different translation units
  663. // in this case. Until MS fixes that bug we put Impl into the class scope
  664. // and put the typedef both here (for use in assert statement) and
  665. // in the Impl class. But both definitions must be the same.
  666. typedef typename internal::Function<F>::Result Result;
  667. // Asserts at compile time that F returns void.
  668. CompileAssertTypesEqual<void, Result>();
  669. return Action<F>(new Impl<F>(action_));
  670. }
  671. private:
  672. template <typename F>
  673. class Impl : public ActionInterface<F> {
  674. public:
  675. typedef typename internal::Function<F>::Result Result;
  676. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  677. explicit Impl(const A& action) : action_(action) {}
  678. virtual void Perform(const ArgumentTuple& args) {
  679. // Performs the action and ignores its result.
  680. action_.Perform(args);
  681. }
  682. private:
  683. // Type OriginalFunction is the same as F except that its return
  684. // type is IgnoredValue.
  685. typedef typename internal::Function<F>::MakeResultIgnoredValue
  686. OriginalFunction;
  687. const Action<OriginalFunction> action_;
  688. GTEST_DISALLOW_ASSIGN_(Impl);
  689. };
  690. const A action_;
  691. GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
  692. };
  693. // A ReferenceWrapper<T> object represents a reference to type T,
  694. // which can be either const or not. It can be explicitly converted
  695. // from, and implicitly converted to, a T&. Unlike a reference,
  696. // ReferenceWrapper<T> can be copied and can survive template type
  697. // inference. This is used to support by-reference arguments in the
  698. // InvokeArgument<N>(...) action. The idea was from "reference
  699. // wrappers" in tr1, which we don't have in our source tree yet.
  700. template <typename T>
  701. class ReferenceWrapper {
  702. public:
  703. // Constructs a ReferenceWrapper<T> object from a T&.
  704. explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT
  705. // Allows a ReferenceWrapper<T> object to be implicitly converted to
  706. // a T&.
  707. operator T&() const { return *pointer_; }
  708. private:
  709. T* pointer_;
  710. };
  711. // Allows the expression ByRef(x) to be printed as a reference to x.
  712. template <typename T>
  713. void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) {
  714. T& value = ref;
  715. UniversalPrinter<T&>::Print(value, os);
  716. }
  717. // Does two actions sequentially. Used for implementing the DoAll(a1,
  718. // a2, ...) action.
  719. template <typename Action1, typename Action2>
  720. class DoBothAction {
  721. public:
  722. DoBothAction(Action1 action1, Action2 action2)
  723. : action1_(action1), action2_(action2) {}
  724. // This template type conversion operator allows DoAll(a1, ..., a_n)
  725. // to be used in ANY function of compatible type.
  726. template <typename F>
  727. operator Action<F>() const {
  728. return Action<F>(new Impl<F>(action1_, action2_));
  729. }
  730. private:
  731. // Implements the DoAll(...) action for a particular function type F.
  732. template <typename F>
  733. class Impl : public ActionInterface<F> {
  734. public:
  735. typedef typename Function<F>::Result Result;
  736. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  737. typedef typename Function<F>::MakeResultVoid VoidResult;
  738. Impl(const Action<VoidResult>& action1, const Action<F>& action2)
  739. : action1_(action1), action2_(action2) {}
  740. virtual Result Perform(const ArgumentTuple& args) {
  741. action1_.Perform(args);
  742. return action2_.Perform(args);
  743. }
  744. private:
  745. const Action<VoidResult> action1_;
  746. const Action<F> action2_;
  747. GTEST_DISALLOW_ASSIGN_(Impl);
  748. };
  749. Action1 action1_;
  750. Action2 action2_;
  751. GTEST_DISALLOW_ASSIGN_(DoBothAction);
  752. };
  753. } // namespace internal
  754. // An Unused object can be implicitly constructed from ANY value.
  755. // This is handy when defining actions that ignore some or all of the
  756. // mock function arguments. For example, given
  757. //
  758. // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
  759. // MOCK_METHOD3(Bar, double(int index, double x, double y));
  760. //
  761. // instead of
  762. //
  763. // double DistanceToOriginWithLabel(const string& label, double x, double y) {
  764. // return sqrt(x*x + y*y);
  765. // }
  766. // double DistanceToOriginWithIndex(int index, double x, double y) {
  767. // return sqrt(x*x + y*y);
  768. // }
  769. // ...
  770. // EXEPCT_CALL(mock, Foo("abc", _, _))
  771. // .WillOnce(Invoke(DistanceToOriginWithLabel));
  772. // EXEPCT_CALL(mock, Bar(5, _, _))
  773. // .WillOnce(Invoke(DistanceToOriginWithIndex));
  774. //
  775. // you could write
  776. //
  777. // // We can declare any uninteresting argument as Unused.
  778. // double DistanceToOrigin(Unused, double x, double y) {
  779. // return sqrt(x*x + y*y);
  780. // }
  781. // ...
  782. // EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
  783. // EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
  784. typedef internal::IgnoredValue Unused;
  785. // This constructor allows us to turn an Action<From> object into an
  786. // Action<To>, as long as To's arguments can be implicitly converted
  787. // to From's and From's return type cann be implicitly converted to
  788. // To's.
  789. template <typename To>
  790. template <typename From>
  791. Action<To>::Action(const Action<From>& from)
  792. : impl_(new internal::ActionAdaptor<To, From>(from)) {}
  793. // Creates an action that returns 'value'. 'value' is passed by value
  794. // instead of const reference - otherwise Return("string literal")
  795. // will trigger a compiler error about using array as initializer.
  796. template <typename R>
  797. internal::ReturnAction<R> Return(R value) {
  798. return internal::ReturnAction<R>(value);
  799. }
  800. // Creates an action that returns NULL.
  801. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
  802. return MakePolymorphicAction(internal::ReturnNullAction());
  803. }
  804. // Creates an action that returns from a void function.
  805. inline PolymorphicAction<internal::ReturnVoidAction> Return() {
  806. return MakePolymorphicAction(internal::ReturnVoidAction());
  807. }
  808. // Creates an action that returns the reference to a variable.
  809. template <typename R>
  810. inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
  811. return internal::ReturnRefAction<R>(x);
  812. }
  813. // Creates an action that returns the reference to a copy of the
  814. // argument. The copy is created when the action is constructed and
  815. // lives as long as the action.
  816. template <typename R>
  817. inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
  818. return internal::ReturnRefOfCopyAction<R>(x);
  819. }
  820. // Creates an action that does the default action for the give mock function.
  821. inline internal::DoDefaultAction DoDefault() {
  822. return internal::DoDefaultAction();
  823. }
  824. // Creates an action that sets the variable pointed by the N-th
  825. // (0-based) function argument to 'value'.
  826. template <size_t N, typename T>
  827. PolymorphicAction<
  828. internal::SetArgumentPointeeAction<
  829. N, T, internal::IsAProtocolMessage<T>::value> >
  830. SetArgPointee(const T& x) {
  831. return MakePolymorphicAction(internal::SetArgumentPointeeAction<
  832. N, T, internal::IsAProtocolMessage<T>::value>(x));
  833. }
  834. #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
  835. // This overload allows SetArgPointee() to accept a string literal.
  836. // GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
  837. // this overload from the templated version and emit a compile error.
  838. template <size_t N>
  839. PolymorphicAction<
  840. internal::SetArgumentPointeeAction<N, const char*, false> >
  841. SetArgPointee(const char* p) {
  842. return MakePolymorphicAction(internal::SetArgumentPointeeAction<
  843. N, const char*, false>(p));
  844. }
  845. template <size_t N>
  846. PolymorphicAction<
  847. internal::SetArgumentPointeeAction<N, const wchar_t*, false> >
  848. SetArgPointee(const wchar_t* p) {
  849. return MakePolymorphicAction(internal::SetArgumentPointeeAction<
  850. N, const wchar_t*, false>(p));
  851. }
  852. #endif
  853. // The following version is DEPRECATED.
  854. template <size_t N, typename T>
  855. PolymorphicAction<
  856. internal::SetArgumentPointeeAction<
  857. N, T, internal::IsAProtocolMessage<T>::value> >
  858. SetArgumentPointee(const T& x) {
  859. return MakePolymorphicAction(internal::SetArgumentPointeeAction<
  860. N, T, internal::IsAProtocolMessage<T>::value>(x));
  861. }
  862. // Creates an action that sets a pointer referent to a given value.
  863. template <typename T1, typename T2>
  864. PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
  865. return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
  866. }
  867. #if !GTEST_OS_WINDOWS_MOBILE
  868. // Creates an action that sets errno and returns the appropriate error.
  869. template <typename T>
  870. PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
  871. SetErrnoAndReturn(int errval, T result) {
  872. return MakePolymorphicAction(
  873. internal::SetErrnoAndReturnAction<T>(errval, result));
  874. }
  875. #endif // !GTEST_OS_WINDOWS_MOBILE
  876. // Various overloads for InvokeWithoutArgs().
  877. // Creates an action that invokes 'function_impl' with no argument.
  878. template <typename FunctionImpl>
  879. PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
  880. InvokeWithoutArgs(FunctionImpl function_impl) {
  881. return MakePolymorphicAction(
  882. internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
  883. }
  884. // Creates an action that invokes the given method on the given object
  885. // with no argument.
  886. template <class Class, typename MethodPtr>
  887. PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
  888. InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
  889. return MakePolymorphicAction(
  890. internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
  891. obj_ptr, method_ptr));
  892. }
  893. // Creates an action that performs an_action and throws away its
  894. // result. In other words, it changes the return type of an_action to
  895. // void. an_action MUST NOT return void, or the code won't compile.
  896. template <typename A>
  897. inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
  898. return internal::IgnoreResultAction<A>(an_action);
  899. }
  900. // Creates a reference wrapper for the given L-value. If necessary,
  901. // you can explicitly specify the type of the reference. For example,
  902. // suppose 'derived' is an object of type Derived, ByRef(derived)
  903. // would wrap a Derived&. If you want to wrap a const Base& instead,
  904. // where Base is a base class of Derived, just write:
  905. //
  906. // ByRef<const Base>(derived)
  907. template <typename T>
  908. inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT
  909. return internal::ReferenceWrapper<T>(l_value);
  910. }
  911. } // namespace testing
  912. #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_