gmock-actions.h 87 KB

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