gmock-actions.h 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302
  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/main/docs/gmock_cook_book.md
  125. // IWYU pragma: private, include "gmock/gmock.h"
  126. // IWYU pragma: friend gmock/.*
  127. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  128. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
  129. #ifndef _WIN32_WCE
  130. #include <errno.h>
  131. #endif
  132. #include <algorithm>
  133. #include <functional>
  134. #include <memory>
  135. #include <string>
  136. #include <tuple>
  137. #include <type_traits>
  138. #include <utility>
  139. #include "gmock/internal/gmock-internal-utils.h"
  140. #include "gmock/internal/gmock-port.h"
  141. #include "gmock/internal/gmock-pp.h"
  142. #ifdef _MSC_VER
  143. #pragma warning(push)
  144. #pragma warning(disable : 4100)
  145. #endif
  146. namespace testing {
  147. // To implement an action Foo, define:
  148. // 1. a class FooAction that implements the ActionInterface interface, and
  149. // 2. a factory function that creates an Action object from a
  150. // const FooAction*.
  151. //
  152. // The two-level delegation design follows that of Matcher, providing
  153. // consistency for extension developers. It also eases ownership
  154. // management as Action objects can now be copied like plain values.
  155. namespace internal {
  156. // BuiltInDefaultValueGetter<T, true>::Get() returns a
  157. // default-constructed T value. BuiltInDefaultValueGetter<T,
  158. // false>::Get() crashes with an error.
  159. //
  160. // This primary template is used when kDefaultConstructible is true.
  161. template <typename T, bool kDefaultConstructible>
  162. struct BuiltInDefaultValueGetter {
  163. static T Get() { return T(); }
  164. };
  165. template <typename T>
  166. struct BuiltInDefaultValueGetter<T, false> {
  167. static T Get() {
  168. Assert(false, __FILE__, __LINE__,
  169. "Default action undefined for the function return type.");
  170. return internal::Invalid<T>();
  171. // The above statement will never be reached, but is required in
  172. // order for this function to compile.
  173. }
  174. };
  175. // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
  176. // for type T, which is NULL when T is a raw pointer type, 0 when T is
  177. // a numeric type, false when T is bool, or "" when T is string or
  178. // std::string. In addition, in C++11 and above, it turns a
  179. // default-constructed T value if T is default constructible. For any
  180. // other type T, the built-in default T value is undefined, and the
  181. // function will abort the process.
  182. template <typename T>
  183. class BuiltInDefaultValue {
  184. public:
  185. // This function returns true if and only if type T has a built-in default
  186. // value.
  187. static bool Exists() { return ::std::is_default_constructible<T>::value; }
  188. static T Get() {
  189. return BuiltInDefaultValueGetter<
  190. T, ::std::is_default_constructible<T>::value>::Get();
  191. }
  192. };
  193. // This partial specialization says that we use the same built-in
  194. // default value for T and const T.
  195. template <typename T>
  196. class BuiltInDefaultValue<const T> {
  197. public:
  198. static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
  199. static T Get() { return BuiltInDefaultValue<T>::Get(); }
  200. };
  201. // This partial specialization defines the default values for pointer
  202. // types.
  203. template <typename T>
  204. class BuiltInDefaultValue<T*> {
  205. public:
  206. static bool Exists() { return true; }
  207. static T* Get() { return nullptr; }
  208. };
  209. // The following specializations define the default values for
  210. // specific types we care about.
  211. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
  212. template <> \
  213. class BuiltInDefaultValue<type> { \
  214. public: \
  215. static bool Exists() { return true; } \
  216. static type Get() { return value; } \
  217. }
  218. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
  219. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
  220. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
  221. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
  222. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
  223. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
  224. // There's no need for a default action for signed wchar_t, as that
  225. // type is the same as wchar_t for gcc, and invalid for MSVC.
  226. //
  227. // There's also no need for a default action for unsigned wchar_t, as
  228. // that type is the same as unsigned int for gcc, and invalid for
  229. // MSVC.
  230. #if GMOCK_WCHAR_T_IS_NATIVE_
  231. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
  232. #endif
  233. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
  234. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
  235. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
  236. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
  237. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
  238. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
  239. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT
  240. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT
  241. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
  242. GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
  243. #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
  244. // Partial implementations of metaprogramming types from the standard library
  245. // not available in C++11.
  246. template <typename P>
  247. struct negation
  248. // NOLINTNEXTLINE
  249. : std::integral_constant<bool, bool(!P::value)> {};
  250. // Base case: with zero predicates the answer is always true.
  251. template <typename...>
  252. struct conjunction : std::true_type {};
  253. // With a single predicate, the answer is that predicate.
  254. template <typename P1>
  255. struct conjunction<P1> : P1 {};
  256. // With multiple predicates the answer is the first predicate if that is false,
  257. // and we recurse otherwise.
  258. template <typename P1, typename... Ps>
  259. struct conjunction<P1, Ps...>
  260. : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {};
  261. template <typename...>
  262. struct disjunction : std::false_type {};
  263. template <typename P1>
  264. struct disjunction<P1> : P1 {};
  265. template <typename P1, typename... Ps>
  266. struct disjunction<P1, Ps...>
  267. // NOLINTNEXTLINE
  268. : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {};
  269. template <typename...>
  270. using void_t = void;
  271. // Detects whether an expression of type `From` can be implicitly converted to
  272. // `To` according to [conv]. In C++17, [conv]/3 defines this as follows:
  273. //
  274. // An expression e can be implicitly converted to a type T if and only if
  275. // the declaration T t=e; is well-formed, for some invented temporary
  276. // variable t ([dcl.init]).
  277. //
  278. // [conv]/2 implies we can use function argument passing to detect whether this
  279. // initialization is valid.
  280. //
  281. // Note that this is distinct from is_convertible, which requires this be valid:
  282. //
  283. // To test() {
  284. // return declval<From>();
  285. // }
  286. //
  287. // In particular, is_convertible doesn't give the correct answer when `To` and
  288. // `From` are the same non-moveable type since `declval<From>` will be an rvalue
  289. // reference, defeating the guaranteed copy elision that would otherwise make
  290. // this function work.
  291. //
  292. // REQUIRES: `From` is not cv void.
  293. template <typename From, typename To>
  294. struct is_implicitly_convertible {
  295. private:
  296. // A function that accepts a parameter of type T. This can be called with type
  297. // U successfully only if U is implicitly convertible to T.
  298. template <typename T>
  299. static void Accept(T);
  300. // A function that creates a value of type T.
  301. template <typename T>
  302. static T Make();
  303. // An overload be selected when implicit conversion from T to To is possible.
  304. template <typename T, typename = decltype(Accept<To>(Make<T>()))>
  305. static std::true_type TestImplicitConversion(int);
  306. // A fallback overload selected in all other cases.
  307. template <typename T>
  308. static std::false_type TestImplicitConversion(...);
  309. public:
  310. using type = decltype(TestImplicitConversion<From>(0));
  311. static constexpr bool value = type::value;
  312. };
  313. // Like std::invoke_result_t from C++17, but works only for objects with call
  314. // operators (not e.g. member function pointers, which we don't need specific
  315. // support for in OnceAction because std::function deals with them).
  316. template <typename F, typename... Args>
  317. using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...));
  318. template <typename Void, typename R, typename F, typename... Args>
  319. struct is_callable_r_impl : std::false_type {};
  320. // Specialize the struct for those template arguments where call_result_t is
  321. // well-formed. When it's not, the generic template above is chosen, resulting
  322. // in std::false_type.
  323. template <typename R, typename F, typename... Args>
  324. struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>
  325. : std::conditional<
  326. std::is_void<R>::value, //
  327. std::true_type, //
  328. is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};
  329. // Like std::is_invocable_r from C++17, but works only for objects with call
  330. // operators. See the note on call_result_t.
  331. template <typename R, typename F, typename... Args>
  332. using is_callable_r = is_callable_r_impl<void, R, F, Args...>;
  333. // Like std::as_const from C++17.
  334. template <typename T>
  335. typename std::add_const<T>::type& as_const(T& t) {
  336. return t;
  337. }
  338. } // namespace internal
  339. // Specialized for function types below.
  340. template <typename F>
  341. class OnceAction;
  342. // An action that can only be used once.
  343. //
  344. // This is accepted by WillOnce, which doesn't require the underlying action to
  345. // be copy-constructible (only move-constructible), and promises to invoke it as
  346. // an rvalue reference. This allows the action to work with move-only types like
  347. // std::move_only_function in a type-safe manner.
  348. //
  349. // For example:
  350. //
  351. // // Assume we have some API that needs to accept a unique pointer to some
  352. // // non-copyable object Foo.
  353. // void AcceptUniquePointer(std::unique_ptr<Foo> foo);
  354. //
  355. // // We can define an action that provides a Foo to that API. Because It
  356. // // has to give away its unique pointer, it must not be called more than
  357. // // once, so its call operator is &&-qualified.
  358. // struct ProvideFoo {
  359. // std::unique_ptr<Foo> foo;
  360. //
  361. // void operator()() && {
  362. // AcceptUniquePointer(std::move(Foo));
  363. // }
  364. // };
  365. //
  366. // // This action can be used with WillOnce.
  367. // EXPECT_CALL(mock, Call)
  368. // .WillOnce(ProvideFoo{std::make_unique<Foo>(...)});
  369. //
  370. // // But a call to WillRepeatedly will fail to compile. This is correct,
  371. // // since the action cannot correctly be used repeatedly.
  372. // EXPECT_CALL(mock, Call)
  373. // .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)});
  374. //
  375. // A less-contrived example would be an action that returns an arbitrary type,
  376. // whose &&-qualified call operator is capable of dealing with move-only types.
  377. template <typename Result, typename... Args>
  378. class OnceAction<Result(Args...)> final {
  379. private:
  380. // True iff we can use the given callable type (or lvalue reference) directly
  381. // via StdFunctionAdaptor.
  382. template <typename Callable>
  383. using IsDirectlyCompatible = internal::conjunction<
  384. // It must be possible to capture the callable in StdFunctionAdaptor.
  385. std::is_constructible<typename std::decay<Callable>::type, Callable>,
  386. // The callable must be compatible with our signature.
  387. internal::is_callable_r<Result, typename std::decay<Callable>::type,
  388. Args...>>;
  389. // True iff we can use the given callable type via StdFunctionAdaptor once we
  390. // ignore incoming arguments.
  391. template <typename Callable>
  392. using IsCompatibleAfterIgnoringArguments = internal::conjunction<
  393. // It must be possible to capture the callable in a lambda.
  394. std::is_constructible<typename std::decay<Callable>::type, Callable>,
  395. // The callable must be invocable with zero arguments, returning something
  396. // convertible to Result.
  397. internal::is_callable_r<Result, typename std::decay<Callable>::type>>;
  398. public:
  399. // Construct from a callable that is directly compatible with our mocked
  400. // signature: it accepts our function type's arguments and returns something
  401. // convertible to our result type.
  402. template <typename Callable,
  403. typename std::enable_if<
  404. internal::conjunction<
  405. // Teach clang on macOS that we're not talking about a
  406. // copy/move constructor here. Otherwise it gets confused
  407. // when checking the is_constructible requirement of our
  408. // traits above.
  409. internal::negation<std::is_same<
  410. OnceAction, typename std::decay<Callable>::type>>,
  411. IsDirectlyCompatible<Callable>> //
  412. ::value,
  413. int>::type = 0>
  414. OnceAction(Callable&& callable) // NOLINT
  415. : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>(
  416. {}, std::forward<Callable>(callable))) {}
  417. // As above, but for a callable that ignores the mocked function's arguments.
  418. template <typename Callable,
  419. typename std::enable_if<
  420. internal::conjunction<
  421. // Teach clang on macOS that we're not talking about a
  422. // copy/move constructor here. Otherwise it gets confused
  423. // when checking the is_constructible requirement of our
  424. // traits above.
  425. internal::negation<std::is_same<
  426. OnceAction, typename std::decay<Callable>::type>>,
  427. // Exclude callables for which the overload above works.
  428. // We'd rather provide the arguments if possible.
  429. internal::negation<IsDirectlyCompatible<Callable>>,
  430. IsCompatibleAfterIgnoringArguments<Callable>>::value,
  431. int>::type = 0>
  432. OnceAction(Callable&& callable) // NOLINT
  433. // Call the constructor above with a callable
  434. // that ignores the input arguments.
  435. : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{
  436. std::forward<Callable>(callable)}) {}
  437. // We are naturally copyable because we store only an std::function, but
  438. // semantically we should not be copyable.
  439. OnceAction(const OnceAction&) = delete;
  440. OnceAction& operator=(const OnceAction&) = delete;
  441. OnceAction(OnceAction&&) = default;
  442. // Invoke the underlying action callable with which we were constructed,
  443. // handing it the supplied arguments.
  444. Result Call(Args... args) && {
  445. return function_(std::forward<Args>(args)...);
  446. }
  447. private:
  448. // An adaptor that wraps a callable that is compatible with our signature and
  449. // being invoked as an rvalue reference so that it can be used as an
  450. // StdFunctionAdaptor. This throws away type safety, but that's fine because
  451. // this is only used by WillOnce, which we know calls at most once.
  452. //
  453. // Once we have something like std::move_only_function from C++23, we can do
  454. // away with this.
  455. template <typename Callable>
  456. class StdFunctionAdaptor final {
  457. public:
  458. // A tag indicating that the (otherwise universal) constructor is accepting
  459. // the callable itself, instead of e.g. stealing calls for the move
  460. // constructor.
  461. struct CallableTag final {};
  462. template <typename F>
  463. explicit StdFunctionAdaptor(CallableTag, F&& callable)
  464. : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {}
  465. // Rather than explicitly returning Result, we return whatever the wrapped
  466. // callable returns. This allows for compatibility with existing uses like
  467. // the following, when the mocked function returns void:
  468. //
  469. // EXPECT_CALL(mock_fn_, Call)
  470. // .WillOnce([&] {
  471. // [...]
  472. // return 0;
  473. // });
  474. //
  475. // Such a callable can be turned into std::function<void()>. If we use an
  476. // explicit return type of Result here then it *doesn't* work with
  477. // std::function, because we'll get a "void function should not return a
  478. // value" error.
  479. //
  480. // We need not worry about incompatible result types because the SFINAE on
  481. // OnceAction already checks this for us. std::is_invocable_r_v itself makes
  482. // the same allowance for void result types.
  483. template <typename... ArgRefs>
  484. internal::call_result_t<Callable, ArgRefs...> operator()(
  485. ArgRefs&&... args) const {
  486. return std::move(*callable_)(std::forward<ArgRefs>(args)...);
  487. }
  488. private:
  489. // We must put the callable on the heap so that we are copyable, which
  490. // std::function needs.
  491. std::shared_ptr<Callable> callable_;
  492. };
  493. // An adaptor that makes a callable that accepts zero arguments callable with
  494. // our mocked arguments.
  495. template <typename Callable>
  496. struct IgnoreIncomingArguments {
  497. internal::call_result_t<Callable> operator()(Args&&...) {
  498. return std::move(callable)();
  499. }
  500. Callable callable;
  501. };
  502. std::function<Result(Args...)> function_;
  503. };
  504. // When an unexpected function call is encountered, Google Mock will
  505. // let it return a default value if the user has specified one for its
  506. // return type, or if the return type has a built-in default value;
  507. // otherwise Google Mock won't know what value to return and will have
  508. // to abort the process.
  509. //
  510. // The DefaultValue<T> class allows a user to specify the
  511. // default value for a type T that is both copyable and publicly
  512. // destructible (i.e. anything that can be used as a function return
  513. // type). The usage is:
  514. //
  515. // // Sets the default value for type T to be foo.
  516. // DefaultValue<T>::Set(foo);
  517. template <typename T>
  518. class DefaultValue {
  519. public:
  520. // Sets the default value for type T; requires T to be
  521. // copy-constructable and have a public destructor.
  522. static void Set(T x) {
  523. delete producer_;
  524. producer_ = new FixedValueProducer(x);
  525. }
  526. // Provides a factory function to be called to generate the default value.
  527. // This method can be used even if T is only move-constructible, but it is not
  528. // limited to that case.
  529. typedef T (*FactoryFunction)();
  530. static void SetFactory(FactoryFunction factory) {
  531. delete producer_;
  532. producer_ = new FactoryValueProducer(factory);
  533. }
  534. // Unsets the default value for type T.
  535. static void Clear() {
  536. delete producer_;
  537. producer_ = nullptr;
  538. }
  539. // Returns true if and only if the user has set the default value for type T.
  540. static bool IsSet() { return producer_ != nullptr; }
  541. // Returns true if T has a default return value set by the user or there
  542. // exists a built-in default value.
  543. static bool Exists() {
  544. return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
  545. }
  546. // Returns the default value for type T if the user has set one;
  547. // otherwise returns the built-in default value. Requires that Exists()
  548. // is true, which ensures that the return value is well-defined.
  549. static T Get() {
  550. return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
  551. : producer_->Produce();
  552. }
  553. private:
  554. class ValueProducer {
  555. public:
  556. virtual ~ValueProducer() {}
  557. virtual T Produce() = 0;
  558. };
  559. class FixedValueProducer : public ValueProducer {
  560. public:
  561. explicit FixedValueProducer(T value) : value_(value) {}
  562. T Produce() override { return value_; }
  563. private:
  564. const T value_;
  565. FixedValueProducer(const FixedValueProducer&) = delete;
  566. FixedValueProducer& operator=(const FixedValueProducer&) = delete;
  567. };
  568. class FactoryValueProducer : public ValueProducer {
  569. public:
  570. explicit FactoryValueProducer(FactoryFunction factory)
  571. : factory_(factory) {}
  572. T Produce() override { return factory_(); }
  573. private:
  574. const FactoryFunction factory_;
  575. FactoryValueProducer(const FactoryValueProducer&) = delete;
  576. FactoryValueProducer& operator=(const FactoryValueProducer&) = delete;
  577. };
  578. static ValueProducer* producer_;
  579. };
  580. // This partial specialization allows a user to set default values for
  581. // reference types.
  582. template <typename T>
  583. class DefaultValue<T&> {
  584. public:
  585. // Sets the default value for type T&.
  586. static void Set(T& x) { // NOLINT
  587. address_ = &x;
  588. }
  589. // Unsets the default value for type T&.
  590. static void Clear() { address_ = nullptr; }
  591. // Returns true if and only if the user has set the default value for type T&.
  592. static bool IsSet() { return address_ != nullptr; }
  593. // Returns true if T has a default return value set by the user or there
  594. // exists a built-in default value.
  595. static bool Exists() {
  596. return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
  597. }
  598. // Returns the default value for type T& if the user has set one;
  599. // otherwise returns the built-in default value if there is one;
  600. // otherwise aborts the process.
  601. static T& Get() {
  602. return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
  603. : *address_;
  604. }
  605. private:
  606. static T* address_;
  607. };
  608. // This specialization allows DefaultValue<void>::Get() to
  609. // compile.
  610. template <>
  611. class DefaultValue<void> {
  612. public:
  613. static bool Exists() { return true; }
  614. static void Get() {}
  615. };
  616. // Points to the user-set default value for type T.
  617. template <typename T>
  618. typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
  619. // Points to the user-set default value for type T&.
  620. template <typename T>
  621. T* DefaultValue<T&>::address_ = nullptr;
  622. // Implement this interface to define an action for function type F.
  623. template <typename F>
  624. class ActionInterface {
  625. public:
  626. typedef typename internal::Function<F>::Result Result;
  627. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  628. ActionInterface() {}
  629. virtual ~ActionInterface() {}
  630. // Performs the action. This method is not const, as in general an
  631. // action can have side effects and be stateful. For example, a
  632. // get-the-next-element-from-the-collection action will need to
  633. // remember the current element.
  634. virtual Result Perform(const ArgumentTuple& args) = 0;
  635. private:
  636. ActionInterface(const ActionInterface&) = delete;
  637. ActionInterface& operator=(const ActionInterface&) = delete;
  638. };
  639. template <typename F>
  640. class Action;
  641. // An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)
  642. // object that represents an action to be taken when a mock function of type
  643. // R(Args...) is called. The implementation of Action<T> is just a
  644. // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You
  645. // can view an object implementing ActionInterface<F> as a concrete action
  646. // (including its current state), and an Action<F> object as a handle to it.
  647. template <typename R, typename... Args>
  648. class Action<R(Args...)> {
  649. private:
  650. using F = R(Args...);
  651. // Adapter class to allow constructing Action from a legacy ActionInterface.
  652. // New code should create Actions from functors instead.
  653. struct ActionAdapter {
  654. // Adapter must be copyable to satisfy std::function requirements.
  655. ::std::shared_ptr<ActionInterface<F>> impl_;
  656. template <typename... InArgs>
  657. typename internal::Function<F>::Result operator()(InArgs&&... args) {
  658. return impl_->Perform(
  659. ::std::forward_as_tuple(::std::forward<InArgs>(args)...));
  660. }
  661. };
  662. template <typename G>
  663. using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
  664. public:
  665. typedef typename internal::Function<F>::Result Result;
  666. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  667. // Constructs a null Action. Needed for storing Action objects in
  668. // STL containers.
  669. Action() {}
  670. // Construct an Action from a specified callable.
  671. // This cannot take std::function directly, because then Action would not be
  672. // directly constructible from lambda (it would require two conversions).
  673. template <
  674. typename G,
  675. typename = typename std::enable_if<internal::disjunction<
  676. IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
  677. G>>::value>::type>
  678. Action(G&& fun) { // NOLINT
  679. Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
  680. }
  681. // Constructs an Action from its implementation.
  682. explicit Action(ActionInterface<F>* impl)
  683. : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
  684. // This constructor allows us to turn an Action<Func> object into an
  685. // Action<F>, as long as F's arguments can be implicitly converted
  686. // to Func's and Func's return type can be implicitly converted to F's.
  687. template <typename Func>
  688. Action(const Action<Func>& action) // NOLINT
  689. : fun_(action.fun_) {}
  690. // Returns true if and only if this is the DoDefault() action.
  691. bool IsDoDefault() const { return fun_ == nullptr; }
  692. // Performs the action. Note that this method is const even though
  693. // the corresponding method in ActionInterface is not. The reason
  694. // is that a const Action<F> means that it cannot be re-bound to
  695. // another concrete action, not that the concrete action it binds to
  696. // cannot change state. (Think of the difference between a const
  697. // pointer and a pointer to const.)
  698. Result Perform(ArgumentTuple args) const {
  699. if (IsDoDefault()) {
  700. internal::IllegalDoDefault(__FILE__, __LINE__);
  701. }
  702. return internal::Apply(fun_, ::std::move(args));
  703. }
  704. // An action can be used as a OnceAction, since it's obviously safe to call it
  705. // once.
  706. operator OnceAction<F>() const { // NOLINT
  707. // Return a OnceAction-compatible callable that calls Perform with the
  708. // arguments it is provided. We could instead just return fun_, but then
  709. // we'd need to handle the IsDoDefault() case separately.
  710. struct OA {
  711. Action<F> action;
  712. R operator()(Args... args) && {
  713. return action.Perform(
  714. std::forward_as_tuple(std::forward<Args>(args)...));
  715. }
  716. };
  717. return OA{*this};
  718. }
  719. private:
  720. template <typename G>
  721. friend class Action;
  722. template <typename G>
  723. void Init(G&& g, ::std::true_type) {
  724. fun_ = ::std::forward<G>(g);
  725. }
  726. template <typename G>
  727. void Init(G&& g, ::std::false_type) {
  728. fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
  729. }
  730. template <typename FunctionImpl>
  731. struct IgnoreArgs {
  732. template <typename... InArgs>
  733. Result operator()(const InArgs&...) const {
  734. return function_impl();
  735. }
  736. FunctionImpl function_impl;
  737. };
  738. // fun_ is an empty function if and only if this is the DoDefault() action.
  739. ::std::function<F> fun_;
  740. };
  741. // The PolymorphicAction class template makes it easy to implement a
  742. // polymorphic action (i.e. an action that can be used in mock
  743. // functions of than one type, e.g. Return()).
  744. //
  745. // To define a polymorphic action, a user first provides a COPYABLE
  746. // implementation class that has a Perform() method template:
  747. //
  748. // class FooAction {
  749. // public:
  750. // template <typename Result, typename ArgumentTuple>
  751. // Result Perform(const ArgumentTuple& args) const {
  752. // // Processes the arguments and returns a result, using
  753. // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
  754. // }
  755. // ...
  756. // };
  757. //
  758. // Then the user creates the polymorphic action using
  759. // MakePolymorphicAction(object) where object has type FooAction. See
  760. // the definition of Return(void) and SetArgumentPointee<N>(value) for
  761. // complete examples.
  762. template <typename Impl>
  763. class PolymorphicAction {
  764. public:
  765. explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
  766. template <typename F>
  767. operator Action<F>() const {
  768. return Action<F>(new MonomorphicImpl<F>(impl_));
  769. }
  770. private:
  771. template <typename F>
  772. class MonomorphicImpl : public ActionInterface<F> {
  773. public:
  774. typedef typename internal::Function<F>::Result Result;
  775. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  776. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  777. Result Perform(const ArgumentTuple& args) override {
  778. return impl_.template Perform<Result>(args);
  779. }
  780. private:
  781. Impl impl_;
  782. };
  783. Impl impl_;
  784. };
  785. // Creates an Action from its implementation and returns it. The
  786. // created Action object owns the implementation.
  787. template <typename F>
  788. Action<F> MakeAction(ActionInterface<F>* impl) {
  789. return Action<F>(impl);
  790. }
  791. // Creates a polymorphic action from its implementation. This is
  792. // easier to use than the PolymorphicAction<Impl> constructor as it
  793. // doesn't require you to explicitly write the template argument, e.g.
  794. //
  795. // MakePolymorphicAction(foo);
  796. // vs
  797. // PolymorphicAction<TypeOfFoo>(foo);
  798. template <typename Impl>
  799. inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
  800. return PolymorphicAction<Impl>(impl);
  801. }
  802. namespace internal {
  803. // Helper struct to specialize ReturnAction to execute a move instead of a copy
  804. // on return. Useful for move-only types, but could be used on any type.
  805. template <typename T>
  806. struct ByMoveWrapper {
  807. explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
  808. T payload;
  809. };
  810. // The general implementation of Return(R). Specializations follow below.
  811. template <typename R>
  812. class ReturnAction final {
  813. public:
  814. explicit ReturnAction(R value) : value_(std::move(value)) {}
  815. template <typename U, typename... Args,
  816. typename = typename std::enable_if<conjunction<
  817. // See the requirements documented on Return.
  818. negation<std::is_same<void, U>>, //
  819. negation<std::is_reference<U>>, //
  820. std::is_convertible<R, U>, //
  821. std::is_move_constructible<U>>::value>::type>
  822. operator OnceAction<U(Args...)>() && { // NOLINT
  823. return Impl<U>(std::move(value_));
  824. }
  825. template <typename U, typename... Args,
  826. typename = typename std::enable_if<conjunction<
  827. // See the requirements documented on Return.
  828. negation<std::is_same<void, U>>, //
  829. negation<std::is_reference<U>>, //
  830. std::is_convertible<const R&, U>, //
  831. std::is_copy_constructible<U>>::value>::type>
  832. operator Action<U(Args...)>() const { // NOLINT
  833. return Impl<U>(value_);
  834. }
  835. private:
  836. // Implements the Return(x) action for a mock function that returns type U.
  837. template <typename U>
  838. class Impl final {
  839. public:
  840. // The constructor used when the return value is allowed to move from the
  841. // input value (i.e. we are converting to OnceAction).
  842. explicit Impl(R&& input_value)
  843. : state_(new State(std::move(input_value))) {}
  844. // The constructor used when the return value is not allowed to move from
  845. // the input value (i.e. we are converting to Action).
  846. explicit Impl(const R& input_value) : state_(new State(input_value)) {}
  847. U operator()() && { return std::move(state_->value); }
  848. U operator()() const& { return state_->value; }
  849. private:
  850. // We put our state on the heap so that the compiler-generated copy/move
  851. // constructors work correctly even when U is a reference-like type. This is
  852. // necessary only because we eagerly create State::value (see the note on
  853. // that symbol for details). If we instead had only the input value as a
  854. // member then the default constructors would work fine.
  855. //
  856. // For example, when R is std::string and U is std::string_view, value is a
  857. // reference to the string backed by input_value. The copy constructor would
  858. // copy both, so that we wind up with a new input_value object (with the
  859. // same contents) and a reference to the *old* input_value object rather
  860. // than the new one.
  861. struct State {
  862. explicit State(const R& input_value_in)
  863. : input_value(input_value_in),
  864. // Make an implicit conversion to Result before initializing the U
  865. // object we store, avoiding calling any explicit constructor of U
  866. // from R.
  867. //
  868. // This simulates the language rules: a function with return type U
  869. // that does `return R()` requires R to be implicitly convertible to
  870. // U, and uses that path for the conversion, even U Result has an
  871. // explicit constructor from R.
  872. value(ImplicitCast_<U>(internal::as_const(input_value))) {}
  873. // As above, but for the case where we're moving from the ReturnAction
  874. // object because it's being used as a OnceAction.
  875. explicit State(R&& input_value_in)
  876. : input_value(std::move(input_value_in)),
  877. // For the same reason as above we make an implicit conversion to U
  878. // before initializing the value.
  879. //
  880. // Unlike above we provide the input value as an rvalue to the
  881. // implicit conversion because this is a OnceAction: it's fine if it
  882. // wants to consume the input value.
  883. value(ImplicitCast_<U>(std::move(input_value))) {}
  884. // A copy of the value originally provided by the user. We retain this in
  885. // addition to the value of the mock function's result type below in case
  886. // the latter is a reference-like type. See the std::string_view example
  887. // in the documentation on Return.
  888. R input_value;
  889. // The value we actually return, as the type returned by the mock function
  890. // itself.
  891. //
  892. // We eagerly initialize this here, rather than lazily doing the implicit
  893. // conversion automatically each time Perform is called, for historical
  894. // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126)
  895. // made the Action<U()> conversion operator eagerly convert the R value to
  896. // U, but without keeping the R alive. This broke the use case discussed
  897. // in the documentation for Return, making reference-like types such as
  898. // std::string_view not safe to use as U where the input type R is a
  899. // value-like type such as std::string.
  900. //
  901. // The example the commit gave was not very clear, nor was the issue
  902. // thread (https://github.com/google/googlemock/issues/86), but it seems
  903. // the worry was about reference-like input types R that flatten to a
  904. // value-like type U when being implicitly converted. An example of this
  905. // is std::vector<bool>::reference, which is often a proxy type with an
  906. // reference to the underlying vector:
  907. //
  908. // // Helper method: have the mock function return bools according
  909. // // to the supplied script.
  910. // void SetActions(MockFunction<bool(size_t)>& mock,
  911. // const std::vector<bool>& script) {
  912. // for (size_t i = 0; i < script.size(); ++i) {
  913. // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i]));
  914. // }
  915. // }
  916. //
  917. // TEST(Foo, Bar) {
  918. // // Set actions using a temporary vector, whose operator[]
  919. // // returns proxy objects that references that will be
  920. // // dangling once the call to SetActions finishes and the
  921. // // vector is destroyed.
  922. // MockFunction<bool(size_t)> mock;
  923. // SetActions(mock, {false, true});
  924. //
  925. // EXPECT_FALSE(mock.AsStdFunction()(0));
  926. // EXPECT_TRUE(mock.AsStdFunction()(1));
  927. // }
  928. //
  929. // This eager conversion helps with a simple case like this, but doesn't
  930. // fully make these types work in general. For example the following still
  931. // uses a dangling reference:
  932. //
  933. // TEST(Foo, Baz) {
  934. // MockFunction<std::vector<std::string>()> mock;
  935. //
  936. // // Return the same vector twice, and then the empty vector
  937. // // thereafter.
  938. // auto action = Return(std::initializer_list<std::string>{
  939. // "taco", "burrito",
  940. // });
  941. //
  942. // EXPECT_CALL(mock, Call)
  943. // .WillOnce(action)
  944. // .WillOnce(action)
  945. // .WillRepeatedly(Return(std::vector<std::string>{}));
  946. //
  947. // EXPECT_THAT(mock.AsStdFunction()(),
  948. // ElementsAre("taco", "burrito"));
  949. // EXPECT_THAT(mock.AsStdFunction()(),
  950. // ElementsAre("taco", "burrito"));
  951. // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty());
  952. // }
  953. //
  954. U value;
  955. };
  956. const std::shared_ptr<State> state_;
  957. };
  958. R value_;
  959. };
  960. // A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T.
  961. //
  962. // This version applies the type system-defeating hack of moving from T even in
  963. // the const call operator, checking at runtime that it isn't called more than
  964. // once, since the user has declared their intent to do so by using ByMove.
  965. template <typename T>
  966. class ReturnAction<ByMoveWrapper<T>> final {
  967. public:
  968. explicit ReturnAction(ByMoveWrapper<T> wrapper)
  969. : state_(new State(std::move(wrapper.payload))) {}
  970. T operator()() const {
  971. GTEST_CHECK_(!state_->called)
  972. << "A ByMove() action must be performed at most once.";
  973. state_->called = true;
  974. return std::move(state_->value);
  975. }
  976. private:
  977. // We store our state on the heap so that we are copyable as required by
  978. // Action, despite the fact that we are stateful and T may not be copyable.
  979. struct State {
  980. explicit State(T&& value_in) : value(std::move(value_in)) {}
  981. T value;
  982. bool called = false;
  983. };
  984. const std::shared_ptr<State> state_;
  985. };
  986. // Implements the ReturnNull() action.
  987. class ReturnNullAction {
  988. public:
  989. // Allows ReturnNull() to be used in any pointer-returning function. In C++11
  990. // this is enforced by returning nullptr, and in non-C++11 by asserting a
  991. // pointer type on compile time.
  992. template <typename Result, typename ArgumentTuple>
  993. static Result Perform(const ArgumentTuple&) {
  994. return nullptr;
  995. }
  996. };
  997. // Implements the Return() action.
  998. class ReturnVoidAction {
  999. public:
  1000. // Allows Return() to be used in any void-returning function.
  1001. template <typename Result, typename ArgumentTuple>
  1002. static void Perform(const ArgumentTuple&) {
  1003. static_assert(std::is_void<Result>::value, "Result should be void.");
  1004. }
  1005. };
  1006. // Implements the polymorphic ReturnRef(x) action, which can be used
  1007. // in any function that returns a reference to the type of x,
  1008. // regardless of the argument types.
  1009. template <typename T>
  1010. class ReturnRefAction {
  1011. public:
  1012. // Constructs a ReturnRefAction object from the reference to be returned.
  1013. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
  1014. // This template type conversion operator allows ReturnRef(x) to be
  1015. // used in ANY function that returns a reference to x's type.
  1016. template <typename F>
  1017. operator Action<F>() const {
  1018. typedef typename Function<F>::Result Result;
  1019. // Asserts that the function return type is a reference. This
  1020. // catches the user error of using ReturnRef(x) when Return(x)
  1021. // should be used, and generates some helpful error message.
  1022. static_assert(std::is_reference<Result>::value,
  1023. "use Return instead of ReturnRef to return a value");
  1024. return Action<F>(new Impl<F>(ref_));
  1025. }
  1026. private:
  1027. // Implements the ReturnRef(x) action for a particular function type F.
  1028. template <typename F>
  1029. class Impl : public ActionInterface<F> {
  1030. public:
  1031. typedef typename Function<F>::Result Result;
  1032. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  1033. explicit Impl(T& ref) : ref_(ref) {} // NOLINT
  1034. Result Perform(const ArgumentTuple&) override { return ref_; }
  1035. private:
  1036. T& ref_;
  1037. };
  1038. T& ref_;
  1039. };
  1040. // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
  1041. // used in any function that returns a reference to the type of x,
  1042. // regardless of the argument types.
  1043. template <typename T>
  1044. class ReturnRefOfCopyAction {
  1045. public:
  1046. // Constructs a ReturnRefOfCopyAction object from the reference to
  1047. // be returned.
  1048. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
  1049. // This template type conversion operator allows ReturnRefOfCopy(x) to be
  1050. // used in ANY function that returns a reference to x's type.
  1051. template <typename F>
  1052. operator Action<F>() const {
  1053. typedef typename Function<F>::Result Result;
  1054. // Asserts that the function return type is a reference. This
  1055. // catches the user error of using ReturnRefOfCopy(x) when Return(x)
  1056. // should be used, and generates some helpful error message.
  1057. static_assert(std::is_reference<Result>::value,
  1058. "use Return instead of ReturnRefOfCopy to return a value");
  1059. return Action<F>(new Impl<F>(value_));
  1060. }
  1061. private:
  1062. // Implements the ReturnRefOfCopy(x) action for a particular function type F.
  1063. template <typename F>
  1064. class Impl : public ActionInterface<F> {
  1065. public:
  1066. typedef typename Function<F>::Result Result;
  1067. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  1068. explicit Impl(const T& value) : value_(value) {} // NOLINT
  1069. Result Perform(const ArgumentTuple&) override { return value_; }
  1070. private:
  1071. T value_;
  1072. };
  1073. const T value_;
  1074. };
  1075. // Implements the polymorphic ReturnRoundRobin(v) action, which can be
  1076. // used in any function that returns the element_type of v.
  1077. template <typename T>
  1078. class ReturnRoundRobinAction {
  1079. public:
  1080. explicit ReturnRoundRobinAction(std::vector<T> values) {
  1081. GTEST_CHECK_(!values.empty())
  1082. << "ReturnRoundRobin requires at least one element.";
  1083. state_->values = std::move(values);
  1084. }
  1085. template <typename... Args>
  1086. T operator()(Args&&...) const {
  1087. return state_->Next();
  1088. }
  1089. private:
  1090. struct State {
  1091. T Next() {
  1092. T ret_val = values[i++];
  1093. if (i == values.size()) i = 0;
  1094. return ret_val;
  1095. }
  1096. std::vector<T> values;
  1097. size_t i = 0;
  1098. };
  1099. std::shared_ptr<State> state_ = std::make_shared<State>();
  1100. };
  1101. // Implements the polymorphic DoDefault() action.
  1102. class DoDefaultAction {
  1103. public:
  1104. // This template type conversion operator allows DoDefault() to be
  1105. // used in any function.
  1106. template <typename F>
  1107. operator Action<F>() const {
  1108. return Action<F>();
  1109. } // NOLINT
  1110. };
  1111. // Implements the Assign action to set a given pointer referent to a
  1112. // particular value.
  1113. template <typename T1, typename T2>
  1114. class AssignAction {
  1115. public:
  1116. AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
  1117. template <typename Result, typename ArgumentTuple>
  1118. void Perform(const ArgumentTuple& /* args */) const {
  1119. *ptr_ = value_;
  1120. }
  1121. private:
  1122. T1* const ptr_;
  1123. const T2 value_;
  1124. };
  1125. #if !GTEST_OS_WINDOWS_MOBILE
  1126. // Implements the SetErrnoAndReturn action to simulate return from
  1127. // various system calls and libc functions.
  1128. template <typename T>
  1129. class SetErrnoAndReturnAction {
  1130. public:
  1131. SetErrnoAndReturnAction(int errno_value, T result)
  1132. : errno_(errno_value), result_(result) {}
  1133. template <typename Result, typename ArgumentTuple>
  1134. Result Perform(const ArgumentTuple& /* args */) const {
  1135. errno = errno_;
  1136. return result_;
  1137. }
  1138. private:
  1139. const int errno_;
  1140. const T result_;
  1141. };
  1142. #endif // !GTEST_OS_WINDOWS_MOBILE
  1143. // Implements the SetArgumentPointee<N>(x) action for any function
  1144. // whose N-th argument (0-based) is a pointer to x's type.
  1145. template <size_t N, typename A, typename = void>
  1146. struct SetArgumentPointeeAction {
  1147. A value;
  1148. template <typename... Args>
  1149. void operator()(const Args&... args) const {
  1150. *::std::get<N>(std::tie(args...)) = value;
  1151. }
  1152. };
  1153. // Implements the Invoke(object_ptr, &Class::Method) action.
  1154. template <class Class, typename MethodPtr>
  1155. struct InvokeMethodAction {
  1156. Class* const obj_ptr;
  1157. const MethodPtr method_ptr;
  1158. template <typename... Args>
  1159. auto operator()(Args&&... args) const
  1160. -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
  1161. return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
  1162. }
  1163. };
  1164. // Implements the InvokeWithoutArgs(f) action. The template argument
  1165. // FunctionImpl is the implementation type of f, which can be either a
  1166. // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
  1167. // Action<F> as long as f's type is compatible with F.
  1168. template <typename FunctionImpl>
  1169. struct InvokeWithoutArgsAction {
  1170. FunctionImpl function_impl;
  1171. // Allows InvokeWithoutArgs(f) to be used as any action whose type is
  1172. // compatible with f.
  1173. template <typename... Args>
  1174. auto operator()(const Args&...) -> decltype(function_impl()) {
  1175. return function_impl();
  1176. }
  1177. };
  1178. // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
  1179. template <class Class, typename MethodPtr>
  1180. struct InvokeMethodWithoutArgsAction {
  1181. Class* const obj_ptr;
  1182. const MethodPtr method_ptr;
  1183. using ReturnType =
  1184. decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
  1185. template <typename... Args>
  1186. ReturnType operator()(const Args&...) const {
  1187. return (obj_ptr->*method_ptr)();
  1188. }
  1189. };
  1190. // Implements the IgnoreResult(action) action.
  1191. template <typename A>
  1192. class IgnoreResultAction {
  1193. public:
  1194. explicit IgnoreResultAction(const A& action) : action_(action) {}
  1195. template <typename F>
  1196. operator Action<F>() const {
  1197. // Assert statement belongs here because this is the best place to verify
  1198. // conditions on F. It produces the clearest error messages
  1199. // in most compilers.
  1200. // Impl really belongs in this scope as a local class but can't
  1201. // because MSVC produces duplicate symbols in different translation units
  1202. // in this case. Until MS fixes that bug we put Impl into the class scope
  1203. // and put the typedef both here (for use in assert statement) and
  1204. // in the Impl class. But both definitions must be the same.
  1205. typedef typename internal::Function<F>::Result Result;
  1206. // Asserts at compile time that F returns void.
  1207. static_assert(std::is_void<Result>::value, "Result type should be void.");
  1208. return Action<F>(new Impl<F>(action_));
  1209. }
  1210. private:
  1211. template <typename F>
  1212. class Impl : public ActionInterface<F> {
  1213. public:
  1214. typedef typename internal::Function<F>::Result Result;
  1215. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  1216. explicit Impl(const A& action) : action_(action) {}
  1217. void Perform(const ArgumentTuple& args) override {
  1218. // Performs the action and ignores its result.
  1219. action_.Perform(args);
  1220. }
  1221. private:
  1222. // Type OriginalFunction is the same as F except that its return
  1223. // type is IgnoredValue.
  1224. typedef
  1225. typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;
  1226. const Action<OriginalFunction> action_;
  1227. };
  1228. const A action_;
  1229. };
  1230. template <typename InnerAction, size_t... I>
  1231. struct WithArgsAction {
  1232. InnerAction inner_action;
  1233. // The signature of the function as seen by the inner action, given an out
  1234. // action with the given result and argument types.
  1235. template <typename R, typename... Args>
  1236. using InnerSignature =
  1237. R(typename std::tuple_element<I, std::tuple<Args...>>::type...);
  1238. // Rather than a call operator, we must define conversion operators to
  1239. // particular action types. This is necessary for embedded actions like
  1240. // DoDefault(), which rely on an action conversion operators rather than
  1241. // providing a call operator because even with a particular set of arguments
  1242. // they don't have a fixed return type.
  1243. template <typename R, typename... Args,
  1244. typename std::enable_if<
  1245. std::is_convertible<
  1246. InnerAction,
  1247. // Unfortunately we can't use the InnerSignature alias here;
  1248. // MSVC complains about the I parameter pack not being
  1249. // expanded (error C3520) despite it being expanded in the
  1250. // type alias.
  1251. // TupleElement is also an MSVC workaround.
  1252. // See its definition for details.
  1253. OnceAction<R(internal::TupleElement<
  1254. I, std::tuple<Args...>>...)>>::value,
  1255. int>::type = 0>
  1256. operator OnceAction<R(Args...)>() && { // NOLINT
  1257. struct OA {
  1258. OnceAction<InnerSignature<R, Args...>> inner_action;
  1259. R operator()(Args&&... args) && {
  1260. return std::move(inner_action)
  1261. .Call(std::get<I>(
  1262. std::forward_as_tuple(std::forward<Args>(args)...))...);
  1263. }
  1264. };
  1265. return OA{std::move(inner_action)};
  1266. }
  1267. template <typename R, typename... Args,
  1268. typename std::enable_if<
  1269. std::is_convertible<
  1270. const InnerAction&,
  1271. // Unfortunately we can't use the InnerSignature alias here;
  1272. // MSVC complains about the I parameter pack not being
  1273. // expanded (error C3520) despite it being expanded in the
  1274. // type alias.
  1275. // TupleElement is also an MSVC workaround.
  1276. // See its definition for details.
  1277. Action<R(internal::TupleElement<
  1278. I, std::tuple<Args...>>...)>>::value,
  1279. int>::type = 0>
  1280. operator Action<R(Args...)>() const { // NOLINT
  1281. Action<InnerSignature<R, Args...>> converted(inner_action);
  1282. return [converted](Args&&... args) -> R {
  1283. return converted.Perform(std::forward_as_tuple(
  1284. std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
  1285. };
  1286. }
  1287. };
  1288. template <typename... Actions>
  1289. class DoAllAction;
  1290. // Base case: only a single action.
  1291. template <typename FinalAction>
  1292. class DoAllAction<FinalAction> {
  1293. public:
  1294. struct UserConstructorTag {};
  1295. template <typename T>
  1296. explicit DoAllAction(UserConstructorTag, T&& action)
  1297. : final_action_(std::forward<T>(action)) {}
  1298. // Rather than a call operator, we must define conversion operators to
  1299. // particular action types. This is necessary for embedded actions like
  1300. // DoDefault(), which rely on an action conversion operators rather than
  1301. // providing a call operator because even with a particular set of arguments
  1302. // they don't have a fixed return type.
  1303. template <typename R, typename... Args,
  1304. typename std::enable_if<
  1305. std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,
  1306. int>::type = 0>
  1307. operator OnceAction<R(Args...)>() && { // NOLINT
  1308. return std::move(final_action_);
  1309. }
  1310. template <
  1311. typename R, typename... Args,
  1312. typename std::enable_if<
  1313. std::is_convertible<const FinalAction&, Action<R(Args...)>>::value,
  1314. int>::type = 0>
  1315. operator Action<R(Args...)>() const { // NOLINT
  1316. return final_action_;
  1317. }
  1318. private:
  1319. FinalAction final_action_;
  1320. };
  1321. // Recursive case: support N actions by calling the initial action and then
  1322. // calling through to the base class containing N-1 actions.
  1323. template <typename InitialAction, typename... OtherActions>
  1324. class DoAllAction<InitialAction, OtherActions...>
  1325. : private DoAllAction<OtherActions...> {
  1326. private:
  1327. using Base = DoAllAction<OtherActions...>;
  1328. // The type of reference that should be provided to an initial action for a
  1329. // mocked function parameter of type T.
  1330. //
  1331. // There are two quirks here:
  1332. //
  1333. // * Unlike most forwarding functions, we pass scalars through by value.
  1334. // This isn't strictly necessary because an lvalue reference would work
  1335. // fine too and be consistent with other non-reference types, but it's
  1336. // perhaps less surprising.
  1337. //
  1338. // For example if the mocked function has signature void(int), then it
  1339. // might seem surprising for the user's initial action to need to be
  1340. // convertible to Action<void(const int&)>. This is perhaps less
  1341. // surprising for a non-scalar type where there may be a performance
  1342. // impact, or it might even be impossible, to pass by value.
  1343. //
  1344. // * More surprisingly, `const T&` is often not a const reference type.
  1345. // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to
  1346. // U& or U&& for some non-scalar type U, then InitialActionArgType<T> is
  1347. // U&. In other words, we may hand over a non-const reference.
  1348. //
  1349. // So for example, given some non-scalar type Obj we have the following
  1350. // mappings:
  1351. //
  1352. // T InitialActionArgType<T>
  1353. // ------- -----------------------
  1354. // Obj const Obj&
  1355. // Obj& Obj&
  1356. // Obj&& Obj&
  1357. // const Obj const Obj&
  1358. // const Obj& const Obj&
  1359. // const Obj&& const Obj&
  1360. //
  1361. // In other words, the initial actions get a mutable view of an non-scalar
  1362. // argument if and only if the mock function itself accepts a non-const
  1363. // reference type. They are never given an rvalue reference to an
  1364. // non-scalar type.
  1365. //
  1366. // This situation makes sense if you imagine use with a matcher that is
  1367. // designed to write through a reference. For example, if the caller wants
  1368. // to fill in a reference argument and then return a canned value:
  1369. //
  1370. // EXPECT_CALL(mock, Call)
  1371. // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19)));
  1372. //
  1373. template <typename T>
  1374. using InitialActionArgType =
  1375. typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
  1376. public:
  1377. struct UserConstructorTag {};
  1378. template <typename T, typename... U>
  1379. explicit DoAllAction(UserConstructorTag, T&& initial_action,
  1380. U&&... other_actions)
  1381. : Base({}, std::forward<U>(other_actions)...),
  1382. initial_action_(std::forward<T>(initial_action)) {}
  1383. template <typename R, typename... Args,
  1384. typename std::enable_if<
  1385. conjunction<
  1386. // Both the initial action and the rest must support
  1387. // conversion to OnceAction.
  1388. std::is_convertible<
  1389. InitialAction,
  1390. OnceAction<void(InitialActionArgType<Args>...)>>,
  1391. std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
  1392. int>::type = 0>
  1393. operator OnceAction<R(Args...)>() && { // NOLINT
  1394. // Return an action that first calls the initial action with arguments
  1395. // filtered through InitialActionArgType, then forwards arguments directly
  1396. // to the base class to deal with the remaining actions.
  1397. struct OA {
  1398. OnceAction<void(InitialActionArgType<Args>...)> initial_action;
  1399. OnceAction<R(Args...)> remaining_actions;
  1400. R operator()(Args... args) && {
  1401. std::move(initial_action)
  1402. .Call(static_cast<InitialActionArgType<Args>>(args)...);
  1403. return std::move(remaining_actions).Call(std::forward<Args>(args)...);
  1404. }
  1405. };
  1406. return OA{
  1407. std::move(initial_action_),
  1408. std::move(static_cast<Base&>(*this)),
  1409. };
  1410. }
  1411. template <
  1412. typename R, typename... Args,
  1413. typename std::enable_if<
  1414. conjunction<
  1415. // Both the initial action and the rest must support conversion to
  1416. // Action.
  1417. std::is_convertible<const InitialAction&,
  1418. Action<void(InitialActionArgType<Args>...)>>,
  1419. std::is_convertible<const Base&, Action<R(Args...)>>>::value,
  1420. int>::type = 0>
  1421. operator Action<R(Args...)>() const { // NOLINT
  1422. // Return an action that first calls the initial action with arguments
  1423. // filtered through InitialActionArgType, then forwards arguments directly
  1424. // to the base class to deal with the remaining actions.
  1425. struct OA {
  1426. Action<void(InitialActionArgType<Args>...)> initial_action;
  1427. Action<R(Args...)> remaining_actions;
  1428. R operator()(Args... args) const {
  1429. initial_action.Perform(std::forward_as_tuple(
  1430. static_cast<InitialActionArgType<Args>>(args)...));
  1431. return remaining_actions.Perform(
  1432. std::forward_as_tuple(std::forward<Args>(args)...));
  1433. }
  1434. };
  1435. return OA{
  1436. initial_action_,
  1437. static_cast<const Base&>(*this),
  1438. };
  1439. }
  1440. private:
  1441. InitialAction initial_action_;
  1442. };
  1443. template <typename T, typename... Params>
  1444. struct ReturnNewAction {
  1445. T* operator()() const {
  1446. return internal::Apply(
  1447. [](const Params&... unpacked_params) {
  1448. return new T(unpacked_params...);
  1449. },
  1450. params);
  1451. }
  1452. std::tuple<Params...> params;
  1453. };
  1454. template <size_t k>
  1455. struct ReturnArgAction {
  1456. template <typename... Args,
  1457. typename = typename std::enable_if<(k < sizeof...(Args))>::type>
  1458. auto operator()(Args&&... args) const -> decltype(std::get<k>(
  1459. std::forward_as_tuple(std::forward<Args>(args)...))) {
  1460. return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));
  1461. }
  1462. };
  1463. template <size_t k, typename Ptr>
  1464. struct SaveArgAction {
  1465. Ptr pointer;
  1466. template <typename... Args>
  1467. void operator()(const Args&... args) const {
  1468. *pointer = std::get<k>(std::tie(args...));
  1469. }
  1470. };
  1471. template <size_t k, typename Ptr>
  1472. struct SaveArgPointeeAction {
  1473. Ptr pointer;
  1474. template <typename... Args>
  1475. void operator()(const Args&... args) const {
  1476. *pointer = *std::get<k>(std::tie(args...));
  1477. }
  1478. };
  1479. template <size_t k, typename T>
  1480. struct SetArgRefereeAction {
  1481. T value;
  1482. template <typename... Args>
  1483. void operator()(Args&&... args) const {
  1484. using argk_type =
  1485. typename ::std::tuple_element<k, std::tuple<Args...>>::type;
  1486. static_assert(std::is_lvalue_reference<argk_type>::value,
  1487. "Argument must be a reference type.");
  1488. std::get<k>(std::tie(args...)) = value;
  1489. }
  1490. };
  1491. template <size_t k, typename I1, typename I2>
  1492. struct SetArrayArgumentAction {
  1493. I1 first;
  1494. I2 last;
  1495. template <typename... Args>
  1496. void operator()(const Args&... args) const {
  1497. auto value = std::get<k>(std::tie(args...));
  1498. for (auto it = first; it != last; ++it, (void)++value) {
  1499. *value = *it;
  1500. }
  1501. }
  1502. };
  1503. template <size_t k>
  1504. struct DeleteArgAction {
  1505. template <typename... Args>
  1506. void operator()(const Args&... args) const {
  1507. delete std::get<k>(std::tie(args...));
  1508. }
  1509. };
  1510. template <typename Ptr>
  1511. struct ReturnPointeeAction {
  1512. Ptr pointer;
  1513. template <typename... Args>
  1514. auto operator()(const Args&...) const -> decltype(*pointer) {
  1515. return *pointer;
  1516. }
  1517. };
  1518. #if GTEST_HAS_EXCEPTIONS
  1519. template <typename T>
  1520. struct ThrowAction {
  1521. T exception;
  1522. // We use a conversion operator to adapt to any return type.
  1523. template <typename R, typename... Args>
  1524. operator Action<R(Args...)>() const { // NOLINT
  1525. T copy = exception;
  1526. return [copy](Args...) -> R { throw copy; };
  1527. }
  1528. };
  1529. #endif // GTEST_HAS_EXCEPTIONS
  1530. } // namespace internal
  1531. // An Unused object can be implicitly constructed from ANY value.
  1532. // This is handy when defining actions that ignore some or all of the
  1533. // mock function arguments. For example, given
  1534. //
  1535. // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
  1536. // MOCK_METHOD3(Bar, double(int index, double x, double y));
  1537. //
  1538. // instead of
  1539. //
  1540. // double DistanceToOriginWithLabel(const string& label, double x, double y) {
  1541. // return sqrt(x*x + y*y);
  1542. // }
  1543. // double DistanceToOriginWithIndex(int index, double x, double y) {
  1544. // return sqrt(x*x + y*y);
  1545. // }
  1546. // ...
  1547. // EXPECT_CALL(mock, Foo("abc", _, _))
  1548. // .WillOnce(Invoke(DistanceToOriginWithLabel));
  1549. // EXPECT_CALL(mock, Bar(5, _, _))
  1550. // .WillOnce(Invoke(DistanceToOriginWithIndex));
  1551. //
  1552. // you could write
  1553. //
  1554. // // We can declare any uninteresting argument as Unused.
  1555. // double DistanceToOrigin(Unused, double x, double y) {
  1556. // return sqrt(x*x + y*y);
  1557. // }
  1558. // ...
  1559. // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
  1560. // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
  1561. typedef internal::IgnoredValue Unused;
  1562. // Creates an action that does actions a1, a2, ..., sequentially in
  1563. // each invocation. All but the last action will have a readonly view of the
  1564. // arguments.
  1565. template <typename... Action>
  1566. internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
  1567. Action&&... action) {
  1568. return internal::DoAllAction<typename std::decay<Action>::type...>(
  1569. {}, std::forward<Action>(action)...);
  1570. }
  1571. // WithArg<k>(an_action) creates an action that passes the k-th
  1572. // (0-based) argument of the mock function to an_action and performs
  1573. // it. It adapts an action accepting one argument to one that accepts
  1574. // multiple arguments. For convenience, we also provide
  1575. // WithArgs<k>(an_action) (defined below) as a synonym.
  1576. template <size_t k, typename InnerAction>
  1577. internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(
  1578. InnerAction&& action) {
  1579. return {std::forward<InnerAction>(action)};
  1580. }
  1581. // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
  1582. // the selected arguments of the mock function to an_action and
  1583. // performs it. It serves as an adaptor between actions with
  1584. // different argument lists.
  1585. template <size_t k, size_t... ks, typename InnerAction>
  1586. internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
  1587. WithArgs(InnerAction&& action) {
  1588. return {std::forward<InnerAction>(action)};
  1589. }
  1590. // WithoutArgs(inner_action) can be used in a mock function with a
  1591. // non-empty argument list to perform inner_action, which takes no
  1592. // argument. In other words, it adapts an action accepting no
  1593. // argument to one that accepts (and ignores) arguments.
  1594. template <typename InnerAction>
  1595. internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(
  1596. InnerAction&& action) {
  1597. return {std::forward<InnerAction>(action)};
  1598. }
  1599. // Creates an action that returns a value.
  1600. //
  1601. // The returned type can be used with a mock function returning a non-void,
  1602. // non-reference type U as follows:
  1603. //
  1604. // * If R is convertible to U and U is move-constructible, then the action can
  1605. // be used with WillOnce.
  1606. //
  1607. // * If const R& is convertible to U and U is copy-constructible, then the
  1608. // action can be used with both WillOnce and WillRepeatedly.
  1609. //
  1610. // The mock expectation contains the R value from which the U return value is
  1611. // constructed (a move/copy of the argument to Return). This means that the R
  1612. // value will survive at least until the mock object's expectations are cleared
  1613. // or the mock object is destroyed, meaning that U can safely be a
  1614. // reference-like type such as std::string_view:
  1615. //
  1616. // // The mock function returns a view of a copy of the string fed to
  1617. // // Return. The view is valid even after the action is performed.
  1618. // MockFunction<std::string_view()> mock;
  1619. // EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco")));
  1620. // const std::string_view result = mock.AsStdFunction()();
  1621. // EXPECT_EQ("taco", result);
  1622. //
  1623. template <typename R>
  1624. internal::ReturnAction<R> Return(R value) {
  1625. return internal::ReturnAction<R>(std::move(value));
  1626. }
  1627. // Creates an action that returns NULL.
  1628. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
  1629. return MakePolymorphicAction(internal::ReturnNullAction());
  1630. }
  1631. // Creates an action that returns from a void function.
  1632. inline PolymorphicAction<internal::ReturnVoidAction> Return() {
  1633. return MakePolymorphicAction(internal::ReturnVoidAction());
  1634. }
  1635. // Creates an action that returns the reference to a variable.
  1636. template <typename R>
  1637. inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
  1638. return internal::ReturnRefAction<R>(x);
  1639. }
  1640. // Prevent using ReturnRef on reference to temporary.
  1641. template <typename R, R* = nullptr>
  1642. internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
  1643. // Creates an action that returns the reference to a copy of the
  1644. // argument. The copy is created when the action is constructed and
  1645. // lives as long as the action.
  1646. template <typename R>
  1647. inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
  1648. return internal::ReturnRefOfCopyAction<R>(x);
  1649. }
  1650. // DEPRECATED: use Return(x) directly with WillOnce.
  1651. //
  1652. // Modifies the parent action (a Return() action) to perform a move of the
  1653. // argument instead of a copy.
  1654. // Return(ByMove()) actions can only be executed once and will assert this
  1655. // invariant.
  1656. template <typename R>
  1657. internal::ByMoveWrapper<R> ByMove(R x) {
  1658. return internal::ByMoveWrapper<R>(std::move(x));
  1659. }
  1660. // Creates an action that returns an element of `vals`. Calling this action will
  1661. // repeatedly return the next value from `vals` until it reaches the end and
  1662. // will restart from the beginning.
  1663. template <typename T>
  1664. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
  1665. return internal::ReturnRoundRobinAction<T>(std::move(vals));
  1666. }
  1667. // Creates an action that returns an element of `vals`. Calling this action will
  1668. // repeatedly return the next value from `vals` until it reaches the end and
  1669. // will restart from the beginning.
  1670. template <typename T>
  1671. internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
  1672. std::initializer_list<T> vals) {
  1673. return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
  1674. }
  1675. // Creates an action that does the default action for the give mock function.
  1676. inline internal::DoDefaultAction DoDefault() {
  1677. return internal::DoDefaultAction();
  1678. }
  1679. // Creates an action that sets the variable pointed by the N-th
  1680. // (0-based) function argument to 'value'.
  1681. template <size_t N, typename T>
  1682. internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
  1683. return {std::move(value)};
  1684. }
  1685. // The following version is DEPRECATED.
  1686. template <size_t N, typename T>
  1687. internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
  1688. return {std::move(value)};
  1689. }
  1690. // Creates an action that sets a pointer referent to a given value.
  1691. template <typename T1, typename T2>
  1692. PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
  1693. return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
  1694. }
  1695. #if !GTEST_OS_WINDOWS_MOBILE
  1696. // Creates an action that sets errno and returns the appropriate error.
  1697. template <typename T>
  1698. PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
  1699. int errval, T result) {
  1700. return MakePolymorphicAction(
  1701. internal::SetErrnoAndReturnAction<T>(errval, result));
  1702. }
  1703. #endif // !GTEST_OS_WINDOWS_MOBILE
  1704. // Various overloads for Invoke().
  1705. // Legacy function.
  1706. // Actions can now be implicitly constructed from callables. No need to create
  1707. // wrapper objects.
  1708. // This function exists for backwards compatibility.
  1709. template <typename FunctionImpl>
  1710. typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
  1711. return std::forward<FunctionImpl>(function_impl);
  1712. }
  1713. // Creates an action that invokes the given method on the given object
  1714. // with the mock function's arguments.
  1715. template <class Class, typename MethodPtr>
  1716. internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
  1717. MethodPtr method_ptr) {
  1718. return {obj_ptr, method_ptr};
  1719. }
  1720. // Creates an action that invokes 'function_impl' with no argument.
  1721. template <typename FunctionImpl>
  1722. internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
  1723. InvokeWithoutArgs(FunctionImpl function_impl) {
  1724. return {std::move(function_impl)};
  1725. }
  1726. // Creates an action that invokes the given method on the given object
  1727. // with no argument.
  1728. template <class Class, typename MethodPtr>
  1729. internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
  1730. Class* obj_ptr, MethodPtr method_ptr) {
  1731. return {obj_ptr, method_ptr};
  1732. }
  1733. // Creates an action that performs an_action and throws away its
  1734. // result. In other words, it changes the return type of an_action to
  1735. // void. an_action MUST NOT return void, or the code won't compile.
  1736. template <typename A>
  1737. inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
  1738. return internal::IgnoreResultAction<A>(an_action);
  1739. }
  1740. // Creates a reference wrapper for the given L-value. If necessary,
  1741. // you can explicitly specify the type of the reference. For example,
  1742. // suppose 'derived' is an object of type Derived, ByRef(derived)
  1743. // would wrap a Derived&. If you want to wrap a const Base& instead,
  1744. // where Base is a base class of Derived, just write:
  1745. //
  1746. // ByRef<const Base>(derived)
  1747. //
  1748. // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
  1749. // However, it may still be used for consistency with ByMove().
  1750. template <typename T>
  1751. inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
  1752. return ::std::reference_wrapper<T>(l_value);
  1753. }
  1754. // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
  1755. // instance of type T, constructed on the heap with constructor arguments
  1756. // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
  1757. template <typename T, typename... Params>
  1758. internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
  1759. Params&&... params) {
  1760. return {std::forward_as_tuple(std::forward<Params>(params)...)};
  1761. }
  1762. // Action ReturnArg<k>() returns the k-th argument of the mock function.
  1763. template <size_t k>
  1764. internal::ReturnArgAction<k> ReturnArg() {
  1765. return {};
  1766. }
  1767. // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
  1768. // mock function to *pointer.
  1769. template <size_t k, typename Ptr>
  1770. internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
  1771. return {pointer};
  1772. }
  1773. // Action SaveArgPointee<k>(pointer) saves the value pointed to
  1774. // by the k-th (0-based) argument of the mock function to *pointer.
  1775. template <size_t k, typename Ptr>
  1776. internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
  1777. return {pointer};
  1778. }
  1779. // Action SetArgReferee<k>(value) assigns 'value' to the variable
  1780. // referenced by the k-th (0-based) argument of the mock function.
  1781. template <size_t k, typename T>
  1782. internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
  1783. T&& value) {
  1784. return {std::forward<T>(value)};
  1785. }
  1786. // Action SetArrayArgument<k>(first, last) copies the elements in
  1787. // source range [first, last) to the array pointed to by the k-th
  1788. // (0-based) argument, which can be either a pointer or an
  1789. // iterator. The action does not take ownership of the elements in the
  1790. // source range.
  1791. template <size_t k, typename I1, typename I2>
  1792. internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
  1793. I2 last) {
  1794. return {first, last};
  1795. }
  1796. // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
  1797. // function.
  1798. template <size_t k>
  1799. internal::DeleteArgAction<k> DeleteArg() {
  1800. return {};
  1801. }
  1802. // This action returns the value pointed to by 'pointer'.
  1803. template <typename Ptr>
  1804. internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
  1805. return {pointer};
  1806. }
  1807. // Action Throw(exception) can be used in a mock function of any type
  1808. // to throw the given exception. Any copyable value can be thrown.
  1809. #if GTEST_HAS_EXCEPTIONS
  1810. template <typename T>
  1811. internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
  1812. return {std::forward<T>(exception)};
  1813. }
  1814. #endif // GTEST_HAS_EXCEPTIONS
  1815. namespace internal {
  1816. // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
  1817. // defines an action that can be used in a mock function. Typically,
  1818. // these actions only care about a subset of the arguments of the mock
  1819. // function. For example, if such an action only uses the second
  1820. // argument, it can be used in any mock function that takes >= 2
  1821. // arguments where the type of the second argument is compatible.
  1822. //
  1823. // Therefore, the action implementation must be prepared to take more
  1824. // arguments than it needs. The ExcessiveArg type is used to
  1825. // represent those excessive arguments. In order to keep the compiler
  1826. // error messages tractable, we define it in the testing namespace
  1827. // instead of testing::internal. However, this is an INTERNAL TYPE
  1828. // and subject to change without notice, so a user MUST NOT USE THIS
  1829. // TYPE DIRECTLY.
  1830. struct ExcessiveArg {};
  1831. // Builds an implementation of an Action<> for some particular signature, using
  1832. // a class defined by an ACTION* macro.
  1833. template <typename F, typename Impl>
  1834. struct ActionImpl;
  1835. template <typename Impl>
  1836. struct ImplBase {
  1837. struct Holder {
  1838. // Allows each copy of the Action<> to get to the Impl.
  1839. explicit operator const Impl&() const { return *ptr; }
  1840. std::shared_ptr<Impl> ptr;
  1841. };
  1842. using type = typename std::conditional<std::is_constructible<Impl>::value,
  1843. Impl, Holder>::type;
  1844. };
  1845. template <typename R, typename... Args, typename Impl>
  1846. struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
  1847. using Base = typename ImplBase<Impl>::type;
  1848. using function_type = R(Args...);
  1849. using args_type = std::tuple<Args...>;
  1850. ActionImpl() = default; // Only defined if appropriate for Base.
  1851. explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {}
  1852. R operator()(Args&&... arg) const {
  1853. static constexpr size_t kMaxArgs =
  1854. sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
  1855. return Apply(MakeIndexSequence<kMaxArgs>{},
  1856. MakeIndexSequence<10 - kMaxArgs>{},
  1857. args_type{std::forward<Args>(arg)...});
  1858. }
  1859. template <std::size_t... arg_id, std::size_t... excess_id>
  1860. R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
  1861. const args_type& args) const {
  1862. // Impl need not be specific to the signature of action being implemented;
  1863. // only the implementing function body needs to have all of the specific
  1864. // types instantiated. Up to 10 of the args that are provided by the
  1865. // args_type get passed, followed by a dummy of unspecified type for the
  1866. // remainder up to 10 explicit args.
  1867. static constexpr ExcessiveArg kExcessArg{};
  1868. return static_cast<const Impl&>(*this)
  1869. .template gmock_PerformImpl<
  1870. /*function_type=*/function_type, /*return_type=*/R,
  1871. /*args_type=*/args_type,
  1872. /*argN_type=*/
  1873. typename std::tuple_element<arg_id, args_type>::type...>(
  1874. /*args=*/args, std::get<arg_id>(args)...,
  1875. ((void)excess_id, kExcessArg)...);
  1876. }
  1877. };
  1878. // Stores a default-constructed Impl as part of the Action<>'s
  1879. // std::function<>. The Impl should be trivial to copy.
  1880. template <typename F, typename Impl>
  1881. ::testing::Action<F> MakeAction() {
  1882. return ::testing::Action<F>(ActionImpl<F, Impl>());
  1883. }
  1884. // Stores just the one given instance of Impl.
  1885. template <typename F, typename Impl>
  1886. ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
  1887. return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
  1888. }
  1889. #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
  1890. , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
  1891. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
  1892. const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
  1893. GMOCK_INTERNAL_ARG_UNUSED, , 10)
  1894. #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
  1895. #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
  1896. const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
  1897. #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
  1898. #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
  1899. GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
  1900. #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
  1901. #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
  1902. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
  1903. #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
  1904. #define GMOCK_ACTION_TYPE_PARAMS_(params) \
  1905. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
  1906. #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
  1907. , param##_type gmock_p##i
  1908. #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
  1909. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
  1910. #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
  1911. , std::forward<param##_type>(gmock_p##i)
  1912. #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
  1913. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
  1914. #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
  1915. , param(::std::forward<param##_type>(gmock_p##i))
  1916. #define GMOCK_ACTION_INIT_PARAMS_(params) \
  1917. GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
  1918. #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
  1919. #define GMOCK_ACTION_FIELD_PARAMS_(params) \
  1920. GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
  1921. #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
  1922. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1923. class full_name { \
  1924. public: \
  1925. explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
  1926. : impl_(std::make_shared<gmock_Impl>( \
  1927. GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \
  1928. full_name(const full_name&) = default; \
  1929. full_name(full_name&&) noexcept = default; \
  1930. template <typename F> \
  1931. operator ::testing::Action<F>() const { \
  1932. return ::testing::internal::MakeAction<F>(impl_); \
  1933. } \
  1934. \
  1935. private: \
  1936. class gmock_Impl { \
  1937. public: \
  1938. explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
  1939. : GMOCK_ACTION_INIT_PARAMS_(params) {} \
  1940. template <typename function_type, typename return_type, \
  1941. typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1942. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  1943. GMOCK_ACTION_FIELD_PARAMS_(params) \
  1944. }; \
  1945. std::shared_ptr<const gmock_Impl> impl_; \
  1946. }; \
  1947. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1948. inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
  1949. GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \
  1950. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1951. inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
  1952. GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
  1953. return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
  1954. GMOCK_ACTION_GVALUE_PARAMS_(params)); \
  1955. } \
  1956. template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
  1957. template <typename function_type, typename return_type, typename args_type, \
  1958. GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1959. return_type \
  1960. full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \
  1961. GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  1962. } // namespace internal
  1963. // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
  1964. #define ACTION(name) \
  1965. class name##Action { \
  1966. public: \
  1967. explicit name##Action() noexcept {} \
  1968. name##Action(const name##Action&) noexcept {} \
  1969. template <typename F> \
  1970. operator ::testing::Action<F>() const { \
  1971. return ::testing::internal::MakeAction<F, gmock_Impl>(); \
  1972. } \
  1973. \
  1974. private: \
  1975. class gmock_Impl { \
  1976. public: \
  1977. template <typename function_type, typename return_type, \
  1978. typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1979. return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
  1980. }; \
  1981. }; \
  1982. inline name##Action name() GTEST_MUST_USE_RESULT_; \
  1983. inline name##Action name() { return name##Action(); } \
  1984. template <typename function_type, typename return_type, typename args_type, \
  1985. GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
  1986. return_type name##Action::gmock_Impl::gmock_PerformImpl( \
  1987. GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
  1988. #define ACTION_P(name, ...) \
  1989. GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
  1990. #define ACTION_P2(name, ...) \
  1991. GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
  1992. #define ACTION_P3(name, ...) \
  1993. GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
  1994. #define ACTION_P4(name, ...) \
  1995. GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
  1996. #define ACTION_P5(name, ...) \
  1997. GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
  1998. #define ACTION_P6(name, ...) \
  1999. GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
  2000. #define ACTION_P7(name, ...) \
  2001. GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
  2002. #define ACTION_P8(name, ...) \
  2003. GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
  2004. #define ACTION_P9(name, ...) \
  2005. GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
  2006. #define ACTION_P10(name, ...) \
  2007. GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
  2008. } // namespace testing
  2009. #ifdef _MSC_VER
  2010. #pragma warning(pop)
  2011. #endif
  2012. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_