gmock-actions_test.cc 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  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. // This file tests the built-in actions.
  32. #include "gmock/gmock-actions.h"
  33. #include <algorithm>
  34. #include <functional>
  35. #include <iterator>
  36. #include <memory>
  37. #include <sstream>
  38. #include <string>
  39. #include <tuple>
  40. #include <type_traits>
  41. #include <utility>
  42. #include <vector>
  43. #include "gmock/gmock.h"
  44. #include "gmock/internal/gmock-port.h"
  45. #include "gtest/gtest-spi.h"
  46. #include "gtest/gtest.h"
  47. #include "gtest/internal/gtest-port.h"
  48. // Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
  49. // length exceeded) for MSVC.
  50. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503)
  51. #if defined(_MSC_VER) && (_MSC_VER == 1900)
  52. // and silence C4800 (C4800: 'int *const ': forcing value
  53. // to bool 'true' or 'false') for MSVC 15
  54. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
  55. #endif
  56. namespace testing {
  57. namespace {
  58. using ::testing::internal::BuiltInDefaultValue;
  59. TEST(TypeTraits, Negation) {
  60. // Direct use with std types.
  61. static_assert(std::is_base_of<std::false_type,
  62. internal::negation<std::true_type>>::value,
  63. "");
  64. static_assert(std::is_base_of<std::true_type,
  65. internal::negation<std::false_type>>::value,
  66. "");
  67. // With other types that fit the requirement of a value member that is
  68. // convertible to bool.
  69. static_assert(std::is_base_of<
  70. std::true_type,
  71. internal::negation<std::integral_constant<int, 0>>>::value,
  72. "");
  73. static_assert(std::is_base_of<
  74. std::false_type,
  75. internal::negation<std::integral_constant<int, 1>>>::value,
  76. "");
  77. static_assert(std::is_base_of<
  78. std::false_type,
  79. internal::negation<std::integral_constant<int, -1>>>::value,
  80. "");
  81. }
  82. // Weird false/true types that aren't actually bool constants (but should still
  83. // be legal according to [meta.logical] because `bool(T::value)` is valid), are
  84. // distinct from std::false_type and std::true_type, and are distinct from other
  85. // instantiations of the same template.
  86. //
  87. // These let us check finicky details mandated by the standard like
  88. // "std::conjunction should evaluate to a type that inherits from the first
  89. // false-y input".
  90. template <int>
  91. struct MyFalse : std::integral_constant<int, 0> {};
  92. template <int>
  93. struct MyTrue : std::integral_constant<int, -1> {};
  94. TEST(TypeTraits, Conjunction) {
  95. // Base case: always true.
  96. static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value,
  97. "");
  98. // One predicate: inherits from that predicate, regardless of value.
  99. static_assert(
  100. std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value,
  101. "");
  102. static_assert(
  103. std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, "");
  104. // Multiple predicates, with at least one false: inherits from that one.
  105. static_assert(
  106. std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
  107. MyTrue<2>>>::value,
  108. "");
  109. static_assert(
  110. std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
  111. MyFalse<2>>>::value,
  112. "");
  113. // Short circuiting: in the case above, additional predicates need not even
  114. // define a value member.
  115. struct Empty {};
  116. static_assert(
  117. std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
  118. Empty>>::value,
  119. "");
  120. // All predicates true: inherits from the last.
  121. static_assert(
  122. std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>,
  123. MyTrue<2>>>::value,
  124. "");
  125. }
  126. TEST(TypeTraits, Disjunction) {
  127. // Base case: always false.
  128. static_assert(
  129. std::is_base_of<std::false_type, internal::disjunction<>>::value, "");
  130. // One predicate: inherits from that predicate, regardless of value.
  131. static_assert(
  132. std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value,
  133. "");
  134. static_assert(
  135. std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, "");
  136. // Multiple predicates, with at least one true: inherits from that one.
  137. static_assert(
  138. std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
  139. MyFalse<2>>>::value,
  140. "");
  141. static_assert(
  142. std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
  143. MyTrue<2>>>::value,
  144. "");
  145. // Short circuiting: in the case above, additional predicates need not even
  146. // define a value member.
  147. struct Empty {};
  148. static_assert(
  149. std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
  150. Empty>>::value,
  151. "");
  152. // All predicates false: inherits from the last.
  153. static_assert(
  154. std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>,
  155. MyFalse<2>>>::value,
  156. "");
  157. }
  158. TEST(TypeTraits, IsInvocableRV) {
  159. struct C {
  160. int operator()() const { return 0; }
  161. void operator()(int) & {}
  162. std::string operator()(int) && { return ""; };
  163. };
  164. // The first overload is callable for const and non-const rvalues and lvalues.
  165. // It can be used to obtain an int, cv void, or anything int is convertible
  166. // to.
  167. static_assert(internal::is_callable_r<int, C>::value, "");
  168. static_assert(internal::is_callable_r<int, C&>::value, "");
  169. static_assert(internal::is_callable_r<int, const C>::value, "");
  170. static_assert(internal::is_callable_r<int, const C&>::value, "");
  171. static_assert(internal::is_callable_r<void, C>::value, "");
  172. static_assert(internal::is_callable_r<const volatile void, C>::value, "");
  173. static_assert(internal::is_callable_r<char, C>::value, "");
  174. // It's possible to provide an int. If it's given to an lvalue, the result is
  175. // void. Otherwise it is std::string (which is also treated as allowed for a
  176. // void result type).
  177. static_assert(internal::is_callable_r<void, C&, int>::value, "");
  178. static_assert(!internal::is_callable_r<int, C&, int>::value, "");
  179. static_assert(!internal::is_callable_r<std::string, C&, int>::value, "");
  180. static_assert(!internal::is_callable_r<void, const C&, int>::value, "");
  181. static_assert(internal::is_callable_r<std::string, C, int>::value, "");
  182. static_assert(internal::is_callable_r<void, C, int>::value, "");
  183. static_assert(!internal::is_callable_r<int, C, int>::value, "");
  184. // It's not possible to provide other arguments.
  185. static_assert(!internal::is_callable_r<void, C, std::string>::value, "");
  186. static_assert(!internal::is_callable_r<void, C, int, int>::value, "");
  187. // In C++17 and above, where it's guaranteed that functions can return
  188. // non-moveable objects, everything should work fine for non-moveable rsult
  189. // types too.
  190. // TODO(b/396121064) - Fix this test under MSVC
  191. #ifndef _MSC_VER
  192. {
  193. struct NonMoveable {
  194. NonMoveable() = default;
  195. NonMoveable(NonMoveable&&) = delete;
  196. };
  197. static_assert(!std::is_move_constructible_v<NonMoveable>);
  198. struct Callable {
  199. NonMoveable operator()() { return NonMoveable(); }
  200. };
  201. static_assert(internal::is_callable_r<NonMoveable, Callable>::value);
  202. static_assert(internal::is_callable_r<void, Callable>::value);
  203. static_assert(
  204. internal::is_callable_r<const volatile void, Callable>::value);
  205. static_assert(!internal::is_callable_r<int, Callable>::value);
  206. static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
  207. }
  208. #endif // _MSC_VER
  209. // Nothing should choke when we try to call other arguments besides directly
  210. // callable objects, but they should not show up as callable.
  211. static_assert(!internal::is_callable_r<void, int>::value, "");
  212. static_assert(!internal::is_callable_r<void, void (C::*)()>::value, "");
  213. static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, "");
  214. }
  215. // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
  216. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
  217. EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);
  218. EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);
  219. EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);
  220. }
  221. // Tests that BuiltInDefaultValue<T*>::Exists() return true.
  222. TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
  223. EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
  224. EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
  225. EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
  226. }
  227. // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
  228. // built-in numeric type.
  229. TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
  230. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
  231. EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
  232. EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
  233. #if GMOCK_WCHAR_T_IS_NATIVE_
  234. #if !defined(__WCHAR_UNSIGNED__)
  235. EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
  236. #else
  237. EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
  238. #endif
  239. #endif
  240. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
  241. EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
  242. EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
  243. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
  244. EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
  245. EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
  246. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
  247. EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
  248. EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
  249. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); // NOLINT
  250. EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); // NOLINT
  251. EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT
  252. EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
  253. EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
  254. }
  255. // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
  256. // built-in numeric type.
  257. TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
  258. EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
  259. EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
  260. EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
  261. #if GMOCK_WCHAR_T_IS_NATIVE_
  262. EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
  263. #endif
  264. EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
  265. EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
  266. EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
  267. EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
  268. EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
  269. EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
  270. EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
  271. EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
  272. EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
  273. EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT
  274. EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT
  275. EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT
  276. EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
  277. EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
  278. }
  279. // Tests that BuiltInDefaultValue<bool>::Get() returns false.
  280. TEST(BuiltInDefaultValueTest, IsFalseForBool) {
  281. EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
  282. }
  283. // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
  284. TEST(BuiltInDefaultValueTest, BoolExists) {
  285. EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
  286. }
  287. // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
  288. // string type.
  289. TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
  290. EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get());
  291. }
  292. // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
  293. // string type.
  294. TEST(BuiltInDefaultValueTest, ExistsForString) {
  295. EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());
  296. }
  297. // Tests that BuiltInDefaultValue<const T>::Get() returns the same
  298. // value as BuiltInDefaultValue<T>::Get() does.
  299. TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
  300. EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
  301. EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
  302. EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
  303. EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
  304. }
  305. // A type that's default constructible.
  306. class MyDefaultConstructible {
  307. public:
  308. MyDefaultConstructible() : value_(42) {}
  309. int value() const { return value_; }
  310. private:
  311. int value_;
  312. };
  313. // A type that's not default constructible.
  314. class MyNonDefaultConstructible {
  315. public:
  316. // Does not have a default ctor.
  317. explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
  318. int value() const { return value_; }
  319. private:
  320. int value_;
  321. };
  322. TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
  323. EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
  324. }
  325. TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
  326. EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
  327. }
  328. TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
  329. EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
  330. }
  331. // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
  332. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
  333. EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");
  334. EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");
  335. }
  336. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
  337. EXPECT_DEATH_IF_SUPPORTED(
  338. { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");
  339. }
  340. // Tests that DefaultValue<T>::IsSet() is false initially.
  341. TEST(DefaultValueTest, IsInitiallyUnset) {
  342. EXPECT_FALSE(DefaultValue<int>::IsSet());
  343. EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
  344. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
  345. }
  346. // Tests that DefaultValue<T> can be set and then unset.
  347. TEST(DefaultValueTest, CanBeSetAndUnset) {
  348. EXPECT_TRUE(DefaultValue<int>::Exists());
  349. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
  350. DefaultValue<int>::Set(1);
  351. DefaultValue<const MyNonDefaultConstructible>::Set(
  352. MyNonDefaultConstructible(42));
  353. EXPECT_EQ(1, DefaultValue<int>::Get());
  354. EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
  355. EXPECT_TRUE(DefaultValue<int>::Exists());
  356. EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
  357. DefaultValue<int>::Clear();
  358. DefaultValue<const MyNonDefaultConstructible>::Clear();
  359. EXPECT_FALSE(DefaultValue<int>::IsSet());
  360. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
  361. EXPECT_TRUE(DefaultValue<int>::Exists());
  362. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
  363. }
  364. // Tests that DefaultValue<T>::Get() returns the
  365. // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
  366. // false.
  367. TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
  368. EXPECT_FALSE(DefaultValue<int>::IsSet());
  369. EXPECT_TRUE(DefaultValue<int>::Exists());
  370. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
  371. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
  372. EXPECT_EQ(0, DefaultValue<int>::Get());
  373. EXPECT_DEATH_IF_SUPPORTED(
  374. { DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
  375. }
  376. TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
  377. EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
  378. EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
  379. DefaultValue<std::unique_ptr<int>>::SetFactory(
  380. [] { return std::make_unique<int>(42); });
  381. EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
  382. std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
  383. EXPECT_EQ(42, *i);
  384. }
  385. // Tests that DefaultValue<void>::Get() returns void.
  386. TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }
  387. // Tests using DefaultValue with a reference type.
  388. // Tests that DefaultValue<T&>::IsSet() is false initially.
  389. TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
  390. EXPECT_FALSE(DefaultValue<int&>::IsSet());
  391. EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
  392. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
  393. }
  394. // Tests that DefaultValue<T&>::Exists is false initially.
  395. TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
  396. EXPECT_FALSE(DefaultValue<int&>::Exists());
  397. EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
  398. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
  399. }
  400. // Tests that DefaultValue<T&> can be set and then unset.
  401. TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
  402. int n = 1;
  403. DefaultValue<const int&>::Set(n);
  404. MyNonDefaultConstructible x(42);
  405. DefaultValue<MyNonDefaultConstructible&>::Set(x);
  406. EXPECT_TRUE(DefaultValue<const int&>::Exists());
  407. EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
  408. EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
  409. EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
  410. DefaultValue<const int&>::Clear();
  411. DefaultValue<MyNonDefaultConstructible&>::Clear();
  412. EXPECT_FALSE(DefaultValue<const int&>::Exists());
  413. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
  414. EXPECT_FALSE(DefaultValue<const int&>::IsSet());
  415. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
  416. }
  417. // Tests that DefaultValue<T&>::Get() returns the
  418. // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
  419. // false.
  420. TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
  421. EXPECT_FALSE(DefaultValue<int&>::IsSet());
  422. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
  423. EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
  424. EXPECT_DEATH_IF_SUPPORTED(
  425. { DefaultValue<MyNonDefaultConstructible>::Get(); }, "");
  426. }
  427. // Tests that ActionInterface can be implemented by defining the
  428. // Perform method.
  429. typedef int MyGlobalFunction(bool, int);
  430. class MyActionImpl : public ActionInterface<MyGlobalFunction> {
  431. public:
  432. int Perform(const std::tuple<bool, int>& args) override {
  433. return std::get<0>(args) ? std::get<1>(args) : 0;
  434. }
  435. };
  436. TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
  437. MyActionImpl my_action_impl;
  438. (void)my_action_impl;
  439. }
  440. TEST(ActionInterfaceTest, MakeAction) {
  441. Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
  442. // When exercising the Perform() method of Action<F>, we must pass
  443. // it a tuple whose size and type are compatible with F's argument
  444. // types. For example, if F is int(), then Perform() takes a
  445. // 0-tuple; if F is void(bool, int), then Perform() takes a
  446. // std::tuple<bool, int>, and so on.
  447. EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
  448. }
  449. // Tests that Action<F> can be constructed from a pointer to
  450. // ActionInterface<F>.
  451. TEST(ActionTest, CanBeConstructedFromActionInterface) {
  452. Action<MyGlobalFunction> action(new MyActionImpl);
  453. }
  454. // Tests that Action<F> delegates actual work to ActionInterface<F>.
  455. TEST(ActionTest, DelegatesWorkToActionInterface) {
  456. const Action<MyGlobalFunction> action(new MyActionImpl);
  457. EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
  458. EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));
  459. }
  460. // Tests that Action<F> can be copied.
  461. TEST(ActionTest, IsCopyable) {
  462. Action<MyGlobalFunction> a1(new MyActionImpl);
  463. Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
  464. // a1 should continue to work after being copied from.
  465. EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  466. EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
  467. // a2 should work like the action it was copied from.
  468. EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
  469. EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
  470. a2 = a1; // Tests the assignment operator.
  471. // a1 should continue to work after being copied from.
  472. EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  473. EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
  474. // a2 should work like the action it was copied from.
  475. EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
  476. EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
  477. }
  478. // Tests that an Action<From> object can be converted to a
  479. // compatible Action<To> object.
  480. class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
  481. public:
  482. bool Perform(const std::tuple<int>& arg) override {
  483. return std::get<0>(arg) != 0;
  484. }
  485. };
  486. TEST(ActionTest, CanBeConvertedToOtherActionType) {
  487. const Action<bool(int)> a1(new IsNotZero); // NOLINT
  488. const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
  489. EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
  490. EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
  491. }
  492. // The following two classes are for testing MakePolymorphicAction().
  493. // Implements a polymorphic action that returns the second of the
  494. // arguments it receives.
  495. class ReturnSecondArgumentAction {
  496. public:
  497. // We want to verify that MakePolymorphicAction() can work with a
  498. // polymorphic action whose Perform() method template is either
  499. // const or not. This lets us verify the non-const case.
  500. template <typename Result, typename ArgumentTuple>
  501. Result Perform(const ArgumentTuple& args) {
  502. return std::get<1>(args);
  503. }
  504. };
  505. // Implements a polymorphic action that can be used in a nullary
  506. // function to return 0.
  507. class ReturnZeroFromNullaryFunctionAction {
  508. public:
  509. // For testing that MakePolymorphicAction() works when the
  510. // implementation class' Perform() method template takes only one
  511. // template parameter.
  512. //
  513. // We want to verify that MakePolymorphicAction() can work with a
  514. // polymorphic action whose Perform() method template is either
  515. // const or not. This lets us verify the const case.
  516. template <typename Result>
  517. Result Perform(const std::tuple<>&) const {
  518. return 0;
  519. }
  520. };
  521. // These functions verify that MakePolymorphicAction() returns a
  522. // PolymorphicAction<T> where T is the argument's type.
  523. PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
  524. return MakePolymorphicAction(ReturnSecondArgumentAction());
  525. }
  526. PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
  527. ReturnZeroFromNullaryFunction() {
  528. return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
  529. }
  530. // Tests that MakePolymorphicAction() turns a polymorphic action
  531. // implementation class into a polymorphic action.
  532. TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
  533. Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT
  534. EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));
  535. }
  536. // Tests that MakePolymorphicAction() works when the implementation
  537. // class' Perform() method template has only one template parameter.
  538. TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
  539. Action<int()> a1 = ReturnZeroFromNullaryFunction();
  540. EXPECT_EQ(0, a1.Perform(std::make_tuple()));
  541. Action<void*()> a2 = ReturnZeroFromNullaryFunction();
  542. EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);
  543. }
  544. // Tests that Return() works as an action for void-returning
  545. // functions.
  546. TEST(ReturnTest, WorksForVoid) {
  547. const Action<void(int)> ret = Return(); // NOLINT
  548. return ret.Perform(std::make_tuple(1));
  549. }
  550. // Tests that Return(v) returns v.
  551. TEST(ReturnTest, ReturnsGivenValue) {
  552. Action<int()> ret = Return(1); // NOLINT
  553. EXPECT_EQ(1, ret.Perform(std::make_tuple()));
  554. ret = Return(-5);
  555. EXPECT_EQ(-5, ret.Perform(std::make_tuple()));
  556. }
  557. // Tests that Return("string literal") works.
  558. TEST(ReturnTest, AcceptsStringLiteral) {
  559. Action<const char*()> a1 = Return("Hello");
  560. EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));
  561. Action<std::string()> a2 = Return("world");
  562. EXPECT_EQ("world", a2.Perform(std::make_tuple()));
  563. }
  564. // Return(x) should work fine when the mock function's return type is a
  565. // reference-like wrapper for decltype(x), as when x is a std::string and the
  566. // mock function returns std::string_view.
  567. TEST(ReturnTest, SupportsReferenceLikeReturnType) {
  568. // A reference wrapper for std::vector<int>, implicitly convertible from it.
  569. struct Result {
  570. const std::vector<int>* v;
  571. Result(const std::vector<int>& vec) : v(&vec) {} // NOLINT
  572. };
  573. // Set up an action for a mock function that returns the reference wrapper
  574. // type, initializing it with an actual vector.
  575. //
  576. // The returned wrapper should be initialized with a copy of that vector
  577. // that's embedded within the action itself (which should stay alive as long
  578. // as the mock object is alive), rather than e.g. a reference to the temporary
  579. // we feed to Return. This should work fine both for WillOnce and
  580. // WillRepeatedly.
  581. MockFunction<Result()> mock;
  582. EXPECT_CALL(mock, Call)
  583. .WillOnce(Return(std::vector<int>{17, 19, 23}))
  584. .WillRepeatedly(Return(std::vector<int>{29, 31, 37}));
  585. EXPECT_THAT(mock.AsStdFunction()(),
  586. Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));
  587. EXPECT_THAT(mock.AsStdFunction()(),
  588. Field(&Result::v, Pointee(ElementsAre(29, 31, 37))));
  589. }
  590. TEST(ReturnTest, PrefersConversionOperator) {
  591. // Define types In and Out such that:
  592. //
  593. // * In is implicitly convertible to Out.
  594. // * Out also has an explicit constructor from In.
  595. //
  596. struct In;
  597. struct Out {
  598. int x;
  599. explicit Out(const int val) : x(val) {}
  600. explicit Out(const In&) : x(0) {}
  601. };
  602. struct In {
  603. operator Out() const { return Out{19}; } // NOLINT
  604. };
  605. // Assumption check: the C++ language rules are such that a function that
  606. // returns Out which uses In a return statement will use the implicit
  607. // conversion path rather than the explicit constructor.
  608. EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19));
  609. // Return should work the same way: if the mock function's return type is Out
  610. // and we feed Return an In value, then the Out should be created through the
  611. // implicit conversion path rather than the explicit constructor.
  612. MockFunction<Out()> mock;
  613. EXPECT_CALL(mock, Call).WillOnce(Return(In()));
  614. EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19));
  615. }
  616. // It should be possible to use Return(R) with a mock function result type U
  617. // that is convertible from const R& but *not* R (such as
  618. // std::reference_wrapper). This should work for both WillOnce and
  619. // WillRepeatedly.
  620. TEST(ReturnTest, ConversionRequiresConstLvalueReference) {
  621. using R = int;
  622. using U = std::reference_wrapper<const int>;
  623. static_assert(std::is_convertible<const R&, U>::value, "");
  624. static_assert(!std::is_convertible<R, U>::value, "");
  625. MockFunction<U()> mock;
  626. EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19));
  627. EXPECT_EQ(17, mock.AsStdFunction()());
  628. EXPECT_EQ(19, mock.AsStdFunction()());
  629. }
  630. // Return(x) should not be usable with a mock function result type that's
  631. // implicitly convertible from decltype(x) but requires a non-const lvalue
  632. // reference to the input. It doesn't make sense for the conversion operator to
  633. // modify the input.
  634. TEST(ReturnTest, ConversionRequiresMutableLvalueReference) {
  635. // Set up a type that is implicitly convertible from std::string&, but not
  636. // std::string&& or `const std::string&`.
  637. //
  638. // Avoid asserting about conversion from std::string on MSVC, which seems to
  639. // implement std::is_convertible incorrectly in this case.
  640. struct S {
  641. S(std::string&) {} // NOLINT
  642. };
  643. static_assert(std::is_convertible<std::string&, S>::value, "");
  644. #ifndef _MSC_VER
  645. static_assert(!std::is_convertible<std::string&&, S>::value, "");
  646. #endif
  647. static_assert(!std::is_convertible<const std::string&, S>::value, "");
  648. // It shouldn't be possible to use the result of Return(std::string) in a
  649. // context where an S is needed.
  650. //
  651. // Here too we disable the assertion for MSVC, since its incorrect
  652. // implementation of is_convertible causes our SFINAE to be wrong.
  653. using RA = decltype(Return(std::string()));
  654. static_assert(!std::is_convertible<RA, Action<S()>>::value, "");
  655. #ifndef _MSC_VER
  656. static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, "");
  657. #endif
  658. }
  659. TEST(ReturnTest, MoveOnlyResultType) {
  660. // Return should support move-only result types when used with WillOnce.
  661. {
  662. MockFunction<std::unique_ptr<int>()> mock;
  663. EXPECT_CALL(mock, Call)
  664. // NOLINTNEXTLINE
  665. .WillOnce(Return(std::unique_ptr<int>(new int(17))));
  666. EXPECT_THAT(mock.AsStdFunction()(), Pointee(17));
  667. }
  668. // The result of Return should not be convertible to Action (so it can't be
  669. // used with WillRepeatedly).
  670. static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())),
  671. Action<std::unique_ptr<int>()>>::value,
  672. "");
  673. }
  674. // Tests that Return(v) is covariant.
  675. struct Base {
  676. bool operator==(const Base&) { return true; }
  677. };
  678. struct Derived : public Base {
  679. bool operator==(const Derived&) { return true; }
  680. };
  681. TEST(ReturnTest, IsCovariant) {
  682. Base base;
  683. Derived derived;
  684. Action<Base*()> ret = Return(&base);
  685. EXPECT_EQ(&base, ret.Perform(std::make_tuple()));
  686. ret = Return(&derived);
  687. EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));
  688. }
  689. // Tests that the type of the value passed into Return is converted into T
  690. // when the action is cast to Action<T(...)> rather than when the action is
  691. // performed. See comments on testing::internal::ReturnAction in
  692. // gmock-actions.h for more information.
  693. class FromType {
  694. public:
  695. explicit FromType(bool* is_converted) : converted_(is_converted) {}
  696. bool* converted() const { return converted_; }
  697. private:
  698. bool* const converted_;
  699. };
  700. class ToType {
  701. public:
  702. // Must allow implicit conversion due to use in ImplicitCast_<T>.
  703. ToType(const FromType& x) { *x.converted() = true; } // NOLINT
  704. };
  705. TEST(ReturnTest, ConvertsArgumentWhenConverted) {
  706. bool converted = false;
  707. FromType x(&converted);
  708. Action<ToType()> action(Return(x));
  709. EXPECT_TRUE(converted) << "Return must convert its argument in its own "
  710. << "conversion operator.";
  711. converted = false;
  712. action.Perform(std::tuple<>());
  713. EXPECT_FALSE(converted) << "Action must NOT convert its argument "
  714. << "when performed.";
  715. }
  716. // Tests that ReturnNull() returns NULL in a pointer-returning function.
  717. TEST(ReturnNullTest, WorksInPointerReturningFunction) {
  718. const Action<int*()> a1 = ReturnNull();
  719. EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
  720. const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
  721. EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);
  722. }
  723. // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
  724. // functions.
  725. TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
  726. const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
  727. EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
  728. const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
  729. EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);
  730. }
  731. // Tests that ReturnRef(v) works for reference types.
  732. TEST(ReturnRefTest, WorksForReference) {
  733. const int n = 0;
  734. const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
  735. EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));
  736. }
  737. // Tests that ReturnRef(v) is covariant.
  738. TEST(ReturnRefTest, IsCovariant) {
  739. Base base;
  740. Derived derived;
  741. Action<Base&()> a = ReturnRef(base);
  742. EXPECT_EQ(&base, &a.Perform(std::make_tuple()));
  743. a = ReturnRef(derived);
  744. EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
  745. }
  746. template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
  747. bool CanCallReturnRef(T&&) {
  748. return true;
  749. }
  750. bool CanCallReturnRef(Unused) { return false; }
  751. // Tests that ReturnRef(v) is working with non-temporaries (T&)
  752. TEST(ReturnRefTest, WorksForNonTemporary) {
  753. int scalar_value = 123;
  754. EXPECT_TRUE(CanCallReturnRef(scalar_value));
  755. std::string non_scalar_value("ABC");
  756. EXPECT_TRUE(CanCallReturnRef(non_scalar_value));
  757. const int const_scalar_value{321};
  758. EXPECT_TRUE(CanCallReturnRef(const_scalar_value));
  759. const std::string const_non_scalar_value("CBA");
  760. EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));
  761. }
  762. // Tests that ReturnRef(v) is not working with temporaries (T&&)
  763. TEST(ReturnRefTest, DoesNotWorkForTemporary) {
  764. auto scalar_value = []() -> int { return 123; };
  765. EXPECT_FALSE(CanCallReturnRef(scalar_value()));
  766. auto non_scalar_value = []() -> std::string { return "ABC"; };
  767. EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));
  768. // cannot use here callable returning "const scalar type",
  769. // because such const for scalar return type is ignored
  770. EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));
  771. auto const_non_scalar_value = []() -> const std::string { return "CBA"; };
  772. EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));
  773. }
  774. // Tests that ReturnRefOfCopy(v) works for reference types.
  775. TEST(ReturnRefOfCopyTest, WorksForReference) {
  776. int n = 42;
  777. const Action<const int&()> ret = ReturnRefOfCopy(n);
  778. EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
  779. EXPECT_EQ(42, ret.Perform(std::make_tuple()));
  780. n = 43;
  781. EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
  782. EXPECT_EQ(42, ret.Perform(std::make_tuple()));
  783. }
  784. // Tests that ReturnRefOfCopy(v) is covariant.
  785. TEST(ReturnRefOfCopyTest, IsCovariant) {
  786. Base base;
  787. Derived derived;
  788. Action<Base&()> a = ReturnRefOfCopy(base);
  789. EXPECT_NE(&base, &a.Perform(std::make_tuple()));
  790. a = ReturnRefOfCopy(derived);
  791. EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
  792. }
  793. // Tests that ReturnRoundRobin(v) works with initializer lists
  794. TEST(ReturnRoundRobinTest, WorksForInitList) {
  795. Action<int()> ret = ReturnRoundRobin({1, 2, 3});
  796. EXPECT_EQ(1, ret.Perform(std::make_tuple()));
  797. EXPECT_EQ(2, ret.Perform(std::make_tuple()));
  798. EXPECT_EQ(3, ret.Perform(std::make_tuple()));
  799. EXPECT_EQ(1, ret.Perform(std::make_tuple()));
  800. EXPECT_EQ(2, ret.Perform(std::make_tuple()));
  801. EXPECT_EQ(3, ret.Perform(std::make_tuple()));
  802. }
  803. // Tests that ReturnRoundRobin(v) works with vectors
  804. TEST(ReturnRoundRobinTest, WorksForVector) {
  805. std::vector<double> v = {4.4, 5.5, 6.6};
  806. Action<double()> ret = ReturnRoundRobin(v);
  807. EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
  808. EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
  809. EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
  810. EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
  811. EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
  812. EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
  813. }
  814. // Tests that DoDefault() does the default action for the mock method.
  815. class MockClass {
  816. public:
  817. MockClass() = default;
  818. MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
  819. MOCK_METHOD0(Foo, MyNonDefaultConstructible());
  820. MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
  821. MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
  822. MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
  823. MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
  824. MOCK_METHOD2(TakeUnique,
  825. int(const std::unique_ptr<int>&, std::unique_ptr<int>));
  826. private:
  827. MockClass(const MockClass&) = delete;
  828. MockClass& operator=(const MockClass&) = delete;
  829. };
  830. // Tests that DoDefault() returns the built-in default value for the
  831. // return type by default.
  832. TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
  833. MockClass mock;
  834. EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
  835. EXPECT_EQ(0, mock.IntFunc(true));
  836. }
  837. // Tests that DoDefault() throws (when exceptions are enabled) or aborts
  838. // the process when there is no built-in default value for the return type.
  839. TEST(DoDefaultDeathTest, DiesForUnknowType) {
  840. MockClass mock;
  841. EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());
  842. #if GTEST_HAS_EXCEPTIONS
  843. EXPECT_ANY_THROW(mock.Foo());
  844. #else
  845. EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");
  846. #endif
  847. }
  848. // Tests that using DoDefault() inside a composite action leads to a
  849. // run-time error.
  850. void VoidFunc(bool /* flag */) {}
  851. TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
  852. MockClass mock;
  853. EXPECT_CALL(mock, IntFunc(_))
  854. .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
  855. // Ideally we should verify the error message as well. Sadly,
  856. // EXPECT_DEATH() can only capture stderr, while Google Mock's
  857. // errors are printed on stdout. Therefore we have to settle for
  858. // not verifying the message.
  859. EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");
  860. }
  861. // Tests that DoDefault() returns the default value set by
  862. // DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
  863. TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
  864. DefaultValue<int>::Set(1);
  865. MockClass mock;
  866. EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
  867. EXPECT_EQ(1, mock.IntFunc(false));
  868. DefaultValue<int>::Clear();
  869. }
  870. // Tests that DoDefault() does the action specified by ON_CALL().
  871. TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
  872. MockClass mock;
  873. ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));
  874. EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
  875. EXPECT_EQ(2, mock.IntFunc(false));
  876. }
  877. // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
  878. TEST(DoDefaultTest, CannotBeUsedInOnCall) {
  879. MockClass mock;
  880. EXPECT_NONFATAL_FAILURE(
  881. { // NOLINT
  882. ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());
  883. },
  884. "DoDefault() cannot be used in ON_CALL()");
  885. }
  886. // Tests that SetArgPointee<N>(v) sets the variable pointed to by
  887. // the N-th (0-based) argument to v.
  888. TEST(SetArgPointeeTest, SetsTheNthPointee) {
  889. typedef void MyFunction(bool, int*, char*);
  890. Action<MyFunction> a = SetArgPointee<1>(2);
  891. int n = 0;
  892. char ch = '\0';
  893. a.Perform(std::make_tuple(true, &n, &ch));
  894. EXPECT_EQ(2, n);
  895. EXPECT_EQ('\0', ch);
  896. a = SetArgPointee<2>('a');
  897. n = 0;
  898. ch = '\0';
  899. a.Perform(std::make_tuple(true, &n, &ch));
  900. EXPECT_EQ(0, n);
  901. EXPECT_EQ('a', ch);
  902. }
  903. // Tests that SetArgPointee<N>() accepts a string literal.
  904. TEST(SetArgPointeeTest, AcceptsStringLiteral) {
  905. typedef void MyFunction(std::string*, const char**);
  906. Action<MyFunction> a = SetArgPointee<0>("hi");
  907. std::string str;
  908. const char* ptr = nullptr;
  909. a.Perform(std::make_tuple(&str, &ptr));
  910. EXPECT_EQ("hi", str);
  911. EXPECT_TRUE(ptr == nullptr);
  912. a = SetArgPointee<1>("world");
  913. str = "";
  914. a.Perform(std::make_tuple(&str, &ptr));
  915. EXPECT_EQ("", str);
  916. EXPECT_STREQ("world", ptr);
  917. }
  918. TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
  919. typedef void MyFunction(const wchar_t**);
  920. Action<MyFunction> a = SetArgPointee<0>(L"world");
  921. const wchar_t* ptr = nullptr;
  922. a.Perform(std::make_tuple(&ptr));
  923. EXPECT_STREQ(L"world", ptr);
  924. #if GTEST_HAS_STD_WSTRING
  925. typedef void MyStringFunction(std::wstring*);
  926. Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
  927. std::wstring str = L"";
  928. a2.Perform(std::make_tuple(&str));
  929. EXPECT_EQ(L"world", str);
  930. #endif
  931. }
  932. // Tests that SetArgPointee<N>() accepts a char pointer.
  933. TEST(SetArgPointeeTest, AcceptsCharPointer) {
  934. typedef void MyFunction(bool, std::string*, const char**);
  935. const char* const hi = "hi";
  936. Action<MyFunction> a = SetArgPointee<1>(hi);
  937. std::string str;
  938. const char* ptr = nullptr;
  939. a.Perform(std::make_tuple(true, &str, &ptr));
  940. EXPECT_EQ("hi", str);
  941. EXPECT_TRUE(ptr == nullptr);
  942. char world_array[] = "world";
  943. char* const world = world_array;
  944. a = SetArgPointee<2>(world);
  945. str = "";
  946. a.Perform(std::make_tuple(true, &str, &ptr));
  947. EXPECT_EQ("", str);
  948. EXPECT_EQ(world, ptr);
  949. }
  950. TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
  951. typedef void MyFunction(bool, const wchar_t**);
  952. const wchar_t* const hi = L"hi";
  953. Action<MyFunction> a = SetArgPointee<1>(hi);
  954. const wchar_t* ptr = nullptr;
  955. a.Perform(std::make_tuple(true, &ptr));
  956. EXPECT_EQ(hi, ptr);
  957. #if GTEST_HAS_STD_WSTRING
  958. typedef void MyStringFunction(bool, std::wstring*);
  959. wchar_t world_array[] = L"world";
  960. wchar_t* const world = world_array;
  961. Action<MyStringFunction> a2 = SetArgPointee<1>(world);
  962. std::wstring str;
  963. a2.Perform(std::make_tuple(true, &str));
  964. EXPECT_EQ(world_array, str);
  965. #endif
  966. }
  967. // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
  968. // the N-th (0-based) argument to v.
  969. TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
  970. typedef void MyFunction(bool, int*, char*);
  971. Action<MyFunction> a = SetArgumentPointee<1>(2);
  972. int n = 0;
  973. char ch = '\0';
  974. a.Perform(std::make_tuple(true, &n, &ch));
  975. EXPECT_EQ(2, n);
  976. EXPECT_EQ('\0', ch);
  977. a = SetArgumentPointee<2>('a');
  978. n = 0;
  979. ch = '\0';
  980. a.Perform(std::make_tuple(true, &n, &ch));
  981. EXPECT_EQ(0, n);
  982. EXPECT_EQ('a', ch);
  983. }
  984. // Sample functions and functors for testing Invoke() and etc.
  985. int Nullary() { return 1; }
  986. class NullaryFunctor {
  987. public:
  988. int operator()() { return 2; }
  989. };
  990. bool g_done = false;
  991. void VoidNullary() { g_done = true; }
  992. class VoidNullaryFunctor {
  993. public:
  994. void operator()() { g_done = true; }
  995. };
  996. short Short(short n) { return n; } // NOLINT
  997. char Char(char ch) { return ch; }
  998. const char* CharPtr(const char* s) { return s; }
  999. bool Unary(int x) { return x < 0; }
  1000. const char* Binary(const char* input, short n) { return input + n; } // NOLINT
  1001. void VoidBinary(int, char) { g_done = true; }
  1002. int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
  1003. int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
  1004. class Foo {
  1005. public:
  1006. Foo() : value_(123) {}
  1007. int Nullary() const { return value_; }
  1008. private:
  1009. int value_;
  1010. };
  1011. // Tests InvokeWithoutArgs(function).
  1012. TEST(InvokeWithoutArgsTest, Function) {
  1013. // As an action that takes one argument.
  1014. Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT
  1015. EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
  1016. // As an action that takes two arguments.
  1017. Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT
  1018. EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));
  1019. // As an action that returns void.
  1020. Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
  1021. g_done = false;
  1022. a3.Perform(std::make_tuple(1));
  1023. EXPECT_TRUE(g_done);
  1024. }
  1025. // Tests InvokeWithoutArgs(functor).
  1026. TEST(InvokeWithoutArgsTest, Functor) {
  1027. // As an action that takes no argument.
  1028. Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT
  1029. EXPECT_EQ(2, a.Perform(std::make_tuple()));
  1030. // As an action that takes three arguments.
  1031. Action<int(int, double, char)> a2 = // NOLINT
  1032. InvokeWithoutArgs(NullaryFunctor());
  1033. EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));
  1034. // As an action that returns void.
  1035. Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
  1036. g_done = false;
  1037. a3.Perform(std::make_tuple());
  1038. EXPECT_TRUE(g_done);
  1039. }
  1040. // Tests InvokeWithoutArgs(obj_ptr, method).
  1041. TEST(InvokeWithoutArgsTest, Method) {
  1042. Foo foo;
  1043. Action<int(bool, char)> a = // NOLINT
  1044. InvokeWithoutArgs(&foo, &Foo::Nullary);
  1045. EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
  1046. }
  1047. // Tests using IgnoreResult() on a polymorphic action.
  1048. TEST(IgnoreResultTest, PolymorphicAction) {
  1049. Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
  1050. a.Perform(std::make_tuple(1));
  1051. }
  1052. // Tests using IgnoreResult() on a monomorphic action.
  1053. int ReturnOne() {
  1054. g_done = true;
  1055. return 1;
  1056. }
  1057. TEST(IgnoreResultTest, MonomorphicAction) {
  1058. g_done = false;
  1059. Action<void()> a = IgnoreResult(Invoke(ReturnOne));
  1060. a.Perform(std::make_tuple());
  1061. EXPECT_TRUE(g_done);
  1062. }
  1063. // Tests using IgnoreResult() on an action that returns a class type.
  1064. MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
  1065. g_done = true;
  1066. return MyNonDefaultConstructible(42);
  1067. }
  1068. TEST(IgnoreResultTest, ActionReturningClass) {
  1069. g_done = false;
  1070. Action<void(int)> a =
  1071. IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
  1072. a.Perform(std::make_tuple(2));
  1073. EXPECT_TRUE(g_done);
  1074. }
  1075. TEST(AssignTest, Int) {
  1076. int x = 0;
  1077. Action<void(int)> a = Assign(&x, 5);
  1078. a.Perform(std::make_tuple(0));
  1079. EXPECT_EQ(5, x);
  1080. }
  1081. TEST(AssignTest, String) {
  1082. ::std::string x;
  1083. Action<void(void)> a = Assign(&x, "Hello, world");
  1084. a.Perform(std::make_tuple());
  1085. EXPECT_EQ("Hello, world", x);
  1086. }
  1087. TEST(AssignTest, CompatibleTypes) {
  1088. double x = 0;
  1089. Action<void(int)> a = Assign(&x, 5);
  1090. a.Perform(std::make_tuple(0));
  1091. EXPECT_DOUBLE_EQ(5, x);
  1092. }
  1093. // DoAll should support &&-qualified actions when used with WillOnce.
  1094. TEST(DoAll, SupportsRefQualifiedActions) {
  1095. struct InitialAction {
  1096. void operator()(const int arg) && { EXPECT_EQ(17, arg); }
  1097. };
  1098. struct FinalAction {
  1099. int operator()() && { return 19; }
  1100. };
  1101. MockFunction<int(int)> mock;
  1102. EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{}));
  1103. EXPECT_EQ(19, mock.AsStdFunction()(17));
  1104. }
  1105. // DoAll should never provide rvalue references to the initial actions. If the
  1106. // mock action itself accepts an rvalue reference or a non-scalar object by
  1107. // value then the final action should receive an rvalue reference, but initial
  1108. // actions should receive only lvalue references.
  1109. TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
  1110. struct Obj {};
  1111. // Mock action accepts by value: the initial action should be fed a const
  1112. // lvalue reference, and the final action an rvalue reference.
  1113. {
  1114. struct InitialAction {
  1115. void operator()(Obj&) const { FAIL() << "Unexpected call"; }
  1116. void operator()(const Obj&) const {}
  1117. void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
  1118. void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
  1119. };
  1120. MockFunction<void(Obj)> mock;
  1121. EXPECT_CALL(mock, Call)
  1122. .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
  1123. .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
  1124. mock.AsStdFunction()(Obj{});
  1125. mock.AsStdFunction()(Obj{});
  1126. }
  1127. // Mock action accepts by const lvalue reference: both actions should receive
  1128. // a const lvalue reference.
  1129. {
  1130. struct InitialAction {
  1131. void operator()(Obj&) const { FAIL() << "Unexpected call"; }
  1132. void operator()(const Obj&) const {}
  1133. void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
  1134. void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
  1135. };
  1136. MockFunction<void(const Obj&)> mock;
  1137. EXPECT_CALL(mock, Call)
  1138. .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}))
  1139. .WillRepeatedly(
  1140. DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}));
  1141. mock.AsStdFunction()(Obj{});
  1142. mock.AsStdFunction()(Obj{});
  1143. }
  1144. // Mock action accepts by non-const lvalue reference: both actions should get
  1145. // a non-const lvalue reference if they want them.
  1146. {
  1147. struct InitialAction {
  1148. void operator()(Obj&) const {}
  1149. void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
  1150. };
  1151. MockFunction<void(Obj&)> mock;
  1152. EXPECT_CALL(mock, Call)
  1153. .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}))
  1154. .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
  1155. Obj obj;
  1156. mock.AsStdFunction()(obj);
  1157. mock.AsStdFunction()(obj);
  1158. }
  1159. // Mock action accepts by rvalue reference: the initial actions should receive
  1160. // a non-const lvalue reference if it wants it, and the final action an rvalue
  1161. // reference.
  1162. {
  1163. struct InitialAction {
  1164. void operator()(Obj&) const {}
  1165. void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
  1166. };
  1167. MockFunction<void(Obj&&)> mock;
  1168. EXPECT_CALL(mock, Call)
  1169. .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
  1170. .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
  1171. mock.AsStdFunction()(Obj{});
  1172. mock.AsStdFunction()(Obj{});
  1173. }
  1174. // &&-qualified initial actions should also be allowed with WillOnce.
  1175. {
  1176. struct InitialAction {
  1177. void operator()(Obj&) && {}
  1178. };
  1179. MockFunction<void(Obj&)> mock;
  1180. EXPECT_CALL(mock, Call)
  1181. .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
  1182. Obj obj;
  1183. mock.AsStdFunction()(obj);
  1184. }
  1185. {
  1186. struct InitialAction {
  1187. void operator()(Obj&) && {}
  1188. };
  1189. MockFunction<void(Obj&&)> mock;
  1190. EXPECT_CALL(mock, Call)
  1191. .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
  1192. mock.AsStdFunction()(Obj{});
  1193. }
  1194. }
  1195. // DoAll should support being used with type-erased Action objects, both through
  1196. // WillOnce and WillRepeatedly.
  1197. TEST(DoAll, SupportsTypeErasedActions) {
  1198. // With only type-erased actions.
  1199. const Action<void()> initial_action = [] {};
  1200. const Action<int()> final_action = [] { return 17; };
  1201. MockFunction<int()> mock;
  1202. EXPECT_CALL(mock, Call)
  1203. .WillOnce(DoAll(initial_action, initial_action, final_action))
  1204. .WillRepeatedly(DoAll(initial_action, initial_action, final_action));
  1205. EXPECT_EQ(17, mock.AsStdFunction()());
  1206. // With &&-qualified and move-only final action.
  1207. {
  1208. struct FinalAction {
  1209. FinalAction() = default;
  1210. FinalAction(FinalAction&&) = default;
  1211. int operator()() && { return 17; }
  1212. };
  1213. EXPECT_CALL(mock, Call)
  1214. .WillOnce(DoAll(initial_action, initial_action, FinalAction{}));
  1215. EXPECT_EQ(17, mock.AsStdFunction()());
  1216. }
  1217. }
  1218. // A DoAll action should be convertible to a OnceAction, even when its component
  1219. // sub-actions are user-provided types that define only an Action conversion
  1220. // operator. If they supposed being called more than once then they also support
  1221. // being called at most once.
  1222. TEST(DoAll, ConvertibleToOnceActionWithUserProvidedActionConversion) {
  1223. // Simplest case: only one sub-action.
  1224. struct CustomFinal final {
  1225. operator Action<int()>() { // NOLINT
  1226. return Return(17);
  1227. }
  1228. operator Action<int(int, char)>() { // NOLINT
  1229. return Return(19);
  1230. }
  1231. };
  1232. {
  1233. OnceAction<int()> action = DoAll(CustomFinal{});
  1234. EXPECT_EQ(17, std::move(action).Call());
  1235. }
  1236. {
  1237. OnceAction<int(int, char)> action = DoAll(CustomFinal{});
  1238. EXPECT_EQ(19, std::move(action).Call(0, 0));
  1239. }
  1240. // It should also work with multiple sub-actions.
  1241. struct CustomInitial final {
  1242. operator Action<void()>() { // NOLINT
  1243. return [] {};
  1244. }
  1245. operator Action<void(int, char)>() { // NOLINT
  1246. return [] {};
  1247. }
  1248. };
  1249. {
  1250. OnceAction<int()> action = DoAll(CustomInitial{}, CustomFinal{});
  1251. EXPECT_EQ(17, std::move(action).Call());
  1252. }
  1253. {
  1254. OnceAction<int(int, char)> action = DoAll(CustomInitial{}, CustomFinal{});
  1255. EXPECT_EQ(19, std::move(action).Call(0, 0));
  1256. }
  1257. }
  1258. // Tests using WithArgs and with an action that takes 1 argument.
  1259. TEST(WithArgsTest, OneArg) {
  1260. Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
  1261. EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
  1262. EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
  1263. }
  1264. // Tests using WithArgs with an action that takes 2 arguments.
  1265. TEST(WithArgsTest, TwoArgs) {
  1266. Action<const char*(const char* s, double x, short n)> a = // NOLINT
  1267. WithArgs<0, 2>(Invoke(Binary));
  1268. const char s[] = "Hello";
  1269. EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
  1270. }
  1271. struct ConcatAll {
  1272. std::string operator()() const { return {}; }
  1273. template <typename... I>
  1274. std::string operator()(const char* a, I... i) const {
  1275. return a + ConcatAll()(i...);
  1276. }
  1277. };
  1278. // Tests using WithArgs with an action that takes 10 arguments.
  1279. TEST(WithArgsTest, TenArgs) {
  1280. Action<std::string(const char*, const char*, const char*, const char*)> a =
  1281. WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
  1282. EXPECT_EQ("0123210123",
  1283. a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
  1284. CharPtr("3"))));
  1285. }
  1286. // Tests using WithArgs with an action that is not Invoke().
  1287. class SubtractAction : public ActionInterface<int(int, int)> {
  1288. public:
  1289. int Perform(const std::tuple<int, int>& args) override {
  1290. return std::get<0>(args) - std::get<1>(args);
  1291. }
  1292. };
  1293. TEST(WithArgsTest, NonInvokeAction) {
  1294. Action<int(const std::string&, int, int)> a =
  1295. WithArgs<2, 1>(MakeAction(new SubtractAction));
  1296. std::tuple<std::string, int, int> dummy =
  1297. std::make_tuple(std::string("hi"), 2, 10);
  1298. EXPECT_EQ(8, a.Perform(dummy));
  1299. }
  1300. // Tests using WithArgs to pass all original arguments in the original order.
  1301. TEST(WithArgsTest, Identity) {
  1302. Action<int(int x, char y, short z)> a = // NOLINT
  1303. WithArgs<0, 1, 2>(Invoke(Ternary));
  1304. EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
  1305. }
  1306. // Tests using WithArgs with repeated arguments.
  1307. TEST(WithArgsTest, RepeatedArguments) {
  1308. Action<int(bool, int m, int n)> a = // NOLINT
  1309. WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
  1310. EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
  1311. }
  1312. // Tests using WithArgs with reversed argument order.
  1313. TEST(WithArgsTest, ReversedArgumentOrder) {
  1314. Action<const char*(short n, const char* input)> a = // NOLINT
  1315. WithArgs<1, 0>(Invoke(Binary));
  1316. const char s[] = "Hello";
  1317. EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
  1318. }
  1319. // Tests using WithArgs with compatible, but not identical, argument types.
  1320. TEST(WithArgsTest, ArgsOfCompatibleTypes) {
  1321. Action<long(short x, char y, double z, char c)> a = // NOLINT
  1322. WithArgs<0, 1, 3>(Invoke(Ternary));
  1323. EXPECT_EQ(123,
  1324. a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
  1325. }
  1326. // Tests using WithArgs with an action that returns void.
  1327. TEST(WithArgsTest, VoidAction) {
  1328. Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
  1329. g_done = false;
  1330. a.Perform(std::make_tuple(1.5, 'a', 3));
  1331. EXPECT_TRUE(g_done);
  1332. }
  1333. TEST(WithArgsTest, ReturnReference) {
  1334. Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
  1335. int i = 0;
  1336. const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
  1337. EXPECT_EQ(&i, &res);
  1338. }
  1339. TEST(WithArgsTest, InnerActionWithConversion) {
  1340. Action<Derived*()> inner = [] { return nullptr; };
  1341. MockFunction<Base*(double)> mock;
  1342. EXPECT_CALL(mock, Call)
  1343. .WillOnce(WithoutArgs(inner))
  1344. .WillRepeatedly(WithoutArgs(inner));
  1345. EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
  1346. EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
  1347. }
  1348. // It should be possible to use an &&-qualified inner action as long as the
  1349. // whole shebang is used as an rvalue with WillOnce.
  1350. TEST(WithArgsTest, RefQualifiedInnerAction) {
  1351. struct SomeAction {
  1352. int operator()(const int arg) && {
  1353. EXPECT_EQ(17, arg);
  1354. return 19;
  1355. }
  1356. };
  1357. MockFunction<int(int, int)> mock;
  1358. EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{}));
  1359. EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
  1360. }
  1361. #ifndef GTEST_OS_WINDOWS_MOBILE
  1362. class SetErrnoAndReturnTest : public testing::Test {
  1363. protected:
  1364. void SetUp() override { errno = 0; }
  1365. void TearDown() override { errno = 0; }
  1366. };
  1367. TEST_F(SetErrnoAndReturnTest, Int) {
  1368. Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
  1369. EXPECT_EQ(-5, a.Perform(std::make_tuple()));
  1370. EXPECT_EQ(ENOTTY, errno);
  1371. }
  1372. TEST_F(SetErrnoAndReturnTest, Ptr) {
  1373. int x;
  1374. Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
  1375. EXPECT_EQ(&x, a.Perform(std::make_tuple()));
  1376. EXPECT_EQ(ENOTTY, errno);
  1377. }
  1378. TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
  1379. Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
  1380. EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
  1381. EXPECT_EQ(EINVAL, errno);
  1382. }
  1383. #endif // !GTEST_OS_WINDOWS_MOBILE
  1384. // Tests ByRef().
  1385. // Tests that the result of ByRef() is copyable.
  1386. TEST(ByRefTest, IsCopyable) {
  1387. const std::string s1 = "Hi";
  1388. const std::string s2 = "Hello";
  1389. auto ref_wrapper = ByRef(s1);
  1390. const std::string& r1 = ref_wrapper;
  1391. EXPECT_EQ(&s1, &r1);
  1392. // Assigns a new value to ref_wrapper.
  1393. ref_wrapper = ByRef(s2);
  1394. const std::string& r2 = ref_wrapper;
  1395. EXPECT_EQ(&s2, &r2);
  1396. auto ref_wrapper1 = ByRef(s1);
  1397. // Copies ref_wrapper1 to ref_wrapper.
  1398. ref_wrapper = ref_wrapper1;
  1399. const std::string& r3 = ref_wrapper;
  1400. EXPECT_EQ(&s1, &r3);
  1401. }
  1402. // Tests using ByRef() on a const value.
  1403. TEST(ByRefTest, ConstValue) {
  1404. const int n = 0;
  1405. // int& ref = ByRef(n); // This shouldn't compile - we have a
  1406. // negative compilation test to catch it.
  1407. const int& const_ref = ByRef(n);
  1408. EXPECT_EQ(&n, &const_ref);
  1409. }
  1410. // Tests using ByRef() on a non-const value.
  1411. TEST(ByRefTest, NonConstValue) {
  1412. int n = 0;
  1413. // ByRef(n) can be used as either an int&,
  1414. int& ref = ByRef(n);
  1415. EXPECT_EQ(&n, &ref);
  1416. // or a const int&.
  1417. const int& const_ref = ByRef(n);
  1418. EXPECT_EQ(&n, &const_ref);
  1419. }
  1420. // Tests explicitly specifying the type when using ByRef().
  1421. TEST(ByRefTest, ExplicitType) {
  1422. int n = 0;
  1423. const int& r1 = ByRef<const int>(n);
  1424. EXPECT_EQ(&n, &r1);
  1425. // ByRef<char>(n); // This shouldn't compile - we have a negative
  1426. // compilation test to catch it.
  1427. Derived d;
  1428. Derived& r2 = ByRef<Derived>(d);
  1429. EXPECT_EQ(&d, &r2);
  1430. const Derived& r3 = ByRef<const Derived>(d);
  1431. EXPECT_EQ(&d, &r3);
  1432. Base& r4 = ByRef<Base>(d);
  1433. EXPECT_EQ(&d, &r4);
  1434. const Base& r5 = ByRef<const Base>(d);
  1435. EXPECT_EQ(&d, &r5);
  1436. // The following shouldn't compile - we have a negative compilation
  1437. // test for it.
  1438. //
  1439. // Base b;
  1440. // ByRef<Derived>(b);
  1441. }
  1442. // Tests that Google Mock prints expression ByRef(x) as a reference to x.
  1443. TEST(ByRefTest, PrintsCorrectly) {
  1444. int n = 42;
  1445. ::std::stringstream expected, actual;
  1446. testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
  1447. testing::internal::UniversalPrint(ByRef(n), &actual);
  1448. EXPECT_EQ(expected.str(), actual.str());
  1449. }
  1450. struct UnaryConstructorClass {
  1451. explicit UnaryConstructorClass(int v) : value(v) {}
  1452. int value;
  1453. };
  1454. // Tests using ReturnNew() with a unary constructor.
  1455. TEST(ReturnNewTest, Unary) {
  1456. Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
  1457. UnaryConstructorClass* c = a.Perform(std::make_tuple());
  1458. EXPECT_EQ(4000, c->value);
  1459. delete c;
  1460. }
  1461. TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
  1462. Action<UnaryConstructorClass*(bool, int)> a =
  1463. ReturnNew<UnaryConstructorClass>(4000);
  1464. UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
  1465. EXPECT_EQ(4000, c->value);
  1466. delete c;
  1467. }
  1468. TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
  1469. Action<const UnaryConstructorClass*()> a =
  1470. ReturnNew<UnaryConstructorClass>(4000);
  1471. const UnaryConstructorClass* c = a.Perform(std::make_tuple());
  1472. EXPECT_EQ(4000, c->value);
  1473. delete c;
  1474. }
  1475. class TenArgConstructorClass {
  1476. public:
  1477. TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
  1478. int a8, int a9, int a10)
  1479. : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
  1480. int value_;
  1481. };
  1482. // Tests using ReturnNew() with a 10-argument constructor.
  1483. TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
  1484. Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
  1485. 1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
  1486. 0);
  1487. TenArgConstructorClass* c = a.Perform(std::make_tuple());
  1488. EXPECT_EQ(1234567890, c->value_);
  1489. delete c;
  1490. }
  1491. std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); }
  1492. std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
  1493. std::vector<std::unique_ptr<int>> out;
  1494. out.emplace_back(new int(7));
  1495. return out;
  1496. }
  1497. TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
  1498. MockClass mock;
  1499. std::unique_ptr<int> i(new int(19));
  1500. EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
  1501. EXPECT_CALL(mock, MakeVectorUnique())
  1502. .WillOnce(Return(ByMove(VectorUniquePtrSource())));
  1503. Derived* d = new Derived;
  1504. EXPECT_CALL(mock, MakeUniqueBase())
  1505. .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
  1506. std::unique_ptr<int> result1 = mock.MakeUnique();
  1507. EXPECT_EQ(19, *result1);
  1508. std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
  1509. EXPECT_EQ(1u, vresult.size());
  1510. EXPECT_NE(nullptr, vresult[0]);
  1511. EXPECT_EQ(7, *vresult[0]);
  1512. std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
  1513. EXPECT_EQ(d, result2.get());
  1514. }
  1515. TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
  1516. testing::MockFunction<void()> mock_function;
  1517. MockClass mock;
  1518. std::unique_ptr<int> i(new int(19));
  1519. EXPECT_CALL(mock_function, Call());
  1520. EXPECT_CALL(mock, MakeUnique())
  1521. .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
  1522. &testing::MockFunction<void()>::Call),
  1523. Return(ByMove(std::move(i)))));
  1524. std::unique_ptr<int> result1 = mock.MakeUnique();
  1525. EXPECT_EQ(19, *result1);
  1526. }
  1527. TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
  1528. MockClass mock;
  1529. // Check default value
  1530. DefaultValue<std::unique_ptr<int>>::SetFactory(
  1531. [] { return std::make_unique<int>(42); });
  1532. EXPECT_EQ(42, *mock.MakeUnique());
  1533. EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
  1534. EXPECT_CALL(mock, MakeVectorUnique())
  1535. .WillRepeatedly(Invoke(VectorUniquePtrSource));
  1536. std::unique_ptr<int> result1 = mock.MakeUnique();
  1537. EXPECT_EQ(19, *result1);
  1538. std::unique_ptr<int> result2 = mock.MakeUnique();
  1539. EXPECT_EQ(19, *result2);
  1540. EXPECT_NE(result1, result2);
  1541. std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
  1542. EXPECT_EQ(1u, vresult.size());
  1543. EXPECT_NE(nullptr, vresult[0]);
  1544. EXPECT_EQ(7, *vresult[0]);
  1545. }
  1546. TEST(MockMethodTest, CanTakeMoveOnlyValue) {
  1547. MockClass mock;
  1548. auto make = [](int i) { return std::make_unique<int>(i); };
  1549. EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
  1550. return *i;
  1551. });
  1552. // DoAll() does not compile, since it would move from its arguments twice.
  1553. // EXPECT_CALL(mock, TakeUnique(_, _))
  1554. // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
  1555. // Return(1)));
  1556. EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
  1557. .WillOnce(Return(-7))
  1558. .RetiresOnSaturation();
  1559. EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
  1560. .WillOnce(Return(-1))
  1561. .RetiresOnSaturation();
  1562. EXPECT_EQ(5, mock.TakeUnique(make(5)));
  1563. EXPECT_EQ(-7, mock.TakeUnique(make(7)));
  1564. EXPECT_EQ(7, mock.TakeUnique(make(7)));
  1565. EXPECT_EQ(7, mock.TakeUnique(make(7)));
  1566. EXPECT_EQ(-1, mock.TakeUnique({}));
  1567. // Some arguments are moved, some passed by reference.
  1568. auto lvalue = make(6);
  1569. EXPECT_CALL(mock, TakeUnique(_, _))
  1570. .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
  1571. return *i * *j;
  1572. });
  1573. EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
  1574. // The unique_ptr can be saved by the action.
  1575. std::unique_ptr<int> saved;
  1576. EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
  1577. saved = std::move(i);
  1578. return 0;
  1579. });
  1580. EXPECT_EQ(0, mock.TakeUnique(make(42)));
  1581. EXPECT_EQ(42, *saved);
  1582. }
  1583. // It should be possible to use callables with an &&-qualified call operator
  1584. // with WillOnce, since they will be called only once. This allows actions to
  1585. // contain and manipulate move-only types.
  1586. TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) {
  1587. struct Return17 {
  1588. int operator()() && { return 17; }
  1589. };
  1590. // Action is directly compatible with mocked function type.
  1591. {
  1592. MockFunction<int()> mock;
  1593. EXPECT_CALL(mock, Call).WillOnce(Return17());
  1594. EXPECT_EQ(17, mock.AsStdFunction()());
  1595. }
  1596. // Action doesn't want mocked function arguments.
  1597. {
  1598. MockFunction<int(int)> mock;
  1599. EXPECT_CALL(mock, Call).WillOnce(Return17());
  1600. EXPECT_EQ(17, mock.AsStdFunction()(0));
  1601. }
  1602. }
  1603. // Edge case: if an action has both a const-qualified and an &&-qualified call
  1604. // operator, there should be no "ambiguous call" errors. The &&-qualified
  1605. // operator should be used by WillOnce (since it doesn't need to retain the
  1606. // action beyond one call), and the const-qualified one by WillRepeatedly.
  1607. TEST(MockMethodTest, ActionHasMultipleCallOperators) {
  1608. struct ReturnInt {
  1609. int operator()() && { return 17; }
  1610. int operator()() const& { return 19; }
  1611. };
  1612. // Directly compatible with mocked function type.
  1613. {
  1614. MockFunction<int()> mock;
  1615. EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
  1616. EXPECT_EQ(17, mock.AsStdFunction()());
  1617. EXPECT_EQ(19, mock.AsStdFunction()());
  1618. EXPECT_EQ(19, mock.AsStdFunction()());
  1619. }
  1620. // Ignores function arguments.
  1621. {
  1622. MockFunction<int(int)> mock;
  1623. EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
  1624. EXPECT_EQ(17, mock.AsStdFunction()(0));
  1625. EXPECT_EQ(19, mock.AsStdFunction()(0));
  1626. EXPECT_EQ(19, mock.AsStdFunction()(0));
  1627. }
  1628. }
  1629. // WillOnce should have no problem coping with a move-only action, whether it is
  1630. // &&-qualified or not.
  1631. TEST(MockMethodTest, MoveOnlyAction) {
  1632. // &&-qualified
  1633. {
  1634. struct Return17 {
  1635. Return17() = default;
  1636. Return17(Return17&&) = default;
  1637. Return17(const Return17&) = delete;
  1638. Return17 operator=(const Return17&) = delete;
  1639. int operator()() && { return 17; }
  1640. };
  1641. MockFunction<int()> mock;
  1642. EXPECT_CALL(mock, Call).WillOnce(Return17());
  1643. EXPECT_EQ(17, mock.AsStdFunction()());
  1644. }
  1645. // Not &&-qualified
  1646. {
  1647. struct Return17 {
  1648. Return17() = default;
  1649. Return17(Return17&&) = default;
  1650. Return17(const Return17&) = delete;
  1651. Return17 operator=(const Return17&) = delete;
  1652. int operator()() const { return 17; }
  1653. };
  1654. MockFunction<int()> mock;
  1655. EXPECT_CALL(mock, Call).WillOnce(Return17());
  1656. EXPECT_EQ(17, mock.AsStdFunction()());
  1657. }
  1658. }
  1659. // It should be possible to use an action that returns a value with a mock
  1660. // function that doesn't, both through WillOnce and WillRepeatedly.
  1661. TEST(MockMethodTest, ActionReturnsIgnoredValue) {
  1662. struct ReturnInt {
  1663. int operator()() const { return 0; }
  1664. };
  1665. MockFunction<void()> mock;
  1666. EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
  1667. mock.AsStdFunction()();
  1668. mock.AsStdFunction()();
  1669. }
  1670. // Despite the fanciness around move-only actions and so on, it should still be
  1671. // possible to hand an lvalue reference to a copyable action to WillOnce.
  1672. TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) {
  1673. MockFunction<int()> mock;
  1674. const auto action = [] { return 17; };
  1675. EXPECT_CALL(mock, Call).WillOnce(action);
  1676. EXPECT_EQ(17, mock.AsStdFunction()());
  1677. }
  1678. // A callable that doesn't use SFINAE to restrict its call operator's overload
  1679. // set, but is still picky about which arguments it will accept.
  1680. struct StaticAssertSingleArgument {
  1681. template <typename... Args>
  1682. static constexpr bool CheckArgs() {
  1683. static_assert(sizeof...(Args) == 1, "");
  1684. return true;
  1685. }
  1686. template <typename... Args, bool = CheckArgs<Args...>()>
  1687. int operator()(Args...) const {
  1688. return 17;
  1689. }
  1690. };
  1691. // WillOnce and WillRepeatedly should both work fine with naïve implementations
  1692. // of actions that don't use SFINAE to limit the overload set for their call
  1693. // operator. If they are compatible with the actual mocked signature, we
  1694. // shouldn't probe them with no arguments and trip a static_assert.
  1695. TEST(MockMethodTest, ActionSwallowsAllArguments) {
  1696. MockFunction<int(int)> mock;
  1697. EXPECT_CALL(mock, Call)
  1698. .WillOnce(StaticAssertSingleArgument{})
  1699. .WillRepeatedly(StaticAssertSingleArgument{});
  1700. EXPECT_EQ(17, mock.AsStdFunction()(0));
  1701. EXPECT_EQ(17, mock.AsStdFunction()(0));
  1702. }
  1703. struct ActionWithTemplatedConversionOperators {
  1704. template <typename... Args>
  1705. operator OnceAction<int(Args...)>() && { // NOLINT
  1706. return [] { return 17; };
  1707. }
  1708. template <typename... Args>
  1709. operator Action<int(Args...)>() const { // NOLINT
  1710. return [] { return 19; };
  1711. }
  1712. };
  1713. // It should be fine to hand both WillOnce and WillRepeatedly a function that
  1714. // defines templated conversion operators to OnceAction and Action. WillOnce
  1715. // should prefer the OnceAction version.
  1716. TEST(MockMethodTest, ActionHasTemplatedConversionOperators) {
  1717. MockFunction<int()> mock;
  1718. EXPECT_CALL(mock, Call)
  1719. .WillOnce(ActionWithTemplatedConversionOperators{})
  1720. .WillRepeatedly(ActionWithTemplatedConversionOperators{});
  1721. EXPECT_EQ(17, mock.AsStdFunction()());
  1722. EXPECT_EQ(19, mock.AsStdFunction()());
  1723. }
  1724. // Tests for std::function based action.
  1725. int Add(int val, int& ref, int* ptr) { // NOLINT
  1726. int result = val + ref + *ptr;
  1727. ref = 42;
  1728. *ptr = 43;
  1729. return result;
  1730. }
  1731. int Deref(std::unique_ptr<int> ptr) { return *ptr; }
  1732. struct Double {
  1733. template <typename T>
  1734. T operator()(T t) {
  1735. return 2 * t;
  1736. }
  1737. };
  1738. std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); }
  1739. TEST(FunctorActionTest, ActionFromFunction) {
  1740. Action<int(int, int&, int*)> a = &Add;
  1741. int x = 1, y = 2, z = 3;
  1742. EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
  1743. EXPECT_EQ(42, y);
  1744. EXPECT_EQ(43, z);
  1745. Action<int(std::unique_ptr<int>)> a1 = &Deref;
  1746. EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
  1747. }
  1748. TEST(FunctorActionTest, ActionFromLambda) {
  1749. Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
  1750. EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  1751. EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));
  1752. std::unique_ptr<int> saved;
  1753. Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
  1754. saved = std::move(p);
  1755. };
  1756. a2.Perform(std::make_tuple(UniqueInt(5)));
  1757. EXPECT_EQ(5, *saved);
  1758. }
  1759. TEST(FunctorActionTest, PolymorphicFunctor) {
  1760. Action<int(int)> ai = Double();
  1761. EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
  1762. Action<double(double)> ad = Double(); // Double? Double double!
  1763. EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));
  1764. }
  1765. TEST(FunctorActionTest, TypeConversion) {
  1766. // Numeric promotions are allowed.
  1767. const Action<bool(int)> a1 = [](int i) { return i > 1; };
  1768. const Action<int(bool)> a2 = Action<int(bool)>(a1);
  1769. EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));
  1770. EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));
  1771. // Implicit constructors are allowed.
  1772. const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
  1773. const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
  1774. EXPECT_EQ(0, s2.Perform(std::make_tuple("")));
  1775. EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
  1776. // Also between the lambda and the action itself.
  1777. const Action<bool(std::string)> x1 = [](Unused) { return 42; };
  1778. const Action<bool(std::string)> x2 = [] { return 42; };
  1779. EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
  1780. EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
  1781. // Ensure decay occurs where required.
  1782. std::function<int()> f = [] { return 7; };
  1783. Action<int(int)> d = f;
  1784. f = nullptr;
  1785. EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
  1786. // Ensure creation of an empty action succeeds.
  1787. Action<void(int)>(nullptr);
  1788. }
  1789. TEST(FunctorActionTest, UnusedArguments) {
  1790. // Verify that users can ignore uninteresting arguments.
  1791. Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {
  1792. return 2 * i;
  1793. };
  1794. std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
  1795. EXPECT_EQ(6, a.Perform(dummy));
  1796. }
  1797. // Test that basic built-in actions work with move-only arguments.
  1798. TEST(MoveOnlyArgumentsTest, ReturningActions) {
  1799. Action<int(std::unique_ptr<int>)> a = Return(1);
  1800. EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
  1801. a = testing::WithoutArgs([]() { return 7; });
  1802. EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));
  1803. Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
  1804. int x = 0;
  1805. a2.Perform(std::make_tuple(nullptr, &x));
  1806. EXPECT_EQ(x, 3);
  1807. }
  1808. ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
  1809. TEST(ActionMacro, LargeArity) {
  1810. EXPECT_EQ(
  1811. 1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
  1812. EXPECT_EQ(
  1813. 10,
  1814. testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
  1815. ReturnArity())
  1816. .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
  1817. EXPECT_EQ(
  1818. 20,
  1819. testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
  1820. int, int, int, int, int, int, int, int, int)>(
  1821. ReturnArity())
  1822. .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
  1823. 14, 15, 16, 17, 18, 19)));
  1824. }
  1825. } // namespace
  1826. } // namespace testing
  1827. #if defined(_MSC_VER) && (_MSC_VER == 1900)
  1828. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800
  1829. #endif
  1830. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 4503