gmock-actions.h 86 KB

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