gmock-actions_test.cc 71 KB

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