gmock-actions.h 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  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/googlemock/docs/cook_book.md
  125. // GOOGLETEST_CM0002 DO NOT DELETE
  126. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  127. #define GMOCK_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. public:
  402. typedef typename internal::Function<F>::Result Result;
  403. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  404. // Constructs a null Action. Needed for storing Action objects in
  405. // STL containers.
  406. Action() {}
  407. // Construct an Action from a specified callable.
  408. // This cannot take std::function directly, because then Action would not be
  409. // directly constructible from lambda (it would require two conversions).
  410. template <typename G,
  411. typename IsCompatibleFunctor =
  412. ::std::is_constructible<::std::function<F>, G>,
  413. typename IsNoArgsFunctor =
  414. ::std::is_constructible<::std::function<Result()>, G>,
  415. typename = typename ::std::enable_if<internal::disjunction<
  416. IsCompatibleFunctor, IsNoArgsFunctor>::value>::type>
  417. Action(G&& fun) { // NOLINT
  418. Init(::std::forward<G>(fun), IsCompatibleFunctor());
  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... Args, size_t... I>
  899. std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
  900. return {std::get<I>(actions)...};
  901. }
  902. public:
  903. std::tuple<Actions...> actions;
  904. template <typename R, typename... Args>
  905. operator Action<R(Args...)>() const { // NOLINT
  906. struct Op {
  907. std::vector<Action<void(Args...)>> converted;
  908. Action<R(Args...)> last;
  909. R operator()(Args... args) const {
  910. auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
  911. for (auto& a : converted) {
  912. a.Perform(tuple_args);
  913. }
  914. return last.Perform(tuple_args);
  915. }
  916. };
  917. return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
  918. std::get<sizeof...(Actions) - 1>(actions)};
  919. }
  920. };
  921. } // namespace internal
  922. // An Unused object can be implicitly constructed from ANY value.
  923. // This is handy when defining actions that ignore some or all of the
  924. // mock function arguments. For example, given
  925. //
  926. // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
  927. // MOCK_METHOD3(Bar, double(int index, double x, double y));
  928. //
  929. // instead of
  930. //
  931. // double DistanceToOriginWithLabel(const string& label, double x, double y) {
  932. // return sqrt(x*x + y*y);
  933. // }
  934. // double DistanceToOriginWithIndex(int index, double x, double y) {
  935. // return sqrt(x*x + y*y);
  936. // }
  937. // ...
  938. // EXPECT_CALL(mock, Foo("abc", _, _))
  939. // .WillOnce(Invoke(DistanceToOriginWithLabel));
  940. // EXPECT_CALL(mock, Bar(5, _, _))
  941. // .WillOnce(Invoke(DistanceToOriginWithIndex));
  942. //
  943. // you could write
  944. //
  945. // // We can declare any uninteresting argument as Unused.
  946. // double DistanceToOrigin(Unused, double x, double y) {
  947. // return sqrt(x*x + y*y);
  948. // }
  949. // ...
  950. // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
  951. // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
  952. typedef internal::IgnoredValue Unused;
  953. // Creates an action that does actions a1, a2, ..., sequentially in
  954. // each invocation.
  955. template <typename... Action>
  956. internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
  957. Action&&... action) {
  958. return {std::forward_as_tuple(std::forward<Action>(action)...)};
  959. }
  960. // WithArg<k>(an_action) creates an action that passes the k-th
  961. // (0-based) argument of the mock function to an_action and performs
  962. // it. It adapts an action accepting one argument to one that accepts
  963. // multiple arguments. For convenience, we also provide
  964. // WithArgs<k>(an_action) (defined below) as a synonym.
  965. template <size_t k, typename InnerAction>
  966. internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
  967. WithArg(InnerAction&& action) {
  968. return {std::forward<InnerAction>(action)};
  969. }
  970. // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
  971. // the selected arguments of the mock function to an_action and
  972. // performs it. It serves as an adaptor between actions with
  973. // different argument lists.
  974. template <size_t k, size_t... ks, typename InnerAction>
  975. internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
  976. WithArgs(InnerAction&& action) {
  977. return {std::forward<InnerAction>(action)};
  978. }
  979. // WithoutArgs(inner_action) can be used in a mock function with a
  980. // non-empty argument list to perform inner_action, which takes no
  981. // argument. In other words, it adapts an action accepting no
  982. // argument to one that accepts (and ignores) arguments.
  983. template <typename InnerAction>
  984. internal::WithArgsAction<typename std::decay<InnerAction>::type>
  985. WithoutArgs(InnerAction&& action) {
  986. return {std::forward<InnerAction>(action)};
  987. }
  988. // Creates an action that returns 'value'. 'value' is passed by value
  989. // instead of const reference - otherwise Return("string literal")
  990. // will trigger a compiler error about using array as initializer.
  991. template <typename R>
  992. internal::ReturnAction<R> Return(R value) {
  993. return internal::ReturnAction<R>(std::move(value));
  994. }
  995. // Creates an action that returns NULL.
  996. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
  997. return MakePolymorphicAction(internal::ReturnNullAction());
  998. }
  999. // Creates an action that returns from a void function.
  1000. inline PolymorphicAction<internal::ReturnVoidAction> Return() {
  1001. return MakePolymorphicAction(internal::ReturnVoidAction());
  1002. }
  1003. // Creates an action that returns the reference to a variable.
  1004. template <typename R>
  1005. inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
  1006. return internal::ReturnRefAction<R>(x);
  1007. }
  1008. // Prevent using ReturnRef on reference to temporary.
  1009. template <typename R, R* = nullptr>
  1010. internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
  1011. // Creates an action that returns the reference to a copy of the
  1012. // argument. The copy is created when the action is constructed and
  1013. // lives as long as the action.
  1014. template <typename R>
  1015. inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
  1016. return internal::ReturnRefOfCopyAction<R>(x);
  1017. }
  1018. // Modifies the parent action (a Return() action) to perform a move of the
  1019. // argument instead of a copy.
  1020. // Return(ByMove()) actions can only be executed once and will assert this
  1021. // invariant.
  1022. template <typename R>
  1023. internal::ByMoveWrapper<R> ByMove(R x) {
  1024. return internal::ByMoveWrapper<R>(std::move(x));
  1025. }
  1026. // Creates an action that returns an element of `vals`. Calling this action will
  1027. // repeatedly return the next value from `vals` until it reaches the end and
  1028. // will restart from the beginning.
  1029. template <typename T>
  1030. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
  1031. return internal::ReturnRoundRobinAction<T>(std::move(vals));
  1032. }
  1033. // Creates an action that returns an element of `vals`. Calling this action will
  1034. // repeatedly return the next value from `vals` until it reaches the end and
  1035. // will restart from the beginning.
  1036. template <typename T>
  1037. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
  1038. std::initializer_list<T> vals) {
  1039. return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
  1040. }
  1041. // Creates an action that does the default action for the give mock function.
  1042. inline internal::DoDefaultAction DoDefault() {
  1043. return internal::DoDefaultAction();
  1044. }
  1045. // Creates an action that sets the variable pointed by the N-th
  1046. // (0-based) function argument to 'value'.
  1047. template <size_t N, typename T>
  1048. internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
  1049. return {std::move(value)};
  1050. }
  1051. // The following version is DEPRECATED.
  1052. template <size_t N, typename T>
  1053. internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
  1054. return {std::move(value)};
  1055. }
  1056. // Creates an action that sets a pointer referent to a given value.
  1057. template <typename T1, typename T2>
  1058. PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
  1059. return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
  1060. }
  1061. #if !GTEST_OS_WINDOWS_MOBILE
  1062. // Creates an action that sets errno and returns the appropriate error.
  1063. template <typename T>
  1064. PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
  1065. SetErrnoAndReturn(int errval, T result) {
  1066. return MakePolymorphicAction(
  1067. internal::SetErrnoAndReturnAction<T>(errval, result));
  1068. }
  1069. #endif // !GTEST_OS_WINDOWS_MOBILE
  1070. // Various overloads for Invoke().
  1071. // Legacy function.
  1072. // Actions can now be implicitly constructed from callables. No need to create
  1073. // wrapper objects.
  1074. // This function exists for backwards compatibility.
  1075. template <typename FunctionImpl>
  1076. typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
  1077. return std::forward<FunctionImpl>(function_impl);
  1078. }
  1079. // Creates an action that invokes the given method on the given object
  1080. // with the mock function's arguments.
  1081. template <class Class, typename MethodPtr>
  1082. internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
  1083. MethodPtr method_ptr) {
  1084. return {obj_ptr, method_ptr};
  1085. }
  1086. // Creates an action that invokes 'function_impl' with no argument.
  1087. template <typename FunctionImpl>
  1088. internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
  1089. InvokeWithoutArgs(FunctionImpl function_impl) {
  1090. return {std::move(function_impl)};
  1091. }
  1092. // Creates an action that invokes the given method on the given object
  1093. // with no argument.
  1094. template <class Class, typename MethodPtr>
  1095. internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
  1096. Class* obj_ptr, MethodPtr method_ptr) {
  1097. return {obj_ptr, method_ptr};
  1098. }
  1099. // Creates an action that performs an_action and throws away its
  1100. // result. In other words, it changes the return type of an_action to
  1101. // void. an_action MUST NOT return void, or the code won't compile.
  1102. template <typename A>
  1103. inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
  1104. return internal::IgnoreResultAction<A>(an_action);
  1105. }
  1106. // Creates a reference wrapper for the given L-value. If necessary,
  1107. // you can explicitly specify the type of the reference. For example,
  1108. // suppose 'derived' is an object of type Derived, ByRef(derived)
  1109. // would wrap a Derived&. If you want to wrap a const Base& instead,
  1110. // where Base is a base class of Derived, just write:
  1111. //
  1112. // ByRef<const Base>(derived)
  1113. //
  1114. // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
  1115. // However, it may still be used for consistency with ByMove().
  1116. template <typename T>
  1117. inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
  1118. return ::std::reference_wrapper<T>(l_value);
  1119. }
  1120. namespace internal {
  1121. template <typename T, typename... Params>
  1122. struct ReturnNewAction {
  1123. T* operator()() const {
  1124. return internal::Apply(
  1125. [](const Params&... unpacked_params) {
  1126. return new T(unpacked_params...);
  1127. },
  1128. params);
  1129. }
  1130. std::tuple<Params...> params;
  1131. };
  1132. } // namespace internal
  1133. // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
  1134. // instance of type T, constructed on the heap with constructor arguments
  1135. // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
  1136. template <typename T, typename... Params>
  1137. internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
  1138. Params&&... params) {
  1139. return {std::forward_as_tuple(std::forward<Params>(params)...)};
  1140. }
  1141. namespace internal {
  1142. // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
  1143. // defines an action that can be used in a mock function. Typically,
  1144. // these actions only care about a subset of the arguments of the mock
  1145. // function. For example, if such an action only uses the second
  1146. // argument, it can be used in any mock function that takes >= 2
  1147. // arguments where the type of the second argument is compatible.
  1148. //
  1149. // Therefore, the action implementation must be prepared to take more
  1150. // arguments than it needs. The ExcessiveArg type is used to
  1151. // represent those excessive arguments. In order to keep the compiler
  1152. // error messages tractable, we define it in the testing namespace
  1153. // instead of testing::internal. However, this is an INTERNAL TYPE
  1154. // and subject to change without notice, so a user MUST NOT USE THIS
  1155. // TYPE DIRECTLY.
  1156. struct ExcessiveArg {};
  1157. // A helper class needed for implementing the ACTION* macros.
  1158. template <typename Result, class Impl>
  1159. class ActionHelper {
  1160. public:
  1161. template <typename... Ts>
  1162. static Result Perform(Impl* impl, const std::tuple<Ts...>& args) {
  1163. static constexpr size_t kMaxArgs = sizeof...(Ts) <= 10 ? sizeof...(Ts) : 10;
  1164. return Apply(impl, args, MakeIndexSequence<kMaxArgs>{},
  1165. MakeIndexSequence<10 - kMaxArgs>{});
  1166. }
  1167. private:
  1168. template <typename... Ts, std::size_t... tuple_ids, std::size_t... rest_ids>
  1169. static Result Apply(Impl* impl, const std::tuple<Ts...>& args,
  1170. IndexSequence<tuple_ids...>, IndexSequence<rest_ids...>) {
  1171. return impl->template gmock_PerformImpl<
  1172. typename std::tuple_element<tuple_ids, std::tuple<Ts...>>::type...>(
  1173. args, std::get<tuple_ids>(args)...,
  1174. ((void)rest_ids, ExcessiveArg())...);
  1175. }
  1176. };
  1177. // A helper base class needed for implementing the ACTION* macros.
  1178. // Implements constructor and conversion operator for Action.
  1179. //
  1180. // Template specialization for parameterless Action.
  1181. template <typename Derived>
  1182. class ActionImpl {
  1183. public:
  1184. ActionImpl() = default;
  1185. template <typename F>
  1186. operator ::testing::Action<F>() const { // NOLINT(runtime/explicit)
  1187. return ::testing::Action<F>(new typename Derived::template gmock_Impl<F>());
  1188. }
  1189. };
  1190. // Template specialization for parameterized Action.
  1191. template <template <typename...> class Derived, typename... Ts>
  1192. class ActionImpl<Derived<Ts...>> {
  1193. public:
  1194. explicit ActionImpl(Ts... params) : params_(std::forward<Ts>(params)...) {}
  1195. template <typename F>
  1196. operator ::testing::Action<F>() const { // NOLINT(runtime/explicit)
  1197. return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});
  1198. }
  1199. private:
  1200. template <typename F, std::size_t... tuple_ids>
  1201. ::testing::Action<F> Apply(IndexSequence<tuple_ids...>) const {
  1202. return ::testing::Action<F>(new
  1203. typename Derived<Ts...>::template gmock_Impl<F>(
  1204. std::get<tuple_ids>(params_)...));
  1205. }
  1206. std::tuple<Ts...> params_;
  1207. };
  1208. namespace invoke_argument {
  1209. // Appears in InvokeArgumentAdl's argument list to help avoid
  1210. // accidental calls to user functions of the same name.
  1211. struct AdlTag {};
  1212. // InvokeArgumentAdl - a helper for InvokeArgument.
  1213. // The basic overloads are provided here for generic functors.
  1214. // Overloads for other custom-callables are provided in the
  1215. // internal/custom/gmock-generated-actions.h header.
  1216. template <typename F, typename... Args>
  1217. auto InvokeArgumentAdl(AdlTag, F f, Args... args) -> decltype(f(args...)) {
  1218. return f(args...);
  1219. }
  1220. } // namespace invoke_argument
  1221. #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
  1222. , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
  1223. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
  1224. const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
  1225. GMOCK_INTERNAL_ARG_UNUSED, , 10)
  1226. #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
  1227. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
  1228. const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
  1229. #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
  1230. #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
  1231. GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
  1232. #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
  1233. #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
  1234. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
  1235. #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
  1236. #define GMOCK_ACTION_TYPE_PARAMS_(params) \
  1237. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
  1238. #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
  1239. , param##_type gmock_p##i
  1240. #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
  1241. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
  1242. #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
  1243. , std::forward<param##_type>(gmock_p##i)
  1244. #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
  1245. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
  1246. #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
  1247. , param(::std::forward<param##_type>(gmock_p##i))
  1248. #define GMOCK_ACTION_INIT_PARAMS_(params) \
  1249. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
  1250. #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
  1251. #define GMOCK_ACTION_FIELD_PARAMS_(params) \
  1252. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
  1253. #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
  1254. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1255. class full_name : public ::testing::internal::ActionImpl< \
  1256. full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>> { \
  1257. using base_type = ::testing::internal::ActionImpl<full_name>; \
  1258. \
  1259. public: \
  1260. using base_type::base_type; \
  1261. template <typename F> \
  1262. class gmock_Impl : public ::testing::ActionInterface<F> { \
  1263. public: \
  1264. typedef F function_type; \
  1265. typedef typename ::testing::internal::Function<F>::Result return_type; \
  1266. typedef \
  1267. typename ::testing::internal::Function<F>::ArgumentTuple args_type; \
  1268. explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
  1269. : GMOCK_ACTION_INIT_PARAMS_(params) {} \
  1270. return_type Perform(const args_type& args) override { \
  1271. return ::testing::internal::ActionHelper<return_type, \
  1272. gmock_Impl>::Perform(this, \
  1273. args); \
  1274. } \
  1275. template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1276. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  1277. GMOCK_ACTION_FIELD_PARAMS_(params) \
  1278. }; \
  1279. }; \
  1280. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1281. inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
  1282. GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
  1283. return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
  1284. GMOCK_ACTION_GVALUE_PARAMS_(params)); \
  1285. } \
  1286. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1287. template <typename F> \
  1288. template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1289. typename ::testing::internal::Function<F>::Result \
  1290. full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl< \
  1291. F>::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \
  1292. const
  1293. } // namespace internal
  1294. #define ACTION(name) \
  1295. class name##Action : public ::testing::internal::ActionImpl<name##Action> { \
  1296. using base_type = ::testing::internal::ActionImpl<name##Action>; \
  1297. \
  1298. public: \
  1299. using base_type::base_type; \
  1300. template <typename F> \
  1301. class gmock_Impl : public ::testing::ActionInterface<F> { \
  1302. public: \
  1303. typedef F function_type; \
  1304. typedef typename ::testing::internal::Function<F>::Result return_type; \
  1305. typedef \
  1306. typename ::testing::internal::Function<F>::ArgumentTuple args_type; \
  1307. gmock_Impl() {} \
  1308. return_type Perform(const args_type& args) override { \
  1309. return ::testing::internal::ActionHelper<return_type, \
  1310. gmock_Impl>::Perform(this, \
  1311. args); \
  1312. } \
  1313. template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1314. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  1315. }; \
  1316. }; \
  1317. inline name##Action name() { return name##Action(); } \
  1318. template <typename F> \
  1319. template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1320. typename ::testing::internal::Function<F>::Result \
  1321. name##Action::gmock_Impl<F>::gmock_PerformImpl( \
  1322. GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  1323. #define ACTION_P(name, ...) \
  1324. GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
  1325. #define ACTION_P2(name, ...) \
  1326. GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
  1327. #define ACTION_P3(name, ...) \
  1328. GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
  1329. #define ACTION_P4(name, ...) \
  1330. GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
  1331. #define ACTION_P5(name, ...) \
  1332. GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
  1333. #define ACTION_P6(name, ...) \
  1334. GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
  1335. #define ACTION_P7(name, ...) \
  1336. GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
  1337. #define ACTION_P8(name, ...) \
  1338. GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
  1339. #define ACTION_P9(name, ...) \
  1340. GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
  1341. #define ACTION_P10(name, ...) \
  1342. GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
  1343. } // namespace testing
  1344. #ifdef _MSC_VER
  1345. # pragma warning(pop)
  1346. #endif
  1347. #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_