gmock-actions_test.cc 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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 C4800 (C4800: 'int *const ': forcing value
  33. // to bool 'true' or 'false') for MSVC 15
  34. #ifdef _MSC_VER
  35. #if _MSC_VER == 1900
  36. # pragma warning(push)
  37. # pragma warning(disable:4800)
  38. #endif
  39. #endif
  40. #include "gmock/gmock-actions.h"
  41. #include <algorithm>
  42. #include <iterator>
  43. #include <memory>
  44. #include <string>
  45. #include "gmock/gmock.h"
  46. #include "gmock/internal/gmock-port.h"
  47. #include "gtest/gtest.h"
  48. #include "gtest/gtest-spi.h"
  49. namespace {
  50. // This list should be kept sorted.
  51. using testing::_;
  52. using testing::Action;
  53. using testing::ActionInterface;
  54. using testing::Assign;
  55. using testing::ByMove;
  56. using testing::ByRef;
  57. using testing::DefaultValue;
  58. using testing::DoAll;
  59. using testing::DoDefault;
  60. using testing::IgnoreResult;
  61. using testing::Invoke;
  62. using testing::InvokeWithoutArgs;
  63. using testing::MakePolymorphicAction;
  64. using testing::Ne;
  65. using testing::PolymorphicAction;
  66. using testing::Return;
  67. using testing::ReturnNull;
  68. using testing::ReturnRef;
  69. using testing::ReturnRefOfCopy;
  70. using testing::SetArgPointee;
  71. using testing::SetArgumentPointee;
  72. using testing::Unused;
  73. using testing::WithArgs;
  74. using testing::internal::BuiltInDefaultValue;
  75. using testing::internal::Int64;
  76. using testing::internal::UInt64;
  77. #if !GTEST_OS_WINDOWS_MOBILE
  78. using testing::SetErrnoAndReturn;
  79. #endif
  80. // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
  81. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
  82. EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);
  83. EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);
  84. EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);
  85. }
  86. // Tests that BuiltInDefaultValue<T*>::Exists() return true.
  87. TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
  88. EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
  89. EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
  90. EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
  91. }
  92. // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
  93. // built-in numeric type.
  94. TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
  95. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
  96. EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
  97. EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
  98. #if GMOCK_WCHAR_T_IS_NATIVE_
  99. #if !defined(__WCHAR_UNSIGNED__)
  100. EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
  101. #else
  102. EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
  103. #endif
  104. #endif
  105. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
  106. EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
  107. EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
  108. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
  109. EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
  110. EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
  111. EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
  112. EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
  113. EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
  114. EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
  115. EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
  116. EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
  117. EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
  118. }
  119. // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
  120. // built-in numeric type.
  121. TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
  122. EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
  123. EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
  124. EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
  125. #if GMOCK_WCHAR_T_IS_NATIVE_
  126. EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
  127. #endif
  128. EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
  129. EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
  130. EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
  131. EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
  132. EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
  133. EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
  134. EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
  135. EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
  136. EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
  137. EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
  138. EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
  139. EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
  140. EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
  141. }
  142. // Tests that BuiltInDefaultValue<bool>::Get() returns false.
  143. TEST(BuiltInDefaultValueTest, IsFalseForBool) {
  144. EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
  145. }
  146. // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
  147. TEST(BuiltInDefaultValueTest, BoolExists) {
  148. EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
  149. }
  150. // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
  151. // string type.
  152. TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
  153. EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
  154. }
  155. // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
  156. // string type.
  157. TEST(BuiltInDefaultValueTest, ExistsForString) {
  158. EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
  159. }
  160. // Tests that BuiltInDefaultValue<const T>::Get() returns the same
  161. // value as BuiltInDefaultValue<T>::Get() does.
  162. TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
  163. EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
  164. EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
  165. EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
  166. EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
  167. }
  168. // A type that's default constructible.
  169. class MyDefaultConstructible {
  170. public:
  171. MyDefaultConstructible() : value_(42) {}
  172. int value() const { return value_; }
  173. private:
  174. int value_;
  175. };
  176. // A type that's not default constructible.
  177. class MyNonDefaultConstructible {
  178. public:
  179. // Does not have a default ctor.
  180. explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
  181. int value() const { return value_; }
  182. private:
  183. int value_;
  184. };
  185. TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
  186. EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
  187. }
  188. TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
  189. EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
  190. }
  191. TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
  192. EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
  193. }
  194. // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
  195. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
  196. EXPECT_DEATH_IF_SUPPORTED({
  197. BuiltInDefaultValue<int&>::Get();
  198. }, "");
  199. EXPECT_DEATH_IF_SUPPORTED({
  200. BuiltInDefaultValue<const char&>::Get();
  201. }, "");
  202. }
  203. TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
  204. EXPECT_DEATH_IF_SUPPORTED({
  205. BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
  206. }, "");
  207. }
  208. // Tests that DefaultValue<T>::IsSet() is false initially.
  209. TEST(DefaultValueTest, IsInitiallyUnset) {
  210. EXPECT_FALSE(DefaultValue<int>::IsSet());
  211. EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
  212. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
  213. }
  214. // Tests that DefaultValue<T> can be set and then unset.
  215. TEST(DefaultValueTest, CanBeSetAndUnset) {
  216. EXPECT_TRUE(DefaultValue<int>::Exists());
  217. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
  218. DefaultValue<int>::Set(1);
  219. DefaultValue<const MyNonDefaultConstructible>::Set(
  220. MyNonDefaultConstructible(42));
  221. EXPECT_EQ(1, DefaultValue<int>::Get());
  222. EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
  223. EXPECT_TRUE(DefaultValue<int>::Exists());
  224. EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
  225. DefaultValue<int>::Clear();
  226. DefaultValue<const MyNonDefaultConstructible>::Clear();
  227. EXPECT_FALSE(DefaultValue<int>::IsSet());
  228. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
  229. EXPECT_TRUE(DefaultValue<int>::Exists());
  230. EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
  231. }
  232. // Tests that DefaultValue<T>::Get() returns the
  233. // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
  234. // false.
  235. TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
  236. EXPECT_FALSE(DefaultValue<int>::IsSet());
  237. EXPECT_TRUE(DefaultValue<int>::Exists());
  238. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
  239. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
  240. EXPECT_EQ(0, DefaultValue<int>::Get());
  241. EXPECT_DEATH_IF_SUPPORTED({
  242. DefaultValue<MyNonDefaultConstructible>::Get();
  243. }, "");
  244. }
  245. TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
  246. EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
  247. EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
  248. DefaultValue<std::unique_ptr<int>>::SetFactory([] {
  249. return std::unique_ptr<int>(new int(42));
  250. });
  251. EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
  252. std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
  253. EXPECT_EQ(42, *i);
  254. }
  255. // Tests that DefaultValue<void>::Get() returns void.
  256. TEST(DefaultValueTest, GetWorksForVoid) {
  257. return DefaultValue<void>::Get();
  258. }
  259. // Tests using DefaultValue with a reference type.
  260. // Tests that DefaultValue<T&>::IsSet() is false initially.
  261. TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
  262. EXPECT_FALSE(DefaultValue<int&>::IsSet());
  263. EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
  264. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
  265. }
  266. // Tests that DefaultValue<T&>::Exists is false initiallly.
  267. TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
  268. EXPECT_FALSE(DefaultValue<int&>::Exists());
  269. EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
  270. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
  271. }
  272. // Tests that DefaultValue<T&> can be set and then unset.
  273. TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
  274. int n = 1;
  275. DefaultValue<const int&>::Set(n);
  276. MyNonDefaultConstructible x(42);
  277. DefaultValue<MyNonDefaultConstructible&>::Set(x);
  278. EXPECT_TRUE(DefaultValue<const int&>::Exists());
  279. EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
  280. EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
  281. EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
  282. DefaultValue<const int&>::Clear();
  283. DefaultValue<MyNonDefaultConstructible&>::Clear();
  284. EXPECT_FALSE(DefaultValue<const int&>::Exists());
  285. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
  286. EXPECT_FALSE(DefaultValue<const int&>::IsSet());
  287. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
  288. }
  289. // Tests that DefaultValue<T&>::Get() returns the
  290. // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
  291. // false.
  292. TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
  293. EXPECT_FALSE(DefaultValue<int&>::IsSet());
  294. EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
  295. EXPECT_DEATH_IF_SUPPORTED({
  296. DefaultValue<int&>::Get();
  297. }, "");
  298. EXPECT_DEATH_IF_SUPPORTED({
  299. DefaultValue<MyNonDefaultConstructible>::Get();
  300. }, "");
  301. }
  302. // Tests that ActionInterface can be implemented by defining the
  303. // Perform method.
  304. typedef int MyGlobalFunction(bool, int);
  305. class MyActionImpl : public ActionInterface<MyGlobalFunction> {
  306. public:
  307. int Perform(const std::tuple<bool, int>& args) override {
  308. return std::get<0>(args) ? std::get<1>(args) : 0;
  309. }
  310. };
  311. TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
  312. MyActionImpl my_action_impl;
  313. (void)my_action_impl;
  314. }
  315. TEST(ActionInterfaceTest, MakeAction) {
  316. Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
  317. // When exercising the Perform() method of Action<F>, we must pass
  318. // it a tuple whose size and type are compatible with F's argument
  319. // types. For example, if F is int(), then Perform() takes a
  320. // 0-tuple; if F is void(bool, int), then Perform() takes a
  321. // std::tuple<bool, int>, and so on.
  322. EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
  323. }
  324. // Tests that Action<F> can be contructed from a pointer to
  325. // ActionInterface<F>.
  326. TEST(ActionTest, CanBeConstructedFromActionInterface) {
  327. Action<MyGlobalFunction> action(new MyActionImpl);
  328. }
  329. // Tests that Action<F> delegates actual work to ActionInterface<F>.
  330. TEST(ActionTest, DelegatesWorkToActionInterface) {
  331. const Action<MyGlobalFunction> action(new MyActionImpl);
  332. EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
  333. EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));
  334. }
  335. // Tests that Action<F> can be copied.
  336. TEST(ActionTest, IsCopyable) {
  337. Action<MyGlobalFunction> a1(new MyActionImpl);
  338. Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
  339. // a1 should continue to work after being copied from.
  340. EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  341. EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
  342. // a2 should work like the action it was copied from.
  343. EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
  344. EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
  345. a2 = a1; // Tests the assignment operator.
  346. // a1 should continue to work after being copied from.
  347. EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  348. EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
  349. // a2 should work like the action it was copied from.
  350. EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
  351. EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
  352. }
  353. // Tests that an Action<From> object can be converted to a
  354. // compatible Action<To> object.
  355. class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
  356. public:
  357. bool Perform(const std::tuple<int>& arg) override {
  358. return std::get<0>(arg) != 0;
  359. }
  360. };
  361. TEST(ActionTest, CanBeConvertedToOtherActionType) {
  362. const Action<bool(int)> a1(new IsNotZero); // NOLINT
  363. const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
  364. EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
  365. EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
  366. }
  367. // The following two classes are for testing MakePolymorphicAction().
  368. // Implements a polymorphic action that returns the second of the
  369. // arguments it receives.
  370. class ReturnSecondArgumentAction {
  371. public:
  372. // We want to verify that MakePolymorphicAction() can work with a
  373. // polymorphic action whose Perform() method template is either
  374. // const or not. This lets us verify the non-const case.
  375. template <typename Result, typename ArgumentTuple>
  376. Result Perform(const ArgumentTuple& args) {
  377. return std::get<1>(args);
  378. }
  379. };
  380. // Implements a polymorphic action that can be used in a nullary
  381. // function to return 0.
  382. class ReturnZeroFromNullaryFunctionAction {
  383. public:
  384. // For testing that MakePolymorphicAction() works when the
  385. // implementation class' Perform() method template takes only one
  386. // template parameter.
  387. //
  388. // We want to verify that MakePolymorphicAction() can work with a
  389. // polymorphic action whose Perform() method template is either
  390. // const or not. This lets us verify the const case.
  391. template <typename Result>
  392. Result Perform(const std::tuple<>&) const {
  393. return 0;
  394. }
  395. };
  396. // These functions verify that MakePolymorphicAction() returns a
  397. // PolymorphicAction<T> where T is the argument's type.
  398. PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
  399. return MakePolymorphicAction(ReturnSecondArgumentAction());
  400. }
  401. PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
  402. ReturnZeroFromNullaryFunction() {
  403. return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
  404. }
  405. // Tests that MakePolymorphicAction() turns a polymorphic action
  406. // implementation class into a polymorphic action.
  407. TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
  408. Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT
  409. EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));
  410. }
  411. // Tests that MakePolymorphicAction() works when the implementation
  412. // class' Perform() method template has only one template parameter.
  413. TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
  414. Action<int()> a1 = ReturnZeroFromNullaryFunction();
  415. EXPECT_EQ(0, a1.Perform(std::make_tuple()));
  416. Action<void*()> a2 = ReturnZeroFromNullaryFunction();
  417. EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);
  418. }
  419. // Tests that Return() works as an action for void-returning
  420. // functions.
  421. TEST(ReturnTest, WorksForVoid) {
  422. const Action<void(int)> ret = Return(); // NOLINT
  423. return ret.Perform(std::make_tuple(1));
  424. }
  425. // Tests that Return(v) returns v.
  426. TEST(ReturnTest, ReturnsGivenValue) {
  427. Action<int()> ret = Return(1); // NOLINT
  428. EXPECT_EQ(1, ret.Perform(std::make_tuple()));
  429. ret = Return(-5);
  430. EXPECT_EQ(-5, ret.Perform(std::make_tuple()));
  431. }
  432. // Tests that Return("string literal") works.
  433. TEST(ReturnTest, AcceptsStringLiteral) {
  434. Action<const char*()> a1 = Return("Hello");
  435. EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));
  436. Action<std::string()> a2 = Return("world");
  437. EXPECT_EQ("world", a2.Perform(std::make_tuple()));
  438. }
  439. // Test struct which wraps a vector of integers. Used in
  440. // 'SupportsWrapperReturnType' test.
  441. struct IntegerVectorWrapper {
  442. std::vector<int> * v;
  443. IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT
  444. };
  445. // Tests that Return() works when return type is a wrapper type.
  446. TEST(ReturnTest, SupportsWrapperReturnType) {
  447. // Initialize vector of integers.
  448. std::vector<int> v;
  449. for (int i = 0; i < 5; ++i) v.push_back(i);
  450. // Return() called with 'v' as argument. The Action will return the same data
  451. // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
  452. Action<IntegerVectorWrapper()> a = Return(v);
  453. const std::vector<int>& result = *(a.Perform(std::make_tuple()).v);
  454. EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
  455. }
  456. // Tests that Return(v) is covaraint.
  457. struct Base {
  458. bool operator==(const Base&) { return true; }
  459. };
  460. struct Derived : public Base {
  461. bool operator==(const Derived&) { return true; }
  462. };
  463. TEST(ReturnTest, IsCovariant) {
  464. Base base;
  465. Derived derived;
  466. Action<Base*()> ret = Return(&base);
  467. EXPECT_EQ(&base, ret.Perform(std::make_tuple()));
  468. ret = Return(&derived);
  469. EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));
  470. }
  471. // Tests that the type of the value passed into Return is converted into T
  472. // when the action is cast to Action<T(...)> rather than when the action is
  473. // performed. See comments on testing::internal::ReturnAction in
  474. // gmock-actions.h for more information.
  475. class FromType {
  476. public:
  477. explicit FromType(bool* is_converted) : converted_(is_converted) {}
  478. bool* converted() const { return converted_; }
  479. private:
  480. bool* const converted_;
  481. GTEST_DISALLOW_ASSIGN_(FromType);
  482. };
  483. class ToType {
  484. public:
  485. // Must allow implicit conversion due to use in ImplicitCast_<T>.
  486. ToType(const FromType& x) { *x.converted() = true; } // NOLINT
  487. };
  488. TEST(ReturnTest, ConvertsArgumentWhenConverted) {
  489. bool converted = false;
  490. FromType x(&converted);
  491. Action<ToType()> action(Return(x));
  492. EXPECT_TRUE(converted) << "Return must convert its argument in its own "
  493. << "conversion operator.";
  494. converted = false;
  495. action.Perform(std::tuple<>());
  496. EXPECT_FALSE(converted) << "Action must NOT convert its argument "
  497. << "when performed.";
  498. }
  499. class DestinationType {};
  500. class SourceType {
  501. public:
  502. // Note: a non-const typecast operator.
  503. operator DestinationType() { return DestinationType(); }
  504. };
  505. TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
  506. SourceType s;
  507. Action<DestinationType()> action(Return(s));
  508. }
  509. // Tests that ReturnNull() returns NULL in a pointer-returning function.
  510. TEST(ReturnNullTest, WorksInPointerReturningFunction) {
  511. const Action<int*()> a1 = ReturnNull();
  512. EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
  513. const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
  514. EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);
  515. }
  516. // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
  517. // functions.
  518. TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
  519. const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
  520. EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
  521. const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
  522. EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);
  523. }
  524. // Tests that ReturnRef(v) works for reference types.
  525. TEST(ReturnRefTest, WorksForReference) {
  526. const int n = 0;
  527. const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
  528. EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));
  529. }
  530. // Tests that ReturnRef(v) is covariant.
  531. TEST(ReturnRefTest, IsCovariant) {
  532. Base base;
  533. Derived derived;
  534. Action<Base&()> a = ReturnRef(base);
  535. EXPECT_EQ(&base, &a.Perform(std::make_tuple()));
  536. a = ReturnRef(derived);
  537. EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
  538. }
  539. // Tests that ReturnRefOfCopy(v) works for reference types.
  540. TEST(ReturnRefOfCopyTest, WorksForReference) {
  541. int n = 42;
  542. const Action<const int&()> ret = ReturnRefOfCopy(n);
  543. EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
  544. EXPECT_EQ(42, ret.Perform(std::make_tuple()));
  545. n = 43;
  546. EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
  547. EXPECT_EQ(42, ret.Perform(std::make_tuple()));
  548. }
  549. // Tests that ReturnRefOfCopy(v) is covariant.
  550. TEST(ReturnRefOfCopyTest, IsCovariant) {
  551. Base base;
  552. Derived derived;
  553. Action<Base&()> a = ReturnRefOfCopy(base);
  554. EXPECT_NE(&base, &a.Perform(std::make_tuple()));
  555. a = ReturnRefOfCopy(derived);
  556. EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
  557. }
  558. // Tests that DoDefault() does the default action for the mock method.
  559. class MockClass {
  560. public:
  561. MockClass() {}
  562. MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
  563. MOCK_METHOD0(Foo, MyNonDefaultConstructible());
  564. MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
  565. MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
  566. MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
  567. MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
  568. MOCK_METHOD2(TakeUnique,
  569. int(const std::unique_ptr<int>&, std::unique_ptr<int>));
  570. private:
  571. GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
  572. };
  573. // Tests that DoDefault() returns the built-in default value for the
  574. // return type by default.
  575. TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
  576. MockClass mock;
  577. EXPECT_CALL(mock, IntFunc(_))
  578. .WillOnce(DoDefault());
  579. EXPECT_EQ(0, mock.IntFunc(true));
  580. }
  581. // Tests that DoDefault() throws (when exceptions are enabled) or aborts
  582. // the process when there is no built-in default value for the return type.
  583. TEST(DoDefaultDeathTest, DiesForUnknowType) {
  584. MockClass mock;
  585. EXPECT_CALL(mock, Foo())
  586. .WillRepeatedly(DoDefault());
  587. #if GTEST_HAS_EXCEPTIONS
  588. EXPECT_ANY_THROW(mock.Foo());
  589. #else
  590. EXPECT_DEATH_IF_SUPPORTED({
  591. mock.Foo();
  592. }, "");
  593. #endif
  594. }
  595. // Tests that using DoDefault() inside a composite action leads to a
  596. // run-time error.
  597. void VoidFunc(bool /* flag */) {}
  598. TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
  599. MockClass mock;
  600. EXPECT_CALL(mock, IntFunc(_))
  601. .WillRepeatedly(DoAll(Invoke(VoidFunc),
  602. DoDefault()));
  603. // Ideally we should verify the error message as well. Sadly,
  604. // EXPECT_DEATH() can only capture stderr, while Google Mock's
  605. // errors are printed on stdout. Therefore we have to settle for
  606. // not verifying the message.
  607. EXPECT_DEATH_IF_SUPPORTED({
  608. mock.IntFunc(true);
  609. }, "");
  610. }
  611. // Tests that DoDefault() returns the default value set by
  612. // DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
  613. TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
  614. DefaultValue<int>::Set(1);
  615. MockClass mock;
  616. EXPECT_CALL(mock, IntFunc(_))
  617. .WillOnce(DoDefault());
  618. EXPECT_EQ(1, mock.IntFunc(false));
  619. DefaultValue<int>::Clear();
  620. }
  621. // Tests that DoDefault() does the action specified by ON_CALL().
  622. TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
  623. MockClass mock;
  624. ON_CALL(mock, IntFunc(_))
  625. .WillByDefault(Return(2));
  626. EXPECT_CALL(mock, IntFunc(_))
  627. .WillOnce(DoDefault());
  628. EXPECT_EQ(2, mock.IntFunc(false));
  629. }
  630. // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
  631. TEST(DoDefaultTest, CannotBeUsedInOnCall) {
  632. MockClass mock;
  633. EXPECT_NONFATAL_FAILURE({ // NOLINT
  634. ON_CALL(mock, IntFunc(_))
  635. .WillByDefault(DoDefault());
  636. }, "DoDefault() cannot be used in ON_CALL()");
  637. }
  638. // Tests that SetArgPointee<N>(v) sets the variable pointed to by
  639. // the N-th (0-based) argument to v.
  640. TEST(SetArgPointeeTest, SetsTheNthPointee) {
  641. typedef void MyFunction(bool, int*, char*);
  642. Action<MyFunction> a = SetArgPointee<1>(2);
  643. int n = 0;
  644. char ch = '\0';
  645. a.Perform(std::make_tuple(true, &n, &ch));
  646. EXPECT_EQ(2, n);
  647. EXPECT_EQ('\0', ch);
  648. a = SetArgPointee<2>('a');
  649. n = 0;
  650. ch = '\0';
  651. a.Perform(std::make_tuple(true, &n, &ch));
  652. EXPECT_EQ(0, n);
  653. EXPECT_EQ('a', ch);
  654. }
  655. // Tests that SetArgPointee<N>() accepts a string literal.
  656. TEST(SetArgPointeeTest, AcceptsStringLiteral) {
  657. typedef void MyFunction(std::string*, const char**);
  658. Action<MyFunction> a = SetArgPointee<0>("hi");
  659. std::string str;
  660. const char* ptr = nullptr;
  661. a.Perform(std::make_tuple(&str, &ptr));
  662. EXPECT_EQ("hi", str);
  663. EXPECT_TRUE(ptr == nullptr);
  664. a = SetArgPointee<1>("world");
  665. str = "";
  666. a.Perform(std::make_tuple(&str, &ptr));
  667. EXPECT_EQ("", str);
  668. EXPECT_STREQ("world", ptr);
  669. }
  670. TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
  671. typedef void MyFunction(const wchar_t**);
  672. Action<MyFunction> a = SetArgPointee<0>(L"world");
  673. const wchar_t* ptr = nullptr;
  674. a.Perform(std::make_tuple(&ptr));
  675. EXPECT_STREQ(L"world", ptr);
  676. # if GTEST_HAS_STD_WSTRING
  677. typedef void MyStringFunction(std::wstring*);
  678. Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
  679. std::wstring str = L"";
  680. a2.Perform(std::make_tuple(&str));
  681. EXPECT_EQ(L"world", str);
  682. # endif
  683. }
  684. // Tests that SetArgPointee<N>() accepts a char pointer.
  685. TEST(SetArgPointeeTest, AcceptsCharPointer) {
  686. typedef void MyFunction(bool, std::string*, const char**);
  687. const char* const hi = "hi";
  688. Action<MyFunction> a = SetArgPointee<1>(hi);
  689. std::string str;
  690. const char* ptr = nullptr;
  691. a.Perform(std::make_tuple(true, &str, &ptr));
  692. EXPECT_EQ("hi", str);
  693. EXPECT_TRUE(ptr == nullptr);
  694. char world_array[] = "world";
  695. char* const world = world_array;
  696. a = SetArgPointee<2>(world);
  697. str = "";
  698. a.Perform(std::make_tuple(true, &str, &ptr));
  699. EXPECT_EQ("", str);
  700. EXPECT_EQ(world, ptr);
  701. }
  702. TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
  703. typedef void MyFunction(bool, const wchar_t**);
  704. const wchar_t* const hi = L"hi";
  705. Action<MyFunction> a = SetArgPointee<1>(hi);
  706. const wchar_t* ptr = nullptr;
  707. a.Perform(std::make_tuple(true, &ptr));
  708. EXPECT_EQ(hi, ptr);
  709. # if GTEST_HAS_STD_WSTRING
  710. typedef void MyStringFunction(bool, std::wstring*);
  711. wchar_t world_array[] = L"world";
  712. wchar_t* const world = world_array;
  713. Action<MyStringFunction> a2 = SetArgPointee<1>(world);
  714. std::wstring str;
  715. a2.Perform(std::make_tuple(true, &str));
  716. EXPECT_EQ(world_array, str);
  717. # endif
  718. }
  719. // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
  720. // the N-th (0-based) argument to v.
  721. TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
  722. typedef void MyFunction(bool, int*, char*);
  723. Action<MyFunction> a = SetArgumentPointee<1>(2);
  724. int n = 0;
  725. char ch = '\0';
  726. a.Perform(std::make_tuple(true, &n, &ch));
  727. EXPECT_EQ(2, n);
  728. EXPECT_EQ('\0', ch);
  729. a = SetArgumentPointee<2>('a');
  730. n = 0;
  731. ch = '\0';
  732. a.Perform(std::make_tuple(true, &n, &ch));
  733. EXPECT_EQ(0, n);
  734. EXPECT_EQ('a', ch);
  735. }
  736. // Sample functions and functors for testing Invoke() and etc.
  737. int Nullary() { return 1; }
  738. class NullaryFunctor {
  739. public:
  740. int operator()() { return 2; }
  741. };
  742. bool g_done = false;
  743. void VoidNullary() { g_done = true; }
  744. class VoidNullaryFunctor {
  745. public:
  746. void operator()() { g_done = true; }
  747. };
  748. short Short(short n) { return n; } // NOLINT
  749. char Char(char ch) { return ch; }
  750. const char* CharPtr(const char* s) { return s; }
  751. bool Unary(int x) { return x < 0; }
  752. const char* Binary(const char* input, short n) { return input + n; } // NOLINT
  753. void VoidBinary(int, char) { g_done = true; }
  754. int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
  755. int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
  756. class Foo {
  757. public:
  758. Foo() : value_(123) {}
  759. int Nullary() const { return value_; }
  760. private:
  761. int value_;
  762. };
  763. // Tests InvokeWithoutArgs(function).
  764. TEST(InvokeWithoutArgsTest, Function) {
  765. // As an action that takes one argument.
  766. Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT
  767. EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
  768. // As an action that takes two arguments.
  769. Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT
  770. EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));
  771. // As an action that returns void.
  772. Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
  773. g_done = false;
  774. a3.Perform(std::make_tuple(1));
  775. EXPECT_TRUE(g_done);
  776. }
  777. // Tests InvokeWithoutArgs(functor).
  778. TEST(InvokeWithoutArgsTest, Functor) {
  779. // As an action that takes no argument.
  780. Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT
  781. EXPECT_EQ(2, a.Perform(std::make_tuple()));
  782. // As an action that takes three arguments.
  783. Action<int(int, double, char)> a2 = // NOLINT
  784. InvokeWithoutArgs(NullaryFunctor());
  785. EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));
  786. // As an action that returns void.
  787. Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
  788. g_done = false;
  789. a3.Perform(std::make_tuple());
  790. EXPECT_TRUE(g_done);
  791. }
  792. // Tests InvokeWithoutArgs(obj_ptr, method).
  793. TEST(InvokeWithoutArgsTest, Method) {
  794. Foo foo;
  795. Action<int(bool, char)> a = // NOLINT
  796. InvokeWithoutArgs(&foo, &Foo::Nullary);
  797. EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
  798. }
  799. // Tests using IgnoreResult() on a polymorphic action.
  800. TEST(IgnoreResultTest, PolymorphicAction) {
  801. Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
  802. a.Perform(std::make_tuple(1));
  803. }
  804. // Tests using IgnoreResult() on a monomorphic action.
  805. int ReturnOne() {
  806. g_done = true;
  807. return 1;
  808. }
  809. TEST(IgnoreResultTest, MonomorphicAction) {
  810. g_done = false;
  811. Action<void()> a = IgnoreResult(Invoke(ReturnOne));
  812. a.Perform(std::make_tuple());
  813. EXPECT_TRUE(g_done);
  814. }
  815. // Tests using IgnoreResult() on an action that returns a class type.
  816. MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
  817. g_done = true;
  818. return MyNonDefaultConstructible(42);
  819. }
  820. TEST(IgnoreResultTest, ActionReturningClass) {
  821. g_done = false;
  822. Action<void(int)> a =
  823. IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
  824. a.Perform(std::make_tuple(2));
  825. EXPECT_TRUE(g_done);
  826. }
  827. TEST(AssignTest, Int) {
  828. int x = 0;
  829. Action<void(int)> a = Assign(&x, 5);
  830. a.Perform(std::make_tuple(0));
  831. EXPECT_EQ(5, x);
  832. }
  833. TEST(AssignTest, String) {
  834. ::std::string x;
  835. Action<void(void)> a = Assign(&x, "Hello, world");
  836. a.Perform(std::make_tuple());
  837. EXPECT_EQ("Hello, world", x);
  838. }
  839. TEST(AssignTest, CompatibleTypes) {
  840. double x = 0;
  841. Action<void(int)> a = Assign(&x, 5);
  842. a.Perform(std::make_tuple(0));
  843. EXPECT_DOUBLE_EQ(5, x);
  844. }
  845. // Tests using WithArgs and with an action that takes 1 argument.
  846. TEST(WithArgsTest, OneArg) {
  847. Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
  848. EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
  849. EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
  850. }
  851. // Tests using WithArgs with an action that takes 2 arguments.
  852. TEST(WithArgsTest, TwoArgs) {
  853. Action<const char*(const char* s, double x, short n)> a = // NOLINT
  854. WithArgs<0, 2>(Invoke(Binary));
  855. const char s[] = "Hello";
  856. EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
  857. }
  858. struct ConcatAll {
  859. std::string operator()() const { return {}; }
  860. template <typename... I>
  861. std::string operator()(const char* a, I... i) const {
  862. return a + ConcatAll()(i...);
  863. }
  864. };
  865. // Tests using WithArgs with an action that takes 10 arguments.
  866. TEST(WithArgsTest, TenArgs) {
  867. Action<std::string(const char*, const char*, const char*, const char*)> a =
  868. WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
  869. EXPECT_EQ("0123210123",
  870. a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
  871. CharPtr("3"))));
  872. }
  873. // Tests using WithArgs with an action that is not Invoke().
  874. class SubtractAction : public ActionInterface<int(int, int)> {
  875. public:
  876. int Perform(const std::tuple<int, int>& args) override {
  877. return std::get<0>(args) - std::get<1>(args);
  878. }
  879. };
  880. TEST(WithArgsTest, NonInvokeAction) {
  881. Action<int(const std::string&, int, int)> a =
  882. WithArgs<2, 1>(MakeAction(new SubtractAction));
  883. std::tuple<std::string, int, int> dummy =
  884. std::make_tuple(std::string("hi"), 2, 10);
  885. EXPECT_EQ(8, a.Perform(dummy));
  886. }
  887. // Tests using WithArgs to pass all original arguments in the original order.
  888. TEST(WithArgsTest, Identity) {
  889. Action<int(int x, char y, short z)> a = // NOLINT
  890. WithArgs<0, 1, 2>(Invoke(Ternary));
  891. EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
  892. }
  893. // Tests using WithArgs with repeated arguments.
  894. TEST(WithArgsTest, RepeatedArguments) {
  895. Action<int(bool, int m, int n)> a = // NOLINT
  896. WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
  897. EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
  898. }
  899. // Tests using WithArgs with reversed argument order.
  900. TEST(WithArgsTest, ReversedArgumentOrder) {
  901. Action<const char*(short n, const char* input)> a = // NOLINT
  902. WithArgs<1, 0>(Invoke(Binary));
  903. const char s[] = "Hello";
  904. EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
  905. }
  906. // Tests using WithArgs with compatible, but not identical, argument types.
  907. TEST(WithArgsTest, ArgsOfCompatibleTypes) {
  908. Action<long(short x, char y, double z, char c)> a = // NOLINT
  909. WithArgs<0, 1, 3>(Invoke(Ternary));
  910. EXPECT_EQ(123,
  911. a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
  912. }
  913. // Tests using WithArgs with an action that returns void.
  914. TEST(WithArgsTest, VoidAction) {
  915. Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
  916. g_done = false;
  917. a.Perform(std::make_tuple(1.5, 'a', 3));
  918. EXPECT_TRUE(g_done);
  919. }
  920. TEST(WithArgsTest, ReturnReference) {
  921. Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
  922. int i = 0;
  923. const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
  924. EXPECT_EQ(&i, &res);
  925. }
  926. TEST(WithArgsTest, InnerActionWithConversion) {
  927. Action<Derived*()> inner = [] { return nullptr; };
  928. Action<Base*(double)> a = testing::WithoutArgs(inner);
  929. EXPECT_EQ(nullptr, a.Perform(std::make_tuple(1.1)));
  930. }
  931. #if !GTEST_OS_WINDOWS_MOBILE
  932. class SetErrnoAndReturnTest : public testing::Test {
  933. protected:
  934. void SetUp() override { errno = 0; }
  935. void TearDown() override { errno = 0; }
  936. };
  937. TEST_F(SetErrnoAndReturnTest, Int) {
  938. Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
  939. EXPECT_EQ(-5, a.Perform(std::make_tuple()));
  940. EXPECT_EQ(ENOTTY, errno);
  941. }
  942. TEST_F(SetErrnoAndReturnTest, Ptr) {
  943. int x;
  944. Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
  945. EXPECT_EQ(&x, a.Perform(std::make_tuple()));
  946. EXPECT_EQ(ENOTTY, errno);
  947. }
  948. TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
  949. Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
  950. EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
  951. EXPECT_EQ(EINVAL, errno);
  952. }
  953. #endif // !GTEST_OS_WINDOWS_MOBILE
  954. // Tests ByRef().
  955. // Tests that the result of ByRef() is copyable.
  956. TEST(ByRefTest, IsCopyable) {
  957. const std::string s1 = "Hi";
  958. const std::string s2 = "Hello";
  959. auto ref_wrapper = ByRef(s1);
  960. const std::string& r1 = ref_wrapper;
  961. EXPECT_EQ(&s1, &r1);
  962. // Assigns a new value to ref_wrapper.
  963. ref_wrapper = ByRef(s2);
  964. const std::string& r2 = ref_wrapper;
  965. EXPECT_EQ(&s2, &r2);
  966. auto ref_wrapper1 = ByRef(s1);
  967. // Copies ref_wrapper1 to ref_wrapper.
  968. ref_wrapper = ref_wrapper1;
  969. const std::string& r3 = ref_wrapper;
  970. EXPECT_EQ(&s1, &r3);
  971. }
  972. // Tests using ByRef() on a const value.
  973. TEST(ByRefTest, ConstValue) {
  974. const int n = 0;
  975. // int& ref = ByRef(n); // This shouldn't compile - we have a
  976. // negative compilation test to catch it.
  977. const int& const_ref = ByRef(n);
  978. EXPECT_EQ(&n, &const_ref);
  979. }
  980. // Tests using ByRef() on a non-const value.
  981. TEST(ByRefTest, NonConstValue) {
  982. int n = 0;
  983. // ByRef(n) can be used as either an int&,
  984. int& ref = ByRef(n);
  985. EXPECT_EQ(&n, &ref);
  986. // or a const int&.
  987. const int& const_ref = ByRef(n);
  988. EXPECT_EQ(&n, &const_ref);
  989. }
  990. // Tests explicitly specifying the type when using ByRef().
  991. TEST(ByRefTest, ExplicitType) {
  992. int n = 0;
  993. const int& r1 = ByRef<const int>(n);
  994. EXPECT_EQ(&n, &r1);
  995. // ByRef<char>(n); // This shouldn't compile - we have a negative
  996. // compilation test to catch it.
  997. Derived d;
  998. Derived& r2 = ByRef<Derived>(d);
  999. EXPECT_EQ(&d, &r2);
  1000. const Derived& r3 = ByRef<const Derived>(d);
  1001. EXPECT_EQ(&d, &r3);
  1002. Base& r4 = ByRef<Base>(d);
  1003. EXPECT_EQ(&d, &r4);
  1004. const Base& r5 = ByRef<const Base>(d);
  1005. EXPECT_EQ(&d, &r5);
  1006. // The following shouldn't compile - we have a negative compilation
  1007. // test for it.
  1008. //
  1009. // Base b;
  1010. // ByRef<Derived>(b);
  1011. }
  1012. // Tests that Google Mock prints expression ByRef(x) as a reference to x.
  1013. TEST(ByRefTest, PrintsCorrectly) {
  1014. int n = 42;
  1015. ::std::stringstream expected, actual;
  1016. testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
  1017. testing::internal::UniversalPrint(ByRef(n), &actual);
  1018. EXPECT_EQ(expected.str(), actual.str());
  1019. }
  1020. std::unique_ptr<int> UniquePtrSource() {
  1021. return std::unique_ptr<int>(new int(19));
  1022. }
  1023. std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
  1024. std::vector<std::unique_ptr<int>> out;
  1025. out.emplace_back(new int(7));
  1026. return out;
  1027. }
  1028. TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
  1029. MockClass mock;
  1030. std::unique_ptr<int> i(new int(19));
  1031. EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
  1032. EXPECT_CALL(mock, MakeVectorUnique())
  1033. .WillOnce(Return(ByMove(VectorUniquePtrSource())));
  1034. Derived* d = new Derived;
  1035. EXPECT_CALL(mock, MakeUniqueBase())
  1036. .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
  1037. std::unique_ptr<int> result1 = mock.MakeUnique();
  1038. EXPECT_EQ(19, *result1);
  1039. std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
  1040. EXPECT_EQ(1u, vresult.size());
  1041. EXPECT_NE(nullptr, vresult[0]);
  1042. EXPECT_EQ(7, *vresult[0]);
  1043. std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
  1044. EXPECT_EQ(d, result2.get());
  1045. }
  1046. TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
  1047. testing::MockFunction<void()> mock_function;
  1048. MockClass mock;
  1049. std::unique_ptr<int> i(new int(19));
  1050. EXPECT_CALL(mock_function, Call());
  1051. EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
  1052. InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
  1053. Return(ByMove(std::move(i)))));
  1054. std::unique_ptr<int> result1 = mock.MakeUnique();
  1055. EXPECT_EQ(19, *result1);
  1056. }
  1057. TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
  1058. MockClass mock;
  1059. // Check default value
  1060. DefaultValue<std::unique_ptr<int>>::SetFactory([] {
  1061. return std::unique_ptr<int>(new int(42));
  1062. });
  1063. EXPECT_EQ(42, *mock.MakeUnique());
  1064. EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
  1065. EXPECT_CALL(mock, MakeVectorUnique())
  1066. .WillRepeatedly(Invoke(VectorUniquePtrSource));
  1067. std::unique_ptr<int> result1 = mock.MakeUnique();
  1068. EXPECT_EQ(19, *result1);
  1069. std::unique_ptr<int> result2 = mock.MakeUnique();
  1070. EXPECT_EQ(19, *result2);
  1071. EXPECT_NE(result1, result2);
  1072. std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
  1073. EXPECT_EQ(1u, vresult.size());
  1074. EXPECT_NE(nullptr, vresult[0]);
  1075. EXPECT_EQ(7, *vresult[0]);
  1076. }
  1077. TEST(MockMethodTest, CanTakeMoveOnlyValue) {
  1078. MockClass mock;
  1079. auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
  1080. EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
  1081. return *i;
  1082. });
  1083. // DoAll() does not compile, since it would move from its arguments twice.
  1084. // EXPECT_CALL(mock, TakeUnique(_, _))
  1085. // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
  1086. // Return(1)));
  1087. EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
  1088. .WillOnce(Return(-7))
  1089. .RetiresOnSaturation();
  1090. EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
  1091. .WillOnce(Return(-1))
  1092. .RetiresOnSaturation();
  1093. EXPECT_EQ(5, mock.TakeUnique(make(5)));
  1094. EXPECT_EQ(-7, mock.TakeUnique(make(7)));
  1095. EXPECT_EQ(7, mock.TakeUnique(make(7)));
  1096. EXPECT_EQ(7, mock.TakeUnique(make(7)));
  1097. EXPECT_EQ(-1, mock.TakeUnique({}));
  1098. // Some arguments are moved, some passed by reference.
  1099. auto lvalue = make(6);
  1100. EXPECT_CALL(mock, TakeUnique(_, _))
  1101. .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
  1102. return *i * *j;
  1103. });
  1104. EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
  1105. // The unique_ptr can be saved by the action.
  1106. std::unique_ptr<int> saved;
  1107. EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
  1108. saved = std::move(i);
  1109. return 0;
  1110. });
  1111. EXPECT_EQ(0, mock.TakeUnique(make(42)));
  1112. EXPECT_EQ(42, *saved);
  1113. }
  1114. // Tests for std::function based action.
  1115. int Add(int val, int& ref, int* ptr) { // NOLINT
  1116. int result = val + ref + *ptr;
  1117. ref = 42;
  1118. *ptr = 43;
  1119. return result;
  1120. }
  1121. int Deref(std::unique_ptr<int> ptr) { return *ptr; }
  1122. struct Double {
  1123. template <typename T>
  1124. T operator()(T t) { return 2 * t; }
  1125. };
  1126. std::unique_ptr<int> UniqueInt(int i) {
  1127. return std::unique_ptr<int>(new int(i));
  1128. }
  1129. TEST(FunctorActionTest, ActionFromFunction) {
  1130. Action<int(int, int&, int*)> a = &Add;
  1131. int x = 1, y = 2, z = 3;
  1132. EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
  1133. EXPECT_EQ(42, y);
  1134. EXPECT_EQ(43, z);
  1135. Action<int(std::unique_ptr<int>)> a1 = &Deref;
  1136. EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
  1137. }
  1138. TEST(FunctorActionTest, ActionFromLambda) {
  1139. Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
  1140. EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
  1141. EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));
  1142. std::unique_ptr<int> saved;
  1143. Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
  1144. saved = std::move(p);
  1145. };
  1146. a2.Perform(std::make_tuple(UniqueInt(5)));
  1147. EXPECT_EQ(5, *saved);
  1148. }
  1149. TEST(FunctorActionTest, PolymorphicFunctor) {
  1150. Action<int(int)> ai = Double();
  1151. EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
  1152. Action<double(double)> ad = Double(); // Double? Double double!
  1153. EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));
  1154. }
  1155. TEST(FunctorActionTest, TypeConversion) {
  1156. // Numeric promotions are allowed.
  1157. const Action<bool(int)> a1 = [](int i) { return i > 1; };
  1158. const Action<int(bool)> a2 = Action<int(bool)>(a1);
  1159. EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));
  1160. EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));
  1161. // Implicit constructors are allowed.
  1162. const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
  1163. const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
  1164. EXPECT_EQ(0, s2.Perform(std::make_tuple("")));
  1165. EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
  1166. // Also between the lambda and the action itself.
  1167. const Action<bool(std::string)> x = [](Unused) { return 42; };
  1168. EXPECT_TRUE(x.Perform(std::make_tuple("hello")));
  1169. }
  1170. TEST(FunctorActionTest, UnusedArguments) {
  1171. // Verify that users can ignore uninteresting arguments.
  1172. Action<int(int, double y, double z)> a =
  1173. [](int i, Unused, Unused) { return 2 * i; };
  1174. std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
  1175. EXPECT_EQ(6, a.Perform(dummy));
  1176. }
  1177. // Test that basic built-in actions work with move-only arguments.
  1178. TEST(MoveOnlyArgumentsTest, ReturningActions) {
  1179. Action<int(std::unique_ptr<int>)> a = Return(1);
  1180. EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
  1181. a = testing::WithoutArgs([]() { return 7; });
  1182. EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));
  1183. Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
  1184. int x = 0;
  1185. a2.Perform(std::make_tuple(nullptr, &x));
  1186. EXPECT_EQ(x, 3);
  1187. }
  1188. } // Unnamed namespace
  1189. #ifdef _MSC_VER
  1190. #if _MSC_VER == 1900
  1191. # pragma warning(pop)
  1192. #endif
  1193. #endif